Is there a pythonic way to make a while loop with an index?

Is there a more pythonic way to write the code at the bottom so that it iterates over some condition but also preserves the index of the iterations?

def TrieMatching(text, trie):
    match_locations = []
    location = 0
    while text:
        if PrefixTrieMatching(text, trie):
            match_locations.append(location)
        text = text[1:]
        location += 1

      

+3


source to share


6 answers


I always love comprehension of lists.



def TrieMatching(text, trie):
    match_locations = [
        location
        for location in range(len(text))
        if PrefixTrieMatch(text[location:],trie)
    ]

      

+5


source


You are always increasing i

, so just use a range:



def TrieMatching(text, trie):
    match_locations = []
    for i in range(len(text)):
        if PrefixTrieMatching(text[i:], trie):
            match_locations.append(i)

      

+4


source


Have you ever heard the old saying, "Give a man a hammer and all of a sudden all his problems will be like nails"? The cycle is while

not a hammer.

Why use a loop at all while

? If I am correct, your problem can be listed without referencing them as "create a list of locations of all suffixes text

that match the given one trie

".

This can be written as a list comprehension:

def TrieMatching(text, trie):
   return [l for l in range(len(text)) if PrefixTrieMatching(text[l:], trie)]

      

I added return

, since it makes no sense to compute the value just to not reference it.

+1


source


enumerate()

is a great way to iterate over something and get the index. It returns an iterable which gives tuples (counter, value)

https://docs.python.org/2/library/functions.html#enumerate

From the docs:

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

      

This way you can easily use it in a for loop:

for (i,season) in enumerate(seasons):
     print "{} {}".format(i,season)

      

prints:

0 Spring
1 Summer
2 Fall
3 Winer

      

0


source


enumerate

often used to keep track of an index in a for loop. Here's an example on how to use it.

for i, elem in enumerate("abc"):
    print(i, elem)

0 a
1 b
2 c

      

In your example you are not using elem

as in the above case, so it enumerate

may not be the best solution. You should probably either try using range

it or stick with the loop while

you already have.

for location in range(len(text)):
    if PrefixTrieMatching(text[location:], trie):
        match_locations.append(location)

      

0


source


I wouldn't necessarily use that, but itertools.count()

- [1, 2, 3, ...]

.

import itertools
for i in itertools.count():
    ...

      

-1


source







All Articles