Issue
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
Solution
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']
Answered By - Tim Roberts
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.