Write a recursive function called inverse_pair with a single parameter L, which
ID: 3679512 • Letter: W
Question
Write a recursive function called inverse_pair with a single parameter L, which is a list of integers. The function returns True if L contains a pair of integers whose sum is zero and False otherwise. The base case occurs when the list has exactly two integers (since it doesn’t make sense to talk about a “pair” of integers for lists with fewer than two elements). For example, inverse pair should return False for the list [12, 8, 10, -5] and True for the list [12, 5, 10, -5, -9]. Your function should consist only of the base case and the recursive calls. As above, all usual restrictions apply for the recursive implementation.
Please use correct indentation and this is to be written in Python 3.4
Explanation / Answer
python program:
def inverse_pair(L):
if len(L)!=1:
for i in range(1,len(L)):
if (L[0]+L[i])==0 :
return 1
del L[0];
return inverse_pair(L)
else:
return 0
ip=inverse_pair( [12, 8, 10, -5])
if ip==1:
print "list [12, 8, 10, -5] have inverse pair";
else:
print "list [12, 8, 10, -5] don't have inverse pair";
ip=inverse_pair( [12, 5, -51, -121, -5])
if ip==1:
print "list [12, 5, -51, -121, -5] have inverse pair";
else:
print "list [12, 5, -51, -121, -5] don't have inverse pair";
output:
list [12, 8, 10, -5] don't have inverse pair
list [12, 5, -51, -121, -5] have inverse pair
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.