Transcript
Page 1: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

1

CSIT

Workshop – User Manual

A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A

[email protected] 9444473301 / 0435-2420301

This Article Private Circulation Only Release Date: 07/09/2017

CSIT

#28, 1st

Floor, Nalli Plaza, T.S.R Big Street, Kumbakonam.

Installation & Configuration

Scripting Programs

CGI

SQLite

PyGame

Anna University Programs

Problem Solving with Data Structure

Page 2: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

2

Introduction

Python is an easy to learn, powerful programming language. It has efficient

high-level data structures and a simple but effective approach to object-oriented

programming. Python’s elegant syntax and dynamic typing, together with its

interpreted nature, make it an ideal language for scripting and rapid application

development in many areas on most platforms. Developed by Guido van

Rossum.

The Python interpreter and the extensive standard library are freely available in

source or binary form for all major platforms from the Python Web site,

https://www.python.org/, and may be freely distributed.

The Python interpreter is easily extended with new functions and data types

implemented in C or C++ (or other languages callable from C). Python is also

suitable as an extension language for customizable applications.

Python Features

Interpreted Language - Interpreter reads the source code of the program, line by

line, parses the source code, and interprets the instructions. Python Interpreters

are available for many operating systems.

Object-oriented programming language. Python is an open source scripting

language. Large standard libraries to solve common tasks. Cross Platform

Language.

Python provides no braces to indicate blocks of code for class and function

definitions or flow control. Blocks of code are denoted by line indentation.

Python has a very simple and elegant syntax. It's much easier to read and write

Python programs compared to other languages like: C++, Java, C#.

Page 3: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

3

Installation & Configuration

Software Requirements: Key Points

1) Windows 7 Service Pack1 / Windows 8/ 10

2) Python 3.6.2

3) JDK 1.7

4) NetBeans IDE 8.0.2

5) Python Plugins for NetBeans 8.0

6) Install IIS and configure CGI

7) DB Browser for SQLite

8) PyGame Plugins

Open a Web browser and go to https://www.python.org/downloads/

Run the downloaded file Python 3.6.2. This brings up the Python install wizard, just accept the default settings, and wait until the install is finished.

Page 4: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

4

Installation & Configuration

Console Mode: CLI - Command Line Interface

IDLE - Integrated Development and Learning Environment

Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32. Type "help", "copyright", "credits" or "license" for more information.

>>> print("Welcome, Python")

Welcome, Python

Online console : https://www.python.org/ Online console : https://www.tutorialspoint.com/execute_python_online.php

Python in NetBeans IDE 8.0.2

Let's get started with Python in NetBeans IDE 8.0.2. Take the following steps:

Prerequisite: Here you can download jdk 7u11 windows i586 (JDK 1.7)

http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html

1) dowload and install NetBeans IDE 8.0.2.

Now, download NetBeans IDE 8.0.2.

Quickly and easily develop desktop, mobile and web applications with Java,

JavaScript, HTML5, PHP, Python,C/C++ and more. NetBeans IDE is FREE,

open source, and has a worldwide community of users and developers.

Product Version: NetBeans IDE 8.0 (Build 201403101706) Updates: Updates available to version NetBeans 8.0.2 Patch 2 Java: 1.7.0_11; Java HotSpot(TM) Client VM 23.6-b04 Runtime: Java(TM) SE Runtime Environment 1.7.0_11-b21 System: Windows 7 version 6.1 running on x86; Cp1252; en_IN (nb)

Page 5: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

5

Installation & Configuration

2) Get the Python Plugin for NetBeans IDE 8.0.2. Go here, click

Download on the page, and then unzip the file

http://plugins.netbeans.org/plugin/56795/python4netbeans802

3) Go to the Plugin Manager in NetBeans IDE.

In NetBeans IDE, go to Tools | Plugins. Click the "Downloaded" tab, which you

see below. Click Add Plugins and browse to the folder where you unzipped the

files in the previous step. Select them all. You now should see exactly this:

4) Install the Python Plugin. Click Install. Click Next. Put a checkmark in

"I accept the terms in all of the license agreements." Click Install. Click

Continue. Click Finish. Click Close.

Go to the New Project Dialog. Go to File | New Project or press Ctrl-Shift-N.

You should now see this:

Page 6: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

6

Installation & Configuration

Page 7: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

7

Installation & Configuration

Python CGI Script Map in IIS 7

1. Please make sure Python is installed properly.

2. Make sure CGI module is installed in IIS 7

CGI – Common Gateway Interface

Control Panel -> Programs -> Program and Features -> Turn Windows features

on and off ->

Internet Information Services -> World Wide Web Services -> Application

Development Features -> CGI module. (Click Add Role Services then check

CGI)

Pysical Location : C:\inetpub\wwwroot

URL : http://localhost/

Page 8: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

8

Installation & Configuration

Add web application for Python, In IIS Manager

Go to Control Panel -> Administrative Tools -> IIS Manager

In Features View, open Handler Mappings, right click to Add Script Map

Page 9: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

9

Installation & Configuration

Edit Feature Permissions.

Check Execute

Page 10: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

10

Installation & Configuration

Create a file prg1.py with the following web root, c:\inetpub\wwwroot

Now, you should be able to go to a web browser and navigate to

http://localhost/ prg1.py and see your output webpage.

Simple Python Web Script CGI Program

SQLite

http://sqlitebrowser.org/

Page 11: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

11

Installation & Configuration

PyGame

Pygame is a cross-platform set of Python modules designed for writing video

games. It includes computer graphics and sound libraries designed to be used

with the Python programming language.

Download PyGame Plugins : pygame 1.9.3 cp36 cp36m win32.whl

Download URL : http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame

Move the downloaded .whl file to your python35/Scripts directory

Open a command prompt in the Scripts directory (Shift-Right click in the

directory > Open a command window here)

Enter the command:

pip3 install pygame-1.9.2a0-cp35-none-win32.whl

Page 12: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

12

Scripting Programs

* Lines and Indentation

* Assigning Values to Variables

Python has five standard data types:

Numbers ( int, float, long, complex)

String

List

Tuple

Dictionary

Ex1: Simple Program

print ("Hello World")

a=5

b=5

c=a+b

print ("Ans: ",c) o/p : Hello World 10

Ex2: Runtime Input from Console

a=input("Enter A :") \\ old version : a=raw_input(“Enter A”)

print (a) o/p : Enter A : 10 10

Ex3: Type Casting (Float value convert to Integer) / Data type conversion

a=10.5

b= int(a)

print (b) o/p : 10

Page 13: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

13

Scripting Programs

Ex4: Math Functions

import math others, abs(x), pow(x,y)

x=16

print (math.sqrt(x)) o/p : 4.0

#try more math buil in functions

Ex5: If- Else (Decision Making)

a=1

b=5

if (a>b):

print (a)

else:

print (b)

o/p: 5

Ex6: Loops (for & while)

sequence1

for i in "Python":

print (i)

for i in ("Name1","Name2"):

print (i)

for i in (1,2,3,4,5):

print (i)

P y t h o n

Name1

Name2

1 2 3 4 5

Syntax

if expression1:

statement(s)

elif expression2:

statement(s)

else:

statement(s)

Syntax

for iterating in sequence:

statements(s)

Page 14: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

14

Scripting Programs

Range

i=0

for i in range(5):

i=i+1

print (i)

for i in range(5):

print (i)

for i in range(1,5):

print (i)

fact=1

for i in range(1,6):

fact=fact*i

print (fact)

While

i=0

while (i<=5):

i=i+1

print(i)

0 1 2 3 4

1 2 6 24 120

1 2 3 4

1 2 3 4 5

1 2 3 4 5 6

Syntax

for iterating in range:

statements(s)

Syntax

while expression:

statements(s)

Page 15: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

15

Scripting Programs

Ex 7 : Random Number

import random

for i in range(10):

print (random.randrange(1,10))

Ex 8 : List of array values

x=[10,20,30,40,50]

for i in range(1,5):

print (x[i])

Ex 9: String Functions

str1="A1" str2="A2"

print (str1+str2)

if str1==str2:

print (“Equal”)

else:

print ("Not Equal")

print (str1.lower()) o/p a1

print (len(str1)) o/p 2

print (str1[::-1]) o/p 1a

str1=str2 (String Copy)

print (str1.isdigit()) o/p false

20 30 40 50

Page 16: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

16

Scripting Programs

Ex10 : Datetime

import datetime

print (datetime.date.today())

List / Tuple / Dictionary

Lists are similar to arrays in C. list can be of different data type. A List is a

sequence of mutable Python objects.

Tuples cannot be updated. Tuples can be thought of as read-only lists. A tuple

is a sequence of immutable Python objects.

Dictionaries Python's dictionaries are kind of hash table type. They work like

associative arrays or hashes found in Perl and consist of key-value pairs.

Ex11:

list =[10,20.5,'a','name']

print (list[3])

list[0]=100

print (list[0])

tuple =(10,20,30,40,50)

print (tuple[0])

dict ={'id':10,'name':'Andrew'}

print (dict['name'])

o/p name 100 10 Andrew

Page 17: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

17

Scripting Programs

Function

A function is a block of organized, reusable code that is used to perform a

single, related action.

Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).

Ex12:

def f1():

str="simple Function"

print (str)

f1()

Ex13 : Return Function

def calc(x,y):

z=x+y

return z

print(calc(5,5))

Ex14 : File Handling

fhand =open('newfile.txt','r')

str1= fhand.read()

print (str1)

fout=open('newfile.txt','a')

str2="Demo"

fout.write(str2)

Syntax def functionname( parameters ):

"function_docstring" function_suite return [expression]

Page 18: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

18

Scripting Programs

Ex15: Exception Handling

An exception is an event, which occurs during the execution of a program that

disrupts the normal flow of the program's instructions. When a Python script

raises an exception, it must either handle the exception immediately otherwise it

terminates and quits.

try:

fhand =open('newfile.txt','r')

str1= fhand.read()

print (str1)

except IOError:

print ("Error: can\'t find file or read data")

else:

print ("Written content in the file successfully")

Ex16: Class & Object

class stud:

def f1(self):

print ("Simple Class")

s1=stud()

s1.f1()

Page 19: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

19

Scripting Programs

Ex17: Constructor

class stud:

global a,b

a=10 b=10

def __init__(self):

print ("Default Constructor")

def __init__(self,a,b):

self.a=a

self.b=b

print (self.a, self.b)

c=a+b

print (c)

def __del__(self):

print (stud, "destroyed")

s1=stud(2,2)

Ex18: Inheritance

class stud:

def f1(self):

print ("Base Class")

class dept(stud):

def f2(self):

print("Derived Class")

d1=dept()

d1.f1() d1.f2()

Page 20: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

20

Scripting Programs

Ex19: Regular Expressions

A regular expression is a special sequence of characters that helps you match or

find other strings or sets of strings, using a specialized syntax held in a pattern.

The module re provides full support for Perl-like regular expressions in Python.

import re

line=("Cats are smarter than dogs")

#matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)

matchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)

if matchObj:

print ("matchObj.group(1) : ", matchObj.group(1))

print ("matchObj.group(2) : ", matchObj.group(2))

else:

print ("No match!!")

string1 =('hello [email protected] and us email [email protected]')

string2=("Andrew 9444473301 Bergeran 7904204339")

findobj1=re.findall('\S+@\S+',string1)

findobj2=re.findall('[0-9]+',string2)

print(findobj1)

print(findobj2)

Ex20 : Web Crawling using URLLIB

import urllib.request

y = urllib.request.urlopen('http://www.py4inf.com/code/romeo.txt')

print (y.read())

Page 21: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

21

CGI – Common Gateway Interface

The Common Gateway Interface, or CGI, is a set of standards that define how

information is exchanged between the web server and a custom script.

The Common Gateway Interface, or CGI, is a standard for external gateway

programs to interface with information servers such as HTTP servers.

The line Content-type:text/html\r\n\r\n is part of HTTP header which is sent

to the browser to understand the content.

EX21: CGI Programs

print ('Content-type:text/html\r\n\r\n')

print ('<html>')

print ('<head>')

print ('<title>Hello Word - First CGI Program</title>')

print ('</head>')

print ('<body>')

print ('<h2>Python CGI- Program</h2>')

print ('</body>')

print ('</html>')

Page 22: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

22

CGI

<form action="prg2.py" method="post">

First Name: <input type="text" name="first_name"><br />

Last Name: <input type="text" name="last_name" />

<input type="submit" value="Submit" />

</form>

import cgi, cgitb

form = cgi.FieldStorage()

first_name = form.getvalue('first_name')

last_name = form.getvalue('last_name')

print ("Content-type:text/html\r\n\r\n")

print ("<html>")

print ("<head>")

print ("<title>Hello - Second CGI Program</title>")

print ("</head>")

print ("<body>")

print ("<h2>Welcome %s and %s</h2>" % (first_name, last_name))

print ("</body>") print ("</html>")

