插入和冒泡排序部分起作用

问题描述 投票:1回答:2

全部是Python的数据结构和算法的新手。我在广告资源计划中实现了插入和气泡排序。在对当前词典进行排序时,插入和冒泡排序都可以使用。但是,在添加新项目或从字典中删除项目之后,我的插入和冒泡排序获得了关键错误。我曾尝试将字典更改为[{description ..}],并且之前也将market [len(market)+ 1]更改为market [len(market)]。这些都不起作用。如果有人帮助我编辑代码或向我解释发生了什么,我将非常感谢。预先谢谢您:“)

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()
python algorithm sorting insertion
2个回答
0
投票

插入代码的问题是,您通过跳过每次插入一个索引来插入新元素。最初市场的大小为5,所以当您插入新元素时,该元素应位于索引5(起始索引为0),但market [len(market)+1]则插入索引6。因此,当您在排序中运行顺序循环时因为您没有5作为密钥,所以会引发密钥错误。类似地,在删除任何项目时,在删除过程中,序列中断会导致键错误,就像在插入情况下一样。您可能应该考虑在字典的键(在您的情况下是那些项ID)上运行循环。希望对您有所帮助!


0
投票

您正在混合使用键和索引的概念。当您添加项目时,您给它指定密钥len(market)+ 1,即5 +1。因此,密钥“ 5”未使用,您将获得包含密钥1,2,3,4,6的字典

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

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

删除项目时也会发生相同的问题。密钥被删除,留下带有例如密钥的字典:0、1、2、4。您现在在key ='3'

上遇到密钥错误

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

© www.soinside.com 2019 - 2024. All rights reserved.