473,788 Members | 2,898 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to make a generator use the last yielded value when it regainscontrol

Ok, I wrote this all by myself, which explains why it doesn't work. It
is meant to take a number and generate the next number that follows
according to the Morris sequence. It works for a single number, but what
I'd like it to do is either:

1. repeat indefinitely and have the number of times controlled elsewhere
in the program (e.g., use the morris() generator in a for loop and use
that context to tell it when to stop)

2. just make it a function that takes a second argument, that being the
number of times you want it to repeat itself and create numbers in the
sequence

Here's the code so far, and any general comments are always appreciated
as well:

def morris(seed):
seed = list(str(seed))
grouping = []
nextNum = []
for i in range(len(seed) ):
try:
if seed[i] == seed[i + 1]:
grouping.append (seed[i])
else:
grouping.append (seed[i])
nextNum.append( str(len(groupin g)) + seed[i])
grouping = []
except IndexError:
grouping.append (seed[i])
nextNum.append( str(len(groupin g)) + seed[i])
seed = ''.join(nextNum )
yield seed

I thought the second to last line might rebind 'seed' to the new value,
and it would use that again the next time through, but it seems to just
keep using the original value each time and yielding the same output.
Apr 7 '06
18 1787
John Salerno wrote:
Ben Cartwright wrote:
Definitely go for (1). The Morris sequence is a great candidate to
implement as a generator. As a generator, it will be more flexible and
efficient than (2).


Actually I was just thinking about this and it seems like, at least for
my purpose (to simply return a list of numbers), I don't need a
generator. My understanding of a generator is that you do something to
each yielded value before returning to the generator (so that you might
not return at all), but since I'm not handling the individual numbers,
just getting a list, it seems I don't need them to be yielded. Of
course, a generator would allow the process to be done over and over, I
suppose, which is what I wanted, I just couldn't figure out how to keep
using the new values.


itertools.group by makes this very straightforward :
from itertools import groupby .... def lookandsay(seed ): .... seed = str(seed)
.... while 1:
.... seed = "".join("%s %s" % (len(list(group )), item)
.... for item, group in groupby(seed))
.... yield seed
....
seq = lookandsay(1)
seq.next() '11' seq.next() '21' seq.next() '1211' seq.next() '111221' seq.next() '312211'

If you want to get just part of the infinite series, use itertools.islic e:
from itertools import islice
list(islice(loo kandsay(1),10)) ['11', '21', '1211', '111221', '312211', '13112221', '1113213211',
'31131211131221 ', '13211311123113 112211', '11131221133112 132113212221'] list(islice(loo kandsay(1),10,2 0)) ['31131122212321 121113122113121 13211',
'13211321321112 131221123113112 221131112211312 21',
'11131221131211 131231121113112 221121321132132 211331222113112 211',
'31131122211311 123113111213211 231132132211211 131221131211132 221231132211321 2221',
'13211321322113 311213211331121 113122112132113 121113222112311 311222113111231 133211121321132 2211312113211',
'11131221131211 132221232112111 312212321123113 112221121113122 113111231133221 121321132132211 331121321231231 121113122113322 113111221131221 ',
'31131122211311 123113321112131 221123113112211 121312211213211 321322112311311 222113311213212 322211211131221 131211132221232 112111312111213 111213211231131 122212322211331 222113112211',
'13211321322113 311213212312311 211131122211213 211321223112111 311222112111312 211312111322211 213211321322123 211211131211121 332211231131122 211311123113321 112131221123113 111231121113311 211131221121321 132132111213322 123113221132122 21',
'11131221131211 132221232112111 312111213111213 211231132132211 211131221131211 221321123113213 221123113112221 131112311332211 211131221131211 132211121312211 231131112311211 232221121321132 132211331121321 231231121113112 221121321133112 132112312321123 113112221121113 122113121113123 112112322111213 211322211312113 211',
'31131122211311 123113321112131 221123113111231 121113311211131 221121321131211 132221123113112 221131112212211 131221121321131 211132221121321 132132211331121 321232221123113 112221131112311 322311211131122 211213211331121 321122112133221 121113122113121 113222123211211 131211121311121 321123113213221 121113122123211 211131221121311 121312211213211 321322112311311 222113111231131 112132112211213 223112111312211 332211311122113 1221']

HTH
Michael

Apr 8 '06 #11
Michael Spencer wrote:
itertools.group by makes this very straightforward :


I was considering this function, but then it seemed like it was only
used for determing consecutive numbers like 1, 2, 3 -- not consecutive
equivalent numbers like 1, 1, 1. But is that not right?
Apr 8 '06 #12
John Salerno wrote:
Michael Spencer wrote:
itertools.group by makes this very straightforward :


I was considering this function, but then it seemed like it was only
used for determing consecutive numbers like 1, 2, 3 -- not consecutive
equivalent numbers like 1, 1, 1. But is that not right?

data = [1, 1, 1, 2, 2, 3, 4, 4, 3, 2, 2, 1, 1, 2, 2,4, 2, 2]

from itertools import groupby
for k, g in groupby( data ):
print k, list(g)

1 [1, 1, 1]
2 [2, 2]
3 [3]
4 [4, 4]
3 [3]
2 [2, 2]
1 [1, 1]
2 [2, 2]
4 [4]
2 [2, 2]

for k, g in groupby( data, lambda x: x<2 ):
print k, list(g)

True [1, 1, 1]
False [2, 2, 3, 4, 4, 3, 2, 2]
True [1, 1]
False [2, 2, 4, 2, 2]

Gerard

Apr 8 '06 #13
John Salerno wrote:
Michael Spencer wrote:
itertools.group by makes this very straightforward :


I was considering this function, but then it seemed like it was only
used for determing consecutive numbers like 1, 2, 3 -- not consecutive
equivalent numbers like 1, 1, 1. But is that not right?

With one argument, groupby assembles groups of equal consecutive elements:
list((key, list(group)) for key, group in groupby("AAABBC AAA")) [('A', ['A', 'A', 'A']), ('B', ['B', 'B']), ('C', ['C']), ('A', ['A', 'A', 'A'])]

With a second keyfunc argument, groupby assembles groups where keyfunc(element )
is equal for consecutive elements list((key, list(group)) for key, group in groupby("AAAaaa AAA",str.isuppe r)) [(True, ['A', 'A', 'A']), (False, ['a', 'a', 'a']), (True, ['A', 'A', 'A'])]


HTH
Michael

Apr 8 '06 #14
Gerard Flanagan wrote:
John Salerno wrote:
Michael Spencer wrote:
itertools.group by makes this very straightforward :

I was considering this function, but then it seemed like it was only
used for determing consecutive numbers like 1, 2, 3 -- not consecutive
equivalent numbers like 1, 1, 1. But is that not right?

data = [1, 1, 1, 2, 2, 3, 4, 4, 3, 2, 2, 1, 1, 2, 2,4, 2, 2]

from itertools import groupby
for k, g in groupby( data ):
print k, list(g)

1 [1, 1, 1]
2 [2, 2]
3 [3]
4 [4, 4]
3 [3]
2 [2, 2]
1 [1, 1]
2 [2, 2]
4 [4]
2 [2, 2]

for k, g in groupby( data, lambda x: x<2 ):
print k, list(g)

True [1, 1, 1]
False [2, 2, 3, 4, 4, 3, 2, 2]
True [1, 1]
False [2, 2, 4, 2, 2]

Gerard


Interesting. After following along with the doc example, it seemed like
I had to do complicated stuff with the keys parameter, and I kind of
lost track of it all.
Apr 9 '06 #15
Lonnie Princehouse wrote:
Here's my take on the thing. It only prints one term, though.

http://www.magicpeacefarm.com/lonnie...morris.py.html

(a bit too long to post)


excerpt :

def morris(seed, n):
"""..."""
if n == 1:
return seed
else:
return length_encode(m orris(seed,n-1))

What's wrong with the following ?

def morris(seed,n) :
"""..."""
for k in xrange(n-1) :
seed=length_enc ode(seed)
return seed

or even

def morris(seed,n) :
return reduce(lambda x,y:y(x),n*[length_encode],seed)

I'd defend using recursion when it allows a more concise expression of
an algorithm, but not in other cases.

