• 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
  • к

Занятие 6. Lists

Difficulty level:

Task«Search for the greatest general subsequence (LCS)»

You are developing a program for comparing text data and you need to find the greatest general subsequence between two lines. Style = "Text-align: Justify;"> Two lines are given. Find the greatest general subsequence (LCS, Longest Common Subsequence).

Input format

two lines, the tips of each of which are separated by spaces (if the element is one, then compare inside it)

Output format

The longest general subsequence

Example

Input

Music movie Traveling Book Sports
Cinema Dancing Books Culinary

Output

Cinema Book

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
def longest_common_subsequence(s1, s2):
    """
    Находит самую длинную общую подпоследовательность между двумя строками.
    Работает как пословно, так и посимвольно — автоматически.
    """

    # Если строки содержат пробелы — считаем, что нужно сравнивать слова
    if ' ' in s1 or ' ' in s2:
        seq1 = s1.split()
        seq2 = s2.split()
        join_result = lambda lst: ' '.join(lst)  # итог как строка слов
    else:
        seq1 = list(s1)
        seq2 = list(s2)
        join_result = lambda lst: ''.join(lst)   # итог как строка символов

    n, m = len(seq1), len(seq2)

    # Матрица DP для хранения последовательностей
    dp = [[""] * (m + 1) for _ in range(n + 1)]

    # Заполнение таблицы
    for i in range(n):
        for j in range(m):
            if seq1[i] == seq2[j]:
                dp[i + 1][j + 1] = dp[i][j] + " " + seq1[i]
            else:
                dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j], key=len)

    # Возвращаем результат без лишнего пробела
    return join_result(dp[-1][-1].strip().split())

# === Точка входа ===
if __name__ == "__main__":
    s1 = input()
    s2 = input()
    print(longest_common_subsequence(s1, s2))

🎉 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, я могу рассказать о функциях, методах, обьяснить то, что тебе не понятно, а так же о текущей задаче!