0

I'm randomly generating a tuple from a dictionary. I want to run this a random number of times, and each run should return a true or false. How do I run this randomly N times and also have a counter and print out the amount of times it's True?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Data.bond
  • 1
  • 1
  • 1
    Can you share your code for tuple generation? You want to return True or False based on what criteria? – Ssayan Feb 11 '22 at 15:51
  • Are you having trouble generating a random number? Or using that randomly-generated number in a for loop? – TylerH Feb 11 '22 at 15:51
  • Related, probably one of a couple of good duplicate targets: https://stackoverflow.com/questions/3996904/generate-random-integers-between-0-and-9 – TylerH Feb 11 '22 at 15:53

1 Answers1

0

First, you need to generate a random number within a specified number range:

n = random.randint(0, 10)

Then, you need to add a base counter from which to count onto for each of the specified True outcomes:

reds = 0
blacks = 0

When iterating with a for loop, you need to set the starting point and ending point. You were missing the starting index and a colon here. You say you want to loop a random number of times, which is where n comes into play:

for i in range(0, n):

If the conditions are met, you want to increment either the reds or blacks variable by one, so you're able to see how many of each condition were True. I'd recommend changing your operator from < or > to <= or >=. As it's written, you aren't handling the third iteration of the loop. I left it in in my example below, because I'm not sure what your desired outcome is there.

At the end, you have something like this:

    n = random.randint(0, 10)
    bag = {}
    reds = 0
    blacks = 0
    for i in range(0, n):
        if i < 3:
            bag[i] = 'red'
            reds+=1
        elif i > 3 and i < 10:
            bag[i] = 'black'
            blacks+=1

        entry_list = list(bag.items())
        random_entry = random.choice(entry_list)
        print(random_entry)
    print(reds)
    print(blacks)
(0, 'red')
(1, 'red')
(2, 'red')
(1, 'red')
(1, 'red')
(5, 'black')
(6, 'black')
(4, 'black')
(8, 'black')
3
5

If you wanted to also explicitly keep track of True and False runs for each variable, you just add a little logic for that, as such:

    blackfalse = True
    redfalse = True
    for i in range(0, n):
        if i < 3:
            bag[i] = 'red'
            reds+=1
            blackfalse = True
            redfalse = False
        elif i > 3 and i < 10:
            bag[i] = 'black'
            blacks+=1
            redfalse = True
            blackfalse = False
        print(redfalse)
        print(blackfalse)
RMA Dev
  • 166
  • 5