kung.lao
kung.lao

Reputation: 25

pythonic way to use circular list

I have have a list, for example:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

The user has say a number, for example 16. Then the program needs to give back the number at the '16th' position, here 6. So if the number is bigger than the length of the list, you have to continue counting at the beginning of the list. After that element has been printed, it has to be removed from the list. Then the user has to chose a new number to do this proces again, but the program needs to start counting from the position where it ended. If the chosen number is 7, you need to add 7 positions starting from position 6. This proces has to be repeated on the new list until it is empty.

This is what i have so far.

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
i = 0
position = 0

while i < len(my_list):
    position += number
    print(my_list[position])
    my_list.pop(position)
    i += 1
    number = int(input())

The problem is main problem is to find a good way to print the number with a certain position in the list.

Upvotes: 1

Views: 158

Answers (2)

Laughing Man
Laughing Man

Reputation: 111

i think if you want the 16th item it would be 7? 0 indexes and all that. If thats the case then i think this is a nice simple solution:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
while(len(my_list) > 1):
    number = int(input("number:"))
    index = 0;
    number += index
    while(number >= len(my_list)):
        number = number % len(my_list)
    index = number
    print(my_list[number])
    my_list.pop(index)

If you really did want the number 6 then just adjusting the numbering by 1 would work fine. Obviously this could be improved in many ways. I would reccomend that you go with the solution presented by @Blckknght which is more concise and avoids mutation.

Upvotes: 1

Blckknght
Blckknght

Reputation: 104712

The other answer works just fine, but here's an alternative solution that's a bit more concise. Rather than using list.pop to remove an item from the middle of the list (and then needing to keep track of where we removed it from), this code instead rebuilds the list after each lookup with two slice operations, so that the item after the one we removed will be at the start of the list. As a nice side effect, we no longer mutate the initial list.

my_list = list(range(1, 11))
while my_list:  # no need for len(lst) > 0 here, list are falsey when empty
    index = int(input()) % len(my_list)  # get index from the user, wrap if necessary
    print(my_list[index])                # print out the value at the requested index
    my_list = my_list[index+1:] + my_list[:index]  # rebuild the list without that value

Upvotes: 1

Related Questions