问题陈述: 当且仅当它具有以下结构时才接受数组:
其中:
即使这个问题的算法看起来很容易实现,但我对代码有些困难。这是我写的。
print("Enter list: ")
arr = [int(x) for x in input().split()]
print(arr)
i = 0
if arr[0] == 1: # to check whether input starts with a 1.
if arr[i] == 1: #If next number is also 1, then
while arr[i] == 1: #while numbers are equal to 1, increment i
i = i + 1
if arr[i] == 2: #If next number is 2, then
while arr[i] == 2: #same procedure as above ... and so on
i = i + 1
if arr[i] == 3:
while arr[i] == 3:
i = i + 1
if arr[i] == 4:
while arr[i] == 4:
i = i + 1
if arr[i] == 5:
while arr[i] == 5:
i = i + 1
if arr[i] == 6:
while arr[i] == 6:
i = i + 1
if arr[i] == 7:
while arr[i] == 7:
i = i + 1
if arr[-1] == 7: #to check if last number is a 7
print("Accepted")
else:
print("not")
else:
print("not")
else:
print("not")
else:
print("not")
else:
print("not")
else:
print("not")
else:
print("not")
else:
print("not")
else:
print("not")
我似乎在得到某种索引错误:
while arr[i] == 7:
IndexError: list index out of range
我不明白为什么遇到这个错误。据我所知,我没有超过列表索引。
答案 0 :(得分:1)
你可以试试这个:
def is_accepted(arr):
return arr[0] == 1 and all(arr[i] -1 == arr[i-1] or arr[i] == arr[i-1] for i in range(1, len(arr)))
print(is_accepted([1, 2, 3, 4, 5, 6, 7]))
输出:
True
第二份清单:
s = [1, 2, 3, 4, 5, 5, 4, 3, 5, 6, 7]
print(is_accepted(s))
输出:
False
上次输入:
s = [1, 1, 2, 2, 3, 3, 3, 4, 5, 6, 6, 7]
print(is_accepted(s))
输出:
True
答案 1 :(得分:0)
递归的有趣练习。
写下以下情况:
列表为空
列表中的第一项少于last_checked作为短路
递归匹配。
def match(lst, last_checked=1): if lst == []: return True # base case if lst[0] < last_checked: return False return True and match(lst[1:], lst[0])