美文网首页
python基础练习

python基础练习

作者: warManHy | 来源:发表于2019-10-25 00:17 被阅读0次
    • 兔子问题
      内容:1个兔子,1个月后变3个,n月有几个
      公式 3^(n-i)
    def rabbit_sum(m):
        sum = 0
        for i in range(1, m+1):
             sum += 3**(m-i)
        return sum
    
    • 青蛙上台阶
      内容:当n = 1, 只有1中跳法;当n = 2时,有两种跳法;当n = 3 时,有3种跳法;当n = 4时,有5种跳法;当n = 5时,有8种跳法
    def frog(n):
         if n == 1:
              return 1
         elif n == 2:
               return 2
         else:
               return frog(n-2) + frog(n-1)
    
    

    回溯算法:

    cout = 0
    def dfs(cout, target):
          global cout
          if target <= 2:
               cout += target
                return
           dfs(cout, target-1)
           dfs(cout, target-2)
    
    dfs(cout, 4)
    
    • 三门问题
      内容:概率问题,三个门后有一个有car,你指定开一个门,主持人会吧一个有goat的门打开,求你要不要换开剩下的门
    from random import choice
    def switch():
         doors = ['car', 'goat', 'goat']
         choose = choice(doors)
         doors.remove(choose)
         doors.remove('goat')
         if doors == ['car']:
             return 'win'
         else:
              return 'failed'
    
    def stay():
         doors = ['car', 'goat', 'goat']
         choose = choice(doors)
         if choose == 'car':
              return 'win'
         else:
              retuen 'failed'
    
    if __name__ == "__main__":
         total = 1000
         switch_sum, stay_num, win_switch, win_stay = 0, 0, 0, 0
         for i in range(total):
              choose = choice([1, 2])
              #1 switch
              if choose == 1:
                   switch_num += 1
                   if switch() == 'win':
                       win_switch += 1
              else:
                   stay_num += 1
                   if stay() == 'win':
                       win_stay += 1
          print float(stay_win)/stay_num, float(win_switch)/switch_num
    

    相关文章

      网友评论

          本文标题:python基础练习

          本文链接:https://www.haomeiwen.com/subject/nedjvctx.html