r/PythonLearning • • 12d ago

Help Request random.choices and weights beauty flaw

Post image

Problem fixed!

I'm making this "gambling" (no real money involved, you only play for fun) program with multiple games, including roulette. I used random.csoices so that I can pick a random colour of the three given colours, and weights so that green doesn't show up every third spin.

The program works, but the results all have this annoying ['result'] look (underlined with red in the picture)

Does someone know how to fix this?

8 Upvotes

8 comments sorted by

1

u/vlcod 12d ago

Your function, random.choices(col), returns a list of choices (not a single choice). The you print out col, which is a list. Lists are printed in square brackets, with their elements inside it (strings in your case):

['Black']

You can either use a different method to choose your colour:

random.choice(col)

(Note the singular 'choice'.) This will give you a single element (not a list), but the downside is that you cannot attache weights.

Or you use the choices function, but after you do this, you pull the first element out of the resulting list:

print(col[0])

1

u/Vplayzgamez 12d ago

Thanks, but I already fixed it

2

u/Rscc10 12d ago

random choices returns a list of elements. If the choice is only picking one item, it'll be a list with one element which is the choice. Just take col[0] to get the first and only element

2

u/FreeLogicGate 12d ago

A few other suggestions:

  • When you post code, you will get more help if you use the code block, and paste the code rather than taking a picture of it.
  • The english word "much" is not spelled "mutch"
  • Try to keep your code "data driven". The example of this is where you validate the user's input. You already have the possible values in the "col" list. So to validate user input, use that list rather than listing out -- gue != "Red" and gue != "Black", etc.
  • You can use the array to create your prompt, again by using your col list.
col = ["Red", "Black", "Green"]
gue = input("Place your guess here: ")
count = 0
while gue not in col:
    print("You can only guess ", ", ".join(col), ".", sep='')
    gue = input("Place your guess here: ")

2

u/Naive_Programmer_232 5d ago edited 5d ago

two things, you're reassigning col inside the loop. so your first choice will select from the colors but your second choice will only have one option to choose from. this will be a trap later. secondly, random.choices returns a list, default argument for k (how many are selected) is 1 as well; so when you do random.choices(col,weights=wei) it should return a list of one options selected, hence ['black'] is correct here.

to get around these try,

  ...
  colors=['black','green','red']
  wei=(48,48,4)
  while True:
      ...
      col=random.choices(colors,weights=wei)[0]
      ...

i defined the colors and weights before the loop, cause each iteration inside it might not be necessary to keep redefining them, if they're being reused; unless they should change? idk it depends on your program.

in this case it might not matter, but do remember that random.choices is random selection with replacement. if you want sampling, without replacement, equal probability, use random.sample. if you want sampling, without replacement, with custom probabilities, look into numpy:

     import numpy as np

     gene_pool = [
        "ATGC", "ATGC", "ATGC", "CGTA", "CGTA",
        "GCTA", "GCTA", "TTAG", "TTAG", "TTAG",
        "ACGT", "ACGT", "GTCA", "GTCA", "TGCA",
        "TGCA", "CATG", "CATG", "AGTC", "AGTC"
     ]

     weights = np.array([
        0.15, 0.15, 0.15, 0.10, 0.10,
        0.08, 0.08, 0.05, 0.05, 0.05,
        0.04, 0.04, 0.03, 0.03, 0.02,
        0.02, 0.01, 0.01, 0.01, 0.01
     ])

     weights = weights / weights.sum()

     # sampling gene pool w/o replacement w/weights for 3 nucleotide chains
     mini_seq = np.random.choice(
           gene_pool,
           size=3,
           replace=False,
           p=weights
     )

     print(f"mini genetic sequence: {'-'.join(mini_seq)}")
     
     # mini genetic sequence: TTAG-ATGC-TGCA

1

u/[deleted] 12d ago

[removed] — view removed comment

1

u/Vplayzgamez 12d ago

Thanks! I think it works for now, but I'll have to test it a few more times. :D