Change the value of Global Variable in Python3 - python

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

Related

What the missing part for my python stress test Algorithm?

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

how to fix this combination program using binomial factorial equation?

my answer for finding the number of combinations given drawing 3 cards out of 52 is off by a spot. Like 0 cards from 52 should = 1, 1 should = 52, 2 = 1326 and so on. but I have 0 = 1, 1 = 1, 2 = 52 and so on. What would I modify to reach the desired result? I think the error is in def factorial() but I can not seem to fix/ find the issue, no matter what I try.
def factorial(num):
i = 2
if num == 0:
num = 1
print(num)
elif num > 1:
for i in range(i, num):
num = num * i
return num
def combinations(n,r):
l = n-r
nn = factorial(n)
rn = factorial(r)
ln = factorial(l)
result = nn / (rn * ln)
print(result)
return result
def main():
h = 52
a = 0
while a<4:
combinations(h,a)
a = a + 1
You're printing extra stuff in factorial which may lead to the confusion. I suggest you print out your final result with comparison to your a variable at the end of the combinations function like so:
print("For a=" + str(r) + ", result=" + str(result))
Here is the overall edited code:
def factorial(num):
if num == 0:
num = 1
elif num > 1:
for i in range(2, num): # Setting i=2 at the start is redundant
num = num * i
return num
def combinations(n,r):
l = n-r
nn = factorial(n)
rn = factorial(r)
ln = factorial(l)
result = nn / (rn*ln)
print("For a=" + str(r) + ", result=" + str(result))
return
h = 52
a = 0
while a<4:
combinations(h,a)
a = a + 1

How do I display the max function i created in python

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

None output when I run my code

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))

difference between decorating with # symbol and without it in python

Consider the following code
Here I have not used the # symbol for decoration
import math
def isOddMy(func):
def innerOdd(x):
y = func(x)
if math.fmod(y, 2) == 0 :
return 0
else:
if y is not None:
return y
else:
return 0
return innerOdd
##isOddMy
def fib(n):
#print n,
if n == 0 :
return 0
elif n == 1 :
return 1
else:
return fib(n-2) + fib(n-1)
def main():
#oddFibi = isOdd(fib)
#print [i for i in oddFibi(100)]
for i in range(1,10):
print fib(i),
print
fib1 = isOddMy(fib)
for i in range(1,10):
print fib1(i),
if __name__ == '__main__':
main()
and the result is
1 1 2 3 5 8 13 21 34
1 1 0 3 5 0 13 21 0
whereas below i have used # symbol but the result is
1 1 0 1 1 0 1 1 0
Why is this so??
import math
def isOddMy(func):
def innerOdd(x):
y = func(x)
if math.fmod(y, 2) == 0 :
return 0
else:
if y is not None:
return y
else:
return 0
return innerOdd
#isOddMy
def fib(n):
#print n,
if n == 0 :
return 0
elif n == 1 :
return 1
else:
return fib(n-2) + fib(n-1)
def main():
#oddFibi = isOdd(fib)
#print [i for i in oddFibi(100)]
for i in range(1,10):
print fib(i),
'''print
fib1 = isOddMy(fib)
for i in range(1,10):
print fib1(i),'''
if __name__ == '__main__':
main()
Thanks.
The difference is probably to do with the recursive call. When fib calls fib, that name is looked up in module scope. If you use the # decorator syntax, the decorated function is found with name fib. If you just do fib1 = isOddMy(fib), the undecorated function is found with name fib.

Categories

Resources