我正在尝试在python中编写hackerrank的this problem代码。
(如果链接不起作用,问题如下)
" Goku使用一些块写了一条秘密消息。每个块包含一个字符。 悟饭喜欢玩这些积木。他把这些块堆叠在一起。
在任何时候,Gohan都可以将一个块从秘密消息的前面移动到堆栈的顶部,或者他可以从顶部移除块并将其添加到他创建的新消息的末尾。
Gohan通过将从堆栈顶部删除的块添加到新字符串的末尾,按照从堆栈顶部删除它们的顺序来创建此新消息。最终消息与原始消息具有相同的字符数,即必须从堆栈中删除所有块。 悟空担心他的原始信息可能会丢失。
他想知道悟饭可以重建原始信息的方式数量以及悟饭可能创造的不同信息的数量。
示例输入:ball
样本输出:2 9"
Gohan可以创建以下9条消息:{llab,lalb,labl,allb,albl,abll,blla,blal,ball}
这是一个回溯问题,我们需要在递归中传递一个堆栈,我们在递归中修改(插入/删除)堆栈。我使用普通列表作为堆栈。
问题的编辑是:(link)
(如果链接不起作用,编辑在下面)
Times_Recreated=0
Distinct_Messages=0
calculate_ans(OriginalMessage,Index,Stack st,NewMessage)
if Index = Length of the original message
Pop the remaining characters in the stack and add them to NewMessage
If NewMessage hasn't been encountered already, increment Distinct_Messages.
If NewMessage is same as OriginalMessage, increment Times_Recreated.
Return
Add OriginalMessage[Index] to the stack
Recurse for the remaining string calculate_ans(OriginalMessage,Index+1,st,NewMessage)
Pop the character from the top of the stack to restore the original state
If the stack isn't empty
Pop a character from the stack and add the character to NewMessage
Recurse calculate_ans(OriginalMessage,Index,st,NewMessage)
我正在尝试下面的代码,但我无法将列表(堆栈)传递给允许其修改的递归。
我认为这个列表对函数来说是全局的。它显示错误 - IndexError:从空列表中弹出
s= str(raw_input()) #string s as message input
words= set() # to store distinct messages Gohan can create
count=0 # number of ways in which Gohan could have recreated the original message
# s=message, i=index of s to be processed, stack= list as stack, new_s= new message
def backtrack(s, i, stack, new_s):
if i==len(s):
# pop the remaining characters from stack and add them to new_message
while stack:
new_s=new_s+ stack.pop()
words.add(new_s) # insert new message to set words
if new_s==s:
count+=1 # increase count if original message is obtained
return
stack.append(s[i]) #push in stack
backtrack(s, i+1, stack, new_s) # backtrack
stack.pop() #pop from stack
if stack:
new_s= new_s+stack.pop() # new message by appending stack pop
backtrack(s, i, stack, new_s) # backtrack
# function call with i=0, a blank list stack and empty new message new_s
backtrack(s, 0, [], "")
print count, len(words) # printing output
在这种情况下,请更正此代码或提供一些方法/代码来传递列表。
答案 0 :(得分:1)
变量是通过引用传递的,这意味着当你对堆栈变量进行递归调用并弹出其所有元素时,它在每个其他递归调用中都是空的,所以将其更改为
backtrack(s, i+1, [x for x in stack], new_s)
每次创建一个新列表时也会将count声明为回溯函数中的全局变量
global count