Type C Solutions
Type C Solutions
Tuples
1. Write a Python program that creates a tuple storing first 9 terms of Fibonacci series.
# Code
fib = (0,1,1)
for i in range(6):
fib = fib + ( fib [ i +1] + fib [ i + 2 ] ,)
print(fib)
2.(a). Write a program that receives the index and returns the corresponding value.
(b). Write a program that receives a Fibonacci term and returns a number telling which
term it is. For instance, if you pass 3 it returns 5, telling it 5th term, for 8 it returns 7.
Program:
fib=(0,1,1,2,3,5,8,13,21)
#display the values based on its index (solution for (a))
i=int(input("Enter index:"))
print(fib[i])
#display the position of the values in the series (solution for (b))
f=int(input("Enter fibonacci term"))
print(f,"comes at position",fib.index(f)+1, "in the fibonacci sequence")
OR
a)
a = eval (input('Enter the list ='))
b = int (input ("Enter the index number ="))
if b< len(a):
print ("value is =", a[b])
else :
print ("index out of range")
b)
term= int (input ("Enter the term of seris ="))
fib = (0,1,1)
for i in range(term):
fib = fib + ( fib [ i + 1] + fib [ i + 2 ],)
for j in range(len(fib)):
if term == fib[ j ] :
1
break
print("this is ",j + 1,"th of fibonocci ")
3. Write a program that interactively creates a nested tuple to store the marks in three
subjects for five students, i.e., tuple will look somewhat like :
marks((45,45,40),(35,40,38),(36,30,38),(25,27,20),(10,15,20))
Program:
total = ()
for i in range(3):
mark = ()
mark1 = int(input("enter the marks of first subject = "))
mark2 = int(input("enter the marks of second subject = "))
mark3 = int(input("enter the marks of third subject = "))
mark = (mark1 , mark2 , mark3)
total= total + (mark,)
print("total marks = ",total)
4. In the program created in previous question, add a function that computes total marks
and average marks obtained by each student.
Program:
def comp(m):
print("Total marks of 1st student is",m[0][0]+m[0][1]+m[0][1])
print("Average marks of 1st student is",(m[0][0]+m[0][1]+m[0][1])/3)
OR
for i in range(3):
mark1 = int(input("enter the marks of first subject = "))
mark2 = int(input("enter the marks of second subject = "))
mark3 = int(input("enter the marks of third subject = "))
print("total marks of",i+1,"student = ", mark1 + mark2 + mark3)
print("average marks of",i+1,"student = ", (mark1 + mark2 + mark3 )/3)
2
5. Write a program that inputs two tuples and creates a third, that contains all elements of
the first followed by all elements of the second.
Program:
OR
“Return the length of the shortest string in the tuple of strings str_tuple.
Precondition: the tuple will contain at least one element.”
Program:
str_tuple=tuple(input("Enter tuple of strings:").split()) #split() splits the input on whitespace
l=float("inf") #float(“inf”) is a very big number used to compare with other numbers, it is
#bigger than any decimal number
for i in range(len(str_tuple)):
if len(str_tuple[i])<l:
l=len(str_tuple[i])
print("Length of shortest in the tuple is ",l)
OR
Program:
OR
tup = ()
for i in range(1,51):
tup = tup + ( i,)
print(tup)
(b) the tuple (“a”,”bb”,”ccc”,”dddd”,...) that ends with 26 copies of the letter z.
Program:
t=tuple(chr(i)*(i-96) for i in range(97,123)) #chr() is used to convert an ascii number into a #ascii
character
print(t)
OR
tup = ()
for i in range(1 , 26):
tup = tup + ( chr(i + 96 )* i ,)
print(tup)
8. Given a tuple pairs = ((2, 5), (4, 2), (9, 8), (12,10)), count the number of pairs (a, b) such
that both a and b are even.
Program:
pairs=((2,5),(4,2),(9,8),(12,10))
c=0
for i in range(len(pairs)):
if (pairs[i][0]%2==0 and pairs[i][1]%2==0):
c+=1
print("There are",c,"pairs with both the numbers are even")
9. Write a program that inputs two tuples seq_a and seq_b and prints True if every
element in seq_a is also an element of seq_b, else prints False.
Program:
OR
tup1 = eval(input("enter first tuple = "))
tup2 = eval(input("enter second tuple = "))
count = 0
if len(tup1)==len(tup2):
for i in range(len(tup1)) :
if tup1[i] == tup2 [ i ] :
continue
else :
count += 1
if count == 0 :
print("True")
else :
print("False")
else :
print("False")
11. Mean of means. Given a nested tuple tup1 = ( (1, 2), (3, 4.15, 5.15), ( 7, 8, 12, 15)). Write
a program that displays the means of individual elements of tuple tup1 and then displays
the mean of these computed means . That is for above tuple, it should display as :
Program:
OR
a = eval (input ("Enter the numeric tupal ="))
b=0
for i in range (len(a)):
b = b +a[i]
print('mean of tupal=',b/len(a))
5
Dictionary
1. Repeatedly ask the user to enter a team name and how many games the team has won
and how many they lost. Store this information in a dictionary where the keys are the team
names and the values are lists of the form [wins, losses].
(a) Using the dictionary created above, allow the user to enter a team name and print out the
team’s
winning percentage.
(b) Using the dictionary, create a list whose entries are the number of wins of each team.
(c) Using the dictionary, create a list of all those teams that have winning records.
# Code
n=int(input("How many teams?"))
CompWinners={}
for a in range(n):
key=input("Name of the Team:")
wins=int(input("Number of games won:"))
lost=int(input("Number of games lost:"))
CompWinners[key]=[wins,lost]
print("The dictionary now is")
print(CompWinners)
t=input("Enter team name")
print("Winning percentage of", t,"is",(CompWinners[t][0]/sum(CompWinners[t]))*100)
winteam=[i[0] for i in CompWinners.values()]
print("Number of wins in each team")
print(winteam)
winrec=[]
for i in CompWinners:
if CompWinners[i][0]>0:
winrec.append(i)
print("List of winning team")
print(winrec)
OR
dic ={}lstwin = []lstrec = []while True : name = input ("Enter the name of team (enter q for
quit)=")
2. Write a program that repeatedly asks the user to enter product names and prices. Store
all of these in a dictionary whose keys are the product names and whose values are the
prices. When the user is done entering products and prices, allow them to repeatedly enter
a product name and print the corresponding price or a message if the product is not in the
dictionary.
# Code
n = int(input("Enter number of products :"))
prod = {}
for i in range(n):
p = input("Enter product name :")
prod[p] = int(input("Enter its price :"))
q = True
while q:
p = input("Enter product for price or q to exit:")
if p == "q":
break
if p in prod:
print("price of", p, "is", prod[p])
else:
print(p, "is not here")
OR
dic = { }
while True :
product = input("enter the name of product (enter q for quit )= ")
if product == "q" or product == "Q" :
break
else :
price = int(input("enter the price of product = "))
dic [ product ] = price
while True :
name = input("enter the name of product those you are entered (enter q for quit )= ")
if name == "q" or name == "Q" :
break
else :
if name not in dic :
print("name of product is invaild")
else :
print("price of product = ",dic[name])
7
3. Create a dictionary whose keys are month names and whose values are the number o f
days in the corresponding months.
a) Ask the user to enter a month name and use the dictionary to tell how manu days are in
the month
b)Print out all of the keys in alphabetical order
c) Print out all of the months with 31 days
d) Print out the (key-value) pairs sorted by the number of days in each month.
Program:
month={"January":31,"February":28,"March":31,"April":30,"May":31,"June":30,"July":31,"Aug
ust":31,"September":31,"October":31,"November":30,"December":31}
print("Display the number of days in a month")
name=input("Enter a month name")
print("Number of days in",name,"is",month.get(name.strip(),"Enter again"))
print("Arranging the month name in alphabetical order")
print(sorted(month))
print("months with 31 days")
for i in month:
if month[i]==31:
print(i,end="\t")
print()
print("key value pairs sorted with number of days in each month")
v=sorted([(i,j) for j,i in month.items()])
print([(j,i) for i,j in v])
OR
8
4. Can you store the details of 10 students in a dictionary at the same time ? Details include
– rollno, name marks, grade etc. Give example to support your answer.
Program:
details={}
for i in range(10):
n=input("Enter name:")
r=int(input("Enter roll number:"))
m=int(input("Enter marks:"))
g=input("Enter grade:")
details[n]=[r,m,g]
print(details)
OR
dic = { }
while True :
roll = input("enter the roll no. of student (enter Q for quit )= ")
if roll == "Q" or roll == "q" :
break
else :
name = input("enter the name of student = ")
mark = input("enter the marks of student = ")
grade = input("enter the grade of stucent = ")
dic[roll] = [ name , mark , grade ]
print(dic)
5. Given the dictionary x = {‘k1’: ‘v1’, ‘k2’: ‘v2’, ‘k3’: ‘v3’}, create a dictionary with the
opposite mapping i.e., write a program to create the dictionary as : inverted_x = { ‘ v1’ : ‘
k1’ , ‘ v2 ‘ : ‘ k2 ‘ , ‘ v3 ‘ : ‘ k3 ‘ }
Program:
x={"k1":"v1","k2":"v2","k3":"v3"}
y={}
for i in x:
y[x[i]]=i
print(y)
6. Given two dictionaries say D1 and D2. Write a program that lists the overlapping keys of
the two dictionaries, i.e., if a key of D1 is also a key of D2, the list it.
Program:
D1={"k1":"v1","k2":"v2","k3":"v3"}
D2={"k5":"v4","k2":"v5","k4":"v6"}
l=[]
9
for i in D1:
if i in D2:
l.append(i)
print("Keys common in both the dictionaries are:",l)
OR
Understanding Sorting
1. Election is a dictionary where key , value pair are in the form of name : votes received. Write
a program that sorts the contents of the election dictionary and create two list that stores the
sorted data . list a [i] will contain the name of the candidate and list b [i] will contain the votes
received by candidate list a[i] . print the name of candidates with votes received in decreasing
order of the number of votes received .
Program:
election = {"modi":99,"congress":40,"bsp":50,"ajp":90,"ram":60,"sita":49}
b = list(election.values())
a = list(election.keys())
print(b)
print(a)
b.sort()
dic = {}
for i in range(len(b)):
for j in a :
if b [ i ] == election [ j ] :
dic [ j ] = b [ i ]
print(dic)
2. Given the following list L that stores the names of Nobel prize winners . each element of the
list is a tuple containing details of the one nobel prize winner .
10
Write a program to short the list in the order of last names of the winners . use insertion sort
algorithm .
Program:
L = [("Wilhelm Conrad R Ontgen","Physics",1901),("Ronald Ross","Medicine",1902), ("Marie
Curie", "Physics",1903), ("Ivan Pavlov","Medicine",1904),("Henryk
Sienkiewicz","Literature",1905),("Theodore Roosevelt","Peace",1906)]
st = ''
lst = []
x=0
for a in L :
st = ''
for b in a[0]:
if b == ' ' :
st = ''
else :
st = st + b
lst.insert(x,st)
x=x+1
length = len(L)
for i in range (1 , length) :
temp = lst [ i ]
extemp = L[ i ]
j=i-1
while j>=0 and temp<lst[j]:
L[j+1] = L[j]
lst[j+1] = lst[j]
j=j-1
L[j+1] = extemp
lst[j+1] = temp
for x in L:
print(x)
3. Write a program to read a list containing three digit integer only . then write an insertion sort
function that sorts the list on the basis of one’s digit of all element .
Program:
lst = eval(input("Enter a three digit numbers list = "))
length = len(lst)
for i in range(1,length):
temp = lst[i]%10
t = lst[i]
j = i-1
while j>=0 and temp<(lst[j]%10):
lst[j+1] = lst[j]
j = j -1
lst[j+1] = t
print(lst)
11
4. Write a program to perform sorting on the given list of strings, on the basis of length of
strings. That is the smallest – length string should be the first string in the list and the largest –
length string should be the last string in the sorted list.
Program:
a = eval(input("enter a list of string = "))
for i in range (len(a)):
for j in range(len(a)-1):
if len(a [ j ] ) > len(a [ j + 1 ]) :
a[j],a[j+1]=a[j+1],a[j]
print(a)
5. Write a program that sort a list of tuple – elements in descending order of points using bubble
sort. The tuple – element of the list contain following information about different players:
(player number , player name , points )
Program:
lst = [(103 , 'ritika' , 3001),(104 ,'john',2819),(101,'razia',3451),(105,'tarandeep',2971)]
for i in range( len( lst ) - 1 ):
for j in range( len ( lst ) - 1 ):
if lst [ j ] [ 2 ] < lst [ j + 1 ] [ 2 ] :
lst [ j ] , lst [ j + 1 ] = lst [ j + 1 ] , lst [ j ]
print(lst)
12