Home > Net >  IndexError: list index out of range: idk where
IndexError: list index out of range: idk where

Time:12-26

Although compilation works successfully I get an error: IndexError: list index out of range

The function takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements. The code i write:

def fnc(l, a):
   print(l)
   if l[a] == l[a 1]:
      del l[a]
      return fnc(l, 0)
   elif l[a] != l[a 1]:
      return fnc(l, a 1)
   elif a == len(l):
      return l

def unique_in_order(txt):
   list = []
   for i in txt:
      list   = [i]
   return fnc(list, 0)

Thanks for help

CodePudding user response:

You don't need to do anything fancy like using recursion just for the sake of it. Python is known for providing many ways to solve the problem but good programmers are known for writing simple code so everyone can understand.

Now coming to your problem. You just need to check if the next word is same or not, if not then store the current word.


input_string = 'AAAABBBCCDAABBB'

# return string without next duplicates and in order

output_list = []
for char in range(len(input_string)):
    if char == len(input_string)-1:
        output_list.append(input_string[char])
    else:
        if input_string[char] != input_string[char 1]:
            output_list.append(input_string[char])

output_string = ''.join(output_list)
print(output_string)
#ABCDAB
  • Related