我正在制作一个程序,该程序采用名单列表并返回名称的前20位,不论性别如何。
我有点难以理解我做错了什么,因为我正在尝试使用insertion_sort,但它无法正常工作。
这是代码。
class babyName():
__slots__ = ("name" , "gender" , "occurences")
def __init__(self, name, gender, occurences):
self.name = name
self.gender = gender
self.occurences = occurences
def __str__(self):
return self.name + "," + self.gender + "," + self.occurences
def mkEntry(name, gender, occurences):
entry = babyName(name, gender, occurences)
return entry
def readFile(year):
lst = []
lst2 = []
topm = 20
topf = 20
yob = ("yob" + str(year) + ".txt")
for line in open("names/" + yob ):
line = line.split(",")
if line[1] == "F":
if topf > 0:
entry = mkEntry(line[0], line[1], line[2])
lst.append(entry)
topf -= 1
elif line[1] == "M":
if topm > 0:
entry = mkEntry(line[0], line[1], line[2])
lst2.append(entry)
topm -= 1
mergedlist = lst + lst2
return mergedlist
def insertion_sort(lst):
for i in range(1, len(lst)):
h = i - 1
val = lst[i].occurences
val2 = lst[i-1].occurences
while (h >= 0) and (val2 > val):
lst[h+1] = lst[h]
h = h - 1
lst[h+1] = val
def main():
year = input("Enter the year of birth:")
file = readFile(year)
insertion_sort(file)
for x in file:
print(x)
main()
有任何帮助吗?我不完全确定出了什么问题......
答案 0 :(得分:0)
lst[h+1] = val # val isn't a babyName instance
应该是
lst[h+1] = lst[i]
答案 1 :(得分:0)
嗯。不应该有移动/插入的东西的占位符吗?
def insertion_sort(lst):
for i in range(1, len(lst)):
# placeholder for the item being moved
tmp = lst[i]
h = i - 1
val = lst[i].occurences
val2 = lst[i-1].occurences
while (h >= 0) and (val2 > val):
lst[h+1] = lst[h]
h = h - 1
lst[h+1] = tmp
您可能希望查看Wikipedia文章中的伪代码。