Question

In: Computer Science

Python3 *Use Recursion* Write a function called smallest_sum(A,L) where A is the value and L is...

Python3 *Use Recursion*

Write a function called smallest_sum(A,L) where A is the value and L is a list of ints.

smallest_sum should return the length of the smallest combinations of L that add up to A

if there are no possible combinations then float("inf") is returned.

Examples

smallest_sum(5, [2, 3]) == 2

smallest_sum(313, [7, 24, 42]) == 10

smallest_sum(13, [8, 3, 9, 6]) == float(‘‘inf’’)

No Loops and map/reduce functions are allowed

Solutions

Expert Solution

python code with explanation in comments (code to copy)

# This recursive function looks for all possible combinations from the list
# L which can make up to A
# The parameters cur_pos represents the current element we are going to add or not add
# cur_sum represents the current sum after adding previous elements
# cur_count represents how many elements we have added so far
def recursion(L, A, cur_pos,cur_sum, cur_count):
    # base case, if we have found a combination thnen return the 
    # number of elements added so far
    if(cur_sum==A):
        return cur_count
    # If our array is over or our current sum has exceeded required sum which is A
    # we can exit the function
    if cur_pos==len(L) or cur_sum>A:
        return float("inf")
    # If we are here, it means that we still need to add more numbers
    # we have two choice either add the current number
    # or not add it
    # Remember that we can use numbers multiple times so if we add the number we dont increase
    # cur_pos but if we dont add it then we increment cur_pos to process next element
    # we call both functions and since we are looking for the minimum we return min of them
    return min(recursion(L, A,cur_pos, cur_sum+L[cur_pos], cur_count+1), recursion(L, A,cur_pos+1, cur_sum, cur_count))

def smallest_sum(A, L):
    return recursion(L, A, 0, 0, 0)

print("smallest_sum(5, [2, 3]) == ", smallest_sum(5, [2, 3]))
print("smallest_sum(313, [7, 24, 42]) == ", smallest_sum(313, [7, 24, 42]))
print("smallest_sum(13, [8, 3, 9, 6]) == ", smallest_sum(13, [8, 3, 9, 6]))

python code screenshot

Code Output Screenshot

Let me know in the comments if you have any doubts.
Do leave a thumbs up if this was helpful.


Related Solutions

-> > Use recursion to write a C++ function for determining if a strings has more...
-> > Use recursion to write a C++ function for determining if a strings has more vowels than consonants. Please include the pseudo code so that I can understand better with simple English as much as possible.
C++ only Write a function decimalToBinaryRecursive that converts a decimal value to binary using recursion. This...
C++ only Write a function decimalToBinaryRecursive that converts a decimal value to binary using recursion. This function takes a single parameter, a non-negative integer, and returns a string corresponding to the binary representation of the given value. Your function should be named decimalToBinaryRecursive Your function should take a single argument An integer to be converted to binary Your function should not print anything Your function should use recursion instead of a loop. Note that if you try to use a...
Use recursion function to derive computation time for Binary Search by drawing a recursion tree diagram...
Use recursion function to derive computation time for Binary Search by drawing a recursion tree diagram and using algebra calculation.
python3 (3a) Write a function, frequent, with one parameter, psw, a string. If psw is in...
python3 (3a) Write a function, frequent, with one parameter, psw, a string. If psw is in a list of frequently used passwords ['password', '12345', 'qwerty', 'letmein', 'trustno1', '000000', 'passw0rd'], frequent should return False; otherwise, return True. Be sure to include at least three good test cases in the docstring. (3b) Password Protection SecuriCorp has recently been the victim of a number of security breaches. Internal analysis has determined that employees use simple passwords that are too easy to guess. You...
Write a function called draw_card. It takes no arguments and returns an integer representing the value...
Write a function called draw_card. It takes no arguments and returns an integer representing the value of a blackjack card drawn from a deck. Get a random integer in the range 1 to 13, inclusive. If the integer is a 1, print "Ace is drawn" and return 1. If the integer is between 2 and 10, call it x, print "<x> is drawn" and return x (print the number, not the string literal "<x>"). If the number is 11, 12,...
Please use python3 Create the function team_average which has the following header def team_average(filename): This function...
Please use python3 Create the function team_average which has the following header def team_average(filename): This function will return the average number of games won by the Red Sox from a text file with entries like this 2011-07-02 Red Sox @ Astros Win 7-5 2011-07-03 Red Sox @ Astros Win 2-1 2011-07-04 Red Sox vs Blue Jays Loss 7-9 This function should create a file object for the file whose name is given by the parameter filename. If the file cannot...
use python to solve Write a function called word_chain that repeatedly asks the user for a...
use python to solve Write a function called word_chain that repeatedly asks the user for a word until either (1) the user has entered ten words, or (2) the user types nothing and presses enter. Each time the user enters an actual word, your program should print all the words entered so far, in one long chain. For example, if the user just typed "orange", and the user has already entered "apple" and "banana", your program should print "applebananaorange" before...
python3 Continue from the previous function, write a draw_table method which draws a table of data....
python3 Continue from the previous function, write a draw_table method which draws a table of data. For example, consider the following code fragment: my_table = Table([['Alice', 24], ['Bob', 19]], width=10) my_table.draw_table() produces: |Alice 24 | |Bob 19 | Note: the column width is the value set up by the constructor. Insert a space in between columns. and my previous function is class Table: def __init__(self,x, h = None, width=5): self.x= x self.h = h self.w= width def __str__(self): return "headers={},...
(Python3) Write a function friend_besties() that calculates the "besties" (i.e. degree-one friends) of a given individual...
(Python3) Write a function friend_besties() that calculates the "besties" (i.e. degree-one friends) of a given individual in a social network. The function takes two arguments: individual, an individual in the social network, in the form of a string ID. bestie_dict, a dictionary of sets of friends of each individual in the social network (as per the first question of the Project) The function should return a sorted list, made up of all "degree-one" friends for the individual. In the instance...
1) Write a function equation(A, B) that returns a value C where A + B =...
1) Write a function equation(A, B) that returns a value C where A + B = C a. Write the equation function: b: Write the output of your function for a few values: 2) Write a non-recursive function called fact(n) that computes n! Try computing fact(n) for large values. Can you find the maximum value for n your program will compute correctly? a) Write your fact function: b) Write the output of your function for a few values: 3) Write...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT