How to find all pairs of digits that sum to a specific number
How to find all pairs of digits that sum to a specific number
I am trying to write a Python function that gets a number as input, and prints all pairs of digits within the number that sums into a per-specified number.
My code is:
def f(n,num):
s = str(n)
l =
for digit in s:
l.append(digit)
for i in range(len(l)):
for j in range(len(l)):
if i != j:
if (int(l[i]) + int(l[j]) == num):
print(l[i]," ",l[j])
It works fine, but every pair is printed twice. I couldn't find a way to remove the duplicates and print every pair only once.
Can you assist ? Thank you.
for j in range(len(l)):
for j in range(i+1,len(l)):
Thank you, works now.
– user2899944
Jun 30 at 7:44
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
for j in range(len(l)):
=>for j in range(i+1,len(l)):
and you can drop the i != j test– Jean-François Fabre
Jun 30 at 7:30