Python – 列表中的第一个偶数
有时,在使用列表时,我们可能会遇到需要提取某些第一次出现的数字的问题。这也可以是偶数。这种问题在日常和竞争性编程中很常见。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是可以执行此任务的蛮力方式。在此,我们循环遍历列表,当第一次出现偶数时,我们存储并中断循环。
# Python3 code to demonstrate
# First Even Number in List
# using loop
# Initializing list
test_list = [43, 9, 6, 72, 8, 11]
# printing original list
print("The original list is : " + str(test_list))
# First Even Number in List
# using loop
res = None
for ele in test_list:
if not ele % 2 :
res = ele
break
# printing result
print ("The first even element in list is : " + str(res))
输出 :
The original list is : [43, 9, 6, 72, 8, 11]
The first even element in list is : 6
方法#2:使用二分查找(排序列表)
当我们对列表进行排序时,也可以在列表上使用二进制搜索。在这种情况下,我们会在找到一个时继续寻找更小的偶数项,并在找不到时移动到后端。
# Python3 code to demonstrate
# First Even Number in List
# using binary search
# Initializing list
test_list = [3, 7, 8, 9, 10, 15]
# printing original list
print("The original list is : " + str(test_list))
# First Even Number in List
# using binary search
res = len(test_list)
low = 0
high = len(test_list) - 1
while low <= high:
mid = (low + high) // 2
if test_list[mid] % 2:
low = mid + 1
else:
res = test_list[mid]
high = mid - 1
# printing result
print ("The first even element in list is : " + str(res))
输出 :
The original list is : [3, 7, 8, 9, 10, 15]
The first even element in list is : 8