[英]Insertion and Bubble Sort partially working
我是 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()
插入代碼的問題是您通過每次插入跳過一個索引來插入新元素。 市場的初始大小為 5,因此當您插入新元素時,該元素應在索引 5 處為 go(起始索引為 0),但 market[len(market)+1] 在索引 6 處插入。因此,當您在排序中運行順序循環時它會拋出一個鍵錯誤,因為你沒有 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' 上得到一個鍵錯誤
希望這能提供足夠的線索來更正您的腳本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.