python - 递归删除偶数的相邻重复字母的代码
问题描述
最近在一个现场编码测试中被要求写代码递归删除偶数相邻的字母。当时我写不了代码。后来我尽力了。我的逻辑和代码有什么问题?
例如 cbbbaaaabbbccc => cbbbbbbccc => cccc => 空字符串
例如 aabbc => bbc => c
例如 abbbccc => abbbccc - 因为没有字母在偶数中重复
编辑 - 我根据 Rory 的建议编辑了代码,但仍然不明白为什么在字符串变空后它会进入递归调用而不是退出循环
str = "cbbbaaaabbbccc"
def remUtil(str):
i = 0
ind = 0
while i < (len(str)-1):
j = 0
if str[i] == str[i + 1]:
j = i
ind = i
count = 0
while j < len(str)-1 and str[j] == str[j + 1]:
count = count + 1
j = j + 1
i = i + 1
# if the no. of comparisons are odd then even letters compared
if count % 2 != 0:
str = str[:(ind)] + str[(ind + count) + 1:]
#print(str)
remUtil(str)
else:
i = i + 1
解决方案
一个较短的版本,避免了对索引的操作:
def rm_even_duplicates(s):
ls = list(s) + [None]
tmp = [ls[0]]
out = []
for c in ls[1:]:
if c != tmp[0]:
if len(tmp) % 2 == 1:
out.extend(tmp)
tmp = []
tmp.append(c)
# The recursive part, if you want to do it that way;
# that could as well have been a while loop
if len(out) == len(s):
return ''.join(out)
else:
return rm_even_duplicates(out)
一些示例和您的测试用例:
print(rm_even_duplicates('aaabbcdddd'))
# aaac
print(rm_even_duplicates('aaabbccaaadda'))
# aaaaaaa
assert rm_even_duplicates('cbbbaaaabbbccc') == ''
assert rm_even_duplicates('aabbc') == 'c'
assert rm_even_duplicates('abbbccc') == 'abbbccc'
推荐阅读
- python - 从同一个类中调用类成员变量会在 Python 中产生 NameError
- r - 将 data.frame 因子转换为日期
- java - 在 mssql jdbc 中使用 TLS 1.2
- visual-studio-code - 如何在可视代码中复制 html 面包屑?
- python - 在读取文件 Python 3 时进入循环的问题
- android - 从 0.52 升级到 0.59 时,黑色标头反应原生
- python - 熊猫将多键值数据框列重塑为行
- php - 试图调用类“Symfony\Component\HttpClient\CurlHttpClient”的未定义方法“Create”
- c++ - 输出屏幕变为空白
- android - Jetpack Compose:分析表达式时出现异常