Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

python for ai

The document provides an overview of Artificial Intelligence (AI), including its definition, historical milestones, and key figures in its development. It also discusses the construction of intelligent agents, symbolic and non-symbolic representations, and the advantages of each. Additionally, the document introduces Python programming, highlighting its features, installation process, basic syntax, and fundamental concepts such as variables, keywords, and operators.

Uploaded by

amesgtari4682
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

python for ai

The document provides an overview of Artificial Intelligence (AI), including its definition, historical milestones, and key figures in its development. It also discusses the construction of intelligent agents, symbolic and non-symbolic representations, and the advantages of each. Additionally, the document introduces Python programming, highlighting its features, installation process, basic syntax, and fundamental concepts such as variables, keywords, and operators.

Uploaded by

amesgtari4682
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 155

Lesson 1: Artificial Intelligence - Review

What is Artificial Intelligence?


"AI is the boundary between what people can do and what computers can't [yet]."

History
Ancient Times

 Aristotle (Logic as an instrument for studying thought)

Early Efforts by Philsopher/Mathemticians

 Descartes (The mind body problem)


 Hume (Cognition is computation)
 Euler (1735 - representation of structure; search)

Formal Notation and Calculating Machines

 Leibnitz (1887 - first system of formal logic; calculating machines)


 Babbage (Programmable computing machines)
 Boole (1847, 1859)
 Frege (1879, 1884 - first-order predicate calculus)

Modern Founders of AI

 Alan Turing ("Computing Machinery and Intelligence"; Turing test)


 McCulloch & Pitts (neural nets)
 Norbert Wiener (cybernetics)
 John von Neumann (game theory)
 Claude Shannon (information theory)
 Newell & Simon (The Logic Theorist)
 John McCarthy (LISP, common sense reasoning)
 Marvin Minsky (Frames)
 Donald Michie (Freddy)

Achievements of AI
 Deep Thought is an international grand master chess player.
 Sphinx can recognise continuous speech without training for each speaker. It
operates in near real time using a vocabulary of 1000 words and has 94% word
accuracy.
 Navlab is a truck that can drive along a road at 55mph in normal traffic.
 Carlton and United Breweries use an AI planning system to plan production of
their beer.
 Robots are used regularly in manufacturing.
 Natural language interfaces to databases can be obtained on a PC.
 Machine Learning methods have been used to build expert systems.
 Expert systems are used regularly in finance, medicine, manufacturing, and
agriculture

How do we build an intelligent agent?


 Must be able to perceive its environment.
 Must be able to affect its environment.
 Must be able to reason about observations and actions
 Must be able to learn from observations and actions.
 Must have goals.

Symbolic Representations
To construct intelligent systems it is necessary to employ internal representations of a
symbolic nature, with cognitive activity corresponding to computational manipulation
of these symbolic representations. The symbolic representations must refer to the
external world.

Advantages of symbolic representation:


 The system builder can read what the system knows.
 Knowledge is represented by sentences in a formal language.
 It is possible to read the representation and understand the meaning of the
knowledge.

Non-symbolic Representations
Knowledge is represented by weights on connections in a network

Advantages of non-symbolic representation

 Can deal with combinations of attributes such as an image.


 Noise tolerant
ARTIFICIAL INTELLIGENCE
PROGRAMMING

LESSON 2: INTRODUTION TO PYTHON PROGRAMMING


Why You Should Use Python
• Python, named after the British comedy group Monty Python, is a high-
level, interpreted, interactive, and object-oriented programming language.
Its flexibility allows you to do many things, both big and small. With Python,
you can write basic programs and scripts and also to create complex and
large-scale enterprise solutions. Here’s a sampling of its uses:
• Building desktop applications, including GUI applications, CLI tools, and even games
• Doing mathematical and scientific analysis of data
• Building web and Internet applications
• Doing computer systems administration and automating tasks
• Performing DevOps tasks
• You can find Python everywhere in the world of computer programming. For
example, Python is the foundation of some of the world’s most popular websites,
including Reddit, Dropbox, and YouTube, to name a few. The Python web
framework Django powers both Instagram and Pinterest.
• Python has a bunch of features that make it attractive as your first programming
language:
• Free: Python is available free of charge, even for commercial purposes.
• Open source: Anyone can contribute to Python development.
• Accessible: People of all ages, from school children to retirees, have learned Python, and so
can you.
• Versatile: Python can help you solve problems in many fields, including scripting, data
science, web development, GUI development, and more.
• Powerful: You can code small scripts to automate repetitive tasks, and you can also create
complex and large-scale enterprise solutions with Python.
• Compared to other programming languages, Python has the following
features:
• Interpreted: It’s portable and quicker to experiment with than compiled languages.
• Multiparadigm: It lets you write code in different styles, including object-
oriented, imperative, and functional style.
• Dynamically typed: It checks variable types at runtime, so you don’t need to declare
them explicitly.
• Strongly typed: It won’t let unsafe operations on incompatible types go unnoticed.
How to Download and Install Python
• Python works on Linux, Mac, Windows, and several other platforms. It
comes preinstalled on macOS and on most Linux distributions. However, if
you want to be up to date, then you probably need to download and install
the latest version. You also have the choice of using different Python
versions in different projects if you want to.
• To check what Python version has been installed globally in your operating
system, open the terminal or command line and run the following
command:
• $ python3 -V
• This command prints the version of your system’s default Python 3
installation. Note that you use python3 instead of python because some
operating systems still include Python 2 as their default Python installation.
Installing Python From Binaries
• Regardless of your operating system, you can download an appropriate
version of Python from the official site. Go there and grab the appropriate
32-bit or 64-bit version for your operating system and processor.
• Selecting and downloading a Python binary from the language’s official site
is often a good choice. However, there are some OS-specific alternatives:
• macOS:You have the option of installing Python from Homebrew.
• Linux: You can install several Python versions using your distribution’s package
manager.
• Windows: You can install Python from the Microsoft Store.
• You can also use the Anaconda distribution to install Python along with a
rich set of packages and libraries, or you can use Miniconda if you want to
install only the packages you need
Running Your Python Interpreter

• >>>
• >>> print("Python is fun!")
• Python is fun!
• That’s it! You’ve just written your first Python program! When you’re done,
you can use exit() or quit() to leave the interactive session, or you can use
the following key combinations:
• macOS and Linux: Ctrl+D
• Windows: Ctrl+D and then press Enter
The Basic Python Syntax
• The Python syntax is clear, concise, and focused on readability. Readability
is arguably one of the more attractive features of the language itself. It
makes Python ideal for people who are learning to program. There are
several important components of the Python syntax:
• Comments
• Variables
• Keywords
• Built-in data types
• Conditional statements
• Loops
• Functions
Comments
• Comments are pieces of text that live in your code but are ignored by the Python
interpreter as it executes the code. You can use comments to describe the code so
that you and other developers can quickly understand what the code does or why
the code is written in a given way. To write a comment in Python, just add a hash
mark (#) before your comment text:
• # This is a comment on its own line
• The Python interpreter ignores the text after the hash mark and up to the end of
the line. You can also add inline comments to your code. In other words, you can
combine a Python expression or statement with a comment in a single line, given
that the comment occupies the final part of the line:
• var = "Hello, World!" # This is an inline comment
• You should use inline comments sparingly to clear up pieces of code that aren’t
obvious on their own. In general, your comments should be short and to the point.
Variables
• In Python, variables are names attached to a particular object. They hold a reference,
or pointer, to the memory address at which an object is stored. Once a variable is assigned
an object, you can access the object using the variable name.
• You need to define your variables in advance. Here’s the syntax:
• variable_name = variable_value
• You should use a naming scheme that makes your variables intuitive and readable. The
variable name should provide some indication as to what the values assigned to it are.
• Your variable names can be any length and can consist of uppercase and lowercase letters
(A-Z, a-z), digits (0-9), and also the underscore character (_). In sum, variable names should
be alphanumeric, but note that even though variable names can contain digits, their first
character can’t be a digit.
• Note: The lower_case_with_underscores naming convention, also known as snake_case,
is commonly used in Python. It isn’t enforced, but it’s a widely adopted standard.
Keywords
• Like any other programming language, Python has a set of special words that are part of its syntax. These
words are known as keywords. To get the complete list of keywords available in your current Python
installation, you can run the following code in an interactive session:
• >>>
• >>> help("keywords")
• Here is a list of the Python keywords. Enter any keyword to get more help.
• False class from or
• None continue global pass
• True def if raise
• and del import return
• as elif in try
• assert else is while
• async except lambda with
• await finally nonlocal yield
• break for not
• There’s another way of getting access to the whole list of Python keywords:
• >>>
• >>> import keyword
• >>> keyword.kwlist
• ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'cla
• ss', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from
• ', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pas
• s', 'raise', 'return', 'try', 'while', 'with', 'yield']
• keyword provides a set of functions that allow you to determine if a given
string is a keyword. For example, keyword.kwlist holds a list of all the
current keywords in Python. These are handy when you need to manipulate
keywords programmatically in your Python programs.
• Here are some examples of valid and invalid variable names in Python:
• >>>
• >>> numbers = [1, 2, 3, 4, 5]
• >>> numbers
• [1, 2, 3, 4, 5]

• >>> first_num = 1
• >>> first_num
• 1

• >>> 1rst_num = 1
• File "<input>", line 1
• 1rst_num = 1
• ^
• SyntaxError: invalid syntax

• >>> π = 3.141592653589793
• >>> π
• 3.141592653589793
Operators
• Operators represent operations, such as addition, subtraction, multiplication, division, and so on. When
you combine them with numbers, they form expressions that Python can evaluate:
• >>>
• >>> # Addition
• >>> 5 + 3
• 8

• >>> # Subtraction
• >>> 5 - 3
• 2

• >>> # Multiplication
• >>> 5 * 3
• 15
• >>> # Division
• >>> 5 / 3
• 1.6666666666666667

• >>> # Floor division
• >>> 5 // 3
• 1

• >>> # Modulus (returns the remainder from division)
• >>> 5 % 3
• 2

• >>> # Power
• >>> 5 ** 3
• 125
• These operators work with two operands and are commonly known as arithmetic operators. The operands can be
numbers or variables that hold numbers.
• Besides operators, Python provides you with a bunch of built-in
functions for manipulating numbers. These functions are always available to
you. In other words, you don’t have to import them to be able to use them in
your programs.
• Note: There are modules available in the Python standard library, such
as math, that also provide you with functions to manipulate numbers.
• To use the functions associated with these modules, you first have to import
the module and then access the function using module.function_name().
Alternatively, you can import a function directly from the module using:
• from module import function_name.
• Given an integer number or a string representing a number as an argument, float() returns a floating-point number:
• >>>
• >>> # Integer numbers
• >>> float(9)
• 9.0
• >>> float(-99999)
• -99999.0

• >>> # Strings representing numbers
• >>> float("2")
• 2.0
• >>> float("-200")
• -200.0
• >>> float("2.25")
• 2.25

• >>> # Complex numbers
• >>> float(complex(1, 2))
• Traceback (most recent call last):
• File "<input>", line 1, in <module>
• float(complex(1, 2))
• TypeError: can't convert complex to float
• With float(), you can convert integer numbers and strings representing numbers into floating-point numbers, but you can’t convert a complex number into a floating-
point number.
• Given a floating-point number or a string as an argument, int() returns an integer. This function doesn’t
round the input up to the nearest integer. It simply truncates the input, throwing out anything after the
decimal point, and returns the number. So, an input of 10.6 returns 10 instead of 11. Similarly, 3.25 returns 3:
• >>>
• >>> # Floating-point numbers
• >>> int(10.6)
• 10
• >>> int(3.25)
• 3

• >>> # Strings representing numbers
• >>> int("2")
• 2
• >>> int("2.3")
• Traceback (most recent call last):
• File "<input>", line 1, in <module>
• int("2.3")
• ValueError: invalid literal for int() with base 10: '2.3'

• Note that you can pass a string representing an integer to int(), but you can’t pass a string representing a
floating-point number. Complex numbers don’t work either.
• Besides these built-in functions, there are a few methods associated with each type of number. You can
access them using attribute reference, also known as dot notation:
• >>>
• >>> 10.0.is_integer()
• True
• >>> 10.2.is_integer()
• False

• >>> (10).bit_length()
• 4
• >>> 10.bit_length()
• File "<input>", line 1
• 10.bit_length()
• ^
• SyntaxError: invalid syntax
• These methods can be a useful tool to learn about. In the case of integer numbers, to access their methods
through a literal, you need to use a pair of parentheses. Otherwise, you get a SyntaxError.
Numbers

• Python provides integers, floating-point numbers, and complex


numbers. Integers and floating-point numbers are the most commonly
used numeric types in day-to-day programming, while complex
numbers have specific use cases in math and science.
• Integer numbers have unlimited precision. Floating-point numbers’
precision information is available in sys.float_info. Complex numbers
have a real part and an imaginary part, which are both floating-point
numbers.
Here’s a summary of their features:

Number Description Examples Python Data Type


Integer Whole numbers 1, 2, 42, 476, -99999 int

Floating-point Numbers with decimal points 1.0, 2.2, 42.09, 476.1, -99999.9 float

Complex Numbers with a real part and complex(1, 2), complex(-1, complex
an imaginary part 7), complex("1+2j")
ARTIFICIAL INTELLIGENCE PROGRAMMING

Lesson 3: Step by step instruction to install Python in


Windows

Installing or updating Python on your system is the first step to


becoming a Python developer. There are many ways you can get started
with setup and installation: you can download official Python
distributions from Python.org, install from a package
manager(Anaconda), and even install specialized distributions for
scientific computing, Internet of Things, and embedded systems.

Check if you already have Python installed

You can check in the command-line application, such as PowerShell

Tip: Here’s how you open PowerShell:

1. Press the ⊞ Win key.

2. Type PowerShell or cmd.

3. Press Enter
Alternatively, you can right-click the Start button and select Windows
PowerShell or Windows PowerShell (Admin).

If you’re interested in where the installation is located, then you


can use the where.exe command in Command Prompt or
PowerShell.

Python | PowerShell

1. Run python without parameters


2. Install Python — Full Installer

Step 1: Select Version of Python to download Full Installer and


install

The most stable Windows downloads are available from the Python for
Windows page. On Windows, you have a choice between 32-bit
(labeled x86) and 64-bit (labeled x86–64) versions, and several flavors
of the installer for each. Underneath the Python Releases for Windows
find the Latest Python 3 Release — Python 3.9.4
Step 2: Download Python Executable Installer and install it

Double-click the executable file, which is downloaded; the following


window will open. Select Customize installation and proceed. Click on
the Add Path check box, it will set the Python path automatically.

1. Run the Python Installer once downloaded. (In this example, we


have downloaded Python 3.9.4)

2. Make sure you select the “Install launcher for all users” and “Add
Python 3.9 to PATH” checkboxes.

3. Select Install Now — the recommended installation options.


Step 3: Wait for it to complete the installation process
The next dialog will prompt you to select whether to Disable the path
length limit. Choosing this option will allow Python to bypass the 260-
character MAX_PATH limit. Effectively, it will enable Python to use
long path names.
The Disable path length limit option will not affect any other system
settings. Turning it on will resolve potential name length issues that
may arise with Python projects developed in Linux.

Step 4: Verification of installation of python in Windows

To check if Python 3.9.4 has been successfully installed in our system,

 Open Cmd prompt in your system

 Run “ Python -V”


Step 5: Run python

Kudos! python has been installed in your system, Now go to

1. Windows search

2. Type IDLE

3. Open it.

Run your First Python code

Happy Coding

Step 6: Verify Pip Was Installed


If you opted to install an older version of Python, it is possible
that it did not come with Pip preinstalled. Pip is a powerful
package management system for Python software packages.
Thus, make sure that you have it installed.

We recommend using Pip for most Python packages, especially when


working in virtual environments.

Pip has not been installed yet if you get the following output:
'pip' is not recognized as an internal or external command,
Operable program or batch file.

3. Install Python using Anaconda navigator

Anaconda Navigator is a desktop GUI interface that comes with


Anaconda Individual Edition. It makes it easy to launch applications
and manage packages and environments without using command-line
commands(CLI).

Step 1: Visit the official site for anaconda

Download: Anaconda
Step 2: Select Open Source Distribution

Step 3: Click on the download button


Step 4: Select your OS and Download a package

Step 5: After the installer gets downloaded, open it


Step 6: Start the installation in your system
Step 7: Kudos! ANACONDA has been successfully installed in
your system.
Happy Coding

Online Python Interpreters

For some or other reason if you are not setting up Python on your
machine, then there are several websites that offer an online Python
interpreter:

 Python.org Online Console

 Repl.it

 Trinket

 Python Anywhere
ARTIFICIAL INTELLIGENCE
PROGRAMMING

LESSON 4: LIST PROCESSING IN PYTHON


Booleans
• Booleans are implemented as a subclass of integers with only two possible values in Python: True or False. Note that these values must start
with a capital letter.
• You use Boolean values to express the truth value of an expression or object. Booleans are handy when you’re writing predicate functions or
when you’re using comparison operators, such as greater than (>), lower than (<), equal (==), and so on:
• >>>
• >>> 2 < 5
• True
• >>> 4 > 10
• False
• >>> 4 <= 3
• False
• >>> 3 >= 3
• True
• >>> 5 == 6
• False
• >>> 6 != 9
• True
• Python provides a built-in function, bool(), that is closely related to Boolean values. Here’s how it works:
• >>>
• >>> bool(0)
• False
• >>> bool(1)
• True

• >>> bool("")
• False
• >>> bool("a")
• True

• >>> bool([])
• False
• >>> bool([1, 2, 3])
• True
• bool() takes an object as an argument and returns True or False according to the object’s truth value. To
evaluate the truth value of an object, the function uses Python’s truth testing rules.
• On the other hand, int() takes a Boolean value and
returns 0 for False and 1 for True:
• >>>
• >>> int(False)
• 0
• >>> int(True)
• 1
• This is because Python implements its Boolean values as a subclass of int, as
you saw before.
Strings
• Strings are pieces of text or sequences of characters that you can define using
single, double, or triple quotes:
• >>>
• >>> # Use single quotes
• >>> greeting = 'Hello there!'
• >>> greeting
• 'Hello there!'

• >>> # Use double quotes
• >>> welcome = "Welcome to Real Python!"
• >>> welcome
• 'Welcome to Real Python!'

• >>> # Use triple quotes
• >>> message = """Thanks for joining us!"""
• >>> message
• 'Thanks for joining us!'

• >>> # Escape characters
• >>> escaped = 'can\'t'
• >>> escaped
• "can't"
• >>> not_escaped = "can't"
• >>> not_escaped
• "can't"
• Note that you can use different types of quotes to create string objects in
Python. You can also use the backslash character (\) to escape characters
with special meaning, such as the quotes themselves.
• Once you define your string objects, you can use the plus operator (+)
to concatenate them in a new string:
• >>>
• >>> "Happy" + " " + "pythoning!"
• 'Happy pythoning!'
• When used on strings, the plus operator (+) concatenates them into a single
string. Note that you need to include a blank space (" ") between words to
have proper spacing in your resulting string. If you need to concatenate a lot
of strings, then you should consider using .join(), which is more efficient.
• Python comes with many useful built-in functions and methods for string
manipulation. For example, if you pass a string as an argument to len(), then
you’ll get the string’s length, or the number of characters it contains:
• >>>
• >>> len("Happy pythoning!")
• 16
• When you call len() using a string as an argument, you get the number of
characters, including any blank spaces, in the input string.
• The string class (str) provides a rich set of methods that are useful for
manipulating and processing strings. For example, str.join() takes
an iterable of strings and joins them together in a new string. The string on
which you call the method plays the role of a separator:
• >>>
• >>> " ".join(["Happy", "pythoning!"])
• 'Happy pythoning!'
• str.upper() returns a copy of the underlying string with all the letters
converted to uppercase:
• >>>
• >>> "Happy pythoning!".upper()
• 'HAPPY PYTHONING!'
• str.lower() returns a copy of the underlying string with all the letters
converted to lowercase:
• >>>
• >>> "HAPPY PYTHONING!".lower()
• 'happy pythoning!'
• str.format() performs a string formatting operation. This method provides a
lot of flexibility for string formatting and interpolation:
• >>>
• >>> name = "John Doe"
• >>> age = 25
• >>> "My name is {0} and I'm {1} years old".format(name, age)
• "My name is John Doe and I'm 25 years old"
• You can also use an f-string to format your strings without using .format():
• >>>
• >>> name = "John Doe"
• >>> age = 25
• >>> f"My name is {name} and I'm {age} years old"
• "My name is John Doe and I'm 25 years old"
• Python’s f-strings are an improved string formatting syntax. They’re string
literals with an f at the beginning, outside the quotes. Expressions that
appear in embedded curly braces ({}) are replaced with their values in the
formatted string.
• Strings are sequences of characters. This means that you can retrieve individual
characters from a string using their positional index. An index is a zero-
based integer number associated with a specific position in a sequence:
• >>>
• >>> welcome = "Welcome to Real Python!"
• >>> welcome[0]
• 'W'
• >>> welcome[11]
• 'R'
• >>> welcome[-1]
• '!'
• An indexing operation retrieves the character at the position indicated by the given
index. Note that a negative index retrieves the element in reverse order, with -
1 being the index of the last character in the string.
• You can also retrieve a part of a string by slicing it:
• >>>
• >>> welcome = "Welcome to Real Python!"
• >>> welcome[0:7]
• 'Welcome'
• >>> welcome[11:22]
• 'Real Python'
• Slicing operations take the element in the form [start:end:step].
Here, start is the index of the first item to include in the slice, and end is the
index of the last item, which isn’t included in the returned slice.
Finally, step is an optional integer representing the number of items to jump
over while extracting the items from the original string. A step of 2, for
example, will return every other element between start and stop.
Lists
• Lists are usually called arrays in nearly every other programming language. In Python, lists
are mutable sequences that group various objects together. To create a list, you use an
assignment with a sequence of comma-separated objects in square brackets ([]) on its right
side:
• >>>
• >>> # Define an empty list
• >>> empty = []
• >>> empty
• []

• >>> # Define a list of numbers
• >>> numbers = [1, 2, 3, 100]
• >>> numbers
• [1, 2, 3, 100]
• Lists can contain objects of different data types, including other lists. They can also be empty. Since lists are
mutable sequences, you can modify them in place using index notation and an assignment operation.
• >>> # Modify the list in place
• >>> numbers[3] = 200
• >>> numbers
• [1, 2, 3, 200]

• >>> # Define a list of strings
• >>> superheroes = ["batman", "superman", "spiderman"]
• >>> superheroes
• ['batman', 'superman', 'spiderman']

• >>> # Define a list of objects with different data types
• >>> mixed_types = ["Hello World", [4, 5, 6], False]
• >>> mixed_types
• ['Hello World', [4, 5, 6], False]
• Since lists are sequences just like strings, you can access their individual items using zero-based
integer indices:
• >>>
• >>> numbers = [1, 2, 3, 200]
• >>> numbers[0]
• 1
• >>> numbers[1]
• 2

• >>> superheroes = ["batman", "superman", "spiderman"]
• >>> superheroes[-1]
• "spiderman"
• >>> superheroes[-2]
• "superman"
• Indexing operations also work with Python lists, so you can retrieve any item in a list by using its
positional index. Negative indices retrieve items in reverse order, starting from the last item.
• You can also create new lists from an existing list using a slicing operation:
• >>>
• >>> numbers = [1, 2, 3, 200]
• >>> new_list = numbers[0:3]
• >>> new_list
• [1, 2, 3]
• If you nest a list, a string, or any other sequence within another list, then you can access the
inner items using multiple indices:
• >>>
• >>> mixed_types = ["Hello World", [4, 5, 6], False]
• >>> mixed_types[1][2]
• 6
• >>> mixed_types[0][6]
• 'W'
• In this case, the first index gets the item from the container list, and the second index retrieves
an item from the inner sequence.
• You can also concatenate your lists using the plus operator:
• >>>
• >>> fruits = ["apples", "grapes", "oranges"]
• >>> veggies = ["corn", "kale", "mushrooms"]
• >>> grocery_list = fruits + veggies
• >>> grocery_list
• ['apples', 'grapes', 'oranges', 'corn', 'kale', 'mushrooms']
• Since lists are sequences of objects, you can use the same functions you use
on any other sequence, such as strings.
• Given a list as an argument, len() returns the list’s length, or the number of
objects it contains:
• >>>
• >>> numbers = [1, 2, 3, 200]
• >>> len(numbers)
• 4
• Below is a summary of some of the most commonly used methods.
• list.append() takes an object as an argument and adds it to the end of the
underlying list:
• >>>
• >>> fruits = ["apples", "grapes", "oranges"]
• >>> fruits.append("blueberries")
• >>> fruits
• ['apples', 'grapes', 'oranges', 'blueberries']
• list.sort() sorts the underlying list in place:
• >>>
• >>> fruits.sort()
• >>> fruits
• ['apples', 'blueberries', 'grapes', 'oranges']
• list.pop() takes an integer index as an argument, then removes and returns
the item at that index in the underlying list:
• >>>
• >>> numbers_list = [1, 2, 3, 200]
• >>> numbers_list.pop(2)
• 3
• >>> numbers_list
• [1, 2, 200]
• Lists are quite common and versatile data structures in Python. They’re so
popular that developers sometimes tend to overuse them, which can make
the code inefficient.
ARTIFICIAL INTELLIGENCE
PROGRAMMING

LESSON 5: LAB 2 PROGRAMMING DATA STRUCTURES


ARTIFICIAL INTELLIGENCE
PROGRAMMING

LESSON 6: CONTROL STATEMENTS & FUNCTIONS


Conditionals
• Sometimes you need to run (or not run) a given code block depending on whether
certain conditions are met. In this case, conditional statements are your ally.
These statements control the execution of a group of statements based on
the truth value of an expression. You can create a conditional statement in Python
with the if keyword and the following general syntax:
• if expr0:
• # Run if expr0 is true
• # Your code goes here...
• elif expr1:
• # Run if expr1 is true
• # Your code goes here...
• elif expr2:
• # Run if expr2 is true
• # Your code goes here...
• ...
• else:
• # Run if all expressions are false
• # Your code goes here...

• # Next statement
• The if statement runs only one code block. In other words, if expr0 is true,
then only its associated code block will run. After that, the execution jumps
to the statement directly below the if statement.
• The first elif clause evaluates expr1 only if expr0 is false. If expr0 is false
and expr1 is true, then only the code block associated with expr1 will run,
and so on.
• The else clause is optional and will run only if all the previously evaluated
conditions are false.
• You can have as many elif clauses as you need, including none at all, but you
can have only up to one else clause.
• Here are some examples of how this works:
• >>>
• >>> age = 21
• >>> if age >= 18:
• ... print("You're a legal adult")
• ...
• You're a legal adult

• >>> age = 16
• >>> if age >= 18:
• ... print("You're a legal adult")
• ... else:
• ... print("You're NOT an adult")
• ...
• You're NOT an adult
• >>> age = 18
• >>> if age > 18:
• ... print("You're over 18 years old")
• ... elif age == 18:
• ... print("You're exactly 18 years old")
• ...
• You're exactly 18 years old
• In the first example, age is equal to 21, so the condition is true, and Python
printsYou're a legal adult to your screen. In the second example, the expression age
>= 18 evaluates to False, so Python runs the code block of the else clause and
printsYou're NOT an adult on your screen.
• In the final example, the first expression, age > 18, is false, so the execution jumps
to the elif clause. The condition in this clause is true, so Python runs the associated
code block and printsYou're exactly 18 years old.
Loops

• If you need to repeat a piece of code several times to get a final result, then
you might need to use a loop.
• Loops are a common way of iterating multiple times and performing some
actions in each iteration. Python provides two types of loops:
• for loops for definite iteration, or performing a set number or repetitions
• while loops for indefinite iteration, or repeating until a given condition is met
• Here’s the general syntax to create a for loop:
• for loop_var in iterable:
• # Repeat this code block until iterable is exhausted
• # Do something with loop_var...
• if break_condition:
• break # Leave the loop
• if continue_condition:
• continue # Resume the loop without running the remaining code
• # Remaining code...
• else:
• # Run this code block if no break statement is run

• # Next statement
• This type of loop performs as many iterations as items in iterable. Normally, you use each
iteration to perform a given operation on the value of loop_var. The else clause is optional and
runs when the loop finishes. The break and continue statements are also optional.
• Check out the following example:
• >>>
• >>> for i in (1, 2, 3, 4, 5):
• ... print(i)
• ... else:
• ... print("The loop wasn't interrupted")
• ...
• 1
• 2
• 3
• 4
• 5
• The loop wasn't interrupted
• When the loop processes the last number in the tuple, the flow of execution
jumps into the else clause and prints The loop wasn't interrupted on your
screen.
• That’s because your loop wasn’t interrupted by a break statement. You
commonly use an else clause in loops that have a break statement in their
code block. Otherwise, there’s no need for it.
• If the loop hits a break_condition, then the break statement interrupts the loop
execution and jumps to the next statement below the loop without consuming the
rest of the items in iterable:
• >>>
• >>> number = 3
• >>> for i in (1, 2, 3, 4, 5):
• ... if i == number:
• ... print("Number found:", i)
• ... break
• ... else:
• ... print("Number not found")
• ...
• Number found: 3
• If the loop hits a continue_condition, then the continue statement resumes the
loop without running the rest of the statements in the loop’s code block:
• >>>
• >>> for i in (1, 2, 3, 4, 5):
• ... if i == 3:
• ... continue
• ... print(i)
• ...
• 1
• 2
• 4
• 5
• This time, the continue statement restarts the loop when i == 3. That’s why you
don’t see the number 3 in the output.
While
• You normally use a while loop when you don’t know beforehand how many iterations you need to complete a given
operation. That’s why this loop is used to perform indefinite iterations.
• Here’s the general syntax for a while loop in Python:
• while expression:
• # Repeat this code block until expression is false
• # Do something...
• if break_condition:
• break # Leave the loop
• if continue_condition:
• continue # Resume the loop without running the remaining code
• # Remaining code...
• else:
• # Run this code block if no break statement is run

• # Next statement
• This loop works similarly to a for loop, but it’ll keep iterating until expression is false. A common problem
with this type of loop comes when you provide an expression that never evaluates to False. In this case, the
loop will iterate forever.
• Here’s an example of how the while loop works:
• >>>
• >>> count = 1
• >>> while count < 5:
• ... print(count)
• ... count = count + 1
• ... else:
• ... print("The loop wasn't interrupted")
• ...
• 1
• 2
• 3
• 4
• The loop wasn't interrupted
Functions
• In Python, a function is a named code block that performs actions and
optionally computes the result, which is then returned to the calling code.
You can use the following syntax to define a function:
• def function_name(arg1, arg2, ..., argN):
• # Do something with arg1, arg2, ..., argN
• return return_value
• The def keyword starts the function header. Then you need the name of the
function and a list of arguments in parentheses. Note that the list of
arguments is optional, but the parentheses are syntactically required.
ARTIFICIAL INTELLIGENCE
PROGRAMMING

LESSON 7: LAB 3 CODING CONTROL STATEMENTS &


FUNCTIONS
ARTIFICIAL INTELLIGENCE
PROGRAMMING

LESSON 8: PRORAMMING ERRORS & TOOLS


How to Handle Errors in Python

• Errors are something that irritates and frustrates programmers at every


level of experience.
• Having the ability to identify and handle them is a core skill for
programmers.
• In Python, there are two types of code-based errors: syntax
errors and exceptions.
Syntax Errors
• Syntax errors occur when the syntax of your code isn’t valid in Python. They
automatically stop the execution of your programs. For example, the if statement
below is missing a colon at the end of the statement’s header, and Python quickly
points out the error:
• >>>
• >>> if x < 9
• File "<stdin>", line 1
• if x < 9
• ^
• SyntaxError: invalid syntax
• The missing colon at the end of the if statement is invalid Python syntax. The
Python parser catches the problem and raises a SyntaxError immediately. The
arrow (^) indicates where the parser found the problem.
Exceptions
• Exceptions are raised by syntactically correct code at runtime to signal a
problem during program execution. For example, consider the following
math expression:
• >>>
• >>> 12 / 0
• Traceback (most recent call last):
• File "<stdin>", line 1, in <module>
• ZeroDivisionError: integer division or modulo by zero
• The expression 12 / 0 is syntactically correct in the eyes of the Python parser.
However, it raises a ZeroDivisionError exception when the interpreter tries
to actually evaluate the expression.
• Note: In Python, you’ll commonly rely on exceptions to control the flow of a
program. Python developers favor this coding style, known as EAFP (Easier
to Ask for Forgiveness than Permission), over the coding style known
as LBYL (Look Before You Leap), which is based on using if statements.
• Python provides several convenient built-in exceptions that allow you
to catch and handle errors in your code.
Semantic Errors

• Semantic errors happen as a result of one or more problems in the logic of a


program. These errors can be difficult to find, debug, and fix because no
error message is generated. The code runs but generates unexpected
output, incorrect output, or no output at all.
• A classic example of a semantic error would be an infinite loop, which most
programmers experience at least once in their coding lifetime.
How to Get Help in Python
• Like a good friend, Python is always there to help if you get stuck. Perhaps you
want to know how a specific function, method, class, or object works. In this case,
you can just open an interactive session and call help(). That’ll take you directly to
Python’s help utility:
• >>>
• >>> help()

• Welcome to Python 3.9's help utility!

• If this is your first time using Python, you should definitely check out the tutorial on the
Internet at …
• ...
• Once there, you can type in the name of a Python object to get helpful information about
it:
• >>>
• >>> help()
• ...

• help> len

• Help on built-in function len in module builtins:

• len(obj, /)
• Return the number of items in a container.
• When you type the name len at the help> prompt and hit Enter, you get help content
related to that built-in function. To leave the content and get back to the help> prompt, you
can press Q. To leave the help utility, you can type quit and hit Enter.
• You can also use help() with the name of an object as an argument to get
information about that object:
• >>>
• >>> help(dir)

• Help on built-in function dir in module builtins:

• dir(...)
• dir([object]) -> list of strings
• ...
Tools for Coding in Python
• There are three main approaches to coding in Python. You already used one
of them, the Python interactive interpreter, also known as the read-
evaluate-print loop (REPL). Even though the REPL is quite useful for trying
out small pieces of code and experimenting, you can’t save your code for
later use.
• To save and reuse your code, you need to create a Python script or module.
Both of them are plain text files with a .py (or .pyw on Windows) extension.
To create scripts and modules, you can use a code editor or an integrated
development environment (IDE), which are the second and third
approaches to coding in Python.
REPLs (Read-Evaluate-Print Loops)

• Although you can create functions in an interactive session, you’ll typically


use the REPL for one-line expressions and statements or for
short compound statements to get quick feedback on your code. Fire up
your Python interpreter and type the following:
• >>>
• >>> 24 + 10
• 34
• The interpreter simply evaluates 24 + 10, adding the two numbers, and
outputs the sum, 34.
• Now try one more:
• >>>
• >>> import this
• Take a minute to read the output. It states some important principles in Python,
which will help you write better and more Pythonic code.
• So far, you’ve used the standard Python REPL, which ships with your current
Python distribution. However, this isn’t the only REPL out there. Third-party REPLs
provide many useful features, such as syntax highlighting, code completion, and so
on. Here are some popular options:
• IPython provides a rich toolkit to help you code in Python interactively.
• bpython is an interface to the Python interpreter for Linux, BSD, macOS, and Windows.
• Ptpython is a Python REPL that also works on Linux, BSD, macOS, and Windows.
Code Editors
• The second approach to coding in Python is to use a code editor. Some
people prefer an integrated development environment (IDE), but a code
editor is often better for learning purposes. Why? Because when you’re
learning something new, you want to peel off as many layers of complexity
as possible. Adding a complex IDE into the mix can make the task of
learning Python more difficult.
• A Python program, in its bare-bones form, consists of lines of text (code)
saved in a file with a .py or .pyw extension. You can write Python code in
something as basic as Notepad on Windows, but there’s no reason to put
yourself through such an ordeal since there are much better options
available.
• At its core, a code editor should provide several features to help
programmers create programs. In most cases, you can customize the code
editor to suit your needs and style. So, what should you look for in a code
editor? The answer to this question might depend on your personal needs,
but in general, you should look for at least the following features:
• Syntax highlighting
• Auto-indentation
• Auto-completion
• Tabbed interface
• Line numbering
• Customizable look and feel
• A curated set of plugins
• Here’s a non-exhaustive list of some modern code editors that you can use:
• Visual Studio Code is a full-featured code editor available for Linux, macOS, and
Windows platforms.
• Sublime Text 3 is a powerful and cross-platform code editor.
• Gedit is also cross-platform and comes installed in some Linux distributions that
use GNOME.
• Notepad++ is also a great editor, but it’s for Windows only.
• Vim is available for Mac, Linux, and Windows.
• GNU Emacs is free and available on every platform.
IDEs (Integrated Development Environments)

• An IDE is a program dedicated to software development. IDEs commonly


integrate several features, such as code editing, debugging, version control,
the ability to build and run your code, and so on. There are a lot of available
IDEs that support Python or that are Python-specific. Here are three popular
examples:
1. IDLE is Python’s Integrated Development and Learning Environment. You can use IDLE
interactively exactly as you use the Python interpreter. You can also use it for code reuse
since you can create and save your code with IDLE. If you’re interested in using IDLE, then
check out Getting Started With Python IDLE.
2. PyCharm is a full-featured, Python-specific IDE developed by JetBrains. If you’re
interested in using it, then check out PyCharm for Productive Python Development
(Guide). It’s available on all major platforms and comes in free Edu and Community
versions as well as a paid Professional version.
3. Thonny is a beginner-friendly IDE that will enable you to start working with Python
right away. If you’re thinking of using Thonny, then check out Thonny: The Beginner-
Friendly Python Editor.
The Standard Library
• One of the great things about Python is the plethora of available modules,
packages, and libraries both built into the Python core and made available
by third-party developers. These modules, packages, and libraries can be
quite helpful in your day-to-day work as a Python coder. Here are some of
the most commonly used built-in modules:
• math for mathematical operations
• random for generating pseudo-random numbers
• re for working with regular expressions
• os for using operating system–dependent functionalities
• itertools for working with iterators
• collections for specialized container data types
• For example, here you import math to use pi, find the square root of a number
with sqrt(), and raise a number to a power with pow():
• >>>
• >>> import math

• >>> math.pi
• 3.141592653589793

• >>> math.sqrt(121)
• 11.0

• >>> math.pow(7, 2)
• 49.0
• You can also import specific functions directly from math or any other
module:
• >>>
• >>> from math import sqrt
• >>> sqrt(121)
• 11.0
• This kind of import statement brings the name sqrt() into your
current namespace, so you can use it directly without the need to reference
the containing module.
The Python Package Index and pip
• The Python package index, also known as PyPI (pronounced “pie pea
eye”), is a massive repository of Python packages that includes frameworks,
tools, packages, and libraries. You can install any PyPI package using pip.
This is one of the recommended tools for managing third-party modules,
packages, and libraries in Python.
• For example, say you’re trying to run an application that uses pandas, but
you don’t have this library installed on your computer. In this case, you can
open your terminal and use pip like this:
• $ pip3 install pandas
ARTIFICIAL INTELLIGENCE
PROGRAMMING

LESSON 6: PYTHON DATA STRUCTURES


Tuples
• Tuples are similar to lists, but they’re immutable sequences. This means that you can’t
change them after creation. To create a tuple object, you can use an assignment operation
with a sequence of a comma-separated items on its right side. You commonly use
parentheses to delimit a tuple, but they’re not mandatory:
• >>>
• >>> employee = ("Jane", "Doe", 31, "Software Developer")

• >>> employee[0] = "John"
• Traceback (most recent call last):
• File "<input>", line 1, in <module>
• employee[0] = "John"
• TypeError: 'tuple' object does not support item assignment
• If you try to change a tuple in place, then you get a TypeError indicating that tuples don’t
support in-place modifications.
• Just like lists, you can also do indexing and slicing with tuples:
• >>>
• >>> employee = ("Jane", "Doe", 31, "Software Developer")
• >>> employee[0]
• 'Jane'
• >>> employee[1:3]
• ('Doe', 31)
• Since tuples are sequences, you can use indices to retrieve specific items in
the tuples. Note that you can also retrieve slices from a tuple with a slicing
operation.
• You can also add two tuples using the concatenation operator:
• >>>
• >>> first_tuple = (1, 2)
• >>> second_tuple = (3, 4)
• >>> third_tuple = first_tuple + second_tuple
• >>> third_tuple
• (1, 2, 3, 4)
• A concatenation operation with two tuples creates a new tuple containing
all the items in the two input tuples.
• Like with lists and strings, you can use some built-in functions to manipulate
tuples. For example, len() returns the length of the tuple, or the number of
items it contains:
• >>>
• >>> numbers = (1, 2, 3)
• >>> len(numbers)
• 3
• With a tuple as an argument, list() returns a list with all the items in the input
tuple:
• >>>
• >>> numbers = (1, 2, 3)
• >>> list(numbers)
• [1, 2, 3]
• Because tuples are immutable sequences, many of the methods that are available for lists
don’t work on tuples. However, tuples have two built-in methods:
• .count()
• .index()
• tuple.count() takes an object as an argument and returns the number of times the item
appears in the underlying tuple. If the object isn’t in the tuple, then .count() returns 0:
• >>>
• >>> letters = ("a", "b", "b", "c", "a")
• >>> letters.count("a")
• 2
• >>> letters.count("c")
• 1
• >>> letters.count("d")
• 0
• tuple.index() takes an object as an argument and returns the index of the
first instance of that object in the tuple at hand. If the object isn’t in the
tuple, then .index() raises a ValueError:
• >>>
• >>> letters = ("a", "b", "b", "c", "a")
• >>> letters.index("a")
• 0

• >>> letters.index("c")
• 3
• >>> letters.index("d")
• Traceback (most recent call last):
• File "<input>", line 1, in <module>
• letters.index("d")
• ValueError: tuple.index(x): x not in tuple
• Tuples are quite useful data structures. They’re memory efficient,
immutable, and have a lot of potential for managing data that shouldn’t be
modified by the user. They can also be used as dictionary keys.
Dictionaries
• Dictionaries are a type of associative array containing a collection of key-value
pairs in which each key is a hashable object that maps to an arbitrary object, the
value. There are several ways to create a dictionary. Here are two of them:
• >>>
• >>> person1 = {"name": "John Doe", "age": 25, "job": "Python Developer"}
• >>> person1
• {'name': 'John Doe', 'age': 25, 'job': 'Python Developer'}

• >>> person2 = dict(name="Jane Doe", age=24, job="Web Developer")
• >>> person2
• {'name': 'Jane Doe', 'age': 24, 'job': 'Web Developer'}
• The first approach uses a pair of curly brackets in which you add a comma-
separated list of key-value pairs, using a colon (:) to separate the keys from
the values.
• The second approach uses the built-in function dict(), which can
take keyword arguments and turn them into a dictionary, with the keywords
as the keys and the arguments as the values.
• Note: Since Python 3.6, dictionaries have been ordered data structures. But
before that, they were unordered.
• So, if you’re using a Python version lower than 3.6 and you need an ordered
dictionary, then consider using collections.OrderedDict().
• You can retrieve the value associated with a given key using the following
syntax:
• >>>
• >>> person1 = {"name": "John Doe", "age": 25, "job": "Python Developer"}
• >>> person1["name"]
• 'John Doe'
• >>> person1["age"]
• 25
• This is quite similar to an indexing operation, but this time you use a key
instead of an index.
• You can also retrieve the keys, values, and key-value pairs in a dictionary
using .keys(), .values(), and .items(), respectively:
• >>>
• >>> # Retrieve all the keys
• >>> person1.keys()
• dict_keys(['name', 'age', 'job'])

• >>> # Retrieve all the values
• >>> person1.values()
• dict_values(['John Doe', 25, 'Python Developer'])
• >>> # Retrieve all the key-value pairs
• >>> person1.items()
• dict_items([('name', 'John Doe'), ('age', 25), ('job', 'Python Developer')])
• These three methods are fundamental tools when it comes to manipulating
dictionaries in Python, especially when you’re iterating through a dictionary.
Sets
• Python also provides a set data structure. Sets are unordered and mutable collections of
arbitrary but hashable Python objects. You can create sets in several ways. Here are two of
them:
• >>>
• >>> employees1 = {"John", "Jane", "Linda"}
• {'John', 'Linda', 'Jane'}

• >>> employees2 = set(["David", "Mark", "Marie"])
• {'Mark', 'David', 'Marie'}

• >>> empty = set()
• >>> empty
• set()
• In the first example, you use curly brackets and a list of comma-separated
objects to create a set.
• If you use set(), then you need to provide the objects you want to include in
the set.
• Finally, if you want to create an empty set, then you need to
use set() without arguments.
• Using an empty pair of curly brackets creates an empty dictionary instead of
a set.
• One of the most common use cases of sets is to use them for removing
duplicate objects from an existing iterable:
• >>>
• >>> set([1, 2, 2, 3, 4, 5, 3])
• {1, 2, 3, 4, 5}
• Since sets are collections of unique objects, when you create a set
using set() and an iterable as an argument, the class constructor removes
any duplicate objects and keeps only one instance of each in the resulting
set.
• You can use some built-in functions with sets like you’ve done with other
built-in data structures. For example, if you pass a set as an argument
to len(), then you get the number of items in the set:
• >>>
• >>> employees1 = {"John", "Jane", "Linda"}

• >>> len(employees1)
• 3
• You can also use operators to manage sets in Python. In this case, most operators represent typical set
operations like union (|), intersection (&), difference (-), and so on:
• >>>
• >>> primes = {2, 3, 5, 7}
• >>> evens = {2, 4, 6, 8}

• >>> # Union
• >>> primes | evens
• {2, 3, 4, 5, 6, 7, 8}

• >>> # Intersection
• >>> primes & evens
• {2}

• >>> # Difference
• >>> primes - evens
• {3, 5, 7}
• Sets provide a bunch of methods, including methods that perform set
operations like those in the above example.
• They also provide methods to modify or update the underlying set.
• For example, set.add() takes an object and adds it to the set:
• >>>
• >>> primes = {2, 3, 5, 7}

• >>> primes.add(11)
• >>> primes
• {2, 3, 5, 7, 11}
• set.remove() takes an object and removes it from the set:
• >>>
• >>> primes = {2, 3, 5, 7, 11}

• >>> primes.remove(11)
• >>> primes
• {2, 3, 5, 7}
• Python sets are quite useful data structures that are an important addition
to the Python developer’s tool kit.
Lesson 10: Implementing Search in Python
1. Breadth First Search in Python (with Code) | BFS Algorithm

Breadth-first search and Depth-first search in python are algorithms used to traverse a
graph or a tree. They are two of the most important topics that any new python
programmer should definitely learn about. Here we will study what breadth-first search
in python is, understand how it works with its algorithm, implementation with python
code, and the corresponding output to it. Also, we will find out the application and uses
of breadth-first search in the real world.

What is Breadth-First Search?


As discussed earlier, Breadth-First Search (BFS) is an algorithm used for traversing
graphs or trees. Traversing means visiting each node of the graph. Breadth-First Search
is a recursive algorithm to search all the vertices of a graph or a tree. BFS in python can
be implemented by using data structures like a dictionary and lists. Breadth-First Search
in tree and graph is almost the same. The only difference is that the graph may contain
cycles, so we may traverse to the same node again.

BFS Algorithm
Before learning the python code for Breadth-First and its output, let us go through the
algorithm it follows for the same. We can take the example of Rubik’s Cube for the
instance. Rubik’s Cube is seen as searching for a path to convert it from a full mess of
colors to a single color. So comparing the Rubik’s Cube to the graph, we can say that
the possible state of the cube is corresponding to the nodes of the graph and the
possible actions of the cube is corresponding to the edges of the graph.

As breadth-first search is the process of traversing each node of the graph, a standard
BFS algorithm traverses each vertex of the graph into two parts: 1) Visited 2) Not
Visited. So, the purpose of the algorithm is to visit all the vertex while avoiding cycles.

BFS starts from a node, then it checks all the nodes at distance one from the beginning
node, then it checks all the nodes at distance two, and so on. So as to recollect the
nodes to be visited, BFS uses a queue.

The steps of the algorithm work as follow:

1. Start by putting any one of the graph’s vertices at the back of the queue.
2. Now take the front item of the queue and add it to the visited list.
3. Create a list of that vertex's adjacent nodes. Add those which are not within the
visited list to the rear of the queue.
4. Keep continuing steps two and three till the queue is empty.

Many times, a graph may contain two different disconnected parts and therefore to
make sure that we have visited every vertex, we can also run the BFS algorithm at
every node.

BFS pseudocode
The pseudocode for BFS in python goes as below:

create a queue Q

mark v as visited and put v into Q

while Q is non-empty

remove the head u of Q

mark and enqueue all (unvisited) neighbors of u

BFS implementation in Python (Source Code)


Consider the following graph which is implemented in the code below:
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}

visited = [] # List for visited nodes.


queue = [] #Initialize a queue

def bfs(visited, graph, node): #function for BFS


visited.append(node)
queue.append(node)

while queue: # Creating loop to visit each node


m = queue.pop(0)
print (m, end = " ")

for neighbour in graph[m]:


if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)

# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling

In the above code, first, we will create the graph for which we will use the breadth-first
search. After creation, we will create two lists, one to store the visited node of the graph
and another one for storing the nodes in the queue.

After the above process, we will declare a function with the parameters as visited
nodes, the graph itself and the node respectively. And inside a function, we will keep
appending the visited and queue lists.

Then we will run the while loop for the queue for visiting the nodes and then will remove
the same node and print it as it is visited.

At last, we will run the for loop to check the not visited nodes and then append the same
from the visited and queue list.

As the driver code, we will call the user to define the bfs function with the first node we
wish to visit.

Output
The output of the above code will be as follow:

Following is the Breadth-First Search


537248

Example
Let us see how this algorithm works with an example. Here, we will use an undirected
graph with 5 vertices.
We begin from the vertex P, the BFS algorithmic program starts by putting it within the
Visited list and puts all its adjacent vertices within the stack.
Next, we have a tendency to visit the part at the front of the queue i.e. Q and visit its
adjacent nodes. Since P has already been visited, we have a tendency to visit R
instead.
Vertex R has an unvisited adjacent vertex in T, thus we have a tendency to add that to
the rear of the queue and visit S, which is at the front of the queue.
Now, only T remains within the queue since the only adjacent node of S i.e. P is already
visited. We have a tendency to visit it.
Since the queue is empty, we've completed the Traversal of the graph.

Time Complexity
The time complexity of the Breadth first Search algorithm is in the form of O(V+E),
where V is the representation of the number of nodes and E is the number of edges.

