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

n16 Python Programs

Uploaded by

SATYA SAI
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

n16 Python Programs

Uploaded by

SATYA SAI
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

4/20/22, 7:56 PM 16-w1

list of experiments 1.arthematic operations 2.logical operation 3.ascii values 4.convert decimal
number into binary,octal,hexagonal numbers

In [1]:
#experiment 1 arthemetic operations
2+3,2-3,2*3,2/3,2%3

(5, -1, 6, 0.6666666666666666, 2)

In [2]:
#arthematic operation
a=int (input("enter value"))
b=int (input("enterr value"))
print("addion of a&b",a+b)
print("substraction b from a",a-b)
print("multiplication a&b",a*b)
print("division of a&b",a/b)
print("modulus of a&b",a%b)

enter value4
enterr value3
addion of a&b 7
substraction b from a 1
multiplication a&b 12
division of a&b 1.3333333333333333
modulus of a&b 1

In [3]:
#check whether the given number is even and less than 10
a=int(input("enter value"))
a%2==0 and a<10

enter value4
True

In [4]:
#check the number is even or not
a=int(input("enter value"))
not(a%2==1)

enter value5
False

In [5]:
#to find ASCII value
a=input("enter character")
print("the ASCII value is",ord(a))

enter characterc
the ASCII value ofcis 99

In [6]:
a=int(input("enter number"))
print("character is",chr(a))

enter number121
character is y

In [7]:
# to convert devimal number into binary,octa,hexadecimal
a=int(input("enter number"))
b=bin(a)
c=oct(a)
localhost:8888/nbconvert/html/36-w1.ipynb?download=false 1/2
4/20/22, 7:56 PM 16-w1

d=hex(a)
print("binary number is",b)
print("octa number is",c)
print("hexadecimal number is",d)

enter number5
binary number is 0b101
octa number is 0o5
hexadecimal number is 0x5
NAME : S.SATYA SAI
JNTU NO : 21341A03C3
ROLL NO : N16

localhost:8888/nbconvert/html/36-w1.ipynb?download=false 2/2
4/20/22, 3:48 PM 16_w2

list of experiments: A)write a python program to check the given year is a leap or not using if
statement B)write a python program to check the given number is armstrong or not using
iteration statements C)write a python program to perform follow operations on list .create a
empty list .append the elements into list .find the length,minimum,maximum

In [1]:
#experiment to check the given year is leap year or not
x=int(input("enter the year"))
if x%100==0 and x%400==0:
print(x,"is a leap year")
elif x%4==0 and x%100!=0:
print(x,"is a leap year")
else:
print(x,"is not a leap year")

enter the year2001


2001 is not a leap year

In [2]:
#experiment to check given number is armstrong or not
number = int(input("enter the number"))
sum = 0
dummy = number
while dummy > 0:
digit = dummy%10
sum += digit**3
dummy //= 10
if number == sum:
print(number,"is an armstrong number")
else:
print(number,"is not a armstrong number")

enter the number152


152 is not a armstrong number

In [6]:
#experiment
lis = []
print(lis)
x = int(input("enter how many elements to append: "))
i =0
for i in range (0,x):
if i <= x:
a = input("enter the value: ")
lis.insert(i,int(a))
i+=1
else:
i =0
print(len(lis),"is length of the lis")
print(min(lis),"is minimum of the lis")
print(max(lis),"is maximum of the lis")

[]
enter how many elements to append: 5
enter the value: 10
enter the value: 20
enter the value: 30
enter the value: 40
enter the value: 50
5 is length of the lis
10 is minimum of the lis
50 is maximum of the lis
localhost:8888/nbconvert/html/16_w2.ipynb?download=false 1/2
4/20/22, 3:48 PM 16_w2

NAME : S.SATYA SAI


JNTU NO : 21341A03C3
ROLL NO : N16

localhost:8888/nbconvert/html/16_w2.ipynb?download=false 2/2
4/27/22, 3:57 PM Untitled - Jupyter Notebook

1)write a python program to use python generators to print all the prime numbers upto
given value n
2)
a)write a python program for a given list of numbers
b)print all the numbers one by one
c)using iterations in python

In [1]:

#experiment to write a python program to use python generators to print all prime numbers
def generate_primenumbers(n):
for i in range(2,n+1):
for j in range (2,i):
if(i%j==0):
break
else:
yield i
k=int(input("upto which number do you wish to generate prime number: "))
print(*generate_primenumbers(k))

upto which number do you wish to generate prime number: 16


2 3 5 7 11 13

In [12]:

#write a python program for a given list of numbers


#print all the numbers one by one
#using iterations in python
list=[]
x=int(input("enetr the size of the list: "))
i=0
for i in range(0,x):
a=input("enter the value: ")
list.insert(i,int(a))
i+=1
print(list)
myit=iter(list)
for i in range(0,x):
print(next(myit))

enetr the size of the list: 5


enter the value: 10
enter the value: 20
enter the value: 30
enter the value: 40
enter the value: 50
[10, 20, 30, 40, 50]
10
20
30
40
50

NAME : S.SATYA SAI


ROLL NO : N16
JNTU NO : 21341A03C3

localhost:8888/notebooks/Untitled.ipynb?kernel_name=python3 1/2
4/27/22, 3:57 PM Untitled - Jupyter Notebook

localhost:8888/notebooks/Untitled.ipynb?kernel_name=python3 2/2
5/4/22, 3:49 PM 16_w4

1) write a python program to flatten a nested list.


2) write a python program to split a list into evenly sized chunks.
3) write a python program to find the transpose of a matrix using list.

In [1]:

#experiment to write a python program to flatten a nested list


nested=[[1,2,3,],[4,5,6,],[7,8,9,]]
flattened2=[]
for sublist in nested:
for num in sublist:
flattened2.append(num)
print(flattened2)

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

In [2]:

#experiment to write a python program to flatten a nested list


nested=[[1,2,3,],[4,5,6,],[7,8,9]]
flattened=[num for sublist in nested for num in sublist]
print(flattened)

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

In [9]:

#experiment to write a python program to split a list into evenly sized chunks
def split(list_a,chunk_size):
for i in range(0,len(list_a),chunk_size):
yield list_a[i:i+chunk_size]
chunk_size=3
my_list=[1,2,3,4,5,6,7,8,9]
print(list(split(my_list,chunk_size)))

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

In [10]:

#experiment to write a python program to find the transpose of the matrix using list
x=[[1,2,3],
[4,5,6],
[7,8,9],
[10,11,12]]
result=[[0,0,0,0,],
[0,0,0,0,],
[0,0,0,0,]]
for i in range(len(x)):
for j in range(len(x[0])):
result[j][i]=x[i][j]
for r in result:
print(r)

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

localhost:8888/notebooks/Untitled1.ipynb?kernel_name=python3 1/2
5/4/22, 3:49 PM 16_w4

NAME : S.SATYA SAI


ROLL NO : N-16
JNTU NO : 21341A03C3

localhost:8888/notebooks/Untitled1.ipynb?kernel_name=python3 2/2
5/11/22, 3:38 PM 16_w5

1) write a python program in a given list of numbers create another list of even numbers
using list comprehension
2) write a python program in a given list of numbers n from a tuple of two numbers such
that highest maximum and lowest minimum are in 1 tuple,second maximum and second minimum
in other tuple and so on
example:given list of numbers 1,4,6,2,3,5
output:((6,1),(5,2),(4,3))

In [9]:

#to seperate even numbers into a new list


a=list(map(int,input("enter the numbers of list: ").split(",")))
even=[num for num in a if num%2==0]
print("even list is",even)

enter the numbers of list: 1,25,3,45,16,78,26,44,99,102


even list is [16, 78, 26, 44, 102]

In [12]:

#program to print the elements in list as a pair of minimum and maximum values as a tuple
a=list(map(int,input("enter elements of list: ").split(",")))
a.sort()
print_list=[]
n=len(a)
for i in range(n//2):
pair=[]
pair.append(a[n-i-1])
pair.append(a[i])
r=tuple(pair)
print_list.append(r)
print_list=tuple(print_list)
print(print_list)

enter elements of list: 23,54,68,71,24,16,36,18


((71, 16), (68, 18), (54, 23), (36, 24))

NAME : S.SATYA SAI


ROLL NO : N-16
JNTU NO : 21341A03C3

localhost:8888/notebooks/Untitled2.ipynb?kernel_name=python3# 1/1
6/14/22, 6:39 PM n16_w6 - Jupyter Notebook

A)Write a python program to remove puntuations from a string


B)Write a python program to count the frequency of characters in the string and store
them in a dictionary data structure

In [1]:

#program to remove punctuations from a string


punctuation='''``!@#$%^&*()_[]{}:;""<,>.?/\|'''
string=input("enter the string:")
no_punct=""
for char in string:
if char not in punctuation:
no_punct=no_punct+char
print(no_punct)

enter the string:sa#t%y^as*&a!i


satyasai

In [2]:

#to count the frequency of characters in string and store them in a dictionary structure
string=input("enter the string:")
string=string.upper()
x=list(string)
f={}
for i in x:
if i in f:
f[i]+=1
else:
f[i]=1
print(f)

enter the string:satya sai


{'S': 2, 'A': 3, 'T': 1, 'Y': 1, ' ': 1, 'I': 1}

NAME:S.SATYA SAI
ROLL NO:N16
JNTU NO:21341A03C3

localhost:8888/notebooks/n16_w6.ipynb 1/1
6/8/22, 4:04 PM n16_w7 - Jupyter Notebook

A)Write a python program to find the cube of a given number using lambda()
B)Write a python program to filter only even numbers from a given list using filter
method

In [1]:

#cube of given number using lambda function


list1=list(map(eval,input("enter number:").split(',')))
b=list(map(lambda a:a**3,list1))
print("the cube of {} is:{}".format(list1,b))

enter number:4
the cube of [4] is:[64]

In [4]:

#filter even numbers from list


a=list(map(eval,input("enter number:").split(',')))
b=list(filter(lambda x:x%2==0,a))
print("the even numbers are:",b)

enter number:1,2,3,5,4,56,57,95
the even numbers are: [2, 4, 56]

NAME:S.SATYA SAI
ROLL NO:N16
JNTU NO:21341A03C3

localhost:8888/notebooks/n16_w7.ipynb 1/1
6/15/22, 2:46 PM n16_w8 - Jupyter Notebook

A)Write a python program to find the squares of the list of numbers using map functions.
B)Write a python program to print all the combinations for the given list of numbers
using itertools.
C)Write a python program to print all the permutations for the given list of numbers
using itertools.

In [1]:

#squares of the list of numbers using map functions


x=list(map(eval,input("enter numbers:").split(',')))
b=list(map(lambda a:a**2,x))
print("squares of",x,"is",b)

enter numbers:1,5,3,6
squares of [1, 5, 3, 6] is [1, 25, 9, 36]

In [1]:

#print combinations for the given list of numbers using itertools


from itertools import combinations
a=list(map(eval,input("enter numbers:").split(',')))
for i in combinations(a,2):
print(i)

enter numbers:1,2,3
(1, 2)
(1, 3)
(2, 3)

In [2]:

#print permutations for the given list of numbers using itertools


from itertools import permutations
a=list(map(eval,input("enter numbers:").split(',')))
for i in permutations(a,2):
print(i)

enter numbers:1,2,3
(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
(3, 2)

NAME: S.SATYA SAI


ROLL NO: N16
JNTU NO: 21341A03C3

localhost:8888/notebooks/n16_w8.ipynb 1/1
6/15/22, 3:02 PM n16_w9 - Jupyter Notebook

A)Write a method which accepts multiple parameters/arguments and find the sum of given
parameters.
B)Write a python program to find the sum of the elements in the array using reduce
function of the python.

