22Simon's Algorithm (Classical Simulation)
33
44Simon's algorithm finds a hidden bitstring s such that
5- f(x ) = f(y ) if and only if x XOR y = s.
5+ f(input_bits ) = f(other_bits ) if and only if input_bits XOR other_bits = s.
66
77Here we simulate the mapping behavior classically to
88illustrate how the hidden period can be discovered by
9- analyzing collisions in f(x ).
9+ analyzing collisions in f(input_bits ).
1010
1111References:
1212https://en.wikipedia.org/wiki/Simon's_problem
1616from itertools import product
1717
1818
19- def xor_bits (a : list [int ], b : list [int ]) -> list [int ]:
19+ def xor_bits (bits1 : list [int ], bits2 : list [int ]) -> list [int ]:
2020 """
2121 Return the bitwise XOR of two equal-length bit lists.
2222
2323 >>> xor_bits([1, 0, 1], [1, 1, 0])
2424 [0, 1, 1]
2525 """
26- if len (a ) != len (b ):
26+ if len (bits1 ) != len (bits2 ):
2727 raise ValueError ("Bit lists must be of equal length." )
28- return [x ^ y for x , y in zip (a , b )]
28+ return [x ^ y for x , y in zip (bits1 , bits2 )]
2929
3030
31- def simons_algorithm (f : Callable [[list [int ]], list [int ]], n : int ) -> list [int ]:
31+ def simons_algorithm (f : Callable [[list [int ]], list [int ]], num_bits : int ) -> list [int ]:
3232 """
3333 Simulate Simon's algorithm classically to find the hidden bitstring s.
3434
3535 Args:
3636 f: A function mapping n-bit input to n-bit output.
37- n : Number of bits in the input.
37+ num_bits : Number of bits in the input.
3838
3939 Returns:
4040 The hidden bitstring s as a list of bits.
4141
4242 >>> # Example with hidden bitstring s = [1, 0, 1]
4343 >>> s = [1, 0, 1]
44- >>> def f(x ):
44+ >>> def f(input_bits ):
4545 ... mapping = {
4646 ... (0,0,0): (1,1,0),
4747 ... (1,0,1): (1,1,0),
@@ -52,22 +52,22 @@ def simons_algorithm(f: Callable[[list[int]], list[int]], n: int) -> list[int]:
5252 ... (0,1,1): (0,0,0),
5353 ... (1,1,0): (0,0,0),
5454 ... }
55- ... return mapping[tuple(x )]
55+ ... return mapping[tuple(input_bits )]
5656 >>> simons_algorithm(f, 3)
5757 [1, 0, 1]
5858 """
5959 mapping : dict [tuple [int , ...], tuple [int , ...]] = {}
60- inputs = list (product ([0 , 1 ], repeat = n ))
60+ inputs = list (product ([0 , 1 ], repeat = num_bits ))
6161
62- for x in inputs :
63- fx = tuple (f (list (x )))
62+ for bits in inputs :
63+ fx = tuple (f (list (bits )))
6464 if fx in mapping :
65- y = mapping [fx ]
66- return xor_bits (list (x ), list (y ))
67- mapping [fx ] = x
65+ prev_bits = mapping [fx ]
66+ return xor_bits (list (bits ), list (prev_bits ))
67+ mapping [fx ] = bits
6868
6969 # If no collision found, function might be constant
70- return [0 ] * n
70+ return [0 ] * num_bits
7171
7272
7373if __name__ == "__main__" :
0 commit comments