gpt4 book ai didi

python - 遍历字符串并打印字符之间的距离

转载 作者:行者123 更新时间:2023-12-01 23:47:12 30 4
gpt4 key购买 nike

source = 'abc'

def editDistance(source, target):
items1=[]
for c in range(0,len(source)):
for k in range(1,len(source)):
if (k < len(source)):
test = ord(source[k]) - ord(source[c])
items1.append(test)
return items1

我试图遍历字符串并找到字母表中每个字符之间的距离。因此,ab 之间的距离是 1bc 之间的距离是> 是 1。我想打印出 [1, 1] 数组,但是,我认为我弄乱了 for 循环及其打印输出:[1, 2, 0, 1 , -1, 0].

最佳答案

这不就是这么简单吗:

alphabet = 'abcdefghijklmnopqrstuvwxyz'
abs(alphabet.index('z') - alphabet.index('a'))

这是一个概念证明:

Python 3.7.4 (default, Aug 12 2019, 14:45:07) 
[GCC 9.1.1 20190605 (Red Hat 9.1.1-2)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> alphabet = 'abcdefghijklpmnopqrstuvwxyz'
>>> abs(alphabet.index('z') - alphabet.index('a'))
26
>>> abs(alphabet.index('a') - alphabet.index('c'))
2
>>> abs(alphabet.index('c') - alphabet.index('a'))
2
>>>

它实际上适用于任何字符集,无论什么情况或类别:

Python 3.7.4 (default, Aug 12 2019, 14:45:07) 
[GCC 9.1.1 20190605 (Red Hat 9.1.1-2)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> s='ABCdefgh!çõ'
>>> abs(s.index('ç') - s.index('A'))
9
>>> abs(s.index('B') - s.index('A'))
1
>>> abs(s.index('B') - s.index('!'))
7
>>> abs(s.index('!') - s.index('B'))
7
>>>

关于python - 遍历字符串并打印字符之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58565035/

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