Question
My code below is not outputting the correct values and not sure how to fix it. NOTE: This function returns a new list (copying the
My code below is not outputting the correct values and not sure how to fix it.
NOTE: This function returns a new list (copying the first). The original list should not be modified.
The call clamp([-1, 1, 3, 5], 0, 4) returns [0], not [0, 1, 3, 4].
def clamp(alist,min,max): """ Returns a copy of alist where 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: clamp([-1, 1, 3, 5],0,4) returns [0,1,3,4] clamp([-1, 1, 3, 5],-2,8) returns [-1,1,3,-5] clamp([-1, 1, 3, 5],-2,-1) returns [-1,-1,-1,-1] clamp([],0,4) returns [] Parameter alist: the list to copy 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 """ newlist = [] for i in range(len(alist)): if alist[i] < min: newlist.append(min) elif alist[i] > max: newlist.append(max) else: newlist.append(alist[i]) return newlist
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started