0% found this document useful (0 votes)
5 views20 pages

UNIT 2 PDS Notes P1

The document covers various aspects of Python programming, focusing on sets, dictionaries, files, and packages. It includes detailed explanations of dictionary methods, operations, and comparisons, as well as advanced list processing techniques like list comprehension. Additionally, it presents illustrative programs for sorting algorithms, matrix operations, and a retail billing system.

Uploaded by

shriyanth
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)
5 views20 pages

UNIT 2 PDS Notes P1

The document covers various aspects of Python programming, focusing on sets, dictionaries, files, and packages. It includes detailed explanations of dictionary methods, operations, and comparisons, as well as advanced list processing techniques like list comprehension. Additionally, it presents illustrative programs for sorting algorithms, matrix operations, and a retail billing system.

Uploaded by

shriyanth
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/ 20

UNIT II SETS, DICTIONARIES, FILES,PACAGES

Sets – operations - methods; Dictionaries - operations and methods; advanced listprocessing


- list comprehension. Files and exceptions: text files - reading and writing files - format
operator; command line arguments - Errors and exceptions - handling exceptions - Modules
- Packages; Illustrative Programs
DICTIONARIES
1. Describe in detail about dictionary methods. (or) What is Dictionary? Give an example.
(8 MARKS) (DEC 2018)
2.Give a function that can take a value and return the first key mapping to that value in a
Dictionary. (2 MARKS) (JAN 2019)
3. Define Dictionary in python. Do the following operations on dictionaries.
(10 MARKS) (NOV 2019)
i) Initialize two dictionaries with key and value pairs.
ii) Compare two dictionaries with master key list and print missing keys. iii)
Find keys that are in first and not in second dictionary.
iv) Find same keys in two dictionaries.
v) Merge two dictionaries and create a new dictionary using a single expression.
4.How python dictionaries store data? Give example. (2 MARKS) (DEC 2018)
5.Write a python program to create a dictionary and sort the contents based on the values in
reverse order. (8 MARKS) (JAN 2022)

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'}

accessing an >>> a[1] Accessing the elements by using


element 'one' keys.
>>> a[0]
KeyError: 0
Update >>> a[1]="ONE" Assigning a new value to key. It
>>> print(a) replaces the old value by new
{1: 'ONE', 2: 'two'} value.
add element >>> a[3]="three" Add new element in to the
>>> print(a) dictionary with key.
{1: 'ONE', 2: 'two', 3: 'three'}
membership a={1: 'ONE', 2: 'two', 3: 'three'} Returns True if the key is
>>> 1 in a present in dictionary. Otherwise
True returns false.
>>> 3 not in a
False

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.

Difference between List, Tuples and dictionary:

List Tuples Dictionary


A list is mutable A tuple is immutable A dictionary is mutable
Lists are dynamic Tuples are fixed size in nature In values can be of any
data type and can
repeat, keys must be of
immutable type
List are enclosed in Tuples are enclosed in Tuples are enclosed in curly
Brackets [ ] and their elements parenthesis ( ) and cannot be braces { } and consist of key:value
and size can be changed updated
Homogenous Heterogeneous Homogenous
Example: Example: Example:
List = [10, 12, 15] Words = ("spam", "egss") or Dict = {"ram": 26, "abi":24}
Words = "spam", "eggs"
Access: Access: Access:
print(list[0]) print(words[0]) print(dict["ram"])

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

Usage: Usage: Usage:


 List is used if a
collection of data that  Tuple can be used when  Dictionary is used when a
does not need random data cannot be changed. logical association between
access.  A tuple is used in key:value pair.
 List is used when combination  When in need of fast lookup
 data can be modified  with a dictionary i.e.a tuple for data, basedon a custom
frequently mightrepresent a key. key.
 Dictionary is used when
data is being constantly
modified.

ADVANCED LIST PROCESSING:

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 ]

List Comprehension Output

>>>L=[x**2 for x in range(0,5)] [0, 1, 4, 9, 16]


