문제 설명
반환된 목록에서 장소가 바뀐 항목 삭제 (Deleting items that have the place swapped around in a returned list)
내 함수는 숫자와 숫자 목록을 사용합니다.
목록에 있는 2개의 숫자가 원래 숫자에 더해진다면 [Num1, Num2]
형식입니다. .
이제 "중복"을 원하지 않습니다. 즉, [4, ‑7]
만 반환되고 [4, ‑7], [‑ 7, 4]
.
def pairs(n, num_list):
newest_list = []
for j in range(len(num_list)):
for i in range(len(num_list)‑1):
if num_list[j] + num_list[i+1] == n:
newest_list.append([num_list[j], num_list[i+1]])
return newest_list
이제 코드를 게시하는 것보다 간단한 힌트를 원합니다. 제 질문은 다음과 같습니다.
내 코드 내에서 그렇게 할 수 있는 능력이 있습니까? 그렇다면 힌트가 좋을 것입니다. 아니면 그렇게 하기 위해 다른 함수를 정의해야 합니까?
참조 솔루션
방법 1:
You definitely have the ability to do that within your code.
A hint to complete this would be to think about at what point in your code it makes sense to stop searching for further matches and to return what you've found. Let me know if that's too cryptic!
방법 2:
You can still do that in your current code by simply appending these two numbers into a Set. For more info, this will help you.
방법 3:
When adding a pair [a, b]
to the result list, sort the pair, then see if it's in the result list. If so, don't add it.
Also, consider using a Python set.
방법 4:
if you have 2 lists l1, and l2 where:
l1=[1,2]
l2=[2,1]
If you convert them to sets, you can compare them and they will evaluate to True if they have the same elements, no matter what the order is:
set(l1) == set(l2) # this evaluates to True
In your if condition, before appending the numbers, you can check if the set set([num_list[j], num_list[i+1]])
is already in newest_list
.
I am tempted to write some code, but you said not to, so I'll leave it here :p
방법 5:
You can leave your code the way it is, but before you return the list, you can filter
the list with a predicate that the pair [a,b]
is only accepted if pair [b,a]
is not in the list
(by RonaldB、Qichao Zhao、eshirima、johntellsall、JesusAlvSoto、smac89)