4
\$\begingroup\$

This is Python code to sort the numbers in ascending order (It's my school task). How does it look?

It works, but I think that this can be improved.

# How many number we have to sort 
num = int(input("How many figures : ")) 
storage = []
result = []

# Creating an array of users numbers
for i in range(1,num+1):
    a = int(input("Enter value" + str(i) + " : "))
    storage.append(a) # user enter

# Sorting the array
for m in range(len(storage)):
    b = min(storage)
    storage.remove(b)
    result.append(b) # user get
j = ' '.join(str(i) for i in result)
print(j)
\$\endgroup\$
  • 2
    \$\begingroup\$ Are there any limitations to the problem? Why, for example, cannot you just use sorted()? Does the solution have to follow this idea of finding minimum from the rest of the elements? (selection sort like) \$\endgroup\$ – alecxe Oct 19 '17 at 20:39
  • \$\begingroup\$ We were learning some kind of bubble sort . I decided to do experiments by myself to find out more about Python . \$\endgroup\$ – GoodExchanger Oct 19 '17 at 21:56
2
\$\begingroup\$

You could combine your input to a single line to improve ease of use. For example,

storage = input("Enter values separated by spaces:")
storage = [int(x) for x in storage.split()]

This way you have the entire list of input and can avoid having to have the user enter the number of input, and avoid having to declare the num variable at all.

However, you probably also want to include some form of input validation or throw a meaningful error as right now if your user was to enter non-integers, your program would simply crash and output a vague error that the user would probably have a difficult time understanding.

try: 
    storage = [int(x) for x in test.split()]
except ValueError:
    print("Non-integers in input!")

Alternatively, you could check if all the values are numeric and if not, have the user re-enter their input.

As for your sorting algorithm, if you don't want to use Python's implemented sort() or sorted(), you should research more efficient algorithm's such as quick sort or even implement the bubble sort that you learned.

Currently, your min_sort algorithm finds the minimum value in the list, which is O(n) then removes that element from the list (separately from the search) which is again O(n). This is extremely wasteful as you may end up searching through the entire list again and again (n times), so it would be better to use a more efficient sorting algorithm or at least recognize that we don't need to pass through the entire list twice on each iteration, just pass through the list once and keep track of the minimum value. You could do this by writing your own function like:

def find_remove_min(nums):
    """Returns the minimum number and the list without the min number"""
    if nums:
        min_index = 0
        for i in range(1, len(nums)):
            if nums[i] < nums[min_index]:
                min_index = i
        return nums[min_index], nums[:min_index] + nums[min_index+1:]

Then you could do something like,

while storage:
    min_num, storage = find_remove_min(storage)
    result.append(min_num)

which would be more readable and efficient imo.

\$\endgroup\$
2
\$\begingroup\$

The built-in sorted(), which uses Timsort, is always preferable, but since you said you were learning bubble sort, I would stick with it even though it is too slow and mutate the input list instead of creating a new one.

numbers = input("Enter numbers separated by a comma: ")
numbers = [int(n) for n in numbers.split(',')]

end = len(numbers) - 1

while end != 0:

    for i in range(end):
        if numbers[i] > numbers[i + 1]:
            numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i]

    end = end - 1

Running it:

Enter numbers separated by a comma: 3, 0, 1, 4, 2
[0, 1, 2, 3, 4]
>>> 
\$\endgroup\$
-1
\$\begingroup\$

alist= int (input (" enter the values of the list")) #list formed will have the keyboard values

n= len(alist) # length of the list

for r in range( n-1):

  for c in range(0, n-r-1):

        if alist[c] > alist [ c+1]:

              alist [ c] , alist [ c+1] =alist [ c+1] , alist [c] #toswap

print( " sorted list", alist)

  • will give sorted list in ascending order
\$\endgroup\$
  • 3
    \$\begingroup\$ Your code isn't formatted correctly. Also code only answers are highly discouraged, please say what and how this is better than the OPs code. \$\endgroup\$ – Peilonrayz Apr 27 at 15:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.