missing a step. | Sololearn: Learn to code for FREE!

+1

# missing a step.

Yesterday I tried to solve this problem Given a range of numbers. Iterate from first number to the end number and print the sum of the current number and previous number. x =[x for x in range(0,20,2)] for y in x: if y == 0: print(0) else: print(2*y-2) It work but only if you know the interval between the number and if it is constant. So I tried to find a way to check for calculating and checking the interval in a list I used a for loop for y in x: d = x[y] - x[-1] and an if/else to check that d was equal to the value on the first step. It was working fine for a list without step (0,1,2,3,4), but not at all if there was any step. With a step of two only half the element of the list where compared. Took me one hour to figure out that x[y] was not the value of x for the element y, but the value of x at the indice y. So in the case of an odd list : [0,2,4,6] for iteration I had 0 4 that is x[2] and a message error because x[4] does not exist. Finding the source of the error was a lot of fun, because I had to write many variation of my code to understand where was the issue. I ended up understanding that I had to use enumarte and that was the final code. x =[0,1,2,3,5,9,-5] c = x[1] - x[0] print(x) print(f"First step is {c}") for i,j in enumerate(x): if i > 0: d = x[i]-x[i-1] else: d =c if d != c: print(f"none regular step between {i-1} and {i}, the step is {d}")

11/29/2019 5:31:06 AM

nicolas seespan

+3

Hello no real question because I solved this by myself. But when I post people make suggestion on other way to solve the issue. That's how I learn about enumerate. I am a total newbie and I am learning with " a crash course in python" and by trying to do some exercise. I will have a look at the zip function, never heard of this one before.

+4

Great learning, although I don't really see a question here, you seem to have figured this out yourself. Well done ;) I can show you an even more pythonic solution, its simplicity is just amazing and it also works with lists that are empty or have 1 element... It used the zip() function, to combine the list with a sliced version of itself. https://code.sololearn.com/cZgO80zEG4Y0/?ref=app

+3

nicolas seespan, in your code you have an expression "c = x[1] - x[0]" that fills var c. But it's never used?

+2

And the answer to the initial problem x =[0,1,2,3,5,9,-5] c = x[1] - x[0] print(x) for i,j in enumerate(x): if i > 0: y = x[i] + x[i-1] print(y) else: y = x[0] print(y) This one will works not matter what the composition of the list :-).

+1

Hello it was a part from the version of the code which was checking the interval I forgot to remove it.