Given an array of ints, return True if the array contains a 2 next to a 2 somewhere.
时间: 2024-05-16 20:18:12 浏览: 11
可以使用一个循环遍历整个数组,检查每个元素是否为 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
```
相关问题
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.
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)