Book Image

Artificial Intelligence with Python

Book Image

Artificial Intelligence with Python

Overview of this book

Artificial Intelligence is becoming increasingly relevant in the modern world. By harnessing the power of algorithms, you can create apps which intelligently interact with the world around you, building intelligent recommender systems, automatic speech recognition systems and more. Starting with AI basics you'll move on to learn how to develop building blocks using data mining techniques. Discover how to make informed decisions about which algorithms to use, and how to apply them to real-world scenarios. This practical book covers a range of topics including predictive analytics and deep learning.
Table of Contents (23 chapters)
Artificial Intelligence with Python
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Validating primes


Let's see how to use logic programming to check for prime numbers. We will use the constructs available in logpy 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:

import itertools as it 
import logpy.core as lc 
from sympy.ntheory.generate import prime, isprime 

Next, define a function that checks if the given number is prime depending on the type of data. If it's a number, then it's pretty straightforward. If it's 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 check_prime(x): 
    if lc.isvar(x): 
        return lc.condeseq([(lc.eq, x, p)] for p in map(prime, it.count(1))) 
    else: 
        return lc.success...