DEV Community

Cover image for Crack the Code
Modasser Billah
Modasser Billah

Posted on • Originally published at modasserbillah.ml

3 1

Crack the Code

With quarantines and lock-downs, most people around the world are stuck and bored in their houses. A lot of fun riddles are circulating in news feeds on social medias. Here's one of those.

riddle

Can you crack the code? It's fun to solve by hand but can you crack it using Python? Here's how I did it:

from itertools import product


def first_fifth_condition(candidate, condition):
    common_elements = [digit for digit in candidate if digit in condition]
    return (len(common_elements) == 1) and (
        candidate.index(common_elements[0]) != condition.index(common_elements[0])
    )


def second_condition(candidate):
    condition = (1, 8, 9)
    common_elements = [digit for digit in candidate if digit in condition]
    return (len(common_elements) == 1) and (
        candidate.index(common_elements[0]) == condition.index(common_elements[0])
    )


def third_condition(candidate):
    condition = (9, 6, 4)
    common_elements = [digit for digit in candidate if digit in condition]
    if len(common_elements) != 2:
        return False
    for digit in common_elements:
        if candidate.index(digit) == condition.index(digit):
            return False
    return True


def fourth_condition(candidate):
    condition = (5, 2, 3)
    common_elements = [digit for digit in candidate if digit in condition]
    return len(common_elements) == 0


def find_code():
    # for completeness test all possible permutations with repetition of digits for length 3.
    # We can further optimize by eliminating 0,5,2,3 from the possible candidate calculation.
    for candidate in product(range(10), repeat=3):
        if (
            first_fifth_condition(candidate, (1, 4, 7))
            and second_condition(candidate)
            and third_condition(candidate)
            and fourth_condition(candidate)
            and first_fifth_condition(candidate, (2, 8, 6))
        ):
            return "".join(map(str, candidate))
    return "No solution found."


if __name__ == "__main__":
    print(find_code())

Enter fullscreen mode Exit fullscreen mode

Got better code to crack the code? Share links to your solution in the comments! Happy hacking!

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay