简体   繁体   中英

Iterate through string and print distance between characters

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

I'm trying to iterate through the string and find the distance between each character in the alphabet. Hence the distance between a and b is 1 and the distance between b and c is 1 . I want to print out an array of [1, 1] , however, I think I'm messing up on the for loops and its printing out: [1, 2, 0, 1, -1, 0] .

Isn't that just as simple as:

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

Here is a proof of concept:

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

And it works for any set of characters actually, no matter what case or class:

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

you can use list comprehension, by using ord for converting ascii to int and abs function

[abs(ord(source[i])-ord(source[i+1])) for i in range(len(source)-1)]

or by using for loop

for c in range(len(source)-1):
    test = ord(source[c]) - ord(source[c+1])
    items1.append(abs(test))  
return items1

or you can import string and use string.ascii_lowercase to find the index

string.ascii_lowercase.index('b')  # 1
def char_distanc(word):
    result =[]
    for i, char1 in enumerate(word):
        tmp =[]
        for j, char2 in enumerate(word):
            tmp.append(abs(ord(char1)-ord(char2)))
        result.append(tmp)
    return result

word = "abc"
print(char_distanc(word))

output

[[0, 1, 2], [1, 0, 1], [2, 1, 0]]

visual explaination

    'a' 'b' 'c'
'a'  0   1   2
'b'  1   0   1
'c'  2   1   0

You can use abs . Here is a quick example of making it into something interactive for a user:

import string

alphabet = string.ascii_lowercase
# a_dict = {i: letter for i, letter in enumerate(alphabet)} if you want to assign a count to x amount of keys
print('''
\t\t\tDifference calculator version 0.0.1
''')

while True:
  try:
    first = str(input('Enter first letter:> '))
    if first == 'exit':
      break
    second = str(input('Enter second letter:> '))
    if second == 'exit':
      break
    result = abs(alphabet.index(first) - alphabet.index(second))
    print('\nDistance between the letters are: ', result) # + 1 if you want to count the initial letter
    break
  except ValueError:
    print('Enter 1 Letter in each section\nType exit to quit')

you could do this in a one-liner list comprehension if you really wanted to by just defining the alphabet, grabbing the index of each letter and comparing it to the index of the letter before it:

alph = 'abcdefghijklmnopqrstuvwxyz'
source = 'abc'.lower() #add the lower just to make sure all the letters are in the predefined alph

[abs(alph.index(source[i]) - alph.index(source[i-1])) for i in range(len(source)) if i != 0]

output:

[1, 1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM