diff --git a/.gitignore b/.gitignore index 2cc2704f..5774f27a 100644 --- a/.gitignore +++ b/.gitignore @@ -44,6 +44,7 @@ ehthumbs.db Thumbs.db dist MANIFEST +.idea # Translations *.mo diff --git a/samples/advance/do_generator.py b/samples/advance/do_generator.py index 4c89afc0..ed40e7c3 100755 --- a/samples/advance/do_generator.py +++ b/samples/advance/do_generator.py @@ -29,3 +29,17 @@ def fib(max): print('Generator return value:', e.value) break +# 杨辉三角 +def triangles(): + N = [1] + while True: + yield N # generator函数与普通函数的差别:在执行过程中,遇到yield就中断,下次又继续执行 + N.append(0) + N = [N[i-1] + N[i] for i in range(len(N))] + +n = 0 +for t in triangles(): + print(t) + n = n + 1 + if n == 10: + break \ No newline at end of file diff --git a/samples/advance/do_listcompr.py b/samples/advance/do_listcompr.py index 328d5c5a..a3d17a6f 100755 --- a/samples/advance/do_listcompr.py +++ b/samples/advance/do_listcompr.py @@ -8,5 +8,5 @@ d = {'x': 'A', 'y': 'B', 'z': 'C' } print([k + '=' + v for k, v in d.items()]) -L = ['Hello', 'World', 'IBM', 'Apple'] -print([s.lower() for s in L]) +L = ['Hello', 'World', 18, 'IBM', 'Apple', None] +print([s.lower() for s in L if isinstance(s, str)]) diff --git a/samples/basic/do_for.py b/samples/basic/do_for.py index 8db278f4..477447e5 100755 --- a/samples/basic/do_for.py +++ b/samples/basic/do_for.py @@ -9,3 +9,9 @@ # 打印数字 0 - 9 for x in range(10): print(x) + +# 计算1+2+3...+100 +sum = 0 +for n in list(range(1,101,1)): + sum += n +print(sum) diff --git a/samples/basic/do_if.py b/samples/basic/do_if.py index c0c16d7a..df2b1c09 100755 --- a/samples/basic/do_if.py +++ b/samples/basic/do_if.py @@ -5,11 +5,36 @@ # input()返回的是字符串 # 必须通过int()将字符串转换为整数 # 才能用于数值比较: -age = int(input('Input your age: ')) - -if age >= 18: - print('adult') -elif age >= 6: - print('teenager') -else: - print('kid') + +def age(): + age = int(input('请输入你的年龄: ')) + if age >= 18: + print('adult') + elif age >= 6: + print('teenager') + else: + print('kid') +age() + +def bmi(): + weight = float(input('请输入你的体重:')) + height = float(input('请输入你的身高:')) + + bmi = weight/height/height + if bmi < 18.5: + print('过轻') + elif bmi < 25: + print('正常') + elif bmi < 28: + print('过重') + elif bmi < 32: + print('肥胖') + else: + print('严重肥胖') + +bmi() + + + + + diff --git a/samples/basic/the_list.py b/samples/basic/the_list.py index 8dac133f..b28ad510 100755 --- a/samples/basic/the_list.py +++ b/samples/basic/the_list.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +''' classmates = ['Michael', 'Bob', 'Tracy'] print('classmates =', classmates) print('len(classmates) =', len(classmates)) @@ -10,3 +11,17 @@ print('classmates[-1] =', classmates[-1]) classmates.pop() print('classmates =', classmates) +''' + +L = [ +['Apple', 'Google', 'Microsoft'], +['Java', 'Python', 'Ruby', 'PHP'], +['Adam', 'Bart', 'Lisa'] +] +print(L[0][0]) +print(L[1][1]) +print(L[2][2]) +print(L[-1][-1]) + +L.append('yunge') +print(L[-1]) \ No newline at end of file diff --git a/samples/basic/the_set.py b/samples/basic/the_set.py index 67162e6a..9d586a12 100755 --- a/samples/basic/the_set.py +++ b/samples/basic/the_set.py @@ -4,5 +4,6 @@ s1 = set([1, 1, 2, 2, 3, 3]) print(s1) s2 = set([2, 3, 4]) +print(s2) print(s1 & s2) print(s1 | s2) diff --git a/samples/basic/the_tuple.py b/samples/basic/the_tuple.py index 382c3aa7..d1163969 100755 --- a/samples/basic/the_tuple.py +++ b/samples/basic/the_tuple.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- -classmates = ('Michael', 'Bob', 'Tracy') +classmates = ('Michael', 'Bob', 'Tracy', ['yunge', 'handsome']) print('classmates =', classmates) print('len(classmates) =', len(classmates)) print('classmates[0] =', classmates[0]) @@ -9,5 +9,9 @@ print('classmates[2] =', classmates[2]) print('classmates[-1] =', classmates[-1]) -# cannot modify tuple: -classmates[0] = 'Adam' +# 不能修改元组内不可变的值 +#classmates[0] = 'Adam' + +# 元组里的列表内容是可变的 +classmates[-1][0] = 'liuxinyun' +print('classmates[-1] =', classmates[-1]) diff --git a/samples/function/call_func.py b/samples/function/call_func.py index d864134a..a0a91d08 100755 --- a/samples/function/call_func.py +++ b/samples/function/call_func.py @@ -7,3 +7,7 @@ print('max(1, 2, 3) =', max(1, 2, 3)) print('min(1, 2, 3) =', min(1, 2, 3)) print('sum([1, 2, 3]) =', sum([1, 2, 3])) + +n1 = 10 +n2 = 255 +print(hex(n1), hex(n2)) diff --git a/samples/function/def_func.py b/samples/function/def_func.py index d7c09a13..c7c1cab9 100755 --- a/samples/function/def_func.py +++ b/samples/function/def_func.py @@ -19,7 +19,7 @@ def move(x, y, step, angle=0): n = my_abs(-20) print(n) -x, y = move(100, 100, 60, math.pi / 6) +x, y = move(100, 100, 60, int(math.pi / 6)) print(x, y) # TypeError: bad operand type: diff --git a/samples/function/recur.py b/samples/function/recur.py index e3f66076..9a53e899 100755 --- a/samples/function/recur.py +++ b/samples/function/recur.py @@ -12,13 +12,23 @@ def fact(n): print('fact(5) =', fact(5)) print('fact(10) =', fact(10)) +# 尾递归 +def fact1(n): + return fact_iter(n,1) +def fact_iter(num, product): + if num==1: + return product + return fact_iter(num-1, num*product) + +print('fact(6) = ', fact1(6)) + # 利用递归函数移动汉诺塔: def move(n, a, b, c): if n == 1: print('move', a, '-->', c) else: - move(n-1, a, c, b) - move(1, a, b, c) - move(n-1, b, a, c) + move(n-1, a, c, b) # 将上边的n-1个小盘子通过c移动到b + move(1, a, b, c) # 将最后一个大盘子通过b移动c + move(n-1, b, a, c) # 将b上的n-1个小盘子通过a移动到c move(4, 'A', 'B', 'C') diff --git a/samples/functional/decorator.py b/samples/functional/decorator.py index 938bedf5..d7b5d8c3 100755 --- a/samples/functional/decorator.py +++ b/samples/functional/decorator.py @@ -6,8 +6,9 @@ def log(func): @functools.wraps(func) def wrapper(*args, **kw): - print('call %s():' % func.__name__) - return func(*args, **kw) + print('begin call %s():' % func.__name__) + func(*args, **kw) + print('end call %s():' % func.__name__) return wrapper @log @@ -16,11 +17,14 @@ def now(): now() -def logger(text): +def logger(text=None): def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): - print('%s %s():' % (text, func.__name__)) + if text is None: + print('call %s():' % func.__name__) + else: + print('%s %s():' % (text, func.__name__)) return func(*args, **kw) return wrapper return decorator diff --git a/samples/functional/do_filter.py b/samples/functional/do_filter.py index 8a9081cc..682a6609 100755 --- a/samples/functional/do_filter.py +++ b/samples/functional/do_filter.py @@ -1,11 +1,17 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +# 奇数 def is_odd(n): return n % 2 == 1 +# 回数 +def is_palindrome(n): + return str(n) == str(n)[::-1] + L = range(100) +print(list(filter(is_palindrome, L))) print(list(filter(is_odd, L))) def not_empty(s): diff --git a/samples/functional/do_map.py b/samples/functional/do_map.py index 9360a50a..943f054d 100755 --- a/samples/functional/do_map.py +++ b/samples/functional/do_map.py @@ -1,7 +1,18 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +from functools import reduce + def f(x): return x * x print(list(map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]))) + +def normalize(name): + r1 = name.upper()[0] + r2 = name.lower()[1:] + return r1 + r2 + +L1 = ['adam', 'LISA', 'barT'] +L2 = list(map(normalize, L1)) +print(L2) diff --git a/samples/functional/do_partial.py b/samples/functional/do_partial.py index 05da7b6f..a287b0b0 100755 --- a/samples/functional/do_partial.py +++ b/samples/functional/do_partial.py @@ -6,4 +6,12 @@ int2 = functools.partial(int, base=2) print('1000000 =', int2('1000000')) -print('1010101 =', int2('1010101')) +print('1010101 =', int2('1010101', base=10)) + +# 把1作为参数的一部分 +min1 = functools.partial(min, 1) +print(min1(5, 7, 2)) + +# 把10作为参数的一部分 +max2 = functools.partial(max, 10) +print(max2(5, 7, 2)) diff --git a/samples/functional/do_reduce.py b/samples/functional/do_reduce.py index bf8bc8a9..46f2c5bd 100755 --- a/samples/functional/do_reduce.py +++ b/samples/functional/do_reduce.py @@ -3,6 +3,11 @@ from functools import reduce + +def prod(L): + return reduce(lambda x, y : x * y, L) +print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9])) + CHAR_TO_INT = { '0': 0, '1': 1, diff --git a/samples/functional/do_sorted.py b/samples/functional/do_sorted.py index c787958d..6e8e61cb 100755 --- a/samples/functional/do_sorted.py +++ b/samples/functional/do_sorted.py @@ -8,8 +8,17 @@ print(sorted(L)) print(sorted(L, key=str.lower)) +def by_name(t): + return t[0] + +def by_score(t): + return t[1] + students = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] print(sorted(students, key=itemgetter(0))) +print(sorted(students, key=lambda t: t[0])) +print(sorted(students, key=by_name)) print(sorted(students, key=lambda t: t[1])) +print(sorted(students, key=by_score)) print(sorted(students, key=itemgetter(1), reverse=True)) diff --git a/samples/functional/prime_numbers.py b/samples/functional/prime_numbers.py index e6a6a9e2..7174a652 100755 --- a/samples/functional/prime_numbers.py +++ b/samples/functional/prime_numbers.py @@ -1,12 +1,6 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- -def main(): - for n in primes(): - if n < 1000: - print(n) - else: - break def _odd_iter(): n = 1 @@ -19,11 +13,18 @@ def _not_divisible(n): def primes(): yield 2 - it = _odd_iter() + it = _odd_iter() # 初始化序列 while True: - n = next(it) + n = next(it) # 返回序列的第一个数 yield n it = filter(_not_divisible(n), it) +def main(): + for n in primes(): + if n < 1000: + print(n) + else: + break + if __name__ == '__main__': main() diff --git a/samples/module/hello.py b/samples/module/hello.py index 4cb622bf..6f144ed4 100755 --- a/samples/module/hello.py +++ b/samples/module/hello.py @@ -10,7 +10,7 @@ def test(): args = sys.argv if len(args)==1: - print('Hello, world!') + print('Hello, world!') elif len(args)==2: print('Hello, %s!' % args[1]) else: @@ -18,4 +18,6 @@ def test(): if __name__=='__main__': test() + sys.argv.append('yunge') + test() diff --git a/samples/oop_advance/special_getattr.py b/samples/oop_advance/special_getattr.py index 930141a4..e381e67d 100755 --- a/samples/oop_advance/special_getattr.py +++ b/samples/oop_advance/special_getattr.py @@ -1,6 +1,24 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- + +class Chain(object): + def __init__(self, path=''): + self._path = path + + def __getattr__(self, path): + return Chain('%s/%s' % (self._path, path)) + + def __call__(self, path): + return Chain('%s/%s' % (self._path, path)) + + def __str__(self): + return self._path + __repr__ = __str__ + +print(Chain().github.liuxinyun.repos) +print(Chain('github').users('liuxinyun').repos) + class Student(object): def __init__(self): diff --git a/samples/oop_advance/special_getitem.py b/samples/oop_advance/special_getitem.py index 19f5bcdd..1edeff4a 100755 --- a/samples/oop_advance/special_getitem.py +++ b/samples/oop_advance/special_getitem.py @@ -12,15 +12,20 @@ def __getitem__(self, n): if isinstance(n, slice): start = n.start stop = n.stop + step = n.step if start is None: start = 0 + if stop is None or stop<=0: + raise ValueError('slice stop must be positive value') + if step is None or step<=0: + step = 1 a, b = 1, 1 L = [] for x in range(stop): if x >= start: L.append(a) a, b = b, a + b - return L + return L[::step] f = Fib() print(f[0]) @@ -28,3 +33,4 @@ def __getitem__(self, n): print(f[100]) print(f[0:5]) print(f[:10]) +print(f[:5:2]) diff --git a/samples/oop_advance/special_iter.py b/samples/oop_advance/special_iter.py index 90e1f8f1..e2b49eed 100755 --- a/samples/oop_advance/special_iter.py +++ b/samples/oop_advance/special_iter.py @@ -12,7 +12,7 @@ def __iter__(self): def __next__(self): self.a, self.b = self.b, self.a + self.b # 计算下一个值 if self.a > 100000: # 退出循环的条件 - raise StopIteration(); + raise StopIteration() return self.a # 返回下一个值 for n in Fib(): diff --git a/samples/oop_advance/special_str.py b/samples/oop_advance/special_str.py index 1071b693..79d837d9 100755 --- a/samples/oop_advance/special_str.py +++ b/samples/oop_advance/special_str.py @@ -6,9 +6,14 @@ class Student(object): def __init__(self, name): self.name = name + def __call__(self): + print(self) + def __str__(self): return 'Student object (name: %s)' % self.name __repr__ = __str__ print(Student('Michael')) +s = Student('yunge') +s() diff --git a/samples/oop_advance/use_property.py b/samples/oop_advance/use_property.py index 9edcb02a..bf19587e 100755 --- a/samples/oop_advance/use_property.py +++ b/samples/oop_advance/use_property.py @@ -1,6 +1,33 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +class Screen(object): + + @property + def width(self): + return self._width + + @width.setter + def width(self, value): + self._width = value + + @property + def height(self): + return self._height + + @height.setter + def height(self, value): + self._height = value + + @property + def resolution(self): + return self._width * self._height + +s = Screen() +s.width = 1024 +s.height = 768 +print(s.resolution) + class Student(object): @property diff --git a/samples/oop_basic/get_type.py b/samples/oop_basic/get_type.py index ae079e63..6d215aa9 100755 --- a/samples/oop_basic/get_type.py +++ b/samples/oop_basic/get_type.py @@ -7,8 +7,14 @@ print('type(\'123\') =', type('123')) print('type(None) =', type(None)) print('type(abs) =', type(abs)) +print('type(123)==int ?', type(123)==int) +print('type(\'abc\')==str ?', type('abc')==str) import types -print('type(\'abc\')==str?', type('abc')==str) +print('type(abs)==BuiltinFunctionType ?', type(abs)==types.BuiltinFunctionType) +print('type(lambda x: x)==LambdaType ?', type(lambda x: x)==types.LambdaType) +print('type((x for x in range(10)))==GeneratorType ?', type((x for x in range(10)))==types.GeneratorType) + + diff --git a/samples/oop_basic/protected_student.py b/samples/oop_basic/protected_student.py index 6d67a71c..058a313c 100755 --- a/samples/oop_basic/protected_student.py +++ b/samples/oop_basic/protected_student.py @@ -32,4 +32,8 @@ def get_grade(self): bart.set_score(60) print('bart.get_score() =', bart.get_score()) +# 双下划线开头表示私有变量,但是Python并没有提供限制使用的方法,因此非要用也可以,全靠自觉。 +bart.__score = 70 +print(bart.__score) + print('DO NOT use bart._Student__name:', bart._Student__name) diff --git a/samples/oop_basic/student.py b/samples/oop_basic/student.py index 8a832ff0..b2b13f2c 100755 --- a/samples/oop_basic/student.py +++ b/samples/oop_basic/student.py @@ -27,3 +27,8 @@ def get_grade(self): print('grade of Bart:', bart.get_grade()) print('grade of Lisa:', lisa.get_grade()) + +# Python可以直接为实例变量增加属性 +bart.age = 18 +print(bart.age) +print(lisa.age)