简体   繁体   中英

Looping through a list not in order in Python

I am very new to programming, so please bear with me...I have been learning Python and I just did an assessment that involved looping through a list using your current value as the next index value to go to while looping. This is roughly what the question was:

You have a zero-indexed array length N of positive and negative integers. Write a function that loops through the list, creates a new list, and returns the length of the new list. While looping through the list, you use your current value as the next index value to go to. It stops looping when A[i] = -1

For example:

A[0] = 1
A[1] = 4
A[2] = -1
A[3] = 3
A[4] = 2 

This would create:

newlist = [1, 4, 2, -1]

len(newlist) = 4

It was timed and I was not able to finish, but this is what I came up with. Any criticism is appreciated. Like I said I am new and trying to learn. In the meantime, I will keep looking. Thanks in advance!

def sol(A):
    i = 0
    newlist = []
    for A[i] in range(len(A)):
        e = A[i]
        newlist.append(e)
        i == e
        if A[i] == -1:
            return len(newlist)

This might be the easiest way to do it if your looking for the least lines of code to write.

A = [1,4,-1,3,2]
B = []

n = 0

while A[n] != -1:
    B.append(A[n])
    n = A[n]

B.append(-1)

print(len(B))

First of all, note that for A[i] in range(len(A)) is a pattern you certainly want to avoid, as it is an obscure construct that will modify the list A by storing increasing integers into A[i] . To loop over elements of A , use for val in A . To loop over indices into A , use for ind in xrange(len(A)) .

The for loop, normally the preferred Python looping construct, is not the right tool for this problem because the problem requires iterating over the sequence in an unpredictable order mandated by the contents of the sequence. For this, you need to use the more general while loop and manage the list index yourself. Here is an example:

def extract(l):
    newlist = []
    ind = 0
    while l[ind] != -1:
        newlist.append(l[ind])
        ind = l[ind]
    newlist.append(-1)   # the problem requires the trailing -1
    print newlist        # for debugging
    return len(newlist)

>>> extract([1, 4, -1, 3, 2])
[1, 4, 2, -1]
4

Note that collecting the values into the new list doesn't really make sense in any kind of real-world scenario because the list is not visible outside the function in any way. A more sensible implementation would simply increment a counter in each loop pass and return the value of the counter. But since the problem explicitly requests maintaining the list, code like the above will have to do.

It's simpler to just use a while loop:

data = [1,4,-1,3,2]
ls = []
i = 0
steps = 0
while data[i] != -1:
    ls.append(data[i])
    i = data[i]
    steps += 1
    assert steps < len(data), "Infinite loop detected"
ls.append(-1)
print ls, len(ls)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM