Files
tira/viikko2/onechar.old.py
T
2023-11-07 01:27:43 +02:00

55 lines
1.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
def count(s):
"""
Tehtäväsi on laskea, monessako merkkijonon osajonossa jokainen
merkki on sama. Esimerkiksi merkkijonossa abbbcaa tällaiset osajonot ovat
a (kolmesti)
aa
b (kolmesti)
bb (kahdesti)
bbb
c
eli yhteensä 11 osajonoa.
Voit olettaa, että merkkijono muodostuu merkeistä a–z ja siinä on
enintään 105 merkkiä. Tavoitteena on, että algoritmin
aikavaativuus on O(n).
Toteuta tiedostoon onechar.py funktio count,
joka palauttaa halutun tuloksen.
"""
prev_char = ""
total = 0
for char in s:
if prev_char == "":
prev_char = char
print(
f"{total} + {s.count(char)} = {total + s.count(char)} --- {char} -> {prev_char}"
)
total += s.count(char)
elif prev_char[0] == char:
prev_char += char
print(
f"{total} + {s.count(prev_char)} = {total + s.count(prev_char)} --- {char} -> {prev_char}"
)
total += s.count(prev_char)
elif prev_char != char:
prev_char = char
print(
f"{total} + {s.count(char)} = {total + s.count(char)} --- {char} -> {prev_char}"
)
total += s.count(char)
print(s)
return total
if __name__ == "__main__":
print(count("aaa")) # 6
print(count("abbbcaa")) # 11
print(count("abcde")) # 5