[英]Sorting from smallest to biggest
I would like to sort several points from smallest to biggest however. 我想从最小到最大排序几个点。 I will wish to get this result : 我希望得到这个结果 :
Drogba 2 pts
Owen 4 pts
Henry 6 pts
However, my ranking seems to be reversed for now :-( 但是,我的排名目前似乎已经逆转了:-(
Henry 6 pts
Owen 4 pts
Drogba 2 pts
I think my problem is with my function Bubblesort ? 我认为我的问题出在我的功能Bubblesort上吗?
def Bubblesort(name, goal1, point):
swap = True
while swap:
swap = False
for i in range(len(name)-1):
if goal1[i+1] > goal1[i]:
goal1[i], goal1[i+1] = goal1[i+1], goal1[i]
name[i], name[i+1] = name[i+1], name[i]
point[i], point[i + 1] = point[i + 1], point[i]
swap = True
return name, goal1, point
def ranking(name, point):
for i in range(len(name)):
print(name[i], "\t" , point[i], " \t ")
name = ["Henry", "Owen", "Drogba"]
point = [0]*3
goal1 = [68, 52, 46]
gain = [6,4,2]
name, goal1, point = Bubblesort( name, goal1, point )
for i in range(len(name)):
point[i] += gain[i]
ranking (name, point)
In your code: 在您的代码中:
if goal1[i+1] > goal1[i]:
that checks if it is greater. 检查是否更大。 You need to swap it if the next one is less, not greater. 如果下一个较小而不是较大,则需要交换它。
Change that to: 更改为:
if goal1[i+1] < goal1[i]:
A bunch of issues: 一堆问题:
def Bubblesort
- PEP8 says function names should be lowercase, ie def bubblesort
def Bubblesort
-PEP8说函数名应该小写,即def bubblesort
You are storing your data as a bunch of parallel lists; 您将数据存储为一堆并行列表。 this makes it harder to work on and think about (and sort!). 这使得工作和思考(和排序!)变得更加困难。 You should transpose your data so that instead of having a list of names, a list of points, a list of goals you have a list of players, each of whom has a name, points, goals. 您应该对数据进行转置,以使您不再具有名称列表,积分列表,目标列表,而是拥有球员列表,每个球员都有一个名称,得分,目标。
def bubblesort(name, goal1, point):
- should look like def bubblesort(items)
because bubblesort
does not need to know that it is getting names and goals and points and sorting on goals (specializing it that way keeps you from reusing the function later to sort other things). def bubblesort(name, goal1, point):
-应该看起来像def bubblesort(items)
因为bubblesort
不需要知道它正在获取名称,目标和点以及对目标进行排序(以这种方式专门化可以防止您重用该函数稍后再排序)。 All it needs to know is that it is getting a list of items and that it can compare pairs of items using >
, ie Item.__gt__
is defined. 它只需要知道它正在获取项目列表,并且可以使用>
比较项目对,即定义了Item.__gt__
。
Instead of using the default "native" sort order, Python sort functions usually let you pass an optional key
function which allows you to tell it what to sort on - that is, sort on key(items[i]) > key(items[j])
instead of items[i] > items[j]
. Python排序函数通常不使用默认的“本机”排序顺序,而是让您传递一个可选的key
函数,该函数允许您告诉它排序的内容-即按key(items[i]) > key(items[j])
而不是items[i] > items[j]
。 This is often more efficient and/or convenient than reshuffling your data to get the sort order you want. 与重新整理数据以获得所需的排序顺序相比,这通常更有效和/或更方便。
for i in range(len(name)-1):
- you are iterating more than needed. for i in range(len(name)-1):
-您迭代的次数超过了需要。 After each pass, the highest value in the remaining list gets pushed to the top (hence "bubble" sort, values rise to the top of the list like bubbles). 每次通过之后,其余列表中的最大值将被推到顶部(因此“冒泡”排序,值像气泡一样上升到列表的顶部)。 You don't need to look at those top values again because you already know they are higher than any of the remaining values; 您无需再查看这些最高值,因为您已经知道它们比任何其他剩余值都高。 after the nth pass, you can ignore the last n values. 在第n次传递之后,您可以忽略最后n个值。
actually, the situation is a bit better than that; 实际上,情况要好得多; you will often find runs of values which are already in sorted order. 您通常会发现已按排序顺序运行的值。 If you keep track of the highest index that actually got swapped, you don't need to go beyond that on your next pass. 如果您跟踪实际交换的最高索引,则无需在下一次传递中超越该指数。
So your sort function becomes 所以你的排序功能变成
def bubblesort(items, *, key=None):
"""
Return items in sorted order
"""
# work on a copy of the list (don't destroy the original)
items = list(items)
# process key values - cache the result of key(item)
# so it doesn't have to be called repeatedly
keys = items if key is None else [key(item) for item in items]
# initialize the "last item to sort on the next pass" index
last_swap = len(items) - 1
# sort!
while last_swap:
ls = 0
for i in range(last_swap):
j = i + 1
if keys[i] > keys[j]:
# have to swap keys and items at the same time,
# because keys may be an alias for items
items[i], items[j], keys[i], keys[j] = items[j], items[i], keys[j], keys[i]
# made a swap - update the last_swap index
ls = i
last_swap = ls
return items
You may not be sure that this is actually correct, so let's test it: 您可能不确定这是否正确,所以让我们对其进行测试:
from random import sample
def test_bubblesort(tries = 1000):
# example key function
key_fn = lambda item: (item[2], item[0], item[1])
for i in range(tries):
# create some sample data to sort
data = [sample("abcdefghijk", 3) for j in range(10)]
# no-key sort
assert bubblesort(data) == sorted(data), "Error: bubblesort({}) gives {}".format(data, bubblesort(data))
# keyed sort
assert bubblesort(data, key=key_fn) == sorted(data, key=key_fn), "Error: bubblesort({}, key) gives {}".format(data, bubblesort(data, key_fn))
test_bubblesort()
Now the rest of your code becomes 现在,您的其余代码变为
class Player:
def __init__(self, name, points, goals, gains):
self.name = name
self.points = points
self.goals = goals
self.gains = gains
players = [
Player("Henry", 0, 68, 6),
Player("Owen", 0, 52, 4),
Player("Drogba", 0, 46, 2)
]
# sort by goals
players = bubblesort(players, key = lambda player: player.goals)
# update points
for player in players:
player.points += player.gains
# show the result
for player in players:
print("{player.name:<10s} {player.points:>2d} pts".format(player=player))
which produces 产生
Drogba 2 pts
Owen 4 pts
Henry 6 pts
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.