0% found this document useful (0 votes)
8 views

pdsp1

The document outlines practical exercises for a Python for Data Science course, focusing on basic programming concepts and data structures including lists, tuples, sets, and dictionaries. It includes detailed descriptions of each data structure, their characteristics, and provides sample code for various Python programs such as a simple calculator, string manipulation, and calculating age based on date of birth. Additionally, it covers functions for checking Armstrong numbers, generating Pascal's triangle, and counting lines in a text file.

Uploaded by

hermaparvin
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)
8 views

pdsp1

The document outlines practical exercises for a Python for Data Science course, focusing on basic programming concepts and data structures including lists, tuples, sets, and dictionaries. It includes detailed descriptions of each data structure, their characteristics, and provides sample code for various Python programs such as a simple calculator, string manipulation, and calculating age based on date of birth. Additionally, it covers functions for checking Armstrong numbers, generating Pascal's triangle, and counting lines in a text file.

Uploaded by

hermaparvin
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/ 15

Python for Data Science (3150713) Enrollment no:220280107046

∙∙∙

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.

Computer Engineering Department, L. D. College of Engineering, Ahmedabad-15 11


Python for Data Science (3150713) Enrollment no:220280107046
∙∙∙

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)

Computer Engineering Department, L. D. College of Engineering, Ahmedabad-15 12


Python for Data Science (3150713) Enrollment no:220280107046
∙∙∙

• Tools /material needed:


➢ Software: python
➢ Hardware:
• Code:
➢ Basics of Python Program:
1. Write a program in python to implement menu driven simple calculator.

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")

Computer Engineering Department, L. D. College of Engineering, Ahmedabad-15 13


Python for Data Science (3150713) Enrollment no:220280107046
∙∙∙

▪ 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.

str1=input("enter first string")


str2=input("enter secound string")
print(str1)
print(str2)
print("basic operation:")
print(str1.replace("sh","ac"))
print(len(str1))
print(len(str2))
print(str1.upper())
print(str2.lower())
print(str1[0:7])
print(str2[0:4])
print(str1[3:6])
print(str1+" "+str2)
▪ Output:
enter first string shailesh
enter secound string bhil
shailesh
bhil
basic operation:
acaileac

Computer Engineering Department, L. D. College of Engineering, Ahmedabad-15 14


Python for Data Science (3150713) Enrollment no:220280107046
∙∙∙

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: ")

dob_str = input("Please enter your date of birth (YYYY-MM-DD): ")


birthdate = datetime.strptime(dob_str, "%Y-%m-%d")

today = datetime.today()
age = today.year - birthdate.year - ((today.month, today.day) <
(birthdate.month, birthdate.day))

print(f"\nHello {name}, you are {age} years old.")


birth_year = birthdate.year
birth_month = birthdate.month

print(f"\nHere is the calendar for the month and year you were born:\n")
print(calendar.month(birth_year, birth_month))

year_turn_100 = birth_year + 100

print(f"{name}, you will turn 100 years old in the year {year_turn_100}.")

Computer Engineering Department, L. D. College of Engineering, Ahmedabad-15 15


Python for Data Science (3150713) Enrollment no:220280107046
∙∙∙

▪ Output:
Please enter your name: Bob
Please enter your date of birth (YYYY-MM-DD): 1985-07-23

Hello Bob, you are 39 years old.

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

5. Write a Python function to check whether a number is Armstrong or not.


Perform it with and without user defined function.
def armstrong(num):
sum=0
while num%10!=0:
sum=sum+pow(int(num%10),3)
num/=10
print(sum)
if(sum==n):
print(n,"is armstrong")
else:
print(n,"is not armstrong")

number=int(input("enter number from(100 to 999)"))


n=number
print("with using function:")
armstrong(number)

print("without use function:")

Computer Engineering Department, L. D. College of Engineering, Ahmedabad-15 17


Python for Data Science (3150713) Enrollment no:220280107046
∙∙∙

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

6. Write a Python function to print first n rows of Pascal's triangle.


def print_pascals_triangle(n):
triangle = []

