Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

PROGRAM

Uploaded by

saurishseth
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

PROGRAM

Uploaded by

saurishseth
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

xPROGRAM-53

#Program to find marks of students and return max and min


# list of numbers
list1 =input("ENter your list of marks:")

list1=list1.split(',')
# sorting the list
list1.sort()

# printing the last element


print("highest mark is:", list1[-1])
print("lowest mark is :",list1[0])
Enter your list of marks:[48,68,78,79,98]
highest mark is: 98
lowest mark is : 48

PROGRAM-54
#Program to have an increment of 10 to each element of list
#Saurish Seth
#class-11A
#roll number-19
def increment(ListA):
for i in range(0,len(ListA)):
ListA[i]+=10 #Adding 10 to each element
return ListA
ListA=[1,8,9,52,67]
ListA=increment(ListA)
print(ListA)

===================== RESTART: /Users/saurish/Desktop/Q1.py ====================


[11, 18, 19, 62, 77]
PROGRAM-55
#Program to input marks of student and count number of children who have
gotten more than 70 marks
#Saurish Seth
#class-11A
#roll number-19
def morethan(List2):
count=0
for i in range(0,len(List2)):
if List2[i]>70:
count+=1
return count
List2=eval(input("Enter the marks of the students:"))

count=morethan(List2)
print('Number of children who have gotten more than 70 marks are:',count)

===================== RESTART: /Users/saurish/Desktop/Q1.py ====================


Enter the marks of the students:65,87,90,62,99
Number of children who have gotten more than 70 marks are: 3

PROGRAM-56
#Program to swap elements of the list
#Saurish Seth
#class-11A
#roll number-19
def swap_adjacent_elements(lst):
for i in range(0, len(lst)-1, 2):
lst[i], lst[i+1] = lst[i+1], lst[i]

ListA = [1, 4, 9, 10, 25, 33]


swap_adjacent_elements(ListA)
print(ListA)

===================== RESTART: /Users/saurish/Desktop/Q1.py ====================


[4, 1, 10, 9, 33, 25]

PROGRAM-57
#Program to half even and double odd elements

#Saurish Seth
#class-11A
#roll number-19
def half_even_double_odd(input_list):
result_list = []
for num in input_list:
if num % 2 == 0:
result_list.append(num / 2)
else:
result_list.append(num * 2)
return result_list
input_numbers = [1, 2, 3, 4, 5, 6]
result = half_even_double_odd(input_numbers)
print("Input List:", input_numbers)
print("Result List:", result)

===================== RESTART: /Users/saurish/Desktop/Q1.py ====================


Input List: [1, 2, 3, 4, 5, 6]
Result List: [2, 1.0, 6, 2.0, 10, 3.0]

PROGRAM-58
#program to show bubblesort
def bubblesort(theSeq):
n=len(theSeq)

for i in range(n-1):
flag=0

for j in range(n-1):
if theSeq[j]>theSeq[j+1]:
tmp=theSeq[j]
theSeq[j]=theSeq[j+1]
theSeq[j+1]=tmp
flag=1
if flag==0:
break
return theSeq
el=[21,6,9,33,3]
print('Unsorted array:',el)

result=bubblesort(el)
print('Sorted Array:',result)
Unsorted array: [21, 6, 9, 33, 3]
Sorted Array: [3, 6, 9, 21, 33]
PROGRAM-59
#Program to count the number of vowels in a string using concepts of lists

#Saurish Seth
#class-11A
#roll number-19
str=input("Enter a string:")
vowels=['a','e','i','o','u','A','E','I','O','U'] #list of vowels
wordlist=str.split(" ")
count=0 #initial count
for word in wordlist:
for i in range(len(word)):
if word[i] in vowels:
#increasing the count by 1
count+=1
print("Number of vowels in the string are:",count)

===================== RESTART: /Users/saurish/Desktop/Q1.py ====================


Enter a string:The weapons of war must be abolished before they abolish us.
Number of vowels in the string are: 20

PROGRAM-60
#Program to calculate the cost of tent
#Saurish Seth
#class-11A
#roll number-19
#function definition
def cyl(h,r):
area_cyl = 2*3.14*r*h #Area of cylindrical part
return(area_cyl)
#function definition
def con(l,r):
area_con = 3.14*r*l #Area of conical part
return(area_con)
#function definition
def post_tax_price(cost): #compute payable amount for the tent
tax = 0.18 * cost;
net_price = cost + tax
return(net_price)
print("Enter values of cylindrical part of the tent in meters:")
h = float(input("Height: "))
r = float(input("Radius: "))
csa_cyl = cyl(h,r) #function call
l = float(input("Enter slant height of the conical area in meters: "))
csa_con = con(l,r) #function call
#Calculate area of the canvas used for making the tent
canvas_area = csa_cyl + csa_con
print("Area of canvas = ",canvas_area," m^2")
#Calculate cost of canvas
unit_price = float(input("Enter cost of 1 m^2 canvas in rupees: "))
total_cost = unit_price * canvas_area
print("Total cost of canvas before tax = ",total_cost)
print("Net amount payable (including tax) = ",post_tax_price(total_cost))

===================== RESTART: /Users/saurish/Desktop/Q1.py ====================


Enter values of cylindrical part of the tent in meters:
Height: 5
Radius: 9
Enter slant height of the conical area in meters: 54
Area of canvas = 1808.6400000000003 m^2
Enter cost of 1 m^2 canvas in rupees: 19
Total cost of canvas before tax = 34364.16
Net amount payable (including tax) = 40549.70880000001

PROGRAM-61
#Program to take two numbers from the user and printing their sum
#Saurish Seth
#class-11A
#roll number-19
#function definition
def sum(num1,num2):
their_sum=num1+num2 #finding their sum by adding them
return their_sum
#driver code
#taking input of the two numbers from the user
num1=int(input("Enter the first number:"))
num2=int(input("Enter the second number:"))
their_sum=sum(num1,num2) #assigning the result to the variable
print('The sum if the numbers is :',their_sum)

===================== RESTART: /Users/saurish/Desktop/Q1.py ====================


Enter the first number:6
Enter the second number:8
The sum if the numbers is : 14

PROGRAM-62
#Program to find sum of the first n natural numbers

#Saurish Seth
#class-11A
#roll number-19
def nsum(n):
sum=0
for i in range(1,n+1):
sum+=i
return sum
#Driver code
#taking inputs
n=int(input("Enter the number till the sum has to be taken:"))
sum=nsum(n)
print('The sum of n numbers is:',sum)

===================== RESTART: /Users/saurish/Desktop/Q1.py ====================


Enter the number till the sum has to be taken:5
The sum of n numbers is: 15

PROGRAM-63
#Program to add an increment of 5 to nunber and printing the id before and after
the increment
#Saurish Seth
#class-11A
#roll number-19
def increment(num):
print('Number is',num)
print('id of the number before increment',id(num)) #id of the number
before increment
num+=5
return num
num=int(input("Enter a number:"))
num=increment(num)
print('Number after increment by 5 is',num)
print('id of the number after increment is',id(num))

============ RESTART: /Users/saurish/Desktop/Q1.py ===========


Enter a number:7
Number is 7
id of the number before increment 4575554840
Number after increment by 5 is 12
id of the number after increment is 4575555000

PROGRAM-64
#Program to input names and print the full name

#Saurish Seth
#class-11A
#roll number-19
def f_name(firs_name,last_name):
full_name=firs_name+' '+last_name #using concatenation
return full_name

firs_name=input("Enter your first name:")


last_name=input("Enter your last name:")
#Calling function
full_name=f_name(firs_name,last_name) #printing full name
print('Your full name is',full_name)

============ RESTART: /Users/saurish/Desktop/Q1.py ===========


Enter your first name:rohan
Enter your last name:aggarwal
Your full name is rohan aggarwal

PROGRAM-65
#Program to print mixed fraction where the value of denominator is fixed as 1
def mixedfraction(num,deno=1):
remainder=num%deno
quotient=int(num/deno)
if remainder!=0:

print('The mixed fraction:',quotient,'(',remainder,'/',deno,')')


else:
print('The result is a whole number',remainder)
#Driver code
#taking inputs
num=int(input("Enter the numerator"))
deno=int(input("Enter the denominator"))
if num>deno:
mixedfraction(num,deno)
else:
print("The given fraction is already a proper fraction")
Enter the numerator21
Enter the denominator4
The mixed fraction: 5 ( 1 / 4 )

PROGRAM-66
#Program to print exponential value of the number entered
#Saurish Seth
#class-11A
#roll number-19
def POWER(x,y):
z=1
for i in range(1,y+1):
z=x*z
return z
#Driver code
x=int(input("Enter the base value:"))
y=int(input("Enter the exp value:"))
result=POWER(x,y)
print('The exponential value is:',result)

============ RESTART: /Users/saurish/Desktop/Q1.py ===========


Enter the base value:5
Enter the exp value:2
The exponential value is: 25
PROGRAM-67
#Program to print area and perimeter of th given rectangle
def calcAreaPeri(Length,Breadth):
area = length * breadth
perimeter = 2 * (length + breadth)
#a tuple is returned consisting of 2 values area and perimeter
return (area,perimeter)
length = float(input("Enter length of the rectangle: "))
breadth = float(input("Enter breadth of the rectangle: "))
#value of tuples assigned in order they are returned
area,perimeter = calcAreaPeri(length,breadth)
print("Area is:",area,"\nPerimeter is:",perimeter)
============ RESTART: /Users/saurish/Desktop/Q1.py ===========
Enter length of the rectangle: 10
Enter breadth of the rectangle: 2
Area is: 20.0
Perimeter is: 24.0

