Why does k increment to 1 in this recursion function - python-3.x

I'm running a recursion function that I got from w3schools for the page that they have on recursion, and after running the code in debug mode in vscode the k for some reason completely decrements to 0, and out of nowhere increments back up to 1. Can someone explain this to me I would much appreciate it.
Here is the code
def tri_Recursion(k):
if(k > 0):
result = k + tri_Recursion(k-1)
print(result)
else:
result = 0
return result
def main():
tri_Recursion(6)
print("\n\nRecursion Example Results")
if __name__ == "__main__":
main()

Related

CODEFORCES 1744B, how could I fix runtime error?

I'm trying to solve the next problem: https://codeforces.com/contest/1744/problem/B
When I run the code in my terminal, it works with the example given in the exercise; but it doesn't when I submit it in CodeForces, it cause a runtime error which I cannot figure out.
def increment(arr, length, option, add):
for i in range(length):
if(option == '0') and (arr[i]%2 == 0):
arr[i] += add
elif(option == '1') and (arr[i]%2 != 0):
arr[i] += add
else:
pass
return arr
def main():
quantityOperation = int(input())
while quantityOperation > 0:
length, times = input().split()
length = int(length)
times = int(times)
arr = [int(x) for x in input().split()]
while times > 0:
opt, add = input().split()
add = int(add)
res = sum(increment(arr, length, opt, add))
print(res)
times -= 1
quantityOperation -= 1
main()
The loop inside your main function doesn't end. You should put quantityOperation -= 1 inside the while loop.
However, your code will still become time limit exceeded after fixing this. The correct idea is to precalculate odd and even sum and modify them according to the queries instead of looping all elements inside increment function every time. You can check the editorial for this problem.

Python returning none instead of an array

