Wie validieren Sie, wenn eine Liste mit einem bestimmten strukturellen Muster übereinstimmt?
Posted: 15 Feb 2025, 06:57
Ich versuche, eine Python -Funktion zu schreiben, um zu überprüfen
In Wörtern:
Code: Select all
model = [
["h", "P12", "P13"],
["P12", "P23", "eL"],
["P13", "P23", "eR"]
]
- Die festen Elemente "H" , "el" und "er" muss in verschiedenen Sublisten erscheinen. "P23" - sind willkürliche Elemente abhängig von der zu testenden Liste. Code>, "el" und "er" in einem Sublisten sind zulässig, wenn es zur Modellstruktur passt.
Code: Select all
test_list_1 = [
["h", "a2", "a3"],
["a2", "a4", "eL"],
["a3", "a4", "eR"]
]
> True
test_list_2 = [
["h", "h", "Y"],
["h", "Z", "eL"],
["Y", "Z", "eR"]
]
> True
test_list_3 = [
["h", "X", "eL"],
["X", "Z", "eL"],
["eL", "Z", "eR"]
]
> True
test_list_4 = [
["h", "P1", "eL"],
["P1", "P3", "P2"], # ❌ there is no list containing "eL"
["P2", "P3", "eR"]
]
> False
< /code>
Ich habe es mit ChatGPT ausprobiert, aber der folgende Code funktioniert nicht ordnungsgemäß, und bisher kann ich es nicht funktionieren: < /p>
from collections import defaultdict
def validate_structure(model, test_list):
fixed_elements = {"h", "eL", "eR"}
model_fixed_positions = {}
placeholder_mapping = {}
# Step 1: Identify where fixed elements appear in the model
for i, sublist in enumerate(model):
for item in sublist:
if item in fixed_elements:
model_fixed_positions[item] = i
# Step 2: Identify where fixed elements appear in the test list
test_fixed_positions = {}
for i, sublist in enumerate(test_list):
for item in sublist:
if item in fixed_elements:
if item in test_fixed_positions:
return False # Each fixed element must be in a distinct sublist
test_fixed_positions[item] = i
# Step 3: Ensure fixed elements are in corresponding positions
if set(model_fixed_positions.keys()) != set(test_fixed_positions.keys()):
return False # Missing or extra fixed elements
for key in model_fixed_positions:
if model_fixed_positions[key] != test_fixed_positions[key]:
return False # Fixed elements must appear in the same indexed sublists
# Step 4: Establish and validate placeholder mapping
for i, (model_sublist, test_sublist) in enumerate(zip(model, test_list)):
model_placeholders = [x for x in model_sublist if x not in fixed_elements]
test_placeholders = [x for x in test_sublist if x not in fixed_elements]
if len(model_placeholders) != len(test_placeholders):
return False # Different number of elements
for m_item, t_item in zip(model_placeholders, test_placeholders):
if m_item in placeholder_mapping:
if placeholder_mapping[m_item] != t_item:
return False # Inconsistent placeholder mapping
else:
placeholder_mapping[m_item] = t_item
return True # Structure matches
# Example usage:
print(validate_structure(model, test_list_2)) # Expected: True, but returns False