-1

I need to design a function that takes a list of int as a parameter and in that list we look at the last element it will have some value v, Then we take v cards from the top of the deck and put them above the bottom most card in the deck.

Here is an example:

>>> test_list = [1, 28, 3, 4, 27, 8, 7, 6, 5]
>>> insert_top_to_bottom(test_list)
>>> test_list = [8, 7, 6, 1, 28, 3, 4, 27, 5]

value = deck[-1] # value of the last element
Syed Naqi
  • 37
  • 7
  • Can you please show your code attempt for this. Please indicate which areas of your code are giving you difficultly. – idjaw Nov 15 '15 at 14:20
  • after that part I don't know how to USE the slice method to slice v items from the list. – Syed Naqi Nov 15 '15 at 14:22

2 Answers2

1

I believe this will do

def insert_top_to_bottom(test_list, v):
    return test_list[v : -1] + test_list[:v] + [test_list[-1]]

test_list = [1, 28, 3, 4, 27, 8, 7, 6, 5]
test_list = insert_top_to_bottom(test_list, 5)
print test_list
Anupam Ghosh
  • 314
  • 3
  • 10
  • thank you for the help also can you please explain little bit about the slice function in general I tried using it but wasn't able to – Syed Naqi Nov 15 '15 at 14:40
  • I thik this link will give you a good explanation http://stackoverflow.com/questions/509211/explain-pythons-slice-notation – Anupam Ghosh Nov 15 '15 at 14:47
1

Here is my attempt, though you should next time show your own attempts. Please note that I did not include any type of checking or avoiding errors. Just the basics.

def top_to_bottom(l):
    last = l[len(l)-1]
    move_these = l[:last]
    move_these.append(l[len(l)-1])
    del l[:last]
    del l[len(l)-1]
    l.extend(move_these)

I hope I could help.

EDIT

I didn't make it a one-line funtion so you can understand a bit better. Since you asked, here is some more explanaition about slicing.

my_list[x:y] is a basic slice. This will output my_list from index x to (but excluding index y).

You can leave out either, which will just fill up that part as far as possible. For example, using

my_list[:5]

will give you my_list from the beginning to (but excluding!) index 5. If the list is [0, 1, 2, 3, 4, 5, 6], it will give [0, 1, 2, 3, 4]. If you want to get a list from a certain index until the end, you leave out the 'y' part. Like so:

my_list[3:]

Applying that on the list previously stated, you will get [3, 4, 5, 6].

I hope you understood! Comment if you have any more questions.

Martijn Luyckx
  • 402
  • 2
  • 12