Teilzeichenfolgen in PythonPython

Python-Programme
Anonymous
 Teilzeichenfolgen in Python

Post by Anonymous »

Liest man auf diese Weise die Zeichenfolgen aus der Eingabedatei und schreibt alle Zeichenfolgen in eine Ausgabedatei, die als Teilzeichenfolge von mindestens einer anderen Zeichenfolge in der Liste erscheinen?

Code: Select all

# 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")
Logik
  • Vergleiche jede Zeichenfolge mit allen anderen
  • Wenn sie in einer anderen Zeichenfolge erscheint → behalte sie
  • Vermeide den Abgleich mit sich selbst

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post
  • Teilzeichenfolgen in Python
    by Anonymous » » in Python
    0 Replies
    2 Views
    Last post by Anonymous
  • Teilzeichenfolgen in Python
    by Anonymous » » in Python
    0 Replies
    1 Views
    Last post by Anonymous
  • Teilzeichenfolgen und höchste Punktzahl, Python [geschlossen]
    by Anonymous » » in Python
    0 Replies
    1 Views
    Last post by Anonymous
  • Teilzeichenfolgen in Python
    by Anonymous » » in Python
    0 Replies
    2 Views
    Last post by Anonymous
  • Ersetzen Sie alle numerischen Teilzeichenfolgen durch Zeichen
    by Guest » » in Java
    0 Replies
    43 Views
    Last post by Guest