I trying to figure out the most effective way to accomplish this task:
A function, check()
, contains a list of strings. Calling the function with a string as argument, will return True
if the argument string is part of any of the strings in the list. False
if not.
I want to guess the content of that list in as few checks as possible, using the check()
function, knowing only the charset (alphanumeric
+ -_@.[space]
) and displaying the progress (I'm using tqdm).
My code does accomplish this, but it is very inefficient. For example if "strings" is in the list, it performs checks for both "tring", "string" and "trings", which I feel like could be optimized.
Here's my code:
import string
from tqdm import tqdm
def check(text):
"""Returns True if input text is part of any of the strings in the list"""
strings = ["we ", "_want", "t0", "gu@ess", "these-", "str1ngs"]
return any(text in substring for substring in strings)
def remove_partials(input_list):
"""Removes strings from the input list they are a substring of any other string in the list"""
substrings = []
for item in input_list:
for item_2 in input_list:
if item != item_2 and item_2 in item:
substrings.append(item_2)
for partial in substrings:
try:
input_list.remove(partial)
except ValueError:
pass
return input_list
charset = f"{string.ascii_lowercase}{string.digits}@-_. "
known = charset
tried = []
result = []
while len(known) > 0:
found = []
for prefix in (pbar_2 := (tqdm(known, leave=False))):
pbar_2.set_description(prefix)
for char in (pbar := (tqdm(charset, leave=False))):
substring = f"{prefix}{char}"
pbar.set_description(char)
if substring not in tried:
if check(substring) and substring not in found:
tqdm.write(f"{substring}")
found.append(substring)
result.append(substring)
tried.append(substring)
known = found
print()
print(remove_partials(result))
check
function supposed to be a "black box", as in, it's an external function you have no control over? And you're trying to figure out which words satisfy it? \$\endgroup\$