2

I've spent the last few hours trying to figure how to do something relatively simple- i'd like to write a python script that returns a number of strings from a predefined alphabet using certain weights. So for example

strings = 3
length= 4 
alphabet = list('QWER')
weights=[0.0, 0.0, 0.0, 1.0]

this would return

RRRR RRRR RRRR 

or another example

strings = 2
length= 3 
alphabet = list('ABC')
weights=[0.3,0.3,0.3]

This would return

CBA ABC CAA

I've tried playing around with a number of example codes and this is the closest i've come-

import random

import numpy as np

LENGTH = 3
NO_CODES = 100

alphabet = list('ABCD')
weights=[0.0, 0.0, 0.0, 1.0]
np_alphabet = np.array(alphabet, dtype="|U1")
np_codes = np.random.choice(np_alphabet, [NO_CODES, LENGTH])
codes = ["".join(np_codes[i]) for i in range(len(np_codes))]
print(codes)

However, i know i'm not using the weight function correctly. If anyone can tell me what i'm doing wrong or suggest a better way to do it, that would be appreciated. As i'm sure you can tell i don't really know what i'm doing, so any advice would be useful.

Amy D3
  • 43
  • 4

2 Answers2

0

SO thank you for the suggestions, i manged to puzzle through it-

import random

for i in range(100): #number of strings

    a = random.choices(["A", "B", "C"], [0.5, 0.5, 0.0], k=100) #weights of strings

    random_sequence=''

    for i in range(0,5): #length of string
     random_sequence+=random.choice(a)

    print(random_sequence)
Amy D3
  • 43
  • 4
-1

As of Python 3.6, there's a built-in method for this, random.choices(). Here's a working example with output.

import random

strings = 2
length= 3 
alphabet = list('ABC')
weights=[0.3,0.3,0.3]

for i in range(10):
    print(random.choices(alphabet, weights, k=len(alphabet)))
Sam Morgan
  • 2,445
  • 1
  • 16
  • 25
  • Hi, thanks so much for getting back to me but the weights don't seem to work? – Amy D3 Jul 24 '20 at 17:21
  • I don't see why they wouldn't? This is working perfectly for me, exactly as expected. I get a random list of characters from the code above with equal weight. If I change the first weight to 0, A is omitted. What behavior are you seeing? – Sam Morgan Jul 24 '20 at 18:24