Reputation: 60
This is the body of a function that takes an array of directions such as ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]
and shortens it, so opposite directions that are immediately after one another are removed. This example array should return only ["WEST"]
.
The problem is that the code works for most cases, but sometimes it throws a TypeError: sequence item 0: expected str instance, int found
. I can't see the exact case which causes the problem, and i can't figure out how to solve it.
(Problem is on CodeWars: https://www.codewars.com/kata/directions-reduction)
for index in range(len(arr)):
if arr[index]=="NORTH": arr[index]=1
if arr[index]=="SOUTH":arr[index]=-1
if arr[index]=="EAST": arr[index]=2
if arr[index]=="WEST": arr[index]=-2
def nulandrem(array):
count=len(array)
for index1 in range(0,count-1):
if array[index1]+array[index1+1]==0:
array[index1]=0
array[index1+1]=0
newarr=[]
for item in array:
if item!=0:
newarr.append(item)
return newarr
arr=nulandrem(arr)
while arr!=nulandrem(arr):
arr=nulandrem(arr)
for index3 in range(len(arr)):
if arr[index3]==1: arr[index3]="NORTH"
if arr[index3]==-1: arr[index3]="SOUTH"
if arr[index3]==2: arr[index3]="EAST"
if arr[index3]==-2: arr[index3]="WEST"
return arr
Upvotes: 1
Views: 443
Reputation: 2035
You are modifying the list given to your function. Their checking code expects that it stays the same, i.e. contains the strings; but the first thing you do is replacing strings with numbers (and no, you do not change it back in the same list). When the checking code tries to do something with the original list, it throws the exception you see (so it's not from your code).
The problem is easily fixable by making a copy of the given list first. Insert the following as the first line of your code:
arr = arr[:]
and it will work.
Saying that I must notice that the task is too difficult for you. You had written a very complicated and error-prone solution; you surely have to practice on simpler exercises first.
Edit to illustrate what I mean, here's the solution which passes the tests at codewars:
def dirReduc(arr):
opposite = {"NORTH": "SOUTH", "SOUTH": "NORTH", "EAST": "WEST", "WEST": "EAST"}
stack = []
for elt in arr:
if len(stack) and opposite[elt] == stack[-1]:
stack.pop()
else:
stack.append(elt)
return stack
Upvotes: 1