Friday, 10 April 2020

Python Program-11

(11) Develop programs to learn GUI programming using Tkinter.


Program Code:

try: import tkinter
except: import Tkinter as tkinkter 
root = tkinter.Tk()
def grey(*args, **kwargs): 
root.configure(background="grey")
def bthing(): 
root.configure(background="red")
def bthing1(): 
root.configure(background="green")
def bthing2(): 
root.configure(background="blue") 
root.after(1000,grey)
tkinter.Button(text="RED", command=bthing).pack() 
tkinter.Button(text="Green", command=bthing1).pack() 
tkinter.Button(text="BLUE", command=bthing2).pack() 
root.configure(backround="grey") 
root.geometry("100*100")

root.mainloop()

Output:

Python Program-10

(10) Draw graphics using Turtle.
1) Shape 1: Square
2) Shape 2: Star
3) Shape 3: Hexagon
4) A square inside another square box
5) Drawing of pattern-1
6) Drawing of pattern-2


Program Code-1:Square using Turtle:

#Lab-10-Draw graphics using Turtle.
#Shape 1: Square
import turtle
skk = turtle.Turtle()

for i in range(4):
    skk.forward(50)
    skk.right(90)


turtle.done()

Output-1:Square using Turtle


Program Code-2:Star using Turtle

#Lab-10-Draw graphics using Turtle.
#Shape 2: Star
import turtle

star = turtle.Turtle()

for i in range(50):
    star.forward(50)
    star.right(144)
   
turtle.done()

Output-2:Star using Turtle


Program Code-3:Hexagon using Turtle

#Lab-10-Draw graphics using Turtle.
#Shape 3: Hexagon
import turtle

polygon = turtle.Turtle()
num_sides = 6
side_length = 70
angle = 360.0 / num_sides

for i in range(num_sides):
    polygon.forward(side_length)
    polygon.right(angle)

turtle.done()

Output-3:Hexagon using Turtle



Program Code-4:Draw a square inside another square box using Turtle

#Lab-10-Draw graphics using Turtle.
#Draw a square inside another square box.
# import turtle library
import turtle           
my_wn = turtle.Screen()
my_wn.bgcolor("light blue")
my_wn.title("Turtle")
my_pen = turtle.Turtle()
my_pen.color("black")
def my_sqrfunc(size):
   for i in range(4):
      my_pen.fd(size)
      my_pen.left(90)
      size = size - 5
my_sqrfunc(146)
my_sqrfunc(126)
my_sqrfunc(106)
my_sqrfunc(86)
my_sqrfunc(66)
my_sqrfunc(46)
my_sqrfunc(26)

Output-4:Draw a square inside another square box using Turtle




Program Code-5:Drawing of pattern-1 using Turtle

#Lab-10-Draw graphics using Turtle.
#Drawing of pattern-1
# import turtle library
import turtle           
my_wn = turtle.Screen()
turtle.speed(2)
for i in range(30):
   turtle.circle(5*i)
   turtle.circle(-5*i)
   turtle.left(i)
turtle.exitonclick()

Output-5:Drawing of pattern-1 using Turtle



Program Code-6:Drawing of pattern-2 using Turtle

#Lab-10-Draw graphics using Turtle.
#Drawing of pattern-2
# import turtle library
import turtle           
colors = [ "red","purple","blue","green","orange","yellow"]
my_pen = turtle.Pen()
turtle.bgcolor("black")
for x in range(360):
   my_pen.pencolor(colors[x % 6])
   my_pen.width(x/100 + 1)
   my_pen.forward(x)
   my_pen.left(59)

Output-6:Drawing of pattern-2 using Turtle


Python Program-9

(9) Implement classical ciphers using python. 1) Caesar cipher 2) Monoalphabetic cipher


Program Code-1:caesar cipher

#Lab-9-Implement classical ciphers using python.
#caesar cipher
def encrypt(text,s):
    result = ""
# transverse the plain text
for i in range(len(text)):
    char = text[i]
# Encrypt uppercase characters in plain text
    if (char.isupper()):
        result += chr((ord(char) + s-65) % 26 +65)
# Encrypt lowercase characters in plain text
    else:
        result += chr((ord(char) + s - 97) % 26 +97)
        return result
    
#check the above function
text = "CEASER CIPHER DEMO";
s = 4;

print ("Plain Text : " + text);
print ("Shift pattern : " + str(s));
print ("Cipher: " + encrypt(text,s));


Output-1:caesar cipher


Program Code-2:Monoalphabetic cipher

#Lab-9-Implement classical ciphers using python.
#Monoalphabetic cipher
keys={'a':'z','b':'y','c':'x','d':'w','e':'v','f':'u','g':'t','h':'s','i':'r','j':'q','k':'p','l':'o','m':'n'}

reverse_keys={}
for key,value in keys.items():
    reverse_keys[value]=key
def encrypt(text):
    text=str(text)
    encrypting=[]
    for l in text:
        encrypting.append(keys.get(l,l))
    print(''.join(encrypting))
def decipher(text):
    text=str(text)
    decrypted=[]
    for l in text:
        decrypted.append(reverse_keys.get(l,l))
    print(''.join(decrypted))
print(encrypt("Prime"))
print(decipher("gtu12"))

Output-2:Monoalphabetic cipher

Python Program-8

(8) Learn to plot different types of graphs using PyPlot.
1) Plotting a line
2) Bar Chart
3) Histogram
4) Pie-chart


#Lab-8-Learn to plot different types of graphs using PyPlot.

#""Matplotlib and its dependency packages are available in the form of wheel packages
#on the standard Python package repositories and can be installed on Windows,
#Linux as well as MacOS systems using the pip package manager.

#follow this instruction to install Matplotlib Package

#Matplotlib can also be installed using the Python package manager, pip.
#To install Matplotlib with pip, open a terminal window and type:

#pip install matplotlib

#This command installs Matplotlib in the current working Python environment.

#command to update python PIP on a windows
#python -m pip install -U pip


Program Code-1:Plotting a Line:

#Plotting a line
import matplotlib.pyplot as plt

# x axis values
x = [1,2,3]
# corresponding y axis values
y = [2,4,1]

# plotting the points
plt.plot(x, y)

# naming the x axis
plt.xlabel('x - axis') # naming the y axis
plt.ylabel('y - axis')

# giving a title to my graph
plt.title(' College First graph!')

# function to show the plot
plt.show()

Output-1:Plotting a Line:



Program Code-2:Bar Chart:

#Lab-8-Learn to plot different types of graphs using PyPlot.
#Bar Chart

import matplotlib.pyplot as plt
# x-coordinates of left sides of bars
left = [1, 2, 3, 4, 5]
# heights of bars
height = [10, 24, 36, 40, 5]
# labels for bars
tick_label = ['one', 'two', 'three', 'four', 'five']

# plotting a bar chart
plt.bar(left, height, tick_label = tick_label,width = 0.8, color = ['red', 'green'])
# naming the x-axis
plt.xlabel('x - axis') # naming the y-axis
plt.ylabel('y - axis') # plot title
plt.title(' College bar chart!')

# function to show the plot
plt.show()

Output-2:Bar Chart:



Program Code-3:Histogram:

#Lab-8-Learn to plot different types of graphs using PyPlot.
#Histogram
import matplotlib.pyplot as plt

# frequencies
ages = [2,5,70,40,30,45,50,45,43,40,44,
60,7,13,57,18,90,77,32,21,20,40]
# setting the ranges and no. of intervals
range = (0, 100)
bins = 10
# plotting a histogram
plt.hist(ages, bins, range, color = 'green',histtype = 'bar', rwidth = 0.8)

# x-axis label plt.xlabel('age')
# frequency label plt.ylabel('No. of people') # plot title
plt.title(' College histogram')
# function to show the plot
plt.show()

Output-3:Histogram:



Program Code-4:Pie-chart:

#Lab-8-Learn to plot different types of graphs using PyPlot.

#Pie-chart

import matplotlib.pyplot as plt

# defining labels

activities = ['eat', 'sleep', 'work', 'play']

# portion covered by each label

slices = [3, 7, 8, 6]

# color for each label

colors = ['r', 'y', 'g', 'b']

# plotting the pie chart

plt.pie(slices, labels = activities, colors=colors,startangle=90, shadow = True, explode = (0, 0, 0.1, 0),radius = 1.2, autopct = '%1.1f%%')

plt.title(' College Pie Chart')

plt.legend()

# showing the plot

plt.show()


Output-4:Pie-chart:



Python Program-7

(7) Develop chat room application using multithreading.

Program Code (Server Program):
#Lab-7
#AIM: Develop chat room application using multithreading.
#Server Program

import time, socket, sys
print('Setup Server...')
time.sleep(1)
#Get the hostname, IP Address from socket and set Port
soc = socket.socket()
host_name = socket.gethostname()
ip = socket.gethostbyname(host_name)
port = 1234
soc.bind((host_name, port))
print(host_name, '({})'.format(ip))
name = input('Enter name: ')
soc.listen(1) #Try to locate using socket
print('Waiting for incoming connections...')
connection, addr = soc.accept()
print("Received connection from ", addr[0], "(", addr[1], ")\n")
print('Connection Established. Connected From: {}, ({})'.format(addr[0], addr[0]))
#get a connection from client side
client_name = connection.recv(1024)
client_name = client_name.decode()
print(client_name + ' has connected.')
print('Press [bye] to leave the chat room')
connection.send(name.encode())
while True:
   message = input('Me > ')
   if message == '[bye]':
      message = 'Good Night...'
      connection.send(message.encode())
      print("\n")
      break
   connection.send(message.encode())
   message = connection.recv(1024)
   message = message.decode()
   print(client_name, '>', message)


Output (Server Program):



Program Code(Client Program):


#Lab-7
#AIM: Develop chat room application using multithreading.
#Client Program

import time, socket, sys
print('Client Server...')
time.sleep(1)
#Get the hostname, IP Address from socket and set Port
soc = socket.socket()
shost = socket.gethostname()
ip = socket.gethostbyname(shost)
#get information to connect with the server
print(shost, '({})'.format(ip))
server_host = input('Enter server\'s IP address:')
name = input('Enter Client\'s name: ')
port = 1234
print('Trying to connect to the server: {}, ({})'.format(server_host, port))
time.sleep(1)
soc.connect((server_host, port))
print("Connected...\n")
soc.send(name.encode())
server_name = soc.recv(1024)
server_name = server_name.decode()
print('{} has joined...'.format(server_name))
print('Enter [bye] to exit.')
while True:
   message = soc.recv(1024)
   message = message.decode()
   print(server_name, ">", message)
   message = input(str("Me > "))
   if message == "[bye]":
      message = "Leaving the Chat room"
      soc.send(message.encode())
      print("\n")
      break
   soc.send(message.encode())


Output (Client Program):


Python Program-6

(6) Develop programs to learn Regular Expressions using python.

1) match() function       2) search() function

3) compile() function     4) findall() function

5) split() function


Program Code-1:match() & search() method


#Lab-6. Develop programs to learn regular expressions(re) using python.
# A Program by USING re.match() method:

""
#import re #simple structure of re.match()
#matchObject = re.match(pattern, input_str, flags=0)
""
#!/usr/bin/python
import re

line = "Cats are smarter than dogs"

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

if matchObj:
   print ("matchObj.group() : ", matchObj.group())
   print ("matchObj.group(1) : ", matchObj.group(1))
   print ("matchObj.group(2) : ", matchObj.group(2))
else:
   print ("No match!!")



import re

pattern = '^ba...s$'
test_string = 'abyss'
result = re.match(pattern, test_string)

if result:
  print("Search is successful.")
else:
  print("Search is unsuccessful.")


#The search() function searches the string for a match, and
  #returns a Match object if there is a match.import re

txt = "The rain in Spain"
x = re.search("\s", txt)

print("The first white-space character is located in position:", x.start())

import re

txt = "The rain in Spain"
x = re.search("ai", txt)
print(x) #this will print an object

Output-1: match() & search() method


Program Code-2:compile() & findall() method

#Lab-6. Develop programs to learn regular expressions using python.
# A Program by USING re.compile() & re.findall() method:


import re
# compile() creates regular expression character class [a-e],
# which is equivalent to [abcde].
# class [abcde] will match with string with 'a', 'b', 'c', 'd', 'e'.
p = re.compile('[a-e]')
# findall() searches for the Regular Expression and return a list upon finding
print(p.findall("Hello my college is in surat gtu aicte"))

Output-2: compile() & findall() method



Program Code-3:compile() & findall() method

#Lab-6. Develop programs to learn regular expressions using python.
# A Program by USING re.compile() & re.findall() method:

import re
# \d is equivalent to [0-9].
p = re.compile('\d')
print(p.findall("I went to him at 11 A.M. on 4th July 1886"))
# \d+ will match a group on [0-9], group of one or greater size
p = re.compile('\d+')
print(p.findall("I went to him at 11 A.M. on 4th July 1886"))


