이 기사에서 우리는 k와 같은 정확한 차이를 갖는 숫자 쌍의 수를 계산하는 방법을 볼 것입니다. 주어진 숫자는 목록 형식이며 우리는 프로그램에 k 값을 제공합니다.
for 루프 사용
이 접근 방식에서 우리는 두 개의 for 루프를 디자인합니다. 외부 for 루프는 주어진 목록의 각 요소 방문을 추적합니다. 내부 for 루프는 나머지 각 요소를 외부 루프의 요소와 계속 비교하고 필요한 차이와 일치하면 count 변수의 값을 늘립니다.
예
listA = [5, 3, 7, 2, 9]
k = 2
count = 0
# Elements of the list
for i in range(0, len(listA)):
# Make pairs
for j in range(i + 1, len(listA)):
if listA[i] - listA[j] == k or listA[j] - listA[i] == k:
count += 1
print("Required Pairs: ",count)인 경우 출력
위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -
Required Pairs: 3
While 루프 사용
다른 접근 방식에서는 if else 절과 함께 while 루프 로그인을 사용합니다. 여기서 우리는 두 쌍의 차이가 필요한 차이와 일치하는지 여부에 따라 현재 및 다음 인덱스를 계속 증가시킵니다.
예
listA = [5, 3, 7, 2, 9]
k = 2
count = 0
listA.sort()
next_index = 0
current_index = 0
while current_index < len(listA):
if listA[current_index] - listA[next_index] == k:
count += 1
next_index += 1
current_index += 1
elif listA[current_index] - listA[next_index] > k:
next_index += 1
else:
current_index += 1
print("Required Pairs: ",count) 출력
위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -
Required Pairs: 3