Write a Python function called all_change_to_max_end that takes as input a list of integers, determines which is larger, the first or last element in the list, and then sets all the other elements to be that value. Output the changed list.
Sample inputs and output:
all_change_to_max_end([1, 2, 4, 9, 3]) # should be [3, 3, 3, 3, 3]
all_change_to_max_end([11, 5, 9]) # should be [11, 11, 11]
all_change_to_max_end([2, 11]) # should be [11, 11]
I've tried using:
def all_change_to_max_end(a_list):
return max(a_list) * len(a_list)
but this does not work as it multiples the largest number by the total length
all_change_to_max_end([2, 10, 4, 8]
40
Any help would be greatly appreciated!
You need to check the max of these two elements (first and last)
def all_change_to_max_end(a_list):
return [max(a_list[0], a_list[-1])] * len(a_list)
The correct answer is: [max(a_list[-1], a_list[0])] * len(a_list)
.
Pass a list in this function:
def all_change_to_max_end(x):
#select maximum and converting it to list
return [max(x[0], x[-1])]*(len(x))
numbers = [1, 5, 8, 4, 3, 7, 9, 7]
print(all_change_to_max_end(numbers))
Out[79]: [7, 7, 7, 7, 7, 7, 7, 7]
Do this change
When you do max(list) it returns a value not a list so multiplying it to a number is simple multiplication.
max(list) * len(list) #let max = 10 and length = 4, then its output is 40
so do
[max(list[0],list[-1])]
This is sample output
>>> a = [1, 2, 4, 9, 3]
>>> def all_change_to_max_end(a_list):
... return [max(a_list[0],a_list[-1])] * len(a_list)
...
>>> all_change_to_max_end(a)
[3, 3, 3, 3, 3]
you can do:
def all_change_to_max_end(l):
a = l[0]
b = l[-1]
return [max(a,b)] * len(l)
print(all_change_to_max_end([11, 5, 9]))
output
[11, 11, 11]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.