简体   繁体   中英

Failing with a python bubble sort

I've written this code and I want it to organise the player scores.

file = open("leaderboard.txt", "a")
file.write(str(winnerscore)+ ": " + winner + "\n")
file.close()
fileReading = open("leaderboard.txt","r")
lines = fileReading.read()
fileReading.close()
lines = lines.split("\n")
for line in lines:
    print(line)

def bubbleSort(arr):
    n = len(arr) 

    for i in range(n-1): 

        for j in range(0, n-i-1): 


            if arr[j] > arr[j+1] : 
                arr[j], arr[j+1] = arr[j+1], arr[j] 

# Driver code to test above 
arr = int(float(lines[0]))

bubbleSort(arr) 

print ("Sorted array is:") 
for i in range(len(arr)): 
    print ("%s" %arr[i])

It produces this but doesn't sort it:

76: Daniel
36: Gabriel
30: Perry
92: Avi
28: Yehuda
46: Jeremy
54: Mordechai
96: Paul
80: Pauline
72: Fran

Unfortunately it comes up with this error message:

  arr = int(float(lines[0]))
ValueError: could not convert string to float: '76: Daniel'
How do I fix this so it sorts from highest score to lowest score?

How do I make it so that it sorts the scores in the list?

It happens because you are comaparing items like if 76: Daniel>36: Gabriel You can try something like this

mylist=['76: Daniel','36: Gabriel','30: Perry','92: Avi','28: Yehuda','46: Jeremy','54: Mordechai','96: Paul','80: Pauline','72: Fran']

def bubbleSort(arr):
    n=len(arr)
    for i in range(n-1): 

        for j in range(0, n-i-1): 


            if int(arr[j][:2]) < int(arr[j+1][:2]) : 
                arr[j], arr[j+1] = arr[j+1], arr[j] 
bubbleSort(mylist)
print(mylist)
>>>['96: Paul', '92: Avi', '80: Pauline', '76: Daniel', '72: Fran', '54: Mordechai', '46: Jeremy', '36: Gabriel', '30: Perry', '28: Yehuda']

This is pretty obvious and Python tells you where the problem is: You are explicitly trying to convert the whole first line ( lines[0] ) which contains characters to a number.

Extracting just the first line to arr and the ongoing sort of this single line would be useless. Moreover, conversion to float and then to int is definitely not necessary.

If all the numbers are equally long (2 characters), you can simply sort your lines as strings (not numbers) by simply leaving out the conversion. You can simply change the erroneous line to

arr = lines

to make your program work. (Or rename all the following arr references to lines , of course.)

I'd also remove the first 3 lines of your program which are currently unrelated to the rest of your program.

See the result online.

import re
string1 = lines[0]
int(re.search(r'\d+', string1).group())

Instead of arr = int(float(lines[0])), try using the above one. String1 contains the integer values. On that apply the bubble sort.

Short way to use:)

import pandas as pd

df = pd.read_table('leaderboard.txt', delimiter=":", names=('scor', 'Name'))
df.sort_values(by='scor', inplace=True)
df.head()

    scor        Name
7    96        Paul
3    92         Avi
8    80     Pauline
0    76      Daniel
9    72        Fran
6    54   Mordechai
5    46      Jeremy
1    36     Gabriel
2    30       Perry
4    28      Yehuda

arr = df.values  

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM