简体   繁体   中英

Attribute Error While Trying to Run Insertion Sort

I am currently creating a turtle game which will collect scores and initials in an array of records, I want to run an insertion sort in order to display to the user if they had received one of the top three scores. However, whenever I try to run the code I receive an attribute error. Code here (Can supply more code if required):

def insertion_sort(scores):
  value = 0
  i=0
  for i in range(1, len(scores)):
    value = scores[i].Score
    j = i - 1
    while j>= 0 and scores[j].Score > value:
      scores[j + 1].Score = scores[j].Score
      j -=1
    scores[j + 1].Score = value
  return scores

I have tried rearranging my data and changing how it has been stored however nothing has helped. I'm unsure of what else to try as I have tried to work out several different solutions without any success.

Is it possible you were just passing a list of numbers to the fuction? Because that could also explain the attribute error: AttributeError: 'int' object has no attribute 'Score'
You can easily convert a list of numbers to a list of records using a list comprehension. (Or a dictionary like in the first example)

Otherwise your record is likely missing the Score attribute (did you use a capital for it too?)
I've also optimised the code a bit using an enumerate and slice, and switching the records instead of the values.

Records with name and score:

they can be created from a dictionary of names with scores:

class Record:
    def __init__(self, Name, Score):
        self.Name = Name
        self.Score = Score
    def __repr__(self):
        return "%s:%d" % (self.Name, self.Score)

def make_scores(scores):
    return [Record(Name, Score) for Name, Score in scores.items()]

def insertion_sort(scores):
    for j, score in enumerate(scores[1:]):
        value = score.Score
        while j >= 0 and scores[j].Score > value:
            scores[j + 1] = scores[j]
            j -= 1
        scores[j + 1] = score
    return scores

scores = make_scores({
    "Alpha": 0,
    "Bravo": 1,
    "Charlie": 2,
    "Delta": 3,
    "Echo": 7
})
print(insertion_sort(scores))
scores = make_scores({
    "Alpha": 7,
    "Bravo": 3,
    "Charlie": 2,
    "Delta": 1,
    "Echo": 0
})
print(insertion_sort(scores))

Output:

[Alpha:0, Bravo:1, Charlie:2, Delta:3, Echo:7]
[Echo:0, Delta:1, Charlie:2, Bravo:3, Alpha:7]

I hope this is helful. Explanation:

  • The __init__ function of Record just stores a name and a score.
  • The __repr__ function of Record was just added in order to be able to visualise the record, you don't really need it
  • The make_scores function just creates a list of Records with names and scores from an object of names and scores
  • "insertion_sort" will swap records when they are out of order

Records with only the score

they can be created from a list of numbers:

class Record:
    def __init__(self, score):
        self.Score = score
    def __repr__(self):
        return "%d" % self.Score

def make_scores(scores):
    return [Record(score) for score in scores]

def insertion_sort(scores):
    for j, score in enumerate(scores[1:]):
        value = score.Score
        while j >= 0 and scores[j].Score > value:
            scores[j + 1] = scores[j]
            j -= 1
        scores[j + 1] = score
    return scores

scores = make_scores([0,1,2,3,7])
print(insertion_sort(scores))
scores = make_scores([7,3,2,1,0])
print(insertion_sort(scores))

Output:

[0, 1, 2, 3, 7]
[0, 1, 2, 3, 7]

Explanation:

  • The __init__ function of Record just stores a score.
  • The __repr__ function of Record was just added in order to be able to visualise the record, you don't really need it
  • The make_scores function just creates a list of Records with scores from a lis of number
  • "insertion_sort" will swap records when they are out of order

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