gpt4 book ai didi

python - Python 中的运行长度编码

转载 作者:太空狗 更新时间:2023-10-29 22:19:28 26 4
gpt4 key购买 nike

我正在尝试编写一个简单的 Python 算法来解决这个问题。你能帮我弄清楚如何做到这一点吗?

If any character is repeated more than 4 times, the entire set ofrepeated characters should be replaced with a slash '/', followed by a2-digit number which is the length of this run of repeated characters,and the character. For example, "aaaaa" would be encoded as "/05a".Runs of 4 or less characters should not be replaced since performingthe encoding would not decrease the length of the string.

最佳答案

我在这里看到许多很棒的解决方案,但没有一个在我看来非常 pythonic。因此,我正在为我今天为这个问题编写的实现做出贡献。

def run_length_encode(data: str) -> Iterator[Tuple[str, int]]:
"""Returns run length encoded Tuples for string"""
# A memory efficient (lazy) and pythonic solution using generators
return ((x, sum(1 for _ in y)) for x, y in groupby(data))

这将返回一个包含字符和实例数的元组生成器,但也可以很容易地修改为返回一个字符串。这样做的一个好处是,如果您不需要耗尽整个搜索空间,它都是惰性评估的,并且不会消耗比需要更多的内存或 CPU。

如果您仍然想要字符串编码,可以很容易地针对该用例修改代码,如下所示:

def run_length_encode(data: str) -> str:
"""Returns run length encoded string for data"""
# A memory efficient (lazy) and pythonic solution using generators
return "".join(f"{x}{sum(1 for _ in y)}" for x, y in groupby(data))

这是一种更通用的游程长度编码,适用于所有长度,而不仅仅是超过 4 个字符的长度。但如果需要,这也可以很容易地用字符串的条件进行调整。

关于python - Python 中的运行长度编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18948382/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com