'find number of places an alphabet to be shifted to make it alaphabetical order in python
Here let us consider a string 'images'
original string is str = 'images'
alphabetical order is str = 'aegims'
to get this alphabetical order we shifted 'a' two places forward (i.e a) and 'e' to three places forward(i.e ae) and 'g' to one place forward (i.e aeg) and 'i' to three places backward(i.e aegi)
so when user enters a letter we need to display the number of places it shifted
for suppose if user enters letter 'e' we need to print output as 3 places shifted
Solution 1:[1]
If I understood your question correctly, you want to code something like this:
class Word():
def __init__(self, word='') -> None:
self.initial = word
self.final = ''
self.char_shift = {}
self.__alphabetize()
self.__calculate_shift()
def __alphabetize(self) -> None:
word = list(self.initial)
#sort
counter = 0
sorted = False
while not sorted:
#assume already sorted
sorted = True
for i in range(len(word)-1-counter):
#check if actually sorted
if word[i] > word[i+1]:
#set sorted
sorted = False
#swop
temp = word[i]
word[i] = word[i+1]
word[i+1] = temp
#increase loop count
counter += 1
for char in word: self.final += char
def __calculate_shift(self) -> None:
for char in self.initial:
self.char_shift[char] = abs(self.final.index(char) - self.initial.index(char))
It made more sense to make it a class, though functional would also work. Here are my inputs and outputs:
word1 = Word('images')
print(word1.final)
print(word1.initial)
print(word1.char_shift['e'])
Output
aegims
images
3
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Romans |