# Constructing each row of Pascal's Triangle


for i in range(n):
row = [1] # Every row starts with 1
if i > 0:
for j in range(1, i):
# Each value is the sum of the two values above it
row.append(triangle[i-1][j-1] + triangle[i-1][j])
row.append(1) # Every row ends with 1

triangle.append(row)

# Print the triangle


for row in triangle:
print(row)

Computer Engineering Department, L. D. College of Engineering, Ahmedabad-15 18


Python for Data Science (3150713) Enrollment no:220280107046
∙∙∙

# Example usage:
print_pascals_triangle(5)

▪ Output:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]

7. Write a Python function to check whether a string is a pangram or not.


def is_pangram(s):
alphabet = set('abcdefghijklmnopqrstuvwxyz')
return alphabet <= set(s.lower())
string = "The quick brown fox jumps over the lazy dog"
print(is_pangram(string))

▪ Output:
True

8. Write a program to find Highest Common Factor (HCF) and Greatest


Common Divisor (GCD) of two numbers using function.
def hcf_gcd(a, b):
while b:
a, b = b, a % b
return a
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = hcf_gcd(num1, num2)
print("HCF/GCD of", num1, "and", num2, "is:", result)

Enter first number: 45


Enter second number: 76
HCF/GCD of 45 and 76 is: 76

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.

Computer Engineering Department, L. D. College of Engineering, Ahmedabad-15 19


Python for Data Science (3150713) Enrollment no:220280107046
∙∙∙

def count_lines(filename):

total_lines = 0

pds_lines = 0

with open(filename, 'r') as file:

for line in file:

total_lines += 1 # Increment total line count

if line.startswith('PDS'):

pds_lines += 1 # Increment PDS line count

return total_lines, pds_lines

filename = 'sample.txt' # Replace with the actual file path

total, pds_count = count_lines(filename)

print(f"Total number of lines: {total}")

print(f"Number of lines starting with 'PDS': {pds_count}")

▪ Output:

Total number of lines: 5

Number of lines starting with 'PDS': 3

➢ List and Tuple Programs


10.Write a python program to find occurrence of an element in the list.
list=[5,3,7,1,5,3,7,1,1,6,7,6]

for i in range(length(list)):
print(list[i],"is occurs",list.count(list[i]),"time")

Computer Engineering Department, L. D. College of Engineering, Ahmedabad-15 20


Python for Data Science (3150713) Enrollment no:220280107046
∙∙∙

▪ 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)

Computer Engineering Department, L. D. College of Engineering, Ahmedabad-15 21


Python for Data Science (3150713) Enrollment no:220280107046
∙∙∙

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: "))

pds_mark = tuple(float(input(f"Enter marks for student{i+1}: ")) for i in


range(num_stud))

print("\nMarks in PDS subject:")

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

Marks in PDS subject:


34.0
76.0
98.0
89.0
60.0

➢ Set and Dictionary Programs


13.Write a program to create a set of students’ enrolment number and sort them
and display it. Also perform add, delete, union, intersection, difference, and
symmetric difference and membership testing operation for the given sets.
stud={2,5,4,9,7,3,11,15,18,20}
print("set1 :\n")
print(stud,"\n")
print("sorted enrollment numbers:\n")
print(sorted(stud),"\n")
stud.add(12)
print("12 is added\t",stud)
print("\n")
stud.remove(7)
Computer Engineering Department, L. D. College of Engineering, Ahmedabad-15 22
Python for Data Science (3150713) Enrollment no:220280107046
∙∙∙

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")

num=int(input("enter a enrollment_no to check membership:\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

Computer Engineering Department, L. D. College of Engineering, Ahmedabad-15 23


Python for Data Science (3150713) Enrollment no:220280107046
∙∙∙

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)

enter your string:shailesh


{'s': 2, 'h': 2, 'a': 1, 'i': 1, 'l': 1, 'e': 1}

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}

Signature of Faculty: Grade:

Computer Engineering Department, L. D. College of Engineering, Ahmedabad-15 25

You might also like