2

How can I perform below code in python I am new to python and getting troubled, please could someone help

objects = [............] // Array
for (i=0; i<objects.length(); i++) {
    if(readElement(objects[i])){
        //do something
    } else {
      i--; // so that same object is given in next iteration and readElement cant get true
    }
}
3
  • thanks @nu11p01n73R, I can do, but cant I do using for loop only Commented Jun 10, 2015 at 6:48
  • 2
    @SharanabasuAngadi No you cannot. Python's for loop uses iterators. An those are forward only. You can never go back in an iterator. Commented Jun 10, 2015 at 6:53
  • 1
    in python i would not be a counter/number in the C sense. Instead it is an element of the sequence you provide to the for loop. Commented Jun 10, 2015 at 6:55

4 Answers 4

2

Have you considered using recursion?

def func(objects,i):
    if i == len(objects):
        return
    if readElement(objects[i]){
        #do something
        func(objects,i+1)
    else 
        func(objects,i)--; # so that same object is given in next iteration and readElement cant get true
    }
objects = [............] # list
func(objects,0)

Else, you can do this(very non-Pythonic, but using for loops only as you requested):

objects = [............] # Array
func(objects,0)
M = 10E6 # The maximum number of calls you think is needed to readElement(objects[i])
for i in xrange(objects)
    for j in xrange(M):
        if readElement(objects[i]):
            #do something
            break
Sign up to request clarification or add additional context in comments.

1 Comment

@Sharanabasu Angadi does that answers your question?
0

You can try this out

 objects = ["ff","gg","hh","ii","jj","kk"] # Array
 count =0
 for i in objects: # (i=0; i<objects.length(); i++) {
    if i:
        print i
    else :
        print objects[count-1]
    count =+1

Comments

0

I was looking for the same thing, but I ended up writing a while loop, and manage the index myself.

That said, your code can be implemented in Python as:

objects = [............] # Array
idx = 0

while idx < len(objects):
    if readElement(objects[idx]):
        # do hacky yet cool stuff
    elif idx != 0:
        idx -= 1 # THIS is what you hoped to do inside the for loop
    else:
        # some conditions that we haven't thought about how to handle

Comments

-1

Your code is iterating through a list of objects and repeats "readElement" until it returns "True", in which case you call "do something". Well, you could just write that down:

for object in objects:
    while not readElement(object): pass
    dosomething()

[Edit: the first version of this answer inverted the logic, sorry]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.