>>>print(L)
>>>[x for x in range(1,10) if x%2==0] [2, 4, 6, 8]
>>>[x for x in 'Python Programming' if x in ['a','e','i','o','u']] ['o', 'o', 'a', 'i']
>>>mixed=[1,2,"a",3,4.2] [1, 4, 9]
>>> [x**2 for x in mixed if type(x)==int]
>>>[x+3 for x in [1,2,3]] [4, 5, 6]

>>> [x*x for x in range(5)] [0, 1, 4, 9, 16]

>>> num=[-1,2,-3,4,-5,6,-7] [2, 4, 6]


>>> [x for x in num if x>=0]

>>> str=["this","is","an","example"] ['t', 'i', 'a', 'e']


>>> element=[word[0] for word in str]
>>> print(element)

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)

Matrix transpose Output


a=[[1,3],[1,2]] [1, 1]
c=[[0,0],[0,0]] [3, 2]
for i in range(len(a)):
for j in range(len(a)):
c[i][j]=a[j][i]
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

def str (self):


return self.name + ' : ' + str(self.getroll()) +' ::'+ str(self.getmarks())

# Defining a function for building a Record


# which generates list of all the students
def Markss(rec, name, roll, marks):
rec.append(Student(name, roll, marks))
return rec
# Main Code
Record = []
x = 'y'
while x == 'y':
name = input('Enter the name of the student: ')
height = input('Enter the roll number: ')
roll = input('Marks: ')
Record = Markss(Record, name, roll, height)
x = input('another student? y/n: ')
# Printing the list of student
n=1
for el in Record:
print(n,'. ', el)
n=n+1

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

RETAIL BILL PREPARATION


Program:
Write a Python Program to calculate sale bill for the selling items in a Fruit Shop.

Consider the following dictionary as a item database.


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}
}

Initially the transaction dictionary is Null.


trans = {}
Code the following tasks to implement Billing System for a Fruit Shop.

1. Add Fruits to the System


a. Check whether the fruit is exists in database
b. if exists, Get id & Quantity and add the quantity to existing quantity
c. if not exists, Get id, name,quantity & price and add to dictionary

2. Calculate Bill During Sale.


a. Get id & quantity and calculate bill for one or more items
b. Calculate amount for each item
c. Reduce the sold quantity of corresponding item in items database.
d. Add item to transaction as below
trans = {201:{101:[2,400],104:[.5,35]}}
Here in Transaction 201: 2 kg apples for $400 and half kg lemon for $35 were sold.
e. Display items, quantity, amount and total on each item entry

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'])

item_id = int(input("Enter item id (if existing)/Enter 0 (if New)"))


if item_id == 0:
add_new_item()
else:
#Check for Valid Item ID
while not item_id in items:
print("Not Valid Item id")
item_id = int(input("Enter item id:"))
update_item(item_id)
#Billing
def sale(trans_id):
total = 0
transaction_items = {}
while True:
item_id = int(input("Enter item id (0 if no item):"))
if item_id == 0:
break
else:
while not item_id in items:
print("Not Valid Item id")
item_id = int(input("Enter item id:"))
quantity = int(input("Enter Quantity:"))
amount = items[item_id]['Price_per_kg'] * quantity
items[item_id]['Quantity_in_kgs'] = items[item_id]['Quantity_in_kgs'] - quantity
total += amount
transaction_items[item_id] = [quantity,amount]
print('Item id | Item Name | Quantity | Price | Amount')
for item in transaction_items:
print(item, "| ", items[item]['item_name'], " | ",transaction_items[item][0], " | ",
items[item]['Price_per_kg'], " | ", transaction_items[item][1])
print("------------------------------------------------- ")
print("Total:\t\t\t ", total)
trans[trans_id] = transaction_items
#Main Function
while True:
print("Billing System\n Enter Your Choice \n 1. Add Items \n 2. Sales \n 3. Check Stock
\n 4. Exit ")
choice = int(input("Your Choice:"))
if choice == 1:
add_item()
elif choice == 2:

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:

You might also like