Also, the space complexity of the BFS algorithm is O(V).

Applications
Breadth-first Search Algorithm has a wide range of applications in the real-world. Some
of them are as discussed below:

1. In GPS navigation, it helps in finding the shortest path available from one point
to another.
2. In pathfinding algorithms
3. Cycle detection in an undirected graph
4. In minimum spanning tree
5. To build index by search index
6. In Ford-Fulkerson algorithm to find maximum flow in a network.

2. Depth First Search in Python (with Code) | DFS Algorithm

Traversal means that visiting all the nodes of a graph which can be done through
Depth-first search or Breadth-first search in python. Depth-first traversal or Depth-first
Search is an algorithm to look at all the vertices of a graph or tree data structure. Here
we will study what depth-first search in python is, understand how it works with its bfs
algorithm, implementation with python code, and the corresponding output to it.

What is Depth First Search?


What do we do once have to solve a maze? We tend to take a route, keep going until
we discover a dead end. When touching the dead end, we again come back and keep
coming back till we see a path we didn't attempt before. Take that new route. Once
more keep going until we discover a dead end. Take a come back again… This is
exactly how Depth-First Search works.

The Depth-First Search is a recursive algorithm that uses the concept of backtracking. It
involves thorough searches of all the nodes by going ahead if potential, else by
backtracking. Here, the word backtrack means once you are moving forward and there
are not any more nodes along the present path, you progress backward on an
equivalent path to seek out nodes to traverse. All the nodes are progressing to be
visited on the current path until all the unvisited nodes are traversed after which
subsequent paths are going to be selected.

DFS Algorithm
Before learning the python code for Depth-First and its output, let us go through the
algorithm it follows for the same. The recursive method of the Depth-First Search
algorithm is implemented using stack. A standard Depth-First Search implementation
puts every vertex of the graph into one in all 2 categories: 1) Visited 2) Not Visited. The
only purpose of this algorithm is to visit all the vertex of the graph avoiding cycles.

The DSF algorithm follows as:

1. We will start by putting any one of the graph's vertex on top of the stack.
2. After that take the top item of the stack and add it to the visited list of the vertex.
3. Next, create a list of that adjacent node of the vertex. Add the ones which aren't
in the visited list of vertexes to the top of the stack.
4. Lastly, keep repeating steps 2 and 3 until the stack is empty.

DFS pseudocode
The pseudocode for Depth-First Search in python goes as below: In the init() function,
notice that we run the DFS function on every node because many times, a graph may
contain two different disconnected part and therefore to make sure that we have visited
every vertex, we can also run the DFS algorithm at every node.

DFS(G, u)

u.visited = true

for each v ∈ G.Adj[u]

if v.visited == false

DFS(G,v)

init() {

For each u ∈ G

u.visited = false

For each u ∈ G

DFS(G, u)

}
DFS Implementation in Python (Source Code)
Consider the following graph which is implemented in the code below:

# Using a Python dictionary to act as an adjacency list


graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}

visited = set() # Set to keep track of visited nodes of graph.

def dfs(visited, graph, node): #function for dfs


if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)

# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, '5')

In the above code, first, we will create the graph for which we will use the depth-first
search. After creation, we will create a set for storing the value of the visited nodes to
keep track of the visited nodes of the graph.

After the above process, we will declare a function with the parameters as visited
nodes, the graph itself and the node respectively. And inside the function, we will check
whether any node of the graph is visited or not using the “if” condition. If not, then we
will print the node and add it to the visited set of nodes.

Then we will go to the neighboring node of the graph and again call the DFS function to
use the neighbor parameter.

At last, we will run the driver code which prints the final result of DFS by calling the DFS
the first time with the starting vertex of the graph.

Output
The output of the above code is as follow:

Following is the Depth-First Search


532487

Example
Let us see how the DFS algorithm works with an example. Here, we will use an
undirected graph with 5 vertices.
We begin from the vertex P, the DFS rule starts by putting it within the Visited list
and putting all its adjacent vertices within the stack.
Next, we tend to visit the part at the highest of the stack i.e. Q, and head to its adjacent
nodes. Since P has already been visited, we tend to visit R instead.
Vertex R has the unvisited adjacent vertex in T, therefore we will be adding that to the
highest of the stack and visit it.
At last, we will visit the last component S, it does not have any unvisited adjacent
nodes, thus we've completed the Depth First Traversal of the graph.

Time Complexity
The time complexity of the Depth-First Search algorithm is represented within the sort
of O(V + E), where V is that the number of nodes and E is that the number of edges.

The space complexity of the algorithm is O(V).

Applications
Depth-First Search Algorithm has a wide range of applications for practical purposes.
Some of them are as discussed below:

1. For finding the strongly connected components of the graph


2. For finding the path
3. To test if the graph is bipartite
4. For detecting cycles in a graph
5. Topological Sorting
6. Solving the puzzle with only one solution.
7. Network Analysis
8. Mapping Routes
9. Scheduling a problem
Lesson 11: Logic Programming in Python

Logic Programming uses facts and rules for solving the problem. That is why they are
called the building blocks of Logic Programming. A goal needs to be specified for every
program in logic programming. To understand how a problem can be solved in logic
programming, we need to know about the building blocks − Facts and Rules −
Facts
Actually, every logic program needs facts to work with so that it can achieve the given
goal. Facts basically are true statements about the program and data. For example, Delhi
is the capital of India.
Rules
Actually, rules are the constraints which allow us to make conclusions about the problem
domain. Rules basically written as logical clauses to express various facts. For example,
if we are building any game then all the rules must be defined.
Rules are very important to solve any problem in Logic Programming. Rules are basically
logical conclusion which can express the facts. Following is the syntax of rule −
A∶− B1,B2,...,Bn.
Here, A is the head and B1, B2, ... Bn is the body.
For example − ancestor(X,Y) :- father(X,Y).
ancestor(X,Z) :- father(X,Y), ancestor(Y,Z).
This can be read as, for every X and Y, if X is the father of Y and Y is an ancestor of Z, X
is the ancestor of Z. For every X and Y, X is the ancestor of Z, if X is the father of Y and
Y is an ancestor of Z.

Installing Useful Packages


For starting logic programming in Python, we need to install the following two packages

Kanren
It provides us a way to simplify the way we made code for business logic. It lets us express
the logic in terms of rules and facts. The following command will help you install kanren

pip install kanren
SymPy
SymPy is a Python library for symbolic mathematics. It aims to become a full-featured
computer algebra system (CAS) while keeping the code as simple as possible in order to
be comprehensible and easily extensible. The following command will help you install
SymPy −
pip install sympy

1. Count the number of digits in a Number in


Python
Write a program to count the number of digits of a given number.
Sample Input 1:
345
Sample Output 1:
3
Sample Input 2:
56
Sample Output 2:
2

Program or Solution
n = int(input())
count = 0
while n > 0:
n = n // 10
count = count + 1
print(count)

Program Explanation
if we divide a number by 10, then last digit of the same number will removed and we get
remaining digits as output. Do the same till number becomes 0 and count iteration. So the
count is number of digits of the given number .

2. Count the Number of Occurrences of digit in a


number using Python
Get a number and a digit and find occurrences of digit in the number.
Sample Input 1:
Enter the number: 2434
Enter the Digit : 4
Sample Output 1:
4 is occurred 2 times in 234
Sample Input 2:
Enter the number: 974
Enter the Digit : 3
Sample Output 2:
3 is occurred 0 times in 974

Program or Solution

num = int(input("Enter the number"))


digit = int(input("Enter a Digit"))
count = 0
n = num
while n != 0:
rem = n % 10
if rem == digit:
count+=1
n = n // 10
print("{} occured {} times in {}".format(digit,count,num))
Program Explanation
initialize count is equal to 0
calculate the remainder of a number by doing number % 10
check remainder is equal to digit, if it is equal increment the count by 1 , else divide number
by the 10 and repeat the above steps till number becomes zero.
print the count.

3. Sum of Digits of the number using Python


Get a number and sum the digits of the number.
Sample Input 1:
Enter the number: 234
Sample Output 1:
9

Program or Solution

num = int(input("enter a number"))


n = num
total = 0
while n != 0:
rem = n % 10
total = total + rem
n = n // 10
print(total)

Program Explanation
initialize total is equal to 0
calculate the remainder of a number by doing number % 10, add the remainder to total and
divide the number by the 10 and repeat the above steps till number becomes zero.
Print the total, you will get the sum of digits of the number

4. Reverse the digits of a number using Python


Get a number and reverse the digits of the number.
Sample Input 1:
Enter the number: 234
Sample Output 1:
432 is reverse of 234

Flow Chart Design


Program or Solution

num = int(input("enter a number"))


n = num
reverse = 0
while n != 0:
rem = n % 10
reverse = reverse * 10 + rem
n = n // 10
print("{} is reverse of {}".format(reverse,num))

Output

Program Explanation
initialize total is equal to 0
calculate the remainder of a number by doing number % 10, add the remainder to (total *
10) and divide the number by the 10 and repeat the above steps till number becomes zero.
Print the total, you will get the sum of digits of the number.

5. Simple Guessing Game in Python


"Simple Guessing Game"
Create a simple guessing game in which the user must guess the secret number in one
attempt. If the user correctly guessed the secret number, the system should display "your
guess is correct," otherwise it should display the message "your guess is wrong" and the
guessed number.
Hint : Basic if-else condition is enough for this.
Objective : To learn the usage of if-else conditional statement.

Program or Solution

#hashed lines are comment lines used to illustrate the program


#import the built in method randint to generate an automatic secret number

from random import randint

#Generate automatic Secret Number

secret_number = randint(1,5)

#Get a guessing number from user

guess_number = int(input("Guess the secret number between 1 and 5:"))

#check guessing number is correct or not

if secret_number == guess_number:

print("Your Guess is Correct")

else:

print("Your Guess is Wrong, the secret number is {}".format(secret_number))

Program Explanation
Line 3: Imports the randint function from the package random
Line 5: using randint system generates a secret number
Line 7 : getting a guess from user
line 9 : check whether secret number generated by system and guessing number entered by
user are same
line 10 : if same, display "your guess is correct"
line 12 : if not same, display "your guess is wrong"

