Recursion in python need help understanding - python

i need help understanding this recursion thing
i am new to coding and trying to learn python
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
Recursion Example Results
1
3
6
10
15
21
i understood 1 and 3
i never understand why the answer is 6 by the third row
because
result = 3 + tri_recursion(3-1)
print(result) which is 5 right ?

It may help to print out k with your result
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(f"k: {k} = {result}")
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
produces
Recursion Example Results
k: 1 = 1
k: 2 = 3
k: 3 = 6
k: 4 = 10
k: 5 = 15
k: 6 = 21
So you can see for each k that it is itself + the result from the previous line.

Here's how it works:
tri_recursion(1): result = k = 1
tri_recursion(2): result = k + tri_recursion(2-1) = k + tri_recursion(1) = 2 + 1 = 3
tri_recursion(3): result = k + tri_recursion(3-1) = k + tri_recursion(2) = 3 + 3 = 6
... and so on
Hope it helps!

Related

Print nxn grid clockwise and print the sum of the diagonal elements

Example if n = 5 it should print
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
Sum = 21+7+1+3+13+17+5+9+25
= 101
Here is my code
dim=5
result= n = 1
for in range(2,dim,2):
for i in range(4):
n+=k
result+=n
print(result)
Here is what I made
def spiral(n):
# Initialize the values
m = [[0]*n for _ in" "*n] # Define a list of list of n dim
d = n
v = n*n # values
y = 0 # cord of y
x = n # cord of x
while d > 0:
for _ in" "*d: # Equivalent to <=> for i in range(d)
x -= 1
m[y][x] = v
v-=1
d -= 1
for _ in" "*d:
y += 1
m[y][x] = v
v-=1
for _ in" "*d:
x += 1
m[y][x] = v
v-=1
d -= 1
for _ in" "*d:
y -= 1
m[y][x] = v
v-=1
return m # return the list of list
n = 5
matrix = spiral(n)
# Print lines of the matrix
print("Matrix:")
for e in matrix:
print(*e)
# Print the sum
print(f"Sum: {sum(matrix[i][i]for i in range(n)) + sum(matrix[i][n - i - 1]for i in range(n)) - 1}") # There is a - 1 at the end, because the value of the middle is 1
You can rewrite the while loop like this:
while d > 0:
for i in range(4):
for _ in" "*d:
if i%2:
y -= 2 * (i==3) - 1
else:
x -= 2 * (i==0) - 1
m[y][x] = v
v-=1
if i%2 == 0:
d -= 1
It's shorter but less easy to understand
You can compute The Sum this way
def Spiral(size: int):
if(size<=1):
return 1
else:
Sum = 4*(size)**2 - 6(size-1)
return (Sum+Spiral(size-2))
Spiral(5)

how does result = k + tri_recursion(k-1) give me an output of triangular numbers?

I'm currently learning about functions and I came across a recursions example on w3schools.com. This code is giving me a list of triangular numbers for an argument k > 0. My question is how exactly is it printing out a list of triangular numbers with "result" defined as result = k + tri_recursion(k-1) in the body of the code. The output for an input of k = 6, for example, gives me 1, 3, 6, 10, 15, 21 but I just don't understand how I'm getting a list of triangular numbers from such a simple setting of the return variable. Help would be much appreciated :)
def tri_recursion(k):
if k > 0:
result = k + tri_recursion(k-1)
print(result)
else:
result = 0
return result
print("\n\nexample result")
tri_recursion(6)
you need create a list to storage numbers:
tri_list = []
def tri_recursion(k):
if k > 0:
result = k + tri_recursion(k-1)
tri_list.append(result)
print(result)
else:
result = 0
return result
print("\n\nexample result")
tri_recursion(6)
print(tri_list)
Then you have:
k = 6
6 + tri_recursion(5)
5 + tri_recursion(4)
4 + tri_recursion(3)
3 + tri_recursion(2)
2 + tri_recursion(1)
1 + tri_recursion(0)
1 + 0 = 1
2 + 1 = 3
3 + 3 = 6
4 + 6 = 10
5 + 10 = 15
6 + 15 = 21
This happens because you are printing the sum of the previous numbers in each return of each recursion

Doubling every second digit in python

I would like to double the value of every second digit and then add up the digits that are in their tens. Finally adding all the digits together
E.g: 123456789 -> 1 4 3 8 5 12 7 16 9 -> 1 4 3 8 5 3 7 7 9 -> 47
edit: the user would input any number and the function would still work eg: 5153 -> 5 2 5 6 -> 18
-SORRY first post I'm still getting used to this-
So I would like my function to
1. Reverse the inputted number
2. Double the value of the second digit
3. Sum all the digits together
4. Check if it's divisible by 7
Here is my code so far
my testing
def checksum(num):
#print(rev)
odd_digit = ""
even_digit = ""
even_sum = 0
odd_sum = 0
total_sum = 0
if num < 10 and num != 7:
return False
else:
return True
rev = (num[::-1])
for i in range(len(rev)):
if i % 2 == 0:
odd_digit += rev[i]
else:
even_digit += rev[i]
#print(even_digit)
even_digit = int(even_digit)
while even_digit > 0:
even_digit, even_sum = even_digit//10,even_sum+(even_digit%10)
#print(even_sum)
even_sum_2 = even_sum * 2
#print(even_sum_2)
odd_digit = int(odd_digit)
while odd_digit > 0:
odd_digit, odd_sum = odd_digit//10,odd_sum+(odd_digit%10)
#print(odd_sum)
total_sum = even_sum_2 + odd_sum
#print(total_sum)
if total_sum % 7 == 0:
return True
else:
return False
print(checksum(12345678901))
Try using this sum with a map, and a list comprehension:
>>> sum(map(int,''.join([str(int(v)*2) if i%2 else v for i,v in enumerate(s)])))
47
Or use:
>>> sum([sum(map(int,str(int(v)*2))) if i%2 else int(v) for i,v in enumerate(s)])
47
sum([sum(map(int, str(i * 2))) if i % 2 == 0 else i for i in range(1, 10)])

