【问题标题】:i can not seem to get it exactly, i am getting the factorials but cant seem to find a way to put in the combination formula我似乎无法准确地得到它,我得到了阶乘,但似乎无法找到一种方法来输入组合公式
【发布时间】:2019-11-02 09:19:05
【问题描述】:

我已经编写了代码,但无法输入组合公式,我对此很陌生,并使用这些额外的练习来帮助数学,你能帮助改进什么或如何完成吗?

n=(10)
fact=3
while(n>0):
    fact=fact*n
    n=n-1
print("Factorial of the number is: ")
print(fact)


n=int(6)
fact=1
while(n>0):
    fact=fact*n
    n=n-1
print("Factorial of the number is: ")
print(fact)

https://i.stack.imgur.com/SGEDb.png

【问题讨论】:

  • 您的代码似乎可以工作,只是它没有正确缩进。我假设这是剪切和粘贴,而不是您的原始代码的问题。 (我在你的问题中修复了它)。我不确定你在问什么——你只是想要改进它的建议吗?
  • 你检查过图片吗?我找到了一种获取阶乘的方法,但实际上并不是这样,但谢谢!
  • 如果你在谈论公式,那是为了弄清楚如何从总共 n 个项目中选择 k 个项目(例如,从总共 9 个选项中制作一个有 4 个浇头的披萨) .我不确定你是在问数学还是 Python。您已经找到了一种正确找到阶乘的方法,尽管您最好将其定义为一个接受参数的函数(也许您还没有走到那一步,在这种情况下,您的代码现在还可以) .

标签: python python-2.7 function methods


【解决方案1】:
def fact_(n):
    fact = 1
    while (n > 0):
        fact = fact * n
        n = n - 1
    return fact

#mario
result_m = fact_(10)/(fact_(3)*fact_(7))
print(int(result_m))

#luigi
result_l = fact_(9)/(fact_(4)*fact_(5))
print(int(result_l))

输出:

120
126

注意:在 mario 的公式中:n = 10 k = 3,对于 luigi:n = 9 k = 4

【讨论】:

    【解决方案2】:

    取自https://www.geeksforgeeks.org/factorial-in-python/

        n = 23
        fact = 1
    
        for i in range(1,n+1): 
            fact = fact * i 
    
        print ("The factorial of 23 is : ",end="") 
        print (fact) 
    

    或者使用数学模块:

    import math 
    print (math.factorial(23)) 
    

    【讨论】:

    • 谢谢,但如果我没记错的话,这是python 3x nd up,我用的是2.7
    猜你喜欢
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 2020-03-31
    • 2017-08-11
    • 1970-01-01
    • 2020-03-04
    • 2017-07-11
    相关资源
    最近更新 更多