bananalib.py 2.6 KB

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