Yazan Al Hariri
Yazan Al Hariri

Reputation: 11

How to use match case for list with a specific element in an arbitrary index?

I am making a simple math interpreter in python. The program converts the math string to a list of numbers and operations which is then evaluated using match case.

I want to do something like this:

c = ['12', '-', '24', '/', '6', '+', '7']
match c:
    case [*before_div, '/', *after_div]:
        ...

The other option would be matching against the general case and trying to find this character to split the list at its index. Like this:

match c:
    case [*_]:
    try:
        i = c.index("/")
        before_div, after_div = c[:i], c[i+1:]
        ...
    except ValueError:
        pass

But this could end the matching without successfully processing anything.

Upvotes: 0

Views: 33

Answers (1)

olives
olives

Reputation: 98

How about using a parsing function and matching on the return value? For example:

def get_operator(token_list):
    if '/' in token_list:
        return '/'
    ...
    return 'NUM'  # 'NUM' means numeric token 

match get_operator(c):
    case '/':
        i = c.index("/")
        before_div, after_div = c[:i], c[i+1:]
        ...
    case "NUM":
        return c[0]

Upvotes: 0

Related Questions