Home > Net >  Is there a way to make a chain of variables, each one being dependent on the one that came before?
Is there a way to make a chain of variables, each one being dependent on the one that came before?

Time:10-19

Im triyng to make a program that takes into account the number of one variable (chosen at random) to decide the value of the next, and i need to repeat this 11 times (so n3 would depend of n2, n4 of n3, etc.) the idea would be a code like:

def rayuela_cuerpo():
    n2 = random.choice([0,1])
    if n2 == 0:
        n3 = random.choice([1,3])
        return n3
    elif n2 == 1:
        n3 = random.choice([0,2])
        return n3

    if n3 == 0 or n3 == 1:
        n4 = random.choice([1,3])
        return n4
    elif n3 == 2 or n3 == 3:
        n4 = random.choice([0,2])
        return n4 

    if n3 == 0 or n3 == 1:
        n4 = random.choice([1,3])
        return n4
    elif n3 == 2 or n3 == 3:
        n4 = random.choice([0,2])
        return n4

but that it would work.

CodePudding user response:

A way that you could do what you are saying is to do:

def random_simulation(entry_number): # generate a random number based on the input number given to the function
    if entry_number == 0:
        return random.choice([1,3]) # returns the value to where this function was called
    elif entry_number == 1:
        return random.choice([0,2]) # returns the value to where this function was called

def rayuela_cuerpo():
    origin_number = 0
    for _ in range(11): # run through the function 11 times and update the value for the next time the function is run
        origin_number = random_simulation(origin_number)
    return origin_number # return the last number to be generated from the for loop
  • Related