recursive function does not work as expected - python-3.x

Could someone explain the code? I just can not understand why this code gives output like this:
1
3
6
10
15
21
I expected the code to give something like this:
1
3
5
7
9
11
What am I missing here?
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k-1)
print(result)
else:
result = 0
return result
tri_recursion(6)

For your recursive function, the termination condition is k=0.
It's clear that if k=0, tri_recursion(0) = 0.
If k=1, tri_recursion(1) = 1 + tri_recursion(0), which from above, is 1 + 0 or 1.
If k=2, tri_recursion(2) = 2 + tri_recursion(1), which from above, is 2 + 1 or 3.
If k=3, tri_recursion(3) = 3 + tri_recursion(2), which from above, is 3 + 3 or 6.
If k=4, tri_recursion(4) = 5 + tri_recursion(3), which from above, is 4 + 6 or 10.
If k=5, tri_recursion(5) = 4 + tri_recursion(4), which from above, is 5 + 10 or 15.
If k=6, tri_recursion(6) = 6 + tri_recursion(5), which from above, is 6 + 15 or 21.
See the pattern?

Your code is calculating the sum of numbers up to n where n is 6 in the above case. The print statement prints the intermediate results. Hence the output 1 3 6 10 15 21.
1 - The sum of numbers from 0 to 1
3 - The sum of numbers from 0 to 2
6 - The sum of numbers from 0 to 3
10 - The sum of numbers from 0 to 4
15 - The sum of numbers from 0 to 5
21 - The sum of numbers from 0 to 6

Related

How to recognize [1,X,X,X,1] repeating pattern in panda serie

I have a boolean column in a csv file for example:
1 1
2 0
3 0
4 0
5 1
6 1
7 1
8 0
9 0
10 1
11 0
12 0
13 1
14 0
15 1
You can see here 1 is reapting every 5 lines.
I want to recognize this repeating pattern [1,0,0,0] as soon as the repetition is above 10 in python (I have ~20.000 rows/file).
The pattern can start at any position
How could I manage this in python avoiding if .....
# Generate 20000 of 0s and 1s
data = pd.Series(np.random.randint(0, 2, 20000))
# Keep indices of 1s
idx = df[df > 0].index
# Check distance of current index with next index whether is 4 or not,
# Say if position 2 and position 6 is found as 1, so 6 - 2 = 4
found = []
for i, v in enumerate(idx):
if i == len(idx) - 1:
break
next_value = idx[i + 1]
if (next_value - v) == 4:
found.append(v)
print(found)

Python recursive index changing

I am trying to arrange matrix in way that it will dynamically change the indexes.
I have tried to do it by means of for loop, however it only does once for each index.
def arrangeMatrix(progMatrix):
for l in range(len(progMatrix)):
for item in range(len(progMatrix[l])):
if indexExists(progMatrix,l + 1,item) and progMatrix[l + 1][item] == " ":
progMatrix[l + 1][item] = progMatrix[l][item]
progMatrix[l][item] = " "
The original list is:
1 0 7 6 8
0 5 5 5
2 1 6
4 1 3 7
1 1 1 7 5
And my code should fill all gapped indexes from up to bottom, however my result is:
1 0 6 8
0 5 5
2 1 7
4 1 3 7 6
1 1 1 7 5 5
The actual result should be:
1 0
0 5 8
2 1 7 5
4 1 3 7 6 6
1 1 1 7 5 5
Any help or hint is appreciated.Thanks in advance
It is probably easier if you first iterate the columns, since the change that happens in one column is independent on what happens in other columns. Then, per column, you could iterate the cells from the bottom to the top and keep track of the y-coordinate where the next non-space should "drop down" to.
No recursion is needed.
Here is how that could be coded:
def arrangeMatrix(progMatrix):
for x in range(len(progMatrix[0])):
targetY = len(progMatrix)-1
for y in range(len(progMatrix)-1,-1,-1):
row = progMatrix[y]
if row[x] != " ": # Something to drop down
if y < targetY: # Is it really to drop any lower?
progMatrix[targetY][x] = row[x] # copy it down
row[x] = " " # ...and clear the cell where it dropped from
targetY -= 1 # since we filled the target cell, the next drop would be higher

