我正在學校撰寫這個程式,我的老師希望我們將 5 個數字輸入到一個串列中,如果數字串列不是按從小到大的順序排列的,那就是說串列首先出問題的地方。
我的代碼:
#Function Definititions
def start():
list = []
for i in range(0,5):
number = int(input("Enter a number: "))
list.append(number)
flag = 0
i = 1
while i < len(list):
if(list[i] < list[i-1]):
flag = 1
i = 1
if(not flag) :
print("This list of numbers is true.")
else:
print("This list of numbers is false. List became out of order at", )
list = sorted(list, reverse=False)
print("True Version:",list)
return flag
#Main Program
start1 = start()
我想說像 10,4,5,8,10 之類的串列首先出問題的地方,在這種特殊情況下,它會在 list[0] 處。我無法添加任何已內置到 Python 中的快捷函式,我的代碼中顯示的部分 print("This list of numbers is false. List become out of order at", )是我想添加它的地方,這就是為什么我在我的程式中將其留空。我的程式中的其他一切都正常作業,因此如果找不到解決方案也沒關系,但是如果有人知道該怎么做,我會全力以赴。
uj5u.com熱心網友回復:
像這樣的東西
# Function Definitions
def start():
my_list = []
for i in range(0, 5):
number = int(input("Enter a number: "))
my_list.append(number)
flag = False
i = 1
while i < len(my_list):
if my_list[i] < my_list[i - 1]:
# found out of order element
flag = True
print(f'Out of order at {my_list[i - 1]}') # print the element
break # no need to continue
i = 1
if not flag:
print("This list of numbers is true.")
return flag
# Main Program
start1 = start()
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/342957.html
