-1

lets say we have the following pseudo-code:

count = 0 for i in range(0,N): if a[i] == 0: count+= 1

Why would you want to go from 0 to N? Let`s say the array has 10 entries. If you were to go from 0 to 10 you would compare 11 numbers to 0. Would it not be correct to change the range to

for i in range(0,N-1):
Math Noob
  • 25
  • 1
  • 6
  • 3
    `range(0,N)` will generate integers from 0 up to N-1. That is how `range` in python works. Moreover, you can just use `range(N)` as the default start is from 0 unless you want to start from some other number – Sheldore May 11 '20 at 09:35
  • N in not included, --> [0,N), will give your rnage from [0,N-1] – Pygirl May 11 '20 at 09:36
  • What the [official documentation on `range`](https://docs.python.org/3/library/stdtypes.html#range) states, goes. – Jongware May 11 '20 at 09:45

2 Answers2

0
a = [0,1,2,3,4,5]
N = len (a)
count = 0 
for i in range(0,N):
    if a[i] != -1:
        print(a[i])
        count+= 1

Try experimenting by printing out the contents of each accessed element from within your loop. You might be surprised.

Thomas Kimber
  • 10,601
  • 3
  • 25
  • 42
0

In python 3+ range(0, N) means it will iterate from 0 to N-1. In a programming language like java, the programmer needs to take care of n-1 factor while in python it has been taken care of python.

  • `In a programming language like java, the programmer needs to take care of n-1 factor while in python it has been taken care of python` This is using a foreach loop, which also exists in "programming languages like java" (and c++11, and C#, and others). The only difference here, python has native `range()` function. [Java also has something similar now](https://stackoverflow.com/a/22903362/572670). – amit May 11 '20 at 09:53