我需要为uni编写这个排序插入算法,但是我很难找出为什么运行这个代码会得到"None“。
我想让它以这种形式给出输出:
[Product(name='banana', price=3.99), Product(name='peanut butter', price=4.2), Product(name='jelly', price=5.99), Product(name='Phoebe Bridgers CD', price=8.2), Product(name='guitar strings', price=12)]我的代码:
from typing import List
from dataclasses import dataclass
# dataclasses are a convenient new way to create simple "structs" or "records"
# in Python.
@dataclass
class Product:
name: str
price: float
# hint: lst is a python list, so use lst[i] to access element i
# (=what we called "get" in class), and use len(lst) to get its size.
# insertion sort
def sort_insertion(lst: List[Product]) -> List[Product]:
"""Sort lst by insertion, in-place."""
# We start from 1 since the first element is already sorted as it is.
for i in range(1, len(lst)):
cur_value = lst[i].price
cur_pos = i - 1
while cur_pos >= 0 and cur_value < lst[cur_pos].price:
lst[cur_pos + 1].price = lst[cur_pos].price
cur_pos -= 1
lst[cur_pos + 1].price = cur_value
sample_inventory = [
Product(name="banana", price=5.99),
Product(name="peanut butter", price=8.20),
Product(name="jelly", price=3.99),
Product(name="Phoebe Bridgers CD", price=12),
Product(name="guitar strings", price=4.20),
]
print(sort_insertion(sample_inventory))发布于 2021-03-02 04:12:16
这就是了。有三个问题: 1.在while循环的第一行中,您需要进行交换,如下所示。2.你想交换整个产品,而不仅仅是它的价格。您不希望香蕉和其他物品的价格在分拣过程中发生变化。3.这是一个打印排序,所以您不能说in_place (sort_insertion(Sample_inventory)),因为函数不返回任何内容。
def sort_insertion(lst: List[Product]) -> List[Product]:
"""Sort lst by insertion, in-place."""
# We start from 1 since the first element is already sorted as it is.
for i in range(1, len(lst)):
cur_value = lst[i].price
cur_pos = i - 1
while cur_pos >= 0 and cur_value < lst[cur_pos].price:
lst[cur_pos + 1], lst[cur_pos] = lst[cur_pos], lst[cur_pos + 1]
cur_pos -= 1
lst[cur_pos + 1].price = cur_value
sample_inventory = [
Product(name="banana", price=5.99),
Product(name="peanut butter", price=8.20),
Product(name="jelly", price=3.99),
Product(name="Phoebe Bridgers CD", price=12),
Product(name="guitar strings", price=4.20),
]
sort_insertion(sample_inventory)
print(sample_inventory)
#output:
[Product(name='jelly', price=3.99), Product(name='guitar strings', price=4.2), Product(name='banana', price=5.99), Product(name='peanut butter', price=8.2), Product(name='Phoebe Bridgers CD', price=12)]https://stackoverflow.com/questions/66428550
复制相似问题