Search code examples
pythonstringcomputer-scienceprobability

How to make a function that returns a random string based on different characters that have certain probability of being selected python


For my specific assignment, I should create a function that takes in a positive integer width and a Boolean value. The function should then return a string based on the given global variables:

      ARROWS = ‘<>^v’
      PERIOD = ‘.’
      ADDITION = ‘+’
      MULTIPLICATION = ‘X’
      RANDOM_THINGS = ‘*|’

The width integer should determine the length of the string and the Boolean value should determine whether or not the global variable RANDOM_THINGS can be used (if set to false, only use the first four variables).

So far my code accounts for this part. It is as follows:

  Def function(n, true_or_false)
     arrows = random.choice(ARROWS) #to separate the characters in the string
     list1 = (arrows, ADDITION, MULTIPLICATION, PERIOD)
     x = random.choices(list1, k =n)
     print(“”.join(x))
     

This is where the probability comes in: Each character of the string should have a 5/6 chance of being from the variables ARROWS, ADDITION or MULTIPLICATION and a 1/6 chance of being from the variable PERIOD. If the Boolean value is set to True, there should be a 50% chance that one (and only one) character in the string is replaced by a character in the RANDOM_THINGS variable.


Solution

  • from random import choice, choices
    
    ARROWS = '<>^v'
    PERIOD = '.'
    ADDITION = '+'
    MULTIPLICATION = 'X'
    RANDOM_THINGS = '*|'
    
    def function(n, maybe_replace):
        
        list1 = [None, ADDITION, MULTIPLICATION, PERIOD]
        x = []
        
        # Loop to vary the chosen arrow
        for i in range(n):
            
            # update chosen arrow and first element in list1
            list1[0] = choice(ARROWS)
           
            # divide 5/6 into three parts: 5/18 each
            # list1 probabilities: 5/18, 5/18, 5/18, 1/6
            # convert to intergers (weights): 5, 5, 5, 3
            x.append(*choices(list1, weights=[5, 5, 5, 3], k=1))
        
        if maybe_replace:
            
            position = choice(range(n))
            others = [x[position], choice(RANDOM_THINGS)]
            
            # others has two elements, so 50% prob for each...
            x[position] = choice(others)
            
        print("".join(x))