Help me understand this code

I found this code on the web, and i have been reading it 100times but i do not get it. It makes no sence, ive tried to print(i), print(left_node) etc to see what happens.
I also now trying to understand the difference between (), and [ ]. I’ve understood or seen the difference between the usage of these two before but forgot.

i cant understand how the the -2 in the for loop works with the len func.: for i in range(len(li)-2)
then the: current_node = li[i + 1] and right_node = li[i+2]

li = [100, 78, 98, 62, 54, 36, 145]
res = []
for i in range(len(li)-2):
left_node = li[i]
current_node = li[i + 1]
right_node = li[i+2]
if current_node < left_node and current_node < right_node:
res.append(current_node)
print(res)

You may find this article on the different types of brackets used in Python useful (I found it by searching “Python different types of brackets”):
https://www.edlitera.com/blog/posts/python-parentheses

Please note that indentation is important in Python code. On this forum, you may format your code so that its indentation is shown properly by using the </> button in the formatting toolbar.

li contains 7 items, so len(li) = 7.

range(len(li) - 2) therefore means range(7 - 2) i.e. range(5), which are the numbers 0 to 4 (5 is excluded).

When i = 0:

  • left_node = li[0] = 100
  • current_node = li[0 + 1] = li[1] = 78
  • right_node = li[0 + 2] = li[2] = 98
  • current_node < left_node => 78 < 100 => True
  • current_node < right_node => 78 < 98 => True
  • As both conditions are True, 78 is added to the list res.

You may perform a similar analysis for i = 1 to i = 4.

You may notice that when i = 0, the first 3 numbers are checked, and when i = 4, the last 3 numbers are checked. After working through all values of i from 0 to 4, the whole list li is covered.

The code essentially puts every number which is smaller than its neighbours in the list res. The final result, therefore, is [78, 36].

1 Like