Loading...
TodorDaskalov avatar TodorDaskalov 2 Точки

9. *Anonymous Threat List Advanced Python

Моля за помощ, ако някой може да открие грешката ми в кода за тази задача. Максимума, който постигам е 60/100 точки, но не мога да намеря къде е проблема в точно този код. Грешките, които дава са при изпълнение, но нещо пропускам и не мога да разбера какво.

https://pastebin.com/wWG4yaBC

https://judge.softuni.org/Contests/Compete/Index/1731#8

Условие: 

1.*Anonymous Threat

Anonymous has created a hyper cyber virus, which steals data from the CIA. The virus is known for its innovative and unbelievably clever merging and dividing data into partitions. As the lead security developer in the CIA, you have been tasked to analyze the software of the virus and observe its actions on the data.

You will receive a single input line containing strings, separated by spaces. The strings may contain any ASCII character except whitespace. Then you will begin receiving commands in one of the following formats:

  • merge {startIndex} {endIndex}
  • divide {index} {partitions}

Every time you receive the merge command, you must merge all elements from the startIndex to the endIndex. In other words, you should concatenate them.
Example: {abc, def, ghi} -> merge 0 1 -> {abcdef, ghi}

If any of the given indexes is out of the array, you must take only the range that is inside the array and merge it.

Every time you receive the divide command, you must divide the element at the given index into several small substrings with equal length. The count of the substrings should be equal to the given partitions.

Example: {abcdef, ghi, jkl} -> divide 0 3 -> {ab, cd, ef, ghi, jkl}

If the string cannot be exactly divided into the given partitions, make all partitions except the last with equal lengths and make the last one - the longest.

Example: {abcd, efgh, ijkl} -> divide 0 3 -> {a, b, cd, efgh, ijkl}

The input ends when you receive the command "3:1". At that point, you must print the resulting elements, joined by a space.

Input

  • The first input line will contain the array of data.
  • On the next several input lines, you will receive commands in the format specified above.
  • The input ends when you receive the command "3:1".

Output

  • As output, you must print a single line containing the elements of the array, joined by a space.

Constrains

  • The strings in the array may contain any ASCII character except whitespace.
  • The startIndex and the endIndex will be in the range [-1000…1000].
  • The endIndex will always be greater than the startIndex.
  • The index in the divide command will always be inside the array.
  • The partitions will be in the range [0…100].
  • Allowed working time/memory: 100ms / 16MB.

Examples

Input

Output

Ivo Johny Tony Bony Mony

merge 0 3

merge 3 4

merge 0 3

3:1

IvoJohnyTonyBonyMony

abcd efgh ijkl mnop qrst uvwx yz

merge 4 10

divide 4 5

3:1

abcd efgh ijkl mnop qr st uv wx yz

Тагове:
0
Python Fundamentals
valerielashvili avatar valerielashvili 22 Точки

Добавям още едно решение:

strings = input().split()
command = ''

while command != '3:1':
    tokens = input().split()
    command = tokens[0]

    if command == 'merge':
        start_index = int(tokens[1])
        end_index = int(tokens[2])

        start_index = max(0, start_index)
        end_index = min(len(strings) - 1, end_index)

        if start_index <= end_index:
            merged = ''.join(strings[start_index:end_index + 1])
            strings = strings[:start_index] + [merged] + strings[end_index + 1:]

    elif command == 'divide':
        index = int(tokens[1])
        partitions = int(tokens[2])
        string_to_divide = strings.pop(index)

        part_length = len(string_to_divide) // partitions
        remainder = len(string_to_divide) % partitions

        divided_strings = []
        start = 0

        for i in range(partitions):
            current_part_length = part_length

            if i == partitions - 1:
                current_part_length += remainder

            part = string_to_divide[start:start + current_part_length]
            divided_strings.append(part)
            start += current_part_length

        strings[index:index] = divided_strings

result = ''
for element in strings:
    result += f"{element} "
print(result.strip())

Бъдете внимателни в разделянето на стринга! Хвърлейки бърз поглед върху описанието на задачата може да се стори, че ако стрингът не може да бъде разделен на равни части то тогава го делим по един символ, което не е вярно. Има случаи, в които един низ се дели на части с дължината по-голяма от 1, но не се дели на равни части с равна дължина за всичките части, в този случай се взима остатък.

"abcdefghijk" е низ от 11 символа и би трябвало да бъде разделен по следния начин:
"ab cd ef gh ijk" или "a b c d e f g h i jk" в зависимост от това дали искаме да го разделим на 5 или 10 части.

Също така в началото грешката ми беше в това, че циклите ги въртях в range() вместо от самото начало да обхождам количеството части за разделяне на стринга.

Много време отделих за тази задача при положение, че дори и уловки няма в нея. Просто едно решение отиде ли в неправилна посока, или не се ли нагласи в главата правилно от самото начало, започва едно губене на време.

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