# A question about 'Median' exercise

#1

Hi everyone,
I want to ask a question about the median example.
I have just passed this exercise by typing the below codes.

``````def median(text1):
list1=[]
for i in text1:
if i ==",":
list1=list1
else:
list1.append(int(i))
list1.sort()
if len(list1)%2==0:
middle=(float(list1[int(len(list1)/2)])+float(list1[int(len(list1)/2)-1]))/2
return(middle)
else:
middle = float(list1[int(len(list1) / 2)])
return(middle)
text2=str(raw_input("Text:"))
median(text2)``````

Let me explain something about the above code. As you can see, first an input was determined as a string. If the user write some numbers with comma like "1,2,3,4" the code works well. If the user write something like "1,22,33,43" the code works well again at this website code interface page. However in Python3, the second written numbers sorted the numbers like [1,2,2,3,3,3,4]. So in Python3 the digits of numbers can't be formed with this codes. But again i passed the exercise with the above codes.

In order to write a similar program in Python3 some small changes must be done. The below codes work in Python3.

``````def median(text1):
text3=""
for i in text1:
text3+=i
text3=text3.split(",")
list1=[]
for i in text3:
if i ==",":
list1=list1
else:
list1.append(int(i))
list1.sort()
if len(list1)%2==0:
middle=(float(list1[int(len(list1)/2)])+float(list1[int(len(list1)/2)-1]))/2
return(middle)
else:
middle = float(list1[int(len(list1) / 2)])
return(middle)
text2=str(input("Text:"))
median(text2)``````

Normally i do my exercies in Python3. But i can't understand how the first codes print 22 as it is, in Python2.
In Python3 the first codes seperate the digits of 22 because it was defined as a string variable. So a small change is necessarry in order to find the middle of the given numbers.
I wonder how the first code passed the exercise.

#2

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.