정렬된 숫자가 있는 목록이 주어지면 주어진 숫자 범위에서 누락된 숫자를 찾고 싶습니다.
범위 포함
for 루프를 설계하여 숫자 범위를 확인하고 not in 연산자와 함께 if 조건을 사용하여 누락된 요소를 확인할 수 있습니다.
예
listA = [1,5,6, 7,11,14]
# Original list
print("Given list : ",listA)
# using range
res = [x for x in range(listA[0], listA[-1]+1)
if x not in listA]
# Result
print("Missing elements from the list : \n" ,res) 출력
위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -
Given list : [1, 5, 6, 7, 11, 14] Missing elements from the list : [2, 3, 4, 8, 9, 10, 12, 13]
ZIP 포함
ZIP 기능
예
listA = [1,5,6, 7,11,14]
# printing original list
print("Given list : ",listA)
# using zip
res = []
for m,n in zip(listA,listA[1:]):
if n - m > 1:
for i in range(m+1,n):
res.append(i)
# Result
print("Missing elements from the list : \n" ,res) 출력
위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -
Given list : [1, 5, 6, 7, 11, 14] Missing elements from the list : [2, 3, 4, 8, 9, 10, 12, 13]