Output-3: compile() & findall() method

Thursday, 9 April 2020

Python Program-5

(5) Develop programs for data structure algorithms using python   

1) Searching Algorithms, A) Linear Search,  B) Binary Search 


2) Sorting Algorithms, A)Selection Sort, B)Bubble Sort,  C)Insertion Sort, D)Merge Sort, E)Quick Sort,

3) Hash Tables A)Accessing Values B) Updating Values C)Delete Dictionary Elements


Program Code -1A: Linear Search Algorithm program


#Lab-5-Searching
# linear_search program

def linear_search(alist, key):
    """Return index of key in alist. Return -1 if key not present."""
    for i in range(len(alist)):
        if alist[i] == key:
            return i
    return -1


alist = input('Enter the list of numbers: ')
alist = alist.split()
alist = [int(x) for x in alist]
key = int(input('The number to search for: '))

index = linear_search(alist, key)
if index < 0:
    print('{} was not found.'.format(key))
else:
    print('{} was found at index {}.'.format(key, index))


Output-1A:Linear Search Algorithm program






Program Code-1B:binary Search Algorithm program

#Python program to implement binary search without using recursion.
    #The program output is shown below.

def binary_search(alist, key):
    """Search key in alist[start... end - 1]."""
    start = 0
    end = len(alist)
    while start < end:
        mid = (start + end)//2
        if alist[mid] > key:
            end = mid
        elif alist[mid] < key:
            start = mid + 1
        else:
            return mid
    return -1


alist = input('Enter the sorted list of numbers: ')
alist = alist.split()
alist = [int(x) for x in alist]
key = int(input('The number to search for: '))

index = binary_search(alist, key)
if index < 0:
    print('{} was not found.'.format(key))
else:
    print('{} was found at index {}.'.format(key, index))



Output-1B:binary Search Algorithm program




Program Code-2A: Bubble Sort


#Lab-5-Python program to implement bubble_sort
#bubble_sort program
def bubble_sort(alist):
    for i in range(len(alist) - 1, 0, -1):
        no_swap = True
        for j in range(0, i):
            if alist[j + 1] < alist[j]:
                alist[j], alist[j + 1] = alist[j + 1], alist[j]
                no_swap = False
        if no_swap:
            return


alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
bubble_sort(alist)
print('Sorted list: ', end='')

print(alist)



Output-2A: Bubble Sort







Program Code-2B: Quick Sort



#Lab-5-Python program to implement quicksort.
#quick sort program
def quicksort(alist, start, end):
    '''Sorts the list from indexes start to end - 1 inclusive.'''
    if end - start > 1:
        p = partition(alist, start, end)
        quicksort(alist, start, p)
        quicksort(alist, p + 1, end)


def partition(alist, start, end):
    pivot = alist[start]
    i = start + 1
    j = end - 1

    while True:
        while (i <= j and alist[i] <= pivot):
            i = i + 1
        while (i <= j and alist[j] >= pivot):
            j = j - 1

        if i <= j:
            alist[i], alist[j] = alist[j], alist[i]
        else:
            alist[start], alist[j] = alist[j], alist[start]
            return j


alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
quicksort(alist, 0, len(alist))
print('Sorted list: ', end='')

print(alist)



Output-2B: Quick Sort







Program Code-2C: Merge Sort


#Lab-5-Python program to implement mergesort.
#Merge sort program

def merge_sort(alist, start, end):
    '''Sorts the list from indexes start to end - 1 inclusive.'''
    if end - start > 1:
        mid = (start + end)//2
        merge_sort(alist, start, mid)
        merge_sort(alist, mid, end)
        merge_list(alist, start, mid, end)

def merge_list(alist, start, mid, end):
    left = alist[start:mid]
    right = alist[mid:end]
    k = start
    i = 0
    j = 0
    while (start + i < mid and mid + j < end):
        if (left[i] <= right[j]):
            alist[k] = left[i]
            i = i + 1
        else:
            alist[k] = right[j]
            j = j + 1
        k = k + 1
    if start + i < mid:
        while k < end:
            alist[k] = left[i]
            i = i + 1
            k = k + 1
    else:
        while k < end:
            alist[k] = right[j]
            j = j + 1
            k = k + 1


alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
merge_sort(alist, 0, len(alist))
print('Sorted list: ', end='')

print(alist)



Output-2C: Merge Sort








Program Code-2D: insertion Sort



#Lab-5-Python program to implement insertion_sort.
#insertion_sort program

def insertion_sort(alist):
    for i in range(1, len(alist)):
        temp = alist[i]
        j = i - 1
        while (j >= 0 and temp < alist[j]):
            alist[j + 1] = alist[j]
            j = j - 1
        alist[j + 1] = temp


alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
insertion_sort(alist)
print('Sorted list: ', end='')

print(alist)



Output-2D: insertion Sort










Program Code-2E: Selection Sort



#Lab-5-Python program to implement selection_sort.
#selection_sort program
def selection_sort(alist):
    for i in range(0, len(alist) - 1):
        smallest = i
        for j in range(i + 1, len(alist)):
            if alist[j] < alist[smallest]:
                smallest = j
        alist[i], alist[smallest] = alist[smallest], alist[i]


alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
selection_sort(alist)
print('Sorted list: ', end='')

print(alist)



Output-2E: Selection Sort






Program Code -3A: Hash Table(Accessing Values)

dict = {'Name': 'Zara', 'Age': 7,
'Class': 'First'}

# Accessing the dictionary with its key
print ("dict['Name']:
", dict['Name'])
print ("dict['Age']: ", dict['Age'])


Output-3A: Hash Table(Accessing Values)

 

Program Code -3B: Hash Table(Updating)

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} dict['Age'] = 8;
# update existing entry
dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']


Output-3B: Hash Table(Updating)

Program Code -3C: Hash TableLinear(Delete Dictionary Elements)

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary

print ("dict['Age']: ", dict['Age'])

print ("dict['School']: ", dict['School'])

Output-3C: Hash TableLinear(Delete Dictionary Elements)

Python Program-4

(4) Develop programs to understand working of 
1) Exception Handling and 
2) Assertions.


Program Code:
#Lab-4-Exception Handling
try:
  a = int(input("Enter a:"))
  b = int(input("Enter b:"))
  c = a/b;
  print("a/b = %d"%c)
except Exception:
  print("can't divide by zero")
else:
  print("Hi I am else block")

Output-1:

Output-2:



########################################################################

#The assert Statement
#When it encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true.
   #If the expression is false, Python raises an AssertionError exception.

#!/usr/bin/python

def KelvinToFahrenheit(Temperature):
   assert (Temperature >= 0),  "Colder than absolute zero!"
   return ((Temperature-273)*1.8)+32

print (KelvinToFahrenheit(273))
print (int(KelvinToFahrenheit(505.78)))
print (KelvinToFahrenheit(-5))


Output:

Python Program-3

(3) Develop programs to learn concept of
1) Functions Scoping, 2) An example of a Recursive Function to find the factorial of a number and3) List Mutability: A) Copying Mutable Objects by Reference B) Copying Immutable Objects C) Immutable Object Changing Its Value


Program Code:

# LAB-3   function scoping
a='string (Global)'   #global
def func1():
    a='string within the function (Local)' #local
    print("print from func1:",a)
func1()
#here variable a within a the function is printed
print("print from outside:",a)


#while here, variable outside the function is printed
def func2():
    global b 
    b = "global string"
func2()
print("print from outside:", b)
#this is possible because string is declared global
print()




#recursion
# An example of a recursive function to  # find the factorial of a number

def calc_factorial(x):
    """This is a recursive function
    to find the factorial of an integer"""

    if x == 1:
        return 1
    else:
        return (x * calc_factorial(x-1))

num = 5
print("The factorial of", num, "is=", calc_factorial(num))




#Lab-3
#Copying Mutable Objects by Reference

values = [4, 5, 6]
values2 = values
print("Memory Address=",id(values))
print("Memory Address=",id(values2))

values.append(7)
print(values is values2)
print(values)
print(values2)

#Copying Immutable Objects
text = "Python"
text2 = text
print("Memory Address=",id(text))
print("Memory Address=",id(text2))
print(text is text2)
print()

text += " is awesome"
print("Memory Address=",id(text))
print("Memory Address=",id(text2))
print(text is text2)
print()

print(text)
print(text2)


#Immutable Object Changing Its Value

skills = ["Programming", "PRIME", "GTU"]
person = (129392130, skills)
print(type(person))
print(person)

skills[2] = "Maths"

print(person)


Output: