121k views
5 votes
How to find median in python without inbuilt function?

1 Answer

3 votes

Final answer:

To find the median in Python without using the built-in function, you can write a custom function that takes a list of numbers as input and returns the median value.

Step-by-step explanation:

To find the median in Python without using the built-in function, you can write a custom function that takes a list of numbers as input and returns the median value. Here is an example:

def calculate_median(numbers):
numbers.sort()
n = len(numbers)
if n % 2 != 0:
return numbers[n // 2]
else:
median = (numbers[n // 2] + numbers[(n // 2) - 1]) / 2
return median

# Example usage:
numbers = [5, 2, 8, 3, 9, 1, 4, 7, 6]
median = calculate_median(numbers)
print('The median is:', median)

This code first sorts the list of numbers in ascending order. Then, it checks if the number of elements is odd or even. If it's odd, it returns the middle number as the median. If it's even, it calculates the average of the two middle numbers.

User Bellum
by
7.5k points