Fill This Form To Receive Instant Help

Help in Homework
trustpilot ratings
google ratings


Homework answers / question archive / Please explain how I would write a recursive function num_pairs( L, n ) whose inputs are L, a list of numbers, and n, an integer

Please explain how I would write a recursive function num_pairs( L, n ) whose inputs are L, a list of numbers, and n, an integer

Computer Science

Please explain how I would write a recursive function num_pairs( L, n ) whose inputs are L, a list of numbers, and n, an integer. num_pairs should return the number of times two consecutive numbers in L have a sum of n.

Here are four examples of input and output for num_pairs: 

 

In : num_pairs([], 5)

Out: 0

 

In : num_pairs([42], 42)

Out: 0

 

In : num_pairs([0,42,0], 42)

Out: 2

 

In : num_pairs([2,40,2,4,38], 42)

Out: 3

 

Below, implement this num_pairs function (no docstring needed) using recursion or a list of lists. (You may call front_sum(L,n) in your code, if you find that helpful!)

 

Please explain how I would use front_sum(L,n) in this code:

def front_sum(L, n):

  if len(L) <2:

    return False

  if sum(L[:2]) == n:

    return True

  else:

    return False

 

 

def num_pairs ( L, n ):

pur-new-sol

Purchase A New Answer

Custom new solution created by our subject matter experts

GET A QUOTE

Answer Preview

Here is the python code for the function num_pairs which uses recursion to find the pair of consecutive numbers in the list whose sum is equal to the given value.

Follow comments for the explanation of the code. A screenshot of the output with the given test cases has been provided for reference.

Do comment if you have any issues with the code

 

Step-by-step explanation

Python Code:

# Given function front sum
def front_sum(L, n):

  if len(L) <2:

    return False

  if sum(L[:2]) == n:

    return True

  else:

    return False
# Define num_pairs function
def num_pairs(L,n):
  # Use innner recursion function which uses recursion to calculate the count of pair of consecutive numbers with sum =n
  def recursive_count(L,n,count):
    # If size of list is less than 2 return the incremented count is um is equal to n else return the count itself
    if  len(L)<=2:

      return count+1 if front_sum(L,n) else count
    # check first two pairs sum is equal to n. If equal increment the count and calll the function recursively with removing the first element of the list else do the same without incrementing the count    
    elif front_sum(L[:2],n):
      count+=1
      L = L[1:]
      return recursive_count(L,n,count)
    else:
      L = L[1:]
      return recursive_count(L,n,count)

  # return the value returned by inner recursive function
  return recursive_count(L,n,0)
  # Test case
print(num_pairs([2,40,2,4,38],42))

Screenshot of output(see the output in the top right of the image in the console):

please see the attached file.

Related Questions