Ahmed El Ghattas
Ahmed El Ghattas

Reputation: 13

List sort is malfunctioning in python 3.7

I'm new to python and i was practicing to code something to calculate CDF (Cumulative Density Function), the code is below:

It works fine except in some cases when i input something like: 12-12-125-15-152-16-10

The reverse sorting doesn't get a correct sorting results.

# This is a trial to make an app for calculating the CDF for a set of numbers
# x = int(input("Please Enter the Number of Samples: "))  # x represents the number of samples
y = input("\nPlease Enter the samples separated by (-) with no spaces: ") # y represents the samples collection point
# print(y)
z = y.split("-")
x = len(z)
s = len(z)+1    # s represents the total sample space
print("\nThe number of samples is {} and the sample space is {} sample.\n".format(x,s))
# z.reverse()
z.sort(reverse=True)
# print(z)
# print(len(z))
ind = 0
for i in z:
    ind+= 1
    freq = (ind)/s
    print(i, freq, ind)

Expected sorting results: 152 125 16 15 12 12 10

Actual sorting results: 16 152 15 125 12 12 10

Upvotes: 1

Views: 62

Answers (3)

Valentino
Valentino

Reputation: 7361

Other solutions are fine. However if for some reason you wish to keep a z a list of strings, you can convert them in the sorting algorithm.

In your code, add a key to the sort method:

z.sort(key=int, reverse=True)

Strings will be converted to numbers only in the sorting process.

Upvotes: 0

Jinsu
Jinsu

Reputation: 540

It is because you're comparing strs.

Please change str into int

# This is a trial to make an app for calculating the CDF for a set of numbers
# x = int(input("Please Enter the Number of Samples: "))  # x represents the number of samples
y = input("\nPlease Enter the samples separated by (-) with no spaces: ") # y represents the samples collection point
# print(y)
z = y.split("-")
x = len(z)
intList=[]
for char in z:
    intList.append(int(char))
print(intList)
intList.sort(reverse=True)
print(intList)

Upvotes: 1

Robert
Robert

Reputation: 171

You just need to convert str to int in list Z: possible solution is to add list(map(int, z))

# This is a trial to make an app for calculating the CDF for a set of numbers
# x = int(input("Please Enter the Number of Samples: "))  # x represents the number of samples
y = input("\nPlease Enter the samples separated by (-) with no spaces: ") # y represents the samples collection point
# print(y)
z = y.split("-")
z = list(map(int, z))
x = len(z)
s = len(z)+1    # s represents the total sample space
print("\nThe number of samples is {} and the sample space is {} sample.\n".format(x,s))
# z.reverse()
z.sort(reverse=True)
# print(z)
# print(len(z))
ind = 0
for i in z:
    ind+= 1
    freq = (ind)/s
    print(i, freq, ind)

then the result is: 152 125 16 15 12 12 10

Upvotes: 3

Related Questions