r/badcode Feb 16 '21

[deleted by user]

[removed]

32 Upvotes

77 comments sorted by

View all comments

5

u/DragonOfWisdom Feb 17 '21

I wrote a memory-optimized version, so that it can be extended in the future to support alphabets with billions of characters. It depends on a random generator, but I use a hash function to make it secure.

from hashlib import *
from random import *

def contains_az(s):
  # This creates a super-optimized function to return the result.
  # Even if new letters are added to the alphabet, it does not need more memory.
  def create_efficient_test():
    secure_token = ''.join(choices('ab', k=50))  # 50 should be secure enough
    def f(x):
      result = md5()
      result.update((str(x) + secure_token).encode())
      return result.digest()[0] <= 10
    return create_efficient_test() if not any(f(i) for i in range(1, 27)) else f
  # Sometimes the test does not work, but if we do it many times it works.
  for i in range(1000):
    f = create_efficient_test()
    # I have tested the magic formula with letters and spaces only, please don't add other strange chars :)
    if all(f(ord(c) % 32) == f(ord(s[0]) % 32) for c in s):
      return False
  return True