读取1和0的字符串。计算连续1的数字 和连续0的数量, 直到最后。
例如,
s = "10001110000111"
输出应为:
1 1's
3 0's
3 1's
4 0's
3 1's
我只需要使用字符串函数(没有查找函数)和while / for循环来帮助解决这个问题。
我有这个:
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
我做错了什么?
答案 0 :(得分:3)
这与所谓的“运行长度编码”非常类似,它在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)])
我认为你可以采取这种方式并稍微修改它以做你想做的事。
答案 1 :(得分:1)
如果你想放弃纯语言技巧并使用更惯用的风格,这是一个使用groupby
的好时机,它接受输入并根据键函数返回时将其拆分成组不同的价值。在这种情况下,键功能只是值,所以我们可以省略它。
import itertools
s = "10001110000111"
groups = itertools.groupby(s)
groups
现在是一个groupby
迭代器,它懒惰地评估为:
[('1', ['1']),
('0', ['0', '0', '0']),
('1', ['1', '1', '1']),
('0', ['0', '0', '0', '0']),
('1', ['1', '1', '1'])]
您可以对此进行迭代以查看:
for groupname, group in groups:
length = sum(1 for _ in group)
# group is not a list, it just acts like one, so we can't use len
print("{} {}'s".format(length, groupname))
总之,它看起来像:
import itertools
s = "10001110000111"
groups = itertools.groupby(s)
for groupname, group in groups:
length = sum(1 for _ in group)
print("{} {}'s".format(length, groupname))
并返回
的结果1 1's
3 0's
3 1's
4 0's
3 1's
答案 2 :(得分:0)
您可以使用index
字符串方法在每一步中查找下一个序列和修剪源字符串:
s = "10001110000111"
while s:
try:
count = s.index("0") if s[0] == "1" else s.index("1")
print("{} {}'s".format(count, s[0]))
s = s[count:]
except ValueError:
print("{} {}'s".format(len(s), s[0]))
break