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,...
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...
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...
/*Use recursion in the function: void getDigit( int num) /* Try this program and implement the...
/*Use recursion in the function: void getDigit( int num) /* Try this program and implement the function void getDigit( intnum) so that it displays the digits in a given number. For example, the number, 1234 consist of 1, 2, 3 and 4. This is an exercise to demonstate the use of a recursive function and the use of recusrion in C++ */ #include #include using namespace std; int main() {      int num;      cout <<"Enter an integer: ";     ...
Recursion Part //1. Write out the output for eaching of following: /* Consider this function. void...
Recursion Part //1. Write out the output for eaching of following: /* Consider this function. void myMethod( int counter) { if(counter == 0) return; else { System.out.println(""+counter); myMethod(--counter); return; } } This recursion is not infinite, assuming the method is passed a positive integer value. What will the output be? b. Consider this method: void myMethod( int counter) { if(counter == 0) return; else { System.out.println("hello" + counter); myMethod(--counter); System.out.println(""+counter); return; } } If the method is called with the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT