py itertools?

mattia gervaz at gmail.com
Sun Dec 20 08:03:29 EST 2009


Il Sun, 20 Dec 2009 03:49:35 -0800, Chris Rebert ha scritto:

>> On Dec 19, 12:48 pm, Chris Rebert <c... at rebertia.com> wrote:
>>> On Sat, Dec 19, 2009 at 2:54 AM, mattia <ger... at gmail.com> wrote:
>>> > Hi all, I need to create the permutation of two strings but without
>>> > repeat the values, e.g. 'ab' for me is equal to 'ba'. Here is my
>>> > solution, but maybe the python library provides something better:
>>>
>>> >>>> def mcd(a, b):
>>> > ...     if b == 0:
>>> > ...         return a
>>> > ...     else:
>>> > ...         return mcd(b, a % b)
>>> > ...
>>> >>>> def mcm(a, b):
>>> > ...     return int((a * b) / mcd(a, b)) ...
>>> >>>> s1 = 'abc'
>>> >>>> s2 = 'wt'
>>> >>>> m = mcm(len(s1), len(s2))
>>> >>>> set(zip(s1*m, s2*m))
>>> > {('a', 'w'), ('a', 't'), ('b', 'w'), ('c', 't'), ('b', 't'), ('c',
>>> > 'w')}
>>>
>>> > Any help?
>>>
>>> Surprised you didn't think of the seemingly obvious approach:
>>>
>>> def permute_chars(one, two):
>>>     for left in set(one):
>>>         for right in set(two):
>>>             yield (left, right)
>>>
>>> >>> list(permute_chars('abc', 'wt'))
>>>
>>> [('a', 'w'), ('a', 't'), ('b', 'w'), ('b', 't'), ('c', 'w'), ('c',
>>> 't')]
> 
> On Sun, Dec 20, 2009 at 3:21 AM, Parker <xenoszh at gmail.com> wrote:
>>>>> a = 'qwerty'
>>>>> b = '^%&$#'
>>>>> c = [(x,y) for x in a for y in b]
>>>>> c
>> [('q', '^'), ('q', '%'), ('q', '&'), ('q', '$'), ('q', '#'), ('w',
>> '^'), ('w', '%'), ('w', '&'), ('w', '$'), ('w', '#'), ('e', '^'), ('e',
>> '%'), ('e', '&'), ('e', '$'), ('e', '#'), ('r', '^'), ('r', '%'), ('r',
>> '&'), ('r', '$'), ('r', '#'), ('t', '^'), ('t', '%'), ('t', '&'), ('t',
>> '$'), ('t', '#'), ('y', '^'), ('y', '%'), ('y', '&'), ('y', '$'), ('y',
>> '#')]
>>
>>
>> This one is better and simple.
> 
> But fails if either of the input strings has repeated characters.
> (Although writing it as a comprehension is indeed much briefer.)
> 
> Whether this matters, who knows, since the OP's spec for the function
> was rather vague...
> 
> Cheers,
> Chris

Having non-repeating values metter.



More information about the Python-list mailing list