0% found this document useful (0 votes)
2K views

Modules 1

The document discusses using various calendar functions in Python. It defines a function called usingcalendar that accepts a tuple as a parameter. The function prints the calendar for the given year and month, extracts the days in the last week of the month, and counts the number of days in each day of the week in the given month.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views

Modules 1

The document discusses using various calendar functions in Python. It defines a function called usingcalendar that accepts a tuple as a parameter. The function prints the calendar for the given year and month, extracts the days in the last week of the month, and counts the number of days in each day of the week in the given month.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 9

Modules-2

#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'usingiter' function below.
#
# The function is expected to return a TUPLE.
# The function accepts following parameters:
# 1. TUPLE tupb
#
import itertools
import operator
def performIterator(tuplevalues):
# Write your code here
main_list=[]
sub_list=[]
c=0
for i in itertools.cycle(tuplevalues[0]):
if(c<4):
sub_list.append(i)
c+=1
else:
break

main_list.append(tuple(sub_list))
sub_list=itertools.repeat(tuplevalues[1][0],len(tuplevalues[1]))
main_list.append(tuple(sub_list))
main_list.append(tuple(itertools.accumulate(tuplevalues[2])))

main_list.append(tuple(itertools.chain(tuplevalues[0],tuplevalues[1],tuplevalues[2]
,tuplevalues[3])))
main_list.append(tuple(itertools.filterfalse(lambda x:bool(x
%2==0),main_list[3])))
return(tuple(main_list))

if __name__ == '__main__':

length = int(input().strip())

qw1 = []
for i in range(4):
qw2 = []
for _ in range(length):
qw2_item = int(input().strip())
qw2.append(qw2_item)
qw1.append(tuple(qw2))
tupb = tuple(qw1)

q = performIterator(tupb)
print(q)
Modules-3
#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'encrdecr' function below.
#
# The function is expected to return a LIST.
# The function accepts following parameters:
# 1. STRING keyval
# 2. STRING textencr
# 3. Byte-code textdecr
#
from cryptography.fernet import Fernet
def encrdecr(keyval, textencr, textdecr):
# Write your code here
main_list=[]
key=Fernet(keyval)
main_list.append(key.encrypt(textencr))
decrypted=key.decrypt(textdecr)
main_list.append(decrypted.decode())
return main_list

if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')

file = open('key.key', 'rb')


key = file.read() # The key will be type bytes
file.close()

keyval = key

textencr = str(input()).encode()

textdecr = str(input()).encode()

result = encrdecr(keyval, textencr, textdecr)


bk=[]
f = Fernet(key)
val = f.decrypt(result[0])
bk.append(val.decode())
bk.append(result[1])

fptr.write(str(bk) + '\n')

fptr.close()

modules 5:
#!/bin/python3
import math
import os
import random
import re
import sys

#
# Complete the 'collectionfunc' function below.
#
# The function accepts following parameters:
# 1. STRING text1
# 2. DICTIONARY dictionary1
# 3. LIST key1
# 4. LIST val1
# 5. DICTIONARY deduct
# 6. LIST list1
#
from collections import OrderedDict,defaultdict
def collectionfunc(text1, dictionary1, key1, val1, deduct, list1):
word_count={}
words=sorted(text1.split(" "))
for word in words:
if(word not in word_count):
word_count[word]=0
word_count[word]+=1
print(word_count)
dict_counter1=Counter(dictionary1)
dict_counter2=Counter(deduct)
dict_counter1.subtract(dict_counter2)
print(dict(dict_counter1))
od=OrderedDict()
for i in range(0,len(key1)):
od[key1[i]]=val1[i]
od_dict=dict(od)
od_dict.__delitem__(key1[1])
od_dict[key1[1]]=val1[1]
print(od_dict)
dd=defaultdict()
odd=[number for number in list1 if(number%2!=0)]
even=[number for number in list1 if(number%2==0)]
if(len(odd)>0):
dd["odd"]=odd
if(len(even)>0):
dd["even"]=even
print(dict(dd))

if __name__ == '__main__':
from collections import Counter

text1 = input()

n1 = int(input().strip())
qw1 = []
qw2 = []
for _ in range(n1):
qw1_item = (input().strip())
qw1.append(qw1_item)
qw2_item = int(input().strip())
qw2.append(qw2_item)
testdict={}
for i in range(n1):
testdict[qw1[i]]=qw2[i]
collection1 = (testdict)

qw1 = []
n2 = int(input().strip())
for _ in range(n2):
qw1_item = (input().strip())
qw1.append(qw1_item)
key1 = qw1

qw1 = []
n3 = int(input().strip())
for _ in range(n3):
qw1_item = int(input().strip())
qw1.append(qw1_item)
val1 = qw1

n4 = int(input().strip())
qw1 = []
qw2 = []
for _ in range(n4):
qw1_item = (input().strip())
qw1.append(qw1_item)
qw2_item = int(input().strip())
qw2.append(qw2_item)
testdict={}
for i in range(n4):
testdict[qw1[i]]=qw2[i]
deduct = testdict

qw1 = []
n5 = int(input().strip())
for _ in range(n5):
qw1_item = int(input().strip())
qw1.append(qw1_item)
list1 = qw1

collectionfunc(text1, collection1, key1, val1, deduct, list1)

datetime:

#!/bin/python3

import math
import os
import random
import re
import sys
#
# Complete the 'dateandtime' function below.
#
# The function accepts INTEGER val as parameter.
# The return type must be LIST.
#
import datetime
def dateandtime(val,tup):
# Write your code here
lis=[]
if(val==1):
dt=datetime.date(tup[0],tup[1],tup[2])
lis.append(dt)
day=str(dt.day)
day=day.zfill(2)
month=str(dt.month)
month=month.zfill(2)
lis.append("{}/{}/{}".format(day,month,dt.year))
elif(val==2):
lis.append(datetime.date.fromtimestamp(tup[0]))
elif(val==3):
lis.append(datetime.time(tup[0],tup[1],tup[2]))
hr=str(lis[0].hour-12)
hr=hr.zfill(2)
lis.append(hr)
elif(val==4):
dt=datetime.date(tup[0],tup[1],tup[2])
lis.append(dt.strftime("%A"))
lis.append(dt.strftime("%B"))
lis.append(dt.strftime("%j"))
elif(val==5):
dt=datetime.datetime(tup[0],tup[1],tup[2],tup[3],tup[4],tup[5])
lis.append(dt)
return lis

if __name__ == '__main__':
val = int(input().strip())

if val ==1 or val==4 or val ==3:


qw1_count=3
if val==2:
qw1_count=1
if val ==5:
qw1_count=6
qw1 = []

for _ in range(qw1_count):
qw1_item = int(input().strip())
qw1.append(qw1_item)

tup=tuple(qw1)

ans = dateandtime(val,tup)

print(ans)

Handling Exceptions: bank balance


class MinimumDepositError(Exception):
def __init__(self,error):
self.error=error
def __str__(self):
return self.error

class MinimumBalanceError(Exception):
def __init__(self,error):
self.error=error
def __str__(self):
return self.error

def Bank_ATM(balance,choice,amount):
if(balance<500):
raise ValueError("As per the Minimum Balance Policy, Balance must be at
least 500")
elif(choice==1):
if(amount<2000):
raise MinimumDepositError("The Minimum amount of Deposit should be
2000.")
else:
balance+=amount
print("Updated Balance Amount: {}".format(balance))
elif(choice==2):
if((balance-amount)<500):
raise MinimumBalanceError("You cannot withdraw this amount due to
Minimum Balance Policy")
else:
balance-=amount
print("Updated Balance Amount: {}".format(balance))

if __name__ == '__main__':

bal = int(input())
ch = int(input())
amt = int(input())

try:
Bank_ATM(bal,ch,amt)

except ValueError as e:
print(e)
except MinimumDepositError as e:
print(e)
except MinimumBalanceError as e:
print(e)

Handling Exceptions: harry potter


#!/bin/python3

import math
import os
import random
import re
import sys
#
# Complete the 'Library' function below.
#

def Library(memberfee,installment,book):
books=["philosophers stone","chamber of secrets","prisoner of azkaban","goblet
of fire","order of phoenix","half blood prince","deathly hallows 1","deathly
hallows 2"]
if(installment>3):
raise ValueError("Maximum Permitted Number of Installments is 3")
elif(installment<=3):
try:
amount=memberfee/installment
except ZeroDivisionError:
raise ZeroDivisionError("Number of Installments cannot be Zero.")
else:
print("Amount per Installment is {}".format(amount))
if(book.lower() in books):
print("It is available in this section")
elif(book.lower() not in books):
raise NameError("No such book exists in this section")

if __name__ == '__main__':

memberfee = int(input())
installment = int(input())
book = input()

try:
Library(memberfee,installment,book)

except ZeroDivisionError as e:
print(e)
except ValueError as e:
print(e)
except NameError as e:
print(e)

Calendar:
#!/bin/python3

import math
import os
import random
import re
import sys

import calendar
import datetime
#
# Complete the 'calen' function below.
#
# The function accepts TUPLE datetuple as parameter.
#

def usingcalendar(datetuple):
# Write your code here
if(calendar.isleap(datetuple[0])):
month=2
else:
month=datetuple[1]
print(calendar.month(datetuple[0],month))
obj=calendar.Calendar()
days=[]
days_name=[]
days_dict={}
for d in obj.itermonthdates(datetuple[0],month):
days.append(d)
print(days[len(days)-7:len(days)])
for d in obj.itermonthdays(datetuple[0],month):
days_name.append(d)
days_dict["Monday"]=0
days_dict["Tuesday"]=0
days_dict["Wednesday"]=0
days_dict["Thursday"]=0
days_dict["Friday"]=0
days_dict["Saturday"]=0
days_dict["Sunday"]=0
for i in range(0,len(days_name)):
if(days_name[i]!=0):
if i in (0,7,14,21,28):
days_dict["Monday"]+=1
elif i in(1,8,15,22,29):
days_dict["Tuesday"]+=1
elif i in(2,9,16,23,30):
days_dict["Wednesday"]+=1
elif i in(3,10,17,24,31):
days_dict["Thursday"]+=1
elif i in(4,11,18,25,32):
days_dict["Friday"]+=1
elif i in(5,12,19,26,33):
days_dict["Saturday"]+=1
elif i in(6,13,20,27,34):
days_dict["Sunday"]+=1
days_sorted=sorted(days_dict.keys(),key=lambda x:days_dict[x],reverse=True)
print(days_sorted[0])
if __name__ == '__main__':
qw1 = []

for _ in range(3):
qw1_item = int(input().strip())
qw1.append(qw1_item)

tup=tuple(qw1)

usingcalendar(tup)

String methods:
import math
import os
import random
import re
import sys

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


word1=para
for i in special1:
word1=word1.replace(i,'')
word2=word1[0:70]
word2=word2[-1:-71:-1]
print(word2)
l=special2.join(list(word2.replace(" ",'')))
print(l)
count=0
for i in list1:
if (i in para):count+=1
if count==len(list1):
print("Every string in ",list1,"were present")
else:print("Every string in ",list1,"were not present")
print(word1.split()[0:20])
list2=list()
freq=[]
for i in word1.split(" "):
if word1.count(i)<13:
if i in freq:pass
else:freq.append(i)
list2=freq[-1:-21:-1]
print(list2[-1:-21:-1])
print(word1.rindex(strfind))
# Write your code here

if __name__ == '__main__':
para = input()

spch1 = input()

spch2 = input()

qw1_count = int(input().strip())

qw1 = []

for _ in range(qw1_count):
qw1_item = input()
qw1.append(qw1_item)

strf = input()

stringmethod(para, spch1, spch2, qw1, strf)

You might also like