bananalib.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. """Main module."""
  2. import logging
  3. import random
  4. log = logging.getLogger("bananalib")
  5. class Codec:
  6. def __init__(self, dictstart=0, shiftend=0, minlength=0, dictionary=None):
  7. self.dictstart = dictstart
  8. self.shiftend = shiftend
  9. if dictionary is None:
  10. self.dictionary = [list("bcdfglmnprstvz"), list("aeiou")]
  11. else:
  12. self.dictionary = dictionary
  13. def encode(self, num, minlength=0):
  14. dictionary = self.dictionary
  15. numdict = len(dictionary)
  16. v = num
  17. st = ""
  18. length = 0
  19. idx = (numdict - 1 + self.dictstart + self.shiftend) % numdict
  20. while not (
  21. v == 0
  22. and idx == (numdict - 1 + self.dictstart) % numdict
  23. and length >= minlength
  24. ):
  25. r = v % len(dictionary[idx])
  26. v = int(v / len(dictionary[idx]))
  27. st = dictionary[idx][r] + st
  28. idx = (idx - 1) % numdict
  29. length += 1
  30. return st
  31. def decode(self, word):
  32. dictionary = self.dictionary
  33. numdict = len(dictionary)
  34. if (len(word) - self.shiftend) % numdict != 0:
  35. raise ValueError("Banana non valida")
  36. v = 0
  37. for i in range(len(word)):
  38. r = (numdict + i + self.dictstart) % numdict
  39. try:
  40. v = v * len(dictionary[r]) + dictionary[r].index(word[i])
  41. except (ValueError, KeyError):
  42. raise ValueError("Carattere non valido in posizione %d" % i + 1)
  43. return v
  44. def is_valid(self, word):
  45. dictionary = self.dictionary
  46. numdict = len(dictionary)
  47. if (len(word) - self.shiftend) % numdict != 0:
  48. return False
  49. for i in range(len(word)):
  50. r = (numdict + i + self.dictstart) % numdict
  51. if word[i] not in dictionary[r]:
  52. return False
  53. return True
  54. def random(self, minlength=6, prng=random.Random()):
  55. numdict = len(self.dictionary)
  56. word = ""
  57. if minlength < 1:
  58. return ""
  59. curr_dict = (numdict - 1 + self.dictstart + self.shiftend) % numdict
  60. final_dict = (numdict - 1 + self.dictstart) % numdict
  61. while curr_dict != final_dict or len(word) < minlength:
  62. word = prng.choice(self.dictionary[curr_dict]) + word
  63. curr_dict = (curr_dict - 1) % numdict
  64. return word
  65. class BananaCodec(Codec):
  66. def __init__(self):
  67. super().__init__()
  68. class RibesCodec(Codec):
  69. def __init__(self):
  70. super().__init__(0, 1)
  71. class AnanasCodec(Codec):
  72. def __init__(self):
  73. super().__init__(1, 0)
  74. class AvocadoCodec(Codec):
  75. def __init__(self):
  76. super().__init__(1, 1)
  77. if __name__ == "__main__":
  78. print("Ciao sono la libreria banana")