Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to choose the larger of the first and last elements of an array of len(3) and make that all the elements of the array:

def max_end3(nums):
    a = max(nums[0], nums[2])
    for i in nums:
        i = a
    return nums

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
133 views
Welcome To Ask or Share your Answers For Others

1 Answer

So you want to return a new list that is the maximum of the first and last element?

In Python you can access the last element with [-1].

so a solution that doesn't care about the length of the list(minimum one element to work) would look like this:

def set_list_to_max_of_first_last(nums):
    return [max(nums[0], nums[-1])] * len(nums)

What we do here is we use [] to create a new list with one element. Then we make the array as long as the original with identical entries.

HTH


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...