0

In OCaml or similar language I would do something like this:

let hello a b c =
  match (a, b, c) with
    | (1, 1, 1) -> 1
    | (2, 2, 2) -> 2
    | (_, _, 3) -> 3
    | (_, _, _) -> 4

Is there a way in Python to have this? Right now I am using

if a==1 and b==1 and c==1:
  return 1
elif a==2 and b==2 and c==2:
  return 2
elif c==3:
  return 3
else:
  return 4

Is this the most idiomatic Python to achieve that?

2
  • 1
    For the triple case you can use, well, a triple! The if a == 1 and b == 1 and c == 1 becomes if (a, b, c) == (1, 1, 1) for example. Commented Jan 27, 2018 at 10:58
  • Have a look at this github repo. Commented Jan 27, 2018 at 11:11

1 Answer 1

1

As @SilverSlash mentions you can group your variables to a tuple on the fly. A way to save re-writing (a,b,c) is to use a loop, and use the variables themselves for the wildcards:

def hello (a,b,c):
    for (match,result) in (
        ((1,1,1),1),
        ((2,2,2),2),
        ...,
        ((a,b,3),3),
        ...):
        if (a,b,c) == match:
            return result
    return "elseValue"

This looks kind of like the code you're used to. I couldn't say if it's idiomatic or not, but I think it's equally OK as a standard if-else list. It's a bit of a waste of run-time doing the full list check if you just want to look at the last element, but it may not matter for many applications.

Even if you go for an if-else though, I would definitely group to tuples rather than use and between each element. That (I think - maybe a bit of an opinion based question?) is more idiomatic.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.