I input like this -> 10 79 8 51 2
and I want to get [2, 8, 10, 51, 79]
but I get [10, 2, 51, 79, 8]
please tell me what's wrong with my code?
python
list = input().split()
print(list)
for i in range(0, 4):
print(i)
for j in range(i+1, 5):
if list[i] > list[j]:
print(list[i],list[j])
list[i], list[j] = list[j], list[i]
print(list)
else:
print(j, list[i], list[j])
print("don't switch")
The logic of your sort is correct, however it's not working on what you think it is. In practice, it is working on a list of strings (not integers ), and so the comparison is lexicographic, not numeric. Under this criteria, your list is sorted.
If you would change your input to list = [10, 79, 8, 51, 2]
, you'd get the result you want. (Asides from that, it's better not to use names like list
.)
There are three problems with your code.
for i in range(0, len(list)):
for j in range(i+1, len(list)):
list[i]
to int(list[i])
. Or before the for loops, you can do this:for i in range(0, len(list)):
list[i] = int(list[i])
Or, even more succinctly, as Stef mentioned:
list = [int(x) for x in list]
This converts every item in list
to an integer instead of a string.
list
something like lst
instead.There is a simpler way to write your code . check this out :
a = list(map(int,input().split()[:5])) ## Enter 5 numbers with in one line with one space distance
#This method can also be used for N numbers , you just need to change 4.
tol = len(a)
for j in range(tol-1): ## Helps to check sorting process again and again until all of numbers are sorted
for i in range(tol-1): ## To compare each number with next one
if a[i] > a[i+1]:
temp = a [i]
a [i] = a[i+1]
a [i+1]=temp
else:
continue
print(a)
input : 10 79 8 51 2 and Output: [2, 8, 10, 51, 79]
Simple way to sort list is:
list1 = [10, 79, 8, 51, 2]
print(sorted(list1))
output:[2, 8, 10, 51, 79]
I dont know if that will work but i think that sort less. Try maybe to increase your number of loop. Or try this :
list = input().split()
#Turn every value of your list into int and not string
for i in range(0, len(list)):
list[i] = int(list[i])
print(list)
# Sorting the list
list.sort()
print(list)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.