gpt4 book ai didi

python - 检查字符串是否按字母顺序排列

转载 作者:行者123 更新时间:2023-12-01 04:58:21 25 4
gpt4 key购买 nike

我正在学习Python。我目前的自学作业是编写一个程序,该程序接受一个字符串并检查天气或字符串中的字母是否按字母顺序排列。如果不是,程序将返回字母乱序的实例数。我请求 stackoverflow 的帮助,因为代码对我来说看起来不错,但我不断收到错误,该错误包含在下面。

代码

def inversions  (string):
res = 0
for i in string:
if string[i+1] < string[i]:
res += 1
print( res)

我的错误

Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
inversions ('ghutinhjdbessadfg')
File "C:\Users\Christopher\Downloads\pratice.py", line 63, in inversions
if string[i+1] < string[i]:
TypeError: Can't convert 'int' object to str implicitly

我有点明白错误的意思,但我不确定该怎么办。

非常感谢

最佳答案

你所说的有多少是乱序的意思不明确 - 例如字符串

zabcdef

所有字母的顺序都乱了。这是您的意思吗,还是您想要重新排序字符串所需的操作数?

要检查字符串是否按字母顺序排列,请尝试回答此问题:

checking if a string is in alphabetical order in python

def isInAlphabeticalOrder(word):
for i in range(len(word) - 1):
if word[i] > word[i + 1]:

return False
return True

您的问题是因为您使用字符串作为列表索引。

以你的代码为例,我修改了上面的内容

def number_out_of_place(word):
out_of_place = 0
for i in range(len(word) - 1):
if word[i] > word[i + 1]:
out_of_place += 1
return out_of_place

关于python - 检查字符串是否按字母顺序排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26852878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com