Reputation: 1
I'm trying to find, using dictionaries:
Using two while loops, nested, create a dictionary whose keys are the sum of two cubes. That is iterate through all pairs i and j, calculating i^3+j^3 until it gets too large.
2.Whenever you calculate a new i^3+j^3, check and see if there is already an entry for it.
3.If so, you have found a new pair of numbers the sum of whose cubes, because there is already a pair of number that cube and sum to the same value.
Here is my code: please help me figure what is wrong with my code.
dit = dict()
j = 1
i = 1
while i < 10:
while j < 10:
summ = i**3+ j**3
if summ in dit:
print(summ, (i,j), dit.get(summ))
else:
dit [summ] = (i,j)
j = j +1
print(dit)
j = 2
i = i + 1
Upvotes: 0
Views: 712
Reputation: 3741
its easy to just generate unique values from the start by creating a 'trianglular outer product' with nested for:
for a in range(1, c//2+1) for b in range(c//2,c)
c = 5
d = [(a**3 + b**3, (a, b)) for a in range(1, c//2+1) for b in range(c//2,c)]
# test for uniqueness
len(d) == len(set(d))
True
d
[(9, (1, 2)),
(28, (1, 3)),
(65, (1, 4)),
(16, (2, 2)),
(35, (2, 3)),
(72, (2, 4))]
d.sort()
d
[(9, (1, 2)),
(16, (2, 2)),
(28, (1, 3)),
(35, (2, 3)),
(65, (1, 4)),
(72, (2, 4))]
Upvotes: 0
Reputation: 1696
You aren't modifying your variables from within your while loop, so the condition never changes. You need to change your indentation a little so that it works.
dit = dict()
j = 1
i = 1
while i < 10:
while j < 10:
summ = i**3+ j**3
if summ in dit:
print(summ, (i,j), dit.get(summ))
else:
dit [summ] = (i,j)
j = j +1
print(dit)
j = 2
i = i + 1
Upvotes: 0