I'm a beginner to Python and am teaching myself list comprehensions. I've been doing well with almost all of the for-loop code I've been translating to list comprehension, but am very stuck on what I thought was a fairly simple loop.
n = 10000
def sim(y):
count = 0
for i in range(10000):
if 0.9 <= y[i] <= 1.8:
count += 1
probability = count/10000.0
print("P(a < x <= b) : {0:8.4f}".format(probability))
print ("\t case: \n"),sim([0.25 if random() < 0.8 else 1.5 for r in range(n)])
So far I've been trying variations on the following but it's all getting errors related to the use of lists such as "'int' object is unsubscriptable" and "unsupported operand type(s) for +: 'int' and 'list'".
def sim(y):
c4 = sum([y for range(y) in range(len(y)) if 0.9 < y[i] <= 1.8])/10000
print("P(a < x <= b) : {0:8.4f}".format(c4))
The purpose is to basically take the parameter passed to sim() and iterate over the length of it while incrementing by 1 for only those values found true by the condition between 0.9 and 1.8. I'm trying to check each of the n randoms for that condition. Then sum only those that are true.
By the way, the answer should work out around 0.2 -- if you want to check it just think about 1.5 being the only way to fit between 0.9 and 1.8.
I appreciate your patience as I'm learning.