enumerate() and ending early

This is the place for queries that don't fit in any of the other categories.

enumerate() and ending early

Postby XndrK » Mon Apr 07, 2014 7:54 pm

Can you end a generation early with enumerate()? For example, I am using the code at tedlee/markov on GitHub as a starting point for my own Markov chain program (though it is not a direct fork), and it says the following in markovgen.py:

Code: Select all
for i in range(len(self.words) - 2):
    yield (self.words[i], self.words[i+1], self.words[i+2])


I'm trying to figure out how to do that with enumerate(). Is there a way to do that?
Proverbs 26:14 describes me a bit too well.

Version: Python 2.7.5

https://github.com/4of92000
https://github.com/PythonForum/
User avatar
XndrK
 
Posts: 172
Joined: Sat Jun 15, 2013 7:57 pm

Re: enumerate() and ending early

Postby stranac » Mon Apr 07, 2014 8:10 pm

You would break, although it would require you to know the total length.

I would go with something like this instead:
Code: Select all
>>> words = '123456789'
>>> zip(words, words[1:], words[2:])
[('1', '2', '3'), ('2', '3', '4'), ('3', '4', '5'), ('4', '5', '6'), ('5', '6', '7'), ('6', '7', '8'), ('7', '8', '9')]


Of course, if you want all of the lazy goodness, you can use itertools.izip() and itertools.islice().
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1093
Joined: Thu Feb 07, 2013 3:42 pm

Re: enumerate() and ending early

Postby metulburr » Mon Apr 07, 2014 8:16 pm

somethign along the lines of:
Code: Select all
words = 'some random string there to test'
words = words.split()

def run():
   for i, word in enumerate(words):
      if i+2 < len(words):
         yield (word, words[i+1], words[i+2])

for i in run():
   print(i)
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1376
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 2 guests