-5
def roll(M=100,T=100,N=6):
trails=[]
N_plus_1=N+1
for m in range(M):
    collection=[random.randrange(1,N_plus_1)]
    while [sum(collection)<T]:
        collection.append(random.randrange(1,N_plus_1))
    trials.append(len(collection))
return sum(trials)/len(trials) 

why the roll function below keeps running forever and ddoesnt produce an answer. However, if i removes the square brackets from the while loop condition, then the roll function works just fine?

mezo
  • 1

3 Answers3

1

This is because the python syntax recognizes square brackets as a list. While loops have a condition which needs to be a boolean value (either True or False). When you put square brackets around the condition it is treated as a list.

>> [sum(collection) < T]
[True] # a list with True
>> sum(collection) < T
True   # a boolean
sudo97
  • 904
  • 2
  • 11
  • 22
1

If you run in python command line:

if [True]:
  print("true")

it prints: true

if [False]:
  print("true")

it prints: true

The if condition with a [False] within evaluates to true, that is why it keeps looping forever.

[False] or [True] is a list with one element.

Try:

type([False])
or
type([True])

It returns: <class 'list'>

Actually empty lists evaluate to False.

if []:
  print("true")
else:
  print("false")

prints false

0

When you do:

while [sum(collection)<T]:

You are effectively making a list containing the result of your expression which will always evaluates to True because that list will never be emptied. You need to either use (), or nothing:

while sum(collection)<T:

# Or

while (sum(collection)<T):

The second being redundant, though.

Jordan Brière
  • 1,045
  • 6
  • 8