编写递归算法时我的变量 X 应该是什么
what should my variable X be when writing a recursive algorithm
我正在编写一个 python 程序,它将输出字符串中的每个字母,从头开始,一次一个,并将字符串作为参数传递,但变量 X 是我的主要问题代码。我应该将它分配给什么?
def letters(l):
letterCount=len(l)
x=letterCount
if x>-1 and x<(letterCount+1):
x=letterCount-(letterCount)
return l[x]
else:
print('The session is over!')
p=input('Enter a word: ')
count=len(p)
for i in range(0,count):
print(letters(p))
递归意味着一个函数在某些条件为真时调用自身(具有不同的参数值)。
这是实现您的目标的方法:
>>> def print_letters(s):
... if not s: # The string is empty (nothing to print)
... print("The session is over!")
... return
... print(s[0]) # Print the 1st char
... print_letters(s[1:]) # Call itself with the string lacking the 1st char (that was already printed)
...
>>>
>>> print_letters("abcd")
a
b
c
d
The session is over!
虽然递归有时非常方便(而且代码看起来不错),但尽可能使用迭代方法,因为它更简单(也更快)。
我正在编写一个 python 程序,它将输出字符串中的每个字母,从头开始,一次一个,并将字符串作为参数传递,但变量 X 是我的主要问题代码。我应该将它分配给什么?
def letters(l):
letterCount=len(l)
x=letterCount
if x>-1 and x<(letterCount+1):
x=letterCount-(letterCount)
return l[x]
else:
print('The session is over!')
p=input('Enter a word: ')
count=len(p)
for i in range(0,count):
print(letters(p))
递归意味着一个函数在某些条件为真时调用自身(具有不同的参数值)。
这是实现您的目标的方法:
>>> def print_letters(s): ... if not s: # The string is empty (nothing to print) ... print("The session is over!") ... return ... print(s[0]) # Print the 1st char ... print_letters(s[1:]) # Call itself with the string lacking the 1st char (that was already printed) ... >>> >>> print_letters("abcd") a b c d The session is over!
虽然递归有时非常方便(而且代码看起来不错),但尽可能使用迭代方法,因为它更简单(也更快)。