pythonif-statementpattern-matching

Any ways to avoid using many if statements


I just finished learning python basics from CS50 and I am now trying to make a small game program for practice. Halfway through I ran into a potential problem.

To sum the game up, it is like this:

  1. User inputs 5 numbers from 0 to 9
  2. The game is programmed with multiple fixed patterns for the 5 numbers
  3. The program determines whether the user's input matches any of the patterns or not
  4. Based on what it matches (if it does) the program gives the user a score

Example:

User's input - 1,2,3,4,5
Possible patterns - a,a+1,a+2,a+3,a+4  1 point
                  - a,a+2,a+4,a+6,a+8  2 points
                  - a,a+1,a+3,a+5,a+7  3 points

So in this case the user gets 1 point.

My current problem is, I am trying to make a lot of different patterns (Like 20), but the only way I know as of now is to use an if statement for each pattern like this:

if .....

if .....

if .....

Doing this for each pattern feels wrong. I tried searching for ways to reduce the number of if statements but methods like using jump table (dictionaries) do not seem to work here. Thanks in advance.


Solution

  • You could put your patterns and scores in lists. For example store the patterns as lambda expressions, that can be evaluated based on the input a.

    Then you can iterate over the patterns, evaluate them and compare the result with the user input.

    user_input = [12, 14, 16, 18, 20]
    a = user_input[0]
    
    # define your patterns and their scores
    patterns = [
        lambda x: [x, x + 1, x + 2, x + 3, x + 4],
        lambda x: [x, x + 2, x + 4, x + 6, x + 8],
        lambda x: [x, x + 3, x + 6, x + 9, x + 12],
    ]
    scores = [1, 2, 3]
    
    
    def compare_list(list1, list2):
        return list1 == list2
    
    
    score = 0
    for idx, pattern in enumerate(patterns):
        if compare_list(user_input, pattern(a)):
            print("Pattern found")
            score = scores[idx]
            break
    
    print(f"Score: {score}")
    

    You might need to sort the lists before checking equality, depending on the patterns you want to match.