mercredi 4 septembre 2019

How to change if-elif into a dictionary with logical expressions as keys (in Python)

I'm trying to optimize my code buy using dictionaries instead of if-elif statements.

I've read that you can optimize code by using dictionaries instead of if-elif statements, but I don't know how to do that. I'd like to use the logical expressions below somehow in the dictionary. (The code iterates through a and b)

    if a == b: 
        return 6
    elif (a%n == 0, a != n**2, b == a + 1) == (True, True, True):
        return 0 
    elif ((a-1)%n == 0, (a-1) != n**2, b == a - 1) == (True, True, True):
        return 0
    elif (a%n == 0, b == a-(n-1)) == (True, True):
        return 1
    elif (b%n == 0, a == b-(n-1)) == (True, True):
        return 1 
    elif abs(a-b) == 1:
        return 1
    elif abs(a-b) == n:
        return 1
    else:
        return 0

Aucun commentaire:

Enregistrer un commentaire