파이썬3 바이블 - 제5장 연습문제

프리렉 - FREELEC

http://freelec.co.kr/book/catalogue_view.asp?UID=134

이강성저

1.

슬라이싱을 이용한 치환인 경우에, 우변에는 시퀀스 자료형이 공급되어야 한다.

In [2]:
L = [1,2,3,4,5]
L[1:3] = [100]
L
Out[2]:
[1, 100, 4, 5]
In [5]:
L = [1,2,3,4,5]
L[1:3] = 100     # 리스트나 튜플 등의 시퀀스 자료형을 공급해야 한다.
L
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-9d37fca8cbac> in <module>()
      1 L = [1,2,3,4,5]
----> 2 L[1:3] = 100
      3 L

TypeError: can only assign an iterable
In [6]:
L = [1,2,3,4,5]
L[1:3] = 100,     # 튜플도 가능
L
Out[6]:
[1, 100, 4, 5]
In [8]:
L = [1,2,3,4,5]
L[1:3] = 'a'      # 문자열도 가능
L
Out[8]:
[1, 'a', 4, 5]

2.

id() 내장 함수를 이용하면 객체의 id(메모리 주소)를 확인할 수 있다. 다음 두 결과는 같은 메모리를 참조하고 있다는 것을 설명한다.

In [13]:
a = [1,2,3]
id(a)
Out[13]:
139852928072952
In [14]:
a[:] = [4, 5, 6]
In [17]:
id(a)
Out[17]:
139852928072952

3.

In [18]:
s = 'Sometimes I feel like a motherless child'
In [21]:
# 가) 단어의 순서 바꾸기
list(reversed(s.split()))
Out[21]:
['child', 'motherless', 'a', 'like', 'feel', 'I', 'Sometimes']
In [22]:
' '.join(reversed(s.split()))
Out[22]:
'child motherless a like feel I Sometimes'
In [23]:
# 나) 문자열의 순서 뒤집기
s[::-1]
Out[23]:
'dlihc sselrehtom a ekil leef I semitemoS'
In [24]:
# 다) 공백을 없애기
''.join(s.split())
Out[24]:
'SometimesIfeellikeamotherlesschild'

4.

In [37]:
a = [1,2,3]
b = a * 3
c = [a] * 3
In [38]:
# 가) b와 c의 차이
print (b)
print (c)
[1, 2, 3, 1, 2, 3, 1, 2, 3]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]

In [39]:
# 나) 
a[0] = 0

print(b)   
print(c)   
[1, 2, 3, 1, 2, 3, 1, 2, 3]
[[0, 2, 3], [0, 2, 3], [0, 2, 3]]

In [40]:
# 다)
# b는 a가 참조하는 레퍼런스를 복사했으므로 a의 변화와 관계없다
# c는 a레퍼런스를 복사했으므로 a의 변화에 반응한다.
In [44]:
# 라)
a = [1,2,3]

c = [a[:]] * 3  # 레퍼런스 전체 복사한 후 반복
print(c)

a[0] = 100
print(c)    # a의 변화와 관계 없다

c[0][0] = 100   # 그러나 항목들은 공유된다.
print(c)
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
[[100, 2, 3], [100, 2, 3], [100, 2, 3]]

In [45]:
# 마)
a = [1,2,3]

c = [a[:], a[:], a[:]]
print (c)

c[0][0] = 100   # 해당 항목에만 영향을 미친다.
print(c)
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
[[100, 2, 3], [1, 2, 3], [1, 2, 3]]

5.

In [50]:
L = list(range(10))
L
Out[50]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [51]:
L.sort(key=lambda a: a%5)
In [52]:
L
Out[52]:
[0, 5, 1, 6, 2, 7, 3, 8, 4, 9]

6.

In [95]:
a = [1]
b = [2]
a.append(b)
b.append(a)
In [96]:
# 가)
'''
a -->  [1, b]
b -->  [2, a]
'''
Out[96]:
'\na -->  [1, b]\nb -->  [2, a]\n'
In [97]:
# 나)
print(a)
print(b)
[1, [2, [...]]]
[2, [1, [...]]]

In [98]:
# 다)
import sys
print (sys.getrefcount(a))   # 현재 getrefcount() 함수의 참조를 포함하여 3
3

In [99]:
# 라)
del b
print(sys.getrefcount(a))   # 여전히 3이 맞다. b는 직접 a 를 가르키지 않았기 때문이다.
3

In [100]:
# 마)
'''
a -->  [1, b]
       [2, a]
'''
Out[100]:
'\na -->  [1, b]\n       [2, a]\n'
In [101]:
# 바)
del a

이제 객체를 참조할 수는 없지만, 내부에서는 상호 참조되고 있으므로 제거되지 않고 남아있다.

7.

In [102]:
sl = ['Spam', 'egg', 'Ham']
In [104]:
sl.sort(key=lambda a:a.lower())
sl
Out[104]:
['egg', 'Ham', 'Spam']

8.

In [105]:
s = ' first item : second item : third item '
In [110]:
L = []
for ele in s.split(':'):
    L.append(ele.strip())
L
Out[110]:
['first item', 'second item', 'third item']

9.

In [109]:
[ele.strip() for ele in s.split(':')]
Out[109]:
['first item', 'second item', 'third item']

10.

In [121]:
import re

