0

In Java, the FOR loop syntax offers a place where we can add a condition. For instance, in the below code the condition is i*j < n

for (i=0; i*j < n; i++) 
{ ... }

In Python, how can we add such condition in the for loop statement?

for i in range(n):

I know that we can add an if statement inside the for loop, but I am concerned that it will increase the run time to O(n). Please advice.

Sriram
  • 999
  • 2
  • 12
  • 29

2 Answers2

4

the for has a complexity of O(n), so a if does not change the complexity.

The for(i=0; i*j < n; i++) in Java is represented by while in Python:

i = 0  # initialization
while i * j < n:  # conditions
   do_something
   i += 1  # step
Daniel
  • 42,087
  • 4
  • 55
  • 81
1

When I switched from C to python, this was one of my biggest worries, but it turns out that it is actually a misunderstanding of of syntax. In python, although you can write for i in range(n) it is usually a sign that you are doing something else wrong. It is considered better to loop through elements rather than numbers. For a concrete example, in C, you might write

for(i=0; i<len(str); i++){
    str[i] blah blah blah
}

In python the way you would probably do this is to iterate through the characters directly:

for char in str:
    char blah blah blah
Oscar Smith
  • 5,766
  • 1
  • 20
  • 34