[Tutor] problem solving with lists

marcus.luetolf at bluewin.ch marcus.luetolf at bluewin.ch
Mon Apr 4 14:53:51 EDT 2022


Hello Experts,
Francesco Loffredo's solution looks very clean.
It returns 15 sublists/teams in final, but 20 are required, for each item in text has to combine with
every other item in 4 sublists/teams  5 times.
Regards, Marcus. 

-----Ursprüngliche Nachricht-----
Von: Francesco A. Loffredo <fal at libero.it> 
Gesendet: Sonntag, 3. April 2022 17:03
An: tutor at python.org; marcus.luetolf at bluewin.ch
Betreff: Re: [Tutor] problem solving with lists

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