python - 如何使用递归生成交替子串
问题描述
我有一个练习题,要求我使用递归和迭代生成 x 个交替子字符串,即“#-”和“#--”。eg.string_iteration(3) 生成“#-#--#-”。
我已经成功地实现了迭代方法的解决方案,但是我在开始使用递归方法时遇到了麻烦。我该如何进行?
迭代法
def string_iteration(x):
odd_block = '#-'
even_block = '#--'
current_block = ''
if x == 0:
return ''
else:
for i in range(1,x+1):
if i % 2 != 0:
current_block += odd_block
elif i % 2 == 0:
current_block += even_block
i += 1
return current_block
解决方案
对于递归解决方案,您需要一个基本情况并使用其他值再次调用该函数,以便最终获得所需的输出。在这里,我们可以像 - 一样递归解决这个问题string_recursive(x) = string_recursive(x-1) + string_recursive(x-2) + ... + string_recursive(1)
。
def string_recursion(x, parity):
final_str = ''
if x == 0:
return ''
if parity == -1: # when parity -1 we will add odd block
final_str += odd_block
elif parity == 1:
final_str += even_block
parity *= -1 # flip the parity every time
final_str += string_recursion(x-1, parity)
return final_str
odd_block = '#-'
even_block = '#--'
print(string_recursion(3, -1)) # for x=1 case we have odd parity, hence -1
# Output: #-#--#-
推荐阅读
- pandas - Pandas - DataFrame aggregate behaving oddly
- bixby - Bixby:如何在输入视图中的日期选择器中将初始值设置为 self BirthdayInfo?
- javascript - VPC下从Lambda访问API网关
- java - How to create a CSR with empty/suppressed Attributes - Keytool
- docker - Docker 突然无法识别 -p 命令
- matlab - LSTM 网络中的序列到序列和序列到一回归有什么区别?
- sql - 多个 JOIN 表和 WHERE AND 遇到问题
- python-3.x - 如何在 Python 中为音频文件定义损坏文件的条件
- python - keras fit_generator InvalidArgumentError on last step_per_epoch
- r - 使用 R 从 PDF 提取/解析为 CSV?