Given an array of ints length 3, figure out which is larger, the first or last element in the array, and set all the other elements to be that value. Return the changed array.
时间: 2024-02-17 10:00:58 浏览: 23
以下是 Python 代码实现:
```python
def max_end3(nums):
max_num = max(nums[0], nums[-1])
return [max_num] * 3
```
这个函数接受一个长度为 3 的整数数组 `nums` 作为输入,首先比较数组的第一个元素和最后一个元素的大小,然后将其他元素设置为较大的那个值,最后返回修改后的数组。
例如,`max_end3([1, 2, 3])` 的返回值为 `[3, 3, 3]`,`max_end3([2, 2, 1])` 的返回值为 `[2, 2, 2]`。
相关问题
Given an array of ints length 3, return the sum of all the elements.
以下是 Python 代码实现:
```python
def sum3(nums):
return sum(nums)
```
或者可以使用以下代码:
```python
def sum3(nums):
total = 0
for i in nums:
total += i
return total
```
这两个函数都可以接受一个长度为 3 的整数数组 `nums` 作为输入,返回数组中所有元素之和。
Given an array of ints, return a new array length 2 containing the first and last elements from the original array. The original array will be length 1 or more.
Sure, here's the solution in Python:
```python
def make_ends(nums):
return [nums[0], nums[-1]]
```
This function takes an input array `nums` and returns a new array containing the first and last elements of the input array. We use the `[0]` index to access the first element of the array, and the `[-1]` index to access the last element of the array.