I made some code to solve a sudoku puzzle recursively, however when i go to return the output of the puzzle it returns none instead of the output, however printing the result at the end shows the correct solution
def sudoku(puzzle):
for y in range(9):
for x in range(9):
if(puzzle[y][x] == 0):
for n in range(1,10):
if possible(puzzle,x,y,n):
puzzle[y][x] = n
sudoku(puzzle)
puzzle[y][x] = 0
return
print(puzzle)
return puzzle
def possible(puzzle,x,y,n):
for i in range(9):
if (puzzle[y][i] == n):
return False
for i in range(9):
if (puzzle[i][x] == n):
return False
x0 = (x//3)*3
y0 = (y//3)*3
for i in range(3):
for j in range(3):
if(puzzle[y0 + j][x0 + i] == n):
return False
return True
When I run this code, the correct solution gets printed to the console but the returned output is none. I suspect that this is caused by the line return, but I don't know how to go back to the previous level of recursion without this.

Recursion functions for factorial

I am writing this code to get the 10! ,however, I believe I have an infinite loop in there since it keeps repeating the same error code. I am trying to find the issue but can not seem to.
def calculatingfactor(num2cal):
"""this fuction will be calculating a mathematical factorial"""
if num2cal == 1:
returnvalue = 1
elif num2cal <= 0:
returnvalue = 0
else:
print("Calculating the facterial of {}".format(num2cal))
variable2 = calculatingfactor(num2cal - 1)
returnvalue = calculatingfactor(num2cal*variable2)
return
#main code
first_fact=calculatingfactor(10)
print (first_fact)
The recursive case of your code looks incorrect to me. You should be calling the same function with num2cal decremented by one, then returning the current value multiplied by whatever that recursive call returned.
def calculatingfactor(num2cal):
if num2cal == 1:
return 1
elif num2cal <= 0:
return 0
else:
print("Calculating the facterial of {}".format(num2cal))
variable2 = calculatingfactor(num2cal - 1)
return num2cal*variable2
# main code
first_fact=calculatingfactor(10)
print (first_fact)

Count not incrementing properly in python while loop

Can anyone tell me why when I input 1, 2, 3, and 4 into this code, my output is 6, 2, 3.00? I thought that every time my while loop evaluated to true it would increment the count by one, but the output is not making sense. It's taking the total of 3 of the numbers, but only 2 for the count? I'm probably just overlooking something so an extra pair of eyes would be awesome.
def calcAverage(total, count):
average = float(total)/float(count)
return format(average, ',.2f')
def inputPositiveInteger():
str_in = input("Please enter a positive integer, anything else to quit: ")
if not str_in.isdigit():
return -1
else:
try:
pos_int = int(str_in)
return pos_int
except:
return -1
def main():
total = 0
count = 0
while inputPositiveInteger() != -1:
total += inputPositiveInteger()
count += 1
else:
if count != 0:
print(total)
print(count)
print(calcAverage(total, count))
main()
The error with your code is that on this piece of code...
while inputPositiveInteger() != -1:
total += inputPositiveInteger()
You first call inputPositiveInteger and throw out the result in your condition. You need to store the result, otherwise one input out of two is ignored and the other is added even if it is -1.
num = inputPositiveInteger()
while num != -1:
total += num
count += 1
num = inputPositiveInteger()
Improvements
Although, note that your code can be significantly improved. See the comments in the following improved version of your code.
def calcAverage(total, count):
# In Python3, / is a float division you do not need a float cast
average = total / count
return format(average, ',.2f')
def inputPositiveInteger():
str_int = input("Please enter a positive integer, anything else to quit: ")
# If str_int.isdigit() returns True you can safely assume the int cast will work
return int(str_int) if str_int.isdigit() else -1
# In Python, we usually rely on this format to run the main script
if __name__ == '__main__':
# Using the second form of iter is a neat way to loop over user inputs
nums = iter(inputPositiveInteger, -1)
sum_ = sum(nums)
print(sum_)
print(len(nums))
print(calcAverage(sum_, len(nums)))
One detail worth reading about in the above code is the second form of iter.

Python recursive function returning none after completion

My code is supposed to countdown from n to 1. The code completes but returns None at the end. Any suggestions as to why this is happening and how to fix it? Thanks in advance!
def countdown(n):
'''prints values from n to 1, one per line
pre: n is an integer > 0
post: prints values from n to 1, one per line'''
# Base case is if n is <= 0
if n > 0:
print(n)
countdown(n-1)
else:
return 0
def main():
# Main function to test countdown
n = eval(input("Enter n: "))
print(countdown(n))
if __name__ == '__main__':
main()
print(countdown(n)) prints the value returned by countdown(n). If n > 0, the returned value is None, since Python functions return None by default if there is no return statement executed.
Since you are printing values inside countdown, the easiest way to fix the code is to simply remove the print call in main():
def countdown(n):
'''prints values from n to 1, one per line
pre: n is an integer > 0
post: prints values from n to 1, one per line'''
# Base case is if n is <= 0
if n > 0:
print(n)
countdown(n-1)
def main():
# Main function to test countdown
n = eval(input("Enter n: "))
countdown(n)
if __name__ == '__main__':
main()
Edit: Removed the else-clause since the docstring says the last value printed is 1, not 0.
Remove the print(countdown(n)) and replace it with just countdown(n).
What happens is your countdown function returns nothing when n is greater than 0, so that print statement is printing None. You can also remove your else statement in countdown(n) - since you never care about the return value of countdown, it serves no purpose.
def countdown(n):
'''prints values from n to 1, one per line
pre: n is an integer > 0
post: prints values from n to 1, one per line'''
# Base case is if n is <= 0
if n > 0:
print(n)
countdown(n-1)
# No need to return a value from here ever - unused in the recursion and
# you don't mention wanting to have zero printed.
#else:
# return 0
def main():
# Main function to test countdown
n = eval(input("Enter n: "))
# Don't print the result of countdown - just call it
#print(countdown(n))
countdown(n)
if __name__ == '__main__':
main()
You want to return the recursive call to the next invocation of countdown:
def countdown(n):
'''prints values from n to 1, one per line
pre: n is an integer > 0
post: prints values from n to 1, one per line'''
# Base case is if n is <= 0
if n > 0:
print(n)
return countdown(n-1)
else:
return 0
def main():
# Main function to test countdown
n = eval(input("Enter n: "))
print(countdown(n))
if __name__ == '__main__':
main()
In this way, when the base case is reached, the return value of 0 should propagate back up the stack and be returned.
Unfortunately, however, since your base case returns 0, this results in the printing of 0. But, if you want to return something (think about whether or not you actually need to in this case) this would be how you do it.
If you don't need to return anything, then you don't need to print the result. Further modify
print(countdown(n))
to
countdown(n)

Resources