【问题标题】:what should my variable X be when writing a recursive algorithm编写递归算法时我的变量 X 应该是什么
【发布时间】:2021-05-30 03:53:55
【问题描述】:

我正在编写一个 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))

【问题讨论】:

  • 从 0 开始,每次迭代加一。请注意,您的代码中没有递归。
  • 如果您只想打印字符串中的每个字母,您的def letters 似乎是多余的。您可以直接在循环中打印。还是代码里还有什么?
  • 如果您使用递归,则无需使用for循环再次调用该函数。
  • 代码中没有任何其他内容...我得到的错误只是让我更改了一些导致我编写的代码的代码。谢谢大家

标签: python string for-loop recursion selection


【解决方案1】:

递归意味着一个函数在某些条件为真时调用自身(具有不同的参数值)。
以下是实现目标的方法:

>>> 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!

虽然递归有时非常方便(而且代码看起来不错),但尽可能选择迭代方法,因为它更简单(更快)。

【讨论】:

    猜你喜欢
    • 2010-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多