Exercise 69
Write a Python algorithm which determines for a given integer n the list of tuples of integers (p, q) satisfying:
p2 + q2 = n
Solution
#coding: utf-8
def listTuple (n):
# initialization of the list of couples (p, q)
tupleList = []
# iterate over the set of tuples (p, q) such that p <= n and q <= n
for p in range (0, n + 1):
for q in range (0, n + 1):
if p**2 + q**2 == n:
tupleList.append ((p, q))
return tupleList
# Example n = 1000
print (listTuple (1000)) #output: [(10, 30), (18, 26), (26, 18), (30, 10)]
Younes Derfoufi
my-courses.net
my-courses.net