473,786 Members | 2,462 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Itertools question: how to call a function n times?

I want to write a function that each time it gets called, it returns a
random choice of 1 to 5 words from a list of words.

I can write this easily using for loops and random.choice(w ordlist) and
random.randint( 1, 5).

But I want to know how to do this using itertools, since I don't like
manually doing stuff like:

phrase = list()
for i in random.randint( 1, 5):

phrase.append(r andom.choice(wo rdlist))

It just seems slow.

All advice welcome.

TIA

Matt

--
A better way of running series of SAS programs:
http://tplus1.com/wilsonwiki/SasAndMakefiles
Jul 19 '07 #1
4 6790
Matthew Wilson a écrit :
I want to write a function that each time it gets called, it returns a
random choice of 1 to 5 words from a list of words.

I can write this easily using for loops and random.choice(w ordlist) and
random.randint( 1, 5).

But I want to know how to do this using itertools, since I don't like
manually doing stuff like:

phrase = list()
for i in random.randint( 1, 5):

phrase.append(r andom.choice(wo rdlist))
what's wrong with:

phrases = [random.choice(w ordList) for i in random.randint( 1, 5)]

Jul 19 '07 #2
Matthew Wilson wrote:
I want to write a function that each time it gets called, it returns a
random choice of 1 to 5 words from a list of words.

I can write this easily using for loops and random.choice(w ordlist) and
random.randint( 1, 5).

But I want to know how to do this using itertools, since I don't like
manually doing stuff like:

phrase = list()
for i in random.randint( 1, 5):

phrase.append(r andom.choice(wo rdlist))
Use list comprehension:

phrase = [random.choice(w ordlist) for i in xrange(random.r andint(1, 5))]

w.
Jul 19 '07 #3
Matthew Wilson schrieb:
I want to write a function that each time it gets called, it returns a
random choice of 1 to 5 words from a list of words.

I can write this easily using for loops and random.choice(w ordlist) and
random.randint( 1, 5).

But I want to know how to do this using itertools, since I don't like
manually doing stuff like:

phrase = list()
for i in random.randint( 1, 5):

phrase.append(r andom.choice(wo rdlist))

It just seems slow.

All advice welcome.

TIA

Matt
You could do it either using the previously suggested list comprehension
way or, if you don't need to have all choices in memory at once, use
generator expressions. They're basically like list comprehensions,
except that you wrap them into parentheses (), not brackets [].

phrase = (random.choice( wordlist) for i in xrange(random.r andint(1, 5)))

You loose the ability to slice it directly (eg. phrase[3]), though. (See
itertools.islic e for a way to do it.)

HTH,
Stargaming
Jul 19 '07 #4
On Jul 19, 8:35 am, Matthew Wilson <m...@tplus1.co mwrote:
I want to write a function that each time it gets called, it returns a
random choice of 1 to 5 words from a list of words.

I can write this easily using for loops and random.choice(w ordlist) and
random.randint( 1, 5).

But I want to know how to do this using itertools, since I don't like
manually doing stuff like:

phrase = list()
for i in random.randint( 1, 5):

phrase.append(r andom.choice(wo rdlist))
All the previous suggestions in this thread are good. If you *must*
use itertools, you can use the itertools.repea t function to return an
object x many times:

phrase = [somewords(wordl ist) for somewords in
itertools.repea t(random.choice , random.randint( 1, 5))]
Hope it helps,
John

Jul 19 '07 #5

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

Similar topics

6
1741
by: Robert Brewer | last post by:
def warehouse(stock, factory=None): """warehouse(stock, factory=None) -> iavailable, iremainder. Iterate over stock, yielding each value. Once the 'stock' sequence is exhausted, the factory function (or any callable, such as a class) is called to produce a new valid object upon each subsequent call to next().
1
3792
by: Steven Bethard | last post by:
Is there a reason that itertools.islice doesn't support None arguments for start and step? This would be handy for use with slice objects: >>> r = range(20) >>> s1 = slice(2, 10, 2) >>> s2 = slice(2, 10) >>> s3 = slice(10) >>> list(itertools.islice(r, s1.start, s1.stop, s1.step)) >>> list(itertools.islice(r, s2.start, s2.stop, s2.step))
18
2633
by: Ville Vainio | last post by:
For quick-and-dirty stuff, it's often convenient to flatten a sequence (which perl does, surprise surprise, by default): ]]] -> One such implementation is at http://aspn.activestate.com/ASPN/Mail/Message/python-tutor/2302348
21
2187
by: Steven Bethard | last post by:
Jack Diederich wrote: > > itertools to iter transition, huh? I slipped that one in, I mentioned > it to Raymond at PyCon and he didn't flinch. It would be nice not to > have to sprinkle 'import itertools as it' in code. iter could also > become a type wrapper instead of a function, so an iter instance could > be a wrapper that figures out whether to call .next or __getitem__ > depending on it's argument. > for item in...
41
2681
by: rurpy | last post by:
The code below should be pretty self-explanatory. I want to read two files in parallel, so that I can print corresponding lines from each, side by side. itertools.izip() seems the obvious way to do this. izip() will stop interating when it reaches the end of the shortest file. I don't know how to tell which file was exhausted so I just try printing them both. The exhausted one will generate a
23
1470
by: Mathias Panzenboeck | last post by:
I wrote a few functions which IMHO are missing in python(s itertools). You can download them here: http://sourceforge.net/project/showfiles.php?group_id=165721&package_id=212104 A short description to all the functions: icmp(iterable1, iterable2) -integer Return negative if iterable1 < iterable2, zero if iterable1 == iterable1,
13
4589
by: 7stud | last post by:
Bejeezus. The description of groupby in the docs is a poster child for why the docs need user comments. Can someone explain to me in what sense the name 'uniquekeys' is used this example: import itertools mylist = def isString(x):
17
7702
by: Raymond Hettinger | last post by:
I'm considering deprecating these two functions and would like some feedback from the community or from people who have a background in functional programming. * I'm concerned that use cases for the two functions are uncommon and can obscure code rather than clarify it. * I originally added them to itertools because they were found in other functional languages and because it seemed like they would serve basic building blocks in...
4
3303
by: Mensanator | last post by:
With the new functions added to itertools in Python 2.6, I can finally get rid of this monstrosity: def ooloop6(a, n, perm=True, repl=True): if (not repl) and (n>len(a)): return r0 = range(n) r1 = r0 if perm and repl: # ok v = ','.join() f = ' '.join()
0
9647
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
9496
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
10164
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...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9961
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
8989
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
7512
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
5397
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...
2
3669
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.