2

I have asked a similar question yesterday, I was recommended to use weights but they usually use lists, how do I do this with a dictionary? Also, other solutions are welcome!

What I want to do... I have experimented with this pattern but I would like to assign a percent of how much sign '+' will appear. Ways that I have found to do this are related to numbers and I'm having a hard time getting an idea of how to do this.

This is my code... Let's say that I want to sign '+' to appear 20% and a sign '-' to appear 80% but still to be random distribution.

from PIL import Image, ImageDraw
import operator, random

im = Image.new('RGBA', (2000, 2000), (0,0,0)) 
draw = ImageDraw.Draw(im)

operator = {
    '+': operator.add,
    '-': operator.sub
}
step = 50
w, h = im.size
for n in range (step-step,w+w,step):
    for x in range (step-step,h+h,step):
        z = random.choice(list(operator.keys()))
        line = draw.line((n+100,x,n,operator[z](x,100)), fill=(255,255,255), width=4)
im

Thanks in advance!

Firefoxer
  • 265
  • 3
  • 15

1 Answers1

1

Take a look here

In your case it's:

[z] = random.choices(list(operator.keys()), weights=[0.2, 0.8])

or

[z] = random.choices(['+', '-'], weights=[0.2, 0.8])

Note that random.choices returns a list, so I use [z] to unpack first element of that list to variable z

Alex Kosh
  • 2,206
  • 2
  • 19
  • 18