I run this code:
def fact(i):
j = 1
while i >= 1:
j = i * j
i -= 1
i = input("input the number: ")
print (fact(i))
and see this output:
input the number: 6
None
Why is my output None? What is wrong?
You are printing the result of a function. In order for a function to return result, you must use the return statement. If you don't return anything, then the the function will automaticaly return None. I suspect you want your function to return j so you need to add return j to the end of the function for it to work.
That should work:
def fact(i):
j = 1
while i >= 1:
j = i * j
i -= 1
return j
i = input("input the number: ")
print (fact(i))
Related
Here's the code, The main problem is to test the algorithm with the naive method and my own method.
def my_solution(numbers):
n = len(numbers)
index_1 = 1
for i in range(0,n):
if numbers[i] > numbers[index_1]:
index_1 = i
if index_1 == 0:
index_2 = 1
else:
index_2 = 0
for i in range(0,n):
if numbers[i] != numbers[index_1] and numbers[i] >= numbers[index_2]:
index_2 = i
sum = numbers[index_1] * numbers[index_2]
return sum
def naive_solution(numbers):
n = len(numbers)
max_product = 0
for first in range(n):
for second in range(first + 1, n):
max_product = max(max_product,
numbers[first] * numbers[second])
return max_product
def testGenerator():
pass
def main():
for i in range(1000):
test = testGenerator()
correct_answer = naive_solution(test)
my_answer = my_solution(test)
assert(my_answer == correct_answer)
Do I need to edit the testGenerator function? Or any other part missing for? I run the code and nothing happen.
You haven't called your functions. Try calling them by using their name followed by parentheses () and any arguments that need to be entered
I am using a flask app and url endpoint to allow the input of a number. I then want to display the fibonnaci sequence up until it is equal to or less than the inputted number.
This is what I currently have:
#app.route("/fibonacci/<int:param_fi>/")
def getFib(param_fi):
if param_fi < 2:
return ('0,1,1')
else:
L = getFib(param_fi-1)
if L[-1] < param_fi:
L.append(L[-1] + L[-2])
return L
I am having trouble pinpointing exactly where the error is from. I have tried making a list and converting it to strings but can't ever get it to work. When I try this it returns the following error:
"The view function did not return a valid response. The return type must be a string, tuple, Response instance, or WSGI callable, but it was a list."
I am looking for the following output:
/fibonacci/250(this is the user input)/
0,1,1,2,3,5,8,13,21,34,55,89,144,233
Or /fibonacci/90(this is the user input)/
0,1,1,2,3,5,8,13,21,34,55,89
Any help is appreciated.
Final
#app.route("/fibonacci/<int:param_fi>/")
def getFib(param_fi):
i = 0
j = 1
sequence = []
current_operation = 0
index = 0
while True:
sequence.append(i)
current_operation = i + j
i = j
j = current_operation
if i > param_fi:
return json.dumps(sequence)
else:
index += 1
return json.dumps(sequence)
I did not understand the error, can you output the result you want to have ? Do you need recursive like you did or no ?
But I guess you are missing something? You only return 0 or 1, or sum of both, so yes, you will never have the full sequence of the fibonacci.
You need to keep in memory the sequence, or return a list and adding elements each time, at least.
EDIT
https://repl.it/#skapin/AcceptableFoolishAssemblylanguage
def fibo(params):
i = 0
j = 1
sequence = []
current_operation = 0
for current_n in range(0, params+1):
# We appends now, since f(0) = 0 = i_initial , f(1) = 1 =j_initial
sequence.append(i)
# prepare next opération
current_operation = i + j
i = j
j = current_operation
return sequence
print(fibo(10))
EDIT2-Flask
from flask import jsonify
#app.route("/fibonacci/<int:param_fi>/")
def get_fibo(param_fi):
return jsonify(fibo(param_fi))
Final
from flask import jsonify
def fibo(params):
i = 0
j = 1
sequence = []
current_operation = 0
index = 0
while True:
# We appends now, since f(0) = 0 = i_initial , f(1) = 1 =j_initial
sequence.append(i)
# prepare next opération
current_operation = i + j
i = j
j = current_operation
# Stop condition
if i > params:
return sequence
else:
index += 1
return sequence
#app.route("/fibonacci/<int:param_fi>/")
def get_fibo(param_fi):
return jsonify(fibo(param_fi))
I have to get userinputs of ints and store them in a array, and print the max number in the list. But I had to create my own max function. Im not sure what steps to take to implement it into my code.
def getInt(prompt):
n = int
done = False
while not done:
try:
n = int(input(prompt))
except ValueError:
print("I was expecting a number, please try again...")
if n == 0:
done = True
return n
def maxNum(l):
maxi = [0]
for num in l:
if maxi > num:
maxi = num
return maxi
def result():
print("The maxium value is: " + maxNum(i))
def main():
num = []
i = 0
done = False
while not done:
num = getInt("Please enter an integer < 0 to finish >: ")
if num == 0:
done = True
results = maxNum(i)
The below code does exactly what you want.
def getInt(prompt):
try:
n = int(input(prompt))
return n
except ValueError:
print("I was expecting a number, please try again...")
getInt()
def maxNum(lst):
if not lst: # if list is empty
return None
max_elem = lst[0]
for x in lst:
if x > max_elem:
max_elem = x
return max_elem
def main():
nums = []
while True:
num = getInt("Please enter an integer < 0 to finish >: ")
if num == 0:
break
nums.append(num)
result = maxNum(nums)
print("The maxium value is: " + str(result))
main()
python support built-in max function
max([1,2,3]) # return 3
and Your code is totally wrong.
if you want to input array of integers, getInt may be like this.
def getInt():
array = []
while True:
x = int(input('message'))
if x == 0: break
array.append(x)
return array
and main code will be
array = getInt()
max_value = max(array)
print (max_value)
if you want your own max function, it can be
def max_func(array):
max_val = array[0]
for val in array:
if val > max_val: max_val = val
return max_val
Here is a fixed version of your maxNum function:
def maxNum(l):
if not l:
return None # or return whatever you want if user did not input anything
maxi = l[0] # it expects 'l' to be an array!
for num in l[1:]:
if maxi > num:
maxi = num
return maxi
Let's also fix your getInt function:
def getInt(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("I was expecting a number, please try again...")
Finally, your "main" function needs the following fix:
def main():
num = []
n = 1
while n != 0:
n = getInt("Please enter an integer < 0 to finish >: ") # store user input into n - do not overwrite num!
num.append(n) # append each user value to the list num
results = maxNum(num) # pass the entire *list* to maxNum
def opdracht3()
a = True
result = 0
waslijst = []
while a:
n = input("Enter a number: ")
if n == "stop":
a = False
else:
waslijst += n
for nummer in waslijst:
result += int(nummer)
eind = result / len(waslijst)
print(eind)
opdracht3()
I want to get the average of the list that is being created, but when I add numbers like 11, the len(waslijst) gets set to 2 instead of 1. Is there another way to get the average, or am I using the len function wrong?
You need use .append method to store all elements in a list.
def opdracht3():
a = True
result = 0
waslijst = []
while a:
n = input("Enter a number: ")
if n == "stop":
a = False
else:
waslijst.append(n)
for nummer in waslijst:
result += int(nummer)
eind = result / len(waslijst)
print(eind)
opdracht3()
How can I modify a global variable in the main function? I set a global variable ADDITION and modify it in a function. Then, I try to modify it in main, but it seems like I failed.
ADDITION = 0
def add(a, b):
global ADDITION
ADDITION = ADDITION + 1
return a+b
def fib_classic(n):
if(n <= 1):
return n
else:
return add(fib_classic(n-2) , fib_classic(n-1))
def fib_closed(n):
fib = (math.pow(1+math.sqrt(5),n) - (1-math.pow(math.sqrt(5),n)))/(math.pow(2,n)*math.sqrt(5))
return math.floor(fib)
def fib_classic(n):
if(n <= 1):
return n
else:
return add(fib_classic(n-2) , fib_classic(n-1))
def fib_loop(n):
a = 0
b = 1
if(n <= 1):
return n
else:
for i in range(0, n-1):
c = b
b = add(a, b)
a = c
return b
def fib_mem(n):
global FIB_DIC
if(n in FIB_DIC):
return FIB_DIC[n]
else:
if(n <= 1):
FIB_DIC[n] = n
else:
FIB_DIC[n] = add(fib_mem(n-1), fib_mem(n-2))
return FIB_DIC[n]
def main():
for i in range(0,36):
global ADDITION
print("Computing the {0}th Fibonacci Number:".format(i))
print("The closed form finds:", end=" "); print(fib_closed(i))
print("The recursive definition finds:", end=" "); print(fib_classic(i))
print("Additions needed for recursive definition:", end=" "); print(ADDITION)
ADDITIION = 0
print(ADDITION) # not 0
print("The loop definition finds:", end=" "); print(fib_loop(i))
print("Additions needed for loop definition:", end=" "); print(ADDITION)
ADDITION = 0
print("The memoization definition finds:", end=" "); print(fib_mem(i))
print("Additions needed for memoization definition:", end=" "); print(ADDITION)
print("--------------------")
You have a spelling error in main():
ADDITIION = 0
should be
ADDITION = 0
In what way do you think your code isn't working? Perhaps try to simplify it first. This code behaves as expected:
ADDITION = 0
def modify():
global ADDITION
ADDITION = ADDITION + 1
def main():
global ADDITION
print("Initial value: {}".format(ADDITION))
modify()
print("Subsequent value: {}".format(ADDITION))
ADDITION = 0
print("Zero'd out: {}".format(ADDITION))
modify()
print("Modified again: {}".format(ADDITION))
if __name__ == '__main__':
main()
# Output:
# Initial value: 0
# Subsequent value: 1
# Zero'd out: 0
# Modified again: 1