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
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
I am just starting with Python and I have a short question.
import sys
# Function creates a list [1,3,5..99]
def createlist():
list = []
for i in range(1, 100, 2):
list.append(i)
return(list)
# Function asks for an odd integer between 1..100
def numberinsert():
n = int(input("Please enter an odd number between 1 and 100: "))
if n in list:
return(n)
else:
sys.exit("Number does not match requirements!")
def main():
createlist()
numberinsert()
It gives me this: TypeError: argument of type 'type' is not iterable
What am I doing wrong?
You are trying to access a local variable of function createlist from antother function numberinsert and it's not possible (local variables are accessible only in the scope they are defined).
I would recommend you to change your code as follows:
import sys
# Function creates a list [1,3,5..99]
def createlist():
odd_list = []
for i in range(1, 100, 2):
odd_list.append(i)
return(odd_list)
# Function asks for an odd integer between 1..100
def numberinsert():
num_list = createlist()
n = int(input("Please enter an odd number between 1 and 100: "))
if n in num_list:
return(n)
else:
sys.exit("Number does not match requirements!")
def main():
numberinsert()
As a side note, try to avoid naming your variables with names of built-in functions (like list).
You can also write your code in a more compact way, using range(1, 100, 2) directly in your numberinsert function:
# Function asks for an odd integer between 1..100
def numberinsert():
n = int(input("Please enter an odd number between 1 and 100: "))
if n in range(1, 100, 2):
return(n)
else:
sys.exit("Number does not match requirements!")
def main():
numberinsert()
You named your list as list. List is an data type name (I mean its an keyword). list1 or another name solves that error. And I globalized your list1 variable. I am not sure that globalize part but if I was wrong please warn me. This is my first reply.
import sys
# Function creates a list [1,3,5..99]
def createlist():
global list1
list1 = []
for i in range(1, 100, 2):
list1.append(i)
return list1
# Function asks for an odd integer between 1..100
def numberinsert():
n = int(input("Please enter an odd number between 1 and 100: "))
if n in list1:
return n
else:
sys.exit("Number does not match requirements!")
def main():
createlist()
numberinsert()
main()
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()
...
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
I am new to Python and currently reading Python 3 for absolute beginner and face following problem.
I would like to calculate factorial with procedure.
request user to input an non negative number n
then use for loop to calculate factorial
and the code is like that:
N = input("Please input factorial you would like to calculate: ")
ans = 1
for i in range(1,N+1,1):
ans = ans*i
print(ans)
while i would like to add a feature to check whether input number N is non-negative number. like:
if N != int(N) and N < 0:
I want the user to input N again if it is NOT non-negative number.
Thanks for your gentle help.
The construct could look like this:
while True:
N = input("Please input factorial you would like to calculate: ")
try: # try to ...
N = int(N) # convert it to an integer.
except ValueError: # If that didn't succeed...
print("Invalid input: not an integer.")
continue # retry by restarting the while loop.
if N > 0: # valid input
break # then leave the while loop.
# If we are here, we are about to re-enter the while loop.
print("Invalid input: not positive.")
In Python 3, input() returns a string. You have to convert it to a number in all cases. Your N != int(N) thus makes no sense, as you cannot compare a string with an int.
Instead, try to convert it to an int directly, and if that doesn't work, let the user enter again. That rejects floating point numbers as well as everything else which is not valid as an integer.
In Python's math library, there is a factorial function. You can use it like so:
import math
...
ans = math.factorial(N)
Since you want to calculate using a loop however, have you considered the following?
ans = -1
while ans < 0:
N = input("Please enter a positive integer: ")
if N.isdigit() == True:
n = int(N)
if n >= 0:
ans = n
for x in range (n-1, 1, -1):
ans *= x
print (ans)
Note, the second solution doesn't work for N = 0, where ans = 1 is correct by definition of factorial.
Number = int(input("Enter the number to calculate the factorial: "))
factorial = 1
for i in range(1,Number+1):
factorial = i*factorial
print("Factorial of ",Number," is : ", factorial)
def factorial(a):
if a == 1:
return 1
else:
return a * factorial(a - 1)
print('factorial of number', factorial(5))
Start
Declare Integer n,i,n!
Display “Enter a nonnegative integer.”
Input n
For i=1 to n-1 Step1,
Display “n!=i*n”
End for
Stop
You can check math module for python.
# math.factorial(x)
Return x factorial.
Raises ValueError if x is not integral or is negative.