s = 'Python is a programming language that lets you work more quickly and integrate your systems more effectively. You can learn to use Python and see almost immediate gains in productivity and lower maintenance costs.'
s2 = re.sub('[^0-9a-zA-Z]', ' ', s)  # 숫자, 영문을 제외한 기호는 공백으로 대치
s2
Out[121]:
'Python is a programming language that lets you work more quickly and integrate your systems more effectively  You can learn to use Python and see almost immediate gains in productivity and lower maintenance costs '
In [122]:
words = s2.split()  # 공백 단위 분리
words
Out[122]:
['Python',
 'is',
 'a',
 'programming',
 'language',
 'that',
 'lets',
 'you',
 'work',
 'more',
 'quickly',
 'and',
 'integrate',
 'your',
 'systems',
 'more',
 'effectively',
 'You',
 'can',
 'learn',
 'to',
 'use',
 'Python',
 'and',
 'see',
 'almost',
 'immediate',
 'gains',
 'in',
 'productivity',
 'and',
 'lower',
 'maintenance',
 'costs']
In [123]:
words.sort(key=lambda a:len(a))  # 문자열 길이에 따른 정렬
In [124]:
words
Out[124]:
['a',
 'is',
 'to',
 'in',
 'you',
 'and',
 'You',
 'can',
 'use',
 'and',
 'see',
 'and',
 'that',
 'lets',
 'work',
 'more',
 'your',
 'more',
 'learn',
 'gains',
 'lower',
 'costs',
 'Python',
 'Python',
 'almost',
 'quickly',
 'systems',
 'language',
 'integrate',
 'immediate',
 'programming',
 'effectively',
 'maintenance',
 'productivity']

11.

In [128]:
import os
import glob

glob.glob('../src/ch15/*.py')  # 현재 디렉토리에 파일이 없어서.. 다른 디렉토리 파일 목록으로 대치합니다.
Out[128]:
['../src/ch15/diamond2.py',
 '../src/ch15/multithread.py',
 '../src/ch15/mycmdline.py',
 '../src/ch15/diamond1.py',
 '../src/ch15/diamond3.py',
 '../src/ch15/deletagion.py']
In [133]:
for fpath in glob.glob('../src/ch15/*.py'):
    if os.path.getsize(fpath) > 500:
        print (fpath, os.path.getsize(fpath))
../src/ch15/multithread.py 809
../src/ch15/mycmdline.py 751

12.

In [136]:
import os

for fpath in glob.glob('../src/ch15/*.py'):  # 현재 디렉토리에 파일이 없어서.. 다른 디렉토리 파일 목록으로 대치합니다.
    print (fpath, os.path.getmtime(fpath))  # 일단 수정 시간들을 출력해보자. 시간은 숫자로 나온다
../src/ch15/diamond2.py 1385336343.990312
../src/ch15/multithread.py 1381500305.334853
../src/ch15/mycmdline.py 1381500305.334853
../src/ch15/diamond1.py 1385336340.7783122
../src/ch15/diamond3.py 1381500305.334853
../src/ch15/deletagion.py 1381500305.334853

In [138]:
import time
time.time()    # 현재 시간을 얻는 법
Out[138]:
1385336442.9007757
In [139]:
# 24시간 전 시각
time.time() - 24 * 60 * 60
Out[139]:
1385250066.0464716
In [140]:
# 종합
import os

reftime = time.time() - 24 * 60 * 60
for fpath in glob.glob('../src/ch15/*.py'):  # 현재 디렉토리에 파일이 없어서.. 다른 디렉토리 파일 목록으로 대치합니다.
    if os.path.getmtime(fpath) > reftime:
        print (fpath, os.path.getmtime(fpath))  # 일단 수정 시간들을 출력해보자. 시간은 숫자로 나온다
../src/ch15/diamond2.py 1385336343.990312
../src/ch15/diamond1.py 1385336340.7783122

13. (문제가 파이썬2 용으로 되어 있어서 문제를 파이썬3 용으로 다음과 같이 변경합니다)

긴 옵션의 처리 방법을 공부하고 다음을 풀어 보자. 옵션 처리는 argparse.ArgumentParser()를 이용한다. 명령줄에 URL 주소를 입력하면 해당 URL의 HTML 문서를 화면에 출력하는 프로그램을 작성해 보자. URL에서 HTML 문서를 가져오는 것은 다음과 같은 코드를 이용한다.

from urllib.request import urlopen
import sys

def getpage(url):
    f = urlopen(url)
    return f.read( )

text = getpage('http://python.org')

사용 방법은 다음과 같다. 출력 파일을 지정하지 않으면 output.html로 저장한다.

python getpage.py --output python.org.html http://python.org

In [168]:
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('url')
parser.add_argument('--output', default='output.html');
In [169]:
args = parser.parse_args('--output abc.html http://python.org'.split())
In [171]:
args
Out[171]:
Namespace(output='abc.html', url='http://python.org')
In [172]:
args.url
Out[172]:
'http://python.org'
In [173]:
args.output
Out[173]:
'abc.html'
In [175]:
# 종합
from urllib.request import urlopen
import argparse
import sys

def getpage(url):
    f = urlopen(url)
    return f.read( )

parser = argparse.ArgumentParser()
parser.add_argument('url')
parser.add_argument('--output', default='output.html');
#args = parser.parse_args()    # 명령행에서 실행하는 경우
args = parser.parse_args('--output abc.html http://python.org'.split())  # 임시 테스트

output = args.output
url = args.url
text = getpage(url)
In [176]:
len(text)
Out[176]:
20715
In []: