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

Cycle 1 Programs

The document outlines various Python programming exercises covering topics such as printing biodata, finding prime numbers, checking for perfect numbers, defining functions, and using libraries like NumPy and SciPy. It includes examples of matrix operations, statistical calculations, and data visualization techniques. Additionally, it demonstrates string manipulation and file handling operations.

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)
11 views

Cycle 1 Programs

The document outlines various Python programming exercises covering topics such as printing biodata, finding prime numbers, checking for perfect numbers, defining functions, and using libraries like NumPy and SciPy. It includes examples of matrix operations, statistical calculations, and data visualization techniques. Additionally, it demonstrates string manipulation and file handling operations.

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/ 20

Cycle 1 programs

2.Introduction to Python3
a.Printing your biodata on the screen.
print("Name:" ,"Geetha Devi")

print("Gender:", "female")

print("Date of Birth:", "15-aug-1981")

print("Age:",35)

print("Address:"," Hyderabad")

print("Father Name:" ,"Ravi")

print("Mother Name:","swaroopa")

print("E-Mail Address:,""[email protected]")

output:

Name: Geetha Devi

Gender: female

Date of Birth: 15-aug-1981

Age: 35

Address: Hyderabad

Father Name: Ravi

Mother Name: swaroopa

E-Mail Address:,[email protected]

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):


is_prime = True
for i in range(2, number):
if number % i == 0:
is_prime = False
break
if is_prime:
print(number)
output
The Prime Numbers in the range are:
2
3
5
7
11
13
17
19
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 += i

if sum_v == num:
print("The entered number is a perfect number")
else:
print("The entered number is not a perfect number")

Enter the number: 28


The entered number is a perfect number
3)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<input>.


def isPalindrome(num):
return str(num) == str(num)[::-1]
test_number = int(input("Enter any number: "))
print("The original number is:", test_number)
res = isPalindrome(test_number)
print("Is the number palindrome?:", res)

output
Enter any number: 121
The original number is: 121
Is the number palindrome?: True
Enter any number: 123
The original number is: 123
Is the number palindrome?: False
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: # 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)
output
6,3,10,5,16,8,4,2,1
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 # standard deviation
result = math.exp(-((x - m) ** 2) / (2 * s ** 2)) / ((2 * math.pi *
s ** 2) ** 0.5)
return result

print(solve(4, 2))

output
0.05399096651318806
4.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)

output
2X2 matrix
[[86201 50547]
[76360 14299]]
3X3 matrix

[[ 861 50072 79350]


[83930 24624 66903]
[21290 11510 31773]]

b) Write a program that adds, subtracts and multiplies two


matrices.

Method1
matrix1 = [[12, 7, 3],
[4, 5, 6],
[7, 8, 9]]

matrix2 = [[5, 8, 1],


[6, 7, 3],
[4, 5, 9]]

# Initialize the result matrix with zeros


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

# Matrix multiplication logic


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 the result
for row in res:
print(row)

output
[114, 160, 60]
[74, 97, 73]
[119, 157, 112]

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)

output
[[ 63 320 83]
[ 77 484 102]
[ 84 248 117]]

Method 3 Matrix addition

import numpy as np
mat1 = np.array([[1, 6, 5],
[3, 4, 8],
[2, 12, 3]])

mat2 = np.array([[3, 4, 6],


[5, 6, 7],
[6, 56, 7]])
# Proper matrix addition
res = mat1 + mat2
print("Matrix Addition Result:")
print(res)

output
Matrix Addition Result:
[[ 4 10 11]
[ 8 10 15]
[ 8 68 10]]

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)
A*X=B
 A is the coefficient matrix (n × n)

 X is the vector of unknowns (n × 1)

 B is the constant vector (n × 1)

output
[-0.58226371 3.22870478 -1.98599767]
5.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)))

output
Mean of data set 1 is 5.857142857142857
Mean of data set 2 is -7.5
Mean of data set 3 is 2.4285714285714284
Mean of data set 4 is 49/24
Mean of data set 5 is 2

b) Plotting data read from a file.

import matplotlib.pyplot as plt

import csv

X = []

Y = []

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


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

for row in plotting:

X.append(int(row[0]))

Y.append(int(row[1]))

plt.plot(X, Y)

plt.title('Line Graph using CSV')

plt.xlabel('X')

plt.ylabel('Y')

plt.show()
c)Fitting a function through a set of data points using polyfit
function.

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()

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()

6.THE STRING PACKAGE:


a) Read text from a file and print the number of lines , words
and characters.
file = open("text1.txt")

lines = 0

words = 0

symbols = 0

for line in file:

lines += 1

words += len(line.split())

symbols += len(line.strip('\n'))

file.close()

print("Lines:", lines)

print("Words:", words)

print("Symbols:", symbols)

output

Lines: 3

Words: 7

Symbols: 31
b) Read text from a file and return a list of all n letter words
beginning with a vowel.

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))

output:

The original list is : ['all', 'love', 'and', 'get', 'educated', 'by', 'gfg']

The extracted words : ['all', 'and', 'educated']

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(len(data)):
if data[i] in conversion_code:
converted_data += conversion_code[data[i]]
else:
converted_data += data[i]

print(converted_data)

output
Dvoxlnv gl...

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(s):
l1 = []
words = s.split()
for word in words:
l1.append(len(word))
print(l1)
return l1

s = "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(s)

output
[5, 5, 3, 3, 4, 7, 9, 6, 2, 12, 10, 6, 6, 8, 6, 2, 4, 4, 9, 5, 9, 1, 8, 10,
2, 6]

You might also like