0% found this document useful (0 votes)
26 views8 pages

Practical List Class 12th

The document contains code snippets demonstrating various Python functions related to file handling, string manipulation, number conversion, and matrix operations. Specifically: 1. It shows how to read, write, append and iterate through a text file line by line. 2. It defines functions to count vowels in a string, convert numbers between binary, octal, hexadecimal and integer formats, and check if a number is prime or perfect. 3. It demonstrates how to reshape a 2D matrix into a different number of rows and columns while maintaining the same elements.

Uploaded by

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

Practical List Class 12th

The document contains code snippets demonstrating various Python functions related to file handling, string manipulation, number conversion, and matrix operations. Specifically: 1. It shows how to read, write, append and iterate through a text file line by line. 2. It defines functions to count vowels in a string, convert numbers between binary, octal, hexadecimal and integer formats, and check if a number is prime or perfect. 3. It demonstrates how to reshape a 2D matrix into a different number of rows and columns while maintaining the same elements.

Uploaded by

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

1.

)
with open("file.txt","w+") as f:
f.write("""Neither apple nor pine are in pineapple. Boxing rings are square.
Writers write, but fingers don't fing. Overlook and oversee are opposites.
A house can burn up as it burns down. An alarm goes off by going on.""")

f.seek(0)
print(f.read()) #a

f.seek(0)
print(f.readlines())

print("-"*50)

with open("file.txt","a+") as f:
appnd = input("Append Text of your choice :")
f.write(appnd)

f.seek(0)
ln = 0
for i in range(len(f.readlines())):
f.seek(ln)
data = f.readline()
ln += len(data)
print(i,data)

print("-"*50)

f.seek(0)
print(f.readlines()[-1]) #C (Display last line)

f.seek(10) #D (Display first line from 10th character onwards)


print(f.readline())

line = int(input("Display Line Number(starting from 0) : ")) #E


f.seek(0)
print(f.readlines()[line])#E

print("-"*50)

f.seek(0)
data = f.read()
lst = data.split()
uniq = list(set(lst))
d = {}
for i in uniq: #F
d[i[0].lower()] = ()
for i in uniq:
d[i[0].lower()]+=(i,)
for k,v in d.items():
print(f"{k} : {len(v)}")

OUTPUT
Neither apple nor pine are in pineapple. Boxing rings are square.
Writers write, but fingers don't fing. Overlook and oversee are opposites.
A house can burn up as it burns down. An alarm goes off by going on.
['Neither apple nor pine are in pineapple. Boxing rings are square.\n', "Writers write, but fingers don't
fing. Overlook and oversee are opposites.\n", 'A house can burn up as it burns down. An alarm goes off
by going on.']
--------------------------------------------------
Append Text of your choice :Hello World my name is Ali atiyab husain
0 Neither apple nor pine are in pineapple. Boxing rings are square.

1 Writers write, but fingers don't fing. Overlook and oversee are opposites.

2 A house can burn up as it burns down. An alarm goes off by going on.Hello World my name is Ali
atiyab husain
--------------------------------------------------
A house can burn up as it burns down. An alarm goes off by going on.Hello World my name is Ali atiyab
husain
ple nor pine are in pineapple. Boxing rings are square.

Display Line Number(starting from 0) : 2


A house can burn up as it burns down. An alarm goes off by going on.Hello World my name is Ali atiyab
husain
--------------------------------------------------
g:2
a:9
u:1
h:2
b:5
m:1
w:3
f:2
s:1
o:5
c:1
p:2
n:3
i:3
d:2
r:1

2.)
def isvowel(f1):
with open(f1,"r+") as f:
data = f.read()
data_lst = data.split()
save = [i for i in data_lst if i[0].lower() not in ["a","e","i","o","u"]]

with open("file2.txt","w+") as f:
f.write(" ".join(save))
f.seek(0)
print(f.read())

f1 = open("file1.txt","w+")
f1.write("Carry umbrella and overcoat When it Rains")
f1.close()
isvowel("file1.txt")
OUTPUT
Carry When Rains
7.)
def count(n):
sm = 0
n = str(n)
for i in n:
if i.isdigit():
sm+=1
return sm
print(count("abc34 efrf"))

def reverse(n):
n = str(n)
return int(n[::-1])
print(reverse(23423))

def hasdigit(n,n1):
n = str(n)
n1 = str(n1)
for i in n1:
if i == n:
return True
else:
return False
print(hasdigit(2,4355552))

def show(n):
n = str(n)
lst = []
for i in range(len(n)):
val = int(n[len(n)-i-1] + "0"*i)
lst.append(val)
lst.sort(reverse = True)
return lst
print(show(124))
OUTPUT
2
32432
True
[100, 20, 4]

8.)
def Generatefactors(n):
lst = []
for i in range(1,n):
if n % i == 0:
lst.append(i)
return lst

def isPrimeNo(n):
if len(Generatefactors(n)) == 1:
return "PRIME"
else:
return "NOT PRIME"

def isPerfectNo(n):
if n == sum(Generatefactors(n)):
return "PERFECT NUMBER"
else:
return "NOT PERFECT NUMBER"
(in main.py)
from perfect import *
if __name__ == "__main__":
while True:
try:
option = int(input("""Choose:
0 - for finding factors of a number.
1 - for finding whether a number is prime number or not.
2 - for finding whether a number is a perfect number or not.
3 - To exit.
"""))

