Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have my program list every item off of a list randomly and only once

I'm trying to have a function that uses the random import to randomly select a value from the list [0, 1, 2, 3, 4, 5, 6, 7, 8], print that value, then repeat itself until all the numbers are selected. The problem I'm having is then making sure when it repeats itself it won't choose that number again. What I've tried is:

def ListArranger():
    randomPick = random.choices(list)
    if len(list) > 0:
        if list[randomPick] != " ":
            print(list[randomPick])
            list[randomPick] = " "
            ListArranger()
        else:
            ListArranger()

I run into the problem that says list indices must be integers or slices, not list. I'm assuming it's having a problem because I'm trying to set the list value to a string, but I can't figure out how to work around this

like image 849
Noah Friesen Avatar asked Nov 25 '25 15:11

Noah Friesen


2 Answers

The obvious choice that nobody seems to mention is random.sample:

def ListArranger(lst):
    return random.sample(lst, len(lst))

for pick in ListArranger(range(9)):
    print(pick)

4
0
8
1
2
3
7
6
5
like image 125
user2390182 Avatar answered Nov 27 '25 05:11

user2390182


Here is the solution:

import random

def ListArranger(list):
    if len(list) > 0:
        randomPick = random.choice(list)
        print(randomPick)
        list.remove(randomPick)
        ListArranger(list)

list = [0,1,2,3,4,5,6,7,8]
ListArranger(list)

Output:

2
8
7
1
3
4
0
5
6

This function takes a list as an argument an calls itself until the list is empty.

It removes a random element of the list in each recursive call while printing out the removed element.

like image 39
Jesus Aguas Avatar answered Nov 27 '25 03:11

Jesus Aguas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!