[Tutor] problem solving with lists
Francesco A. Loffredo
fal at libero.it
Sun Apr 3 11:03:03 EDT 2022
My two cents:
I tried to solve the problem Marcus proposed, and I think the following
little functions can help.
###################################################
from itertools import combinations
def pairs(seq):
"""
returns all groups of two elements that can be found in seq
"""
seen = set()
for elem in combinations(seq, 2):
seen.add(elem)
seen.add(tuple(reversed(elem)))
return seen
def combi(seq, n, seen=None):
"""
returns all n-tuples taken from the sequence seq, such that no tuple
contains a pair of elements already present in another tuple
(Marcus Luetolf problem)
"""
if seen is None:
seen = set()
res = list()
for elem in combinations(seq, n):
couples = pairs(elem)
if any([x in seen for x in couples]):
continue
else:
seen = seen.union(couples)
res.append(elem)
return res, seen
if __name__ == "__main__":
already = set()
text = "abcdefghijklmnop"
final = list()
final, already = combi(text, 4)
print(final)
######################################################
Let me know if I correctly understood the problem.
Hope this helps
Francesco
More information about the Tutor
mailing list