Read a string of 1's and 0's. Count numbers of successive 1's and number of successive 0's, until the 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 help approaching this using only string functions (no find function), and while/for loops.
I have this:
myString = input("Please enter a string of 0s and 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 am i doing wrong?
This is quite similar to what's called 'run length encoding' which has a nice entry on Rosettacode.org
def encode(input_string):
count = 1
prev = ''
lst = []
for 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 = ""
for 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 be able to take this and modify it a bit to do what you want.