Python 3.xx - Deleting consecutive numbers/letters from a string -


i need evaluating going on code wrote.

it meant function this:

input: remove_duple('wubbalubbadubdub')  output: 'wubalubadubdub' 

another example:

input: remove_duple('aabbccdd')  output: 'abcd' 

i still beginner , know both wrong code , easier way it. (there lines in code part of efforts visualize happening , debug it)

def remove_duple(string):     to_test = list(string)     print (to_test)     icount = 0     dcount = icount + 1     char in to_test:         if to_test[icount] == to_test[dcount]:             del to_test[dcount]             print ('duplicate deleted')             print (to_test)             icount += 1         elif to_test[icount] != to_test[dcount]:             print ('no duplicated deleted')             print (to_test)             icount += 1     print ("".join(to_test)) 

don't modify list (e.g. del to_test[dcount]) iterating over. iterator screwed up. appropriate way deal create new list values want.

a fix code like:

in []: def remove_duple(s):     new_list = []     in range(len(s)-1):  # 1 less length avoid indexerror         if s[i] != s[i+1]:             new_list.append(s[i])     if s:                      # handle passing in empty string         new_list.append(s[-1]) # need add last character      return "".join(new_list)   # return (print outside function)  remove_duple('wubbalubbadubdub')  out[]: wubalubadubdub 

as looking step through string, sliding 2 characters @ time, can ziping string shifted one, , adding first character if 2 characters not equal, e.g.:

in []: import itertools  def remove_duple(s):     return ''.join(x x, y in it.zip_longest(s, s[1:]) if x != y)  remove_duple('wubbalubbadubdub')  out[]: 'wubalubadubdub'  in []: remove_duple('aabbccdd')  out[]: 'abcd' 

note: need itertools.zip_longest() or drop last character. default fillvalue of none fine string.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -