You are on page 1of 11

String Methods:

def stringmethod(para, special1, special2, list1, strfind):


# Write your code here
word1 = ''
newpara =''

for i in para:
if i in special1:
newpara += i
else:
word1 += i

rword2= word1[:70]
rword2= rword2[::-1]
print (rword2)

noSpace = rword2.replace(" ", "")


noSpace = special2.join(noSpace)
print (noSpace)

flag = 0
for each in list1:
if each in para:
continue
else:
flag = 1
break
if flag:
print("Every string in {0} were not
present".format(list1))
else:
print("Every string in {0} were present".
format(list1))

splitted =word1.split()
print (splitted[:20])

ans=[]
for each in splitted:
if splitted.count(each)<3:
if each not in ans:
ans.append(each)

print(ans[-20:])
print(word1.rindex(strfind))
Magic Constant Generator:

def generator_Magic(n1):
lst=[]
for i in range(3,n1+1):
M=i*(i*i+1)/2
lst.append(M)

for i in range(len(lst)):
yield lst[i]

Prime Number Generator:


def primegenerator(num, val):
lst = []
lst1 = []
lst2 = []
odd=1
even=0
for i in range (2, num+1):
if i>1:
for j in range (2, i):
if (i % j) == 0:
break;
else:
lst.append(i)

for i in range (len(lst)):


if(i % 2 == 0):
lst1.append(lst[i])
even += 2
else:
lst2.append(lst[i])
odd +=2

if(val):
for i in range (len(lst1)):
yield lst1[i]
else:
for i in range (len (lst2)):
yield lst2[i]
Classes and Objects 1:
Task1:
class Movie:
def __init__(self, name, n, cost):
self.name = name
self.n = n
self.cost=cost

def __str__(self):
return"Movie : {self.name}\nNumber of Tickets : {self.
n}\nTotal Cost : {self.cost}".format(self=self)

Task2:
class comp:
def __init__(self, a,b):
self.a = a
self.b = b

def add(self, other):


print("Sum of the two Complex numbers :{}+{}i". format
(self.a + other.a, self.b + other.b))

def sub(self, other):


if(self.b>=other.b):
print("Subtraction of the two Complex numbers :{}+
{}i".format(self.a - other.a, self.b - other.b))
else:
print("Subtraction of the two Complex numbers :{}{
}i". format(self.a - other.a, self.b - other.b))
Class and Objects 2:
Task1:
class parent:
def __init__(self, t):
self.t = t
def display (self):
print("Share of Parents is {} Million.".format(round((
self. t)/2, 2)))

class son (parent):


def __init__(self, t, sp):
self.sp= sp
parent.__init__(self,t)

def son_display(self):
Percentage_for_son = (self.t*self.sp)/100
print("Share of Son is {} Million.".format(round(Perce
ntage_for_son, 2)))
print("Total Asset Worth is {} Million.". format(round
(self.t, 2)))

class daughter (parent):


def __init__(self, t, dp):
self.dp = dp
parent.__init__(self, t)

def daughter_display (self):


Percentage_for_daughter = (self.t*self.dp)/100
print("Share of Daughter is {} Million.". format (roun
d(Percentage_for_daughter, 2)))
print("Total Asset Worth is {} Million.".format(round(
self.t, 2)))

Task 2:
class rectangle:
def display (self):
print("This is a Rectangle")

def area(self, a, b):


self.a = a
self.b = b
print("Area of Rectangle is {}".format(self.a * self.
b))

class square:
def display (self):
print("This is a Square")
def area(self, a):
self.a = a
print("Area of square is {}".format(self.a * self.a))

Handling Exceptions 1:
def Handle_Exc1():
# Write your code here
a = int(input())
b = int(input())
if(a>150 or b<100):
print("Input integers value out of range.");
elif(a + b) > 400:
print("Their sum is out of range")
else:
print("All in range")

Handling Exceptions 2:
def FORLoop():
# Write your code here
n = int(input())
l1=[]
for i in range(n):
l1.append(int(input()))

print (l1)
iter1= iter(l1)

for i in range (len(l1)):


print (next(iter1))

return iter1
Handling Exceptions 3:
def Bank_ATM(balance,choice,amount):
# Write your code here
flag = 0
if balance < 500:
print("As per the Minimum Balance Policy, Balance must
be at least 500")
else:
if (choice == 1):
if amount < 2000:
print("The Minimum amount of Deposit should be
2000.")
else:
flag = 1
balance += amount
if (choice == 2):
if(balance - amount)<500:
print("You cannot withdraw this amount due to
Minimum Balance Policy")
else:
flag=1
balance-=amount
if(flag):
print("Updated Balance Amount: {}".format(balance))

Handling Exceptions 4:
def Library(memberfee,installment,book):
# Write your code here
if(installment > 3):
print("Maximum Permitted Number of Installments is 3")
else:
if (installment == 0):
print("Number of Installments cannot be Zero." )
else:
print("Amount per Installment is {}".format (memb
erfee/installment))

ListOfBooks = ["philosophers stone", "chamber of s


ecrets", "prisoner of azkaban", "goblet of fire", "order of ph
oenix", "half blood price", "deathly hallows 1", "deathly hall
ows 2"]
book = book. lower()
if book in ListOfBooks:
print("It is available in this section")
else:
print("No such book exists in this section")
Modules 1: Date Time
import datetime
def dateandtime(val,tup):
# Write your code here
l = []
if val== 1:
c1= datetime.date(tup [0], tup[1], tup[2])
l.append(c1)
l.append(c1.strftime ("%d")+"/"+c1.strftime ("%m")+"/"
+c1. strftime ("%Y"))

elif val == 2:
c1= datetime.date.fromtimestamp (tup[0])
l.append(c1)

elif val == 3:
c1 = datetime.time (tup [0], tup [1], tup [2])
l.append(c1)
l.append(c1.strftime ("%I"))

elif val == 4:
c1= datetime.date(tup[0], tup [1], tup[2])
l.append(c1.strftime ("%A"))
l.append(c1.strftime("%B"))
l.append(c1.strftime("%j"))

elif val == 5:
c1= datetime.datetime (tup[0], tup[1], tup [2], tup[3]
, tup [4], tup[5])
l.append(c1)

return l
Modules 2: Itertools
import itertools
import operator
def performIterator(tuplevalues):
# Write your code here
l1 = []
ans = []

temp = itertools.cycle(tuplevalues [0])

count = 0
for i in temp:
l1.append(i)
count+=1
if count == 4:
break

ans.append(tuple(l1))
ans.append(tuple (list(itertools.repeat (tuplevalues [1][0
], len(tuplevalues[1])))))

temp = itertools.accumulate (tuplevalues[2], operator.add)

ans.append (tuple(list (temp)))

temp = itertools.chain (tuplevalues[0], tuplevalues [1], t


uplevalues[2], tuplevalues[3])
ans.append(tuple(list (temp)))

tempForTask5= list(itertools.chain (tuplevalues[0], tuplev


alues [1], tuplevalues[2], tuplevalues[3]))

temp2 = itertools.filterfalse (lambda x:x%2==0, tempForTas


k5)
ans.append (tuple(list (temp2)))

return tuple (ans)


Modules 3: Cryptography
from cryptography.fernet import Fernet
def encrdecr(keyval, textencr, textdecr):
# Write your code here
mainList = []
f= Fernet (keyval)
mainList.append(f.encrypt (textencr))
d = f.decrypt (textdecr)
mainList.append(d.decode())

return mainList

Modules 4: Calendar
import calendar
import datetime

def checkLeapYear (year):


if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
return 1
else:
return 0
else:
return 1
else:
return 0

def usingcalendar (datetuple):


year = datetuple[0]
leap= checkLeapYear (year)
if leap== 1:
month = 2
else:
month=datetuple[1]
print (calendar. month (year, month))

m = calendar.monthcalendar (year, month)


mondays = [week [0] for week in m if week [0]>0]
day= mondays [-1]

lst = []
MONTH= month
YEAR = year

for i in range(7):
d= datetime.date (year, month, day)
lst.append(d)
if (leap == 1) and (month == 2):
if(day== 29):
day = 0
if(month== 12):
month = 1
year= year + 1
else:
month= month + 1

elif (leap == 0) and (month == 2):


if(day == 28):
day = 0
if(month== 12):
month = 1
year = year + 1
else:
month=month + 1

else:
if((month == 1) or (month== 3) or (month==5)or(mon
th ==7) or (month==8) or(month ==10)or(month == 12)) and (day
== 31):
day= 0
if(month== 12):
month = 1
year = year + 1
else:
month= month + 1

elif((month == 4) or (month == 6) or (month == 9)


or (month == 11)) and (day == 30):
day = 0
if(month== 12):
month = 1
year= year + 1
else:
month= month + 1

day= day + 1

print(lst)

a = (datetime.datetime(YEAR, MONTH,1))
starting_day = a.strftime ("%A")

days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Fri


day", "Saturday", "Sunday" ]
count= [4 for i in range(0,7)]
pos=-1
for i in range(0,7):
if (starting_day == days[i]):
pos= i
break

print(days [pos])

Modules 5: Collections
import collections
def collectionfunc(text1, dictionary1, key1, val1, deduct, list1):
# Write your code here
d = {}
for each in text1.split():
if each in d:
d[each] += 1
else:
d[each]= 1

sort_d= dict(sorted (d.items (), key = lambda kv: kv[0]))


print(sort_d)

cou = collections. Counter (dictionary1)


for each in deduct:
cou[each] -=deduct[each]

print(dict(cou))

orde= collections. OrderedDict()


for i in range (len(key1)):
orde[key1[i]] = val1[i]

del orde[key1[1]]

orde [key1[1]]= val1[1]

print(dict (orde))

d4= {"odd":[], "even": []}


for i in list1:
if i%2==0:
temp = d4["even"]
temp.append(i)
d4["even"]= temp
else:
temp = d4["odd"]
temp.append(i)
d4["odd"]= temp

if d4 ["even"]== []:
del d4["even"]
if d4 ["odd"] == []:
del d4["odd"]
print (d4)

You might also like