[英]Python loops with break and continue
給定一組 N 個實數 = [10.10, 6.4, 7.3, 2.2, 1.1, 0, 5.5, -2.3]。 如果從集合開始的每個第二個元素形成一個降序,則輸出0; 否則,打印違反模式的第一個數字的數字。
numbers = [10.10, 6.4, 7.3, 2.2, 1.1, 0, 5.5, -2.3]
i = 1
while i < len(numbers) - 1:
if all(numbers[i+1] <= numbers[i] for i in range(0, len(numbers), 2)):
print(0)
break
i += 2
else:
print(1)
但這是不正確的,如果我將例如 7.2 更改為 2.2 並且我不寫什么,輸入仍然是 0 你能幫幫我嗎?
單循環方法,僅使用zip
構建序列“序列中的第二個數字”。
numbers = [10.10, 6.4, 7.3, 2.2, 1.1, 0, 5.5, -2.3] # -> 0
#numbers = [10.10, 6.4, 7.3, 202.2, 1.1, 0, 5.5, -2.3] # -> 6.4
# every 2-nd term
numbers_by_step_2 = numbers[1::2]
is_decreasing = True
for i, j in zip(numbers_by_step_2, numbers_by_step_2[1:]):
# check if decreasing
is_decreasing = is_decreasing and i >= j
if not is_decreasing:
print(i)
break
# global check (instead of all-built-in)
if is_decreasing:
print(0)
可以這樣解決
numbers = [10.10, 6.4, 7.3, 2.2, 1.1, 0, 5.5, -2.3]
every_second_number = numbers[1::2] # more info: slices
current_max = float('inf') # can be used any big integer
sequence_is_correct = True
for i in every_second_number:
if i < current_max:
current_max = i
else:
sequence_is_correct = False
print(i)
break
if sequence_is_correct:
print(0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.