quantum/grover.py

46 lines
1.3 KiB
Python
Raw Normal View History

2020-02-21 15:35:40 +01:00
# http://twistedoakstudios.com/blog/Post2644_grovers-quantum-search-algorithm
import inspect
import itertools
import random
from pprint import pprint
def classical_func_search(func, input_range):
"""Grovers algorithm takes a function, searches through
the implicit list of possible inputs to that function, and
returns inputs that causes the function to return true.
"""
rv = []
for i, params in enumerate(input_range):
result = func(params)
if result:
rv.append(params)
return rv
def _3sat(x1, x2, x3):
# https://cstheory.stackexchange.com/questions/38538/oracle-construction-for-grovers-algorithm
# 3-SAT from here: https://qiskit.org/textbook/ch-applications/satisfiability-grover.html
return (not x1 or not x2 or not x3) and \
(x1 or not x2 or x3) and \
(x1 or x2 or not x3) and \
(x1 or not x2 or not x3) and \
(not x1 or x2 or x3)
def classical_3sat(func):
# Generate all possible true/false tupples for the 3-sat problem
sig = inspect.signature(func)
params = sig.parameters
input_range = list(itertools.product([True, False], repeat=len(params)))
random.shuffle(input_range)
return classical_func_search(func, input_range)
def main():
pprint(classical_3sat(_3sat))
if __name__ == "__main__":
main()