Question: We will use the constructs available in kanren to determine which numbers in the given list are prime, as well as finding out if a
We will use the constructs available in kanren to determine which numbers in the given list are prime, as well
as finding out if a given number is a prime or not. Create a new Python file and import the following packages:
from kanren import isvar, run, membero from kanren.core import success, fail, goaleval, condeseq, eq, var from sympy.ntheory.generate import prime, isprime import itertools as it
Next, define a function that checks if the given number is prime depending on the type of data. If its a number, then its pretty straightforward. If its a variable, then we have to run the sequential operation. To give a bit of background, the method conde is a goal constructor that provides logical AND and OR operations. The method condeseq is like conde, but it supports generic iterator of goals:
# Check if the elements of x are prime def prime check(x): if isvar(x): return condeseq([(eq, x, p)] for p in map(prime,it.count(1))) else: return success if isprime(x) else fail Declare the variable x that will be used: # Declate the variable x = var()
Define a set of numbers and check which numbers are prime. The method membero checks if a given number is a member of the list of numbers specified in the input argument: # Check if an element in the list is a prime number list nums = (23, 4, 27, 17, 13, 10, 21, 29, 3, 32, 11, 19) print( List of primes in the list:) print(set(lc.run(0, x, (membero, x, list nums), (prime check, x))))
Lets use the function in a slightly different way now by printing the first 7 prime numbers:
# Print first 7 prime numbers print( List of first 7 prime numbers:) print(run(7, x, prime check(x))) Run the code, and capture the output screen.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
