/Demo_1/Demo_1.py
Python | 397 lines | 320 code | 39 blank | 38 comment | 46 complexity | fe85ac007c39828395e343eb61620ae4 MD5 | raw file
- import math
- print("Hello, wordk!")
- classmates = ['Michael', 'Bob', 'Tracy']
- print(len(classmates))
- for name in classmates:
- print(name)
- sum = 0
- for x in [1,2,3,4,5,6]:
- sum += x
- print(sum)
- sum = 0
- for x in range(101):
- sum += x
- print(sum)
- dic = {'Michael':93, 'Bob': 75, 'Tracy': 85}
- print(dic['Michael'])
- print(dic)
- print(dic.get('SomeName', 'Do not have'))
- dic.pop('Bob')
- print(dic)
- s1 = set([5,2,3])
- s = set([12, 1 , 6])
- print(s1 | s)
- arr = [23, 23, 1, 4, 100]
- arr.sort()
- print(arr)
- def area_of_circle(x):
- return (3.141592654*x*x)
- print('%.3f' %(area_of_circle(1)))
- def move(x, y, stpe, angle = 0):
- return x *10 , y*10, angle*10
- tupleInstance = move(1, 2, 3 , 5)
- print(tupleInstance)
- def move(p):
- return p[0]+11
- L = [1,2]
- print(move(L))
- '''
- 练习
- 请定义一个函数quadratic(a, b, c),接收3个参数,返回一元二次方程:
- ax2 + bx + c = 0
- 的两个解。
- 提示:计算平方根可以调用math.sqrt()函数:
- '''
- #必选参数
- def quadratic(a, b, c):
- if not isinstance(a, (int, float)) or not isinstance(b, (int, float)) or not isinstance(c, (int, float)):
- raise TypeError('bad operand type')
- if a == 0:
- return -c / b
- else:
- return (math.sqrt(b * b - 4 * a * c) - b)/ 2.0 / a, ( - math.sqrt(b * b - 4 * a * c) - b)/ 2.0 / a
- print(quadratic(2, 3, 1))
- print(quadratic(1, 3, -4))
- def pow(x, n = 2):
- s = 1
- while(n):
- n -= 1
- s *= x
- return s
- print(pow(2,5))
- def add_end(L = []):
- L.append('End')
- return L
- print(add_end())
- print(add_end())
- def add_end(L = None):
- if L is None:
- L = []
- L.append('End')
- return L
- print(add_end())
- print(add_end())
- #可变参数
- def calc(*nums):
- sum = 0
- for i in nums:
- sum += math.pow(i, 2)
- return sum
- num = [1,2]
- print(calc(1,2))
- print(calc(*num))
- #关键字参数
- """关键字参数有什么用?它可以扩展函数的功能。"""
- """比如,在person函数里,我们保证能接收到name和age这两个参数,"""
- """但是,如果调用者愿意提供更多的参数,我们也能收到。"""
- """试想你正在做一个用户注册的功能,除了用户名和年龄是必填项外,其他都是可选项,"""
- """利用关键字参数来定义这个函数就能满足注册的需求。"""
- def person(name, age, **kw):
- print('name:', name, 'age:', age, 'others:', kw)
- if 'School'in kw:
- print("有School 信息")
- person("李金旭", 11, School = ['Neu','Swun'], Contry = 'China')
- #命名参数
- '''如果要限制关键字参数的名字,就可以用命名关键字参数,
- 例如,只接收city和job作为关键字参数。这种方式定义的函数如下:'''
- def person(name, age, *, city, job):
- print(name, age, city, job)
- person("李金旭", 11, city = ['Neu','Swun'], job = 'China')
- def person(name, age, *argv):
- print(name, age, argv)
- person("李金旭",11,'Neu')
- def person(name, age, *, city, job):
- print(name,"is", age," years old in ", city, "as a ",job)
- person("李金旭",11,city = "Bejing", job = "IT front to end Engineer")
- #参数组合
- '''
- 在Python中定义函数,可以用必选参数、默认参数、可变参数、关键字参数和命名关键字参数,这5种参数都可以组合使用。
- 但是请注意,参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数。
- '''
- '''
- *args是可变参数,args接收的是一个tuple;
- **kw是关键字参数,kw接收的是一个dict。
- '''
- def func1(a, b, c = 0, *argv, **kw):
- print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
- def func2(*argv, **kw):
- print(argv, kw)
- args = (1,2,3,4)
- kw = {'Name':'李金旭', 'Age': 11}
- func2(args, kw)
- def print_step(x, y):
- print("# ", x," --> ",y)
- def move(n, a, b, c):
- if(n == 1):
- print_step(a, c)
- else:
- move(n-1, a, c, b) #a通过c将n-1个移动到b
- print_step(a, c)
- move(n-1,b,a,c )#将n-1个从b通过a移动到c
- move(4,'A','B','C')
- #练习Leetcode 260. Single Number III
- class Solution(object):
- def singleNumber(self, nums):
- xor = 0
- for num in nums:
- xor = xor^num
- diff_pos = 0
- for i in range(31):
- if(xor & (1 << i)):
- diff_pos = i
- break
- rec = [0,0]
- for num in nums:
- if(num & (1 << diff_pos)):
- rec[1] ^= num
- else:
- rec[0] ^= num
- print(rec)
- return rec
- t = Solution()
- ans = t.singleNumber((1,1,2,2,4,6))
- print(ans)
- #切片
- list_num = list(range(100))
- print(list_num)
- print(list_num[:3])#取出前三个
- print(list_num[::3])#每隔3个取一个
- print(list_num[0:10])
- print(list_num[0:10:2])
- tuple = tuple(range(100))
- #列表生成公式
- print(list(range(1,11)))
- L = []
- for i in range(1,11):
- L.append(i * i)
- print(L)
- L = [ x * x for x in range(2, 10)]
- print(L)
- L = [x*x for x in range(1,11) if x%2 == 0]
- print(L)
- '''使用两层循环生成全排列'''
- L = [m + n for m in 'ABC' for n in 'XYZ']
- print(L)
- import os
- print([d for d in os.listdir('../')])
- L = ['Hello', 'World', 'IBM', 'Apple']
- print([s.lower() for s in L])
- print(isinstance(L[0], str))
- print(isinstance(L[1], int))
- #生成器
- g = (x * x for x in range(10))
- print(next(g))
- print(next(g))
- print(next(g))
- for n in g:
- print(n)
- def fibonacci(max):
- n,a,b = 0, 0, 1
- while n < max:
- print(b)
- a, b = b , a+b
- n = n + 1
- return 'done'
- print(fibonacci(10))
- def fibonacciGenerator(max):
- n,a,b = 0,0,1
- while n < max:
- yield b
- a,b = b, a+b
- n = n + 1
- return 'done'
- print(fibonacciGenerator(6))
- for n in fibonacciGenerator(11):
- print(n)
- '''generator和函数的执行流程不一样。函数是顺序执行,遇到return语句或者最后一行函数语句就返回。
- 而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的
- yield语句处继续执行。'''
- '''yield 相当于在程序中插入了一个断点,这个断点也是通过return返回的'''
- def odd():
- print('step 1')
- yield 1
- print('step 2')
- yield 3
- print('step 3')
- yield 5
- yield 'done'
- g = odd()
- while True:
- try:
- x = next(g)
- print('g:',x)
- except StopIteration as e:
- print('Generator return value:',e.value)
- break
- #练习:生成杨辉三角
- L = []
- def YanghuiTriangle(max):
- n = 0
- L = [[] for i in range(max)]
- while n < max:
- i = 0
- while i <= n:
- if i == 0 or i == n:
- L[n].append(1)
- else:
- L[n].append(L[n - 1][i] + L[n-1][i - 1])
- i+=1
- yield L[n]
- n += 1
- yield 'done'
- gY = YanghuiTriangle(10)
- while True:
- try:
- print('#',next(gY))
- except StopIteration as e:
- print('Generator return value : ', e.value)
- break
- #迭代器
- for x in [1,2,4,5,6,7]:
- print(x)
- '''等价于下面iter'''
- it = iter([1,2,4,5,6,7])
- while True:
- try:
- x = next(it)
- print(x)
- except StopIteration:
- break
- ####函数式编程####
- '''Python 支持函数式编程,因为可以使用变量作为参数,也支持用函数作为参数,所以Python不是纯函数式编程语言'''
- print(abs)
- f = abs
- '''函数名也是变量名'''
- print(f(-11))
- def add(x,y,f):
- return f(x) + f(y)
- print(add(-4,-5,f))
- #map/reduce
- from functools import reduce
- print(list(map(str,[-1,-2,-3,-4,-5])))
- def fn(x, y):
- print(x, y)
- return x*10 + y
- r = reduce(fn,[1,3,5,7,9])
- print(r)
- def func_sum(x, y):
- return x + y
- def square(x):
- return x*x
- list_r = map(square,[-1,-2,-3,-4,-5])
- ll_r = list(list_r)
- print('r = ',ll_r)
- ans = reduce(func_sum, ll_r)
- print('sum is ',ans)
- def add_100(a, b, c):
- print(a,b,c)
- return a * 10000+ b *100 + c
- list1 = [11,22,33]
- list2 = [44,55,66]
- list3 = [77,88,99]
- rec = map(add_100,list1, list2, list3)
- print(list(rec))
- from functools import reduce
- def fn(x, y):
- print(x, y)
- return x * 10 + y
- def char2num(s):
- return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
- '''{} is a dictionary, [] is index of dict, so [key] return value'''
- print(reduce(fn, map(char2num, '13579')))
- def str2int(s):
- def fn(x, y):
- return x * 10 + y
- def char2num(s):
- return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
- return reduce(fn, map(char2num, s))
- print(str2int('13578'))
- print(int('13573'))
- print(str(13572))
- def str2int_(s):
- def char2num(s):
- return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
- return reduce(lambda x,y: x * 10 + y, map(char2num, s))
- '''lambda 匿名函数,有些简单函数只需要用1次,所以不给起名字'''
- print(str2int_('2012'))
- #联系
- #1 规范化英文名
- def normalize(name):
- return name.capitalize()
- L1 = ['adam', 'LISA', 'barT']
- L2 = list(map(normalize, L1))
- print(L2)
- #2 请编写一个prod()函数,可以接受一个list并利用reduce()求积:
- 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]))
- #3 利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:
- from functools import reduce
- def str2float(s):
- def char2num(s):
- return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
- pos = s.find('.')
- s_num = s.split('.')[0] + s.split('.')[1]
- print(pos, s_num)
- L = reduce(lambda x,y : x * 10 + y, map(char2num, s_num))
- return L/ math.pow(10, pos)
- print('str2float(\'123.456\') =', str2float('123.456'))
- #Another solution
- def str2float_(s):
- def char2num(s):
- return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
- a, b = s.split('.')
- L = reduce(lambda x,y: x * 10 + y, map(char2num, a + b))
- return L/10**len(b)
- print('str2float(\'123.456\') =', str2float('123.456'))