In: Computer Science
You are not allowed to import anything • You are not allowed to use slicing • You are not allowed to use sets or dictionaries • You are not allowed to use any string method • You are not allowed to use anything that hasn’t been covered in class • No built-in function except range() and len() is allowed • From list methods, you are allowed to use .append(), .insert(), .remove() or del. Please do not ask on piazza whether you can use .sort(), sorted(), .index(), .count() etc.
mashup(lst) [20pts] Description: Creates a new string that is based on the provided list. Each number in the list specifies how many characters from the string that follows belong in the resulting string. Parameters: lst is a list of variable size, that contains alternating ints and strings Assumptions: When a pair of values doesn’t make sense, throw out that pair. When you have an empty string in the list, move on to the next pair. When you have a number that is larger than the length of the string, move on to the next pair, etc. Return value: the new string that is generated from the replacements
examples:
mashup([3, '', 1, 'QHnwq', 5, 'UgJoSwnkq']) == 'QUgJoS'
mashup([2, 'abc', 1, 'def']) → 'abd'
mashup([3, 'rate', 2, 'inside', 1, 'goat']) → 'rating
In this program, we have to form a string from the first n characters of each string given in the list, where n is given in the index preceding these strings.
Inorder to do this, we will be seperating the lenghts and strings from the list and store them into two seperate lists, named lens and strings.
Then, we will define an empty string finalString. This string will store the string to be returned
Then, loop through each element in lens and strings. If the length of the current string in 0, then move on to next iteration. if the current element in lens in greater than the length of current string, then move on to next iteration. Otherwise, append the first n charaters in strings to finalString, here n is the current element in lens
after the loop , return finalString
program:
def mashup(lst):
finalString = ""
lens = lst[0:-1:2]
strings = lst[1::2]
for i in range(len(lens)):
if len(strings[i])==0:
continue
if lens[i] > len(strings[i]):
continue
finalString += strings[i][:lens[i]]
return finalString
sample function call:
print(mashup([3, '', 1, 'QHnwq', 5, 'UgJoSwnkq']))
print(mashup([2, 'abc', 1, 'def']))
print(mashup([3, 'rate', 2, 'inside', 1, 'goat']))
output: