Given an array of ints, return the sum of the first 2 elements in the array. If the array length is less than 2, just sum up the elements that exist, returning 0 if the array is length 0.
时间: 2024-01-27 21:02:50 浏览: 35
Here is the Python code to solve the problem:
```python
def sum2(nums):
if len(nums) == 0:
return 0
elif len(nums) < 2:
return sum(nums)
else:
return nums[0] + nums[1]
```
The `sum2` function takes an array `nums` as input and returns the sum of the first two elements in the array. If the length of the array is less than 2, it sums up all the elements in the array and returns the result. If the array is empty, it returns 0.
You can test the function with different inputs like this:
```python
print(sum2([1, 2, 3])) # Output: 3
print(sum2([1])) # Output: 1
print(sum2([])) # Output: 0
```
相关问题
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.