• 1
    Input and Output Data
    • Tasks
  • 2
    Conditions
    • Tasks
  • 3
    For Loop
    • Tasks
  • 4
    Strings
    • Tasks
  • 5
    While Loop
    • Tasks
  • 6
    Lists
    • Tasks
  • 7
    Two-Dimensional Arrays
    • Tasks
  • 8
    Dictionaries
    • Tasks
  • 9
    Sets
    • Tasks
  • 10
    Functions and Recursion
    • Tasks
  • к

Занятие 4. Lines

Difficulty level:

Task«The frequency of the symbols of the line»

imagine that you are working as a musical producer at the recording studio. Every day you get dozens of short musical samples (rhythmic drawings). Some of them & mdash; This is just a very short motive, fixated several times, while others & mdash; More complex and unique melodies. Your task & mdash; Save time and write an analyzer program that will help to quickly separate simple repeating Semls from the complex.

rn

you will represent a seed in the form of a line where each symbol & mdash; This is a note or shock sound (for example, "Ababab" or "Takadimitakadimi"). The program should determine whether the whole line is a repetition of some of its shorter initial part.

rn

rn
    rn
  • Semple & nbsp; " ababab " & nbsp; is a repetition of the tune & nbsp; " ab " & nbsp; 3 times. So this is a simple magnifying glass. Result: & nbsp; trye
  • rn
  • Semple & nbsp; " abcabc " & nbsp; is a repetition of the tuning & nbsp; " abc " & nbsp; 2 times. Result: & nbsp; trye
  • rn
  • Semple & nbsp; " abasde " & nbsp; is not a repetition of any of its initial pieces. Result: & nbsp; false
  • rn
  • Semple & nbsp; " aaaa " & nbsp; is a repetition & nbsp; " a " & nbsp; 4 times. Result: & NBSP; True
  • rn
rn

You need to write a program that takes one line (Seml) and the input) and Demits & nbsp; true , if it is a repetition, and & nbsp; false otherwise.

Input format

Musical Semple (Type: Line). This is one line without gaps that the user introduces.

Output format

The result of the check (type: brief value). This is either the word & nbsp; true , or the word & nbsp; false .

Example

Input

gogogo

Output

true

Hint

There will be no clue here, decide for yourself!

main.py
Test 1
Test 2
Test 3
Test 4
Test 5
Test 6
Test 7
Test 8
Test 9
Test 10
Developer’s solution
# Получаем строку от пользователя
input_string = input()

# Получаем длину введенной строки
n = len(input_string)

# Создаем флаг, который покажет, нашли ли мы подходящий шаблон. Изначально считаем, что не нашли.
found_pattern = False

# Начинаем цикл для проверки всех возможных длин подшаблона.
# Длина подшаблона (i) может быть от 1 до половины длины всей строки.
# Длиннее половины быть не может, так как шаблон должен повториться хотя бы дважды.
for i in range(1, n // 2 + 1):
    # Проверяем, делится ли длина всей строки нацело на длину предполагаемого шаблона.
    # Если нет, то из такого шаблона целую строку составить нельзя.
    if n % i == 0:
        # Если делится, то у нас есть кандидат в шаблоны.
        # Это начальная часть строки длиной i.
        pattern = input_string[:i]
        
        # Вычисляем, сколько раз наш кандидат-шаблон должен повториться, чтобы получить строку нужной длины.
        num_repeats = n // i
        
        # Создаем тестовую строку, повторяя наш кандидат-шаблон нужное количество раз.
        test_string = pattern * num_repeats
        
        # Сравниваем созданную тестовую строку с оригинальной.
        if test_string == input_string:
            # Если они совпали, значит, мы нашли повторяющийся шаблон.
            found_pattern = True
            # Прерываем цикл, так как дальнейшие проверки не нужны.
            break

# После завершения цикла выводим значение флага.
# Если мы нашли шаблон, он будет True, если нет - останется False.
print(found_pattern)

🎉 Congratulations! 🎉

You did an excellent job with the task! It was a challenging problem, but you found the correct solution. You are one step closer to mastering programming! Keep up the good work, because every stage you pass makes you even stronger.

AD

Advertisement

red-snake blue-snake green-snake

Running your code...

Помощник ИИ

Привет! Я твой помощник по программированию. Задавай любые вопросы по Python, я могу рассказать о функциях, методах, обьяснить то, что тебе не понятно, а так же о текущей задаче!