PROGRAM-68
#Program to print name and other details of the students
st=((101,"Aman",98),(102,"Raj",91),(103,"Kiara",99),(104,"Timsy",84))
print('S.no','\tRoll no','Name','\tMarks')
for i in range(0,len(st)):
print((i+1),'\t',st[i][0],'\t',st[i][1],'\t',st[i][2])
S.no Roll no Name Marks
1 101 Aman 98
2 102 Raj 91
3 103 Kiara 99
4 104 Timsy 84
PROGRAM-69
#Program to give values to given traffic lights
#Saurish Seth
#class-11A
#roll number-19
def trafficLight():
signal = input("Enter the colour of the traffic light: ")
if (signal not in ("RED","YELLOW","GREEN")):
print("Please enter a valid Traffic Light colour in
CAPITALS")
else:
value = light(signal) #function call to light()
if (value == 0):
print("STOP, Your Life is Precious.")
elif (value == 1):
print ("PLEASE GO SLOW.")
else:
print("GO!,Thank you for being patient.")
#function ends here
def light(colour):
if (colour == "RED"):
return(0);
elif (colour == "YELLOW"):
return (1)
else:
return(2)
#function ends here
trafficLight()
print("SPEED THRILLS BUT KILLS")

============ RESTART: /Users/saurish/Desktop/Q1.py ===========


Enter the colour of the traffic light: RED
STOP, Your Life is Precious.
SPEED THRILLS BUT KILLS
PROGRAM-70
#Program to swap the numbers to the same variables
#Saurish Seth
#class-11A
#roll number-19
num1=int(input("Enter the first number:"))
num2=int(input("Enter the second number:"))
print('Numbers before swapping:')
print('First Number is',num1)
print('Second Number is',num2)
(num1,num2)=(num2,num1)
print('Numbers after swapping:')
print('First Number is',num1)
print('Second Number is',num2)

============ RESTART: /Users/saurish/Desktop/Q1.py ===========


Enter the first number:7
Enter the second number:9
Numbers before swapping:
First Number is 7
Second Number is 9
Numbers after swapping:
First Number is 9
Second Number is 7

PROGRAM71
#Program to find area and circumference of the circle using user-defined
functions
def circle(r):
area=3.14*r*r
circum=2*3.14*r
return (area,circum)
#Driver Code
r=eval(input("Enter the radius of the circle in meters:"))
area,circum=circle(r)
print('Area of the circle is:',area)
print('Circumference if the circle is:',circum)
============ RESTART: /Users/saurish/Desktop/Q1.py ===========
Enter the radius of the circle in meters:5
Area of the circle is: 78.5
Circumference if the circle is: 31.400000000000002
PROGRAM-72
#Program to take n numbers from the user and printing the maximum and the
minimum number
numbers=tuple()
n=int(input("Enter how many numbers you want to input:"))
for i in range(0,n):
num=int(input())
numbers=numbers+(num,)
print('The entered numbers are:')
print(num)
print('\nThe max number is:')
print(max(numbers))
print('\nThe min number is:')
print(min(numbers))
=========== RESTART: /Users/saurish/Desktop/Q1.py ===========
Enter how many numbers you want to input:4
enter5
enter6
enter3
enter9
The entered numbers are:
9

The max number is:


9

The min number is:


3
PROGRAM-73
#Program to do the following operations on the tuple ODD
(a) Display the keys
(b) Display the values
(c) Display the items
(d) Find the length of the dictionary
(e) Check if 7 is present or not
(f) Check if 2 is present or not
(g) Retrieve the value corresponding to the key 9
(h) Delete the item from the dictionary corresponding to the key 9
ODD = {1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
print(ODD)
print(ODD.keys())
print(ODD.values())
print(ODD.items())
print(len(ODD))
print(7 in ODD)
print(2 in ODD)
print(ODD.get(9))
del ODD[9]
print(ODD)
============ RESTART: /Users/saurish/Desktop/Q1.py ===========
{1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven', 9: 'Nine'}
dict_keys([1, 3, 5, 7, 9])
dict_values(['One', 'Three', 'Five', 'Seven', 'Nine'])
dict_items([(1, 'One'), (3, 'Three'), (5, 'Five'), (7, 'Seven'), (9, 'Nine')])
5
True
False
Nine
{1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven'}
PROGRAM-74
#Program to create a dictionary which stores names of the employee
and their salary
num = int(input("Enter the number of employees whose data to be stored: "))
count = 1
employee = dict() #create an empty dictionary
while count <= num:
name = input("Enter the name of the Employee: ")
salary = int(input("Enter the salary: "))
employee[name] = salary
count += 1
print("\n\nEMPLOYEE_NAME\tSALARY")
for k in employee:
print(k,'\t\t',employee[k])
============ RESTART: /Users/saurish/Desktop/Q1.py ===========
Enter the number of employees whose data to be stored: 2
Enter the name of the Employee: a
Enter the salary: 5
Enter the name of the Employee: b
Enter the salary: 7

EMPLOYEE_NAME SALARY
a 5
b 7

PROGRAM-75
#Program to enter number and its value in words
#Creating a user defined function
def inwords(num):

numnames={0:'Zero',1:'One',2:'Two',3:'Three',4:'Four',5:'Five',6:'Six',7:'S
even',8:'Eight',9:'Nine'}

result=' ' #creating an empty string


for ch in num:
key=int(ch)
value=numnames[key]
result=result+' '+value
return result
#Driver Code
num=input("Enter a number:")
words=inwords(num)
print('The number in words is',words)
Enter a number:1582
The number in words is One Five Eight Two
PROGRAM-76
#Program to take n emails and print the domain and usernames
def process_email_ids(email_ids):
usernames = []
domains = []
for email in email_ids:
# Split email address into username and domain
username, domain = email.split('@')
usernames.append(username)
domains.append(domain)
return tuple(email_ids), tuple(usernames), tuple(domains)
def main():
# Get the number of students
n = int(input("Enter the number of students: "))
# Read email IDs
email_ids = []
for i in range(n):
email = input(f"Enter email ID for student {i+1}: ")
email_ids.append(email)
# Process email IDs
email_tuple, usernames_tuple, domains_tuple =
process_email_ids(email_ids)
# Print the tuples
print("\nEmail IDs:", email_tuple)
print("Usernames:", usernames_tuple)
print("Domains:", domains_tuple)
if __name__ == "__main__":
main()

==============================================================
RESTART: /Users/saurish/Desktop/Q1.py
=============================================================
Enter the number of students: 2
Enter email ID for student 1: jrh@gmail.com
Enter email ID for student 2: wurkuewef@gmail.com

Email IDs: ('jrh@gmail.com', 'wurkuewef@gmail.com')


Usernames: ('jrh', 'wurkuewef')
Domains: ('gmail.com', 'gmail.com')
PROGRAM-77
# User-defined function to check if a student is present in the tuple
def is_student_present(student_name, student_tuple):
return student_name in student_tuple
def main():
# Get the number of students
n = int(input("Enter the number of students: "))
# Read names and store them in a tuple
student_names = tuple(input(f"Enter name for student {i+1}: ") for i in
range(n))
# Print the tuple of student names
print("\nStudent Names:", student_names)
# Input a name from the user
search_name = input("\nEnter a name to check if the student is present:
")
# Using user-defined function to check if the student is present
if is_student_present(search_name, student_names):
print(f"{search_name} is present in the tuple.")
else:
print(f"{search_name} is not present in the tuple.")
# Using built-in function to check if the student is present
if search_name in student_names:
print(f"{search_name} is present in the tuple (using built-in
function).")
else:
print(f"{search_name} is not present in the tuple (using built-in
function).")
if __name__ == "__main__":
main()
==============================================================
RESTART: /Users/saurish/Desktop/Q1.py
=============================================================
Enter the number of students: 2
Enter name for student 1: a
Enter name for student 2: b

Student Names: ('a', 'b')

Enter a name to check if the student is present: a


a is present in the tuple.
a is present in the tuple (using built-in function).
PROGRAM-78
#Program to find top two values of the dictionary
def find_highest_two(dictionary):
# Get a sorted list of dictionary items by values in descending order
sorted_items = sorted(dictionary.items(), key=lambda x: x[1],
reverse=True)

# Extract the top two items


top_two = sorted_items[:2]
return top_two
def main():
# Example dictionary (you can replace this with your own)
student_scores = {
'Alice': 90,
'Bob': 85,
'Charlie': 95,
'David': 88,
'Eve': 92}
# Find the highest two values in the dictionary
highest_two = find_highest_two(student_scores)
# Print the result
print("Dictionary:", student_scores)
print("\nTop two values:")
for name, score in highest_two:
print(f"{name}: {score}")
if __name__ == "__main__":
main()

=============================================================
RESTART: /Users/saurish/Desktop/Q1.py
=============================================================
Dictionary: {'Alice': 90, 'Bob': 85, 'Charlie': 95, 'David': 88, 'Eve': 92}

Top two values:


Charlie: 95
Eve: 92
PROGRAM-79
#To access any variable outside the function
num = 5
def myfunc1():
#Prefixing global informs Python to use the updated global
#variable num outside the function
global num
print("Accessing num =",num)
num = 10
print("num reassigned =",num)
#function ends here
myfunc1()
print("Accessing num outside myfunc1",num)
Accessing num = 5
num reassigned = 10
Accessing num outside myfunc1 10
PROGRAM-80
#Program to do following operations:
a) Display the name and phone number of all your
friends
b) Add a new key-value pair in this dictionary and
display the modified dictionary
c) Delete a particular friend from the dictionary
d) Modify the phone number of an existing friend
e) Check if a friend is present in the dictionary or
not
f) Display the dictionary in sorted order of names

#Saurish Seth
#class-11A
#roll number-19
def display_friends(dictionary):
print("\nFriends and their Phone Numbers:")
for name, phone in dictionary.items():
print(f"{name}: {phone}")

def add_friend(dictionary, name, phone):


dictionary[name] = phone
print("\nFriend added successfully.")
display_friends(dictionary)

def delete_friend(dictionary, name):


if name in dictionary:
del dictionary[name]
print("\nFriend deleted successfully.")
display_friends(dictionary)
else:
print("\nFriend not found in the dictionary.")

def modify_phone(dictionary, name, new_phone):


if name in dictionary:
dictionary[name] = new_phone
print("\nPhone number modified successfully.")
display_friends(dictionary)
else:
print("\nFriend not found in the dictionary.")

def check_friend(dictionary, name):


if name in dictionary:
print(f"\n{name} is present in the dictionary with phone
number: {dictionary[name]}")
else:
print(f"\n{name} is not present in the dictionary.")

def display_sorted(dictionary):
sorted_dict = dict(sorted(dictionary.items()))
print("\nDictionary in sorted order of names:")
display_friends(sorted_dict)

def main():
friends_dict = {}

# Add some initial friends (you can remove or modify this)


friends_dict['Alice'] = '123-456-7890'
friends_dict['Bob'] = '987-654-3210'

while True:
print("\nOperations:")
print("a) Display friends and phone numbers")
print("b) Add a new friend")
print("c) Delete a friend")
print("d) Modify phone number")
print("e) Check if a friend is present")
print("f) Display sorted dictionary")
print("x) Exit")

choice = input("Enter your choice: ").lower()

if choice == 'a':
display_friends(friends_dict)
elif choice == 'b':
name = input("Enter friend's name: ")
phone = input("Enter friend's phone number: ")
add_friend(friends_dict, name, phone)
elif choice == 'c':
name = input("Enter the name of the friend to
delete: ")
delete_friend(friends_dict, name)
elif choice == 'd':
name = input("Enter the name of the friend to
modify: ")
new_phone = input("Enter the new phone number: ")
modify_phone(friends_dict, name, new_phone)
elif choice == 'e':
name = input("Enter the name of the friend to check:
")
check_friend(friends_dict, name)
elif choice == 'f':
display_sorted(friends_dict)
elif choice == 'x':
break
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
main()

==============================================================
RESTART: /Users/saurish/Desktop/Q1.py
=============================================================

Operations:
a) Display friends and phone numbers
b) Add a new friend
c) Delete a friend
d) Modify phone number
e) Check if a friend is present
f) Display sorted dictionary
x) Exit
Enter your choice: a

Friends and their Phone Numbers:


Alice: 123-456-7890
Bob: 987-654-3210

Operations:
a) Display friends and phone numbers
b) Add a new friend
c) Delete a friend
d) Modify phone number
e) Check if a friend is present
f) Display sorted dictionary
x) Exit
Enter your choice: b
Enter friend's name: b
Enter friend's phone number: 986723
Friend added successfully.

Friends and their Phone Numbers:


Alice: 123-456-7890
Bob: 987-654-3210
b: 986723

Operations:
a) Display friends and phone numbers
b) Add a new friend
c) Delete a friend
d) Modify phone number
e) Check if a friend is present
f) Display sorted dictionary
x) Exit
Enter your choice: c
Enter the name of the friend to delete: c

Friend not found in the dictionary.

Operations:
a) Display friends and phone numbers
b) Add a new friend
c) Delete a friend
d) Modify phone number
e) Check if a friend is present
f) Display sorted dictionary
x) Exit
Enter your choice: d
Enter the name of the friend to modify: alice
Enter the new phone number: 7262626262

Friend not found in the dictionary.

Operations:
a) Display friends and phone numbers
b) Add a new friend
c) Delete a friend
d) Modify phone number
e) Check if a friend is present
f) Display sorted dictionary
x) Exit
Enter your choice: e
Enter the name of the friend to check: alice

alice is not present in the dictionary.

Operations:
a) Display friends and phone numbers
b) Add a new friend
c) Delete a friend
d) Modify phone number
e) Check if a friend is present
f) Display sorted dictionary
x) Exit
Enter your choice: f

Dictionary in sorted order of names:

Friends and their Phone Numbers:


Alice: 123-456-7890
Bob: 987-654-3210
b: 986723

Operations:
a) Display friends and phone numbers
b) Add a new friend
c) Delete a friend
d) Modify phone number
e) Check if a friend is present
f) Display sorted dictionary
x) Exit
Enter your choice: x

You might also like