[Tutor] Calculating and returning possible combinations ofelements from a given set

Alan Gauld alan.gauld at btinternet.com
Wed Jul 28 19:28:24 CEST 2010


"ZUXOXUS" <zuxoxus at gmail.com> wrote


> My doubt now is whether I can change the way python show the 
> combinations.

Python will display the compbinations however you tell it to.
The function generates the combinations the display is up to you.
In this case you are simply printing the results as they come.
But you can put them in a list if you prefer.

>>> prodList = []
>>> for prod in itertools.product('abc', repeat=3):
...           prodList.append(prod)
...
>>> print prodList

You can manipulate prod however you like before putting it inthe list.
Once you have the list you can sort that list to get anyorder you 
want.
And once you have your soted and formatted list you can print it out
using whatever formatting you want.

It is always good to separate the generation of data fropm the
storage of data from the display of data.

> I have checked how the function works (see below), perhaps I have to 
> just
> change couple of lines of the code and voilá, the result displayed 
> as I
> want... But unfortunately I'm too newbie for this, or this is too 
> hardcore:

Its hardly ever a good idea to modify the standard library functions.
You can write a wrapper around them if you like - and indeed thats 
normal.
But changing them is almost always a very bad  idea!

def myProduct(*args, **kwds):
     # do something with input data
     # call itertools.product(args, kwds)
     # do something with the output
     # return a result

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list