Search code examples
pythonstringrandomprobability

Insert a string within another string based with probability based on location


I'm working in Python and I would like to insert a string within another string at a random location. But I would like the choice of random location based on a probability distribution that favors certain locations more than others. Specifically, I want to insert more strings towards beginning of the original string and less towards the end.

For example, if the insertion string is "I go here" and the original string is "this is a test string and it can be long." I want to insert the insertion string at a random location in the original string. But if I do it say 100 times, I would the result "I go here this is a test string and it can be long" to be the result more number of times than "this is a test string and it can be long. I go here". I want to be able to tune the probability distribution.

Any help is appreciated.


Solution

  • You can use the random.gauss() function.
    It returns a random number with gaussian distribution.
    The function takes two parameters: mean and sigma. mean is the expected mean of the function outputs and sigma is the standard deviation- 'how far the values will be from the mean'.
    Try something like this:

    import random
    
    original_str_len = 7
    mean = 0
    sigma= original_str_len  # just an example.
    
    r = random.gauss(mean, sigma)  # random number- can be negative
    r = abs(r)
    insertion_index = int(r)
    

    Notice, this code is not perfect but the general idea should work.
    I recommend you to read more about the Gaussian Distribution.