Guest User

Untitled

a guest
Dec 13th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. def int_to_trit(i, t_arr):
  2. if i < 0: # Special case for handling negatives: just flip all the trits in the positive version
  3. # return [-x for x in int_to_trit(-i, t_arr)] # the Python way of doing the following:
  4. negative_result = int_to_trit(-i, t_arr) # Store the result of running this against a positive number
  5. for i in range(len(negative_result)): # For each index in the negative_result array,
  6. negative_result[i] *= -1 # negate the stored value
  7. return negative_result # Return the results
  8. if i == 0: # Termination case
  9. return t_arr if len(t_arr) > 0 else [0] # Usually, avoid leading 0's, but I had to add an extra condition for calls of int_to_trit(0, [])
  10. r = abs(i % 3) # Python % always returns a positive number; C does not so some logic below will need changed
  11. # print "{} % 3 == {}".format(i, r) # for debug
  12. if r == 2:
  13. t_arr.insert(0, -1) # insert(0, x) simply means to append to the beginning of a list in Python. If using an actual array, this could be accomplished by allocating a new array of size n + 1, setting the first value to -1, and copying the array of size n after the -1 value. Alternatively, the C implementation may allocate an array with 5 indices for this method and pass the current index as a parameter.
  14. i += 1 # I don't know the best way to describe why we have to do this. Think of the case of 2 though. 2 in ternary is represented as [1, -1]; it's 3 - 1. Since 2 is "1 short" of 3, we need to add one to our accumulator.
  15. elif r == 1:
  16. t_arr.insert(0, 1) # Theoretically, we could subtract one from i as we did above, but it won't do anything due to floor division.
  17. else:
  18. t_arr.insert(0, 0)
  19. return int_to_trit(i // 3, t_arr) # The // operator in Python emphasizes integer division (floors the result)
  20.  
  21. >>> int_to_trit(0, [])
  22. [0]
  23. >>> int_to_trit(1, [])
  24. [1]
  25. >>> int_to_trit(2, [])
  26. [1, -1]
  27. >>> int_to_trit(3, [])
  28. [1, 0]
  29. >>> int_to_trit(72, [])
  30. [1, 0, -1, 0, 0]
  31. >>> int_to_trit(121, [])
  32. [1, 1, 1, 1, 1]
  33. >>> int_to_trit(-121, [])
  34. [-1, -1, -1, -1, -1]
  35. >>> int_to_trit(-72, [])
  36. [-1, 0, 1, 0, 0]
  37. >>> int_to_trit(-3, [])
  38. [-1, 0]
  39. >>> int_to_trit(-2, [])
  40. [-1, 1]
  41. >>> int_to_trit(-1, [])
  42. [-1]
  43.  
  44. # With debug
  45. >>> int_to_trit(72, [])
  46. 72 % 3 == 0
  47. 24 % 3 == 0
  48. 8 % 3 == 2
  49. 3 % 3 == 0
  50. 1 % 3 == 1
  51. [1, 0, -1, 0, 0]
Add Comment
Please, Sign In to add comment