简体   繁体   English

如何在 python 中生成 N 次 function 并计算位数?

[英]How to generate function n times in python and count digits?

I want to generate the fibonacci function N times based on user input.我想根据用户输入生成斐波那契 function N 次。 (I am thinking this as a while loop or an if statement like if N in range). (我认为这是一个 while 循环或 if 语句,如 if N in range)。 Also there is second user input defined as Y. Y represents the amount of digits of the repeated function and I want a count of how many numbers generated have Y amount of digits.还有第二个用户输入定义为 Y。Y 表示重复的 function 的位数,我想计算生成的数字有多少个 Y 位数。

Below is my non complete code:以下是我的不完整代码:

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))

Thanks in advance提前致谢

Try this (read comments in the code below):试试这个(阅读下面代码中的注释):

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))

The algorithm for calculating Fibonacci numbers comes from Wolfram Alpha计算斐波那契数的算法来自Wolfram Alpha

EDIT: In order to save time to find results of multiple Y s, you can keep statistics in a dictionary like so:编辑:为了节省查找多个Y的结果的时间,您可以将统计信息保存在字典中,如下所示:

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))

This will yield an output like:这将产生一个 output 像:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM