PageRenderTime 49ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/Demo_1/Demo_1.py

https://gitlab.com/luntai/Python
Python | 397 lines | 320 code | 39 blank | 38 comment | 46 complexity | fe85ac007c39828395e343eb61620ae4 MD5 | raw file
  1. import math
  2. print("Hello, wordk!")
  3. classmates = ['Michael', 'Bob', 'Tracy']
  4. print(len(classmates))
  5. for name in classmates:
  6. print(name)
  7. sum = 0
  8. for x in [1,2,3,4,5,6]:
  9. sum += x
  10. print(sum)
  11. sum = 0
  12. for x in range(101):
  13. sum += x
  14. print(sum)
  15. dic = {'Michael':93, 'Bob': 75, 'Tracy': 85}
  16. print(dic['Michael'])
  17. print(dic)
  18. print(dic.get('SomeName', 'Do not have'))
  19. dic.pop('Bob')
  20. print(dic)
  21. s1 = set([5,2,3])
  22. s = set([12, 1 , 6])
  23. print(s1 | s)
  24. arr = [23, 23, 1, 4, 100]
  25. arr.sort()
  26. print(arr)
  27. def area_of_circle(x):
  28. return (3.141592654*x*x)
  29. print('%.3f' %(area_of_circle(1)))
  30. def move(x, y, stpe, angle = 0):
  31. return x *10 , y*10, angle*10
  32. tupleInstance = move(1, 2, 3 , 5)
  33. print(tupleInstance)
  34. def move(p):
  35. return p[0]+11
  36. L = [1,2]
  37. print(move(L))
  38. '''
  39. 练习
  40. 请定义一个函数quadratic(a, b, c)接收3个参数返回一元二次方程
  41. ax2 + bx + c = 0
  42. 的两个解
  43. 提示计算平方根可以调用math.sqrt()函数
  44. '''
  45. #必选参数
  46. def quadratic(a, b, c):
  47. if not isinstance(a, (int, float)) or not isinstance(b, (int, float)) or not isinstance(c, (int, float)):
  48. raise TypeError('bad operand type')
  49. if a == 0:
  50. return -c / b
  51. else:
  52. return (math.sqrt(b * b - 4 * a * c) - b)/ 2.0 / a, ( - math.sqrt(b * b - 4 * a * c) - b)/ 2.0 / a
  53. print(quadratic(2, 3, 1))
  54. print(quadratic(1, 3, -4))
  55. def pow(x, n = 2):
  56. s = 1
  57. while(n):
  58. n -= 1
  59. s *= x
  60. return s
  61. print(pow(2,5))
  62. def add_end(L = []):
  63. L.append('End')
  64. return L
  65. print(add_end())
  66. print(add_end())
  67. def add_end(L = None):
  68. if L is None:
  69. L = []
  70. L.append('End')
  71. return L
  72. print(add_end())
  73. print(add_end())
  74. #可变参数
  75. def calc(*nums):
  76. sum = 0
  77. for i in nums:
  78. sum += math.pow(i, 2)
  79. return sum
  80. num = [1,2]
  81. print(calc(1,2))
  82. print(calc(*num))
  83. #关键字参数
  84. """关键字参数有什么用?它可以扩展函数的功能。"""
  85. """比如,在person函数里,我们保证能接收到name和age这两个参数,"""
  86. """但是,如果调用者愿意提供更多的参数,我们也能收到。"""
  87. """试想你正在做一个用户注册的功能,除了用户名和年龄是必填项外,其他都是可选项,"""
  88. """利用关键字参数来定义这个函数就能满足注册的需求。"""
  89. def person(name, age, **kw):
  90. print('name:', name, 'age:', age, 'others:', kw)
  91. if 'School'in kw:
  92. print("有School 信息")
  93. person("李金旭", 11, School = ['Neu','Swun'], Contry = 'China')
  94. #命名参数
  95. '''如果要限制关键字参数的名字,就可以用命名关键字参数,
  96. 例如只接收city和job作为关键字参数这种方式定义的函数如下'''
  97. def person(name, age, *, city, job):
  98. print(name, age, city, job)
  99. person("李金旭", 11, city = ['Neu','Swun'], job = 'China')
  100. def person(name, age, *argv):
  101. print(name, age, argv)
  102. person("李金旭",11,'Neu')
  103. def person(name, age, *, city, job):
  104. print(name,"is", age," years old in ", city, "as a ",job)
  105. person("李金旭",11,city = "Bejing", job = "IT front to end Engineer")
  106. #参数组合
  107. '''
  108. 在Python中定义函数可以用必选参数默认参数可变参数关键字参数和命名关键字参数这5种参数都可以组合使用
  109. 但是请注意参数定义的顺序必须是必选参数默认参数可变参数命名关键字参数和关键字参数
  110. '''
  111. '''
  112. *args是可变参数args接收的是一个tuple
  113. **kw是关键字参数kw接收的是一个dict
  114. '''
  115. def func1(a, b, c = 0, *argv, **kw):
  116. print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
  117. def func2(*argv, **kw):
  118. print(argv, kw)
  119. args = (1,2,3,4)
  120. kw = {'Name':'李金旭', 'Age': 11}
  121. func2(args, kw)
  122. def print_step(x, y):
  123. print("# ", x," --> ",y)
  124. def move(n, a, b, c):
  125. if(n == 1):
  126. print_step(a, c)
  127. else:
  128. move(n-1, a, c, b) #a通过c将n-1个移动到b
  129. print_step(a, c)
  130. move(n-1,b,a,c )#将n-1个从b通过a移动到c
  131. move(4,'A','B','C')
  132. #练习Leetcode 260. Single Number III
  133. class Solution(object):
  134. def singleNumber(self, nums):
  135. xor = 0
  136. for num in nums:
  137. xor = xor^num
  138. diff_pos = 0
  139. for i in range(31):
  140. if(xor & (1 << i)):
  141. diff_pos = i
  142. break
  143. rec = [0,0]
  144. for num in nums:
  145. if(num & (1 << diff_pos)):
  146. rec[1] ^= num
  147. else:
  148. rec[0] ^= num
  149. print(rec)
  150. return rec
  151. t = Solution()
  152. ans = t.singleNumber((1,1,2,2,4,6))
  153. print(ans)
  154. #切片
  155. list_num = list(range(100))
  156. print(list_num)
  157. print(list_num[:3])#取出前三个
  158. print(list_num[::3])#每隔3个取一个
  159. print(list_num[0:10])
  160. print(list_num[0:10:2])
  161. tuple = tuple(range(100))
  162. #列表生成公式
  163. print(list(range(1,11)))
  164. L = []
  165. for i in range(1,11):
  166. L.append(i * i)
  167. print(L)
  168. L = [ x * x for x in range(2, 10)]
  169. print(L)
  170. L = [x*x for x in range(1,11) if x%2 == 0]
  171. print(L)
  172. '''使用两层循环生成全排列'''
  173. L = [m + n for m in 'ABC' for n in 'XYZ']
  174. print(L)
  175. import os
  176. print([d for d in os.listdir('../')])
  177. L = ['Hello', 'World', 'IBM', 'Apple']
  178. print([s.lower() for s in L])
  179. print(isinstance(L[0], str))
  180. print(isinstance(L[1], int))
  181. #生成器
  182. g = (x * x for x in range(10))
  183. print(next(g))
  184. print(next(g))
  185. print(next(g))
  186. for n in g:
  187. print(n)
  188. def fibonacci(max):
  189. n,a,b = 0, 0, 1
  190. while n < max:
  191. print(b)
  192. a, b = b , a+b
  193. n = n + 1
  194. return 'done'
  195. print(fibonacci(10))
  196. def fibonacciGenerator(max):
  197. n,a,b = 0,0,1
  198. while n < max:
  199. yield b
  200. a,b = b, a+b
  201. n = n + 1
  202. return 'done'
  203. print(fibonacciGenerator(6))
  204. for n in fibonacciGenerator(11):
  205. print(n)
  206. '''generator和函数的执行流程不一样。函数是顺序执行,遇到return语句或者最后一行函数语句就返回。
  207. 而变成generator的函数在每次调用next()的时候执行遇到yield语句返回再次执行时从上次返回的
  208. yield语句处继续执行'''
  209. '''yield 相当于在程序中插入了一个断点,这个断点也是通过return返回的'''
  210. def odd():
  211. print('step 1')
  212. yield 1
  213. print('step 2')
  214. yield 3
  215. print('step 3')
  216. yield 5
  217. yield 'done'
  218. g = odd()
  219. while True:
  220. try:
  221. x = next(g)
  222. print('g:',x)
  223. except StopIteration as e:
  224. print('Generator return value:',e.value)
  225. break
  226. #练习生成杨辉三角
  227. L = []
  228. def YanghuiTriangle(max):
  229. n = 0
  230. L = [[] for i in range(max)]
  231. while n < max:
  232. i = 0
  233. while i <= n:
  234. if i == 0 or i == n:
  235. L[n].append(1)
  236. else:
  237. L[n].append(L[n - 1][i] + L[n-1][i - 1])
  238. i+=1
  239. yield L[n]
  240. n += 1
  241. yield 'done'
  242. gY = YanghuiTriangle(10)
  243. while True:
  244. try:
  245. print('#',next(gY))
  246. except StopIteration as e:
  247. print('Generator return value : ', e.value)
  248. break
  249. #迭代器
  250. for x in [1,2,4,5,6,7]:
  251. print(x)
  252. '''等价于下面iter'''
  253. it = iter([1,2,4,5,6,7])
  254. while True:
  255. try:
  256. x = next(it)
  257. print(x)
  258. except StopIteration:
  259. break
  260. ####函数式编程####
  261. '''Python 支持函数式编程,因为可以使用变量作为参数,也支持用函数作为参数,所以Python不是纯函数式编程语言'''
  262. print(abs)
  263. f = abs
  264. '''函数名也是变量名'''
  265. print(f(-11))
  266. def add(x,y,f):
  267. return f(x) + f(y)
  268. print(add(-4,-5,f))
  269. #map/reduce
  270. from functools import reduce
  271. print(list(map(str,[-1,-2,-3,-4,-5])))
  272. def fn(x, y):
  273. print(x, y)
  274. return x*10 + y
  275. r = reduce(fn,[1,3,5,7,9])
  276. print(r)
  277. def func_sum(x, y):
  278. return x + y
  279. def square(x):
  280. return x*x
  281. list_r = map(square,[-1,-2,-3,-4,-5])
  282. ll_r = list(list_r)
  283. print('r = ',ll_r)
  284. ans = reduce(func_sum, ll_r)
  285. print('sum is ',ans)
  286. def add_100(a, b, c):
  287. print(a,b,c)
  288. return a * 10000+ b *100 + c
  289. list1 = [11,22,33]
  290. list2 = [44,55,66]
  291. list3 = [77,88,99]
  292. rec = map(add_100,list1, list2, list3)
  293. print(list(rec))
  294. from functools import reduce
  295. def fn(x, y):
  296. print(x, y)
  297. return x * 10 + y
  298. def char2num(s):
  299. return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
  300. '''{} is a dictionary, [] is index of dict, so [key] return value'''
  301. print(reduce(fn, map(char2num, '13579')))
  302. def str2int(s):
  303. def fn(x, y):
  304. return x * 10 + y
  305. def char2num(s):
  306. return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
  307. return reduce(fn, map(char2num, s))
  308. print(str2int('13578'))
  309. print(int('13573'))
  310. print(str(13572))
  311. def str2int_(s):
  312. def char2num(s):
  313. return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
  314. return reduce(lambda x,y: x * 10 + y, map(char2num, s))
  315. '''lambda 匿名函数,有些简单函数只需要用1次,所以不给起名字'''
  316. print(str2int_('2012'))
  317. #联系
  318. #1 规范化英文名
  319. def normalize(name):
  320. return name.capitalize()
  321. L1 = ['adam', 'LISA', 'barT']
  322. L2 = list(map(normalize, L1))
  323. print(L2)
  324. #2 请编写一个prod()函数可以接受一个list并利用reduce()求积
  325. from functools import reduce
  326. def prod(L):
  327. return reduce(lambda x,y : x * y, L)
  328. print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
  329. #3 利用map和reduce编写一个str2float函数把字符串'123.456'转换成浮点数123.456
  330. from functools import reduce
  331. def str2float(s):
  332. def char2num(s):
  333. return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
  334. pos = s.find('.')
  335. s_num = s.split('.')[0] + s.split('.')[1]
  336. print(pos, s_num)
  337. L = reduce(lambda x,y : x * 10 + y, map(char2num, s_num))
  338. return L/ math.pow(10, pos)
  339. print('str2float(\'123.456\') =', str2float('123.456'))
  340. #Another solution
  341. def str2float_(s):
  342. def char2num(s):
  343. return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
  344. a, b = s.split('.')
  345. L = reduce(lambda x,y: x * 10 + y, map(char2num, a + b))
  346. return L/10**len(b)
  347. print('str2float(\'123.456\') =', str2float('123.456'))