Я попробовал, и это мой код, но я не уверен, что это правильно. Я не настолько уверен во втором примере, поскольку попросил Chat-gpt предоставить мне больше тестовых примеров для проверки моего кода ( Я думаю, это должно быть ложью) :
def checkdom(strparam):
# Define the valid tags
valid_tags = {'b', 'i', 'em', 'div', 'p'}
stack = []
tag_positions = [] # Track positions of opening tags
i = 0
while i < len(strparam):
if strparam[i] == ''
end = strparam.find('>', i)
if end == -1:
return False # No closing '>'
tag = strparam[i + 1:end]
if tag.startswith('/'): # Closing tag
tag_name = tag[1:]
if stack and stack[-1] == tag_name:
stack.pop() # Correct closing tag
tag_positions.pop() # Remove tracked position
else:
# If the closing tag doesn't match the top of the stack
if len(stack) == 1: # If there's only one mismatch
return f"{stack[-1]}" # Suggest the tag to fix
return False
else: # Opening tag
if tag in valid_tags:
stack.append(tag) # Push to stack
tag_positions.append((tag, i)) # Track opening tag position
else:
return False # Invalid tag
i = end + 1
else:
i += 1 # Move to the next character
# Check for leftover unclosed tags
if len(stack) == 1:
return f"{stack[-1]}"
else:
return len(stack) == 0 # True if stack is empty
# Example usage
print(checkdom("
hello world
[/b]")) # True[b]print(checkdom("
hello world[/b]"))#I think this should be false?[b]print(checkdom("[i]hello[/i]world[/b]")) #[b]print(checkdom("helloworld[/b]")) # False
Я попробовал, и это мой код, но я не уверен, что это правильно. Я не настолько уверен во втором примере, поскольку попросил Chat-gpt предоставить мне больше тестовых примеров для проверки моего кода ( Я думаю, это должно быть ложью) :[b][code]def checkdom(strparam): # Define the valid tags valid_tags = {'b', 'i', 'em', 'div', 'p'} stack = [] tag_positions = [] # Track positions of opening tags
i = 0 while i < len(strparam): if strparam[i] == '' end = strparam.find('>', i) if end == -1: return False # No closing '>' tag = strparam[i + 1:end] if tag.startswith('/'): # Closing tag tag_name = tag[1:] if stack and stack[-1] == tag_name: stack.pop() # Correct closing tag tag_positions.pop() # Remove tracked position else: # If the closing tag doesn't match the top of the stack if len(stack) == 1: # If there's only one mismatch return f"{stack[-1]}" # Suggest the tag to fix return False else: # Opening tag if tag in valid_tags: stack.append(tag) # Push to stack tag_positions.append((tag, i)) # Track opening tag position else: return False # Invalid tag i = end + 1 else: i += 1 # Move to the next character
# Check for leftover unclosed tags if len(stack) == 1: return f"{stack[-1]}" else:
return len(stack) == 0 # True if stack is empty
# Example usage print(checkdom(" hello world [/b]")) # True[b]print(checkdom(" hello world[/b]"))#I think this should be false?[b]print(checkdom("[i]hello[/i]world[/b]")) #[b]print(checkdom("helloworld[/b]")) # False [/code] [img]https://i.sstatic.net/1MPJ503L.jpg[/img]