python - Read a string of 1's and 0's. Count numbers of successive 1's and number of successive 0's, until the end -
read string of 1's , 0's. count numbers of successive 1's , number of successive 0's, until end.
for example,
s = "10001110000111"
output should be:
1 1's 3 0's 3 1's 4 0's 3 1's
i need approaching using string functions (no find function), , while/for loops.
i have this:
mystring = input("please enter string of 0s , 1s: ") zerocount = 0 onecount = 0 index = 0 while index < (len(mystring) -1): if mystring[index] == "0": zerocount += 1 if mystring[index +1] == "1": zerocount = 0 elif mystring[index] == "1": onecount += 1 if mystring[index +1] == "0": onecount = 0 index += 1
what doing wrong?
this quite similar what's called 'run length encoding' has nice entry on rosettacode.org
def encode(input_string): count = 1 prev = '' lst = [] character in input_string: if character != prev: if prev: entry = (prev,count) lst.append(entry) #print lst count = 1 prev = character else: count += 1 else: entry = (character,count) lst.append(entry) return lst def decode(lst): q = "" character, count in lst: q += character * count return q #method call encode("aaaaahhhhhhmmmmmmmuiiiiiiiaaaaaa") decode([('a', 5), ('h', 6), ('m', 7), ('u', 1), ('i', 7), ('a', 6)])
i think you'll able take , modify bit want.
Comments
Post a Comment