How to generate function n times in python and count digits? - python

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 Ys, 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

Related

How to debug my Python program, which sums positive numbers based on their evenness

I'm trying to write program that asking the user for positive numbers, if it is an odd number, the software sums all of the odd digits in the number, same for even numbers. After that the software asking non stop for numbers and does the same thing as before, till the user type 0/negative number.
After that the software should print the number with the maximal sum. Sometimes it works and sometimes not.
Code:
def sum_Digits(n):
sum = 0
if n % 2 == 0: #For even numbers
while n>0:
if (n%10)%2 == 0:
sum += n%10
n = n//10
else:
n = n//10
print("sum: " , sum)
return sum
elif n % 2 != 0 : #For odd numbers
while n>0:
if (n%10)%2 != 0:
sum += n%10
n = n//10
else:
n = n//10
print("sum: " , sum)
return sum
def read_Numbers(N):
maX = 0
while N > 0: #while askNum Positive continue summing
suM = sum_Digits(N)
if suM > maX:
maX = N
N = int(input("Please eneter a Natural number: "))
if N <= 0:
return maX
def main():
num = int(input("Please enter a Natural number: ")) #asking the user to enter number
sum_Digits(num)
askNum = int(input("Please eneter a Natural number: "))
maxSum = read_Numbers(askNum)
print("Number with maximal sum: " , maxSum)
main()
Bug:
if user enter a negative number it will continue the loop and print the last entered number
because the program doesn't check for negative numbers
Fix:
I have added a condition if N <= 0:
return maX
this will return the last entered positive number
Bug:
sum_Digits(num)
I have removed this line because it is not needed
because we already call the function sum_Digits in the main function

Printing digits of an integer in order in Python

I want to print the digits of an integer in order, and I don't want to convert to string. I was trying to find the number of digits in given integer input and then divide the number to 10 ** (count-1), so for example 1234 becomes 1.234 and I can print out the "1". now when I want to move to second digit it gets confusing. Here is my code so far:
Note: Please consider that I can only work with integers and I am not allowed to use string and string operations.
def get_number():
while True:
try:
a = int(input("Enter a number: "))
return a
except:
print("\nInvalid input. Try again. ")
def digit_counter(a):
count=0
while a > 0:
count = count+1
a = a // 10
return count
def digit_printer(a, count):
while a != 0:
print (a // (10 ** (count-1)))
a = a // 10
a = get_number()
count = digit_counter(a)
digit_printer(a, count)
I want the output for an integer like 1234 as below:
1
2
3
4
Using modulo to collect the digits in reversed order and then print them out:
n = 1234
digits = []
while n > 0:
digits.append(n%10)
n //=10
for i in reversed(digits):
print(i)
Recursive tricks:
def rec(n):
if n > 0:
rec(n//10)
print(n%10)
rec(1234)
Finding the largest power of 10 needed, then going back down:
n = 1234
d = 1
while d * 10 <= n:
d *= 10
while d:
print(n // d % 10)
d //= 10

I want to compute the sum of first N even numbers based on the user input N using recursive function

I want to compute the sum of first N even numbers based on the user input N using recursive function.
For example:
Sample Input N: 5
Sample Output: 2 + 4 + 6 + 8 + 10 = 30
I did my code in 2 ways but both of them gave wrong outputs. I'm doing something wrong in the function part sorting number in the loop. So I need some help!
n = int(input("Enter a nmuber: "))
for i in range(1,n+1):
for d in range(0,i+1,2):
print(d)
n = int(input("Enter a number: "))
def get_even(n):
for i in range(1,n+1,2):
d += i
print(d)
You can use the following.
Code
def sum_even(n):
# Base case
if n <= 1:
return 0
if n % 2:
# odd n
return sum_even(n - 1) # sum from next smaller even
else:
# even n
return n + sum_even(n - 2) # current plus sum from next smaller even
# Usage
n = int(input('Enter a nmuber: '))
print(sum_even(n))

Enter n different positive numbers. Calculate the average value of all prime numbers among them. [Python]

I need to do as the title suggests however I have ran into a problem. This is my code so far:
#Input
n = int(input('Enter n: '))
#Prime = 0
p = []
#Loopidty
for i in range(n):
#Ask user to input x
x = int(input('Enter a Number: '))
#Check if prime
if x < 2:
print('The number is not prime.')
else:
for n in range(2, x - 1):
if x % n == 0:
print('The number is not prime.')
break
else:
print('The number is prime.')
p.append(x)
#Answer
Answer = sum(p) / n
print('The answer is: ', Answer)
The issues is when I add the prime numbers to the list it only adds the first number and stops there, how do I combat this?
Many thanks
It's a good idea to break your code into smaller parts. We can create a function to check if a number is prime or not and check that it is correct. After that just add the rest of the code.
import math
def is_prime(x):
"""Check that a number `x``is prime"""
# You only need to go up to sqrt(x)
for n in range(2, int(math.sqrt(x) + 1)):
if x % n == 0:
return False
return True
# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
sum = 0.0
num_entries = 0 # Number of prime numbers entered by the user
n = int(input('Enter n: '))
for i in range(n):
x = int(input('Enter a Number: '))
if is_prime(x):
sum += x
num_entries += 1
if num_entries == 0:
print("You didn't enter any prime number")
else:
print("The average of the entered prime numbers is ", sum / num_entries)

Python - print only the highest number of collatz

def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return result
#4. zolang n ongelijk is aan 0, niet stoppen.
n = input("invoer: ")
while n != 1:
n = collatz(int(n))
I've got this code, but I only want to print the highest number in place of the whole queue of collatz sequence.
How could I do that?
Your code can be refactored to print the maximum number from the Collatz Sequence as follows:
def collatz(number):
if number % 2 == 0:
return number // 2
else:
return (3 * number) + 1
# Refactored this part because Collatz Conjecture is defined for positive
# numbers only
try:
n = int(input('invoer: '))
if n <= 0:
raise ValueError
except ValueError:
print('Enter a valid positive integer')
# Set a variable to store maximum value
max_num = 0
while n != 1:
# If the current number is bigger than existing maximum number, update it
max_num = max(n, max_num)
n = collatz(int(n))
print('Maximum number is {}'.format(max_num))
Note that I have updated some of your original code so that only positive integer is a valid input. This is because Collatz Conjecture states that the sequence starts with a positive integer.
Also, in the if-else construct, you do not need to write the condition for odd numbers explicitly because if the integer is not even then it must be odd.
Just have a max variable which you update with n, if n is larger than that variable's value:
def collatz(number):
if number % 2 == 0:
return number // 2
elif number % 2 == 1:
return 3 * number + 1
n = input('invoer: ')
m = 0
while n != 1:
if n > m: m = n
n = collatz(int(n))
print('the max was:', m)
With the input 5 gives 16, since 16 is the max of [5, 16, 8, 4, 2, 1].

Categories