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 22:02:50 浏览: 109
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 True if the array contains a 2 next to a 2 somewhere.
可以使用一个循环遍历整个数组,检查每个元素是否为 2,如果是,则检查下一个元素是否也为 2。如果两个元素都是 2,则返回 True,否则继续循环。如果循环结束后仍未找到相邻的 2,则返回 False。
以下是 Python 代码实现:
```python
def has22(nums):
for i in range(len(nums)-1):
if nums[i] == 2 and nums[i+1] == 2:
return True
return False
```
示例输入和输出:
```python
>>> has22([1, 2, 2])
True
>>> has22([1, 2, 1, 2])
False
>>> has22([2, 2, 1, 2])
True
```
阅读全文