list index out of range - CodingBat Problem - Has22

DOBS

Here's the problem.

This is part of the List-2

Medium python list problems -- 1 loop.

  • Given an array of ints, return True if the array contains a 2 next to a 2 somewhere.

    has22([1, 2, 2]) → True
    has22([1, 2, 1, 2]) → False
    has22([2, 1, 2]) → False


I was getting the error "list index is out of range" at first

I know where I was going wrong on line 4 of the original problem because once it is at the last number in the list it cannot add one anymore.

I have provided my original code below. The first code block was when I was getting the error "index out of range". The second solution works but I am wondering if there is a cleaner way of writing it.

Also on CodingBat when I run my solution it says "Other Tests" Failed at the bottom but no example I'm not sure what that means.

Thanks

Here's my code block - FIRST TRY:

def has22(nums):
    for i in range(len(nums)):
        first = nums[i]
        second = nums[i+1]
    if first == second:
    return True

MY SOLUTION:

def has22(nums):
    size = len(nums)
    for i in range(len(nums)):
        first = nums[i]
        if size >= i+2:
            second = nums[i+1]
        if first == second:
            return True
    return False
radoh

So if the question is whether the solution can be written cleaner, I think something like this should work:

def has22(nums):
    return (2, 2) in zip(num, num[1:])

and it looks pretty clean.

A little bit of explanation - zip creates pairs of values from 2 lists, so I just slice the input list into 2, where in the second list I omit the first element. Then I simply check whether tuple 2, 2 exists in the zipped pairs.

BTW I just noticed a bug in your solution - it returns True for input e.g. [2, 1] (basically any input, where 2 is second to last. So to fix this bug, and preserve the original "idea" of your solution, you could write it like this:

def has22(nums):
   for i, el in enumerate(nums):
       if el == 2 and i + 1 < len(nums) and nums[i + 1] == 2:
           return True
   return False

enumerate is the preferred way of iterating through a list with indices.

Эта статья взята из Интернета, укажите источник при перепечатке.

Если есть какие-либо нарушения, пожалуйста, свяжитесь с[email protected] Удалить.

Отредактировано в
0

я говорю два предложения

0обзор
Войти в системуУчаствуйте в комментариях

Статьи по теме

Ошибка «List index is out of range» для доступа к атрибуту в следующем макете

list index out of range - списки Python с одним элементом

Почему я получаю «IndexError: list index out of range» во время цикла for, на полпути красивого парсинга супа?

Почему эта программа выдает ошибку IndexError: list index out of range, но только иногда

tkinter list index out of range

String to list index out of range

List index out of range Error in python ,but index is in range how is it?

IndexError: list index out of range python 3.6

Keras ImageGenerator : IndexError: list index out of range

Python - Split Function - list index out of range

python append to nested list , index out of range

list index out of range python1

IndexError: list index out of range for loop in python

Python list index out of range - Algorithm

Python regex findall list index out of range

IndexError: list index out of range in Reversal of arrays

IndexError: list index out of range in PyCharm

Программа продолжает выходить из строя bc of list index out of range error

AzureML schema "list index out of range" error

Can't figure out how to fix "list index out of range"

Getting IndexError: string index out of range for a python problem

Python IndexError: list index out of range when using a list as an iterable

.split() function giving IndexError: list index out of range with beautifulsoup

IndexError: list index out of range in if else when condition matches

Python list index out of range, even after delimiting the indexes

list index out of range Error Pygame How To Fix?

Erro "List index out of range" no arquivo Python 3

Python web scrapping "IndexError: list index out of range"

list index out of range - pre-order traversal of BST

TOP список

  1. 1

    Распределение Рэлея Curve_fit на Python

  2. 2

    Редактировать существующий файл Excel C # npoi

  3. 3

    Резервное копирование / восстановление kafka и zookeeper

  4. 4

    Flutter: Unhandled Exception: FileSystemException: Creation failed, path = 'Directory: '' (OS Error: Read-only file system, errno = 30)

  5. 5

    Ipython использует% store magic для получения динамического имени

  6. 6

    Как получить список индексов всех значений NaN в массиве numpy?

  7. 7

    Bogue étrange datetime.utcnow()

  8. 8

    Как добавить Swagger в веб-API с поддержкой OData, работающий на ASP.NET Core 3.1

  9. 9

    В типе Observable <unknown> отсутствуют следующие свойства из типа Promise <any>.

  10. 10

    Дженерики и потоки Java

  11. 11

    Как изменить значок приложения для проекта libgdx android

  12. 12

    Почему бы не выдать ошибку ERROR в тесте Jasmine?

  13. 13

    Выполнение команд PowerShell в программе Java

  14. 14

    How to convert C++/CLI string to const char*

  15. 15

    Почему actionPerformed выполняется двумя потоками?

  16. 16

    Как отфильтровать несколько столбцов в Qtableview?

  17. 17

    Passing Core Data objects from UITableViewCell to another View Controller

  18. 18

    discord.py: on_message (message) не работает несколько дней

  19. 19

    Как прикрепить файл как вложение к письму с помощью SendGrid?

  20. 20

    Динамическое создание точек / квадратов внутри Picturebox

  21. 21

    Строка не читается после новой строки из .env в nodeJs

популярныйтег

файл