Given that in recursion you’re using a divide-and-conquer method to break down problems into smaller pieces, how would you be able to read data from beginning of the problem, at the end of problem?
Example: I have a an encrypt() function that replaces characters in a string with characters 3 indices to the right:
A in string "ABCDEF" becomes D for example
So far I did it recursively up to the point where it stops when 3 indices to the right are undefined, but this leaves the last bit of the string the same as the original.
Example: "ABCDEF" becomes "DEFDEF"
Is there a way that I can pass the beginning of the string to the innermost functions during the recursive calls in an efficient way?
This is my code currently:
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)
May be this does not exactly solves your problem, but you may have to mould it a little bit to make it fit. As I see somewhere you want Recursion. I have just shown how you can move to the beginning, when you reach the end of the string.
Take the modulus of
i + 3with the length of string to move to the beginning automatically: –So, when
i = 3,i + 3 = 6, and6 % 6 = 0-> back to the first characterIf you want to use
Recursion, here’s your modified program: –OUTPUT : –
I added one more parameter to your
method, which I use to take the appropriate index. And also, I’m passing the complete string to the method each time moving the first character to the end.Also, if the
len(plain) <= 3, you can simply return the string.