Search code examples
pythonstringalphabetical

How to find the length/interval between two alphabets in reverse order?


I have a list of paired strings. I want to find the length/interval between two alphabets. So far I'm able to find the interval for ordered alphabets using

alpha =["AM",  "KQ",  "ZN",  "XM",  "UK"]
    
length = []
for i in alpha:
    length.append(len([chr(k) for k in range(ord(i[0]),ord(i[1]))]))
    print(length)
[12]
[12, 6]
[12, 6, 0]
[12, 6, 0, 0]
[12, 6, 0, 0, 0]

I'm unable to find the interval for reversed alphabets?

How to find the length/interval between two alphabets in reverse order? Is there a python function to find interval/length between two alphabets in different orders like A-Z or X-A?


Solution

  • Instead of generating a list between ord(i[0]) and ord(i[1]), and finding its length, there's a better solution, just finding the difference between ord(i[0]) and ord(i[1]).

    This doesn't immediately solve the issue for reversed alphabets, since a reversed alphabet would generate a negative number, but you can solve this with the builtin abs() function which takes the absolute value of a number:

    length.append(abs(ord(i[0]) - ord(i[1])))