>>> 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?
Thanks, Mattia
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')]
Cheers,
Chris
--
http://blog.rebertia.com
even less work:
import itertools
print set(itertools.product('abc', 'wt'))
but neither of those two solves the OP's problem. And neither the OP's
own solution solves his own problem (per my understanding from his
description).
what he wanted was something like:
print set(tuple(sorted(x)) for x in itertools.product(s1, s2))
or, just for some functional fun, when written in point-free form:
from itertools import product
from functools import partial
def compose(f, g):
return lambda *a, **k: f(g(*a, **k))
sortedtuple = compose(tuple, sorted)
setcomp = compose(set, map)
unique_tuples = partial(setcomp, sortedtuple)
permute_chars = compose(unique_tuples, product)
print permute_chars(s1, s2)
Well, this is the code I'm using:
import itertools
def cheapest_travel(l):
"""Given a list of departure and return dates, return the cheapest
solution"""
s = set(itertools.permute(l[0], l[1]))
return sorted(t, key = lambda s: s[0][2] + s[1][2])
# example using a dict
d = {
'2009/12/21' : [[('d', 1, 2), ('d', 3, 4), ('d', 2, 3)], [('r', 3,
5), ('r', 3, 8)]],
'2009/12/19' : [[('d', 1, 2), ('d', 2, 3)], [('r', 1, 4), ('r', 6,
4), ('r', 3, 5), ('r', 3, 8)]],
'2009/12/23' : [[('d', 2, 5), ('d', 2, 4)], [('r', 4, 5)]],
'2009/12/26' : [[('d', 2, 5), ('d', 1, 4)], [('r', 3, 6)]],
'2009/12/28' : [[('d', 2, 5)], [('r', 4, 4)]]
}
for k, v in d.items():
print(k)
res = cheapest_travel(v)
for x in res:
print(x[0], "-->", x[1], "cost", x[0][2] + x[1][2], "EUR")
This one is better and simple.
On Sun, Dec 20, 2009 at 3:21 AM, Parker <xen...@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...
Having non-repeating values metter.