Trying to learn Python; code leads to infinite loop and I can't figure out why?

I am trying to learn Python and I am trying to run a random walk that plots the points. I have tried de-bugging this myself but I cannot figure out where this is going wrong. I apologise since this seems like a really simple problem but I am getting frustrated.
One file rw_visual.py sets things up and then calls the other file random_walk.py to generate the points in the walk.
rw_visual.py:
enter image description here
random_walk.py:
enter image description here
In debugging, rw_visual.py seems to run until it tries to run the command "rw.fill_walk()" and then it hangs. This tells me that there is something wrong in the while loop in random_walk.py causing this. As hard as I try, I cannot figure it out thought.
Sorry for the very basic question.
Python indentation implies scope. By getting the indentation of your while loop (and all it should contain) correct, I think this is producing the results you're looking for I left out the "graphical" part and just printed the x and y coordinates as a result of the random walk. You can take over the graphical part from here.
from random import choice
class RandomWalk():
def __init__(self, num_points=50):
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
while len(self.x_values) < self.num_points:
x_direction = choice([1, -1])
x_distance = choice([0,1,2,3,4])
x_step = x_direction * x_distance
y_direction = choice([1, -1])
y_distance = choice([0,1,2,3,4])
y_step = y_direction * y_distance
if x_step == 0 and y_step == 0:
continue
next_x = self.x_values[-1] + x_step
next_y = self.y_values[-1] + y_step
print (str(next_x) + " " + str(next_y))
self.x_values.append(next_x)
self.y_values.append(next_y)
rw = RandomWalk()
rw.fill_walk()
RESULTS
-2 -3
1 0
-2 0
-1 1
-1 -3
1 -1
4 0
0 0
0 4
0 5
3 5
1 3
1 4
1 3
-2 4
-3 7
0 7
1 7
-2 5
-2 1
-3 1
-1 0
-4 3
-3 5
0 9
3 7
3 4
-1 5
1 8
4 10
6 11
6 7
9 9
13 10
12 10
12 11
9 9
12 10
16 11
15 7
14 6
14 3
16 2
18 2
15 0
13 -2
12 -1
8 1
12 1

Octave position of maximum value in column

I want to find the argmax of the values in a matrix by column, e.g.:
1 2 3 2 3 3
4 5 6 ->
3 7 8
I feel like I should just be able to map an argmax/posmax function over the columns, but I don't see a particularly intuitive way to do this in Octave.
Read max function documentation here
[max_values indices] = max(input);
Example:
input =
1 2 3
4 5 6
3 7 8
[max_values indices] = max(input)
max_values =
4 7 8
indices =
2 3 3
In Octave If
A =
1 3 2
6 5 4
7 9 8
1) For Each Column Max value and corresponding index of them can be found by
>> [max_values,indices] =max(A,[],1)
max_values =
7 9 8
indices =
3 3 3
2) For Each Row Max value and corresponding index of them can be found by
>> [max_values,indices] =max(A,[],2)
max_values =
3
6
9
indices =
2
1
2
Similarly For minimum value
>> [min_values,indices] =min(A,[],1)
min_values =
1 3 2
indices =
1 1 1
>> [min_values,indices] =min(A,[],2)
min_values =
1
4
7
indices =
1
3
1

spoj - CPCRC1C, sum of digits of numbers 1 to n, need clarification, not solution

Once, one boy's teacher asked him to calculate the sum of numbers 1 through n.
the boy quickly answered, and his teacher made him another challenge. He asked him to calculate the sum of the digits of numbers 1 through n.
Input
Two space-separated integers 0 <= a <= b <= 109.
Output
The sum of the digits of numbers a through b.
Example
Input:
1 10
Output: 46
can someone explain what is meant by sum of the digits of numbers a to b?
from above, sum of {1 2 3 4 5 6 7 8 9 10 } is 55 , it is a well known Gaussian formula
but the output is 46!
if i count from 2 to 9, excluding the border numbers 1 and 10, the answer is 44 , still not 46
So what is meant by sum of digits of numbers?
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + (1 + 0)
Don't treat the 10 as the number 10, rather the digits 1 and 0

Resources