2
\$\begingroup\$

I currently have the following piece of code in place that attempts to find matches within a list, based on a priority system:

possible_combinations = ["ABC", "AB", "A", "D"]


if len(possible_combinations) >= 1:
    chosen_combination = [comb for comb in possible_combinations if ("A" in comb) and ("C" in comb)]
    if (len(chosen_combination) == 0):
        chosen_combination = [comb for comb in possible_combinations if ("A" in comb)]
        if (len(chosen_combination) == 0):
            chosen_combination = [comb for comb in possible_combinations if ("C" in comb)]
            if (len(chosen_combination) == 0):
                raise ValueError(f"No match found.")
                
print(chosen_combination)

['ABC']

Is there any way I could refactor this code to get rid of these if-statements, and thereby make my code look nicer?

\$\endgroup\$
1
  • 1
    \$\begingroup\$ perhaps explain why/what, there might be completely different way to solve the problem \$\endgroup\$
    – hjpotter92
    Nov 4 '20 at 17:48
3
\$\begingroup\$

You could do something like this:

possible_combinations = ["ABC", "AB", "A", "D"]
combs = [("A","C"),("A",),("C",)]

for comb in combs:
    chosen_comb = [x for x in possible_combinations if all([y in x for y in comb])]
    if len(chosen_comb) > 0:
        break

print(chosen_comb)
    
\$\endgroup\$
3
  • 4
    \$\begingroup\$ Are you sure that this: ("A","C"),("A"),("C") is your intent? The first parens make a tuple, and the second and third do not. \$\endgroup\$
    – Reinderien
    Nov 4 '20 at 18:33
  • \$\begingroup\$ It doesn't really matter here, but you are right. What I meant was [("A","C"),("A",),("C",)]. I corrected it. \$\endgroup\$
    – Tom Gebel
    Nov 4 '20 at 19:37
  • \$\begingroup\$ Looks quite nice. Thx! \$\endgroup\$ Nov 5 '20 at 8:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.