I want to generate the fibonacci function N times based on user input. (I am thinking this as a while loop or an if statement like 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.
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
EDIT: In order to save time to find results of multiple Y
s, you can keep statistics in a dictionary like so:
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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.