10

Do you know a simpler way to achieve the same result as this? I have this code:

color1 = input("Color 1: ")
color2 = input("Color 2: ")

if ((color1=="blue" and color2=="yellow") or (color1=="yellow" and color2=="blue")):
            print("{0} + {1} = Green".format(color1, color2))

I also tried with this:

if (color1 + color2 =="blueyellow" or color1 + color2 =="yellowblue")
Mazdak
  • 105,000
  • 18
  • 159
  • 188
user2517985
  • 143
  • 1
  • 7
  • 10
    While [Code Review](http://codereview.stackexchange.com/tour) might be a good place to suggest going for this type of question, we should get out of the habit of sending question-askers over there. Please read [this](http://meta.codereview.stackexchange.com/questions/5777/a-guide-to-code-review-for-stack-overflow-users) meta post for clarification. – idjaw Sep 30 '16 at 00:23
  • 5
    Stop referring code review please. Read the links I posted in my comment on why we need to stop doing this. – idjaw Sep 30 '16 at 00:25
  • 3
    set([color1, color2]) == set(["yellow", "blue"]) – zaquest Sep 30 '16 at 00:26

2 Answers2

21

You can use sets for comparison.

Two sets are equal if and only if every element of each set is contained in the other

In [35]: color1 = "blue"

In [36]: color2 = "yellow"

In [37]: {color1, color2} == {"blue", "yellow"}
Out[37]: True

In [38]: {color2, color1} == {"blue", "yellow"}
Out[38]: True
Mazdak
  • 105,000
  • 18
  • 159
  • 188
8

Don't miss the bigger picture. Here is a better way to approach the problem in general.

What if you would define the "mixes" dictionary where you would have mixes of colors as keys and the resulting colors as values.

One idea for implementation is to use immutable by nature frozensets as mapping keys:

mixes = {
    frozenset(['blue', 'yellow']): 'green'
}

color1 = input("Color 1: ")
color2 = input("Color 2: ")

mix = frozenset([color1, color2])
if mix in mixes:
    print("{0} + {1} = {2}".format(color1, color2, mixes[mix]))

This way you may easily scale the solution up, add different mixes without having multiple if/else nested conditions.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195