【问题标题】:How to generate function n times in python and count digits?如何在python中生成函数n次并计算数字?
【发布时间】:2019-11-16 08:27:46
【问题描述】:

我想根据用户输入生成斐波那契函数 N 次。 (我认为这是一个 while 循环或 if 语句,如 if N in range)。 还有第二个用户输入定义为 Y。Y 表示重复函数的位数,我想计算生成的数字有多少位数是 Y。

以下是我的不完整代码:

N = int(input("Enter N: "))
Y = int(input("Enter Y: "))


def fibonacci(n): 
   if n <= 1:
     return n
   else:
     return fibonacci(n-2) + fibonacci(n-1)

nterms = 10

# check if the number of terms is valid
if nterms <= 0:
   print("Please enter a positive integer")
else:
   print("Fibonacci sequence:")
   for i in range(nterms):
       print(fibonacci(i))

提前致谢

【问题讨论】:

  • 请举例说明您计划创建的功能的预期输入和输出。
  • @manavhs13 如果答案对您没有帮助,请发表评论,如果解决了您的问题,请将答案标记为已解决。
  • 在你的例子中你从不使用N

标签: python function fibonacci


【解决方案1】:

试试这个(阅读下面代码中的 cmets):

from math import sqrt

def fibonacci(n):
    return int(((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))) # WA algorithm

# Handle N from user input
while True:
    N = int(input("Enter N: "))
    Y = int(input("Enter Y: "))
    if N < 1 or Y < 1:
        print("Plese enter a positive integers for N and Y")
    else:
        break

count = 0 # Counter of the instances of fibonacci numbers containing Y digits
for n in range(N):
    fib = fibonacci(n) # Calls fibonacci
    print(fib) # Print Fibonacci number
    if len(str(fib)) == Y: # Number of digits in the Fibonacci number
        count += 1 # Count up if number of digits = Y

print("\nFibonacci numbers with {} digits occured {} times" .format(Y, count))

计算斐波那契数的算法来自Wolfram Alpha

编辑: 为了节省查找多个Ys 的结果的时间,您可以将统计信息保存在字典中,如下所示:

from math import sqrt

# Handle N from user input
while True:
    N = int(input("Enter N: "))
    if N < 1:
        print("Plese enter a positive integers for N and Y")
    else:
        break

size = {} # Dictionary with number of occurences of lengths of Fibonacci numbers
count = 0 # Counter of the instances of fibonacci numbers containing Y digits
for n in range(N):
    fib = int(((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))) # WA algorithm
    print(fib) # Print Fibonacci number
    s = str(len(str(fib)))
    if s not in size:
        size[s] = 1
    else:
        size[s] += 1

print()
for key, val in size.items():
    print("{}\toccured\t{} times" .format(key, val))

这将产生如下输出:

Enter N: 13
0
1
1
2
3
5
8
13
21
34
55
89
144

1   occured 7 times
2   occured 5 times
3   occured 1 times

【讨论】:

  • 感谢代码非常有用。但是,我需要生成序列 N 次。 N 不是项的数量,而是生成序列的次数。
  • 哦,我明白了,现在请检查我的答案,它已被编辑。
  • 谢谢,但是这个没有打印N次序列。此外,还有一个提示用户输入 n:所需术语的数量
  • 在您的示例中,您根据循环运行术语的数量。令我惊讶的是,你从来没有使用N,因为我对这个问题发表了评论,但是你使用nterms,然后你运行fibonacci(0), fibonacci(1), ..., fibonacci(nterms),也就是说,我想在N元素的循环中,术语的数量应该是n .无论如何,我更新了代码以打印序列。
  • 不用担心。很高兴我能帮上忙。
猜你喜欢
  • 2020-03-05
  • 1970-01-01
  • 2019-02-06
  • 1970-01-01
  • 2021-09-15
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 2017-04-30
相关资源
最近更新 更多