Подстроки в PythonPython

Программы на Python
Ответить
Anonymous
 Подстроки в Python

Сообщение Anonymous »

так вы считываете строки из входного файла и записываете в выходной файл все строки, которые появляются как подстрока хотя бы одной другой строки в списке?

Код: Выделить всё

# QUESTION: Finding Substrings
# Goal: Find strings that appear INSIDE other strings
# Example: "ab" is inside "acab", so "ab" goes in the result

# Step 1: Read all strings from the input file
# open() opens a file, "r" means Read mode
# "with" automatically closes the file when done
with open("input.txt", "r") as f:
# This is a LIST COMPREHENSION - a compact way to build a list
# For each line in the file:
#   - line.strip() removes extra spaces and newlines
#   - add it to the strings list
strings = [line.strip() for line in f]

# Step 2: Create empty list to store results
result = []

# Step 3: Check each string against all other strings
# Outer loop: check each string one by one
for s in strings:
# Inner loop: compare current string (s) with every other string
for other in strings:
# Check TWO conditions (both must be True):
# 1. s != other: don't compare a string with itself
# 2. s in other: is s found inside other? ("ab" in "acab" = True)
if s != other and s in other:
# Found it! Add to results
result.append(s)
# break stops the inner loop (no need to keep checking)
break

# Step 4: Write results to output file
# "w" means Write mode (creates or overwrites the file)
with open("output.txt", "w") as f:
# Write each result string on its own line
for s in result:
# \n is a newline character (like pressing Enter)
f.write(s + "\n")
Логика
  • Сравнить каждую строку со всеми остальными
  • Если она появляется внутри другой строки → сохраните ее
  • Избегайте сопоставления сама с собой


Подробнее здесь: https://stackoverflow.com/questions/798 ... -in-python
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»