Page 23: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

23

SQLite

Information retrieves from SQLite DB

The Python standard for database interfaces is the Python DB-API. Most Python

database interfaces adhere to this standard.

Python Database API supports a wide range of database servers such as:SQLite,

MySQL, Microsoft SQL Server 2000, Oracle, Sybase

Ex 22:

import cgi, cgitb

import sqlite3

print ("Content-type:text/html\r\n\r\n")

conn = sqlite3.connect('Stud.db')

print ("Opened database successfully")

print ("</br>")

cursor = conn.execute("SELECT * from T1")

for row in cursor:

print ("</br>")

print ("Roll No = ", row[0], "</br>")

print ("NAME = ", row[1], "</br>")

print ("Course = ", row[2] , "</br>")

print ("Operation done successfully")

conn.close

Page 24: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

24

SQLite

Ex 23: Information Stored to SQLite DB

import cgi, cgitb

import sqlite3

print ("Content-type:text/html\r\n\r\n")

conn = sqlite3.connect('Stud.db')

cursor = conn.execute

('insert into t1(rollno,sname,course) values(?,?,?)',(110,'amal','C#'))

conn.commit()

conn.close print ("ok")

JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It

is easy for humans to read and write. It is easy for machines to parse and

generate.

The json library can parse JSON from strings or files. The library parses JSON

into a Python dictionary or list. It can also convert Python dictionaries or lists

into JSON strings.

Ex24:import json

input = ''' [ { "id" : "01", "name" : "Amalesh" } ,

{ "id" : "02", "name" : "Bergeran" } ]'''

info = json.loads(input)

print ('Usercount:',len(info))

for item in info:

print ('Id',item['id'])

print ('Name',item['name'])

Page 25: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

25

Anna University Lab Programs

Problem Solving and Python Programming Laboratory

1. Compute the GCD of two numbers

2. Find the Square root of a number (Newton’s Method) 3. Exponentiation (Power of a number)

4. Find the maximum of a list of numbers

5. Linear Search and Binary Search

6. Selection Sort, Insertion Sort

7. Merge Sort

8. First n Prime Numbers

9. Multiply Matrices

10. Program that take command line argument (word count)

11. Find the most frequent words in a text read from a file

12. Simulate elliptical orbits in PyGame

13. Simulate bouncing ball using PyGame

1. Compute the GCD of two numbers

In mathematics, the greatest common divisor (gcd) of two or more integers,

which are not all zero, is the largest positive integer that divides each of the

integers.

Example : Gcd(12,28)

12=> 3,2,2

28=>2,2,7 = (2,2) is the Greatest Common Divisor , 2x2= GCD(4)

12 28

6 2

3 2

4 7

2 2

3

7 2

2

Page 26: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

26

Problem Solving

Algorithm

Gcd(a,0)=a Gcd(a,b)=gcd(b,a mod b) Where a mod b = a-b [a/b] if the arguments are both greater than zero than the algorithm can be written in more elementary terms as follows. Gcd(a,a)=a Gcd(a,b)=gcd(a-b,b), if a>b Gcd(a,b)=gcd(a,b-a), if b>a

GCD using built-in Function

import fractions a=int(input("Enter the first number:")) b=int(input("Enter the second number:")) print("The GCD of the two numbers is",fractions.gcd(a,b))

Another example,

def gcd(a,b): if(b==0): return a

else: return gcd(b,a%b)

a=int(input("Enter first number:")) b=int(input("Enter second number:")) GCD=gcd(a,b) print ("GCD is: ",GCD) output:

Enter the first number:12 Enter the second number:28 The GCD of the two numbers is 4

Page 27: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

27

Problem Solving

2. Find the Square root of a number (Newton’s Method)

Newton's method (also known as the Newton–Raphson method),

In numerical analysis, a branch of mathematics, there are several square

root algorithms or methods of computing the principal square root of a

non-negative real number. This method for finding successively better

approximations to the roots (or zeroes) of a real-valued function

The Newton–Raphson method in one variable is implemented as follows:

The method starts with a function f defined over the real numbers x, the

function's derivative f ′, and an initial guess x0 for a root of the function f. If the function satisfies the assumptions made in the derivation of the

formula and the initial guess is close, then a better approximation x1 is

Xn+1=

until a sufficiently accurate value is reached.

Page 28: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

28

Problem Solving

Calculating/Computing Square Roots

X f(x)=x2-2 f

