n00bprogrammer22 - 5 months ago 22

Python Question

A random character is instructed to move 1 position left or right if this is possible and return True and if it isn't possible then return False.

Example:

`#Input:`

[['.', 'B', 'B', '.', '.', '.']]

move_sideways("B", "RIGHT", lot0)

#Output:

True

[['.', '.', 'B', 'B', '.', '.']]

So it was possible for both B's to move to the right one position. If one of the B's was in the first position and was instructed to move left it would return False because this would be impossible. Same if the B was in the last position and instructed to move right.

This is my code so far but I really can't figure out how to accomplish this. Maybe I would use pop

def move_sideways(symbol, direction, lst):

`for symbol in range(len(lst))`

lst[1:] + lst[:1]

return lst

Answer

This may not be the most efficient way to do it but it works. I'm happy to answer any questions about it but I'm going to bed soon.

```
def move_sideways(symbol, direction, lst):
if symbol not in lst:
print('symbol is not in list')
return False
ind = [i for i, x in enumerate(lst) if x == symbol] #retunrs a list of the index of every symbol in list [1,2] in given example
if direction == 'RIGHT':
if ind[-1]+1 == len(lst): #check to see if the right most move will go out of the list
return False
for x in ind[::-1]:
lst.insert(x+1,lst.pop(x)) #this will pop out every symbol and insert them back in one to the right
if direction == 'LEFT':
if ind[0] == 0: #checks if the left most symbol is at 0
return False
for x in ind:
lst.insert(x-1,lst.pop(x)) #this will pop out every symbol and insert them back in one to the left
return(True,lst) #return the new list and a True in a tuplit
```

.

```
>>> a = [['.', 'B', 'B', '.', '.']]
>>> print(move_sideways('B', 'RIGHT', a[0]))
(True, ['.', '.', 'B', 'B', '.'])
>>> a = [['.', 'B', 'B', '.', 'B']]
>>> print(move_sideways('B', 'RIGHT', a[0]))
False
```