bananalib.py 2.7 KB

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