6. Multi Stage Guessing Game with Scoring Board


"Multi Stage Guessing Game and Points of every stage"
Create a three stage guessing game with point scoring in each stage the user must guess
the secret number in five attempts. Range of Secret number should be increased at stage
like 1 to 10 in stage in 1, 1 to 20 in stage 2 and 1 to 30 in stage 3. If the user correctly
guessed the secret number, the system should display "your guess is correct" and moves
to next stage; otherwise, it should tell the user whether the guessed number is higher or
lower than the secret number and proceed to the next attempt. If the user fails to guess
correctly after five attempts, the game should end with the message "Game Over, You
Lose the Game." If user successfully guessed in all the three stages, display "You won the
Game with scored points", then points scored at each level and stops the game.

At each stage the points will be awarded to user based on following condition

Solved in points
first attempt 100
second attempt 75
third attempt 50
fourth attempt 25
fifth attempt 10

Hint : Sequence Type (list) is needed for this.


Objective : To learn the declaration and usage of list.

Program or Solution

#hashed lines are comment lines used to illustrate the program

#import the built in method randint to generate an automatic secret number

from random import randint

# initiate level or stage as 1

level = 1

#sequence type to store points

points = [100,75,50,25,10]

#sequence type to store points scored at each level

points_scored = list()

#loop for 3 stages


while level <= 3:

#complexity range for each stage

end_value = level * 10

#secret number generation

secret_number = randint(1,end_value)

#looping statement for 5 attempts at each stage

for counter in range(0,5):

#gets the guessing number as user input

guess_number = int(input("Guess the secret number between 1 and {} ({} attemp


ts left):".format(end_value,5-counter)))

#check guessing number is correct or higher or lower

if secret_number == guess_number:

print("Your Guess is Correct, You Won the level {} with {} points".format


(level,points[counter]))

#add the point scored in this stage into the list

points_scored.append(points[counter])

level = level + 1

break

elif guess_number < secret_number:

print("Your Guess is lower than secret number")

else:

print("Your Guess is higher than secret number")

else:

print("Game Over, You Loose the Game, secret number is {}".format(secret_numb


er))

break

else:

print("Congratz, You Won the Game with {} !!!".format(sum(points_scored)))

#loop to display scored points in every stage

for i in range(0,3):
print("level {} points {}".format(i+1, points_scored[i])) '''

Program Explanation
Logic is same as level 4, in addition,
points are stored using list
points_scored variable is a list which stores the points scored by user at each stage
the final for loop shows the points scored by user at each stage.

7. Python Program for Prime numbers between two


numbers
Get two inputs x and y and print all the prime numbers between x and y.
Sample Input 1 :
10 40
Sample Output 1 :
11 13 17 19 23 29 31 37

Program or Solution

#Python Program to print prime numbers between x and y


x = int(input("Enter a Number X:")) #get input x
y = int(input("Enter a Number Y:")) #get input y
#start your travel from x to y
for n in range(x,y+1):
#check which are the numbers from 2 to n/2 divides n.
#No other after n/2 divides n except n
for i in range(2,n//2+1):
if n % i == 0: #if divisible then it is not prime.
break
else: #this is else of for statement. executes after last iteration if loop is n
ot broken at any iteration.
print("{} ".format(n))

Program Explanation
Prime numbers are numbers those only divisible by 1 and same. using a outer for loop we
check take every number n from x to y
Inner for loop checks each number is prime or not, if prime it prints the n.

8. Python Billing System


Read this Carefully.
Write a Python Program to calculate sale bill for the selling items in a Fruit Shop.
Consider the following dictionary as a item database.
items = {
101:{'item_name':'Apple','Quantity_in_kgs':50,'Price_per_kg':200},

102:{'item_name':'Banana','Quantity_in_kgs':30,'Price_per_kg':80},
103:{'item_name':'Grapes','Quantity_in_kgs':25,'Price_per_kg':300},

104:{'item_name':'Lemon','Quantity_in_kgs':20,'Price_per_kg':70}
}

Initially the transaction dictionary is Null.


trans = {}
Code the following tasks to implement Billing System for a Fruit Shop.

1. Add Fruits to the System


a. Check whether the fruit is exists in database
b. if exists, Get id & Quantity and add the quantity to existing quantity
c. if not exists, Get id, name,quantity & price and add to dictionary

2. Calculate Bill During Sale.


a. Get id & quantity and calculate bill for one or more items
b. Calculate amount for each item
c. Reduce the sold quantity of corresponding item in items database.
d. Add item to transaction as below
trans = {201:{101:[2,400],104:[.5,35]}}
Here in Transaction 201: 2 kg apples for $400 and half kg lemon for
$35 were sold.
e. Display items, quantity, amount and total on each item entry

3. Check Stock
a. Display the items and available quantity
b. Highlight the items which are available less than 5 kgs.

Program or Solution

items = {
101:{'item_name':'Apple','Quantity_in_kgs':50,'Price_per_kg':200},
102:{'item_name':'Banana','Quantity_in_kgs':30,'Price_per_kg':80},
103:{'item_name':'Grapes','Quantity_in_kgs':25,'Price_per_kg':300},
104:{'item_name':'Lemon','Quantity_in_kgs':20,'Price_per_kg':70}
}

trans = {}
#Stock Printing
def stock_check():
print("Item Name | Available Stock")
for item_id in items:

if items[item_id]['Quantity_in_kgs'] <= 5:

print("----------------------------------------")
print("| ",items[item_id]['item_name'], " | ",items[item_id]['Quantity_in
_kgs']," |")
print("----------------------------------------")
else:
print("| ",items[item_id]['item_name'], " | ",items[item_id]['Quantity_in
_kgs']," |")
#Add New Item to Database
def add_new_item():
item_ids = list(items.keys())
item_id = max(item_ids) + 1
item_name = input("Enter Item Name:")
price = int(input("Enter Price Per Kilo Gram:"))
quantiy = int(input("Enter Quantity"))
item = {'item_name':item_name,'Quantity_in_kgs':quantiy,'Price_per_kg':price}
items[item_id]= item
print('Item Added')
print('Item id | Item Name | Quantity | Price ')
print(item_id, " | ", item_name, " | ", quantiy, " | ", price)
#Update the Quantity of Existing Item
def update_item(item_id):
quantiy = int(input("Enter Quantity"))
items[item_id]['Quantity_in_kgs'] = items[item_id]['Quantity_in_kgs'] + quantiy
print('Item Updated')
print('Item id | Item Name | Quantity | Price ')
print(item_id, " | ", items[item_id]['item_name'], " | ", items[item_id]['Quantit
y_in_kgs'], " | ", items[item_id]['Price_per_kg'] )
#Stock Entry
def add_item():
item_name = input("Enter the Item Name")
print("item id | item name")
print("-----------------")
for item in items:
if item_name in items[item]['item_name']:
print(item, " | ", items[item]['item_name'])

item_id = int(input("Enter item id (if existing)/Enter 0 (if New)"))


if item_id == 0:
add_new_item()
else:
#Check for Valid Item ID
while not item_id in items:
print("Not Valid Item id")
item_id = int(input("Enter item id:"))
update_item(item_id)
#Billing
def sale(trans_id):
total = 0
transaction_items = {}
while True:
item_id = int(input("Enter item id (0 if no item):"))
if item_id == 0:
break
else:
while not item_id in items:
print("Not Valid Item id")
item_id = int(input("Enter item id:"))
quantity = int(input("Enter Quantity:"))
amount = items[item_id]['Price_per_kg'] * quantity
items[item_id]['Quantity_in_kgs'] = items[item_id]['Quantity_in_kgs'] - q
uantity
total += amount
transaction_items[item_id] = [quantity,amount]
print('Item id | Item Name | Quantity | Price | Amount')
for item in transaction_items:
print(item, "| ", items[item]['item_name'], " | ",transaction_items[i
tem][0], " | ", items[item]['Price_per_kg'], " | ", transaction_items[item][1])
print("---------------------------------------------------")
print("Total:\t\t\t ", total)
trans[trans_id] = transaction_items
#Main Function
while True:
print("Billing System\n Enter Your Choice \n 1. Add Items \n 2. Sales \n 3. Check
Stock \n 4. Exit ")
choice = int(input("Your Choice:"))
if choice == 1:
add_item()
elif choice == 2:

trans_ids = list(trans.keys())
if len(trans_ids) == 0:
trans_id = 201
else:
trans_id = max(trans_ids) + 1
sale(trans_id)
elif choice == 3:
stock_check()
elif choice == 4:
break
else:
print("Invalid Choice")
Program Explanation
add_item() method checks whether the item is existing item or new item to the fruit shop.
if item is new then it calls add_new_item() method else it call update_item() method.
sale() method gets detail of each item and fetch price from dictionary to calculate amount.
amount will be added to the total. Sale() method finally decrease the sold quantity in item
dictionary.
stock_check() method prints all items and its available quantity.

You might also like