Python Recursion List Sum of Pairs -


i supposed write 2 functions exact same thing implementation different.

the function takes input list of positive integers , positive integer n, , returns true if 2 of numbers in list equal n. otherwise, returns false.

the first function supposed use nested loop, able get.

the second functions not supposed use nested loop. however, supposed sort list out , solve problem.

here have second function.

def pairs2(lst, n):     lst.sort()     if len(lst) == 2:         if lst[0] + lst[1] == n:             return true         else:             return false     elif len(lst) >= 3:         in range(len(lst) - 1):             if lst[0] + lst[i + 1] == n:                 return true         lst.remove(lst[0])         pairs2(lst, n) 

the function works until last 2 lines implemented. after that, doesn't return anything. wrong function?

also, other alternatives not use recursion? came using recursion since first idea got.

a recursive algorithm eliminates largest number @ each recursive step:

def pairs2(lst, n, s=false):      if len(lst) < 2: return false     if not s: lst = sorted(lst)     item in lst:         if item + lst[-1] > n:               return pairs2(lst[:-1], n, true)         if item + lst[-1] == n:             print item, lst[-1]             return true     return false 

the s parameter indicates whether list sorted or not.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -