Home > front end >  How do I do a certain function when at least one if statement is True?
How do I do a certain function when at least one if statement is True?

Time:09-13

I trying to delete a certain elements from a list when two elements are "together" in a specific order expressed in the if statements. However, if the conditions are met, they both do the same thing, so I was wondering if there is a way to not write the same code to execute in each statement, and only do it when an if statement is met.

arr = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]
if arr[i] == "SOUTH" and arr[j] == "NORTH":
    del arr[i]
    del arr[j]
    length-=2
if arr[i] == "NORTH" and arr[j] == "SOUTH":
    del arr[i]
    del arr[j]
    length-=2
if arr[i] == "WEST" and arr[j] == "EAST":
    del arr[i]
    del arr[j]
if arr[i] == "EAST" and arr[j] == "WEST":
    del arr[i]
    del arr[j]
    length-=2

CodePudding user response:

You could combine your if statements into a single if statement with or.

a = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]
if (arr[i] == "SOUTH" and arr[j] == "NORTH") or (arr[i] == "NORTH" and arr[j] == "SOUTH") or \
    (arr[i] == "WEST" and arr[j] == "EAST") or (arr[i] == "EAST" and arr[j] == "WEST"):
    del arr[i]
    del arr[j]
    length-=2

CodePudding user response:

If my surmise is right, and you're trying to reduce a set of moves, thien this will do it:

a = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]
opposite = {"NORTH":"SOUTH","SOUTH":"NORTH","WEST":"EAST","EAST":"WEST"}
b = []
for word in a:
    if b and b[-1] == opposite[word]:
        b.pop()
    else:
        b.append(word)
print(b)

Output:

['WEST']

CodePudding user response:

You can combine the two values into a tuple, then search for that in a set of tuples.

opposites = {("NORTH", "SOUTH"), ("SOUTH", "NORTH"), ("EAST", "WEST"), ("WEST", "EAST")}
pair = (a[i], a[j])
if pair in opposites:
    del arr[i]
    del arr[j]
    length-=2
  • Related