插入和冒泡排序部分工作

Insertion and Bubble Sort partially working

全部 我是 Python 的数据结构和算法的新手。我在我的库存程序中实施了插入和冒泡排序。当我对当前字典进行排序时,我的插入排序和冒泡排序都有效。但是,在添加新项目或从我的字典中删除项目后,我的插入和冒泡排序出现了关键错误。我试过将字典更改为 [{description..}] 并将 market[len(market) + 1] 更改为 market[len(market)] 。 None 这些工作都没有。如果有人帮助我编辑我的代码或向我解释发生了什么,我将不胜感激。提前谢谢你:")

market = {0: {'Description': 'Chocolate', 'Stock': 65, 'Price': 3.2, 'Expiry': '27 Dec', 'Discount': 'eligible'},
          1: {'Description': 'Bread', 'Stock': 20, 'Price': 2.7, 'Expiry': '15 June', 'Discount': 'eligible'},
          2: {'Description': 'Apples', 'Stock': 97, 'Price': 10.6, 'Expiry': '12 July', 'Discount': 'not eligible'},
          3: {'Description': 'Potato', 'Stock': 81, 'Price': 20.8, 'Expiry': '13 April', 'Discount': 'not eligible'},
          4: {'Description': 'Ice', 'Stock': 91, 'Price': 9.8, 'Expiry': '16 April', 'Discount': 'not eligible'}
          }


def menu():
    print('Press 1: To Add items. ')
    print('Press 2: To View items. ')
    print('Press 3: To Remove items. ')
    print('Press 4: Use Insertion Sort. ')
    print('Press 5: Use Bubble Sort. ')
    print('Press 6: Use Binary Search. ')
    print('Press 7: View Total and Average stock level. ')
    print('Press q: To Quit program. ')
    return input('What would you like to do? ')


# print(len(market) + 1) # check counter


# Insertion Sort

def insertionSort(theSeq, key):

    for i in range(1, len(theSeq)):
        temp = theSeq[i][key]
        j = i
        while j > 0 and temp < theSeq[j - 1][key]:
               theSeq[j][key] = theSeq[j - 1][key]
               j = j - 1
        theSeq[j][key] = temp
    return theSeq


# Sorting Menu
def sort_menu(second_list, sort_type):
    print('1. Sort by Description')
    print('2. Sort by Price')

    # Get user input
    user_input = input('Please enter choice: ')

    if user_input == '1':
        second_list = sort_type(second_list, 'Description')
        print('Success! Inventory list is sorted by Description!')

    elif user_input == '2':
        second_list = sort_type(second_list, 'Price')
        print('Success! Inventory list is sorted by Price!')
    else:
        print('You have entered an invalid option!')

    # Return updated list
    return second_list


# Bubble Sort
def bubble_sort(second_list, key):

    # Create temp copy of list
    temp = second_list.copy()

    # Obtain length of list
    y = len(temp)

    for i in range(y - 1, 0, -1):
        for j in range(i):
            if temp[j][key] > temp[j + 1][key]:
                temp[j], temp[j + 1] = temp[j + 1], temp[j]
    # Return updated list
    return temp

# Binary Search
def binarysearch(dictionary,item):
    global founditem
    itemlist = []
    for item2 in dictionary:
        itemlist.append(item2)
    first = 0
    last = len(itemlist) - 1
    found = False

    while first <= last and not found:
        midpoint = (first + last)//2
        if itemlist[midpoint] == item:
            # print(midpoint) test print out
            founditem = dictionary.get(midpoint)
            found = True
        else:
            if item < itemlist[midpoint]:
                last = midpoint-1
            else:
                first = midpoint+1
    return founditem


# Print total and average stock level
def average(market):
    n = len(market)
    total = 0
    for i in range(0,n):
        total += market[i]["Stock"]
    average = total/n
    return average

def total(market):
    n = len(market)
    total = 0
    for i in range(0,n):
        total += market[i]["Stock"]
    return total


