def run_length_encoding(matrix):
# List for storing run length encoding
encoding = []
# Counts the number of occurrences
count = 0
# Initialize previous element to first element in matrix
previous_element = matrix[0][0]
for row in matrix:
for current_element in row:
if current_element == previous_element:
count += 1
else:
encoding.append(previous_element)
encoding.append(count)
# Reset counter and update previous element
count = 1
previous_element = current_element
# Append last element since loop exited.
encoding.append(previous_element)
encoding.append(count)
return encoding
一种方法是对矩阵中的每个子列表使用list^{} 方法:
或者如果你喜欢一句话:
那么
@davedwards给出的答案非常优雅。你知道吗
这是我编写的解决方案,它的运行时与我机器上的解决方案相同。你知道吗
将高性能pyrle库用于运行长度算法:
相关问题 更多 >
编程相关推荐