The 365 Data Science team is proud to invite you to our own community forum. A very well built system to support your queries, questions and give the chance to show your knowledge and help others in their path of becoming Data Science specialists.
Ask
Anybody can ask a question
Answer
Anybody can answer
Vote
The best answers are voted up and moderated by our team

Two sum solution…mine

Two sum solution…mine

0
Votes
1
Answer
list = [0,1,2,3,4,5]
sum = 5
d = {}

for i in list:
    for j in list:
         if i + j == sum:
               d[i] = j
print(d)
{0: 5, 1: 4, 2: 3, 3: 2, 4: 1, 5: 0}
 

1 Answer

0
Votes

list = [3,4,5,2,5,78,4,3,2,1,5,6,8,9]
sum = 10
d = {}
“””a loop in a loop to create a dictionary with all
the pairs which sum is equal to [sum]”””
for i in list:
   for j in list:
       if i + j == sum:
          d[i] = j

print(f”””
{len(d)} pairs.
{d}”””)
“””Unzip the dictionary [d] in two variables [x,y]
and plotted”””
import matplotlib.pyplot as plt
x,y = zip(*d.items())
plt.scatter(x,y,data=True)
plt.show
 
7 pairs.
{4: 6, 5: 5, 2: 8, 1: 9, 6: 4, 8: 2, 9: 1}