From 4e69938d7b55a8f1b50bd263e10247504b91b158 Mon Sep 17 00:00:00 2001 From: Daniel Tsvetkov Date: Mon, 9 Mar 2020 09:42:55 +0100 Subject: [PATCH] 3sat and grover fixes --- 3sat.py | 4 ++-- grover.py | 19 +++++++++++++++++-- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/3sat.py b/3sat.py index c979092..d39d56f 100644 --- a/3sat.py +++ b/3sat.py @@ -3,7 +3,7 @@ import itertools import random from pprint import pprint -from grover import classical_func_search +from grover import classical_func_search_multi_rv class X(object): @@ -88,7 +88,7 @@ def classical_3sat(func): # Generate all possible true/false tupples for the 3-sat problem input_range = list(itertools.product([True, False], repeat=func.predicates)) random.shuffle(input_range) - return classical_func_search(func, input_range) + return classical_func_search_multi_rv(func, input_range) def main(): diff --git a/grover.py b/grover.py index 01401ae..986ffe4 100644 --- a/grover.py +++ b/grover.py @@ -4,7 +4,7 @@ import random from pprint import pprint -def classical_func_search(func, input_range): +def classical_func_search_multi_rv(func, input_range): """Grover’s 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. @@ -17,6 +17,21 @@ def classical_func_search(func, input_range): return rv +def classical_func_search_single_rv(func, input_range): + """Grover’s algorithm takes a function, searches through + the implicit list of possible inputs to that function, and + returns EXACTLY ONE input that causes the function to return true. + """ + rv = None + for i, params in enumerate(input_range): + result = func(params) + if result and rv is None: + rv = result + else: + raise Exception("Exactly one result is needed") + return rv + + def _3sat(params): # https://cstheory.stackexchange.com/questions/38538/oracle-construction-for-grovers-algorithm # 3-SAT from here: https://qiskit.org/textbook/ch-applications/satisfiability-grover.html @@ -32,7 +47,7 @@ def classical_3sat(func): # Generate all possible true/false tupples for the 3-sat problem input_range = list(itertools.product([True, False], repeat=3)) random.shuffle(input_range) - return classical_func_search(func, input_range) + return classical_func_search_multi_rv(func, input_range) def main():