Think my math is wrong? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Think my math is wrong? (/thread-22251.html) |
Think my math is wrong? - edwdas - Nov-05-2019 So I'm trying to calculate the median from inputs (int) that a user submits WITHOUT using a statistics module (just want to see how it can be done) Current function to find the median looks like this def median(): srt = sorted(lst) mid = len(lst)//2 if len(lst) % 2: return srt[mid] else: med = int((srt[mid] + srt[mid-1])) // 2 return medAnd the whole script looks like this lst = [] def median(): srt = sorted(lst) mid = len(lst)//2 if len(lst) % 2: return srt[mid] else: med = int((srt[mid] + srt[mid-1])) // 2 return med while True: l = (input("Enter a number ")) if l == "": print(median()) break lst.append(l) RE: Think my math is wrong? - ichabod801 - Nov-05-2019 You need to convert them to ints as they are appended to lst. If you don't, they won't sort correctly, because strings sort alphabetically. That is, when sorting strings, '2' is higher than '10', and indeed higher than '1234567890'. RE: Think my math is wrong? - buran - Nov-05-2019 // is floor division:>>> 5//2 2so if there are odd number of elements you want to return srt[mid+1] (on line 6)With even number of elements median should be the mean of the middle two numbers (i.e. the true division of the middle 2 elements)- mid and mid+1 , not mid-1 med = (srt[mid] + srt[mid+1]) / 2 Also because of using floor division you don't need to explicitly convert to int on line 8 (but this is just a note) that said, you better add argument to median function, instead of using global variable lst
RE: Think my math is wrong? - edwdas - Nov-05-2019 How would one do this? tried slipping in a cheeky l = [int(lst) for lst in l]directly above the lst.append but that seemed to cause more issues (Nov-05-2019, 02:56 PM)buran Wrote: With even number of elements median should be the mean of the middle two numbers (i.e. the true division of the middle 2 elements)- With these amendments i get the error "int expected str received" in turn it kills itself. Also declaring the "l = input()" to be int it also kills itself with "ValueError: invalid literal for int() with base 10: ''" furthermore, with the script it its original state and changing the -1 to +1 were told too the input is 8 8 8 8 by the user my median is apparently 44? Actually. Applying the suggested math changes and by simplying changing the append to lst.append(int(l)) it bloody worked, so cheers |