2 3 # Consider a list of values, xs. Find and return the value at location index
ID: 3936073 • Letter: 2
Question
2 3 # Consider a list of values, xs. Find and return the value at location index. 4 # If index is invalid for xs, return response instead. Remember that .get() 5 # for dictionaries works gracefully for non-existing keys. Here we are 6 # implementing a get() function for list type. 7 # -Parameters: 8 # -xs :: list of values of any length. 9 # -index :: an integer, specifying which value in the list to return. 10 # -response :: a python value, to be returned when index is invalid for the 11 # list. Defaults to None. 12 # -Return value: a value from xs at index or the pre-set response 13 # -suggestion : use try-except blocks in your solution. 14 # -Examples: 15# -get(['a','b','c'],0) 16 # -get(('a','b','c'],3) 17 # -get(['a",'b','c'],4,"oops" ) --> 'oops ' 18 19 def get(xs, index, response None): 20 return "not yet implemented" 21 NoneExplanation / Answer
def get( xs, index, response=None):
if( index >= len(xs) or index < 0):
return response;
return xs[index];
print get( ['a','b','c'], 0 );
print get( ['a','b','c'], 3 );
print get( ['a','b','c'], 4, "oops" );
def classify( input_string ):
input_string= input_string.split(" ");
numbers= [];
words = [];
for x in input_string:
try:
x = int(x);
numbers.append(x);
except:
if x <> '':
words.append(x);
return [ numbers, words ];
def shelve( inventory, product_list ):
for p in product_list:
try:
inventory[ p[0] ] = inventory[ p[0] ] + p[1];
except:
inventory[ p[0] ] = p[1];
if inventory[ p[0] ] < 0:
raise ValueError('negative amount for '+ p[0] );
return None;
d = {"kiwi":999};
shelve(d,[("kiwi",-2000)]);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.