In [2]:

#method which accepts multiple parameters/arguments and find the sum of given parameters
def sum(*arg):
total=0
for i in arg:
total+=i
return(total)
print("sum of list elements:",sum(1,2,3,4,5,6))

sum of list elements: 21

In [5]:

#the sum of the elements in the arrray using reduce function of the python
import functools as f
m=list(map(int,input("enter numbers:").split(",")))
n=f.reduce(lambda a,b:a+b,m)
print("sum of list elements using reduce:",n)

enter numbers:16,29,36
sum of list elements using reduce: 81

NAME: S.SATYA SAI


ROLL NO: N16
JNTU NO: 21341A03C3

localhost:8888/notebooks/n16_w9.ipynb 1/1
6/29/22, 3:47 PM n16_w10 - Jupyter Notebook

A)Write a python program to search a key element in the list using linear search
operation.
B)Write a python program to sort the given list using bubble sort technique.

In [1]:

#program to search a key element in the list using linear search operation
def linsearch(ib,search):
for i in range(len(ib)):
if ib[i] == search:
return i
return -1
a = list(map(int,input("elements:").split(',')))
x = int(input("enter a number to search:"))
result = linsearch(a,x)
if result == -1:
print("The number is not in the list")
else:
print("{},is located at {} index position".format(x,result))

elements:36,29,16,15
enter a number to search:16
16,is located at 2 index position

In [2]:

#program to sort the given list using bubble sort technique


def bubblesort(lis):
for i in range(len(lis)):
for j in range(len(lis)-i-1):
if lis[j]>lis[j+1]:
lis[j],lis[j+1]=lis[j+1],lis[j]
a = list(map(int,input("enter:").split(',')))
bubblesort(a)
print(a)

enter:36,29,16,15
[15, 16, 29, 36]

NAME : S.SATYA SAI


ROLL NO : N-16
JNTU NO : 21341A03C3

localhost:8888/notebooks/n16_w10.ipynb 1/1
7/13/22, 8:30 PM n16_w11 - Jupyter Notebook

A)Write a python program to convert the given list to numpy array.


B)Write a python program to remove rows in numpy array that contains non-numeric values.
C)Write a python program to find the number of occurences of sequence in numpy array.

In [1]: #convert the given list to numpy array


import numpy as np
a=[1,2,3,4,1,2,3,1,2,3]
b=np.array(a)
print("list is:",a)
print("numpy array is:",b)

list is: [1, 2, 3, 4, 1, 2, 3, 1, 2, 3]


numpy array is: [1 2 3 4 1 2 3 1 2 3]

In [2]: #remove rows in numpy array that contains non-numeric values


import numpy as np
x=np.array([[1,2,np.nan],[np.nan,0,np.nan],[3,4,5]])
print("The array with nans is:",x)
y=x[~np.isnan(x).any(axis=1)]
print("Array without rows that have non-numeric values:")
print(y)

The array with nans is: [[ 1. 2. nan]


[nan 0. nan]
[ 3. 4. 5.]]
Array without rows that have non-numeric values:
[[3. 4. 5.]]

localhost:8888/notebooks/n16_w11.ipynb 1/2
7/13/22, 8:30 PM n16_w11 - Jupyter Notebook

In [3]: #find the number of occurences of sequence in numpy


import numpy as np
x=np.array([[2, 3, 4, 5],[3, 4, 1, 2],[1, 2, 3, 4]])
repeat=repr(x).count("3,4")
print("array:",x)
print("3,4 repeated {} times".format(repeat))

array: [[2 3 4 5]
[3 4 1 2]
[1 2 3 4]]
3,4 repeated 0 times

NAME : S.SATYA SAI


ROLL NO : N16
JNTU NO : 21341A03C3

localhost:8888/notebooks/n16_w11.ipynb 2/2
7/13/22, 8:33 PM n16_w12 - Jupyter Notebook

A)Write a python program to combine one and two-dimensional numpy array.


B)Write a python program to perform matrix multiplication on numpy arrays.
C)Write a python program create a pandas data frame with dimensional list.

In [1]: #combine one and two dimensional numpy array


import numpy as np
x=np.arange(5)
print("1D array:",x)
y=np.arange(10).reshape(2,5)
print("2D array:",y)
for i,j in np.nditer([y,x]):
print("%d:%d"%(i,j))

1D array: [0 1 2 3 4]
2D array: [[0 1 2 3 4]
[5 6 7 8 9]]
0:0
1:1
2:2
3:3
4:4
5:0
6:1
7:2
8:3
9:4

localhost:8888/notebooks/n16_w12.ipynb 1/3
7/13/22, 8:33 PM n16_w12 - Jupyter Notebook

In [2]: #perform matrix multiplication on numpy arrays


import numpy as np
n=int(input("enter no. of rows:"))
m=int(input("enter no. of columns:"))
x=[[int(input()) for j in range(n)] for i in range(m)]
y=[[int(input()) for j in range(n)] for i in range(m)]
a=np.array(x)
b=np.array(y)
c=a @ b
print(c)

enter no. of rows:2


enter no. of columns:2
1
2
3
4
5
6
7
8
[[19 22]
[43 50]]

In [3]: #create a pandas data frame with two dimensional list


import pandas as pd
x=[['a',20,True],['b',30,False],['C',40,True],['d',25,False]]
df1=pd.DataFrame(x,columns=['student','marks','localite'])
print(df1)

student marks localite


0 a 20 True
1 b 30 False
2 C 40 True
3 d 25 False

NAME : S.SATYA SAI


ROLL NO : N16
JNTU NO : 21341A03C3

localhost:8888/notebooks/n16_w12.ipynb 2/3
7/16/22, 7:31 AM n16_w13 - Jupyter Notebook

A)Write a python program to create a data frame from dictionary.


B)Write a python program to clean the string data in the given pandas data frame.
C)Write a python program of conditional operations on pandas data frame

In [1]: #dictionary of numpy array to pandas data frame


import numpy as np
import pandas as pd
D1 = {'student':['j','k','l','m'],'marks':[20,10,25,15]}
df1 = pd.DataFrame(D1)
print(df1)

student marks
0 j 20
1 k 10
2 l 25
3 m 15

In [2]: #clean the string data in the given pandas data frame
D1 = {'student':['JohN','AbbU','CHanikya','YAsH'],'marks':[39,40,39,39]}
df = pd.DataFrame(D1)
print(df)
df['student'] = df['student'].apply(lambda x:x.strip().capitalize())
print("\n updated dataframe with strings \n")
print(df)

student marks
0 JohN 39
1 AbbU 40
2 CHanikya 39
3 YAsH 39

updated dataframe with strings

student marks
0 John 39
1 Abbu 40
2 Chanikya 39
3 Yash 39

localhost:8888/notebooks/n16_w13.ipynb 1/2
7/16/22, 7:31 AM n16_w13 - Jupyter Notebook

In [3]: #conditional operations on pandas data frame


D1 = {'student':['JohN','Kshitij','LANthern','MariE'],'marks':[20,10,15,25]}
df = pd.DataFrame(D1)
score = []
print(df)
df['score'] = df['marks'].apply(lambda x:'Pass' if x>10 else 'Fail')
print(df)

student marks
0 JohN 20
1 Kshitij 10
2 LANthern 15
3 MariE 25
student marks score
0 JohN 20 Pass
1 Kshitij 10 Fail
2 LANthern 15 Pass
3 MariE 25 Pass

NAME : S.SATYA SAI


ROLL NO : N16
JNTU NO : 21341A03C3

localhost:8888/notebooks/n16_w13.ipynb 2/2

You might also like