Question: can anyone help me to implement function in this using for loops. def clamp(alist,min,max): Modifies alist so that every element is between min and
can anyone help me to implement function in this using for loops. def clamp(alist,min,max): """ Modifies alist so that every element is between min and max. Any number in the list less than min is replaced with min. Any number in the tuple greater than max is replaced with max. Any number between min and max is left unchanged. Examples: If a = [-1, 1, 3, 5], clamp(a,0,4) changes a to [0,1,3,4] If a = [-1, 1, 3, 5], clamp(a,-2,8) changes a to [-1,1,3,-5] If a = [-1, 1, 3, 5], clamp(a,-2,-1) changes a to [-1,-1,-1,-1] If a = [], clamp(a,0,4) returns [] Parameter alist: the list to modify Precondition: alist is a list of numbers (float or int) Parameter min: the minimum value for the list Precondition: min <= max is a number Parameter max: the maximum value for the list Precondition: max >= min is a number """
#code list1=[] for x in alist: if x < min: x = min list1.append(x) elif x > max: x = max list1.append(x) elif x>=min and x <=max: list1.append(x) return list1 #error
The call clamp([-1, 1, 3, 5], 0, 4) returns [0, 1, 3, 4], not None. #Test cases def test_clamp(): """ Test procedure for function clamp(). """ print('Testing clamp()') alist = [-1, 1, 3, 5] result = funcs.clamp(alist,0,4) introcs.assert_equals(None,result) introcs.assert_equals([ 0, 1, 3, 4],alist) alist = [-1, 1, 3, 5] result = funcs.clamp(alist,-2,8) introcs.assert_equals(None,result) introcs.assert_equals([-1, 1, 3, 5],alist) alist = [-1, 1, 3, 5] result = funcs.clamp(alist,-2,-1) introcs.assert_equals(None,result) introcs.assert_equals([-1,-1,-1,-1],alist) alist = [-1, 1, 3, 5] result = funcs.clamp(alist,1,1) introcs.assert_equals(None,result) introcs.assert_equals([ 1, 1, 1, 1],alist) alist = [-1, 4, -1, 4, 2] result = funcs.clamp(alist,0,4) introcs.assert_equals(None,result) introcs.assert_equals([ 0, 4, 0, 4, 2],alist) alist = [ 1, 3] result = funcs.clamp(alist,0,4) introcs.assert_equals(None,result) introcs.assert_equals([ 1, 3],alist) alist = [] result = funcs.clamp(alist,0,4) introcs.assert_equals(None,result) introcs.assert_equals([],alist) Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