while True:
    run = menu()
    if run == '1':
        # market[len(market) + 1] = {}
        # addMarket = input('Item to be added to Market? ')
        # market[len(market) + 1]['Description'] = addMarket
        name = input('Item to be added to Market? ')
        price = float(input('Price of food?'))
        amount = int(input('Qty of food to be added to stock? '))
        expiry = input('Enter expiry date: ')
        discount = input('Enter eligibility of discount: ')
        market[len(market) + 1] = {'Description': name, 'Stock': amount, 'Price': price, 'Expiry': expiry,
                                   'Discount': discount}

    elif run == '2':
        for i in market:
            item = market[i]
            print("Item No - %d Description - %s Stock - %d Price - %.2f Expiry - %s Discount - %s" % (
            i, item['Description'], item['Stock'], item['Price'], item['Expiry'], item['Discount']))


    elif run == '3':
        remove = int(input('Key in item number to remove: '))
        del market[remove]

    elif run == '4':
        market = sort_menu(market, insertionSort)

    elif run == '5':
        market = sort_menu(market, bubble_sort)
    #
    elif run == '6':
        key = int(input('Enter key you want to search: '))
        print(binarysearch(market, key))

    elif run == '7':
        print('')
        print('Total stock level is',total(market), 'and Average stock level is', average(market))
        print('')

    else:
        quit = str()
        while quit.upper() != "Q":
            quit = input("Enter Q or q to return to Main Menu. ")
            if quit.upper() == "Q":
                print('Thank you for using MamaStore!')
                menu()

您的插入代码的问题是您通过在每次插入时跳过一个索引来插入新元素。市场的初始大小为 5,因此当您插入新元素时,该元素应位于索引 5(起始索引为 0),但 market[len(market)+1] 插入索引 6。因此,当您 运行 a排序时的顺序循环会抛出一个键错误,因为你没有 5 作为键。
同样在删除时,当您删除任何项目时,序列中断会导致键错误,就像在插入的情况下一样。您可能应该考虑 运行 在字典的键上循环,在您的情况下是那些项目 ID。
但是,对于您的代码,将 dict 转换为列表然后稍后执行排序会很方便,然后再将其返回将其转换回字典。我在下面附上了一个工作代码:


market = {0: {'Description': 'Chocolate', 'Stock': 65, 'Price': 3.2, 'Expiry': '27 Dec', 'Discount': 'eligible'},
          1: {'Description': 'Bread', 'Stock': 20, 'Price': 2.7, 'Expiry': '15 June', 'Discount': 'eligible'},
          2: {'Description': 'Apples', 'Stock': 97, 'Price': 10.6, 'Expiry': '12 July', 'Discount': 'not eligible'},
          3: {'Description': 'Potato', 'Stock': 81, 'Price': 20.8, 'Expiry': '13 April', 'Discount': 'not eligible'},
          4: {'Description': 'Ice', 'Stock': 91, 'Price': 9.8, 'Expiry': '16 April', 'Discount': 'not eligible'}
          }


def menu():
    print('Press 1: To Add items. ')
    print('Press 2: To View items. ')
    print('Press 3: To Remove items. ')
    print('Press 4: Use Insertion Sort. ')
    print('Press 5: Use Bubble Sort. ')
    print('Press 6: Use Binary Search. ')
    print('Press 7: View Total and Average stock level. ')
    print('Press q: To Quit program. ')
    return input('What would you like to do? ')


# Insertion Sort

def insertionSort(theSeq, key):
    temp1 = [i for i in theSeq.values()]
    for i in range(0, len(temp1)):
        temp = temp1[i][key]
        j = i
        while j > 0 and temp < temp1[j - 1][key]:
            temp1[j][key] = temp1[j - 1][key]
            j = j - 1
        temp1[j][key] = temp
    s = {}
    for i in range(len(temp1)):
        s[i] = temp1[i]
    return s


# Sorting Menu
def sort_menu(second_list, sort_type):
    print('1. Sort by Description')
    print('2. Sort by Price')

    # Get user input
    user_input = input('Please enter choice: ')
    if user_input == '1':
        second_list = sort_type(second_list, 'Description')
        print('Success! Inventory list is sorted by Description!')

    elif user_input == '2':
        second_list = sort_type(second_list, 'Price')
        print('Success! Inventory list is sorted by Price!')
    else:
        print('You have entered an invalid option!')

    # Return updated list
    return second_list


# Bubble Sort
def bubble_sort(second_list, key):
    # Create temp copy of list
    temp = [i for  i in second_list.values()]

    # Obtain length of list
    y = len(temp)

    for i in range(y - 1, 0, -1):
        for j in range(i):
            if temp[j][key] > temp[j + 1][key]:
                temp[j], temp[j + 1] = temp[j + 1], temp[j]
    # Return updated list
    s = {}
    for i in range(len(temp)):
        s[i] = temp[i]
    return s

# Binary Search
def binarysearch(dictionary,item):
    global founditem
    itemlist = []
    for item2 in dictionary:
        itemlist.append(item2)
    first = 0
    last = len(itemlist) - 1
    found = False

    while first <= last and not found:
        midpoint = (first + last)//2
        if itemlist[midpoint] == item:
            # print(midpoint) test print out
            founditem = dictionary.get(midpoint)
            found = True
        else:
            if item < itemlist[midpoint]:
                last = midpoint-1
            else:
                first = midpoint+1
    return founditem


# Print total and average stock level
def average(market):
    n = len(market)
    total = 0
    for i in range(0,n):
        total += market[i]["Stock"]
    average = total/n
    return average

def total(market):
    n = len(market)
    total = 0
    for i in range(0,n):
        total += market[i]["Stock"]
    return total


while True:
    run = menu()
    if run == '1':
        name = input('Item to be added to Market? ')
        price = float(input('Price of food?'))
        amount = int(input('Qty of food to be added to stock? '))
        expiry = input('Enter expiry date: ')
        discount = input('Enter eligibility of discount: ')
        market[len(market)] = {'Description': name, 'Stock': amount, 'Price': price, 'Expiry': expiry,
                                   'Discount': discount}

    elif run == '2':
        for i in market:
            item = market[i]
            print("Item No - %d Description - %s Stock - %d Price - %.2f Expiry - %s Discount - %s" % (
            i, item['Description'], item['Stock'], item['Price'], item['Expiry'], item['Discount']))

    elif run == '3':
        remove = int(input('Key in item number to remove: '))
        del market[remove]

    elif run == '4':
        market = sort_menu(market, insertionSort)

    elif run == '5':
        market = sort_menu(market, bubble_sort)

    elif run == '6':
        key = int(input('Enter key you want to search: '))
        print(binarysearch(market, key))

    elif run == '7':
        print('')
        print('Total stock level is',total(market), 'and Average stock level is', average(market))
        print('')

    else:
        quit = str()
        while quit.upper() != "Q":
            quit = input("Enter Q or q to return to Main Menu. ")
            if quit.upper() == "Q":
                print('Thank you for using MamaStore!')
                menu()

希望对您有所帮助!

您混淆了键和索引的概念。当你添加一个项目时,你给它键 len(market) + 1 也就是 5 + 1。因此键 '5' 没有被使用,你得到一个键为 1, 2, 3, 4, 6

下一次,当您开始排序时,您尝试使用这些键作为索引。使用 range(y - 1, 0, -1),您迭代了一组连续的整数,因此在 key='5' 上出现了键错误。您应该遍历键。要获取字典的索引,请使用例如

for i, d in enumerate(market):...

删除项目时会出现同样的问题。键被删除留下一个字典,例如键:0、1、2、4。你现在在 key='3'

上得到一个键错误

希望这能提供足够的线索来更正您的脚本。