我尝试了一种无需使用[::-1]方法即可执行反向字符串功能的方法。我是编码的新手,正在尝试仅使用“原始”步骤。以下是我的功能和规格。我想知道这是否是编写函数的有效方法。感谢您的帮助。谢谢!
def reverse(word):
x = -2 #word in reversed order counter
y = 1 #starts counter to end "while" statement below
reversed = word[-1] #starts the reversed-word at last letter of word
while len(word) > y: #ending parameter for when all letters run through loop
reversed += word[x] #adds letters to reversed word starting at word[-2]
x -= 1 #moves position in word 1 to the left
y += 1 #increases the counter by 1
return reversed
添加到字符串很慢。最好以相反的顺序列出字符串中的字符,然后join
在其上使用string方法。
示例代码(非常接近您的原始功能):
def reverse(word):
index = len(word)-1
result = []
while index >= 0:
result.append(word[index])
index -= 1
return "".join(result)
更好的示例代码:
def reverse(word):
word_list = []
for i in range(len(word)-1, -1, -1):
word_list.append(word[i])
return "".join(word_list)
def reverse(word):
return "".join(word[i] for i in range(len(word)-1, -1, -1))
更好的代码:
def reverse(word):
return "".join(reversed("abc"))
要么
def reverse(word):
return word[::-1]
但是,当然,最有效的代码是字符最少的代码。[/讽刺]
reverse =lambda s:s and s[-1]+reverse(s[:-1])or s
另一个解决方案(我认为这可能会很慢):
def reverse(word):
word_list = []
for i in word:
word_list.insert(0, word[i])
return "".join(word_list)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句