= ["a", 0, 0, "b", "c", 0, 0]
original_list print( move_item(original_list, 3, "left") )
Short Project 6
Move items in list
In this short programming project you will be writing a function that takes a list, and index, and a direction ("left"
or "right"
) as arguments. The goal of the function is to move the item at index to the provided direction skipping over all zeros and taking the place of another item that is not zero. If reaching the end (either left or right end) and all of the items are zero, take place of the last item.
Name the program move_item.py
. Make sure that gradescope gives you the points for passing the test cases.
Examples
['b', 0, 0, 0, 'c', 0, 0]
= ["a", 0, 0, "b", "c", 0, 0]
original_list print( move_item(original_list, 3, "right") )
['a', 0, 0, 0, 'b', 0, 0]
# call the function again
print( move_item(original_list, 4, "right") )
['a', 0, 0, 0, 0, 0, 'b']
Development Strategy
The easiest way to implement this is using two while loops (one for going to the left, another for going to the right). You have the starting point of the item you want to move (the "index"
) – you need to find out where it needs to end
.
Your first guess for the end
index should be minus one on the index
if you are going to the left
or plus one on the index
if you are going to the right
. In your while loop you need to keep subtracting one or adding one (depending on your direction) until you reach your end
destination – meaning, you skip over the zeros until you either reach the beginning of the end of the list (depending on the direction you are going) or you found an item to replace (something that is different than zero).
This section gives you a quick recap of what we covered in class or introduces any new tips or examples that might help you complete the assignment. Take a few minutes to read through it before you begin.
Lists
You can access an item in a list using an index:
= [0, 0, 2, 0, 0, 1] my_list
What’s the index for value 2
and 1
?
You can replace an item in a list using an index:
= [0, 0, 2, 0, 0, 1]
my_list 1] = 5
my_list[ my_list
[0, 5, 2, 0, 0, 1]
Lists
Here is the list:
= [0, 0, 2, 0, 0, 1] my_list
How do we move value 1
to where value 2
is, replacing 1
with zero so the list looks like this:
= [0, 0, 1, 0, 0, 0] my_list
Swapping list values
We want to go from this:
= [0, 0, 2, 0, 0, 1] my_list
To this:
= [0, 0, 1, 0, 0, 0] my_list
We do this:
= 2
index_a = 5
index_b = my_list[index_b]
my_list[index_a] = 0 my_list[index_b]