I(x)=2x x-f(x)/f

I(x)

1 1*1-2 = -1 2*1= 2 1- (-1/2) = 1.5

1.5 1.5*1.5-2=0.25 2*1.5=3 1.5-(0.25/3) = 1.41666

1.41666 1.41666*1.41666

-2 = 0.0069

1.41666*2

=2.83332

1.41666-(0.0069/2.83332)

=1.4142

1.4142 1.4142*1.4142-2

=-3.836e-5

2*1.4142

=2.8284

1.4142- (-3.836e-5/2.8284)

=1.414213562

Page 29: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

29

Problem Solving

Square Root Program [Newton Method]:

def square(x):

return x*x

def average(x, y):

return (x + y) / 2.0

def good_enough(guess, n):

return abs(square(guess) - n)<0.0001

def next_guess(guess,n):

return average(guess,n/guess)

def nsqrt(guess,n):

if good_enough(guess,n):

return guess

else:

return nsqrt(next_guess(guess,n),n)

def newton_square_root(n):

return nsqrt(1,n)

print (newton_square_root(3))

Verify your answer to built-in function

import math

print (math.sqrt(3))

Output:

1.7320508100147274

1.7320508075688772

Page 30: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

30

Problem Solving

3. Exponentiation (Power of a number)

Exponentiation is a mathematical operation, written as bn involving two

numbers, the base b and the exponent n. When nis a positive integer,

exponentiation corresponds to repeated multiplication of the base.

103 = 10 X 10 X 10 => 1000

Ex1: def pow(b, p):

y = b ** p

return y

print(pow(10,3))

Ex2: base=2 exp=7 ans=1

for i in range(7):

ans=ans*base

print (ans)

Ex3: def power(base,exp):

if(exp==1):

return(base)

if(exp!=1):

return(base*power(base,exp-1))

base=int(input("Enter base: "))

exp=int(input("Enter exponential value: "))

print("Result:",power(base,exp))

Page 31: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

31

Problem Solving

4. Find the maximum of a list of numbers

The program takes a list and prints the largest number in the list.

Ex1

a=[1,2,3,4,200,7,99,88,100]

max= 0

for i in a:

if i > max:

max=i

print(max)

Output: 200

Ex2

a=[]

n=int(input("Enter number of elements:"))

for i in range(1,n+1):

b=int(input("Enter element:"))

a.append(b)

a.sort()

print("Largest element is:",a[n-1])

O/p: Enter number of elements:3

Enter element:34

Enter element:65

Enter element:78

Largest element is: 78

Page 32: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

32

Problem Solving

5. Linear Search and Binary Search

In computer science, linear search or sequential search is a method for finding a

target value within a list. It sequentially checks each element of the list for the

target value until a match is found or until all the elements have been searched.

In linear search algorithm we match the element to be searched with the entire

list of elements. Therefore it’s a brute force approach.

Ex: Linear Search

list_of_elements = [10,14,19,26,27,31,33,35,42,44]

x = int(input("Enter number to search: "))

for i in range(len(list_of_elements)):

if(list_of_elements[i] == x):

found = True

print("%d found at %dth position"%(x,i))

break

Output : Enter number to search: 33 (33 found at 6th position)

Page 33: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

33

Problem Solving

Binary Search

In computer science, binary search, also known as half-interval search.

Binary Search is a sorted array by repeatedly dividing the search interval in half.

Begin with an interval covering the whole array. If the value of the search key is

less than the item in the middle of the interval, narrow the interval to the lower

half. Otherwise narrow it to the upper half. Repeatedly check until the value is

found or the interval is empty.

Page 34: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

34

Problem Solving

Ex :Binary Search

def binarySearch(alist, item):

first = 0

last = len(alist)-1

found = False

while first<=last and not found:

midpoint = (first + last)//2

if alist[midpoint] == item:

found = True

else:

if item < alist[midpoint]:

last = midpoint-1

else:

first = midpoint+1

return found

testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]

print(binarySearch(testlist, 13))

Page 35: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

35

Problem Solving

6. Selection Sort, Insertion Sort

Selection sort is a simple sorting algorithm. This sorting algorithm is an in-

place comparison-based algorithm in which the list is divided into two parts,

the sorted part at the left end and the unsorted part at the right end. Initially, the

sorted part is empty and the unsorted part is the entire list.

The smallest element is selected from the unsorted array and swapped with the

