7.Python入門到精通

函數:遞歸是神馬shell

遞歸求階乘編程


寫一個求階乘的函數安全

正整數階乘指從1乘以2乘以3乘以4一直乘到所要求的數。網絡

例如所給的數是5,則階乘式是1×2×3×4×5,獲得的積是120,因此120就是4的階乘。app

def factorial(n):ssh

    result = nide

    for i in range(1,n):函數

        result *= i學習


    return resultui


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[brand.index('魚C工做室')])

魚C工做室的口號是: 讓編程改變世界

>>> 

建立和訪問字典

>>> dict1 = {'李寧':'一切皆有可能' , '耐克': 'Just do it', '阿迪達斯' :'Impossible is nothing', '魚C工做室':'讓編程改變世界'}

>>> print('魚C工做室的口號是:',dict1['魚C工做室'])

魚C工做室的口號是: 讓編程改變世界

>>> 

>>> dict2 = {1:'one',2:'two',3:'three'}

>>> dict2[2]

'two'

>>> 

>>> help(dict)

Help on class dict in module builtins:


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[k] = 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[key].

 |  

 |  __eq__(self, value, /)

 |      Return self==value.

 |  

 |  __ge__(self, value, /)

 |      Return self>=value.

 |  

 |  __getattribute__(self, name, /)

 |      Return getattr(self, name).

 |  

 |  __getitem__(...)

 |      x.__getitem__(y) <==> x[y]

 |  

 |  __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[key] to value.

 |  

 |  __sizeof__(...)

 |      D.__sizeof__() -> size of D in memory, in bytes

 |  

 |  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[k] 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[k]=d if k not in D

 |  

 |  update(...)

 |      D.update([E, ]**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[k] = E[k]

 |      If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v

 |      In either case, this is followed by: for k in F:  D[k] = F[k]

 |  

 |  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[31])

>>> print(dict1[32])

Traceback (most recent call last):

  File "<pyshell#54>", line 1, in <module>

    print(dict1[32])

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'}

>>> id(a)

48459920

>>> id(b)

48463736

>>> id(c)

48459920

>>> c[4] = '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'}

>>> 

相關文章
相關標籤/搜索