1

鉴于在递归中您使用分而治之的方法将问题分解为更小的部分,那么您将如何从问题的开头到问题的结尾读取数据?

示例:我有一个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)
4

3 回答 3

2

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

取字符串长度的模数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 = 3, i + 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,您可以简单地返回字符串。

于 2012-11-23T11:40:10.833 回答
1

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

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'
于 2012-11-23T13:12:57.827 回答
1

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

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

我也很喜欢 Rohit Jain 的回答

于 2012-11-23T11:48:06.293 回答