python 3.x - Using recursion check each pair in a list, if their sum is negative return True else return False -


This is what I've done so far.

  def negative_som (L): if len (L) == 2: If L [0] + L [1]  0: Returns True else: return False else: return negative_ sum (L [0] + negative_sum (L [1:]))   

My base case must be correct. My problem is with my last statement and I need to check the sum of each pair in the list. I have a lot of trouble trying to recur this time. Any advice is highly appreciated. Apart from this I can not use for loop.

A while loop is equivalent to 'tail recycle' with an executable frame . It is easy to express some problems with recursion, with others loop. Generating pairs are easily done with nested for loops.

  def pairs1 (seq``): n = len (seq) pairlist = [] in the range i (0, n -1): in the range of j (i + 1, n) For: pairlist.append ((seq [i], seq [j]) Return Pinistist inp = (1, 2, 3) = out ([1,2], (1,3), (2,3)] Pair 1 (inp) == out   

I usually use yield pairlist.append . Note to include a test with code. As an intermediate step, change to a while in the loop.

  def pairs2 (seq): jmax = len (seq) - 1 pylist = [] i = 0 j = i + 1 while i & lt; Jmax: pairlist.append ((seq [i], seq [j])) if j & lt; Jmax: j + = 1 else: i + = 1 j = i + 1 return choosist pair 2 assert (inp) == out   

now convert it to a nested use It is not very difficult for the tail to repeat the tail instead of the statement.

  def pair 3 (seq): jmax = len (seq) - 1 pairlist = [] I = 0 j = i + 1 def inner (): Nonlocal i, j if i & lt ; Jmax: pairlist.append ((seq [i], seq [j])) if j & lt; Jmax: j + = 1 else: i + = 1 j = i + 1 inner () inner () Returns pylistva 3 pairs (APP) assures   

Here is a more traditional form .

  DEF pairs 4 (CEC, I, J, Pilist): JMX = Lane (CEC) -1 if I & lt; Jmax: pairlist.append ((seq [i], seq [j])) if j & lt; JMX: Return couples 4 (CEC, I, J + 1, Pilist) Other: Return couples 4 (CEC, I + 1, I + 2, Pilist) Other: Return panelists add pair pairs (IP, 0, 1, []) == A strict functionist will replace the penistist with penaltlal, replace the () with the initial [], and replace the list with topload editions in the recursive call. The first call will look like this.  
  Returns added 4 (Seek, I, J + 1, Jupiter + ((Sek [ii], Seek [j]))   

Python In all joints, an O (O) (N) function is converted to the O (N2) 2 function, so I will not do this.

Comments

Popular posts from this blog

java - ImportError: No module named py4j.java_gateway -

python - Receiving "KeyError" after decoding json result from url -

python - 'NoneType' object is not callable using 'find_all' in BeautifulSoup -