0% found this document useful (0 votes)
49 views1 page

Functions and Dictionaries Assignment

Uploaded by

Anish Garg
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)
49 views1 page

Functions and Dictionaries Assignment

Uploaded by

Anish Garg
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/ 1

In 

[13]:
# Q1. Write a function called display menu that displays the menu to the user and allows the user to make a choice.

def displayMenu():

print('a. Message')

print('b. Contact')

print('c. Games')

option = input('Enter your choice(a/b/c) :')

if option == 'a':

message()

elif option == 'b':

contact()

elif option == 'c':

games()

else :

print('Incorrect choice')

def message():

name = input('Recipient name : ')

text = input('Text : ')

print(name,':')

print(' ',text)

def contact():

phonedict = {}

print('a. Add a contact')

print('b. Delete a contact')

choice = input('Enter your choice(a/b) : ')

if choice == 'a':

name = input('Enter name of contact : ')

if name not in phonedict:

number = input('Enter number of your contact')

phonedict.update({name : number})

print('Your contact list :-')

for key in phonedict:

print(key,':',phonedict[key])

else :

print('Contact with this name already exists!')

elif choice == 'b':

nam = input('Enter contact name to be deleted : ')

if nam in phonedict:

del phonedict[nam]

else :

print('This contact doesn\'t exist')

else :

print('Incorrect choice!')

def games():

print('Games trial version has been finished, buy now to play them!')

displayMenu()

a. Message
b. Contact
c. Games

Enter your choice(a/b/c) :a

Recipient name : Rahul

Text : How are you? I am coming to meet you soon.

Rahul :

How are you? I am coming to meet you soon.

In [20]:
# Q2. Purchasing someting online on the internet. Write a function to take price of the item and a boolean varialble indicating

# that you are a member and returns the final discounted value.

def cal():

price = float(input('Enter price of the item : Rs.'))

num = int(input('Are you a member(1 - yes/0 - no)'))

if num:

member = True

else :

member = False

if member:

discountedPrice = price - ((price*15)/100)

else :

discountecPrice = price - ((price*5)/100)

print('Your price : Rs.',price)

print('Discounted Price : Rs.',discountedPrice)

cal()

Enter price of the item : Rs.12334

Are you a member(1 - yes/0 - no)1

Your price : Rs. 12334.0

Discounted Price : Rs. 10483.9

In [3]:
# Q3. Write a function to shift the numbers circularly by some integer k(where k<n). The function should take a list and k as

# arguments and return the shifted list.

def userInput():

lst = input('Enter elements separated by space : ').split(' ')

factor = int(input('Enter the integer \'k\' to shift the elements (k < elements): '))

direc = input('Enter the direction in which to be shifted (r -> right/l -> left) : ')

print('Original list :',lst)

shift(lst,factor,direc)

def shift(lst,factor,direc):

if direc == 'r':

print('shifted by',factor,'to the right:',lst[-factor:]+lst[:len(lst)-factor])

elif direc == 'l':

print('shifted by',factor,'to the left:',lst[factor:]+lst[:factor])

userInput()

Enter elements separated by space : 0 1 2 3 4 5 6 7 8 9

Enter the integer 'k' to shift the elements (k < elements): 4

Enter the direction in which to be shifted (r -> right/l -> left) : r

Original list : ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

shifted by 4 to the right: ['6', '7', '8', '9', '0', '1', '2', '3', '4', '5']

In [5]:
# Q4. Write a function for checking speed of drivers. This function should have one parameter : speed.

def func(speed):

if speed <= 70:

print('OK')

else :

points = (speed - 70) // 5

print('Points :',points)

if points > 12:

print('License suspended!')

speed = int(input('Enter speed : '))

func(speed)

Enter speed : 150

Points : 16

License suspended!

In [2]:
# Q5. Write a function that returns the sum of multiples of 3,5,7 between 0 and limit(parameter).

lst = []

def cal(limit):

sum = 0

for x in range(limit+1):

if (x % 3 == 0) or (x % 5 == 0) or (x % 7 == 0):

lst.append(x)

sum += x

return sum

limit = int(input('Enter limit of the range : '))

print('Sum of : ',lst,'=',cal(limit))

Enter limit of the range : 20

Sum of : [0, 3, 5, 6, 7, 9, 10, 12, 14, 15, 18, 20] = 119

In [5]:
# Q6. Write a function named right_justify.

def right_justify(s):

print(s.center(70))

string = input('Enter a string : ')

right_justify(string)

Enter a string : string

string

In [7]:
# Q7. Write a function to check if a given number is a Curzon number.

def isCurzon(n):

if (2 ** n + 1) % (2 * n + 1) == 0:

return True

else:

return False

num = int(input('Enter a number : '))

print('Number is Curzon :',isCurzon(num))

Enter a number : 5

Number is Curzon : True

In [2]:
# Q8. Write a function that takes an integer(radius of circle) and returns the difference of areas of the squares.

def difference(r):

bigSquareArea = (2*r)**2

smallSquareArea = 2*(r**2)

return bigSquareArea - smallSquareArea

radius = int(input('Enter radius of the circle(in cm): '))

print('Difference of the areas of the two squares :',difference(radius),'cm sq.')

Enter radius of the circle(in cm): 5

Difference of the areas of the two squares : 50 cm sq.

In [3]:
# Q9. Write a function to take no. of balls bowled and return how many overs have been completed.

def overs(balls):

