【问题标题】:Returning binomal as a tuple将二项式作为元组返回
【发布时间】:2010-01-31 21:37:30
【问题描述】:

我想将我的函数 binomal_aux 的结果保存到一个元组,但我不知道如何,这是我现在拥有的代码。

def binomal (n):    
    i=0
    for i in range(n):
        binomal_aux(n,i) #want this to be in a tuple so, binomal (2) = (1,2,1)
    return

def binomal_aux (n,k):
    if (k==0):
        return 1
    elif (n==k):
        return 1
    else:
        return (binomal_aux(n-1,k) + binomal_aux(n-1,k-1))

【问题讨论】:

  • 注意:拼写是二项式,不是二项式。
  • 您不需要在 for 循环之前声明/定义i,也不需要在函数末尾添加return
  • 好的,再来一张。您的 if/elif 可以简单地替换为:if k==0 or k==n:,甚至if k in (0, n):

标签: python recursion tuples


【解决方案1】:

在您的 binomal 函数中,只需创建您想要返回的元组。

def binomal(n):
  return tuple(binomal_aux(n, i) for i in range(n+1))

还要注意正确的拼写是binomial

【讨论】:

    【解决方案2】:
    def binomal (n):    
        return tuple(binomal_aux(n,i) for i in range(n+1))
    

    【讨论】:

    • 更改了返回元组(binomal_aux(n,i) for i in range(n+1)) 并且工作得很好,非常感谢!
    【解决方案3】:

    另一种方式:

    def binomal(n): 
        from itertools import combinations
        return tuple(len(list(combinations(range(n), r=t))) for t in range(n + 1))
    

    【讨论】:

      猜你喜欢
      • 2016-07-15
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-25
      • 1970-01-01
      相关资源
      最近更新 更多