Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,709 questions

55,473 answers

573 users

How to find the median among three given numbers in Python

3 Answers

0 votes
# Method 1: Using sorted()

def median_of_three_numbers(a, b, c):
    return sorted([a, b, c])[1]


print("The median of [1, 1, 1] is %d" % median_of_three_numbers(1, 1, 1))
print("The median of [10, 3, 7] is %d" % median_of_three_numbers(10, 3, 7))
print("The median of [10,-10,-10] is %d" % median_of_three_numbers(10, -10, -10))
print("The median of [3, 3, 5] is %d" % median_of_three_numbers(3, 3, 5))


'''
run:

The median of [1, 1, 1] is 1
The median of [10, 3, 7] is 7
The median of [10,-10,-10] is -10
The median of [3, 3, 5] is 3

'''

 



answered Mar 26 by avibootz
edited Mar 26 by avibootz
0 votes
# Method 2: Without sorting

def is_median(x, y, z):
	# if x is median return true
	if x <= b and x >= z or x >= y and x <= z:
		return True
	else:
		return False

def median_of_three_numbers(a, b, c):
	if is_median(a, b, c):
		return a
	if is_median(b, c, a):
		return b
	else:
		return c


print("The median of [1, 1, 1] is %d" % median_of_three_numbers(1, 1, 1))
print("The median of [10, 3, 7] is %d" % median_of_three_numbers(10, 3, 7))
print("The median of [10,-10,-10] is %d" % median_of_three_numbers(10, -10, -10))
print("The median of [3, 3, 5] is %d" % median_of_three_numbers(3, 3, 5))


'''
run:

The median of [1, 1, 1] is 1
The median of [10, 3, 7] is 7
The median of [10,-10,-10] is -10
The median of [3, 3, 5] is 3

'''

 



answered Mar 26 by avibootz
edited Mar 26 by avibootz
0 votes
# Method 3: One‑liner

def median_of_three_numbers(a, b, c):
    return a + b + c - min(a, b, c) - max(a, b, c)


print("The median of [1, 1, 1] is %d" % median_of_three_numbers(1, 1, 1))
print("The median of [10, 3, 7] is %d" % median_of_three_numbers(10, 3, 7))
print("The median of [10,-10,-10] is %d" % median_of_three_numbers(10, -10, -10))
print("The median of [3, 3, 5] is %d" % median_of_three_numbers(3, 3, 5))


'''
run:

The median of [1, 1, 1] is 1
The median of [10, 3, 7] is 7
The median of [10,-10,-10] is -10
The median of [3, 3, 5] is 3

'''

 



answered Mar 26 by avibootz
...