简体   繁体   中英

Python: for loop outside of while loop not working as expected

I want to get how many attempts have been made before a random value between 0 and 10 is greater than 8. I have the following code which works correctly:

import numpy as np

x = np.random.uniform(low=0, high=10, size=1)
attempt = 1

while(x < 8):
    attempt = attempt + 1
    x = np.random.uniform(low=0, high=10, size=1)

However, now I want to get the number of attempts before x was greater than 8 for the fourth time. To do this, I placed the for loop just before the while loop which becomes like this:

for i in range(0,4):
    while(x < 8):
        attempt = attempt + 1
        x = np.random.uniform(low=0, high=10, size=1)

However, this is not working as I intended it to be. Can someone help me solve this problem?

You want to get the total number of attempts needed to obtain a random number 8 in 4 consecutive trails. Try this:

>>> import numpy as np
>>> def fun():
...     x = np.random.uniform(0,10,1)
...     attempt = 1
...     while x<8:
...             attempt += 1
...             x = np.random.uniform(0,10,1)
...     return attempt 
>>> for i in range(0,4):
...     print("Trial" , i , "took" , fun(), "Attempts")

Output:

Trial 0 took 1 Attempts
Trial 1 took 1 Attempts
Trial 2 took 8 Attempts
Trial 3 took 3 Attempts

The problem is that you're not resetting your x value. So once the variable is set to a value greater than 8, you code will not enter the while loop again. You need to set x = 0 before the while loop.

You should modify your code to

for i in range(0,4):
    x = np.random.uniform(low=0, high=10, size=1)
    while(x < 8):
        attempt = attempt + 1
        x = np.random.uniform(low=0, high=10, size=1)

This would reset x before it enters into the while loop. Without this statement, your the control enters into the while loop only once.

There are many ways of doing this. The below should work...

import numpy as np

successes = 0
rolls = 0
while (successes < 4):
    x = np.random.uniform(low=0, high=10, size=1)
    rolls += 1
    if x > 8:
        successes += 1

print(rolls)

This is not a for loop case. Try this:

while x < 8 and i <= 4:
    x = np.random.uniform(low=0, high=10, size=1)
    if x>8:
        i+=1
        x=np.random.uniform(low=0, high=10, size=1)
        attempt = 1
    print(attempt, x)
    attempt = attempt + 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM