Professional Documents
Culture Documents
I YEAR / II SEMESTER
LABORATORY
Submitted by
REG NO:
Aim: To implement a python program to convert the temperature given in Celsius into
Fahrenheit.
Algorithm:
Step1: Start
Step2: Enter the temperature in Celsius
Step3: Calculate Fahrenheit using the formula
f=c*1.8+32
Step4: Print Fahrenheit
Step5: Stop
Flow Chart:
Start
Enter Celsius,c
Fahrenheit f=c*1.8+32
Print
Fahrenheit f f
Stop
Program:
Output:
Enter the Celsius 37.6
Fahrenheit=99.68
Result:
Thus Python program to convert Celsius to Fahrenheit temperature is executed and output is
verified.
Exp. No 2. To Find the square root of a number (Newton‘s method)
Date:
Aim: To implement a python program to find the square root of a number using Newton’s
method.
Algorithm:
Step1: Start
Step2: Enter the number for which square root is to be calculated, n
Step3: Enter the guess number which may be the square root of the number, x
Step4: Compute new_x=1/2(x+n/x) , Newton’s formula to find the new guess
Step 5: Compute new_x=1/2(x+n/new_x) till the approximate square root is found,
Step6: Print the square root new_n
Step7: Stop
Flow Chart:
Start
new_x=0.5*(x+(n/x))
Print new_x
F
for i in
range(0,10)
T
new_x=0.5*(new_x+
(n/new_x))
Print new_x
Stop
Program:
n=float(input("What number you like to square root?"))
x=float(input("Enter your guess number:"))
print(“Square root Approximation:”)
new_x=0.5*(x+(n/x))
print(new_x)
for i in range(0,10):
new_x=0.5*(new_x+(n/new_x))
print(new_x)
Output:
What number you like to squareroot?12
Enter your guess number:7
Square root Approximation:
4.357142857142857
3.5556206088992974
3.465279430087719
3.4641018153017074
3.4641016151377606
3.4641016151377544
3.4641016151377544
3.4641016151377544
3.4641016151377544
3.4641016151377544
3.4641016151377544
Result:
Thus Python program to find the square root of a number using Newton method is executed and
output is verified.
Exp. No 3. Exponentiation of a number
Date:
Aim: To implement a Python program to calculate the exponentiation of number using exponent
operator.
Algorithm:
Step1. Start
Step2. Enter the value of a and b(to the power of a)
Step3.Multiply a and b using exponent (**) operator
Step4. Store the value into c
Step5.Print c
Step6. Stop
Flow chart:
Start
c=a**b
Print c
Stop
Program:
Output:
Result :
Thus a Python program to calculate the exponentiation of number using exponent operator is
implemented.
Exp. No 4. Distance between two points
Date:
Aim: To implement a Python program to find the distance between two points .
Algorithm:
Step1. Start
Step2. Enter the value of x1 and x2
Step3.Enter the value of y1 and y2
Step4. Use formula ((((x2-x1)**2)+((y2-y1)**2))**0.5) and store the result into d
Step5.Print d
Step6. Stop
Start
d= (((x2-x1)**2)+((y2-y1)**2))**0.5
Print d
Stop
Program:
Output:
enter the number:4
enter the number:2
enter the number:1
enter the number:1
Result :
Thus a Python program to find the distance between two points is implemented.
Exp. No 5. Finding polynomial coefficients
Date:
Algorithm:
Step1. Start
Step2. Define the function ‘poly’
2.1. Assign the values 0 to sum and list to xp
2.2. Iterate the list with the iterator variable ‘a’
2.2.1. Calculate sum=sum+a*xp
2.2.2. caompute xp=x+xp
2.2.3. Return the sum value
Step 3. Do function call
Step 4. Stop
Start
Flow chart:
Call poly(l,x)
Sum=0; xp=l
F
For a times
T
Sum=sum+a*xp
Xp=x+xp
Stop
Program:
Output:
9
91
Aim: To implement a Python program to find whether a given year is leap or not.
Algorithm:
Step1. Start
Step2. Enter the year
Step3. Check the condition (year%4 and year%100!=0 or year%400)
3.1.If the condition is satisfied, then print the given year is leap
3.2. Otherwise, print the given year is not leap
Step4. Stop
Start
True
Stop
Program:
Output:
Result:
Thus a Python program to find the given year is leap or not is implemented.
Exp. No 7. To Exchange the values of two variables
Date:
Algorithm:
Step 1: Start
Step 2: Read the values of a and b.
Step 3:compute a=a+b
b=a-b
a=a-b
Step 4: Print the values of a and b
Step 5: Stop
Flow Chart:
Start
Read a,b
a=a+b
b=a-b
a=a-b
Print a,b
Stop
Program:
Output :
Result:
Thus Python program to exchange the values of two variables is implemented.
Exp. No 8. To Circulate the values of n variables
Date:
Algorithm:
Step 2: Perform
temp=a
a=b
b=c
c=temp
Step 3: Print the values of a,b,c
Flowchart:
Start
Read a,b,c
temp=a
a=b
b=c
c=temp
Print a,b,c
Stop
Program:
Output:
Enter the value for A:10
Enter the value for B:20
Enter the value for C:30
The Circulated values of A,B and C is: 20 30 10
Algorithm:
Flowchart:
Start
Read x,y
F
Whil
e y!
=0
T
x , y = x%y , y
Print x
Stop
Program:
while b!=0:
a,b=b,a%b
print(a,b)
Output:
Result: Thus Python program to find the GCD of two numbers is implemented.
Exp. No 10. Towers of Hanoi
Date:
Aim: To implement a Python program to move discs from source pole to destination pole using
recursive function.
Algorithm:
Step 1. Start
Step 2. Read number of discs N
Step 3. If N=1 Move Single disc from source to dest .
Step 4. Move n-1 disks from source to aux
Step 5. Move nth disk from source to dest.
Step 6. Move n-1 disks from aux to dest.
Step 7. Stop
Flowchart:
Program:
if height >= 1:
moveTower(height-1,fromPole,withPole,toPole)
moveDisk(fromPole,toPole)
moveTower(height-1,withPole,toPole,fromPole)
def moveDisk(fp,tp):
moveTower(3,"A","B","C")
Output:
moving disk from A to B
moving disk from A to C
moving disk from B to C
moving disk from A to B
moving disk from C to A
moving disk from C to B
moving disk from A to B
Result:
Thus Python program to move discs from source pole to destination pole using recursive
function is implemented successfully.
Exp. No 11. Factorial of a Number
Date:
Algorithm:
Step 1. Start
Step 2. Read the number n
Step 3. Initialize i=1, fact=1
Step 4. Repeat the following until i=n
4.1. fact=fact*i
4.2. i=i+1
Step 5. Print fact
Step 6. Stop Start
Flowchart:
Read
N
i = 1 fact=
1
1 *
factF == fact
i
F
i=i+1 is i=N ?
T
Print
fact
Stop
Program:
Output:
Result:
Thus Python program to find factorial of a given number is implemented successfully.
Exp. No 12. To Reverse a given Number
Date:
Algorithm:
Step 1.Start
Step 2.Read Input number: n
Step 3.Initialize rev = 0
Step 3.Loop while n> 0
3.1.divide n by 10 and store the remainder in dig
3.2.rev = rev*10 + dig;
3.3.Divide n by 10
Step 4.Print rev
Step 5.Stop
Flowchart:
Star
t
Read
N
rev=0
is N >
0?
F T
dig = N%10
rev = rev*10 +
dig
N = N/10
Print rev
Sto
p
Program:
Output:
Result: Thus Python program to find reverse of a given number is implemented successfully.
Exp. No.13. To print all Prime Numbers in an Interval of Numbers
Date:
Aim : To implement Python program to print all prime numbers in an interval of numbers.
Algorithm:
Step 1. Start
Step 2. Enter the lower interval and upper interval
Step 3. Repeat step 3.1and step 3.2 for each integer num in the lower to upper interval
Step 3.1.If num % any interger i in interval is equal to zero then num is not prime
Step 3.2.else Print the num value as prime and repeat from step 3 for next value in
interval
Step4.Stop
Flow Chart:
Start
F
for num in range
(lower,upper+1)
and (num>1)
Print num T
F T i in
for
range(2,num)
T
If num F
Stop
Program:
Output :
Result : Thus Python program to print all prime numbers between an interval of numbers is
implemented.
Exp.No.14. To Print Pascal’s triangle for n number of rows
Date:
Aim : To implement a Python Program to print the pascal’s triangle for n number of rows .
Algorithm:
Step1. Start
Step 2. Read no.of rows n
Step 3. Initialize list trow=[1],y=[0]
Step 4. Repeat step 4.1 and 4.2 n no. of times
Step 4.1. Print trow
Step 4.2. List trow is re-created by adding elements of trow+y and y+trow using zip
function
Step 5. Stop
Flow Chart:
Start
for n times
Print trow
Sto
Program:
def pascal_triangle(n):
trow = [1]
y = [0]
for x in range(max(n,0)):
print(trow)
trow=[l+r for l,r in zip(trow+y, y+trow)]
return n>=1
pascal_triangle(6)
Output :
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
Result : Thus Python Program to print the pascal’s triangle for n number of rows is
implemented.
Exp. No.15. To Check if a String is a Palindrome
Date:
Algorithm:
Step 1. Start
Step 2. Read string s
Step 3. String s is compared with its reverse using string slicing
Step 3.1. If both are equal, print the string is a palindrome
Step 3.2.else print the string is not a palindrome
Step 4. Stop
Flow Chart:
Start
Read String
s
If (str = =
str[::-1])
Stop
Program:
string=input("Enter string:")
if(string==string[: : -1]):
print("The string is a palindrome")
else:
print("The string isn't a palindrome")
Output:
Case 1:
Enter string:mam
The string is a palindrome
Case 2:
Enter string:hello
The string isn't a palindrome
Aim: To implement a Python Program to calculate the number of Words and Characters present
in a String
Algorithm:
Step 1. Start
Step 2. Read string s
Step 3. Initialize the character count variable = 0 and word count variable = 1.
Step 4. Traverse through the string s and Repeat steps 4.1 and 4.2 for each character in the string
Step 4.1.Increment character count variable each time.
Step 4.2. Increment the word count variable only if a space is encountered.
Step 5. Print the total count of the characters and words in the string.
Step 6. Stop
Flow Chart:
Start
Read string s
F
for each
character
Stop i in s
char = char+1
F T
If i is space
word = word+1
Program:
string=input("Enter string:")
char=0
word=1
for i in string:
char=char+1
if ( i == ' '):
word=word+1
print("Number of words in the string:")
print(word)
print("Number of characters in the string:")
print(char)
Output:
Result : Thus a Python program to calculate the number of Words and Characters present in a
String is implemented.
Ex.No.17. To Count the number of Vowels in a String
Date:
Algorithm:
Step 1: Start
Step 2: Read string s.
Step 3: Initialize a count = 0.
Step 4: for each character in the string s.
Step 5: if character = vowel increment count else go to step 4
Step 6: Print the total number of vowels in the string.
Step 7: Stop
Flow chart:
Start
Read string s
F
For i through
Initialize each
count=0
character in string s
If i is a
vowels
F
T
vowel = vowel +1
Program:
string=raw_input("Enter string:")
vowel=0
for i in string:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or
i=='U'):
vowel = vowel +1
print("Number of vowels are:")
print(vowel)
Output:
Result : Thus a Python program to Count the number of Vowels in a String is implemented.
Exp. No 18. To Sum an array of numbers and determine its Average
Date:
Aim : To implement a Python program to determine the sum and average of numbers in an array
using list.
Algorithm:
Step1. Start
Step 5. Divide the sum by total number of elements in the list to find average
Step7.Stop
For n
times in
List
Input the elements of the list
Stop
Program:
Output :
Result : Thus a Python program to determine the sum and average of numbers in an array using
list is implemented.
Ex.No.19. Finding maximum from a list of numbers
Date:
Aim: To write a Python Program to find the maximum from a list of numbers.
Algorithm:
Step 1.Start
Step 2.Creating a list with some values
Step 3. Assign the first value of the list as the maximum.
Step 4. Iterate or repeat steps 4.1 and 4.2 up to length of the list
4.1.Compare the current element in the list with maximum element
4.2. If the element is greater than the maximum, then set that element as maximum.
Step 5.Display the maximum element in the list.
Step 6.Stop
Flowchart:
Program:
l=[3,10,2,15,2]
max=l[0]
for i in range(len(l)):
if(l[i]>max):
max=l[i]
Output:
Result:
Thus a Python program to determine the maximum number from a list is implemented.
Exp.No.20. To Insert a Card using a List
Date:
Algorithm:
Step 1. Start
Step 2. Read list A, value , index
Step 3. Sort list A
Step 4. Insert value in the index position of list
Step 5. Print list A
Step 6. Stop
Flow Chart:
Start
Sort list A
Print list A
Sto
Program:
Output :
Enter list = [10, 2, 3, 4]
Enter index were to insert=1
Enter value to be insert=11
[10, 11, 2, 3, 4]
Algorithm:
Step 1. Start
Step 2. Read list A and guessed number
Step 3. If number in list A print the guessed number is in list
Step 4. Else print the guessed number is not in list A
Step 5. Stop
Flow Chart:
Start
F
If
number
in list A
Print guessed
T number is not in
list
Print guessed
number is in list
Sto
p
Program:
A = list(range(1, 10))
number = int(input('Enter a number='))
if number in A:
print(‘Guessed number’,number, ‘is in list’, list(range(1, 10)))
else:
print(‘Guessed number’,number, ‘ is not in list’, list(range(1, 10)))
Output :
Enter a number= 6
Guessed number 6 is in list [1, 2, 3, 4, 5, 6, 7, 8, 9]
Algorithm:
Step 1. Start
Step 2. Read matrix a and b as nested list
Step 3. Find dimension of matrix a (m1 x n1) and b (m2 x n2)
Step 4.if n1 = m2 then
Step 4.1. Create result matrix of dimension (m1 x n2) using list comprehension
Step 4.2. for i traversing through rows of matrix a
Step 4.2.1 for j traversing through column of matrix b
Step 4.2.1.1 for k incremented till n1
Step 4.2.1.1.1 result[i][j] + = a[i][k] * b[k][j]
Step 5. Print result matrix
Step 6. Stop
Flow Chart:
Start
if n1 =
m2
F T
F
for i through
rows of matrix
a
T
F
for j through
column of matrix
b
T
F
for k
incremented till
n1
T
result[i][j]+=m1[i][k]*m2[k][j]
Print cannot
multiply matrices Print
result
matrix
Stop
Program:
Output :
Aim: To implement a Python program to search an element in a list using linear search.
Algorithm:
Step 4.For i = every element of list l until the end of the list
Step 5. Otherwise if end of list, print value is not found in the list.
Step 6.Stop
Flow Chart:
Start
For element i in F
List l
Stop
Program:
l=eval(input(“Enter list:”))
value=int(input(“Enter the value to be searched:”))
for i in l:
if i==value:
print(value,"is found in the list")
break
else:
print(value,"is Ft found in the list")
Output :
Result : Thus a Python program to search an element in a list using linear search is
implemented.
Exp. No. 24. Binary Search
Date:
Aim : To implement a Python program to search an element in a list using binary search.
Algorithm:
Step1. Start
Step 4.3.1 Perform a binary search of the left half of the original list repeating
Step 4.4 Else Perform a binary search of the right half of the original list repeating from
Step 6: Stop
Flow Chart:
Start
Initialize first =0
found =False
last=len(list)-1
While F
(first<=last and
found =False)
F If
T
item_list[mid]=
=item
T if F
item<item_list[mi
d]
Print found
Program:
Stop
def binary_search(item_list,item):
first=0
last=len(item_list)-1
found=False
while(first<=last and Ft found):
mid=(first+last)//2
if item_list[mid]==item:
found=True
else:
if item<item_list[mid]:
last=mid-1
else:
first=mid+1
return found
print(binary_search([1,2,3,5,8],6))
print(binary_search([1,2,3,5,8],5))
Output :
False
True
Result :Thus a Python program to search an element using binary search is implemented.
Ex.No.25. Selection Sort
Date:
Aim:To implement Python program for sorting a lit using selection sort.
Algorithm:
Step3.Input the elements in the list with input() and append() method for n no.of times
Step5.Print list A
Step6.Stop
Flowchart:
Start
F
for i in
range(
n)
T
Append a to A
F
for i in of length
of elements in list
A
T
min_idx=j
F
for j in
range(i+1,len(
A))
T
F
If
A[min_idx]>A[j]
T
min_idx=j
A[i],A[min_idx]=A[min_idx],A[i]
Stop
Program:
A=[ ]
n=int(input())
for i in range(n)
a=int(input())
A.append(a)
Print(*****Selection Sort******)
for i in range(len(A))
min_idx=i
for j in range(i+1,len(A))
if(A[min_idx]>A[j]):
min_idx=j
Output:
Result: Thus Python program to sort a list using selection sort is implemented.
Ex.No.26. Insertion Sort
Date:
Aim:To implement Python program for sorting a lit using insertion sort.
Algorithm:
Step1.Start
Step 3.2.Repeat steps3.2.1 and 3.2.1 until l[pos ] < l[pos-1] and pos > 0
Step5.Stop
Flowchart:
Start
F
for i in of length
of elements in list
A
pos=i
F
While l[pos ] <
l[pos-1] and pos > 0
l[pos],l[pos-1]=l[pos-1],l[pos]
pos=i
Stop
Program:
for i in range(1,len(l)):
pos=i
pos=pos - 1
insertion_sort(list)
Output:
Result: Thus Python program to sort a list using insertion sort is implemented.
Ex. No.27. Merge Sort
Date:
Aim: To implement a python program for sorting a list using Merge sort.
Algorithm:
2.2.4. return(merge(a,b))
5.2.1. if (a[0]<b[0])
5.2.2. if (a[0]>b[0])
5.3: Return c
Flowchart
Start
Input list x
def divide(x)
No
If
(len(x)==1
Yes
Return x
mid=len(x)//2
a=divide(x[:mid])
b=divide(x[mid:])
return(merge(a,b))
def merge(a,b)
B
A
A
B
No
while (len(a)!=0 and
len(b)!=0)
Yes
No
if (a[0]<b[0]):
Yes
c.append(a[0]) c.append(b[0])
a.remove(a[0]) a.remove(b[0])
if (len(a)!=0):
Yes No
c=c+a c=c+b
Return(c)
Program:
def divide(x):
if(len(x)==1):
return(x)
else:
mid=len(x)//2
a=divide(x[:mid])
b=divide(x[mid:])
return(merge(a,b))
def merge(a,b):
c=[]
while (len(a)!=0 and len(b)!=0):
if (a[0]<b[0]):
c.append(a[0])
a.remove(a[0])
else:
c.append(b[0])
b.remove(b[0])
if (len(a)!=0):
c=c+a
else:
c=c+b
return(c)
print(divide([5,3,7,1]))
Output:
[1,3,5,7]
Result: Thus Python program is implemented for sorting a list using Merge sort.
Exp. No 28. Graph
Date:
Algorithm:
Program :
LINE GRAPH
import matplotlib.pyplot as plt
x = [1,2,3]
y = [2,4,1]
plt.plot(x, y)
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.title('My first graph!')
plt.show()
Output :
Step 1 Frequencies are passed as the ages list to plt.hist() function to plot a histogram.
Step 2 Range could be set by defining a tuple containing min and max value.
Step 3 To divide the entire range of values into a series of intervals is to “bin” the range
of values
Step 4 Finally, to view the plot show() function is used
HISTOGRAM
import matplotlib.pyplot as plt
ages = [2,5,70,40,30,45,50,45,43,40,44,60,7,13,57,18,90,77,32,21,20,40]
range = (0, 100)
bins = 10
plt.hist(ages, bins, range, color = 'green',histtype = 'bar', rwidth = 0.8)
plt.xlabel('age')
plt.ylabel('No. of people')
plt.title('My histogram')
plt.show()
Output :
Result: Thus Python program to create Line graph and Histogram are implemented successfully.
Exp. No 29. Python Program That Takes Command Line Argument
(Word Count)
Date:
Aim: To write a python program that takes command line argument (word count)
Algorithm:
Step 1 Start
Step 2 Open python IDLE and open the script mode
Step 3 Import Sys package using import command
Step 4 Assign sys.argv[1], which contains the filename, to filename variable ‘filename’
Step 5 Open the filename object ‘f’
a. Read the contents of file and store them in a string variable
Step 6 Using list comprehension in python, create a list containing words and their count as
pairs
Step 7 Print the word and word count
Step 8 Stop
Start
Stop
Program:
import sys
filename = sys.argv[1]
f = open(filename)
wordcount ={}
passage = f.read()
for w in passage.split():
if word not in wordcount:
wordcount [w] = 1
else:
wordcount[w]+=1
print(wordcount)
f.close()
Output:
TextFile.txt
Python is a high level programming
language.
Result: Thus Python program that takes command line argument (word count) is implemented
successfully.
Exp. No 30. Python Program to find the Most Frequent Word in a
Text: Read from a File
Date:
Aim: To write a python program to find the most frequent word in a text: read from a file
Algorithm:
Step 1.Start
Step 2 Open python IDLE and open the script mode
Step 3 Open the file name to read the text
a. Read the contents of file and store them in a string variable
Step 4 Using list comprehension in python, create a list containing words as keys and their count
as values as pairs
Step 5 Convert the list to dictionary
Step 6 Using the max() function find the most frequent (word and count) pair from dictionary
Step 7 Print the most frequent word
Step 8 Stop
Flow Chart
Start
Get all the unique words from the file using list comprehension in python,
create a list containing words as keys and their count as values as pairs
Convert the list to dictionary
Stop
f = open(‘TextFile’,’r’)
wordcount ={}
passage = f.read()
wordcount ={}
for w in passage.split():
if w not in wordcount:
wordcount [w] = 1
else:
wordcount[w]+=1
print(wordcount)
print("Max Count is")
lcount= wordcount.values()
m = max(lcount)
for i in wordcount:
if(m == wordcount[i]):
print(i," = is Present ",m," times")
Output
TextFile.txt
is = is Present 2 times
Result:
Thus Python Program to find the Most Frequent Word in a Text: Read from a File has
been implemented successfully.
Aim:
To write a Python program to copy file
Algorithm:
Step 1 Start
Step 2 Open the file from which the contents needs to copied in read mode, let it be ‘in’ file
Step 3 Open the file on which the content to copied in write mode, let it be out file
Step 4 Read line by line from the file opened in read mode(from ‘in’ file)
Step 5 Using the write function, write line by line to the file opened in write mode(the ‘out’ file)
Step 6 Print the message “Successfully Completed” after the write function completion.
Step 7 Stop
Flowchart:
Start
Program:
Stop
a = open("TextFile.txt",”r+”)
b = open("out.txt", "w")
for line in a:
b.write(line)
a.close()
b.close()
print(“Successfully Copied a.txt to b.txt file”)
Output:
TextFile.txt Out.txt
The Hello World is a sample program The Hello World is a sample program
that explains primitive concepts. that explains primitive concepts.
Python is a high level programming Python is a high level programming
language language
Result:
Thus Python program to copy file has been implemented successfully.
Program :
try:
print(x) # NameError
except NameError:
print("Variable x is not defined")
try:
a = [1, 2, 3]
print ("Fourth element =" ,a[3]) #IndexError
except IndexError:
print("Throws error since there are only 3 elements in array")
try:
geek = "Python ver"
num = 10
print(geek + num + geek)
except:
print("String type cannot be concatenated with Integer")
try:
b=c=3.0
d = ((b+c) / (b-c)) #ZeroDivisionError
except ZeroDivisionError:
print ("b/c result in 0")
Output :
Result: Thus Python program to handle exceptions has been implemented successfully.
Algorithm:
Program:
from numpy import linalg
from numpy import linspace
import numpy as np
from numpy import meshgrid
import random
import matplotlib.pyplot as plt
from scipy import optimize
from sympy import *
xs = [1.02, 0.95, 0.87, 0.77, 0.67, 0.56, 0.44, 0.30, 0.16, 0.01]
ys = [0.39, 0.32, 0.27, 0.22, 0.18, 0.15, 0.13, 0.12, 0.12, 0.15]
b = [i ** 2 for i in xs]
def fxn(x, y): # That is the function that solves the given equation to find each parameter.
my_list = [] #It is the main list.
for z in range(len(x)):
w = [0] * 5
w[0] = y[z] ** 2
w[1] = x[z] * y[z]
w[2] = x[z]
w[3] = y[z]
w[4] = 1
my_list.append(w)
return my_list
t = linalg.lstsq(fxn(xs, ys), b)
def ysolv(coeffs):
x,y,a,b,c,d,e = symbols('x y a b c d e')
ellipse = a*y**2 + b*x*y + c*x + d*y + e - x**2
y_sols = solve(ellipse, y)
print(*y_sols, sep='\n')
num_coefs = [(a, f) for a, f in (zip([a,b,c,d,e], coeffs))]
y_solsf0 = y_sols[0].subs(num_coefs)
y_solsf1 = y_sols[1].subs(num_coefs)
f0 = lambdify([x], y_solsf0)
f1 = lambdify([x], y_solsf1)
return f0, f1
f0, f1 = ysolv(t[0])
y0 = [f0(x) for x in xs]
y1 = [f1(x) for x in xs]
plt.scatter(xs, ys)
plt.scatter(xs, y0, s=100, color = 'red', marker='+')
plt.scatter(xs, y1, s=100, color = 'green', marker='+')
plt.show()
Output:
Result: Thus Python program to Simulate elliptical orbits in Pygame has been implemented
successfully.
Algorithm:
Program :
import pygame
pygame.init()
window_w = 800
window_h = 600
white = (255, 255, 255)
black = (0, 0, 0)
FPS = 120
window = pygame.display.set_mode((window_w, window_h))
pygame.display.set_caption("Bouncing Ball 2D ")
clock = pygame.time.Clock()
def game_loop():
block_size = 20
velocity = [1, 1]
pos_x = window_w/2
pos_y = window_h/2
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
pos_x += velocity[0]
pos_y += velocity[1]
if pos_x + block_size > window_w or pos_x < 0:
velocity[0] = -velocity[0]
Output:
Result: Thus Python program to simulate bouncing ball using pygame is implemented
successfully.
Exp. No. 35.GUI based python programs with Tkinter
Packages
Date:
Aim: To write a python program to perform GUI based python program using Tkinter package.
Algorithm:
Program:
Result:
Thus GUI based Python program using Tkinter package is implemented successfully.
Mini Project
ABSTRACT:
Rock paper scissors game is also known as stone paper scissors. It is a
hand game that is usually played between 2 people, each player can randomly
form any one of three from their hand. A player who chooses rock will win by
another player who chooses scissors but loose by the player who chooses
paper; a player with paper will lose by the player with the scissors.
If both players choose the same then the game is tied. Rock paper scissors game
is mainly played among kids.
OUTPUT CONCLUSION
Our research evaluated the behavior of human players against other human
opponents as well as computer probabilistic opponents in the RPS game. We
found that, regardless of playing with another human or an algorithm,
participants did not play the optimal strategy. In general, we did not observe a
conclusive win-stay/lose-change strategy for players, but, when humans played
with an algorithm, we observed that the win-stay strategy was common against
the WDLS computer strategy, and lose-change was also common against the
WSLU computer strategy. This suggests that participants are capable of learning
simple strategies when these can result in a clear advantage against their
opponent.