Below is the python code to get the longest concat str with count I am not able to call the function again when in loop and out side loop I am not able to access suffixString
if i call outside the loop it's
t = {"asds":"asds","asas":"asas"}
def checkIfitsLongest(str1):
for i in range(1, len(str1)-1):
suffixString = str1[i+1:-1]
if t.has_key(suffixString):
break
checkIfitsLongest(suffixString)
Putting some well-positioned print
debugging statements we can see that your problem is not with scoping of the checkIfitsLongest
function or suffixString
variable.
t = {"asds":"asds","asas":"asas"}
def checkIfitsLongest(str1):
print "checking", str1
for i in range(1, len(str1)-1):
suffixString = str1[i+1:-1]
print "suffix", suffixString
if t.has_key(suffixString):
break
checkIfitsLongest(suffixString)
Now run in the interpreter:
>>> checkIfitsLongest("asdf")
checking asdf
suffix d
suffix
checking
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
checkIfitsLongest("asdf")
File "C:/Users/me/Desktop/cccc.py", line 10, in checkIfitsLongest
checkIfitsLongest(suffixString)
File "C:/Users/me/Desktop/cccc.py", line 10, in checkIfitsLongest
checkIfitsLongest(suffixString)
UnboundLocalError: local variable 'suffixString' referenced before assignment
>>>
So we can see that suffixString
is being passed down correctly. However it is never initialized when you pass an empty string into the function (never entering the for
loop).
You need to consider how to check your recursive base case. Usually you do this at the beginning of your function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.