0% found this document useful (0 votes)
12 views19 pages

Python Programming Exercises and Solutions

Uploaded by

laughoutloudzero
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)
12 views19 pages

Python Programming Exercises and Solutions

Uploaded by

laughoutloudzero
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

Rahul Suresh 22IZ029

Problem Solving & Python Programming Lab


Exercise-5

1. To find Average of n Numbers

Code:
sum=0
n=int(input("Enter how many numbers you want to add: "))
for i in range(n):
num=int(input("Enter a number: "))
sum=sum+num
average=sum/n
print("Average: ",average)

Output:
Enter how many numbers you want to add: 5
Enter a number: 5
Enter a number: 5
Enter a number: 5
Enter a number: 5
Enter a number: 5
Average: 5.0
Rahul Suresh 22IZ029

2. Checking input number for Odd or Even

Code:
num=int(input("Enter a number: "))
if (num%2==0):
print(num,"is an even number")
else:
print(num,"is an odd number")

Output:
Enter a number: 3
3 is an odd number
Rahul Suresh 22IZ029

3. Print Factors of a Number

Code:
l=[]
num=int(input("Enter the number: "))
for i in range(1,num+1):
if (num%i==0):
[Link](i)
print("Factors of",num,"are: ")
for j in range(len(l)):
print (l[j])

Output:
Enter the number: 6
Factors of 6 are:
1
2
3
6
Rahul Suresh 22IZ029

4. Find Largest among n Numbers

Code:
l=[]
n=int(input("How many numbers do you want to add: "))
for i in range(n):
num=int(input("Enter a number: "))
[Link](num)
print("Largest number is",max(l))

Output:
How many numbers do you want to add: 5
Enter a number: 56
Enter a number: 278
Enter a number: 2564
Enter a number: 43
Enter a number: 567
Largest number is 2564
Rahul Suresh 22IZ029

5. Print Multiplication Table of input Number

Code:
n=int(input("Enter the number you want the multiplication table: "))
print("The Multiplication for",n,"is: ")
for i in range(1,11):
print (n,"*",i,"=",n*i)

Output:
Enter the number you want the multiplication table: 5
The Multiplication for 5 is:
5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
Rahul Suresh 22IZ029

6. Fibonacci Series

Code:
def f(n):
if n<0:
print("invalid")
elif n==0:
return 0
elif n==1 or n==2:
return 1
else:
return f(n-1) + f(n-2)
x=int(input("Enter a number: "))
a=f(x)
print("Fibonacci: ",a)

Output:
Enter a number: 9
Fibonacci: 34
Rahul Suresh 22IZ029

7. Checking for Vowel

Code:
l=[]
n=input("Enter a string: ")
a=["a","A","e","E","i","I","o","O","u","U"]
for i in n:
[Link](i)
for j in l:
if j in a:
print (j)

Output:
Enter a string: Apples
A
e
Rahul Suresh 22IZ029

8. Swapping Two Numbers

Code:
a=int(input("Enter a number: "))
b=int(input("Enter another number: "))
c=a
a=b
b=c
print ("The first number is swapped to",a)
print ("The second number is swapped to",b)

Output:
Enter a number: 5
Enter another number: 6
The first number is swapped to 6
The second number is swapped to 5
Rahul Suresh 22IZ029

9. Second largest among three numbers


Code:
a=int(input("Enter 1st number: "))
b=int(input("Enter 2nd number: "))
c=int(input("Enter 3rd number: "))
if (a>b):
if (c>a):
print (a,"is the second largest number")
elif (a>c):
print (b,"is the second largest number")
elif (b>a):
if(c>b):
print (b,"is the second largest number")
elif (b>c):
print (c,"is the second largest number")
elif (c>a):
if(b>c):
print (c,"is the second largest number")
elif (c>b):
print (a,"is the second largest number")

Output:
Enter 1st number: 5
Enter 2nd number: 3
Enter 3rd number: 15
5 is the second largest number
Rahul Suresh 22IZ029

10. Finding simple interest and compound interest


