I can't think of a conditional expression to find a median without using an existing median function.

Asked 2 years ago, Updated 2 years ago, 40 views

The following issues have been raised at the university:

Create a program to find the median when the data is given as a list.
Replace the median with the variable median and display the value.Create without a median function.You can also use the sorted function.

I know I use if statements, but I can't think of a conditional expression that finds a median without using a function.I've been looking into it for three days, and I want to persevere and complete it on my own, but I haven't made any progress since then.Please give me a hint about the conditional expression.

Data to use

data1:2,3,2,5,1,4,6
data2—2,3,2,5,4,4,6,5
data3—64, 50, 57, 36, 43, 52, 58, 72, 65, 53, 30, 56, 85, 69, 50, 55, 45, 61, 43, 76

Some of the results in the document

x=data1[:]

print("Data to be used:",x)
print("Medium:",median)

python python3

2022-09-30 20:19

1 Answers

If you want to implement it honestly, this is what it looks like.If Create without using a function to find the median then can I use the len() function?

def get_median(nums):
    # sort a list in order of small size
    sorted_nums = sorted(nums)

    # If the list is empty, return 'None' and exit
    length = len(sorted_nums)
    if not length:
        return None

    # Divide the number by two and you get a median index.
    anchor=length//2#`//` is devalued

    If length %2!= 0:// If the number is odd, use the index as it is
        return sorted_nums [anchor]
    else:
        # If the number is even, divide it by adding two values in the middle.
        med1 = sorted_nums [anchor-1]
        med2 = sorted_nums [anchor]
        return(med1+med2)/2

x = [2,3,2,5,1,4,6]

print("Data to be used:",x)
print("Medium:", get_median(x))#3


2022-09-30 20:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.