我有这段自称的代码:
def get_input():
my_var = input('Enter "a" or "b": ')
if my_var != "a" and my_var != "b":
print('You didn\'t type "a" or "b". Try again.')
get_input()
else:
return my_var
print('got input:', get_input())
Run Code Online (Sandbox Code Playgroud)
现在,如果我输入"a"或"b",一切都很好.输出是:
Type "a" or "b": a
got input: a
Run Code Online (Sandbox Code Playgroud)
但是,如果我输入其他内容然后输入"a"或"b",我会得到:
Type "a" or "b": purple
You didn't type "a" or "b". Try again.
Type "a" or "b": a
got input: None
Run Code Online (Sandbox Code Playgroud)
我不知道为什么get_input()要回来None,因为它应该只返回my_var.print语句显示None正确的值,但函数由于某种原因不返回该值.
我有这段代码,出于某种原因,当我尝试返回路径时,我得到的是:
def get_path(dictionary, rqfile, prefix=[]):
for filename in dictionary.keys():
path = prefix+[filename]
if not isinstance(dictionary[filename], dict):
if rqfile in str(os.path.join(*path)):
return str(os.path.join(*path))
else:
get_path(directory[filename], rqfile, path)
Run Code Online (Sandbox Code Playgroud)
有办法解决这个问题吗?提前致谢.
我真的不明白,为什么代码
def isIn(char, aStr):
ms = len(aStr)/2
if aStr[ms] == char:
print 'i am here now'
return True
elif char>aStr[ms] and not ms == len(aStr)-1:
aStr = aStr[ms+1:]
elif char <aStr[ms] and not ms == 0:
aStr = aStr[0:ms]
else:
return False
isIn(char, aStr)
print isIn('a', 'ab')
Run Code Online (Sandbox Code Playgroud)
继续返回无.它打印'我现在在这里',但它不会返回True,就像下一行所说的那样.为什么?
最近在学习递归,写了一个简单的递归函数来验证我的理解:
def hello(n):
if n == 1:
return 'hello'
else:
print('hello')
hello(n-1)
def returnhello():
return 'hello'
print(returnhello())
print()
print(hello(5))
Run Code Online (Sandbox Code Playgroud)
其输出如下所示:
hello
hello
hello
hello
hello
None
Run Code Online (Sandbox Code Playgroud)
为什么递归中的最后一个调用打印 None 而不是 hello?我期待它打印 5 hello
我编写了以下函数来实现我自己的二分查找
def bisect(input, target):
mid = len(input)/ 2
if len(input) == 1:
if input[0] == target:
return 1
else:
return None
elif input[mid] > target:
bisect(input[:mid], target)
elif input[mid] <= target:
bisect(input[mid:], target)
Run Code Online (Sandbox Code Playgroud)
我知道我的实现已经关闭,但我对理解这里的递归堆栈更加好奇。
当我调用时bisect(['d','e'], 'd'),我的函数应该返回
bisect(['d'], 'd')
Run Code Online (Sandbox Code Playgroud)
但它返回无。此外,当我bisect(['d'], 'd')直接调用时 ,我得到了正确的 0 值。这怎么可能?
ps:这个问题只是标记为重复,已经有了答案.问题是,这个问题与另一个问题不一样.在这个问题上,我已经知道我的代码出错了.我问为什么这是错的.
这是我要求解决的udacity问题:
定义一个过程is_palindrome,它接受一个字符串输入,并返回一个布尔值,指示输入字符串是否为回文结构.
暗示:
基础案例:
''=>True递归情况:如果第一个和最后一个字符不匹配=>
False
如果他们匹配,中间是回文吗?
def is_palindrome(s):
if s=='':
return True
else:
if s[0]!=s[-1]:
return False
else:
s=s[1:-1]
is_palindrome(s)
Run Code Online (Sandbox Code Playgroud)
尝试3个输入案例:
print is_palindrome('')
#>>> True
print is_palindrome('abab')
#>>> False
print is_palindrome('abba')
#>>> True
Run Code Online (Sandbox Code Playgroud)
如果我保留我的代码,那么对于案例'abba',它将返回None.可以通过将函数的最后一行更改为可以修复
return is_palindrome(s[1:-1])
Run Code Online (Sandbox Code Playgroud)
请问为什么这return件事?即使没有返回,它不应该只是is_palindrome()一次又一次地运行该功能吗?