Loading...

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

niyazihasan avatar niyazihasan 83 Точки

Rage Quit 80/100

Здравейте,

Опитвам се да получа 100/100, но не ми минават тестовете: 7, 10 в джъдж

Моля за насоки къде ми е проблема?

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 times; convert 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.

Examples

Input

Output

Comments

a3

Unique symbols used: 1

AAA

We have just one string-number pair. The symbol is 'a', convert it to uppercase and repeat 3 times: AAA.

Only one symbol is used ('A').

aSd2&5s@1

Unique symbols used: 5

ASDASD&&&&&S@

"aSd" is converted to "ASD" and repeated twice; "&" is repeated 5 times; "s@" is converted to "S@" and repeated once.

5 symbols are used: 'A', 'S', 'D', '&' and '@'.

import re

string = input().upper()
result = []
unique_chars = []
matches = re.finditer(r"(\D+)(\d+)", string)
for match in matches:
    num = int(match.group(2))
    text = match.group(1)
    if num == 0:
        continue
    for i in range(num):
        result.append(text)
    for char in text:
        unique_chars.append(char)
print(f"Unique symbols used: {len(set(unique_chars))}\n{''.join(result)}")

 

Тагове:
1
Fundamentals Module
MartinBG avatar MartinBG 4803 Точки

Тестовете не минават, защото решението използва повече памет, отколкото е заложения лимит в Judge (17.24 MB при 16 MB лимит). 

Ако променим unique_chars да е set от самото начало, може да свалим използваната памет с около 800KB до 16.43 MB, но и това не е достатъчно. Опитах и още няколко микрооптимизации без успех.

Интересно, че в документа със заданието пише, че лимита за паметта е 64 MB:

Allowed working time for your program: 0.3 seconds. Allowed memory: 64 MB.

Остава да се опита решение без регекс (т.е. без импортване re модула, което следва да намали използваната памет), или да се сигнализират организаторите на курса да променят лимита за памет за тази задача.

1
niyazihasan avatar niyazihasan 83 Точки

Здравейте,

Ето решение без регекс(с точки 90/100, не минава последният тест):

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])
        text = string[last_digit_index + 1:i]
        if num > 0:
            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,09МВ, трябва ми някаква малка оптимизация мисля, но какво е не мога да разбера? 

Благодаря за съдействието

1
24/06/2020 17:24:58
Rafaelo avatar Rafaelo 42 Точки

Здравей,

Опитай да промениш променливата result от лист на стринг и там където е .append му дай +=, така програмата няма да обхожда през елементи при .join и ще въври по-бързо:

 

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])
        text = string[last_digit_index + 1:i]
        if num > 0:
            for v in range(num):
                result += 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(result)

 

Това дава 100 от 100.

1
Georgi_M_Georgiev avatar Georgi_M_Georgiev 4 Точки

Здравейте,

Не мога да си открия грешката, моля за помощ. В judge 28/100, zero тестовете минават. Проблема не е до памет, грешен ми е output-a. Пробвах каквито се сетя варианти, и работят според условията така както аз ги разбирам. Благодаря предварително!

input_str = input()

res_str = ''

start_idx = 0

for i, s in enumerate(input_str):

  if s.isnumeric():

    res_str += int(s) * input_str[start_idx:i].upper()

    start_idx = i + 1

print(f'Unique symbols used: {len(set(res_str))}')

print(f'{res_str}')

0
20/03/2021 15:37:55
Georgi_M_Georgiev avatar Georgi_M_Georgiev 4 Точки

:-) проспал съм "The repeat count for each string will be an integer in the range [0 … 20]." гледал съм само за една цифра. Добавих една проверка и всичко е ок сега.

1
Martinzca avatar Martinzca 11 Точки

Привет,

При мен също repeat count-a беше ключов. :) Споделям и моето решение:

text = input().upper()
med = ''
final = ''
i = 0

while i < len(text):
    if text[i].isdigit():
        if i < len(text) - 1:
            if text[i + 1].isdigit():
                final += (med * int(str(text[i]) + str(text[i + 1])))
                i += 1
            else:
                final += (med * int(text[i]))
        else:
            final += (med * int(text[i]))
        med = ''
    else:
        med += text[i]
    i += 1

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

 

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