Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

niyazihasan avatar niyazihasan 83 Точки

Rage Quit 90/100

Здравейте,

Опитвам се да получа 100/100, но последният тест не минава.

Ако може  някой колега да даде насока как мога да си оптимизирам кода

Получавам от джъдж: Memory: 16.05 MB, Time: 0.540 s, трябва да сваля memory на 16.00MB

1.Rage Quit

Every gamer knows what rage-quitting means. It’s basically when you’re just not good enough and you blame everybody else for losing a game. You press the CAPS LOCK key on the keyboard and flood the chat with gibberish to show your frustration.

Chochko is a gamer, and a bad one at that. He asks for your help; he wants to be the most annoying kid in his team, so when he rage-quits he wants something truly spectacular. He’ll give you a series of strings followed by non-negative numbers, e.g. "a3"; you need to print on the console each string repeated N timesconvert the letters to uppercase beforehand. In the example, you need to write back "AAA".

On the output, print first a statistic of the number of unique symbols used (the casing of letters is irrelevant, meaning that 'a' and 'A' are the same); the format shoud be "Unique symbols used {0}". Then, print the rage message itself.

The strings and numbers will not be separated by anything. The input will always start with a string and for each string there will be a corresponding number. The entire input will be given on a single line; Chochko is too lazy to make your job easier.

Input

  • The input data should be read from the console.
  • It consists of a single line holding a series of string-number sequences.
  • The input data will always be valid and in the format described. There is no need to check it explicitly.

Output

  • The output should be printed on the console. It should consist of exactly two lines.
  • On the first line, print the number of unique symbols used in the message.
  • On the second line, print the resulting rage message itself.

Constraints

  • The count of string-number pairs will be in the range [1 … 20 000].
  • Each string will contain any character except digits. The length of each string will be in the range [1 … 20].
  • The repeat count for each string will be an integer in the range [0 … 20].
  • Allowed working time for your program: 0.3 seconds. Allowed memory: 64 MB.
string = input().upper()
result = []
unique_chars = set()
last_digit_index = current_digit_index = -1
for i in range(len(string)):
    if string[i].isdigit():
        current_digit_index = i
    if current_digit_index != last_digit_index:
        number_len = 1
        for j in range(i + 1, len(string), 1):
            if not string[j].isdigit():
                break
            number_len += 1
        num = int(string[i:number_len+i])
        if num > 0:
            text = string[last_digit_index + 1:i]
            for v in range(num):
                result.append(text)
            for char in text:
                unique_chars.add(char)
        current_digit_index = current_digit_index + number_len - 1
        last_digit_index = current_digit_index
print(f"Unique symbols used: {len(unique_chars)}")
print(f"{''.join(result)}")
Тагове:
0
Fundamentals Module
MartinBG avatar MartinBG 4803 Точки

Проблемът с този тест е, че входните данни са големи и съхраняването на резултата в паметта преди отпечтването му не е възможно, без да се превиши лимита за памет. Може и да има някоя хитрина, която не ми е известна, но единственият вариант, който намерих за да мине теста е да не пазя сринга, а list[pair(string, count)], от който да принтирам резулата директно в конзолата.

Ето решение с регекс (ръчно парсване на стринга рядко има смисъл в практиката):

import re

result = []
unique_chars = set()

for match in re.finditer(r"(\D+)(\d+)", input().upper()):
    if match.group(2) == '0':
        continue

    result.append((match.group(1), match.group(2)))

    unique_chars.update(list(match.group(1)))
    
print(f"Unique symbols used: {len(unique_chars)}")

for pair in result:
    print(pair[0] * int(pair[1]), end="")
Memory: 10.92 MB
Time: 0.431 s

 

1
niyazihasan avatar niyazihasan 83 Точки

Много благодаря

1
MiriyamTsankova avatar MiriyamTsankova 3 Точки

import re

 

final_string = ""

for match in re.findall(r"(\D+)(\d+)", input().upper()):

final_string += match[0] * int(match[1])

print(f"Unique symbols used: {len(set(final_string))}\n{final_string}")

1
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.