0% found this document useful (0 votes)
1 views

Applied Python Programming (Cycle-1)-1

The document provides various Python programming examples, including printing biodata, finding prime numbers, checking for perfect numbers, reading from files, and defining functions. It also covers matrix operations using NumPy, statistical analysis with SciPy, and string manipulation techniques. Overall, it serves as a comprehensive guide to basic Python programming concepts and functionalities.

Uploaded by

sravanipakala205
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Applied Python Programming (Cycle-1)-1

The document provides various Python programming examples, including printing biodata, finding prime numbers, checking for perfect numbers, reading from files, and defining functions. It also covers matrix operations using NumPy, statistical analysis with SciPy, and string manipulation techniques. Overall, it serves as a comprehensive guide to basic Python programming concepts and functionalities.

Uploaded by

sravanipakala205
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

2.

3.
4.
5.
6. INTRODUCING TO PYTHON3:

a) Printing your biodata on the screen.

print("Name:")
print("Gender:")
print("Date of Birth:")
print("Age:")
print("Address:")
print("Father Name:")
print("Mother Name:")
print("E-Mail Address:")
b) Printing all the primes less than a given number.

n= int(input("Please, Enter the Upper Range Value:"))


print ("The Prime Numbers in the range are:")
for number in range (2, n):
if number > 1:
for i in range (2, number):
if (number % i) == 0:
break
else:
print (number)
c) Finding all the factors of a number and show whether it is
a perfect number, i.e., the sum of all its factors (excluding the
number itself) is equal to the number itself.

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


sum_v=0
for i in range(1,num):
if (num%i==0):
sum_v=sum_v+i
if(sum_v==num):
print("The entered number is a perfect number")
else:
print("The entered number is not a perfect number")
7. DEFINING AND USING FUNCTIONS:

a) Write a function to read data from a file and display it on


the screen.
file1 = open("myfile.txt", "w")

L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]

file1.write("Hello \n")

file1.writelines(L)

file1.close()

file1 = open("myfile.txt", "r+")

print("Output of Read function is ")

print(file1.read())

print()

file1.seek(0)

print("Output of Readline function is ")

print(file1.readline())

print()
file1.seek(0)

print("Output of Read(9) function is ")

print(file1.read(9))

print()

file1.seek(0)

print("Output of Readline(9) function is ")

print(file1.readline(9))

print()

file1.seek(0)

print("Output of Readlines function is ")

print(file1.readlines())

print()

file1.close()

output
Output of Read function is
Hello
This is Delhi
This is Paris
This is London
Output of Readline function is
Hello
Output of Read(9) function is
Hello
Th

Output of Readline(9) function is


Hello

Output of Readlines function is


['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']
b) Define a boolean function is palindrome.

METHOD-1:
import math
def isPalindrome(num):
return int(num != 0) and ((num % 10) * (10**int(math.log(num, 10)))
+ isPalindrome(num // 10))

test_number = int (input("Enter any number :"))

print ("The original number is : ",(test_number))

res = test_number == isPalindrome(test_number)

print ("Is the number palindrome ? : ",res)

METHOD-2:
import math

def isPalindrome(num):
return int(num != 0) and ((num % 10) * (10 ** int(math.log(num, 10)))
+ isPalindrome(num // 10))

test_number = int(input("Enter any number: "))

print("The original number is: " + str(test_number))

res = test_number == isPalindrome(test_number)

print("Is the number palindrome?: " + str(res))


c) Write a function Collatz(x) which does the following: if x
is odd, x=3x+1; if x is even, then x=x/2. Return the number
of steps it takes for x=1.

def printCollatz(x):
while x != 1:
print(x,end=',')
if x & 1:
x = 3*x+1
else:
x=x//2
print(x)
printCollatz(6)

def printCollatz(x):
while x != 1:
print(x, end=',')
if x & 1: # Check if x is odd using bitwise AND
x = 3*x + 1
else: # If x is even
x = x // 2
print(x) # Print the final 1 when loop ends

# Function call (make sure it’s not indented!)


printCollatz(6)

printCollatz(6):
Step x Value Condition New x Value
1 6 Even 6 / 2 = 3
2 3 Odd 3*3+1 = 10
3 10 Even 10 / 2 = 5
4 5 Odd 3*5+1 = 16
5 16 Even 16 / 2 = 8
6 8 Even 8 / 2 = 4
7 4 Even 4 / 2 = 2
8 2 Even 2 / 2 = 1
6,3,10,5,16,8,4,2,1

d) Write a function N(m, s) = exp(-(x-m)2/(2s2))/sqrt(2π)s that


computes the Normal distribution.

import math
def solve(x,m):
s=1
result = math.exp(-((x-m)**2)/2*(s**s))/((2 * math.pi * s)**0.5)
return result
print(solve(4,2))

import math

# Function to calculate the Normal distribution


def solve(x, m, s=1): # Default standard deviation is 1
result = (1 / (math.sqrt(2 * math.pi * s**2))) * math.exp(-((x -
m)**2) / (2 * s**2)) import math

# Function to calculate the Normal distribution


def solve(x, m, s=1): # Default standard deviation is 1
result = (1 / (math.sqrt(2 * math.pi * s**2))) * math.exp(-((x -
m)**2) / (2 * s**2))
return result

# Example: Calculate Normal distribution for x=4, m=2, s=1


print(solve(4, 2))
return result

# Example: Calculate Normal distribution for x=4, m=2, s=1


print(solve(4, 2))
Explanation of Code:

math.sqrt(2 * math.pi * s**2): This part of the formula normalizes


the distribution.

math.exp(-((x - m)**2) / (2 * s**2)): This part applies the exponential


function for the distribution.

The function solve(x, m, s) computes the value of the Normal


distribution for the given values of x, m (mean), and s (standard
deviation). By default, the standard deviation s is set to 1 if not
provided.

0.05399096651318806
8. THE PACKAGE NUMPY:
a) Creating a matrix of given order mxn containing random
numbers in the range 1 to 99999.

import numpy as np
array = np.random.randint(low=1, high=99999, size=(2,2))
print(array)
array = np.random.randint(99999, size=(3,3))
print(array)

import numpy as np

# Create a 2x2 array with random integers between 1 and 99999


array1 = np.random.randint(low=1, high=99999, size=(2, 2))
print(array1)

# Create a 3x3 array with random integers between 0 and 99999


(inclusive)
array2 = np.random.randint(99999, size=(3, 3))
print(array2)

low=1: The lowest possible value in the array will be 1.

high=99999: The highest possible value will be 99999, but it will not
include 99999 itself.

size=(2, 2): This creates a 2x2 array (2 rows and 2 columns).

[[ 12345 67890]
[ 54321 98765]]

99999: Since no low value is given, it defaults to 0, and the random


integers will be between 0 and 99999 (inclusive).
size=(3, 3): This creates a 3x3 array (3 rows and 3 columns).

[[56312 18923 89327]


[ 45123 67239 25311]
[ 98391 74382 23412]]
b) Write a program that adds, subtracts and multiplies
two matrices.

METHOD-1:
matrix1 = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
matrix2 = [[5,8,1],
[6,7,3],
[4,5,9]]

res = [[0 for x in range(3)] for y in range(3)]

for i in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)):

res[i][j] += matrix1[i][k] * matrix2[k][j]

print (res)

METHOD-2:
import numpy as np

mat1 = ([1, 6, 5],[3 ,4, 8],[2, 12, 3])


mat2 = ([3, 4, 6],[5, 6, 7],[6,56, 7])

res = np.dot(mat1,mat2)

print(res)
c) Write a program to solve a system of n linear equations in
n variables using matrix inverse.

import numpy as np

A = np.array([[8, 3, -2], [-4, 7, 5], [3, 4, -12]])


b = np.array([9, 15, 35])
x = np.linalg.solve(A, b)

print(x)
9. THE PACKAGE SCIPY:
a) Finding if two sets of data have the same mean value.

from statistics import mean

from fractions import Fraction as fr

data1 = (11, 3, 4, 5, 7, 9, 2)
data2 = (-1, -2, -4, -7, -12, -19)
data3 = (-1, -13, -6, 4, 5, 19, 9)
data4 = (fr(1, 2), fr(44, 12), fr(10, 3), fr(2, 3))
data5 = {1:"one", 2:"two", 3:"three"}

print("Mean of data set 1 is % s" %


(mean(data1))) print("Mean of data set 2 is % s"
% (mean(data2))) print("Mean of data set 3 is %
s" % (mean(data3))) print("Mean of data set 4 is
% s" % (mean(data4))) print("Mean of data set 5
is % s" % (mean(data5)))
b) Plotting data read from a file.

METHOD-1:
import matplotlib.pyplot as plt
import csv

X = []
Y = []

with open("GFG.txt", 'r') as datafile:


plotting = csv.reader(datafile, delimiter=',')

for ROWS in plotting:


X.append(int(ROWS[0]))
Y.append(int(ROWS[1]))
plt.plot(X, Y)
plt.title('Line Graph using CSV')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()

METHOD-2:
import matplotlib.pyplot as plt
import numpy as np

X, Y = np.loadtxt("GFG.txt", delimiter=',', unpack=True)

plt.bar(X, Y)
plt.title('Line Graph using NUMPY')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
c) Fitting a function through a set of data points using polyfit
function.

METHOD-1:
import numpy as np
import matplotlib.pyplot as mp
np.random.seed(12)
x = np.linspace( 0, 1, 25 )
y = np.cos(x) + 0.3*np.random.rand(25)
p = np.poly1d( np.polyfit(x, y, 4) )
t = np.linspace(0, 1, 250)
mp.plot(x, y, 'o', t, p(t), '-')
mp.show()

METHOD-2:
import numpy as np
import matplotlib.pyplot as
mp np.random.seed(12)
x=np.linspace(-20,20,10)
y=2*x+5
coeff = np.polyfit(x,y,2)
xn = np.linspace(-20,20,100)
yn = np.poly1d(coeff)
mp.plot( xn,yn(xn),x,y,'o')
d) Plotting a histogram of a given data set.

from matplotlib import pyplot as plt


x=[300, 400, 500, 2000, 10]

plt.hist(x,10)

plt.show()
10.THE STRING PACKAGE:

a) Read text from a file and print the number of lines , words
and characters.

METHOD-1:
file = open("text.txt")
lines = 0
words = 0
symbols = 0

for line in file:


lines += 1
words += len(line.split())
symbols += len(line.strip('\n'))
print("Lines:", lines)
print("Words:", words)
print("Symbols:", symbols)

METHOD-2:

file = open(" text.txt")

lines = 0
words = 0
letters = 0

for line in file:


lines += 1

for symbol in line:


if symbol not in (' ', '\n', '\t'):
letters += 1

pos = 'out'
for symbol in line:
if symbol != ' ' and pos == 'out':
words += 1
pos = 'in'
elif symbol == '':
pos = 'out'

print("Lines:", lines)
print("Words:", words)
print("Letters:", letters)
b) Read text from a file and return a list of all n letter words
beginning with a vowel.

METHOD-1:
test_list = ["all", "love", "and", "get", "educated", "by", "gfg"]

print("The original list is : " + str(test_list))

res = []
vow = "aeiou"
for sub in test_list:
flag = False

for ele in vow:


if sub.startswith(ele):
flag = True
break
if flag:
res.append(sub)

print("The extracted words : " + str(res))

METHOD-2:
test_list = ["all", "love", "and", "get", "educated", "by", "gfg"]

print("The original list is : " +str(test_list))

res = []
vow = "aeiou"
for sub in test_list:

flag = any(sub.startswith(ele) for ele in vow)


if flag:
res.append(sub)

print("The extracted words : " + str(res))

METHOD-3:
test_list = ["all", "love", "and", "get", "educated", "by", "gfg"]

print("The original list is : " + str(test_list))


def vowelstart(s):
if(s.find("a")==0 or s.find("e")==0 or s.find("i")==0 or s.find("e")==0 or
s.find("u")==0):
return True
return False
res = []

for sub in test_list:


if(vowelstart(sub)):
res.append(sub)

print("The extracted words : " + str(res))


c) Finding a secret message hidden in a paragraph of text.

data = 'Welcome to...'

conversion_code = {

'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', 'N': 'M', 'O': 'L', 'P': 'K', 'Q': 'J', 'R': 'I',
'S': 'H', 'T': 'G', 'U': 'F', 'V': 'E', 'W': 'D', 'X': 'C',
'Y': 'B', 'Z': 'A',

'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', 'n': 'm', 'o': 'l', 'p': 'k', 'q': 'j', 'r': 'i',
's': 'h', 't': 'g', 'u': 'F', 'v': 'e', 'w': 'd', 'x': 'c',
'y': 'b', 'z': 'a'
}

converted_data = " "

for i in range(0, len(data)):


if data[i] in conversion_code.keys():
converted_data += conversion_code[data[i]]
else:
converted_data += data[i]
print(converted_data)
d) Plot a histogram of words according to their length
from text read from a file.

from matplotlib import pyplot as plt


import numpy as np

def splitString(str):
l1=[]
s=str.split()
for words in s:
l1.append(len(words))
print(l1)
return l1

str="Hello World How are you? Program execution starts at


Preprocessor directives starts Modulo operator cannot be used ANSI
expansion ASCII expansion C language developped by Format "

a=splitString(str)

fig,ax=plt.subplots(figsize=(10,7))
ax.hist(a)

plt.show()

You might also like