pdsp1
pdsp1
∙∙∙
Practical – 1
AIM: Implement following programs in python. Programs related to Basics of
Python. Programs related to List, Tuple. Programs related to Set and Dictionary
• Objective: To apply basic concepts of python and its data structure to solve
problems. Apply basic concept of list, tuple, set and dictionary.
• Theory:
1) List:
➢ A list in Python is a mutable, ordered collection of items that can hold elements of
different data types. Lists allow duplicate values and can be modified after creation.
➢ Key Characteristics:
➢ Mutable: You can change, add, or remove elements after the list is created.
➢ Ordered: Items are stored in a specific order and can be accessed via an index.
➢ Allows duplicates: You can have repeated elements.
➢ Indexing: Elements are accessed by their index (starting from 0).
2) Tuple:
➢ A tuple is similar to a list but is immutable, meaning once it’s created, you cannot
change, add, or remove elements. Tuples are often used for fixed collections of
items.
➢ Key Characteristics:
➢ Immutable: Once a tuple is created, it cannot be changed.
➢ Ordered: Like lists, tuples are ordered, and elements can be accessed by index.
➢ Allows duplicates: Repeated elements are allowed.
➢ Faster than lists: Since tuples are immutable, they are generally more memory
efficient and slightly faster than lists.
3) Set:
➢ A set is an unordered collection of unique elements. Sets do not allow duplicates,
and their primary use is to eliminate duplicate entries and perform operations like
union, intersection, and difference.
➢
➢ Key Characteristics:
➢ Mutable: You can add or remove elements from a set.
➢ Unordered: Sets do not preserve the order of elements.
➢ Unique elements: No duplicate values are allowed.
➢ Efficient membership testing: Checking if an element is in a set is very fast due to
the underlying hash-table implementation.
4) Dictionary:
➢ A dictionary is an unordered collection of key-value pairs. Each key in a dictionary
is unique, and it is used to access its corresponding value.
➢ Key Characteristics:
➢ Mutable: You can add, remove, or modify key-value pairs.
➢ Unordered: As of Python 3.7+, dictionaries maintain insertion order, but they are
still conceptually unordered collections.
➢ Keys are unique: No duplicate keys are allowed, but values can be repeated.
➢ Fast lookups: Accessing a value by its key is very fast, making dictionaries ideal
for scenarios where you need to retrieve values based on some identifier.
• Procedure:
➢ List:
➢ Create a List: my_list = [item1, item2, item3, ...]
➢ Access List Elements (by index): list[index]
➢ Add an element: list.append(element)
➢ Remove an element: list.remove(element) or del list[index]
➢ Tuple:
➢ Create a Tuple: my_tuple = (item1, item2, item3, ...)
➢ Access Tuple Elements (by index): tuple[index]
➢ Dictionary:
➢ Create a Dictionary: my_dict = {key1: value1, key2: value2, ...}
➢ Access Values by Key: dict[key]
➢ Modify a Dictionary: dict[key] = value
➢ Add a new key-value pair: dict[key] = value
➢ Remove a key-value pair: del dict[key]
➢ Set:
➢ Create a Set: my_set = {item1, item2, item3, ...}
➢ Add an Element to a Set: set.add(element)
➢ Remove an Element from a Set: set.remove(element)
➢ Union: set1.union(set2)
➢ Intersection: set1.intersection(set2)
print("\"simple calculator\"")
while True:
print("enter your choice:")
print("1 for addition:")
print("2 for substraction:")
print("3 for multiplication:")
print("4 for division")
print("5 for exit:")
ch=int(input())
if(ch==5):
break
else:
a=int(input("enter number1:\t"))
b=int(input("enter number2:\t"))
match ch:
case 1:
print("addition is:",a+b)
case 2:
print("sub is:",a-b)
case 3:
print("mul is:",a*b)
case 4:
print("div is:",a/b)
case _:
print("invalid")
▪ Output:
enter your choice:
1 for addition:
2 for substraction:
3 for multiplication:
4 for division
5 for exit:
2
enter number1: 3
enter number2: 4
sub is: -1
2. Write a program in python to read two strings and display them on console.
Use input () functions. Perform basic operation on it.
8
4
SHAILESH
bhil
shailes
bhil
ile
shailesh bhil
3. Write a program to ask the user to enter name and date of birth. Display age
of the users and print the calendar for the month and year on user was born.
Also, print out a message addressed to them that tells them the year that they
will turn 100 years old.
import calendar
from datetime import datetime
name = input("Please enter your name: ")
today = datetime.today()
age = today.year - birthdate.year - ((today.month, today.day) <
(birthdate.month, birthdate.day))
print(f"\nHere is the calendar for the month and year you were born:\n")
print(calendar.month(birth_year, birth_month))
print(f"{name}, you will turn 100 years old in the year {year_turn_100}.")
▪ Output:
Please enter your name: Bob
Please enter your date of birth (YYYY-MM-DD): 1985-07-23
Here is the calendar for the month and year you were born:
July 1985
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Bob, you will turn 100 years old in the year 2085.
4. Write a program which will allow user to enter 10 numbers and display largest
odd and even number from them. Also display the count of odd and even
numbers.
lst=[]
print("enter 10 number:")
lst=list(int(input(f"enter {i+1} number:"))for i in range(10))
print(lst)
lst_odd=[]
lst_even=[]
for i in range(len(lst)):
if lst[i]%2==0:
lst_even.append(lst[i])
else:
lst_odd.append(lst[i])
print("odd:",lst_odd)
print("even:",lst_even)
print("largest odd number:",max(lst_odd))
print("largest even number:",max(lst_even))
print("total odd number:",len(lst_odd))
print("total even number:",len(lst_even))
Computer Engineering Department, L. D. College of Engineering, Ahmedabad-15 16
Python for Data Science (3150713) Enrollment no:220280107046
∙∙∙
▪ Output:
enter 10 number:
enter 1 number:1
enter 2 number:2
enter 3 number:3
enter 4 number:4
enter 5 number:5
enter 6 number:6
enter 7 number:7
enter 8 number:8
enter 9 number:9
enter 10 number:10
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
odd: [1, 3, 5, 7, 9]
even: [2, 4, 6, 8, 10]
largest odd number: 9
largest even number: 10
total odd number: 5
total even number: 5
sum=0
while number%10!=0:
sum=sum+pow(int(number%10),3)
number=number/10
print(sum)
if(sum==n):
print(n,"is armstrong")
else:
print(n,"is not armstrong")
▪ Output:
enter number from(100 to 999)254
with using function:
197
254 is not armstrong
without use function:
197
254 is not Armstrong
triangle.append(row)
# Example usage:
print_pascals_triangle(5)
▪ Output:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
▪ Output:
True
9. Write a program to count a total number of lines and count the total number
of lines starting with ‘PDS’ from the given text file.
def count_lines(filename):
total_lines = 0
pds_lines = 0
if line.startswith('PDS'):
▪ Output:
for i in range(length(list)):
print(list[i],"is occurs",list.count(list[i]),"time")
▪ Output:
5 is occurs 2 time
3 is occurs 2 time
7 is occurs 3 time
1 is occurs 3 time
5 is occurs 2 time
3 is occurs 2 time
7 is occurs 3 time
1 is occurs 3 time
1 is occurs 3 time
6 is occurs 2 time
7 is occurs 3 time
6 is occurs 2 time
11.Write a python program to Sort the list according to the column using lambda.
Display smallest and largest number from the list. Perform addition of all the
members of list and display it.
list=[35,67,45,32,12,10,9,98]
sort_lst=[]
sort_lst=sorted(list, key=lambda x: x)
print("sorted list:")
print(sort_lst)
print("max number:")
print(max(sort_lst))
print("min number:")
print(min(sort_lst))
print("sum of numbers:")
print(sum(sort_lst)
▪ Output:
sorted list:
[9, 10, 12, 32, 35, 45, 67, 98]
max number:
98
min number:
9
sum of numbers:
308)
12.Create a tuple to store value of student’s marks of pds subject and display it.
num_stud = int(input("Enter the number of students: "))
for i in range(len(pds_mark)):
print(pds_mark[i])
▪ Output:
Enter the number of students: 5
Enter marks for student1: 34
Enter marks for student2: 76
Enter marks for student3: 98
Enter marks for student4: 89
Enter marks for student5: 60
print("7 is removed\t",stud)
print("\n")
stud1={1,3,6,5,9,12,7}
print("set2:\t",stud1)
print("\n")
print("union of stud and stud1 is:\t",stud.union(stud1))
print("\n")
print("intersection of stud and stud1 is:\t",stud.intersection(stud1))
print("\n")
print("difference of stud and stud1 is:\t",stud.difference(stud1))
print("\n")
print("symmetric difference of stud and stud1
is:\t",stud.symmetric_difference(stud1))
print("\n")
if num in stud:
print(num,"is member of stud set")
else:
print(num,"is not member of stud set")
▪ Output:
set1 :
{2, 3, 4, 5, 7, 9, 11, 15, 18, 20}
sorted enrollment numbers:
[2, 3, 4, 5, 7, 9, 11, 15, 18, 20]
12 is added {2, 3, 4, 5, 7, 9, 11, 12, 15, 18, 20}
7 is removed {2, 3, 4, 5, 9, 11, 12, 15, 18, 20}
set2: {1, 3, 5, 6, 7, 9, 12}
union of stud and stud1 is: {1, 2, 3, 4, 5, 6, 7, 9, 11, 12, 15, 18, 20}
intersection of stud and stud1 is: {9, 3, 12, 5}
difference of stud and stud1 is: {2, 4, 11, 15, 18, 20}
symmetric difference of stud and stud1 is: {1, 2, 4, 6, 7, 11, 15, 18, 20}
enter a enrollment_no to check membership:
20
20 is member of stud set
14. Write a program to create a dictionary of student details and perform basic
operation on it.
stud_dict={
"name":"shailesh",
"enrollno":220170200706,
"age":20,
"branch":"computer",
"phone":4569637223
}
print(stud_dict["name"])
print(stud_dict)
print(stud_dict.keys())
print(stud_dict.values())
print(stud_dict.items())
print(stud_dict.get("enrollno"))
stud_mark={
"cgpa":9.08,
"pds":29,
"ada":29,
"cn":29,
"se":29
}
stud_dict.update(stud_mark)
print(stud_dict)
▪ Output:
shailesh
{'name': 'shailesh', 'enrollno': 220170200706, 'age': 20, 'branch': 'computer',
'phone': 4569637223}
dict_keys(['name', 'enrollno', 'age', 'branch', 'phone'])
dict_values(['shailesh', 220170200706, 20, 'computer', 4569637223])
dict_items([('name', 'shailesh'), ('enrollno', 220170200706), ('age', 20),
('branch', 'computer'), ('phone', 4569637223)])
220170200706
{'name': 'shailesh', 'enrollno': 220170200706, 'age': 20, 'branch': 'computer',
'phone': 4569637223, 'cgpa': 9.08, 'pds': 29, 'ada': 29, 'cn': 29, 'se': 29}
15. Write a program to create a dictionary from string in which individual
character is key and its count in string is value of key.
str=input("enter your string:")
count_dict={}
Computer Engineering Department, L. D. College of Engineering, Ahmedabad-15 24
Python for Data Science (3150713) Enrollment no:220280107046
∙∙∙
for ch in str:
if ch in count_dict:
count_dict[ch] += 1
else:
count_dict[ch] = 1
print(count_dict)
16. Write a program to list of objects of dictionary of student details sort them
according to the SPI of students and display top 5 students’ details.
student=[
{"name":"shailesh","roll":9,"spi":8.0},
{"name":"paras","roll":5,"spi":7.0},
{"name":"mahesh","roll":23,"spi":9.0},
{"name":"kuldip","roll":12,"spi":9.0},
{"name":"vishwajit","roll":46,"spi":7.5},
{"name":"harsh","roll":71,"spi":7.35},
{"name":"hardik","roll":79,"spi":8.7},
{"name":"jay","roll":56,"spi":6.9}, ]
toper=[]
toper=sorted(student,key=lambda x: x["spi"],reverse=True)
print("top 5 students:")
for i in range(5):
print(toper[i])
▪ Output:
top 5 students:
{'name': 'mahesh', 'roll': 23, 'spi': 9.0}
{'name': 'kuldip', 'roll': 12, 'spi': 9.0}
{'name': 'hardik', 'roll': 79, 'spi': 8.7}
{'name': 'shailesh', 'roll': 9, 'spi': 8.0}
{'name': 'vishwajit', 'roll': 46, 'spi': 7.5}