tianzhig 发表于 2018-8-15 07:39:56

7.Python入门到精通

  函数:递归是神马
  递归求阶乘
  写一个求阶乘的函数
  正整数阶乘指从1乘以2乘以3乘以4一直乘到所要求的数。
  例如所给的数是5,则阶乘式是1×2×3×4×5,得到的积是120,所以120就是4的阶乘。
  def factorial(n):
  result = n
  for i in range(1,n):
  result *= i
  return result
  number = int(input("请输入一个正整数:"))
  result = factorial(number)
  print("%d的阶乘是:%d" % (number,result))
  def factorial(n):
  if n == 1:
  return 1
  else:
  return n * factorial(n-1)
  number = int(input("请输入一个正整数:"))
  result = factorial(number)
  print("%d的阶乘是:%d" % (number,result))
  
  假设我们n的值传入是5,那么:
  factorial(5) = 5 * factorial(4)
  factorial(4) = 4 * factorial(3)
  factorial(3) = 3 * factorial(2)
  factorial(2) = 2 * factorial(1)
  factorial(1) = 1
  斐波那契数列的迭代实现
  我们都知道兔子繁殖能力是惊人的,如下图:
  所经过的月数123456789101112
  兔子的总对数1123581321345589144
  我们可以用数学函数来定义:
  1,当n=1
  F(n) =      1,当n=2
  F(n-1)+F(n-2),当n>2
  课间练习:假设我们需要求出经历了20个月后,总共有多少对小兔崽子?(迭代 vs 递归)
  def fab(n):
  n1 = 1
  n2 = 1
  n3 = 1
  if n < 1:
  print('输入有误!')
  return -1
  while (n-2) > 0:
  n3 = n2 + n1
  n1 = n2
  n2 = n3
  n -= 1
  return n3
  result = fab(20)
  if result != -1:
  print('总共有%d对小兔崽子诞生!' % result)
  def fab(n):
  if n < 1:
  print('输入有误!')
  return -1
  if n == 1 or n == 2:
  return 1
  else:
  return fab(n-1) + fab(n-2)
  result = fab(20)
  if result != -1:
  print('总共有%d对小兔崽子诞生!' % result)
  递归:汉诺塔
  def hanoi(n, x, y, z):
  if n == 1:
  print(x, ' --> ', z)
  else:
  hanoi(n-1, x, z, y) # 将前n-1个盘子从x移动到y上
  print(x, ' --> ', z) # 将最底下的最后一个盘子从x移动到z上
  hanoi(n-1, y, x, z) # 将y上的n-1个盘子移动到z上
  n = int(input('请输入汉诺塔的层数:'))
  hanoi(n, 'X', 'Y', 'Z')
  字典:当索引不好用时
  >>> brand = ['李宁' , '耐克' , '阿迪达斯' , '鱼C工作室']
  >>> slogan = ['一切皆有可能' , 'Just do it' , 'Impossible is nothing' , '让编程改变世界']
  >>> print('鱼C工作室的口号是:', slogan)
  鱼C工作室的口号是: 让编程改变世界
  >>>
  创建和访问字典
  >>> dict1 = {'李宁':'一切皆有可能' , '耐克': 'Just do it', '阿迪达斯' :'Impossible is nothing', '鱼C工作室':'让编程改变世界'}
  >>> print('鱼C工作室的口号是:',dict1['鱼C工作室'])
  鱼C工作室的口号是: 让编程改变世界
  >>>
  >>> dict2 = {1:'one',2:'two',3:'three'}
  >>> dict2
  'two'
  >>>
  >>> help(dict)

  Help on>  class dict(object)
  |dict() -> new empty dictionary
  |dict(mapping) -> new dictionary initialized from a mapping object's
  |      (key, value) pairs
  |dict(iterable) -> new dictionary initialized as if via:
  |      d = {}
  |      for k, v in iterable:
  |          d = v
  |dict(**kwargs) -> new dictionary initialized with the name=value pairs
  |      in the keyword argument list.For example:dict(one=1, two=2)
  |
  |Methods defined here:
  |
  |__contains__(self, key, /)
  |      True if D has a key k, else False.
  |
  |__delitem__(self, key, /)
  |      Delete self.
  |
  |__eq__(self, value, /)
  |      Return self==value.
  |
  |__ge__(self, value, /)
  |      Return self>=value.
  |
  |__getattribute__(self, name, /)
  |      Return getattr(self, name).
  |
  |__getitem__(...)
  |      x.__getitem__(y) <==> x
  |
  |__gt__(self, value, /)
  |      Return self>value.
  |
  |__init__(self, /, *args, **kwargs)
  |      Initialize self.See help(type(self)) for accurate signature.
  |
  |__iter__(self, /)
  |      Implement iter(self).
  |
  |__le__(self, value, /)
  |      Return self<=value.
  |
  |__len__(self, /)
  |      Return len(self).
  |
  |__lt__(self, value, /)
  |      Return self<value.
  |
  |__ne__(self, value, /)
  |      Return self!=value.
  |
  |__new__(*args, **kwargs) from builtins.type
  |      Create and return a new object.See help(type) for accurate signature.
  |
  |__repr__(self, /)
  |      Return repr(self).
  |
  |__setitem__(self, key, value, /)
  |      Set self to value.
  |
  |__sizeof__(...)

  |      D.__sizeof__() ->>  |
  |clear(...)
  |      D.clear() -> None.Remove all items from D.
  |
  |copy(...)
  |      D.copy() -> a shallow copy of D
  |
  |fromkeys(iterable, value=None, /) from builtins.type
  |      Returns a new dict with keys from iterable and values equal to value.
  |
  |get(...)
  |      D.get(k[,d]) -> D if k in D, else d.d defaults to None.
  |
  |items(...)
  |      D.items() -> a set-like object providing a view on D's items
  |
  |keys(...)
  |      D.keys() -> a set-like object providing a view on D's keys
  |
  |pop(...)
  |      D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
  |      If key is not found, d is returned if given, otherwise KeyError is raised
  |
  |popitem(...)
  |      D.popitem() -> (k, v), remove and return some (key, value) pair as a
  |      2-tuple; but raise KeyError if D is empty.
  |
  |setdefault(...)
  |      D.setdefault(k[,d]) -> D.get(k,d), also set D=d if k not in D
  |
  |update(...)
  |      D.update(**F) -> None.Update D from dict/iterable E and F.
  |      If E is present and has a .keys() method, then does:for k in E: D = E
  |      If E is present and lacks a .keys() method, then does:for k, v in E: D = v
  |      In either case, this is followed by: for k in F:D = F
  |
  |values(...)
  |      D.values() -> an object providing a view on D's values
  |
  |----------------------------------------------------------------------
  |Data and other attributes defined here:
  |
  |__hash__ = None
  >>>
  >>> dict3 = dict((('F',70),('i',105),('s',115),('h',104),('c',67)))
  >>> dict3
  {'F': 70, 'i': 105, 's': 115, 'h': 104, 'c': 67}
  >>>
  >>> dict4 = dict(小甲鱼='编程改变世界',JM='加强各方面知识')
  >>> dict4
  {'小甲鱼': '编程改变世界', 'JM': '加强各方面知识'}
  >>>
  >>> dict4['JM'] = '学习编程'
  >>> dict4
  {'小甲鱼': '编程改变世界', 'JM': '学习编程'}
  >>>
  >>> dict4['小明'] = '网络安全'
  >>> dict4
  {'小甲鱼': '编程改变世界', 'JM': '学习编程', '小明': '网络安全'}
  >>>
  >>> dict1.fromkeys((1,2,3))
  {1: None, 2: None, 3: None}
  >>> dict1.fromkeys((1,2,3),'Number')
  {1: 'Number', 2: 'Number', 3: 'Number'}
  >>>
  >>> dict1.fromkeys((1,2,3),('Number','two','three'))
  {1: ('Number', 'two', 'three'), 2: ('Number', 'two', 'three'), 3: ('Number', 'two', 'three')}
  >>> dict1 =dict1.fromkeys(range(32),'赞')
  >>> dict1
  {0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞', 5: '赞', 6: '赞', 7: '赞', 8: '赞', 9: '赞', 10: '赞', 11: '赞', 12: '赞', 13: '赞', 14: '赞', 15: '赞', 16: '赞', 17: '赞', 18: '赞', 19: '赞', 20: '赞', 21: '赞', 22: '赞', 23: '赞', 24: '赞', 25: '赞', 26: '赞', 27: '赞', 28: '赞', 29: '赞', 30: '赞', 31: '赞'}
  >>> for eachKey in dict1.keys():
  print(eachKey)
  0
  1
  2
  3
  4
  5
  6
  7
  8
  9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  >>> for eachValue in dict1.values():
  print(eachValue)
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  赞
  >>>
  >>> for eachItem in dict1.items():
  print(eachItem)
  (0, '赞')
  (1, '赞')
  (2, '赞')
  (3, '赞')
  (4, '赞')
  (5, '赞')
  (6, '赞')
  (7, '赞')
  (8, '赞')
  (9, '赞')
  (10, '赞')
  (11, '赞')
  (12, '赞')
  (13, '赞')
  (14, '赞')
  (15, '赞')
  (16, '赞')
  (17, '赞')
  (18, '赞')
  (19, '赞')
  (20, '赞')
  (21, '赞')
  (22, '赞')
  (23, '赞')
  (24, '赞')
  (25, '赞')
  (26, '赞')
  (27, '赞')
  (28, '赞')
  (29, '赞')
  (30, '赞')
  (31, '赞')
  >>>
  >>> print(dict1)
  赞
  >>> print(dict1)
  Traceback (most recent call last):
  File "<pyshell#54>", line 1, in <module>
  print(dict1)
  KeyError: 32
  >>>
  >>> dict1.get(32)
  >>> print(dict1.get(32))
  None
  >>>
  >>> dict1.get(32,'没有')
  '没有'
  >>> dict1.get(31,'没有')
  '赞'
  >>>
  >>> 31 in dict1
  True
  >>> 32 in dict1
  False
  >>>
  >>> dict1
  {0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞', 5: '赞', 6: '赞', 7: '赞', 8: '赞', 9: '赞', 10: '赞', 11: '赞', 12: '赞', 13: '赞', 14: '赞', 15: '赞', 16: '赞', 17: '赞', 18: '赞', 19: '赞', 20: '赞', 21: '赞', 22: '赞', 23: '赞', 24: '赞', 25: '赞', 26: '赞', 27: '赞', 28: '赞', 29: '赞', 30: '赞', 31: '赞'}
  >>> dict1.clear()
  >>> dict1
  {}
  >>> dict1 = {}
  >>> a = {'姓名':'小甲鱼'}
  >>> b = a
  >>> b
  {'姓名': '小甲鱼'}
  >>> b
  {'姓名': '小甲鱼'}
  >>> a = {}
  >>> a
  {}
  >>> b
  {'姓名': '小甲鱼'}
  >>> a = b
  >>> a
  {'姓名': '小甲鱼'}
  >>> b
  {'姓名': '小甲鱼'}
  >>> a.clear()
  >>> a
  {}
  >>> b
  {}
  >>> dir(dict)
  ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
  >>>
  >>> a = {1:'one',2:'two',3:'three'}
  >>> b = a.copy()
  >>> c = a
  >>> c
  {1: 'one', 2: 'two', 3: 'three'}
  >>> a
  {1: 'one', 2: 'two', 3: 'three'}
  >>> b
  {1: 'one', 2: 'two', 3: 'three'}

  >>>>  48459920

  >>>>  48463736

  >>>>  48459920
  >>> c = 'four'
  >>> c
  {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
  >>> a
  {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
  >>> b
  {1: 'one', 2: 'two', 3: 'three'}
  >>>
  >>> a.pop(2)
  'two'
  >>> a
  {1: 'one', 3: 'three', 4: 'four'}
  >>> a.popitem()
  (4, 'four')
  >>>
  >>> a
  {1: 'one', 3: 'three'}
  >>> a.setdefault('小白')
  >>> a
  {1: 'one', 3: 'three', '小白': None}
  >>> a.setdefault(5,'five')
  'five'
  >>> a
  {1: 'one', 3: 'three', '小白': None, 5: 'five'}
  >>>
  >>> b = {'小白':'狗'}
  >>> a.update(b)
  >>> a
  {1: 'one', 3: 'three', '小白': '狗', 5: 'five'}
  >>>
页: [1]
查看完整版本: 7.Python入门到精通