1
import random

def Calculate_Pi(total):
    inside = 0
    for i in range(0, total):
        x2 = random.random() ** 2
        y2 = random.random() ** 2
        if x2 + y2 <= 1.0:
            inside += 1
    pi = (float(inside) / total) * 4
    return pi

I want to change this def by using lambda

import random as r

total = int(input("total : "))
pi = lambda inside : float(len([x for x in range(total) if r.random()**2 + r.random()**2 <= 1.0]) / total) * 4
print(pi(total))

this is my code but i don't know this is right and i want to know any better code

윤희제
  • 13
  • 3

1 Answers1

1

Not sure why you want this but you can do it this way

calculate_pi = lambda total:(sum(((random.random()**2) + (random.random()**2)) <=1.0 for _ in range(total)) / total) * 4

print(calculate_pi(5)) # 3.2
python_user
  • 5,375
  • 2
  • 13
  • 32
  • ~~~((random.random()**2) + (random.random()**2)) <=1.0~~~ Only when here is true ~~~for _ in range(total)~~~ here is work? – 윤희제 Mar 16 '21 at 12:17
  • `((random.random()**2) + (random.random()**2)) <=1.0` this results to `True` or `False`, in python you can add `True` and `False`, `True` = `1` and `False` = `0` @윤희제 – python_user Mar 16 '21 at 12:57