0% found this document useful (0 votes)
35 views16 pages

Python Lab Answer1

Uploaded by

aadhithyananbu
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)
35 views16 pages

Python Lab Answer1

Uploaded by

aadhithyananbu
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/ 16

B.E / B.Tech.

PRACTICAL END SEMESTER EXAMINATIONS

JANUARY2022 FirstSemester

GE3171&PROBLEM SOLVING AND PYTHON PROGRAMMIG LABORATORY


(Regulations2021)

Time : 3 Hours
Marks:100

Answer any one Question (To be filled by the question paper setter)

1. Write a python program to create, append and remove lists in python


Algorithm:
Step1: Create a List: Start with an empty list.
Step2: Append Values: Use a loop to add items to the list.
Step3: Remove Values: Use another loop to remove specific items from the list based on a
Condition
Program:
mylist=[]
n=int(input("Enter the number of elements:"))
for i in range(n):
a=input("Enter the element:")
mylist.append(a)
print(mylist)
mylist.append(90)
print(mylist)
del(mylist)
Output:
Enter the number of elements:4
Enter the element:10
Enter the element:20
Enter the element:30
Enter the element:40
[10,20,30,40]
[10,20,30,40,90]
2. Write a program to demonstrate working with tuples in python
Algorithm:
Step1: Create a tuple named my_tuple with elements: "engine", "cooling system", and
"electrical
system".Print the tuple.
Step2:Calculate Length Use the len() function to find the length of my_tuple and print it.
Step3:Add an Element ("fuel system",) to my_tuple to add the element "fuel system".Print the
updated my_tuple
Step4:Concatenate the tuple ("engine",) to my_tuple to add a duplicate "engine".Print the
updated my_tuple
Step5:Create another tuple named new_tuple with elements: "clutch", "break", and "engine".
Concatenate new_tuple to my_tuple Print the updated my_tuple
Step6: Count an Element engine" in my_tuple using the count() method and print the count.
Step7:Delete the tuple using the del keyword.
Step8: Print Remaining Tuple
Program:
my_tuple=("engine", "cooling system","electrical system")
print(my_tuple)
print(len(my_tuple))
my_tuple=my_tuple+("fuel system",)
print(my_tuple)
my_tuple=my_tuple+("engine",)
print(my_tuple)
new_tuple=("clutch","break","engine")
my_tuple=my_tuple+new_tuple
print(my_tuple)
x=my_tuple.count("engine")
print(x)
del my_tuple
print(new_tuple)
Output:
('engine', 'cooling system', 'electrical system')
3
('engine', 'cooling system', 'electrical system', 'fuel system')
('engine', 'cooling system', 'electrical system', 'fuel system', 'engine')
('engine', 'cooling system', 'electrical system', 'fuel system', 'engine')
('engine', 'cooling system', 'electrical system', 'fuel system', 'engine', 'clutch', 'break', 'engine')
3
('clutch', 'break', 'engine')
3. Write a program to demonstrate working with dictionaries in python
Algorithm:
Step 1: Start.
Step 2: Dictionary can be created by placing a sequence of elements within curly {}
braces, separated by
‘comma’. Dictionary holds pairs of values, one being the Key and the other
corresponding pair element
being its Key:value.
Step 3: By using copy() method, to copies the items present in dictionary.
Step 4: By using fromkeys() method, to return returns a new dictionary with the given
sequence of elements as
the keys of the dictionary.
Step 5: By using get() method, to return the specified item from dictionary.
Step 6: By using The items() method will return each item in a dictionary, as tuples in a
list.
Step 7: By using keys() method will return a list of all the keys in the dictionary.
Step 8: By using values() method will return a list of all the values in the dictionary
Step 9: By using The pop() method removes the item with the specified key name.
Step 10: By using popitem() method removes the last inserted item.
Step 11: By using The update() method will update the dictionary with the items from the
given argument.
Step 12: By using clear() method empties the dictionary.
Step13: stop.
Program:
elements={"structure":"roof","beam":"reinforced:concrete beam","wall type":"bricks"}
print(elements)
x=elements.copy()
print(x)
elements1=("structure","beam","wall type")
x=dict.fromkeys(elements1)
print(x)
y=0
x=dict.fromkeys(elements1,y)
print(x)
x=elements.get("structure")
print(x)
x=elements.items()
print(x)
x=elements.keys()
print(x)
x=elements.values()
print(x)
elements.pop("wall type")
print(elements)
elements.popitem()
print(elements)
elements.update({"paint color":"blue"})
elements.clear()
print(elements)
Output:
{'structure': 'roof', 'beam': 'reinforced:concrete beam', 'wall type': 'bricks'}
{'structure': 'roof', 'beam': 'reinforced:concrete beam', 'wall type': 'bricks'}
{'structure': None, 'beam': None, 'wall type': None}
{'structure': 0, 'beam': 0, 'wall type': 0}
roof
dict_items([('structure', 'roof'), ('beam', 'reinforced:concrete beam'), ('wall type', 'bricks')])
dict_keys(['structure', 'beam', 'wall type'])
dict_values(['roof', 'reinforced:concrete beam', 'bricks'])
{'structure': 'roof', 'beam': 'reinforced:concrete beam'}
{'structure': 'roof'}
{}
4. Write a python program to find largest of three numbers
Algorithm:
Step1:Start
Step2:Get three number as input.
Step3:Compare the three numbers using conditional statement.
Step4:Print the largest number
Step5:Stop.
Program:
num1=eval(input(“Enter the first number:”))
num2=eval(input(“Enter the second number:”))
num3=eval(input(“Enter the third number:”))
if num1>=num2 and num1>=num3:
large=num1
elif num2>=num1 and num2>=num3:
large=num2
else:
large=num3
print(“The largest number is:”,large)
Output:
Enter the first number:10
Enter the second number:7
Enter the third number:12
5. Write a python program to convert temperature to and from Celsius to Fahrenheit
Algorithm:
Step1:Start
Step2:Input the temperature in Celsius
Step3:Multiply the Celsius temperature by 9/5
Step4:Add 32 to the result
Step5:Output the temperature in Fahrenheit
Step6:Stop
Program:
celsius=eval(input(“Enter the Celsius:”))
fahrenheit=(celsius*9/5)+32
print(celsius,”°Celsius in”,“Fahrenhei is:”,fahrenheit)

