py itertools?
mattia
gervaz at gmail.com
Sat Dec 19 11:07:52 EST 2009
Il Sat, 19 Dec 2009 10:54:58 +0000, mattia ha scritto:
> 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?
>
> Thanks, Mattia
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")
More information about the Python-list
mailing list