Code:
p=float(input("Enter the principal amount: "))
t=float(input("Enter number of years: "))
r=float(input("Enter rate of interest: "))
n=float(input("Enter the number of times interest is compounded
per year: "))
s=(p*t*(r/100))
print("Simple interest =",s)
a=p+s
m=1+((r/100)/n)
c=(p*(m**(n*t)))-p
print("Compound Interest = ",c)
print("Amount after simple interest = Rs.",a)
b=p+c
print("Amount after compound interest = Rs.",b)

Output:
Enter the principal amount: 1000
Enter number of years: 5
Enter rate of interest: 5
Enter the number of times interest is compounded per year: 2
Simple interest = 250.0
Compound Interest = 280.08454419635655
Amount after simple interest = Rs. 1250.0
Amount after compound interest = Rs. 1280.0845441963565
Rahul Suresh 22IZ029

11. Greatest Common Divisor(GCD)

Code:
import math
a=int(input("Enter a number: "))
b=int(input("Enter another number: "))
print("The gcd of",a,"and",b," : ", end="")
print([Link](a, b))

Output:
Enter a number: 60
Enter another number: 48
The gcd of 60 and 48 : 12
Rahul Suresh 22IZ029

12. Celsius to Fahrenheit

Code:
temp=int(input("Enter temperature in Celsius: "))
k=temp+273
print("Temperature in Kelvin =",k)

Output:
Enter temperature in Celsius: 30
Temperature in Kelvin = 303
Rahul Suresh 22IZ029

13. Roots of Quadratic Roots

Code:
import math
eq=input("Enter the equation correctly in the order (ax^2+bx+c=0): ")
a=int(input("Enter the coefficient of x^2 :"))
b=int(input("Enter the coefficient of x :"))
c=int(input("Enter the constant value: "))
w=((b**2)-(4*a*c))
v=[Link](w)
x=(-b+v)/(2*a)
y=(-b-v)/(2*a)
print("The roots of the equation",eq,"are",x,"and",y)

Output:
Enter the equation correctly in the order (ax^2+bx+c=0): a
Enter the coefficient of x^2 :2
Enter the coefficient of x :-1
Enter the constant value: -6
The roots of the equation a are 2.0 and -1.5
Rahul Suresh 22IZ029

14. Calculate nPr and nCr


Code:
def fact(k):
Output:
f=i=1
Enter the Value of n: 5
while i<=k:
Enter the Value of r: 2
f = i*f
i += 1
Permutation (nPr) = 20.0
return f
def findperm(x, y): Combination (nCr) = 10.0

num = fact(x)
den = fact(x - y)
perm = num / den
return perm
def findcomb(x, y):
num = fact(x)
den = fact(x - y)
den = fact(y) * den
comb = num / den
return comb
print("Enter the Value of n: ", end="")
n = int(input())
print("Enter the Value of r: ", end="")
r = int(input())
print("\nPermutation (nPr) =", findperm(n, r))
print("Combination (nCr) =", findcomb(n, r))
Rahul Suresh 22IZ029

15. To Check Leap Year or not

Code:
year=int(input("Enter the year you want to check for leap year: "))
if (year % 400 == 0) and (year % 100 == 0):
print("{0} is a leap year".format(year))

elif (year % 4 ==0) and (year % 100 != 0):


print(year,"is a leap year")

else:
print(year,"is not a leap year")

Output:
Enter the year you want to check for leap year: 2020
2020 is a leap year
Rahul Suresh 22IZ029

16. To Reverse a Number

Code:
a=input("Enter any number other than single digit number: ")
print ("The reversed order of",a,"is",a[::-1])

Output:
Enter any number other than single digit number: 3567
7653
Rahul Suresh 22IZ029

17. To Check Whether a Number is Palindrome or Not

Code:
num=input("Enter a number to check for palindrome: ")
reverse = int(str(num)[::-1])
if num == reverse:
print('Palindrome')
else:
print("Not Palindrome")

Output:
Enter a number to check for palindrome: 1221
Palindrome
Rahul Suresh 22IZ029

18. To Make a Simple Calculator Using CASE

Code: Output:
def add(x,y): Enter a number: 4
return x+y Enter another number: 7
def multiply(x,y): 1-Add
return x*y 2-Subtract
def subtract(x,y): 3-Multiply
return x-y
4-Divide2
def divide(x,y):
Answer= -3
return x/y
a=int(input("Enter a number: "))
b=int(input("Enter another number: "))
x=int(input("1-Add\n2-Subtract\n3-Multiply\n4-Divide"))
if x==1:
ans=add(a,b)
elif x==2:
ans=subtract(a,b)
elif x==3:
ans=multiply(a,b)
elif x==4:
ans=divide(a,b)
else:
print("Enter correctly")
print("Answer=",ans)
Rahul Suresh 22IZ029

20. To Count Number of Digits in number

Code:
a=int(input("Enter a number: "))
s=str(a)
l=len(s)
print("Number of digits in the number is",l)

Output:
Enter a number: 6788
Number of digits in the number is 4

Common questions

Powered by AI

List comprehensions provide a concise way to construct lists leveraging the benefits of declarative programming. To check vowels in the input string more efficiently, one could use a list comprehension to filter and print vowels. For example, `[print(char) for char in n if char in a]` processes the characters in a single pass. Alternatively, map/lambda functions could be used with a filter function to achieve similar results, ensuring readability and performance improvements by reducing the overhead of unnecessary list appending seen in manual iteration .

The limitations of the leap year determination program include potential inefficiency when processing a large number of inputs simultaneously and lack of user feedback for invalid inputs, such as negative years. Improvements could involve a loop or function to process multiple years in succession and integration of input validation checks with meaningful error messages. Adding comments to explain the leap year logic might also enhance the code's comprehensibility for further maintenance or educational purposes .

In Python, a string can be reversed by utilizing slicing with a step of -1 (e.g., `string[::-1]`). The provided code uses this slicing technique to reverse a number input as a string, which allows it to be reversed by accessing its characters from the last to the first .

An error can occur if the variable 'n' is set to 0, which would result in a division by zero error when calculating the average. This error can be mitigated by adding a condition to check if 'n' is greater than zero before performing the division. If 'n' is zero, the program can print a warning message instead of attempting to calculate the average .

Simple interest is computed as a linear function of time, with interest calculated only on the principal amount, illustrating linear growth because the growth value rises by a constant rate over time. Compound interest, however, involves calculating interest on both the principal and accumulated interest, demonstrating exponential growth as the base amount periodically increases, causing the interest to be calculated on a continually rising base, leading to faster growth rates as time progresses .

The algorithm for finding the GCD, typically using the Euclidean method, involves recursive division to find the largest integer that divides both numbers without a remainder. Using the Python math library simplifies this process by providing a built-in function `math.gcd(a, b)` that efficiently implements this algorithm without requiring the user to write the iterative or recursive logic manually, thereby reducing potential errors and enhancing code readability .

The algorithm first compares the first two numbers. If the first number is greater, it then compares the first with the third to decide if the first is the second largest or the second number is the second largest. If the second number is greater than the first initially, the comparison is made between the second and third numbers. The steps ensure accuracy by systematically eliminating one possibility through direct comparisons, thus narrowing down the selection of the second largest .

When implementing the swap function, it's essential to consider whether additional storage is needed and to account for data mutability. The provided method uses a temporary variable to hold the value of the first number while assigning the second number to the first, then assigns the value in the temporary variable to the second number. This ensures that the original values are swapped without losing any data, leveraging temporary storage to achieve the desired outcome .

To improve user input validation in the Fibonacci series function, include checks to ensure that the input is a non-negative integer. This can be done by adding exception handling to catch non-integer inputs and by verifying that the input is zero or greater. This is necessary to prevent runtime errors and to ensure that invalid inputs do not crash the program or produce incorrect results, aligning with the function's intention to compute valid terms in the Fibonacci sequence .

Permutations and combinations are significant in statistics for quantifying the number of possible configurations in which a set of objects can be arranged (permutations) or selected (combinations), crucial in probability calculations and decision-making processes. The code processes these calculations by employing a factorial function to compute the total possible arrangements (n!) and permutations (nPr) by dividing by the factorial of the difference (n-r)!. Combinations (nCr) are derived by additionally dividing by the factorial of r! to account for order irrelevance .

You might also like