leftmost element, and that element becomes a part of the sorted array. This

process continues moving unsorted array boundary by one element to the right.

Page 36: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

36

Problem Solving

Ex: Selection Sort

def selectionSort(alist):

for fillslot in range(len(alist)-1,0,-1):

positionOfMax=0

for location in range(1,fillslot+1):

if alist[location]>alist[positionOfMax]:

positionOfMax = location

temp = alist[fillslot]

alist[fillslot] = alist[positionOfMax]

alist[positionOfMax] = temp

alist = [54,26,93,17,77,31,44,55,20]

selectionSort(alist)

print(alist)

Output

[17, 20, 26, 31, 44, 54, 55, 77, 93]

Page 37: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

37

Problem Solving

Insertion Sort

An element which is to be 'insert'ed in this sorted sub-list, has to find its

appropriate place and then it has to be inserted there. Hence the name, insertion

sort.

Insertion sort is a simple sorting algorithm that builds the final sorted array (or

list) one item at a time.

Page 38: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

38

Problem Solving

Ex : Insertion Sort

def insertionSort(alist):

for index in range(1,len(alist)):

currentvalue = alist[index]

position = index

while position>0 and alist[position-1]>currentvalue:

alist[position]=alist[position-1]

position = position-1

alist[position]=currentvalue

alist = [54,26,93,17,77,31,44,55,20]

insertionSort(alist)

print(alist)

Output

[17, 20, 26, 31, 44, 54, 55, 77, 93]

Page 39: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

39

Problem Solving

7. Merge Sort

Merge sort is a sorting technique based on divide and conquer technique. With

worst-case time complexity being Ο(n log n), it is one of the most respected

algorithms.

Merge sort first divides the array into equal halves and then combines them in a

sorted manner.

Merging is the process of taking two smaller sorted lists and combining them

together into a single, sorted, new list.

Page 40: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

40

Problem Solving

Merge Sort

Ex: Merge Sort

def mergeSort(alist):

print("Splitting ",alist)

if len(alist)>1:

mid = len(alist)//2

lefthalf = alist[:mid]

righthalf = alist[mid:]

mergeSort(lefthalf)

mergeSort(righthalf)

Page 41: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

41

i=0

j=0

k=0

while i < len(lefthalf) and j < len(righthalf):

if lefthalf[i] < righthalf[j]:

alist[k]=lefthalf[i]

i=i+1

else:

alist[k]=righthalf[j]

j=j+1

k=k+1

while i < len(lefthalf):

alist[k]=lefthalf[i]

i=i+1

k=k+1

while j < len(righthalf):

alist[k]=righthalf[j]

j=j+1

k=k+1

print("Merging ",alist)

alist = [54,26,93,17,77,31,44,55,20]

mergeSort(alist)

print(alist)

Page 42: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

42

Problem Solving

Output

Splitting [54, 26, 93, 17, 77, 31, 44, 55, 20]

Splitting [54, 26, 93, 17]

Splitting [54, 26]

Merging [26, 54]

Splitting [93, 17]

Merging [17, 93]

Merging [17, 26, 54, 93]

Splitting [77, 31, 44, 55, 20]

Splitting [77, 31]

Merging [31, 77]

Splitting [44, 55, 20]

Splitting [55, 20]

Merging [20, 55]

Merging [20, 44, 55]

Merging [20, 31, 44, 55, 77]

Merging [17, 20, 26, 31, 44, 54, 55, 77, 93]

[17, 20, 26, 31, 44, 54, 55, 77, 93]

Page 43: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

43

Problem Solving

8. First n Prime Numbers

A prime number (or a prime) is a natural number greater than 1 that has no

positive divisors other than 1 and itself. A natural number greater than 1 that is

not a prime number is called a composite number. For example, 5 is prime

because 1 and 5 are its only positive integer factors, whereas 6 is composite

because it has the divisors 2 and 3 in addition to 1 and 6.

Ex: Prime Numbers

lower = 1

upper = 100

print("Prime numbers between",lower,"and",upper,"are:")

for num in range(lower,upper + 1):

if num > 1:

for i in range(2,num):

if (num % i) == 0:

break

else:

print(num)

Output

2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97

Page 44: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

44

Problem Solving

9. Multiply Matrices

Matrix multiplication or the matrix product is a binary operation that produces a

matrix from two matrices. The definition is motivated by linear equations and

linear transformations on vectors, which have numerous applications in applied

mathematics, physics, and engineering.

Ex: Matrix

X = [[12,7,3],

[4 ,5,6],

[7 ,8,9]]

# 3x4 matrix

Y = [[5,8,1,2],

[6,7,3,0],

[4,5,9,1]]

# result is 3x4

Page 45: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

45

Problem Solving

result = [[0,0,0,0],

[0,0,0,0],

[0,0,0,0]]

for i in range(len(X)):

for j in range(len(Y[0])):

for k in range(len(Y)):

result[i][j] += X[i][k] * Y[k][j]

for r in result:

print(r)

Output [114, 160, 60, 27]

[74, 97, 73, 14]

[119, 157, 112, 23]

10. Program that take command line argument (word count)

#!/usr/bin/env python3

import sys

total = len(sys.argv)

cmdargs = str(sys.argv)

print ("The total numbers of args passed to the script: %d " % total)

print ("Args list: %s " % cmdargs)

print ("Script name: %s" % str(sys.argv[0]))

print ("First argument: %s" % str(sys.argv[0]))

print ("Second argument: %s" % str(sys.argv[1]))

print ("Second argument: %s" % str(sys.argv[2]))

Page 46: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

46

Problem Solving

11. Find the most frequent words in a text read from a file

To Search Data , Use if – to specify the conditions.

Use starts with – to specify the exact match required.

find()

Used to simulate a text editor search that finds lines wherever the search string is found.

T1.txt

From:[email protected], [email protected], [email protected]

[email protected],

[email protected],

[email protected]

Subject: Python Programming

Ex1

fhand = open('t1.txt')

for line in fhand:

if line.startswith('From:') :

print(line)

o/p: [email protected], [email protected], [email protected]

Page 47: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

47

Ex2

fhand = open('t1.txt')

for line1 in fhand:

line1=line1.rstrip()

if line1.find('gmail.com')==-1:

continue

print (line1)

o/p : [email protected] , [email protected]

Ex3 : Dynamically accept the file name from the user.

fname = input('Enter the file name: ')

fhand = open(fname)

count = 0

for line in fhand:

if line.startswith('Subject:') :

count = count + 1

print ('There were', count, 'subject lines in', fname)

o/p : There were 1 subject lines in t1.txt

Page 48: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

48

Problem Solving

12. Simulate elliptical orbits in PyGame

import pygame

pygame.init()

screen = pygame.display.set_mode((400, 300))

done = False

while not done:

for event in pygame.event.get():

if event.type == pygame.QUIT:

done = True

#pygame.draw.rect(screen, (0, 128, 255), pygame.Rect(30, 30, 60, 60))

#pygame.draw.line(screen, (127,127,127), (61,0), (61,120))

pygame.draw.ellipse(screen, (255,255,255), (0,0,61,61))

pygame.draw.ellipse(screen, (255,255,255), (0,62,60,60))

pygame.display.update()

pygame.display.flip()

Page 49: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

49

Problem Solving

13. Simulate bouncing ball using PyGame

import pygame, sys, time, random

from pygame.locals import *

from time import *

pygame.init()

windowSurface = pygame.display.set_mode((500, 400), 0, 32)

pygame.display.set_caption("Bounce")

BLACK = (0, 0, 0)

WHITE = (255, 255, 255)

RED = (255, 0, 0)

GREEN = (0, 255, 0)

BLUE = (0, 0, 255)

info = pygame.display.Info()

sw = info.current_w

sh = info.current_h

y = 0

# Initial direction is down

direction = 1

Page 50: Workshop ² User Manual - secure.pdf1 CSIT Workshop ² User Manual A.Andrew Bergeran M.Sc.,B.Ed.,M.B.A andrewanbu17@gmail.com 9444473301 / 0435-2420301 This Article Private Circulation

50

while True:

windowSurface.fill(BLACK)

pygame.draw.circle(windowSurface, GREEN , (250,y), 13, 0)

#print "Drawing at 250,", y

sleep(.006)

y += direction

if y >= sh:

# Changes the direction from down to up

direction = -1

elif y <= 0:

# Changes the direction from up to down

direction = 1

pygame.display.update()

for event in pygame.event.get():

if event.type == QUIT:

pygame.quit()

sys.exit()

Online Reference

https://www.google.co.in

https://www.youtube.com/

https://en.wikipedia.org/wiki/Main_Page

https://www.tutorialspoint.com/python/

http://interactivepython.org