Home > database >  Index error in one editor but works in pycharm
Index error in one editor but works in pycharm

Time:04-01

So I'm doing py.checkio.org which is a coding game for python. My task is to reorder elements in a list. I got it working in pycharm but when i copy my solution to checkios editor I get

IndexError: list index out of range
 <listcomp>, 11
 replace_first, 11

Here's my code

from typing import Iterable


def replace_first(items: list) -> Iterable:
    lastdigit=len(items)
    if len(items) == 1:
        return items
    elif len(items) == 0:
        return items
    myorder = [1,2,3,0]
    items=[items[i] for i in myorder]
    return items


if __name__ == "__main__":
    print("Example:")
    print(list(replace_first([1, 2, 3, 4])))

    # These "asserts" are used for self-checking and not for an auto-testing
    assert list(replace_first([1, 2, 3, 4])) == [2, 3, 4, 1]
    assert list(replace_first([1])) == [1]
    assert list(replace_first([])) == []

Any idea why?

The code is not elegant in any way but I don't see why I get a index error in one editor but not the other.

CodePudding user response:

As mentioned in my comment, the code as shown will not induce IndexError. Furthermore, the implementation is overly complex and could be just:

def replace_first(items: list) -> Iterable:
  return items[1:]   items[:1]

CodePudding user response:

Possible solution is the following:

from typing import Union


def change_list_order(items: list, myorder: list) -> Union[list, str]:
    if len(items) <= 1:
        return items
    if len(items) != len(myorder):
        return f"items and myorder lists must have identical qty of elements"
    else:
        items=[items[i] for i in myorder]
        return items
    
print("Example:")
print(change_list_order([1, 2, 3, 4], [1, 2, 3, 0]))

# These "asserts" are used for self-checking and not for an auto-testing
assert change_list_order([1, 2, 3, 4], [1, 2, 3, 0]) == [2, 3, 4, 1]
assert change_list_order([1], [0]) == [1]
assert change_list_order([], [0]) == []
assert change_list_order([1, 2, 3, 4], [1, 2, 3, 0, 5]) == "items and myorder lists must have identical qty of elements"

CodePudding user response:

Never used assert, not sure about it's output, besides that, your second and third assert tried to reorder 1 item and 0 item with 4 indices. Maybe you can change myorder from myorder = [1, 2, 3, 4] to myorder = [1, 2, 3, 4][:len(item)]

  • Related