How to make this run 'faster'? Or is that the right terminology?

I am new to python and I submitted this code for a Hackerrank problem Arrays and Simple Queries, but for a large number of test cases the program is 'terminated due to timeout'. How can I make this more efficient?
I've pasted the main swap function below.
(Repeats M times)
temp = input()
temp = temp.split(" ")
i = int(temp[1])-1
j = int(temp[2])-1
rep = (i-1)+1
if(temp[0]=='1') :
rep = (i-1)+1
while(i<=j) :
count = i-1
ex1 = count
ex2 = i
for k in range(0,rep) :
arr[ex1], arr[ex2] = arr[ex2], arr[ex1]
ex1 = ex1-1
ex2 = ex2-1
i = i+1
else :
rep = (N-(j+1))
while(j>=i) :
count = j+1
ex1 = count
ex2 = j
for k in range(0,rep) :
arr[ex1], arr[ex2] = arr[ex2], arr[ex1]
ex1 = ex1+1
ex2 = ex2+1
j=j-1
Instead of using many loops, you can try simply concatenating slices:
def query(lst, t, start, end):
# Convert to proper zero-indexed index
start -= 1
if t == '1':
return lst[start:end] + lst[:start] + lst[end:]
elif t == '2':
return lst[:start] + lst[end:] + lst[start:end]
# Get the input however you want
N, M = map(int, input().split())
arr = list(map(int, input().split()))
assert len(arr) == N
for _ in range(M):
t, start, end = input().split()
arr = query(arr, t, int(start), int(end))
print(abs(arr[0] - arr[N - 1]))
print(*arr)
Input:
8 4
1 2 3 4 5 6 7 8
1 2 4
2 3 5
1 4 7
2 1 4
Output:
1
2 3 6 5 7 8 4 1

Python Nested For Loop Counting Backwards

This is probably a simple problem, but I am trying to created a nested loop that would count up from 0 to 9 in the outer loop, and in the inner loop, start from the value (or index. They are the same in this case) of the outer loop and count backwards.
Here's an example:
i= 0
k= 0
i= 1
k= 1
k= 0
i= 2
k= 2
k= 1
k= 0
i= 3
k= 3
k= 2
k= 1
k= 0
I got this far:
x = range(0,10)
for i in x:
print 'i = ',x[i]
for k in x:
print 'k = ', x[i::-1]
Obviously, the code above doesn't do what I want it to do. For one, the second for loop doesn't start from the value of i in the outer loop and counts backwards. For another, it doesn't print a new k = for every new value.
I think this should be like this:
x = range(0,10)
for i in x:
print 'i = ',x[i]
for k in x[i::-1]:
print 'k = ', k
print("\n")
The result is:
i = 0
k = 0
i = 1
k = 1
k = 0
i = 2
k = 2
k = 1
k = 0
i = 3
k = 3
k = 2
k = 1
k = 0
i = 4
k = 4
k = 3
k = 2
k = 1
k = 0
i = 5
k = 5
k = 4
k = 3
k = 2
k = 1
k = 0
i = 6
k = 6
k = 5
k = 4
k = 3
k = 2
k = 1
k = 0
i = 7
k = 7
k = 6
k = 5
k = 4
k = 3
k = 2
k = 1
k = 0
i = 8
k = 8
k = 7
k = 6
k = 5
k = 4
k = 3
k = 2
k = 1
k = 0
i = 9
k = 9
k = 8
k = 7
k = 6
k = 5
k = 4
k = 3
k = 2
k = 1
k = 0
Basicly, x[i::-1] should be in the for not in the print.
What about just manipulate it with print function?
i = 0
k = 0
while True:
print (i)
print (k)
if 1<k: #tricky part
print ("\n".join([str(h) for h in range(0,k+1)][::-1]))
print ("")
i += 1
k += 1
if i == 10:
break
You are very close. If you are new to the world of python you can take some inspiration from this example where I use list comprehension.
list = lambda k: [ [ i for i in reversed(xrange(j+1)) ] for j in xrange(k+1) ]
Note: If you are using python 3 "xrange" is changed to "range"
Now call:
list(3)
And you'll see that the result is similar to what you are looking for.
[[0], [1, 0], [2, 1, 0], [3, 2, 1, 0]]

Categories

Resources