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?

asked Nov 4, 2020 at 17:22
\$\endgroup\$
1
  • 1
    \$\begingroup\$ perhaps explain why/what, there might be completely different way to solve the problem \$\endgroup\$ Commented Nov 4, 2020 at 17:48

1 Answer 1

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)
 
answered Nov 4, 2020 at 18:01
\$\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\$ Commented Nov 4, 2020 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\$ Commented Nov 4, 2020 at 19:37
  • \$\begingroup\$ Looks quite nice. Thx! \$\endgroup\$ Commented Nov 5, 2020 at 8:39

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.