Guest User

16bit

a guest
May 7th, 2016
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.00 KB | None | 0 0
  1. from itertools import permutations
  2.  
  3. def find_sum_equal_n_16bit():
  4.     solutions = set()
  5.     best = 10**6
  6.     num1, num2 = split_list(16)
  7.     list_perm2 = list(permutations(num2))
  8.     for perm1 in permutations(num1):
  9.         for perm2 in list_perm2:
  10.             perm = perm1 + perm2
  11.             tple = product_sum(perm)
  12.             temp_best = abs(product_num(tple))
  13.             if temp_best <= best:
  14.                 print perm
  15.                 display_tuple(tuple_2_16bit(perm))
  16.                 best = temp_best
  17.                 if temp_best == 0:
  18.                     solutions.add(perm)
  19.     return list(solutions)
  20.  
  21.  
  22. def split_list(n):
  23.     # Greedy algorithm to divide the list into two
  24.     num = range(1, n)
  25.     high = [num.pop(1)]
  26.     low = []
  27.     while len(num) > 0:
  28.         while sum(high) >= sum(low) and len(num) > 0:
  29.             low.append(num.pop())
  30.         temp_high = high
  31.         high = low
  32.         low = temp_high
  33.     if len(high) > len(low):
  34.         low.append(0)
  35.     else:
  36.         high.append(0)
  37.     return high, low
  38.  
  39.  
  40. def product_sum(tple):
  41.     lst = list(tple)
  42.     num1 = sum(k*16**(4-i) for i, k in enumerate(lst[0:5]))
  43.     num2 = sum(k*16**(2-i) for i, k in enumerate(lst[5:8]))
  44.     num3 = sum(k*16**(4-i) for i, k in enumerate(lst[8:13]))
  45.     num4 = sum(k*16**(2-i) for i, k in enumerate(lst[13:16]))
  46.     return (num1, num2, num3, num4)
  47.  
  48.  
  49. def product_num(tple):
  50.     total = tple[0]*tple[1] - tple[2]*tple[3]
  51.     return total
  52.  
  53.  
  54. def tuple_2_16bit(tple):
  55.     key1 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
  56.     key = key1 + ['A', 'B', 'C', 'D', 'E', 'F']
  57.     lst = [str(key[i]) for i in tple]
  58.     return (''.join(lst[0: 5]), ''.join(lst[5: 8]), ''.join(lst[8: 13]), ''.join(lst[13: 16]))
  59.  
  60.  
  61. def display_tuple(tple):
  62.     print '   ' + tple[0] + ' x ' + tple[1]
  63.     print ' - ' + tple[2] + ' x ' + tple[3]
  64.     print ' = ', int(tple[0], 16)*int(tple[1], 16) - int(tple[2], 16)*int(tple[3], 16)
  65.  
  66. if __name__ == '__main__':
  67.  
  68.     print find_sum_equal_n_16bit()
Advertisement
Add Comment
Please, Sign In to add comment