0

I have this code:

import random

dominos_set = [[i, n] for i in range(0, 7) for n in range(0, 7) if i >= n]
stock = random.choices(dominos_set, k = 14)

for i in stock:
    for n in dominos_set:
        if n == i:
            dominos_set.remove(i)

print(dominos_set)

What I want to do:

  1. I create 26 elements in dominos_set
  2. I took 14 random elements from dominos_set (stock)
  3. I want to remove 14 elements from dominos_set which I pointed in stock.

The problem is that every output of dominos_set is different every time in output: 18, 20, 14 and so on. I cant understand why is it happening? Can someone explain we what is not right?

AlexK
  • 2,855
  • 9
  • 16
  • 27
  • 2
    Does this answer your question? [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – 001 Aug 09 '22 at 21:42
  • You don't need that inner loop at all. You KNOW that all of your choices are in the set. Just do `for i in stock:` / `dominos_set(remove(i))`. Or, even simpler, `dominos_set -= set(stock)`. Sets support set subtraction. – Tim Roberts Aug 09 '22 at 21:43
  • 2
    The real answer to your question is that `random.choices` does not guarantee 14 DIFFERENT choices. You're getting duplicates. A better way to do what you're doing is to use `random.shuffle` and then pull the top 14 items. – Tim Roberts Aug 09 '22 at 21:49
  • @Tim Roberts, `for i in stock: dominos_set.remove(i)` this one doesnt work. You mean I should format dominos_set as set and stock also? – Breathe of fate Aug 09 '22 at 21:56
  • @Tim Roberts, thats clear now, thanx. How can I use random.shuffle for 14 elements? – Breathe of fate Aug 09 '22 at 22:00
  • You `random.shuffle` the entire list, then grab `dominos_set[:14]`, or use `.pop(0)` to pop 14 off the top. And I'm sorry, when I read your code, I thought you were already using a set, not a list. That's why my comments seemed like garbage. – Tim Roberts Aug 09 '22 at 22:06

1 Answers1

0
import random

dominos_set = [[i, n] for i in range(0, 7) for n in range(0, 7) if i >= n]
random.shuffle(dominos_set)
stock = dominos_set[:14]
players_set = [dominos_set.remove(n) for i in stock for n in dominos_set if i == n]

this will be the best solution. thanx @Tim Roberts

  • 1
    The `.remove()` method returns `None`, so currently you'll end up with a list of `None`'s for `players_set`. If you just want to remove the `stock` list items from `dominos_set`, you can use list comprehension: `dominos_set = [elem for elem in dominos_set if elem not in stock]`. – AlexK Aug 10 '22 at 04:36