DEV Community

Cover image for For all the Developers! πŸπŸ’» | The Best Interview Coding Question πŸš€πŸ€–
Arjun Vijay Prakash
Arjun Vijay Prakash

Posted on

For all the Developers! πŸπŸ’» | The Best Interview Coding Question πŸš€πŸ€–

Question

Given Python's random() function that returns a random value between 0 and 1.

Approximate Ο€ using this function.

Hello everyone! I've got an intriguing question for you today. With Python's random function that generates values between 0 and 1, can you estimate the value of Ο€? It might seem challenging initially, but there's a clever and fascinating method to achieve it. If you're up for the challenge, put this article on hold and dive right in!

Let's get started!

Step-by-Step Solution

For the solution, let's look at this circle with a radius of 1 and the surrounding square with a side length of 2.

Image

More precisely, our focus is on the top right quadrant of this square. Inside this top right quadrant, we can place some random points using a random function. They will look like this, for example. So, I just used the random function to generate x and y coordinates between 0 and 1.

Image

Now, we can mark those points with two colours. The yellow points are inside the circle, and the blue points are outside of the circle.

Image

If we now mark those two areas, we can see an approximation that will give us an approximation of Ο€. This approximation is given as follows:

Image

Image

First of all, the yellow area is a quarter of the whole circle, so we have the area as Ο€ times r squared divided by four, and because r is one in our case, we just have Ο€ divided by four. The green area, on the other hand, is just a square with a side length of one, so the area is 1.

Image

Now, let's use our values and substitute them in the approximation above, which will give us the approximate value of Ο€:

Image

When we write a program to calculate this, we already have the number of all points, and the only question is, what is the number of yellow points?

So, how many yellow points are there? To get this number, we can use the following condition: the distance of the yellow points to the centre of the circle must be less than one. When this condition is met, the point is yellow and inside the circle. If the distance is greater than one, the point will be blue and outside of the circle.

Image

Now, we have everything together to write our code.

One-Page Solution

Image

Source Code

The source code is given below!

# Estimating Pi using Python

import random

def estimate_pi(n):
    numPointCircle = 0
    numPointTotal = 0

    for i in range(n):
        x = random.uniform(0, 1)
        y = random.uniform(0, 1)

        distance = x**2 + y**2

        if distance <= 1:
            numPointCircle += 1
        numPointTotal += 1

    return 4 * numPointCircle/numPointTotal

numOfPoints = int(input("Enter the number of points: "))

print(f"Pi estimate with number of points in the circle as {numOfPoints} = " + str(estimate_pi(numOfPoints)))
Enter fullscreen mode Exit fullscreen mode

Give it a star 🌟

Comments in code? Nah, I prefer leaving cryptic messages for future archaeologists to decipher. πŸ‘»πŸ˜‚

Thanks for 7753!

Top comments (6)

Collapse
 
budgiewatts profile image
John Watts

This is a terrible coding interview question. It simply tests whether the developer knows this technique to estimate pi; it tells you little or nothing about how they approach the sort of tasks they'll be working on in the actual job they're being interviewed for.

The correct answer to the question is "No, I'll use math.pi instead thank you very much". You should probably thank them for their time and cut the interview short after that.

Collapse
 
arjuncodess profile image
Arjun Vijay Prakash

Hey!

I suppose you didn't read the question, didn't you? It said:
"Given Python's random() function that returns a random value between 0 and 1. Approximate Ο€ using this function."
It is written straightforwardly that we have to use the random() function to approximate pi.

Thanks!

Collapse
 
budgiewatts profile image
John Watts

You didn't read my answer did you? It is a terrible coding interview question. If you don't know the maths you're not going to figure out the algorithm so you're not testing somebody's ability to write useful code, you're testing their ability to figure out maths problems. If I interview someone for a job, I want someone who re-uses code instead of reinventing the wheel. You have said in your title "The Best Interview Coding Question" but it's a terrible question for an interview. It tells you nothing useful about the candidate. If your title was "Here's a cool way to approximate Pi" if have thought "yes, that's cool" but you didn't, you said it was a good interview question and it's not. It's just not a good interview question. A good interview question demonstrates how someone approaches solving problems, it tests their communication skills, it gives them a chance to show how they express their ideas in code, gives them an opportunity to show how they write tests. This just shows whether they know some maths that's interesting but ultimately useless for average everyday coding in almost every job. A question that invites the candidate to either implement their own algorithm or use one provided by the language or framework is a good question that gives you some idea about how well the candidate can approach coding for a job. It's almost a trick question but if someone tells you they'd implement their own sorting algorithm to sort a list instead of telling you they'd use whichever sort method the language provides, you know you're going to need to ask some more questions. It is not a good question for a coding interview.

Thread Thread
 
arjuncodess profile image
Arjun Vijay Prakash

I understand that the question may appear tricky, but it's important for the community to be aware that there are various types of challenges ranging from these brain-teaser-ish ones (as mentioned by @ervin_szilagyi) to real coding ones.

The title of this question has been designed to grab the reader's attention, but this post also conveys that simple math can be used to get amazing results.

Thanks!
Happy Coding!

Collapse
 
ervin_szilagyi profile image
Ervin Szilagyi

This interview question is cool but problematic. Similar question I was asked a while ago is to calculate the square root of a number without using math.sqrt (hint: Newton-Raphson method).

The problem with these questions is that they are really hard to be figured out on the spot, as long as you don't know the trick/solution. Even if you know the trick to these, you can be caught off-guard, since you most likely don't know the math behind them. It is not obvious (at least for me) why do the work. With a follow-up question the interviewer can find out easily that the solution was essentially memorised by the candidate.

The good thing about this post is that it brings attention to these type of questions. If you are a candidate, at least you should know that these brain-teaser-ish questions still exist and they are being asked.

If you are an interviewer, think twice about what are you asking. Essentially, you would want something which leads to a conversation, not just blatantly memorised algorithms.

Collapse
 
antonkesy profile image
Anton Kesy

This is called Monte Carlo method ;)