Output:
Enter the Celsius:32
32°Celsius in Fahrenheit is 89.6
6. Identification and solving of simple real life or scientific or technical problems, and
developing flow charts for the same
Electricity Billing
Algorithm:
Step 1: Start
Step 2: Read the input'Unit'
Step 3: Process the following conditons When the unit is less than or equal to 100 units ,
calculate usage=unit*1.5 When the unit is between 100 to 200 units,calculate
usage=(100*1.5)+(units-100)*2.5 When the units is between 200 to 300 units,
calculate usage= calculate (100*1.5)+(200100)*2.5+(units-200)*4 When the unit is
between 300 to 350 units,usage=(100*1.5)+(200100)*2.5+(300- 200)*4+(units-350)*5
When the units is consumed above 350, Find charge=1500
Step 4: Display the amount "Usage" to the user
Step 5: Stop.
Program:
units=int(input("Enter the number of units consumed in a month:"))
usage=0
if (units<=100):
usage=units*1.5
elif(units<=200):
usage=(100*1.5)+(units-100)*2.5
elif(units<=300):
usage=(100*1.5)+(200-100)*2.5+(units-200)*4
elif(units<=350):
usage=(100*1.5)+(200-100)*2.5+(300-200)*4+(units-300)*5
else:
usage=1500.00
print("Electricity bill=",usage
Output:
Enter the number of units consumed in a month:500
Electricity bill=1500.0
RETAIL SHOP BILLING
Algorithm:
Step 1: Start
Step 2: Read the values for product1,product2 and product 3
Step 3: Read the values for rate1, rate 2, rate 3
Step 4: Read the values for item 1, item 2, item 3 quantities
Step 5: Calculate Amount=(item 1*rate 1)+(item 2*rate 2)+(item3*rate3)
Step 6: Display the value of "amount"
Step 7:Stop
Program:
prod1=input("Enter the name of the product 1:")
prod2=input("Enter the name of the product2:")
prod3=input("Enter the name of the product3:")
rate1=int(input("Enter the rate of the item 1:"))
rate2=int(input("Enter the rate of the item 2:"))
rate3=int(input("Enter the rate of the item 3:"))
item 1=int(input("Enter the product 1 quantity :"))
item2=int(input("Enter the product 2 quantity:"))
item3=int(input("Enter the product 3 quantity:"))
amount=(item1*rate1)+(item2*rate2)+(item3*rate3)
print("Total bill:",amount)
Output:
Enter the name of the product 1:rice
Enter the name of the product 2:sugar
Enter the name of the product 3:salt
Enter the rate of the item 1:1500
Enter the rate of the item 2:30
Enter the rate of the item 3:10
Enter the product 1 quantity :1
Enter the product 2 quantity :2
Enter the product 3 quantity :1
Total bill:1570
7. Identification and solving of simple real life orscientific or technical problems, and
developing flow charts for the same
Sin series
Algorithm:
Step1: Start
Step2: Import math module to the program to use in build functions.
Step3: Caller user defined function to calculate sin x series and print return values using
round method. User defined functions:
Step4: Initialize sin variable as zero.
Step5: Open for loop from 1 to number using range method
Step6: calculate Sin using the formula (-1)**i
Step7: Convert the angle from degree to radian using formula y=x*(pi/180)
Step8: Calculate the sin series usings the formula
Step9: sin+((y**(2.0*i+1)/math factorial (2*i+1) sign and return sign value to the calling
function.
Step10: Stop the program.
Program:
import math
def sin(x,n): sine=0
for i in range (n):
sign=(-1)**i
pi=22/7
y=x*(pi/180)
sine=sine+((y**(2.0*i+1))/ math.factorial(2*i+1))*sign
return sine
x=int(input("Enter the value of x in degrees:"))
n=int(input("Enter the number of terms:"))
print(round(sin(x,n),2))

Output:
Enter the value of x in degrees:45
Enter the number of terms:87
0.79
Weight of a motorbike
Algorithm:
Step1: Start
Step2: Read the value of weight motor,pr and eoff
Step3: process the following weight=weight motor+pr+eoff
Step4:Display "motor bike weight"
Step5:stop.
Program:
weightmotor=int(input("Enter motorbike weight:"))
pr=int(input("Enter the passenger weight:"))
eoff=int(input("Enter the engine oils &fullfuel weight:"))
weight=weightmotor+pr+eoff
print("The weight of motorbike is:",weight)
Output:
Enter motorbike weight:150
Enter the passenger weight:60
Enter the engine oils &fullfuel weight:20
The weight of motorbike is:230
Weight of steel bar
ALGORITHM:
weight of steel bar=(d2/162)*length(or)d2*length/162 Step1:Start
Step 2:Read the value of d and length
Step 3:Process the following condition Weight=d2*length/162
Step 4: Display the value of weight
Step 5:Stop
PROGRAM:
d=int(input(“Enter the diameter of steel bar:”))
length=int(input(“Enter the length of bars:”))
weight=d*d*length/162
print(“The weight of steelbar is:”,weight)
Output:
Enter the diameter of steel bar:12
Enter the length of bars:60
The weight of steelbar is:53.33333333333333
8. Identification and solving of simple real life or scientific or technical problems, and
developing flow charts for the same
Electrical Current in Three Phase AC Circuit
Algorithm:
Step 1: Start
Step 2: Read the values of pf ,i,v
Step 3: Process the following p=square root of 3*pf*i*v
Step 4: Display"the result is p".
Step 5: Stop

PROGRAM:
import math
pf=float(input("Enters the power factor:"))
i=int(input("Enter the value for current:"))
v=int(input("Enter the value for voltage:"))
p=math.sqrt(3)*pf*i*v
print("The power value is ",p)
Output:
Enters the power factor:0.9
Enter the value for current:50
Enter the value for voltage:250
The power value:19485.57158514987
9. Write a Python programming using simple statements and expressions
Exchange the values of two variables
Using temporary variable
ALGORITHM:
Step 1:Start
Step 2:Read value of x
Step 3: Read value of y
Step 4: temp=x
Step 5: x=y
Step 6: y=temp
Step 7: print x
Step 8:print y
Step 9: End
PROGRAM:
x=5 y=10
x=input("Enter value of x:")
y=input("Enter value of y:")
temp=x
x=y
y=temp
print("The value of x after swapping {}:”.format(x))
print("The value of y after swapping{}:”.format(y))
Output:
Enter value of x:10
Enter value of y:7
The value of x after swapping:7
The value of y after swapping:10
WITHOUT USING A TEMPORARY VARIABLE
Algorithm:
Step 1:Start
Step 2: Read value of x
Step 3: Read value of y
Step 4:x,y=y,x
Step 5:Print x
Step 6:Print y
Step 7:End
PROGRAM
x=5
y=10
x,y=y,x
print ("x=",x)
print("y=",y)
Output:
x=10
y=5
DISTANCE BETWEEN TWO POINTS
ALGORITHM:
Step 1: Start
Step 2: Read value for x1,y1 co-ordinates
Step 3: Read values for x2,y2 co- ordinates
Step 4: Using math module,sqrt() used to calculate distance between two points
Step 5:Print distance
PROGRAM:
import math
print(“Enter co-ordinates for point 1:”)
x1=int(input(“x1=”))
y1=int(input(“y1=”))
print(“Enter co-ordinates for point 2:”)
x2=int(input(“x2=”))
y2=int(input(“y2=”))
dist=math.sqrt(((x2-x1)**2)+((y2-y1)**2))
print(“Distance between given points is”,round(dist,2))
Output:
Enter co-ordinates for point1:
x1=54
y1=54
Enter co-ordinates for point2:
x2=85
y2=85
Distance between given points is:43.04
10. Write a python program toPython programming using simple statements and
expressions
Circulate the values of n variables
ALGORITHM:
Step 1:Start
Step 2:Read the value for list 1
Step 3:By using for loop,use append() to add the values in the list
Step 4:Use pop() to circulate n variable
Step 5: print list1
PROGRAM:
no_of_terms=int(input(“Enter number of values:”))
list1=[]
for value in range(0,no_of_terms,1):
ele=int(input(“Enter integer:”))
list1.append(ele)
print(“Circulating the elements of the list:”,list1)
for val in range(0,no_of_terms,1):
ele=list1.pop(0)
list1.append(ele)
print(list1)
Output:
Enter number of values:4
Enter integer:50
Enter integer:85
Enter integer:25
Enter integer:70
Circulating the elements of the list:[50,85,25,70]
[85,25,70,50]
[25,70,50,85]
[70,50,85,25]
[50,85,25,70]
DISTANCE BETWEEN TWO POINTS
ALGORITHM:
Step 1: Start
Step 2: Read value for x1,y1 co-ordinates
Step 3: Read values for x2,y2 co- ordinates
Step 4: Using math module,sqrt() used to calculate distance between two points
Step 5:Print distance
PROGRAM:
import math
print(“Enter co-ordinates for point 1:”)
x1=int(input(“x1=”))
y1=int(input(“y1=”))
print(“Enter co-ordinates for point 2:”)
x2=int(input(“x2=”))
y2=int(input(“y2=”))
dist=math.sqrt(((x2-x1)**2)+((y2-y1)**2))
print(“Distance between given points is”,round(dist,2))
Output:
Enter co-ordinates for point1:
x1=54
y1=54
Enter co-ordinates for point2:
x2=85
y2=85
Distance between given points is:43.04
11. Write a python programming for Scientific problems using Conditionals and
Iterative loops
Number series(FIBONACCI SERIES)
Algorithm:
Step1:Input the number of values to generate the Fibonacci sequence.
Step 2:Initialize s1=0,s2=1,i=1,sum=0
Step 3:If the num_terms<=0
Step 4: while i<=n
Step 5:print(s1)
Step 6:sum=s1+s2
Step 7:Update the variables s1=s2,s2=sum and so on ,up to the required term.
Step 8:Increment the value of I and then repeat step 4 until condition becomes false
Program:
n=int(input(“Enter a value of n:”)
s1=0
s2=1
i=1
sum=0 print(“Number series”)
while(i<=n):
print(s1)
sum=s1+s2
s1=s2
s2=sum
i+=1

Output:
Enter the value of n:5
Number series
0
1
1
2
3
NUMBER PATTERN
PYTHON PROGRAM TO PRINT NUMBER PATTERN FOR 1 12 123 1234
ALGORITHM:
Step1: Initailize a variable number
Step2:The first outer for loop is used to handle number a rows and inner loop is used to
handle number of
columns
Step3: Print (i end=” “)
PROGRAM:
num=5
for n in range(1,num):
for i in range(1,n+1):
print(i,end=" ")
print(" ")
Output:
1
12
123
1234
PYTHON PROGRAM TO PRINT THE PATTERN FOR 1 22 333 4444
ALGORITHM:
Step1: Take input from the user.
Step2: The first outer for loop is used to handle anumber of row and the inner for loop
is used to handle a number of columns.
Step3: Print(i,end=” ”)is used to display numbers and print(“ “) is used for next line after
each row.
PROGRAM:
num=int(input(“Enter the number of rows:”))
for i in range(1,num+1):
for j in range(1,i+1):
print(i, end=” “)
print(“ “)
Output:
1
22
333
4444
55555
12. Write a python programming for Scientific problems using Conditionals and
Iterative loops
Pyramid pattern
HALF PYRAMID PATTERN OF STARS
ALGORITHM:
Step 1: Start
Step 2: Use nested for loop whereas, first for loop is used to print row value and second
for loop used to
print column values.
Step 3: Print (*) pattern

PROGRAM:
print(“Half pyramid pattern of stars”)
for i in range(5):
for j in range(i+1):
print(“*”,end=”“)
print( )
Output:
Half pyramid pattern of stars
*
**
***
****
*****

INVERTED HALF PYRAMID OF STARS


ALGORITHM:
Step1: Start
Step2: Use nested for loop whereas, first for loop is used to print row value and second
for loop used to print column values.
Step3: Print (‘*’) pattern
PROGRAM;
print(“inverted half pyramid of stars”)
for i in range(5):
for j in range(i,5):
print(“*”,end=” “)
print()
Output:
Inverted half pyramid stars
*****
****
***
**
*
FULL PYRAMID PATTERN OF STARS
ALGORITHM:
Step1: Start
Step2: Use nested for loop whereas, first for loop is used to print row value and second
for loop used to print column values
Step3: Print (“*”) pattern
PROGRAM:
print("inverted half pyramid of stars")
for i in range(5):
for s in range(-5,-i):
print(" ",end="")
for j in range(i+1):
print(" * ",end="")
print()
Output:
Inverted half pyramid of stars
*
**
***
****
*****

INVERTED FULL PYRAMID OF STARS


ALGORITHM:
Step1: Start
Step2: Use nested for loop whereas, first for loop is used to print row value and second
for loop is used to print
column.
Step3: print (‘*’) pattern.
PROGRAM:
print("inverted half pyramid of stars")
for i in range(5):
for s in range(i+1):
print(" ",end="")
for j in range(-5,-i):
print(" * ",end="")
print()
Output:
Inverted full pyramid of stars
*****
****
***
**
*
13. Write a python program to Implementing real-time/technical applications using
Lists,Tuples
Items present in a Library
14. Write a python program to Implementing real-time/technical applications using
Lists, Tuples
Components of a car
ALGORITHM:
Step 1: Start
Step 2: Create the tuples using round brackets().
Step 3: Declare the items in tuple like
(“radiator”,”silencer”,”crankshaft”,”bonnet”,”windshield”,”engine
block”,”silencer”)
Step 4: By using count() method,to count the items present in a tuple.
Step 5:Tuple items are indexed and we can access them by referring to the index number
Step 6: By usingtype() method,to return the data type of the tuple
Step 7: The index of -1 refers to the last item,-2 to the second item and so on.
Step 8: To concatenate the two tuples by using ‘+’ operator.
Step 9: To multiply the tuple items by using ‘*’operator.
Step 10: we can access a range of items in a tuple by using the slicing operator colon[:]
Step11:By using len() function,to retuen the number of items present in tuple.
Step 12:By using min() function ,return the minimum element in tuple.
Step 13: To delete the tuple using del() function
Step 14:Stop.
Program:
mytuple=("radiator","silencer","crankshaft","bonnet","windshield","engineblock","silencer")
print(mytuple)
print(mytuple[0])
x=mytuple.count("silencer")
print(x)
x=mytuple.index("bonnet")
print(x)
mytuple1="engine"
print(type(mytuple1))
print(mytuple[-2])
mytuple=mytuple+("break",)
print(mytuple)
mytuple1=(mytuple1)*2
print(mytuple1)
mytuple=mytuple[:3]+("clutch","door")
print(mytuple)
print(len(mytuple))
print(min(mytuple))
del(mytuple)
Output:
('radiator', 'silencer', 'crankshaft', 'bonnet', 'windshield', 'engineblock', 'silencer')
radiator
2
3
<class 'str'>
engineblock
('radiator', 'silencer', 'crankshaft', 'bonnet', 'windshield', 'engineblock', 'silencer', 'break')
engineengine
('radiator', 'silencer', 'crankshaft', 'clutch', 'door')
5
clutch
15. Write a python program to Implementing real-time/technical applications using
Lists,Tuples

Materials required for construction of a building–operations of list& tuples


ALGORITHM
Step 1: Start
Step 2: create the list using square brackets[ ].
Step 3: Declare the items in list like [‘jalli’,’cement’,’sand’,’red
sand’,’rod’,’bricks’,’wood’,’sand’]
Step 4: By using append() method,to add new item in list.
Step 5: by using copy() method,to copy the values in x variable.
Step 6:By using count() method ,to count the items present in a list.
Step 7:To append elements from another list to current list,use the extend () method.
Step 8: List items are indexed and we can access them by referring to the index number.
Step 9: To insert a new list item,without replacing any of the existing values,we can use
the insert() method.The
insert() method inserts an item at the specified index.
Step 10:The remove() method removes the specified item.
Step11: The pop() method removes the specified index.
Step12: The reverse() method reverses the elements of the list.
Step13 : The sort() method sorts the elements of a given list in a specific ascending Or
descending order.
Step14: The clear () method empties the list. The list still remains,but it has no content.
Step15:stop
Program:
mylist=["jalli","cement","sand","redsand","rod","bricks","wood","sand"]
print(mylist)
mylist.append("electric wires")
print(mylist)
x=mylist.copy()
print(x)
x=mylist.count("sand")
print(x)
mylist1=["metal","plastic","glass"]
mylist.extend(mylist1)
print(mylist)
x=mylist.index("bricks")
print(x)
mylist1.insert(1,"hollow bricks")
print(mylist1)
mylist.pop(1)
print(mylist)
mylist1.pop(0)
print(mylist1)
mylist.remove("rod")
print(mylist)
newlist=["fly ash bricks","clay bricks","concrete"]
newlist.reverse()
print(newlist)
newlist.sort()
print(newlist)
newlist.clear()
print(newlist)
Output:
['jalli', 'cement', 'sand', 'redsand', 'rod', 'bricks', 'wood', 'sand']
['jalli', 'cement', 'sand', 'redsand', 'rod', 'bricks', 'wood', 'sand', 'electric wires']
['jalli', 'cement', 'sand', 'redsand', 'rod', 'bricks', 'wood', 'sand', 'electric wires']
2
['jalli', 'cement', 'sand', 'redsand', 'rod', 'bricks', 'wood', 'sand', 'electric wires', 'metal',
'plastic', 'glass']
5
['metal', 'hollow bricks', 'plastic', 'glass']
['jalli', 'sand', 'redsand', 'rod', 'bricks', 'wood', 'sand', 'electric wires', 'metal', 'plastic',
'glass']
['hollow bricks', 'plastic', 'glass']
['jalli', 'sand', 'redsand', 'bricks', 'wood', 'sand', 'electric wires', 'metal', 'plastic', 'glass']
['concrete', 'clay bricks', 'fly ash bricks']
['clay bricks', 'concrete', 'fly ash bricks']
[]
16. Write a python program to Implementing real-time/technical applications using
Lists,Tuples
Word count
Longest number
Algorithm:
Step 1: Start the program.
Step 2: Create a list and assign value to it.
Step 3: In loop, assign the max to zero and check max against each element in the list
Step 4: If the element is greater than max, the value is assigned to mass and loop
continues the maximum
number is found.
Step 5: Using sort(), sort the list in ascending order and take the element from right
(index -1 for right most
element)
Step 6: Use max() to find the maximum number in the list and print the result.
Step 7: Stop the program
Program:
list=[1,2,3,7,5,9,12,10,4]
def largest(list):
max=0
for i in list:
if max<i:
max=i
return max
print("largest number using loop:",largest(list))
list.sort()
print("largest number using sort():",list[-1])
larg_result=max(list)
print("largest number using max():",larg_result)
Output:
Largest number using loop:12
Largest number using sort():12
Largest number using max():12
18. Write a Python class to convert an integer to a roman numeral
Algorithm:
Step1:Define a mapping of integers to their corresponding Roman numeral values in
descending order.
Step2. Initialize an empty string result to store the Roman numeral.
Step3. Iterate over the integer-Roman numeral pairs.
Step4. For each pair:
While the integer value can fit into the given number:
Subtract the integer value from the number.
Append the Roman numeral to the result string.
Step5. Return the result.
Program:
class IntegerToRoman:
def int_to_roman(self, num):
roman_map = [
(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'),
(100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'),
(10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')
]
result = ""
for value, symbol in roman_map:
result += (num // value) * symbol
num %= value
return result
converter = IntegerToRoman()
num=int(input("Enter the number:"))
print(converter.int_to_roman(num))
Output:
Enter the number:999
CMXCIX

You might also like