Answer the question
In order to leave comments, you need to log in
How to catch an error in the code?
There is a task:
Boring lecture
Lyosha sat at the lecture. He was incredibly bored. The lecturer's voice seemed so distant and imperceptible...
In order not to fall asleep completely, he took a piece of paper and wrote his favorite word on it. A little lower, he repeated his favorite word without the first letter. Even lower, he again wrote his favorite word, but this time without the first and last two letters.
Then the thought occurred to him - there is still a lot of time until the end of the lecture - why not continue to write out this word in all possible ways without some part from the beginning and some part from the end?
After the lecture, Lyosha told Max how wonderfully he had passed the time. Max became interested in counting how many letters of each type are found in Lyosha's leaflet. But unfortunately, the leaf itself disappeared somewhere.
Max knows Lesha's favorite word well, and he also doesn't have as much free time as his friend, so help him quickly recover how many times Lesha had to write down each letter.
Input data:
The input is a string consisting of lowercase Latin letters — Lyosha's favorite word.
The string length ranges from 5 to 100,000 characters.
Output:
For each letter on Lesha's piece of paper, print it, and then, separated by a colon and a space, print how many times it occurred in the words Lesha wrote out (see the output format in the examples). The letters must be in alphabetical order. Letters that do not appear on the sheet do not need to be displayed.
Examples
Input
hello
Output
e: 8
h: 5
l: 17
o:5
from math import ceil
previous = 0
d = {}
li = list(input())
mid = ceil(len(li)/2)-1
for i in range(mid+1):
id_first = i
id_second = len(li) - i - 1
previous = len(li) - 2*i + previous
f_letter = li[id_first]
s_letter = li[id_second]
if f_letter not in d:
d[f_letter] = 0
if i != mid:
if s_letter not in d:
d[s_letter] = 0
d[s_letter] += previous
d[f_letter] += previous
keys = list(d.keys())
keys.sort()
for k in keys:
print(k + ': ', d[k])
Answer the question
In order to leave comments, you need to log in
It seems that on the line "abcdef" you will get d=0, or maybe not write d at all.
The problem is that you are trying to count in parallel for the right and left halves. Logically, the coefficients will be symmetrical there, but you can make a mistake. And your optimization practically does not accelerate acceleration. 2x fewer iterations doing 2x more + extra check each time. In compiled languages, it can also be slower than a naive loop from 0 to n-1. In python, I don't know. Certainly not twice as fast as one might think.
Also, instead of sequentially updating the coefficient in previous, I would consider it explicitly. The i-th character occurs exactly in (i+1)*(ni) substrings.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question