I want to get every letter and their index. But I got the wrong answer.
def counting(sentence):
for letter in sentence:
if not letter == ' ':
print(letter ,":", [sentence.index(letter)],end =" ")
print(counting("Hello my friends"))
H : [0] e : [1] l : [2] l : [2] o : [4] m : [6] y : [7] f : [9] r : [10] i : [11] e : [1] n : [13] d : [14] s : [15]
I got this as an answer. The problem is that I got double e but with the same index. The idea is to get for example e:[1,19,24 etc.]. What should I change? Is a possibility to make it with dictionary?
CodePudding user response:
You could use enumerate
to loop over the string and give both the element and also the index number.
This also uses a defaultdict
in order to have a dictionary containing lists as values, where if the key does not already exist then it will be created as an empty list when you call append
.
from collections import defaultdict
sentence = "Hello my friends"
indexes = defaultdict(list)
for index, letter in enumerate(sentence):
if letter != ' ':
indexes[letter].append(index)
for letter in sorted(indexes):
print(f"{letter}: {indexes[letter]}")
This gives:
H: [0]
d: [14]
e: [1, 12]
f: [9]
i: [11]
l: [2, 3]
m: [6]
n: [13]
o: [4]
r: [10]
s: [15]
y: [7]
UPDATE: in response to a comment below saying that the output indexes should not increment on spaces: this is not my interpretation of the question, but if this is intended, it can be dealt with by pre-processing the input:
sentence = sentence.replace(" ", "")
(and then the if
condition becomes unnecessary and could be removed).
CodePudding user response:
Instead of searching for a letters index in-line, you can just store the current index as a local variable.
def counting(sentence):
current_indx = 0
for letter in sentence:
if not letter == ' ':
print(f'{letter} : [{current_indx}]',end =" ")
current_indx = 1
CodePudding user response:
or you can do like this:
def counting(sentence):
res = {key: [] for key in set(sentence)}
for i in range(len(sentence)):
if not sentence[i] == ' ':
res[sentence[i]].append(i)
return res
print(counting("Hello my friends"))