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.
CodePudding user response:
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)
# 5/6 is 5 times greater than 1/6
# so use 5 and 1 at probability weights
x.append(*choices(list1, weights=[5, 5, 5, 1], 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))
CodePudding user response:
Do you mean this?
def function(n, includeothers = False):
alphabet = ARROWS PERIOD ADDITION MULTIPLICATION
if includeothers:
alphabet = RANDOM_THINGS
x = random.choices(alphabet, k =n)
print(“”.join(x))
Did you want all of the ARROWS in the list of options? What you had would only include ONE if the ARROWS and ignore the rest.