if option == 0:
n = int(input("Number : "))
print(Generatefactors(n))
elif option == 1:
n = int(input("Number : "))
print(isPrimeNo(n))
elif option == 2:
n = int(input("Number : "))
print(isPerfectNo(n))
elif option == 3:
print("Thank You For Using This Program.")
break
else:
raise ValueError("Value should be between 0 and 3 (both included).")
except ValueError as ve:
print("Value should be a number between 1 and 3.")
except Exception as e:
print("Error : ",e)

OUTPUT

Choose:
0 - for finding factors of a number.
1 - for finding whether a number is prime number or not.
2 - for finding whether a number is a perfect number or not.
3 - To exit.
1
Number : 12
NOT PRIME
Choose:
0 - for finding factors of a number.
1 - for finding whether a number is prime number or not.
2 - for finding whether a number is a perfect number or not.
3 - To exit.
3
Thank You For Using This Program.
9.)
def romanToInt(num):
r = ["X","V","I","C","D","L","M"]
n = [10,5,1,100,500,50,1000]
d = dict(zip(r,n))
l1 = []
for i in num:
l1.append(d[i])

lst = []
ind1,ind2 = 0,1
save = 0
k=0
if len(l1) % 2 != 0 and l1[0] == max(l1):
save = l1[0]
l1 = l1[1:]
try:
if len(l1) % 2 != 0 and l1[0] != max(l1):
k = l1[-1]
l1.append(k)
except:
print(f"{num} gives error .")

while ind2 < len(l1):


if l1[ind1] >= l1[ind2]:
lst.append(l1[ind1]+l1[ind2])
else:
lst.append(l1[ind2]-l1[ind1])
ind1+=2
ind2+=2

return save + sum(lst) - k


roman = input("Value in Roman Numerals :")
print(romanToInt(roman))

OUTPUT
Value in Roman Numerals :XVI
16

10.)
def int_to_binary(n):
if type(n) == float:
n = str(n)
intgr,dec = [],[]
cnt = 0
for i in n:
if i == ".":
cnt+=1
if cnt == 0:
intgr.append(i)
else:
dec.append(i)
lst = []
r=1
while n > 0:
r=n%2
n = n // 2
lst.append(str(r))

lst = lst[::-1]
if len(lst) == 0:
lst.append("0")
return "".join(lst).zfill(4)

def int_to_octal(n):
if type(n) == float:
n = str(n)
intgr,dec = [],[]
cnt = 0
for i in n:
if i == ".":
cnt+=1
if cnt == 0:
intgr.append(i)
else:
dec.append(i)

intgr = int("".join(intgr))
dec = float("".join(dec))

dec_bin = []
k = cnt = 0
while cnt < 4 :
cnt+=1
dec = dec*8
k = int(dec)
if k >=1:
dec = dec-k
dec_bin.append(str(k))

n = intgr
lst = []
r=1
while n > 0:
r=n%8
n = n // 8
lst.append(str(r))

lst = lst[::-1]
if len(lst) == 0:
lst.append("0")
return "".join(lst) + "."+ "".join(dec_bin)
int_to_octal(10.54)
def int_to_hex(n):
d = {10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F'}
if type(n) == float:
n = str(n)
intgr,dec = [],[]
cnt = 0
for i in n:
if i == ".":
cnt+=1
if cnt == 0:
intgr.append(i)
else:
dec.append(i)
intgr = int("".join(intgr))
dec = float("".join(dec))
dec_bin = []
k = cnt = 0
while cnt < 4 :
cnt+=1
dec = dec*16
k = int(dec)
if k >=1:
dec = dec-k
if k >=10:
dec_bin.append(d[int(k)])
else:
dec_bin.append(str(k))
n = intgr
lst = []
r=1
while n > 0:
r = n % 16
n = n // 16
if r > 9:
lst.append(d[r])
else:
lst.append(str(r))
lst = lst[::-1]
if len(lst) == 0:
lst.append("0")
return "".join(lst)+ "."+ "".join(dec_bin)

def main(n,mode):
if mode == "B":
print(int_to_binary(n))
elif mode == "O":
print(int_to_octal(n))
elif mode == "H":
print(int_to_hex(n))
else:
print("Mode should be B,O or H.")

mode = input("""Input Mode for Conversion :


B - Binary
O - Octal
H - Hexadecimal
""")
n = eval(input("Number to convert :"))
main(n,mode)

OUTPUT
Input Mode for Conversion :
B - Binary
O - Octal
H - Hexadecimal
H
Number to convert :10.34
A.570A

11.)
def reshape(mat,r,c):
l = []
m=0
for i in mat:
m+=1
n=0
for j in i:
n+=1
l.append(j)
lst = []
if m*n != r*c:
return "List must have dimensions such that their product remains equal."
else:
for i in range(r):
tmp = []
for j in range(c):
tmp.append(l[j])
l = l[j+1:]
lst.append(tmp)
return lst
print(reshape([[1,2],[3,4]],r = 1,c = 4))

OUTPUT
[[1, 2, 3, 4]]

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy