# Python – I need a Python Function that will output a random string of 4 different characters when given the desired probabilites of the characters

pythonrandom

For example,
The function could be something like def RandABCD(n, .25, .34, .25, .25):

Where n is the length of the string to be generated and the following numbers are the desired probabilities of A, B, C, D.

I would imagine this is quite simple, however i am having trouble creating a working program. Any help would be greatly appreciated.

#### Best Solution

Here's the code to select a single weighted value. You should be able to take it from here. It uses bisect and random to accomplish the work.

``````from bisect import bisect
from random import random

def WeightedABCD(*weights):
chars = 'ABCD'
breakpoints = [sum(weights[:x+1]) for x in range(4)]
return chars[bisect(breakpoints, random())]
``````

Call it like this: `WeightedABCD(.25, .34, .25, .25)`.

EDIT: Here is a version that works even if the weights don't add up to 1.0:

``````from bisect import bisect_left
from random import uniform

def WeightedABCD(*weights):
chars = 'ABCD'
breakpoints = [sum(weights[:x+1]) for x in range(4)]
return chars[bisect_left(breakpoints, uniform(0.0,breakpoints[-1]))]
``````