You are on page 1of 48

Sieve of Eratosthenes

• The sieve of Eratosthenes is one of the most efficient


ways to find all primes smaller than n when n is smaller
than 10 million or so
• Following is the algorithm to find all the prime numbers
less than or equal to a given integer n by the
Eratosthene’s method:
When the algorithm terminates, all the numbers in the
list that are not marked are prime.
To find all the prime numbers less than or equal to a given integer n by Eratosthenes'
method:
1.Create a list of consecutive integers from 2 through n: (2, 3, 4, ..., n).
2.Initially, let p equal 2, the smallest prime number.
3.Enumerate the multiples of p by counting in increments of p from 2p to n, and
mark them in the list (these will be 2p, 3p, 4p, ...; the p itself should not be
marked).
4.Find the smallest number in the list greater than p that is not marked. If there
was no such number, stop. Otherwise, let p now equal this new number (which is
the next prime), and repeat from step 3.
5.When the algorithm terminates, the numbers remaining not marked in the list
are all the primes below n.
Pseudocode

algorithm Sieve of Eratosthenes is


input: an integer n > 1.
output: all prime numbers from 2 through n.
let A be an array of Boolean values, indexed by integers 2 to n,
initially all set to true.
for i = 2, 3, 4, ..., not exceeding √n do
if A[i] is true
for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n do
set A[j] := false
return all i such that A[i] is true.
# Python program for the above approach
Primes = [0] * 500001
def SieveOfEratosthenes(n) :
Primes[0] = 1
i=3
while(i*i <= n) :
if (Primes[i // 2] == 0) :
for j in range(3 * i, n+1, 2 * i) :
Primes[j // 2] = 1

i += 2

# Driver Code
if __name__ == "__main__":

n = 100
SieveOfEratosthenes(n)
for i in range(1, n+1) :
if (i == 2) :
print( i, end = " ")
elif (i % 2 == 1 and Primes[i // 2] == 0) :
print( i, end = " ")
Example
What are all prime numbers less than 20. (Use the Sieve of
Eratosthenes method).
Solution: Let us first write the numbers from 2 to 20.
2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20

•Start from 2
•In the next step, encircle 2 and cross the multiples of 2 (4, 6, 8, 10, 12, 14, 16, 18, 20)
•Encircle 3 and cross the left multiples of 3 (9, 15)
•Encircle 5 and cross the left multiples of 5 (only 10 is left)
•Now, encircle the rest of the numbers 7, 11, 13, 17 and 19.
Therefore, the required prime numbers between 1 to 20 are 2, 3, 5, 7, 11,
13, 17 and 19.
Fill all prime numbers less than or equal to 30.

Solution
•Step 1: The first step is to list all the numbers.
2, 3, 4, 5, 6 ,7 ,8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
29, and 30.
•Step 2: Write in bold all multiples of 2, except 2 itself.
2, 3, 4, 5, 6 , 7 , 8, 9, 10,11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
29, and 30.
•Step 3: The next unshaded number is 3. Write its square (32 = 9) in bold.
2, 3, 4, 5, 6 , 7 , 8, 9, 10,11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
29, and 30.
•Step 4: Now the third unshaded number is 5. Write its square 52=25 in bold.
2, 3, 4, 5, 6 , 7 , 8, 9, 10,11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
29, and 30.
•Step 5: The fourth unshaded number is 7 and more than the square root of 30.
Therefore, there are no multiples of 7 left since they have been eliminated by 2 and 3 as 14,
28, and 21 respectively. The remaining numbers 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29 are
prime.
File Handling
• Python has several functions for creating, reading, updating, and deleting files.
• The key function for working with files in Python is the open() function.
• The open() function takes two parameters; filename, and mode.

Syntax

f= open("demofile.txt")

Note: To open a file for reading it is enough to specify the name of the file:
File Handling
There are four different methods (modes) for opening a file:
• "r" -Read-Default value: Opens a file for reading, error if the file does not exist
• "a" –Append: Opens a file for appending, creates the file if it does not exist
• "w" – Write: Opens a file for writing, creates the file if it does not exist
• "x" –Create: Creates the specified file, returns an error if the file exist

In addition you can specify if the file should be handled as binary or text mode

• "t" -Text-Default value: Text mode


• "b" -Binary-Binary mode (e.g. images)

Open a File on the Serve Exmaple:


• Assume we have the following file, located in the same folder
as Python f= open("demo.txt", "r")
• To open the file, use the built-in open() function. print(f.read())
• The open() function returns a file object, which has a read()
method for reading the content of the file: OUTPUT:
Hi pyhon
File Handling
Read Only Parts of the File

By default the read() method returns the whole text, but you can also specify how
many characters you want to return:

Example:
f= open("demo.txt", "r")
print(f.read(6))
OUTPUT:
python

Read Line:
You can return one line by using the readline() method.

Example:
f= open("demofile.txt", "r")
print(f.readline())
File Handling
Close Files: Write to an Existing File¶
It is a good practice to always close the file To write to an existing file, you must add a
when you are done with it parameter to the open() function:
• "a" -Append-will append to the end of the
Example: file
• "w" -Write-will over write any existing
f= open("demofile.txt", "r") content
print(f.readline())
f.close()
Example:
f= open("demofile1.txt", "a")
f.write("Now the file has more content!")
f.close()
f= open("demofile1.txt", "r")
print(f.read())
Delete a File
To delete a file, you must import the OS
Check if File exist:
module, and run its os.remove() function
• To avoid getting an error, you might
want to check if the file exists before
Example: you try to delete it:
import os • Example
os.remove("demofile2.txt") • Check if file exists, then delete it:

Delete Folder
Example:
To delete an entire folder, use the
os.rmdir() method:
import os
if os.path.exists("demofile2.txt"):
#Example os.remove("demofile2.txt")
#Remove the folder"myfolder": else:
import os print("The file does not exist")
os.rmdir(“myfolder")
Exception Handling
• When an error occurs, or exception as we call it, Python will normally stop
and generate an error message.
• An exception is an unexpected event that occurs during program execution.
For example.
• divide_by_zero = 7 / 0
• The above code causes an exception as it is
not possible to divide a number by 0

• Errors that occur at runtime (after passing the syntax test) are called exceptions
or logical errors.
For instance, they occur when we
•try to open a file(for reading) that does not exist (FileNotFoundError)
•try to divide a number by zero (ZeroDivisionError)
•try to import a module that does not exist (ImportError) and so on.
Important Terms
• try
• except
• else
• finally
Python try...except Block

The try...except block is used to handle exceptions in Python.


Here's the syntax of try...except block:

try: Example:
# code that may cause exception try:
except: numerator = 10
# code to run when exception occurs denominator = 0

result = numerator/denominator

print(result)
except:
print("Error: Denominator cannot be 0.")
Error: Denominator cannot be 0.
Catching Specific Exceptions in Python
• For each try block, there can be zero or more except blocks.
Multiple except blocks allow us to handle each exception
differently.
• The argument type of each except block indicates the type of
exception that can be handled by it. For example,
try:
even_numbers = [2,4,6,8]
print(even_numbers[5])

except ZeroDivisionError:
print("Denominator cannot be 0.")

except IndexError:
print("Index Out of Bound.")
Python try with else

Example:
# program to print the reciprocal of even
numbers

try:
num = int(input("Enter a number: "))
assert num % 2 == 0
except:
print("Not an even number!")
else:
reciprocal = 1/num
print(reciprocal)

OUTPUT:
Enter a number: 3 Not an even number!
Python try...finally
• In Python, the finally block is always executed no matter whether there is an
exception or not.
• The finally block is optional. And, for each try block, there can be only one finally
block.
Let's see an example,

Example:
try:
numerator = 10
denominator = 0

result = numerator/denominator

print(result)
except:
print("Error: Denominator cannot be 0.")

finally:
print("This is finally block.")
What is a Module

• Module in Python is a file that contains Python code


• When you import a module using the import statement, Python
creates a new module object.

For example:
import math
• Imports the math built-in module
• A module is a file with the extension .py and contains executable
Python or C code
• A file containing a set of functions you want to include in your
application.
• It is the smallest piece of software. It is set of methods/functions
ready to be used somewhere else.
Types of Modules in Python
Built-in Modules in Python User-defined Modules in Python
The user-define model is written by the user at
• math module the time of program writing
• os module
• random module How to create a user-define module?
• datetime module To create a module just write a python code in a
file with file extension as .py

Example:
def greeting(name):
print("Hello, " + name)

Save this code in a any named (mymodule.py)


Use a Module

Now we can use the module we just created, by


using the import statement:
import mymodule
mymodule.greeting("Jonathan")
ADT
Abstract Data Types (ADT): Defining ‘What’ not ‘How

Abstract Data Types define the conceptual framework for 'what' needs to be accomplished but
leaves the 'how' of it all up to developers. In this way, ADTs are very much like upper
management—complete with a lack of regard for your personal time.
Characteristics of ADTs
• Encapsulates a Data Type and set of operations to manipulate the Type
• Operations are only defined by inputs and outputs
• Operation details are hidden from the user through encapsulation
• Theoretical in nature
• Define what is getting done not how it is getting done
• Allows internal implementation details to change without
ADT operations
Classes and Objects

Object-‐Oriented Programming (OOP): A programming paradigm that involves


designing programs around concepts represented as "objects"
• Python supports OOP through the provision of classes.
• Terminology
•Class: A collection of functions and attributes, attached to a specific
name, which represents an abstract concept.
•Attribute: A named piece of data (i.e. variable associated with a class.
•Object: Objects are specific instances of a class
Creating Classes

Defining a class in Python is done using the class keyword, followed by an


indented block with the class contents.

class <Classname>:
Class data
data1 = value1
attributes
...
dataM = valueM

def <function1>(self,arg1,...,argK):
Class
<block>
...
member
functions
def <functionN>(self,arg1,...,argK):
<block>
Instances of Classes

Classes can be viewed as factories or templates for generating new object

instances.
Each object instance takes on the properties of the class from which it was
created.
Instances of Classes
Creating Classes

Defining a class in Python is done using the class keyword, followed by an


indented block with the class contents.

class <Classname>:
Class data
data1 = value1
attributes
...
dataM = valueM

def <function1>(self,arg1,...,argK):
Class
<block>
...
member
functions
def <functionN>(self,arg1,...,argK):
<block>
Defining Functions in Classes

• A class definition block can include multiple functions.


• These represent the functionality or behaviors that are associated with the class.

>>> class Maths:

... Def subtract(self,i,j):


... return i-j
...
... Def add(self,x,y):
... return x+y

Argument (self) refers to the object itself


Calling Functions in Classes

• Using Class Functions from Outside a Class


Functions are referenced by using the dot syntax:
<objectName>.<methodName>()

>>> m = Maths() No need to


>>> m.subtract(10,5) specify value for
5 self, Python does
>>> m.add(6,7) this automatically
13
Calling Functions in Classes
•Using Class Functions from Inside a Class When referring to functions from
within a class, we must always prefix the function name with self
(e.g. self.subtract())

>>> class Maths:


... def subtract(self,i,j):
... return i-j
...
... def testsub(self):
... print self.subtract(8,4)

Tell Python to use function


associated with this object
Attributes
Class attribute
defined at top of >>> class Person:
Instance attribute
class ... company = "ucd"
defined inside a class
...
function.
... def init (self):
self.age = 23
The self prefix is
...
always required.
defined at top of >>> class
Person:
>>> p1 = Person() Instance Change to instance attribute age
attribute
>>> p2 = Person()
class ... company = affects only the associated
>>> p1.age = 35
"ucd" instance (p2)
>>> print p2.agedefined inside a
class
23 ...

function.
... def
__init__(self):
>>> p1 = Person()
>>> p2 = Person() The self Change to class attribute company
>>> p1.company =prefix
..."ibm"
is
self.age affects all instances (p1 and p2)
= 23
>>> print p2.company
always required.
'ibm'
Constructor
• When an instance of a class is created, the class constructor function is
automatically called.
• The constructor is always named init ()
• It contains code for initializing a new instance of the class to a specific initial state
(e.g. setting instance attribute values).

>>> class Person:


Constructor function taking
... def init ( self, s ):
... self.name = s initial value for instance
... attribute name
... def hello( self ):
... print "Hello", self.name

>>> t = Person("John") Calls init ()


>>> t.hello() on Person
Hello John
“Self”

• “Self” in Python is like the pointer “this” in C++. In Python, functions in


class access data via “self”.

• “Self” in Python works as a variable of function but it won’t invoke data.


Inheritance

Deriving a new class form existing class so that new class inherits all

Inheritance
members(attributes + methods) of existing class is called as inheritance
Inheritance

The functions and attributes of a superclass are inherited by a subclass.

An inherited class can override, modify or augment the


functions and attributes of its parent class.
Creating Subclasses
Simple >>> class Shape:
superclass ... def init ( self ):
... self.color = (0,0,0)

Simple subclass >>> class Rectangle(Shape): Need to call


inheriting from ... def init ( self, w, h ):
constructor
... Shape. init ( self )
Shape function in
... self.width = w
superclass
... self.height = h
...
... def area( self ):
... return self.width*self.height

Construct
>>> r1 = Rectangle( 10, 5 )
>>> print r1.width object instance
10
>>> print r1.height
5
>>> print r1.area()
50
>>> print r1.color Inherited
(0, 0, 0) attribute
Overriding

When inheriting from a class, we can alter the behavior of the original superclass by
"overriding" functions (i.e. declaring functions in the subclass with the same name).

Functions in a subclass take precedence over functions in a superclass.


Overriding

class CustomCounter(Counter):
class Counter: def init (self,size):
def init (self): Counter. init (self)
self.value = 0 self.stepsize = size

def increment(self): def increment(self):


self.value += 1 Overriding self.value += self.stepsize

>>> cc = CustomCounter(4) Calls increment()


>>> cc.increment() on CustomCounter
>>> cc.print_current() not Counter
Current value is 4
Super() function

• Using super() function, we can access parent Example:


class properties. class Computer:
• This function returns a temporary object def __init__(self):
which contains reference to parent class. self.ram="8gb"
• Its make inheritance more manageable and
self.storage="512gb"
extensible.
print("computer class constructor called")
class Mobile(Computer):
def __init__(self):
#super().__init__()
self.model="iphone"
print("mobile class constructor called")
apple=Mobile()
print(apple.__dict__)
Types of inheritance
Single Inheritance :
• Single Inheritance One parent and one child class.
• Multi-level Inheritance
Example:
• Multiple Inheritance class employee:
def __init__(self,sal, ag):
• Hybrid Inheritance self.salary=sal
self.age=ag
e1=employee(50000,27)
print(e1.salary)
print(e1.age)
e2=employee(80000, 45)
print(e2.salary)
print(e2.age)
Multi-level Inheritance:

Parent class and child class further Example:


inherited into new class forming multiple class Employees():
levels.
def Name(self):
print("Employee Name: Khushi")

class salary(Employees):
def Salary(self):
print("Salary: 10000")

class Designation(salary):
def desig(self):
print("Designation: Test Engineer")

call = Designation()
call.Name()
call.Salary()
call.desig()
Multiple Inheritance

• Python supports a limited form of multiple inheritance.


• A class definition with multiple base classes looks as follows:

class DerivedClass(Base1, Base2, Base3 …)


<statement-1>
<statement-2>

• The only rule necessary to explain the semantics is the resolution rule used for
class attribute references. This is depth-first, left-to-right. Thus, if an attribute
is not found in DerivedClass, it is searched in Base1, then recursively in the
classes of Base1, and only if it is not found there, it is searched in Base2, and so
on.
An Example of Multiple Inheritance

C multiple-inherit A and B, but since


A is in the left of B, so C inherit A and
invoke A.A() according to the left-to-
right sequence.

To implement C.B(), class A does not


have B() method, so C inherit B for the
second priority. So C.B() actually
invokes B() in class B.
Hybrid Inheritance Inheritance consisting of multiple types of
inheritance is called hybrid inheritance.

# hybrid inheritance
class School:
def func1(self):
print("This function is in school.")
class Student1(School):
def func2(self):
print("This function is in student 1. ")

class Student2(School):
def func3(self):
print("This function is in student 2.")

class Student3(Student1, School):


def func4(self):
print("This function is in student 3.")
# Driver's code
object = Student3()
object.func1()
object.func2()
Encapsulation
• Encapsulation is one of the fundamental concepts in OOP.
• It describes the idea of restricting access to methods and attributes in a class.
• This will hide the complex details from the users, and prevent data being modified by
accident.
• In Python, this is achieved by using private methods or attributes using underscore as
prefix, i.e. single “_” or double “__”. Let us see the following example.
class Sensor():
def __init__(self, name, location):
self.name = name
self._location = location
self.__version = '1.0'

# a getter function
def get_version(self):
print(f'The sensor version is sensor1 = Sensor('Acc', 'Berkeley')
{self.__version}') print(sensor1.name)
print(sensor1._location)
# a setter function print(sensor1.__version)
def set_version(self, version):
self.__version = version
Polymorphism
• Polymorphism is another fundamental concept in OOP, which means multiple
forms
• Two objects of different classes but supporting the same set of functions or
attributes can be treated identically.
• The implementations may differ internally, but the outward "appearance" is the
same.
• Polymorphism allows us to use a single interface with different underlying
forms such as data types or classes
Polymorphism

Two different classes that contain the function area()


class Rectangle(Shape): class Circle(Shape):
def init (self, w, h): def init (self, rad):
Shape. init (self) Shape. init (self)
self.width = w self.radius = rad
self.height = h
def area(self):
def area(self): return math.pi*(self.radius**2)
return self.width*self.height

Instances of the two classes can be >>> l = []


treated identically... >>> l.append( Rectangle(4,5) )
>>> l.append( Circle(3) )
>>> for someshape in l:
... print someshape.area()
...
Result of area() in Rectangle 20
Result of area() in Circle 28.2743338823
Composition
Classes can be built from other smaller classes,allowing
us to model relationships of the type "x has a y” (e.g. a
department has students).
class Department: class Student:
def init ( self ): def init ( self,last,first ):
self.students = [] self.lastname = last
self.firstname = first
def enroll( self, student ):
self.students.append(student)

Create Student
>>> compsci = Department()
>>> compsci.enroll( Student( "Smith", "John" ) ) instances and add
>>> compsci.enroll( Student( "Murphy", "Alice" ) ) to Department
instance
>>> for s in compsci.students:
... print "%s %s" % (s.firstname,s.lastname)
...
John Smith

You might also like