我正在努力解决这个问题:
偶数索引的数字按降序排列,奇数索引的数字则按升序排列">
这是我的代码:
def Sorted(lst):
if not lst:
return not lst
if lst[0]>lst[2] and lst[1]>lst[3]:
return Sorted(lst[:-1])
def main():
n=int(input("enter length of the list: "))
lst=[]
print("enter places of the list:")
for i in range (n):
lst.append(int(input()))
print(Sorted(lst))
main()
您必须以两步为一步前进,而不是切换偶数/奇数索引。这将影响你的基本情况。此外,您还必须对列表的长度进行一些检查,以避免出现索引错误:
def is_sorted(lst):
if len(lst) < 3:
return True
if lst[0] < lst[2]:
return False
if len(lst) > 3 and lst[1] > lst[3]:
return False
return is_sorted(lst[2:])