0

I want to find a way to make it more efficient to check whether an input is = to one number or another, but the only way i've learnt and can see is using nested if's in python.

def menu():
    while type(x) != int or x < 0 or x > 46:
        try:
            x = int(input("\nEnter a valid menu choice: "))
        except:
            print("\nInvalid input...\n")
    if x == 1:
        max1()
    elif x == 2:

    elif x == 3:

    elif x == 4:

This is my code design for a simple menu function to call upon other functions with a user's input, however i need 46 more if x == n.

Is there a faster way than doing an elif x == n+1 every line?

2
  • There are other options, such as a dispatch dict (constructed outside the function if you really need it to be efficient), but it seems to me like the 46-item menu might be a deeper problem. Commented Oct 28, 2016 at 19:32
  • The "best" solution depends on how different the menu items are from one another Commented Oct 28, 2016 at 19:32

3 Answers 3

2

Use a dictionary to hold the references to the functions, then use x to get the right function, then call it:

{1: max1, 2: whatever, 3: something_else}[x]()

In this case you're selecting the right function with an integer, so you could also use a list:

[max1, whatever, something_else][x-1]()

But I prefer the dictionary because it is easier to read: you can easily find the function associated with 13 if you need to change it.

N.B. there are no "nested ifs" in your code.

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

Comments

1

Use a dictionary of integers to functions:

function_mapping = {
    1: max1,
    2: max2,
    ...
    n: maxn
}

function_mapping[x]()

If your functions are named this way, there are "hackish" ways of constructing this dictionary, e.g.

function_mapping = {i: globals()['max' + str(i)] for i in range(1,n+1)}

Comments

0

If none of these branches can be abstracted/combined, something like this could be useful:

def max1():
  pass # your block body

def error():
  pass # handle lookup failure

{1:max1
,2:...
}.get(x,error)()

Python dictionaries should be hashmaps so the lookup should be roughly constant time, especially for integer keys.

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.