python - index out of range even after initialization of var serving as index -


i dont understand why out of range if initialize j.

this expansion iterates preceding characters of slash, , when combined space, multiplied.

ie

    5</ --> 5<5<     5<// --> 5<5<5<     5</ / --> 5<5< 5<5< 

also, best way accomplish task?

    def ttexpand( program ) :         """         expand string manipulation symbols in program         tinyturtle language program.         program -- tinyturtle string, possibly string manipulation symbols         returns -- tinyturtle string after expansion         """         new_program = ''         array = []         = 0         j = 0         ch in program: #while program.index(ch) != len(program) - 1:              if ch == '/':                 array.append(program.index(ch))                 += 1         if len(array) == 0:             return program          while j <= len(array):             new_program += (program[:array[j]])             j += 1         return new_program 

this doesn't produce correct result, you're trying do:

#while j <= len(array): in array:     new_program += program[:i] #(program[:array[j]]) 

it appear approach accomplishes want:

def tt_expand(program):     '''     expand string manip symbols      example:      >>> tt_expand('5</')     '5<5<'     >>> tt_expand('5<//')     '5<5<5<'     >>> tt_expand('5</ /')     '5<5< 5<5<'     '''      seen = ''     new_program = ''     prev_token = none     i, token in enumerate(program):         if token == '/':             if prev_token == ' ':                 new_program += new_program.rstrip()             else:                 new_program += seen         else:             new_program += token             seen += token         prev_token = token      return new_program    if __name__ == '__main__':     import doctest     doctest.testmod() 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -