你能给我解释一下 python 中的 RLE 算法代码吗

Can you explain me the RLE algorithm code in python

我终于通过观看教程找到了如何制作 RLE 算法,但是本教程没有解释代码中的某些内容我不明白为什么我们写 j = i 而不是 j = 0(知道我 = 0) 是一样的不是吗?

我也不明白为什么 i = j + 1。为什么 i = j + 1 在函数的末尾?为什么不简单地 i += 1 但如果我们想在一个循环中重复一个循环那么我们做 j + 1 ?

第一个 while 循环是否应该重复第二个 while 循环直到字符串完成?

最后为什么 encoded_message 重复了两次?而不是一个。我们 return encoded_message 就这样了吗?我们可以简单地做 print(encode(text)) 而不是 “print('The encoded message is the output ',encoded_message)”(当我们将 encode(text) 放入 encoded_message 时)

我知道我问了很多问题,但我无法在不理解代码的情况下记住代码,这将是完全无用且毫无成效的

    def encode(message):
        
        encoded_message = ""
        i = 0
        while(i<len(message)):
            count = 1
            ch = message[i]
            j = i # ???
            while(j<len(message)-1): # GET IT -----------------------------------------------------------
                if message[j] == message[j+1]: # if the previous and next characters are the same 
                    
                    count = count + 1 # we increase count variable
                    j += 1 # we increase j position
                    # GET IT ----------------------------------------------------------------------------
                else:
                    break
                
            encoded_message = encoded_message + str(count) + ch # "" + count converted to string + character (ch)
            i = j + 1 # ???
        return encoded_message


text = input('enter your charcter chain...')
encoded_message = encode(text)
print('The encoded message is the output ',encoded_message)

当我用 j = 0 替换 j = i 时,终端中没有任何显示

见:no result

有外循环和内循环。带有变量 i 的外层循环开始遍历消息。内部循环使用变量 j 并从 i.

的当前位置开始

即:当i=0时则j=0。但是当 i=5 (例如)然后 j=5 也是。

内循环任务是检查是否有2个或更多相同的字符在后面。如果他们这样做, i 在内循环结束时相应增加。这样邮件的每个字母都只看一次。

这就是为什么 j 不应设置为常量值。将其设置为 j=0 会导致内部循环在每次迭代时从消息的开头开始。

我在您的代码中添加了两个简单的 print() 语句来阐明:

def encode(message):
     encoded_message = ""
     i = 0
     while(i<len(message)):
         print(f'outer loop: i={i}')
         count = 1
         ch = message[i]
         j = i
         while(j<len(message)-1):
             print(f'\tinner loop: j={j}')
             if message[j] == message[j+1]: # if the previous and next characters are the same 
                 count = count + 1 # we increase count variable
                 j += 1 # we increase j position
             else:
                 break
             
         encoded_message = encoded_message + str(count) + ch # "" + count converted to string + character (ch)
         i = j + 1
     return encoded_message


text = 'Hello World'
encoded_message = encode(text)
print('The encoded message is the output ', encoded_message)

(请注意:我不知道 RLE 算法,只是看了你的代码。)