gpt4 book ai didi

python - 如何显示 0-N 范围内的所有数字 "super numbers"

转载 作者:太空狗 更新时间:2023-10-29 18:16:20 25 4
gpt4 key购买 nike

  1. 程序要求用户输入一个数字N

  2. 该程序应该显示 0-N 范围内的所有“ super 数字”。

    Super number: is a number such that the sum of the factorials of its digits equals the number.

    例子:

    • 12 != 1! + 2! = 1 + 2 = 3(不是 super )
    • 145 = 1! + 4! + 5! = 1 + 24 + 120( super )
  3. 我似乎被卡住的部分是当程序显示 0-N 范围内的所有数字时,这些数字是“ super 数字”。我已经得出结论,我需要一个循环来解决这个问题,但我不知道该怎么做。因此,例如,该程序应该读取 0-50 之间的所有数字,并且只要数字超大,它就会显示出来。所以它只显示 1 和 2,因为它们被认为是 super

    enter integer: 50
    2 is super
    1 is super
  4. 我写了两个函数;第一个是常规阶乘程序,第二个是对数字的阶乘求和的程序:

    number = int(input ("enter integer: "))

    def factorial (n):
    result = 1
    i = n * (n-1)
    while n >= 1:
    result = result * n
    n = n-1
    return result

    #print(factorial(number))

    def breakdown (n):
    breakdown_num = 0
    remainder = 0

    if n < 10:
    breakdown_num += factorial(n)
    return breakdown_num
    else:
    while n > 10:
    digit = n % 10
    remainder = n // 10
    breakdown_num += factorial(digit)
    #print (str(digit))
    #print(str(breakdown_num))
    n = remainder

    if n < 10 :
    #print (str(remainder))
    breakdown_num += factorial(remainder)
    #print (str(breakdown_num))

    return breakdown_num

    #print(breakdown(number))
    if (breakdown(number)) == number:
    print(str(number)+ " is super")

最佳答案

现有的答案已经显示了如何进行最终循环以将您的函数联系在一起。或者,您也可以使用更多内置函数和库,例如 summath.factorial,为了获取数字,您只需迭代数字的字符串表示。

这样,问题可以在一行代码中解决(尽管将 is-super 检查移动到一个单独的函数可能会更好)。

def issuper(n):
return sum(math.factorial(int(d)) for d in str(n)) == n

N = 1000
res = [n for n in range(1, N+1) if issuper(n)]
# [1, 2, 145]

关于python - 如何显示 0-N 范围内的所有数字 "super numbers",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51169598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com