繁体   English   中英

字符串递归 - 回到字符串的开头?

[英]Recursion on strings - back to beginning of string?

鉴于在递归中你使用分而治之的方法将问题分解成更小的部分,在问题结束时你将如何从问题的开头读取数据?

示例 :我有一个encrypt()函数,用字符3中的字符替换字符串中的字符:

A在字符串"ABCDEF"变为D例如

到目前为止,我递归地执行它直到它停止时右边的3个索引未定义,但这使得字符串的最后一位与原始字符串相同。

示例"ABCDEF"变为"DEFDEF"

有没有一种方法可以在递归调用期间以有效的方式将字符串的开头传递给最内层的函数?

这是我目前的代码:

def shift_cipher_noloop(plain):

    encrypted = ""

    if(plain == ""):
        encrypted = ""

    else:
        if(len(plain) > 3):            
            temp_sub = plain[3]          
            encrypted = encrypted + temp_sub
            encrypted = encrypted + shift_cipher_noloop(plain[1:])

        else:
            temp_sub = plain[0] 
            encrypted = encrypted + temp_sub
            encrypted = encrypted + shift_cipher_noloop(plain[1:])

    return encrypted

x = "ABCDEFGHIJK"

y = shift_cipher_noloop(x)

print(y)

可能这并不能完全解决您的问题,但您可能需要将其塑造一点以使其适合。 正如我在某处看到你想要的递归。 我刚刚展示了当你到达字符串末尾时如何移动到开头。

i + 3的模数和字符串的长度自动移动到开头: -

>>> my_str = "ABCDEF"
>>> length = len(my_str)

>>> for i in range(length):
        print my_str[(i + 3) % length],


D E F A B C

因此,当i = 3i + 3 = 6 ,并且6 % 6 = 0 - >返回第一个字符


如果你想使用Recursion ,这是你修改过的程序: -

def shift_cipher_noloop(plain, i):

    if(plain == ""):
        return ""

    else:
        # Iterate with your string, moving first character to last on each iteration
        if len(plain) > 3 and i > 0: 
            return shift_cipher_noloop(plain[1:] + plain[0], i - 1)

        else:
            # else Will be executed when either len <= 3, or `i <= 0`.
            # when (i <= 0) is true, you have created a new string, 
            # with each character shifted by `original i` indices. 
            # So, just return it.

            return plain


x = "ABCDEF"
index_to_shift = 3
y = shift_cipher_noloop(x, len(x) - index_to_shift)

print(y)

输出: -

DEFABC

我在你的method添加了一个参数,我用它来获取适当的索引。 而且,每次将第一个字符移动到结尾时,我都会将完整的字符串传递给方法。

另外,如果len(plain) <= 3 ,你只需返回字符串即可。

如果你不必使用递归,那么我会使用简单的字符串方法。

def encrypt(text):
  return text[3:] + text[:3]

我也非常喜欢Rohit Jain的回答

通常,可以选择将附加参数传递给递归函数,该递归函数不变地传递到递归的更深的嵌套中。 您还可以使用始终可以访问外部参数的内部函数:

def shift_cipher_noloop(original):
  def encrypt_recursion(plain):
    encrypted = ""
    if plain == "":
      encrypted = ""
    elif len(plain) > 3:
      encrypted += plain[3]
      encrypted += encrypt_recursion(plain[1:])
    else:
      encrypted += original[3-len(plain)]
      encrypted += encrypt_recursion(plain[1:])
    return encrypted
  return encrypt_recursion(original)

shift_cipher_noloop('abcdefghijklop')
'defghijklopabc'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM