繁体   English   中英

行程编码-计数是后面的变量

[英]Run-Length Encoding - count is a variable behind

uncompressed = raw_input("Enter a string: ")
count = 1
uncompressed = list(uncompressed)
olength = len(uncompressed)
for x in range(olength):
    last = x-1
    current = x+1
    if uncompressed[x] == uncompressed[last]:
        count = count + 1
    else:
        print uncompressed[x], count
        count = 1

如果我要输入laaaava,它将显示l 1 a 1 v 4 a 1

什么时候应该打印l 1 a 4 v 1 a 1

如果这不是学习活动,则可以采用以下方法:

from itertools import groupby

text = 'laaaava'
for k, g in groupby(text):
    print k, len(list(g)),

# l 1 a 4 v 1 a 1

要了解您的版本为何无法正常运行,在遍历循环时可能会帮助您逐步浏览并跟踪变量:

uncompressed = ["l", "a", "a", "a", "a", "v", "a"]

**x = 0:**
last = -1
uncompressed[x] = "l"
uncompressed[last] = "a" # remember in python, negative index wrap around to the end
# these aren't the same so it will print "l 1"

**x = 1:**
last = 0
uncompressed[x] = "a"
uncompressed[last] = "l"
#these aren't equal so it will print "a 1"

**x = 2:**
last = 1
uncompressed[x] = "a"
uncompressed[last] = "a"
# these are equal so 
count = 2

**x = 3:**
last  = 2
uncompressed[x] = "a"
uncompressed[last] = "a"
# these are equal so 
count = 3

**x = 4:**
last = 3
uncompressed[x] = "a"
uncompressed[last] = "a"
# these are equal so
count = 4

**x = 5**
uncompressed[x] = "v"
uncompressed[last] = "a"
# these aren't equal so it will print "v 4"

...你明白了。 为了使其发挥作用,请尝试向前看而不是向后看

希望这可以帮助!

编辑评论:

我想你快到了。 如果您正在向前看,则无法在for循环中遍历整个字符串,因为您将在最后一次迭代过程中越过字符串的末尾,从而导致index out of range错误。

如果改为循环到倒数第二个字符(即range(olength-1) ,则在最后一次迭代中,请检查倒数第二个字符是否与最后一个字符相同。 如果它们相同,则增加计数;如果它们不同,则将计数打印并重置为1,就像在原始发布的代码中所做的一样。

无论哪种方式,当退出循环时,您要做的就是打印最后一个字符,并在循环退出后计数以完成该操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM