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

CS Practical

Uploaded by

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

CS Practical

Uploaded by

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

Q.

1 Write a short program to find average of list of number entered


through keyboard.
Source code :-
sum = count = 0
print("Enter numbers")
print("(Enter 'q' to see the average)")
while True :
n = input()
if n == 'q' or n == 'Q' :
break
else :
sum += int(n)
count += 1
avg = sum / count
print("Average = ", avg)
Output:
Enter numbers
(Enter 'q' to see the average)
2
5
7
15
12
q
Average = 8.2
Q.2Write python program to sum the given sequences :
(a) 2/9 – 5/13 + 8/17………(print 7 th term )
(b) 12 + 3 2 + 52+…….+n2
(input n)
Source code: -
A) n = 7
sum = 0
for i in range(1, n+1):
term = (2*i - 1)**2 / (8*i - 9)
sum += term if i % 2 == 1 else -term
print(f"Term {i}: {term:.2f}")
print(f"\nThe sum of the first {n} terms is: {sum:.4f}")
Output:
Term 1: 0.44
Term 2: -0.38
Term 3: 0.35
Term 4: -0.32
Term 5: 0.29
Term 6: -0.27
Term 7: 0.25
The sum of the first 7 terms is: 0.3642
B) n = int(input("Enter the value of n: "))
sum = 0
for i in range(1, n+1):
term = i**2
sum += term
print(f"The sum of the sequence is: {sum}")

Output:
Enter the value of n: 9
The sum of the sequence is: 165

Q.3 Write a program that reads from user -


(i) An hour between 1 to 12 and
(ii) Number of hours ahead. The program should then print the time
after those many hours.
Source code-
hr = int(input("Enter hour between 1-12 : "))
n = int(input("How many hours ahead : "))

s = hr + n

if s > 12:
s -= 12

print("Time at that time would be : ", s, "O'clock")


Output :
Enter hour between 1-12 : 9
How many hours ahead : 4
Time at that time would be : 1 O'clock
Q.4 Write a short program to check whether square root of a
number is prime or not.
Source code:-
import math

n = int(input("Enter a number: "))


sr = math.sqrt(n)
c=0
for i in range(1, int(sr + 1)) :
if (sr % i == 0) :
c += 1
if c == 2 :
print("Square root is prime")
else :
print("Square root is not prime")
Output:
Enter a number: 49
Square root is prime
Q.5Write a program to input length of three side of a triangle.
Source code: -
a = int(input("Enter first side : "))
b = int(input("Enter second side : "))
c = int(input("Enter third side : "))
if a + b > c and b + c > a and a + c > b :
print("Triangle Possible")
else :
print("Triangle Not Possible")

Output:
Enter first side : 3
Enter second side : 5
Enter third side : 6
Triangle Possible
Q.6 Write a program that prompts the user for a strings and a
character c, and outputs the string produced from s by capitalizing
each occurrence of the character c in s and making all other
characters lowercase.
Source Code: -

# Get input from the user


s = input("Enter a string: ")
c = input("Enter a character: ")
# Iterate through each character in the string
result = ""
for char in s:
# If the current character is the one we're looking for, capitalize it
if char == c:
result += char.upper()
# Otherwise, make it lowercelse:
result += char.lower()
# Print the resulting string
print(result)
Output-
Enter a string: Hello, my name is Alice!
Enter a character: e
hElLO, MY nAMe IS AlICe!
Q.7 Write a program to find the mode, from a list.
Source code :
def mode(numbers):
# Count the occurrences of each number
counts = {}
for number in numbers:
if number not in counts:
counts[number] = 1
else:
counts[number] += 1
# Find the number with the highest count
max_count = max(counts.values())
mode = [num for num in counts if counts[num] == max_count]
return mode
Output :
numbers = [1, 2, 2, 3, 4, 4, 4]
mode(numbers) # Returns [4]
Q.8 Write python that create a tuple storing first 9 term of Fibonacci
series.
Source code: -
lst = [0,1]
a=0
b=1
c=0
for i in range(7):
c=a+b
a=b
b=c
lst.append(c)
tup = tuple(lst)
print("9 terms of Fibonacci series are:", tup)
Output :
9 terms of Fibonacci series are: (0, 1, 1, 2, 3, 5, 8, 13, 21)
Q.9 Write a program that inputs two tuples and creates a third, that
contains all elements of the first followed by all elements of the
second.
Source code:
tup1 = eval(input("Enter the elements of first tuple: "))
tup2 = eval(input("Enter the elements of second tuple: "))
tup3 = tup1 + tup2
print(tup3)
Output:
Enter the elements of first tuple: 1,3,5,7,9
Enter the elements of second tuple: 2,4,6,8,10
(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)
Q.10 Write a program to count the number of times a character
appears in a given string.
Source Code:

str = input("Enter the string: ")


ch = input("Enter the character to count: ");
c = str.count(ch)
print(ch, "occurs", c, "times")
Output:
Enter the string: Helloemily
Enter the character to count: e
e occurs 2 times
Q.11 Repeatedly ask the user to enter a team name and how many
games the team has won and how many they lost. Store this
information in a dictionary where the keys are the team names and
the values are lists of the form [wins, losses].
(a) Using the dictionary created above, allow the user to enter a
team name and print out the team's winning percentage.
(b) Using the dictionary, create a list whose entries are the number
of wins of each team.
(c) Using the dictionary, create a list of all those teams that have
winning records.
Source code :
d = {}
ans = "y"
while ans == "y" or ans == "Y" :
name = input("Enter Team name: ")
w = int(input("Enter number of wins: "))
l = int(input("Enter number of losses: "))
d[name] = [w, l]
ans = input("Do you want to enter more team names? (y/n): ")
team = input("Enter team name for winning percentage: ")
if team not in d:
print("Team not found", team)
else:
wp = d[team][0] / sum(d[team]) * 100
print("Winning percentage of", team, "is", wp)
w_team = []
for i in d.values():
w_team.append(i[0])
print("Number of wins of each team", w_team)
w_rec = []
for i in d:
if d[i][0] > 0:
w_rec.append(i)
print("Teams having winning records are:", w_rec)
OUTPUT
Enter Team name: masters
Enter number of wins: 9
Enter number of losses: 1
Do you want to enter more team names? (y/n): y
Enter Team name: musketeers
Enter number of wins: 6
Enter number of losses: 4
Do you want to enter more team names? (y/n): y
Enter Team name: challengers
Enter number of wins: 0
Enter number of losses: 10
Do you want to enter more team names? (y/n): n
Enter team name for winning percentage: musketeers
Winning percentage of musketeers is 60.0
Number of wins of each team [9, 6, 0]
Teams having winning records are: ['masters', 'musketeers']
Q.12 Write a program to check if the maximum element of a tuple
lies at the middle position of the tuple.
Source code:
def max_at_middle(t):
# Check if the tuple has an odd length
if len(t) % 2 != 1:
return False
# Find the middle index
mid_index = len(t) // 2
# Check if the maximum element is at the middle position
return t[mid_index] == max(t)
Output: t = (1, 2, 3, 4, 5)
max_at_middle(t) # Returns False
Q.13 Write a program to check Armstrong number or not.
Source code :

def is_armstrong(n):
# Convert the number to a string
n_str = str(n)
# Calculate the sum of the cubes of each digit
sum_cubes = sum(int(digit)**3 for digit in n_str)
# Check if the sum of the cubes is equal to the original number
return sum_cubes == n
Output :
print(is_armstrong(153))
True
Q.14 Write a program to check if the elements in the first half of a
tuple are sorted in ascending order or not.
Source Code:
if
firsthalf_tuple == tuple(sorted(firthalf_tuple, reverse=True)):
Order is Descending
elif firsthalf_tuple == tuple(sorted(firsthalf_tuple)):
Order is not in descending order
else:
No order
Output:
t = (6, 5, 4, 3, 2, 1)
TRUE
Q.15 Write a program to calculate the area of an equilateral
triangle.
Source code:
import math
side = float(input("Enter side: "))
area = math.sqrt(3) / 4 * side * side
print("Area of triangle =", area)
Output:
Enter side: 5
Area of triangle = 10.825317547305481
Q.16 Write a program to find largest number of a list of numbers
entered through keyboard.
Source code:
print("Enter numbers:")
print("(Enter 'q' to see the result)")
l = input()
if l != 'q' and l != 'Q' :
l = int(l)
while True:
n = input()
if n == 'q' or n == 'Q' :
break
n = int(n)
if n > l :
l=n
print("Largest Number =", l)
Output:
Enter numbers:
(Enter 'q' to see the result)
3
5
8
2
4
q
Largest Number = 8
Q.17 Write a program to search for an element in a given list of
numbers.
Source code:

def search(numbers, target):


# Check if the target is in the list
if target in numbers:
# Find the index of the target
index = numbers.index(target)
# Return the index
return index
else:
# Return -1 if the target is not in the list
return -1
Output:
numbers = [1, 2, 3, 4, 5]
target = 3
print(search(numbers, target))
2
Q.18 WAP to count frequency of a given element in a list of
numbers
Source code:
L=[2,58,95,999,65,32,15,1,7,45]
n=int(input("Enter the number : "))
print("The frequency of number ",n," is ",L.count(n))
Output:
Enter the number : 58
The frequency of number 58 is 1
Q.19 Input a list of numbers and swap elements at the even
location with the elements at the odd location Python Program
Source code:
# Entering 5 element Lsit
mylist = []
print("Enter 5 elements for the list: ")
for i in range(5):
value = int(input())
mylist.append(value)
# printing original list
print("The original list : " + str(mylist))
# Separating odd and even index elements
odd_i = []
even_i = []
for i in range(0, len(mylist)):
if i % 2:
even_i.append(mylist[i])
else :
odd_i.append(mylist[i])
result = odd_i + even_i
# print result
print("Separated odd and even index list: " + str(result))
Output:
Enter 5 elements for the list:
4
7
16
7
9
The original list : [4, 7, 16, 7, 9]
Separated odd and even index list: [4, 16, 9, 7, 7]
Q.20 Python Program to input 3 numbers and display the largest
number.
Source code:
def maximum(a, b, c):

if (a >= b) and (a >= c):


largest = a

elif (b >= a) and (b >= c):


largest = b
else:
largest = c

return largest
Output:
Input: a = 2, b = 4, c = 3
Output: 4

You might also like