I am trying to write a program which will ask the user to enter a number. I then need to validate it is in the fib sequence
Code:
# asking the user to input number
number = int(input("Enter a number: "))
# creating empty list to be filled
sequence = [0, 1]
x = -2
y = -1
# append items to list
for i in range(number):
x+=2
y+=2
# this code will be executed 'length' times
sequence.append(x+y)
# This should be somewhere in the loop:
if number in sequence:
print("The number is in the Fibonacci sequence")
else:
print("The number is not in the Fibonacci sequence")
Expected Output:
Fibonacci Sequence = 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ….
Enter a number: 5
>>> The number is in the Fibonacci sequence
You will need to do some iteration (or recursion) in order to find the sequence of Fibonacci numbers. Here is one way to do it with a while loop:
number = int(input("Enter a number: "))
sequence = [0, 1]
i= 0
while True:
new_item = sequence[i] + sequence[i+1]
if new_item == number or number in [0,1]:
print("The number is in the Fibonacci sequence")
break
elif new_item > number:
print("The number is not in the Fibonacci sequence")
break
sequence.append(new_item)
i+=1
Notice that you will iterate until the new item in your Fibonacci sequence is greater than or equal to the number the user input.
Sequence doesn't have a position x or y. The line where you append to the sequence should read sequence.append(x+y)
Maybe I'm thinking about this too simply but according to your question, it sounds like a Fibonacci sequence is provided to you. If that is the case you can just use in, i.e.
x = 5 # this will be user's input
fib = [0,1,1,2,3,5,8,13,21,34]
if x in fib:
print('Number is in sequence')
else:
print('Number is not in sequence')
If you have to generate your own Fibonacci sequence then you may want to consider using recursion.
alternativly you could just calculate the fibonachi numebers
def fibo(n):
p = (1+5**.5)/2
q = (1-5**.5)/2
return int(1/5**.5*(p**n-q**n))
def fiba(num):
count = 0
while fibo(count) <= num:
if fibo(count) == num:
return "YES!"
count += 1
return "NO!"
One approach would be to factor out the fibonacci into a generator and then iterator over that generator until >= number, e.g.:
def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a+b
In []
number = 5 # int(input("Enter a number: "))
for f in fib():
if f >= number:
break
if number == f:
print("The number is in the Fibonacci sequence")
else:
print("The number is not in the Fibonacci sequence")
Out[]:
The number is in the Fibonacci sequence
You could use itertools.takewhile to replace the for loop, e.g.:
import itertools as it
from collections import deque
f = deque(it.takewhile(lambda n: n <= number, fib()), maxlen=1).pop()
...
Related
I know how to do this with a while loop and know how to use a for-loop in other languages like Java and C++. I want to use a for-loop in place of where I have written the while loop asking for the user input.
# You are required to use for-loop to solve this and round your answer to 2 decimal places. Write
# a program that takes n ∈ N (i.e., any positive integer including zero) from the user and use the
# input value to compute the sum of the following series:
n = -1
while n < 0:
n = int(input("Enter a value to compute: "))
# keep asking for user input until a whole number (0, 1, 2, 3, etc...) has been entered
k = 0
sum = 0
# To hold the sum of the fraction to be displayed
lastTerm = 0
# This variable represents the last term to be added to the fraction sum before the while loop below terminates
if n == 0:
sum = 0
elif n == 1:
sum = 1
else:
while lastTerm != 1 / n:
lastTerm = (n - k) / (k + 1)
sum = sum + (n - k) / (k + 1)
k += 1
print("{:.2f}".format(sum))
# Print the sum to two decimal places
One option is to catch the exception which is thrown when you cannot convert the input to an int, i.e.
while(True):
try:
# read input and try and covert to integer
n = int(input("Enter a value to compute: "))
# if we get here we got an int but it may be negative
if n < 0:
raise ValueError
# if we get here we have a non-negative integer so exit loop
break
# catch any error thrown by int()
except ValueError:
print("Entered value was not a postive whole number")
Alternative, slightly cleaner but I'm not 100% sure isdigit() will cover all cases
while(true):
n = input("Enter a value to compute: ")
if value.isdigit():
break
else:
print("Entered value was not a postive whole number")
How about this? It uses the for loop and sums all the values in the list.
x=[1,2,3,4] #== test list to keep the for loop going
sum_list=[]
for i in x:
j=float(input("Enter a number: "))
if not j.is_integer() or j<0:
sum_list.append(j)
x.append(1) #=== Add element in list to keep the cyclone going
else:
break
sums=sum(sum_list)
print("The Sum of all the numbers is: ",round(sums,2))
Use this to check for whole numbers -
if num < 0:
# Not a whole number
elif num >= 0:
# A whole number
for a for loop:
import itertools
for _ in itertools.repeat([]): # An infinite for loop
num = input('Enter number : ')
if num < 0:
# Not a whole number
pass # This will ask again
elif num >= 0:
# A whole number
break # break from for loop to continue the program
Easier Way -
mylist = [1]
for i in mylist : # infinite loop
num = int(input('Enter number : '))
if num < 0:
mylist.append(1)
pass # This will ask again
elif num >= 0:
# A whole number
break
This question already has answers here:
Choose largest odd number python
(28 answers)
Closed 4 months ago.
Hi I am new to programming and I made a program for a finger exercise in the book "Introduction to computation and programming using python"
here's the finger exercise : Write a program that examines three variables—x, y, and z—
and prints the largest odd number among them. If none of them are odd, it
should print a message to that effect.
I made this,
l = []
x = int(input("Enter a number for x: "))
y = int(input("Enter a number for y: "))
z = int(input("Enter a number for z: "))
l.append(x)
l.append(y)
l.append(z)
def testodd(n):
return n%2 != 0
def maxodd (l):
oddlist = []
for i in l:
if testodd(i):
oddlist.append(i)
else:
continue
return max(oddlist)
print(maxodd(l))
Program sometimes work properly and sometimes not for example I gave x=231 y=23 and z=678 it says "none of them are odd" what's the problem about this program ?
First we create a list that will contain all the numbers, then we sort that list in descending order (reverse=True) and then we look if there is any odd number. If we don't find any odd number in the list we print the message:
numbers = []
for _ in range(3): # Iterate 3 times
numbers.append(int(input("Enter a number:"))) # Append 1 number each time
numbers.sort(reverse=True) # Sort the numbers in descending order
for n in numbers: # Iterate over the numbers
if n % 2 != 0: # If the number is odd we have found the maximum odd value
print(n) # Print the value
break # Finish the loop
else: # An else block in a for loop will execute if no break was found
print("none of them are odd") # Print the message
A more advanced way to retrieve the numbers would be:
numbers = sorted((int(input("Enter a number:")) for _ in range(3)), reverse=True)
that would replace the first 4 lines.
This is simpler if you put only the odd numbers into a list.
x = int(input("Enter a number for x: "))
y = int(input("Enter a number for y: "))
z = int(input("Enter a number for z: "))
odd_numbers = [value for value in (x,y,z) if value%2]
if odd_numbers:
print("The greatest odd number is", max(odd_numbers))
else:
print("None of the numbers is odd.")
The program finds the maximal number and checks if it's odd.
To find the maximal odd number, you can use list comprehension:
Put the numbers to check at a list numbers = [x, y, z]
Loop over the numbers t for t in numbers, and filter in those who are odd if t % 2 != 0.
Find the maximal among them (#2): max([t for t in numbers if t % 2 != 0])
x = int(input("Enter a number for x: "))
y = int(input("Enter a number for y: "))
z = int(input("Enter a number for z: "))
# Put numbers in a list
numbers = [x, y, z]
# Filter the odd numbers, and find the max
print(max([t for t in numbers if t % 2 != 0]))
You may just append all numbers entered into a list, sort all odds into another list and get the maximum value:
numbs = []
x = int(input("Enter a number for x: "))
numbs.append(x)
y = int(input("Enter a number for y: "))
numbs.append(y)
z = int(input("Enter a number for z: "))
numbs.append(z)
odds = [x for x in numbs if x%2==1]
if odds == []:
print('No odd number was entered')
else:
print(max(odds))
I'm new to this so I apologize for any of my mistakes.
This is my code:
def main():
global user_input
user_input = [0,1,2]
final = fibonacci(user_input)
return final
def append_fibonacci(integer_list):
new_list = []
while integer_list[1] < 40:
integer_list[0], integer_list[1] = integer_list[1], integer_list[0]+integer_list[1]
new_list.append(integer_list[0])
return(new_list)
def fibonacci(max):
final = append_fibonacci(max)
print("Enter a non-negative integer >")
print("The Fibonacci series starts with:",final)
My error is the outcome only prints:
The Fibonacci series starts with: [1, 1, 2, 3, 5, 8, 13, 21, 34]
When it's suppose to print whatever other inputs (such as inputs: 8 / outputs: The Fibonacci series starts with: [1, 1, 2, 3, 5, 8] , inputs: 0 / outputs: The Fibonacci series starts with: [], inputs: 1 / Output: The Fibonacci series starts with: [1, 1] & inputs: six / Output: six is not a non-negative integer ).
I'm unsure if and where to use the (if, else statements) and if to check if it (.isdigit) or (isinstance, str).
Can someone help me or give me the answer? Thank you for your time in assisting me.
This is the question below.
The main function must input a string. If the string does not represent a non-negative integer, then it should print a warning message. If it does represent a non-negative integer, then it should call the fibonacci function to create the list of Fibonacci numbers that are less than or equal to the non-negative integer and output this list. The fibonacci function should call the append_fibonacci function multiple times to create the Fibonacci list.
If you use a function from an imported module in your function, you must import that module inside your function.
The first problem is with this statement while integer_list[1] < 40. Independent of the input you pass to the function it will output Fibonacci numbers less than 40. Second problem is the user_input list you pass through functions which is completely unnecessary. You just need to pass max number and your program will output Fibonacci numbers less than or equal to max. Third problem is you do not have a mechanism to check whether the input is a valid non-negative integer.
Here is the code:
def main():
_max = ""
while not _max.isnumeric():
_max = input("Enter a non-negative integer >")
_max = int(_max)
final = append_fibonacci(max)
print("The Fibonacci series starts with:",final)
return final
def append_fibonacci(_max):
if _max==0:
return []
fibonacci = []
x=1
y=1
while y <= _max:
x, y = y, x+y
fibonaccis.append(x)
return fibonacci
main()
Get input from users, you should use input() method. In main() function, user_input = input("Enter a non-negative integer >") will work. Also avoid using global variables. You don't need input variable as a global variable in this code, simply delete that line.
Use int() to check if the input is integer or not. You can handle the error message using try...except. Use if...else to check if the number negative or not.
Your code should look something like this:
def main():
user_input = input("Enter a non-negative integer > ")
try:
if int(user_input) < 0:
print('{} is not a non-negative integer'.format(user_input))
else:
final = fibonacci(int(user_input))
print("The Fibonacci series integer_lists with: ", final)
except ValueError:
print('"{}" is not a non-negative integer'.format(user_input))
def append_fibonacci(integer_list):
if len(integer_list) < 2:
integer_list.append(1)
else:
integer_list.append(integer_list[-1] + integer_list[-2])
return integer_list
def fibonacci(max):
integer_list = []
if max == 0:
return integer_list
else:
while len(integer_list) < 2 or integer_list[-1] + integer_list[-2] <= max:
integer_list = append_fibonacci(integer_list)
return integer_list
def main():
user_input = input("Enter a non-negative integer >")
try:
if int(user_input) < 0:
print('{} is not a non-negative integer'.format(user_input))
else:
final = fibonacci(int(user_input))
print("The Fibonacci series starts with:", final)
except ValueError:
print('{} is not a non-negative integer'.format(user_input))
def append_fibonacci(integer_list):
if len(integer_list) < 2:
integer_list.append(1)
else:
integer_list.append(integer_list[-1] + integer_list[-2])
return integer_list
def fibonacci(max):
integer_list = []
if max == 0:
return integer_list
else:
while len(integer_list) < 2 or integer_list[-1] + integer_list[-2] <= max:
integer_list = append_fibonacci(integer_list)
return integer_list
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
The program asks the user for a number N.
The program is supposed to displays all numbers in range 0-N that are "super numbers".
Super number: is a number such that the sum of the factorials of its
digits equals the number.
Examples:
12 != 1! + 2! = 1 + 2 = 3 (it's not super)
145 = 1! + 4! + 5! = 1 + 24 + 120 (is super)
The part I seem to be stuck at is when the program displays all numbers in range 0-N that are "super numbers". I have concluded I need a loop in order to solve this, but I do not know how to go about it. So, for example, the program is supposed to read all the numbers from 0-50 and whenever the number is super it displays it. So it only displays 1 and 2 since they are considered super
enter integer: 50
2 is super
1 is super
I have written two functions; the first is a regular factorial program, and the second is a program that sums the factorials of the digits:
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")
Existing answers already show how to do the final loop to tie your functions together. Alternatively, you can also make use of more builtin functions and libraries, like sum, or math.factorial, and for getting the digits, you can just iterate the characters in the number's string representation.
This way, the problem can be solved in a single line of code (though it might be better to move the is-super check to a separate function).
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]
First I would slightly change how main code is executed, by moving main parts to if __name__ == '__main__', which will execute after running this .py as main file:
if __name__ == '__main__':
number = int(input ("enter integer: "))
if (breakdown(number)) == number:
print(str(number)+ " is super")
After that it seems much clearer what you should do to loop over numbers, so instead of above it would be:
if __name__ == '__main__':
number = int(input ("enter integer: "))
for i in range(number+1):
if (breakdown(i)) == i:
print(str(i)+ " is super")
Example input and output:
enter integer: 500
1 is super
2 is super
145 is super
Small advice - you don't need to call str() in print() - int will be shown the same way anyway.
I haven't done much Python in a long time but I tried my own attempt at solving this problem which I think is more readable. For what it's worth, I'm assuming when you say "displays all numbers in range 0-N" it's an exclusive upper-bound, but it's easy to make it an inclusive upper-bound if I'm wrong.
import math
def digits(n):
return (int(d) for d in str(n))
def is_super(n):
return sum(math.factorial(d) for d in digits(n)) == n
def supers_in_range(n):
return (x for x in range(n) if is_super(x))
print(list(supers_in_range(150))) # [1, 2, 145]
I would create a lookup function that tells you the factorial of a single digit number. Reason being - for 888888 you would recompute the factorial of 8 6 times - looking them up in a dict is much faster.
Add a second function that checks if a number isSuper() and then print all that are super:
# Lookup table for single digit "strings" as well as digit - no need to use a recursing
# computation for every single digit all the time - just precompute them:
faks = {0:1}
for i in range(10):
faks.setdefault(i,faks.get(i-1,1)*i) # add the "integer" digit as key
faks.setdefault(str(i), faks [i]) # add the "string" key as well
def fakN(n):
"""Returns the faktorial of a single digit number"""
if n in faks:
return faks[n]
raise ValueError("Not a single digit number")
def isSuper(number):
"Checks if the sum of each digits faktorial is the same as the whole number"
return sum(fakN(n) for n in str(number)) == number
for k in range(1000):
if isSuper(k):
print(k)
Output:
1
2
145
Use range.
for i in range(number): # This iterates over [0, N)
if (breakdown(number)) == number:
print(str(number)+ " is super")
If you want to include number N as well, write as range(number + 1).
Not quite sure about what you are asking for. From the two functions you write, it seems you have solid knowledge about Python programming. But from your question, you don't even know how to write a simple loop.
By only answering your question, what you need in your main function is:
for i in range(0,number+1):
if (breakdown(i)) == i:
print(str(i)+ " is super")
import math
def get(n):
for i in range(n):
l1 = list(str(i))
v = 0
for j in l1:
v += math.factorial(int(j))
if v == i:
print(i)
This will print all the super numbers under n.
>>> get(400000)
1
2
145
40585
I dont know how efficient the code is but it does produce the desired result :
def facto():
minr=int(input('enter the minimum range :')) #asking minimum range
maxr=int(input('enter the range maximum range :')) #asking maximum range
i=minr
while i <= maxr :
l2=[]
k=str(i)
k=list(k) #if i=[1,4,5]
for n in k: #taking each element
fact=1
while int(n) > 0: #finding factorial of each element
n=int(n)
fact=fact*n
n=n-1
l2.append(fact) #keeping factorial of each element eg : [1,24,120]
total=sum(l2) # taking the sum of l2 list eg 1+24+120 = 145
if total==i: #checking if sum is equal to the present value of i.145=145
print(total) # if sum = present value of i than print the number
i=int(i)
i=i+1
facto()
input : minr =0 , maxr=99999
output :
1
2
145
40585