Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def int_to_trit(i, t_arr):
- if i < 0: # Special case for handling negatives: just flip all the trits in the positive version
- # return [-x for x in int_to_trit(-i, t_arr)] # the Python way of doing the following:
- negative_result = int_to_trit(-i, t_arr) # Store the result of running this against a positive number
- for i in range(len(negative_result)): # For each index in the negative_result array,
- negative_result[i] *= -1 # negate the stored value
- return negative_result # Return the results
- if i == 0: # Termination case
- 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, [])
- r = abs(i % 3) # Python % always returns a positive number; C does not so some logic below will need changed
- # print "{} % 3 == {}".format(i, r) # for debug
- if r == 2:
- 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.
- 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.
- elif r == 1:
- 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.
- else:
- t_arr.insert(0, 0)
- return int_to_trit(i // 3, t_arr) # The // operator in Python emphasizes integer division (floors the result)
- >>> int_to_trit(0, [])
- [0]
- >>> int_to_trit(1, [])
- [1]
- >>> int_to_trit(2, [])
- [1, -1]
- >>> int_to_trit(3, [])
- [1, 0]
- >>> int_to_trit(72, [])
- [1, 0, -1, 0, 0]
- >>> int_to_trit(121, [])
- [1, 1, 1, 1, 1]
- >>> int_to_trit(-121, [])
- [-1, -1, -1, -1, -1]
- >>> int_to_trit(-72, [])
- [-1, 0, 1, 0, 0]
- >>> int_to_trit(-3, [])
- [-1, 0]
- >>> int_to_trit(-2, [])
- [-1, 1]
- >>> int_to_trit(-1, [])
- [-1]
- # With debug
- >>> int_to_trit(72, [])
- 72 % 3 == 0
- 24 % 3 == 0
- 8 % 3 == 2
- 3 % 3 == 0
- 1 % 3 == 1
- [1, 0, -1, 0, 0]
Add Comment
Please, Sign In to add comment