Mmmhhh, btw, strangely, it looks like a hole in the library that you
can't write eg

morris= lambda seed,n: reduce(operator .__rcall__,n*[length_encode],seed)
Apr 10 '06 #16
> What's wrong with the following ?

def morris(seed,n) :
"""..."""
for k in xrange(n-1) :
seed=length_enc ode(seed)
return seed


Nothing's wrong with it.

I happen to think the recursive version is more elegant, but that's
just me ;-)

Apr 10 '06 #17
Em Seg, 2006-04-10 Ã*s 10:05 -0700, Lonnie Princehouse escreveu:
I happen to think the recursive version is more elegant, but that's
just me ;-)


It may be elegant, but it's not efficient when you talk about Python.
Method calls are expensive:

$ python2.4 -mtimeit 'pass'
10000000 loops, best of 3: 0.0585 usec per loop
$ python2.4 -mtimeit -s 'def x(): pass' 'x()'
1000000 loops, best of 3: 0.291 usec per loop
$ calc 0.291/0.0585
~4.974358974358 97435897
$ calc 0.291-0.0585
0.2325
This happens because of the dynamic nature of Python and its lack of
tail call optimization. IOW, avoid recursive methods when possible (I
usually write those for the first version of a method then rethink it
using a non-recursive approach), specially if they are part of a hot
spot.

--
Felipe.

Apr 10 '06 #18
In general, you're right - if speed is a concern, loops should be used
instead of recursion in Python when possible.

In this case, the recursive overhead is insignificant compared to the
expense of iterating over the sequence at every iteration. By the time
there are 70 stack frames of recursion (i.e. not much), the sequence is
more than 170 million elements long.

Apr 10 '06 #19

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2358
by: Wai Yip Tung | last post by:
I'm attempting to turn some process than uses callback to return result into a more user friendly generator. I'm hitting some road block so any pointer would be appriciated. Let say there is an existing method producer(x, cb). It calls the supplied cb() every time when there is data available. The definititon of cb should be: def cb(data)
5
2255
by: Jerzy Karczmarczuk | last post by:
I thought that the following sequence gl=0 def gen(x): global gl gl=x yield x s=gen(1)
11
1751
by: vbgunz | last post by:
I am afraid that this is the first time in which I would probably need something explained to me as if I were a little child. I am having a hard time getting this through my thick skull. What in the world is wrong with this!? ''' ########################################################### ''' def generatorFunction(sequence=): for item in sequence: yield item
3
3524
by: andy.leszczynski | last post by:
Hi, I might understand why this does not work, but I am not convinced it should not - following: def nnn(): print 'inside' yield 1 def nn():
4
1584
by: Kenneth McDonald | last post by:
I'm trying to write a 'flatten' generator which, when give a generator/iterator that can yield iterators, generators, and other data types, will 'flatten' everything so that it in turns yields stuff by simply yielding the instances of other types, and recursively yields the stuff yielded by the gen/iter objects. To do this, I need to determine (as fair as I can see), what are generator and iterator objects. Unfortunately: <iterator...
3
1331
by: metaperl | last post by:
For this program: def reverse(data): for index in range(len(data)-1, -1, -1): yield data r = reverse("golf") for char in r: print char
10
2446
by: AA Arens | last post by:
I do have a database with customer info in it. To avoid it will be taken out of our office, is it possible to make it not-readable after a certain period? then every let say seven days, I needs to "extend the license", so it will last another week. It consists of queries, forms, and tables, format Access 2003. Bart
3
1909
by: Dieter Maurer | last post by:
I met the following surprising behaviour .... for i in range(3): .... def gen1(): .... yield i .... yield i, gen1() .... .... 0 0 1 1
2
1157
by: psaffrey | last post by:
I'm trying to implement an interactive graph visualisation tool using matplotlib. I want to use a spring layout, where nodes repulse each other and edges act as springs to pull connected nodes together. Usually, this algorithm runs through a number of iterations of attraction/repulsion to allow the nodes to converge to suitable positions. However, rather than running all these iterations to lay out the graph and then rendering it, I...
0
9656
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9498
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10172
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9967
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8993
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7517
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5398
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4069
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.