ov = str(balls//6) + '.' + str(balls%6)

print('Overs done :',ov)

balls = int(input('Enter number of balls bowled by the bowler : '))

overs(balls)

Enter number of balls bowled by the bowler : 45

Overs done : 7.3

In [5]:
# Q10. Financial institution provides professional services to banks.

def billableDays(days):

if days <= 32:

bonus = 32 * 0

elif days <= 40:

bonus = (days - 32)*325

elif days <= 48:

bonus = (8*325) + ((48 - days)*550)

else:

bonus = (8*325) + (8*550) + ((days - 48)*600)

return bonus

days = int(input('Enter number of billable days : '))

print('Bonus obtained : $',billableDays(days))


Enter number of billable days : 50

Bonus obtained : $ 8200

In [2]:
# Q11. Take a paragraph from user. Calculate frequency of vowels store it in dictionary.

def userInput():

lines = []

vowelDic = {'a':0, 'e':0, 'i':0, 'o':0, 'u':0}

print('Enter a paragraph :')

print('Enter a single dot \'.\' in an empty line to end your input!')

while True:

sen = input()

lines.append(sen)

if sen == '.':

break

for x in lines:

vowelDic['a'] += x.count('a')

vowelDic['e'] += x.count('e')

vowelDic['i'] += x.count('i')

vowelDic['o'] += x.count('o')

vowelDic['u'] += x.count('u')

print(vowelDic)

userInput()

Enter a paragraph :

Enter a single dot '.' in an empty line to end your input!

This is to inform you that i am Tanishk Hada

and i will not be able to come in school today

because i am having fever.

So, grant me leave.

{'a': 13, 'e': 10, 'i': 10, 'o': 10, 'u': 2}

In [4]:
# Q12. Take numbers from user until he says 'over'.If number is odd add it in dictionary 'Odd' else add in 'Even'.

def evenOdd():

even = {}

odd = {}

while True:

n = input('Enter a number(enter \'over\' to stop) : ')

if n == 'over':

break

elif int(n) % 2 == 0:

lst = values(int(n))

even.update({n:lst})

elif int(n) % 2 != 0:

lst = values(int(n))

odd.update({n:lst})

else :

print('Invalid input!')

print('Even dicionary :-\n',even)

print('Odd dictionary :-\n',odd)

def values(n):

lst = []

lst.append(n*n)

lst.append(n*n*n)

return lst

evenOdd()

Enter a number(enter 'over' to stop) : 2

Enter a number(enter 'over' to stop) : 3

Enter a number(enter 'over' to stop) : 4

Enter a number(enter 'over' to stop) : 5

Enter a number(enter 'over' to stop) : over

Even dicionary :-

{'2': [4, 8], '4': [16, 64]}

Odd dictionary :-

{'3': [9, 27], '5': [25, 125]}

In [3]:
# Q13. Given a list of numbers create a new list such that first and last numbers are added and stored as first number and so

# on. In case of odd number of integers leave central element as it is.

def construct(lst):

l = len(lst)

newLst = []

if l % 2 == 0:

for x in range(l):

newLst.append(lst[x] + lst[l-(x+1)])

else :

for x in range(l):

if x == (l//2):

newLst.append(lst[x])

else:

newLst.append(lst[x] + lst[l-(x+1)])

print('New list :',newLst)

print('Enter numbers separated by space :-')

lst = list(map(int,input().split()))

construct(lst)

Enter numbers separated by space :-

1 2 3 4 5

New list : [6, 6, 3, 6, 6]

In [10]:
# Q14. The letters a,b,d,e,g,o,p and q all have something in common.

def countInLowerCase(sen):

withHoles = 0

withoutHoles = 0

for x in 'abdegopq':

withHoles += sen.count(x)

for x in 'cfghijklmnrstuvwxyz':

withoutHoles += sen.count(x)

print('Number of lowercase letters with Holes :',withHoles)

print('Number of lowercase letters without Holes :',withoutHoles)

def countInUpperCase(sen):

withHoles = 0

withoutHoles = 0

for x in 'ABDOPQR':

withHoles += sen.count(x)

for x in 'CEFGHIJKLMNSTUVWYZ':

withoutHoles += sen.count(x)

print('Number of uppercase letters with Holes :',withHoles)

print('Number of uppercase letters without Holes :',withoutHoles)

def wordList(sen):

print()

print('Words with 2 or more letters with holes :-\n')

for x in sen.split(' '):

count = 0

for y in 'abdegopqABDOPQR':

if x.count(y) == 2:

print(x)

break
elif y in x:

count += 1

if count == 2:

print(x)

break

sen = input('Enter a sentence : ')

countInLowerCase(sen.lower())

countInUpperCase(sen.upper())

wordList(sen)

Enter a sentence : how are you buddy

Number of lowercase letters with Holes : 7

Number of lowercase letters without Holes : 7

Number of uppercase letters with Holes : 7

Number of uppercase letters without Holes : 7

Words with 2 or more letters with holes :-

are

buddy

In [3]:
# Q15. Sally invited 17 guests to a dance party. She assigned each guest a number from 2 to 18, keeping 1 for herself.

def combinations(n):

mainlst = []

finallst = []

numlst = []

perfectSq = [4,9,16,25]

for x in range(1,n+1):

for y in range(1,n+1):

if (y != x) and ((x+y) in perfectSq):

numlst.append((x,y))

mainlst.append(numlst)

numlst = []

print(mainlst)

combinations(18)

[[(1, 3), (1, 8), (1, 15)], [(2, 7), (2, 14)], [(3, 1), (3, 6), (3, 13)], [(4, 5), (4, 12)], [(5, 4), (5, 11)], [(6, 3), (6, 10)], [(7, 2), (7, 9), (7, 18)], [(8, 1), (8, 17)],
[(9, 7), (9, 16)], [(10, 6), (10, 15)], [(11, 5), (11, 14)], [(12, 4), (12, 13)], [(13, 3), (13, 12)], [(14, 2), (14, 11)], [(15, 1), (15, 10)], [(16, 9)], [(17, 8)], [(18, 7)]]

In [12]:
# Q16. Using int operatiors '+','-','*','/','**' and numbers 2,3,4,5 find an expression which evaluates to 26.

from itertools import combinations

from itertools import permutations

operatorLst = ['+','-','*','/','**']

numLst = ['2','3','4','5']

def combine(oplst,nmlst):

opcomb = list(combinations(oplst,3))

nmcomb = list(permutations(nmlst))

inner = True

for x in nmcomb:

for y in opcomb:

string = x[0] + y[0] + x[1] + y[1] + x[2] + y[2] + x[3]

ans = eval(string)

if ans == 26:

print('Required expression :',string)

inner = False

break
if inner == False:

break

combine(operatorLst,numLst)

You might also like