UNIT 2 PDS Notes P1
UNIT 2 PDS Notes P1
DICTIONARIES:
Dictionary is an unordered collection of elements. An element in dictionary has a key:
value pair.
All elements in dictionary are placed inside the curly braces i.e. { }
Elements in Dictionaries are accessed via keys and not by their position.
The values of a dictionary can be any data type.
Keys must be immutable data type (numbers, strings, tuple)
Operations Example Description
Creating a >>> a={1:"one",2:"two"} Creating the dictionary with
dictionary >>> print(a) elements of different data types.
{1: 'one', 2: 'two'}
METHODS IN DICTIONARY:
Method Example Description
a.copy( ) a={1: 'ONE', 2: 'two', 3: 'three'} It returns copy of the
>>> b=a.copy() dictionary. here copy of
>>> print(b) dictionary ’a’ get stored
{1: 'ONE', 2: 'two', 3: 'three'} in to dictionary ‘b’
a.items() >>> a.items() Return a new view of
dict_items([(1, 'ONE'), (2, 'two'), the dictionary's items. It
(3, displays a list of
'three')]) dictionary’s (key, value)
tuple pairs.
a.keys() >>> a.keys() It displays list of keys in
dict_keys([1, 2, 3]) a dictionary
a.values() >>> a.values() It displays list of values
dict_values(['ONE', 'two', in dictionary
'three'])
a.pop(key) >>> a.pop(3) Remove the element
'three' with key and return its
>>> print(a) value from the
{1: 'ONE', 2: 'two'} dictionary.
setdefault(key,value) >>> a.setdefault(3,"three") If key is in the
'three' dictionary, return its
>>> print(a) value. If key is not
{1: 'ONE', 2: 'two', 3: 'three'} present, insert key with
>>> a.setdefault(2) a value of dictionary and
'two' return dictionary.
a.update(dictionary) >>> b={4:"four"}
It will add the dictionary
>>> a.update(b)
>>> print(a) with the existing
{1: 'ONE', 2: 'two', 3: 'three', 4: dictionary
'four'}
fromkeys() >>> key={"apple","ball"} It creates a dictionary
>>> value="for kids" from key and values.
>>> d=dict.fromkeys(key,value)
>>> print(d)
{'apple': 'for kids', 'ball': 'for
kids'}
len(a) a={1: 'ONE', 2: 'two', 3: 'three'} It returns the length of
>>>lena(a) the list.
3
clear() a={1: 'ONE', 2: 'two', 3: 'three'} Remove all elements
>>>a.clear() form the dictionary.
>>>print(a)
>>>{ }
del(a) a={1: 'ONE', 2: 'two', 3: 'three'} It will delete the entire
>>> del(a) dictionary.
Can contain duplicate Can contain duplicate elements. Cant contain duplicate keys, but
elements Faster compared to lists can contain duplicate values
Slicing can be done Slicing can be done Slicing can't be done
List Comprehension:
List comprehensions provide a concise way to apply operations on a list.
It creates a new list in which each element is the result of applying a given operation in a
list.
It consists of brackets containing an expression followed by a “for” clause, then a list.
The list comprehension always returns a result list.
Syntax
list=[ expression for item in list if conditional ]
Nested List:
List inside another list is called nested list.
Example:
>>> a=[56,34,5,[34,57]]
>>> a[0] 56
>>> a[3] [34, 57]
>>> a[3][0] 34
>>> a[3][1] 57
Programs on matrix:
Matrix addition Output
a=[[1,1],[1,1]] [3, 3]
b=[[2,2],[2,2]] [3, 3]
c=[[0,0],[0,0]]
for i in range(len(a)):
for j in range(len(b)):
c[i][j]=a[i][j]+b[i][j]
for i in c:
print(i)
Matrix multiplication Output
a=[[1,1],[1,1]] [3, 3]
b=[[2,2],[2,2]] [3, 3]
c=[[0,0],[0,0]]
for i in range(len(a)):
for j in range(len(b)):
for k in range(len(b)):
c[i][j]=a[i][j]+a[i][k]*b[k][j]
for i in c:
print(i)
ILLUSTRATIVE PROGRAMS
1.Demonstrate with simple code to draw the histogram in python. (8 MARKS)(MAY 2019)
2.Write a Python program for merge sort. (8 MARKS)(MAY 2019)
SELECTION SORT
Program:
a=input("Enter list:").split()
a=list(map(eval,a))
for i in range(0,len(a)):
smallest = min(a[i:])
sindex= a.index(smallest)
a[i],a[sindex] = a[sindex],a[i]
print (a)
Output:
Enter list:23 78 45 8 32 56
[8,2 3, 32, 45,56, 78]
INSERTION SORT
Program:
a=input("enter a list:").split()
a=list(map(int,a))
for i in a:
j = a.index(i)
while j>0:
if a[j-1] > a[j]:
a[j-1],a[j] = a[j],a[j-1]
else:
break
j = j-1
print (a)
Output:
enter a list: 8 5 7 1 9 3
[1,3,5,7,8,9]
MERGE SORT
Program:
def merge(a,b):
c = []
while len(a) != 0 and len(b) != 0:
if a[0] < b[0]:
c.append(a[0])
a.remove(a[0])
else:
c.append(b[0])
b.remove(b[0])
if len(a) == 0:
c=c+b
else:
c=c+a
return c
def divide(x):
if len(x) == 0 or len(x) == 1:
return x
else:
middle = len(x)//2
a = divide(x[:middle])
b = divide(x[middle:])
return merge(a,b)
x=[38,27,43,3,9,82,10]
c=divide(x)
print(c)
Output:
[3,9,10,27,38,43,82]
HISTOGRAM
def histogram(a):
for i in a:
sum = ''
while(i>0):
sum=sum+'#'
i=i-1
print(sum)
a=[4,5,7,8,12]
histogram(a)
Output
****
*****
*******
********
************
STUDENTS MARK STATEMENT
Program:
# Defining a class student, which contain name, Roll number and marks of the student.
class Student(object):
def init (self, name, roll, marks):
self.name = name
self.roll = roll
self.marks = marks
def getmarks(self):
return self.marks
def getroll(self):
return self.roll
Output:
Enter the name of the student: ravi
Enter the roll number: 1234
Marks: 80
another student? y/n: y
Enter the name of the student: shilpa
Enter the roll number: 1235
Marks: 60
another student? y/n: y
Enter the name of the student: gowtham
Enter the roll number: 1236
Marks: 90
another student? y/n: y
Enter the name of the student: yasodha
Enter the roll number: 1231
Marks: 100
another student? y/n: n
1 . ravi : 80 ::1234
2 . shilpa : 60 ::1235
3 . gowtham : 90 ::1236
4 . yasodha : 100 ::1231
102:{'item_name':'Banana','Quantity_in_kgs':30,'Price_per_kg':80},
103:{'item_name':'Grapes','Quantity_in_kgs':25,'Price_per_kg':300},
104:{'item_name':'Lemon','Quantity_in_kgs':20,'Price_per_kg':70}
}
3. Check Stock
a. Display the items and available quantity
b. Highlight the items which are available less than 5 kgs.
Program:
items = {101:{'item_name':'Apple','Quantity_in_kgs':50,'Price_per_kg':200},
102:{'item_name':'Banana','Quantity_in_kgs':30,'Price_per_kg':80},
103:{'item_name':'Grapes','Quantity_in_kgs':25,'Price_per_kg':300},
104:{'item_name':'Lemon','Quantity_in_kgs':20,'Price_per_kg':70}}
trans = {}
#Stock Printing
def stock_check():
print("Item Name | Available Stock")
for item_id in items:
if items[item_id]['Quantity_in_kgs'] <= 5:
print("---------------------------------------")
print("| ",items[item_id]['item_name'], " | ",items[item_id]['Quantity_in_kgs']," |")
print("---------------------------------------")
else:
print("| ",items[item_id]['item_name'], " | ",items[item_id]['Quantity_in_kgs']," |")
#Add New Item to Database
def add_new_item():
item_ids = list(items.keys())
item_id = max(item_ids) + 1
item_name = input("Enter Item Name:")
price = int(input("Enter Price Per Kilo Gram:"))
quantiy = int(input("Enter Quantity"))
item = {'item_name':item_name,'Quantity_in_kgs':quantiy,'Price_per_kg':price}
items[item_id]= item
print('Item Added')
print('Item id | Item Name | Quantity | Price ')
print(item_id, " | ", item_name, " | ", quantiy, " | ", price)
#Update the Quantity of Existing Item
def update_item(item_id):
quantiy = int(input("Enter Quantity"))
items[item_id]['Quantity_in_kgs'] = items[item_id]['Quantity_in_kgs'] + quantiy
print('Item Updated')
print('Item id | Item Name | Quantity | Price ')
print(item_id, " | ", items[item_id]['item_name'], " | ", items[item_id]['Quantity_in_kgs'], " |
", items[item_id]['Price_per_kg'] )
#Stock Entry
def add_item():
item_name = input("Enter the Item Name")
print("item id | item name")
print(" ---------------- ")
for item in items:
if item_name in items[item]['item_name']:
print(item, " | ", items[item]['item_name'])
trans_ids = list(trans.keys())
if len(trans_ids) == 0:
trans_id = 201
else:
trans_id = max(trans_ids) + 1
sale(trans_id)
elif choice == 3:
stock_check()
elif choice == 4:
break
else:
print("Invalid Choice")
Program Explanation:
_item() method checks whether the item is existing item or new item to the fruit shop.if
item is new then it calls add_new_item() method else it call update_item() method.
sale() method gets detail of each item and fetch price from dictionary to calculate amount.
amount will be added to the total. Sale() method finally decrease the sold quantity in item
dictionary.
stock_check() method prints all items and its available quantity.
Output:
Billing System
Enter Your Choice
1. Add Items
2. Sales
3. Check Stock
4. Exit
Your Choice:3
Item Name | Available Stock
| Apple | 50 |
| Banana | 30 |
| Grapes | 25 |
| Lemon | 20 |
Billing System
Enter Your Choice
1. Add Items
2. Sales
3. Check Stock
4. Exit
Your Choice:1
Enter the Item Name Apple
Apple
item id | item name
-----------------
101 | Apple
Enter item id (if existing)/Enter 0 (if New)101
Enter Quantity100
Item Updated
Item id | Item Name | Quantity | Price
101 | Apple | 150 | 200
Billing System
Enter Your Choice
1. Add Items
2. Sales
3. Check Stock
4. Exit
Your Choice:3
Item Name | Available Stock
| Apple | 150 |
| Banana | 30 |
| Grapes | 25 |
| Lemon | 20 |
Billing System
Enter Your Choice
1. Add Items
2. Sales
3. Check Stock
4. Exit
Your Choice:2
Enter item id (0 if no item):102
Enter Quantity:10
Item id | Item Name | Quantity | Price | Amount
102 | Banana | 10 | 80 | 800
---------------------------------------------------
Total: 800
Enter item id (0 if no item):0
Billing System
Enter Your Choice
1. Add Items
2. Sales
3. Check Stock
4. Exit
Your Choice: