Programming in Python Assignment - DHANANJAY SINGHAL
Programming in Python Assignment - DHANANJAY SINGHAL
HANSRAJ COLLEGE
BSC (HONS) COMPUTER SCIENCE
SEMESTER - 3
PROGRAMMING IN PYTHON
DHANANJAY SINGHAL
21CS/13
Question 1 :
Write a function that takes the lengths of three sides : side1,side2 and side3 of the triangle as the
input from the user using the input function and return the area and perimeter of the triangle as a
tuple. Also, assert that the sum of the length of any two sides is greater than the third side.
Solution 1 :
if __name__ == "__main__":
Consider a showroom of electronic products, where there are various salesmen.Each salesman is
given a commission of 5%, depending on the sales made per month. Incase the sale done is less
than 50000,then the salesman is not given any commission. Write a function to calculate total
sales of a salesman in a month, commission and remarks for the salesman. Sales done by each
salesman per week is to be provided as input. Use tuples/list to store data of salesmen.
Assign remarks according to the following criteria :
Excellent : Sales>=80000
Good : Sales>=60000 and <80000
Average : Sales>=40000 and <60000
Work Hard : Sales<40000
Solution 2 :
remarks = ""
if total_sales >= 80000:
remarks = "Excellent"
elif total_sales >= 60000:
remarks = "Good"
elif total_sales >= 40000:
remarks = "Average"
elif total_sales < 40000:
remarks = "Work Hard"
if __name__ == "__main__":
sale1 = float(input("Enter the sales for week 1: "))
sale2 = float(input("Enter the sales for week 2: "))
sale3 = float(input("Enter the sales for week 3: "))
sale4 = float(input("Enter the sales for week 4: "))
t_sales, comm, remarks = calc(sale1, sale2, sale3, sale4)
Write a Python function to find the nth term of Fibonacci sequence and its factorial.Return the
result as a list.
Solution 3 :
def factorial(n):
if n <= 1:
return 1
else:
return n * factorial(n-1)
def fibonnaci(n):
if n <= 0:
return 0
if n == 1:
return 1
return fibonnaci(n-1) + fibonnaci(n-2)
if __name__ == '__main__':
num = int(input("Enter a number: "))
print(f"{num} term of fibonacci series : ", fibonnaci(num))
print(f"Factorial of {num} : ", factorial(num))
Output 3 :
Question 4 :
Write a function that takes a number (>=10) as an input and return the digits of the number as a
set.
Solution 4 :
Output 4 :
Question 5 :
Write a function that finds the sum of the n terms of the following series. Import the factorial
function created in question 4.
Series : 1-x2/2!+x4/4!-x6/6!+…xn/n!
Solution 5 :
if __name__ == "__main__":
n = int(input("Enter n: "))
x = int(input("Enter x: "))
sum = sum_series(x, n)
print(f'Sum of {n} terms of series for x={x} is {sum}')
Output 5 :
Question 6 :
Solution 6 :
t1 = (1,2,5,7,9,2,4,6,8,10)
print("Given tuple: ", t1)
# a) Print another tuple whose values are even numbers in the given tuple.
t_even = ()
for i in range(0, len(t1)):
if t1[i] % 2 == 0:
t_even += (t1[i],)
print("New tuple with even values : ", t_even)
Question 7 :
Solution 7 :
def main():
print("\nMenu")
print("-"*20)
print("1. Length of string")
print("2. Maximum of three strings")
print("3. Replace vowels with '#'")
print("4. No. of words")
print("5. Check Palindrome")
print("6. Exit")
print("-"*20)
option = input("Your choice: ")
switcher = {
'1': len_str,
'2': maxof_three,
'3': replace_vowels,
'4': numofwords,
'5': palindrome,
'6': quit
}
func = switcher.get(option, lambda: print("Invalid Choice!"))
func()
if __name__ == "__main__":
ch = 'y'
while ch.lower() == 'y':
main()
ch = input("\nWant to continue? [y/n]: ")
Output 7 :
Question 8 :
Solution 8 :
# c) If list contains all Strings, then display largest String in the list.
def largest_str(l):
flag = True
for i in range(len(l)):
if type(l[i]) != str:
flag = False
if flag:
largest = l[0]
for i in l:
if len(i) > len(largest):
largest = i
print("Largest string: ", largest)
else:
print("List does not contain all strings!")
def main(l):
print("\nMenu")
print("-"*20)
print("1. Check if all elements are numbers")
print("2. Count odd numbers if list is numeric")
print("3. Display largest string in list")
print("4. Reverse the list")
print("5. Find item in list")
print("6. Remove item from list")
print("7. Sort in Descending order")
print("8. Find common elements from another list")
print("9. Exit")
print("-"*20)
option = input("Your choice: ")
switcher = {
'2': count_odd,
'3': largest_str,
'4': display_reverse,
'5': find_item,
'6': remove_item,
'7': sort_desc,
'8': common,
'9': quit
}
if option == '1':
if check_int(l):
print("All elements are numbers")
else:
print("All elements are not numbers")
elif option == '8':
l2 = []
n = int(input("Enter the size of new list: "))
for i in range(0, n, 1):
l2.append(input("Enter element: "))
common(l, l2)
else:
func = switcher.get(option, lambda: print("Invalid Choice!"))
func(l)
if __name__ == "__main__":
l = []
n = int(input("Enter the size of list: "))
for i in range(0, n, 1):
l.append(input("Enter element: "))
ch = 'y'
while ch.lower() == 'y':
main(l)
ch = input("\nWant to continue? [y/n]: ")
Output 8 :
Question 9 :
Use dictionary to store marks of the students in 4 subjects. Write a function to find the name of the
student securing highest percentage.
(Hint:Names of students are unique).
Solution 9 :
def findTopStudent(marks):
name = ''
percentage = 0.0
for student in marks:
marks_list = marks[student]
total = 0.0
for i in range(0, len(marks_list), 1):
total += marks_list[i]
if percentage < total/4:
percentage = total/4
name = student
return name
if __name__ == "__main__":
marks = {}
num = int(input('Enter the no. of students: '))
for i in range(1, num+1, 1):
name = input('\nEnter the name of Student {}: '.format(i))
temp = []
for j in range(1, 5, 1):
mark = float(input('Marks in Subject {}(out of 100): '.format(j)))
temp.append(mark)
marks[name] = temp
topper = findTopStudent(marks)
print('\n{} secured the highest percentage.'.format(topper))
Output 9 :
Question 10 :
Write a function that takes a sentence as input from the user and calculates the frequency of each
letter.
Use a variable of dictionary type to maintain the count.
Solution 10 :
def calcFreqOfLetters(sentence):
freq = {}
for i in range(0, len(sentence), 1):
letter = sentence[i].lower()
if letter not in [' ', '.', ',', '\'', '\"', '!', ';']:
if letter in freq.keys():
freq[letter] += 1
else:
freq[letter] = 1
return freq
if __name__ == "__main__":
sentence = input('\nEnter a sentence : ')
freq = calcFreqOfLetters(sentence)
Output 10 :
Question 11 :
Write a menu-driven program to accept a list of student names and perform the following
a. Search an element using linear search/ binary search.
b. Sort the elements using bubble sort/ insertion sort/ selection sort.
Solution 11 :
def bubbleSort(list):
for i in range(0, len(list)-1, 1):
for j in range(0, len(list) - i - 1, 1):
if list[j] > list[j+1]:
temp = list[j]
list[j] = list[j+1]
list[j+1] = temp
return list
def insertionSort(list):
for i in range(0, len(list), 1):
temp = list[i]
j = i - 1
while j >= 0 and list[j] > temp:
list[j+1] = list[j]
j -= 1
list[j+1] = temp
return list
def selectionSort(list):
for i in range(0, len(list)-1, 1):
minIndex = i
for j in range(i+1, len(list), 1):
if list[minIndex] > list[j]:
minIndex = j
temp = list[minIndex]
list[minIndex] = list[i]
list[i] = temp
return list
if __name__ == "__main__":
num = int(input('\nEnter the number of students: '))
print('Enter the names of students:')
names = []
for i in range(0, num, 1):
names.append(input('{}: '.format(i+1)))
choice = 'y'
while choice.lower() == 'y':
print('\n-------- Menu --------')
print('1. Search a name')
print('2. Sort the list of names')
choice = input('Your Choice: ')
if choice == '1':
name = input('\nEnter a name to search: ')
choice = input('Choose a searching algorithm:\n1. Linear, 2. Binary: ')
index = -1
if choice == '1':
index = linearSearch(names, name)
elif choice == '2':
index = binarySearch(names, name)
else:
print('Invalid Choice!')
if index == -1:
print('Name is not in the list.')
else:
print('Name found in the list.')
elif choice == '2':
choice = input('Choose a sorting algorithm:\n1. Bubble, 2. Insertion,
3. Selection: ')
sorted_names = []
if choice == '1':
sorted_names = bubbleSort(names)
elif choice == '2':
sorted_names = insertionSort(names)
elif choice == '3':
sorted_names = selectionSort(names)
else:
print('Invalid Choice!')
print('Sorted list: ', end='')
for i in range(0, len(sorted_names), 1):
print('\'{}\''.format(sorted_names[i]), end=' ')
print('')
else:
print('Invalid Choice!')
Output 11 :
Question 12 :
Write a program that makes use of a function to accept a list of n integers and displays a
histogram.
Solution 12 :
def inputList():
'''
To take a input of list of integers from user
Returns the list
'''
ls = []
length = int(input('Enter the length of list: '))
for i in range(0, length, 1):
ls.append(int(input('Enter element {}:'.format(i+1))))
return ls
if __name__ == "__main__":
list = inputList()
plt.hist(list, )
plt.xlabel('Integer')
plt.ylabel('Frequency')
plt.title('Histogram')
plt.savefig('hist.png', dpi=275, bbox_inches='tight') # To save the plot
plt.show()
Output 12 :
Question 13 :
Write a program that makes use of a function to display sine, cosine, polynomial and exponential
curves.
Solution 13 :
def sineCurve():
'''
To plot sine function
'''
plt.subplot(2, 2, 1)
degrees = range(0, 360 + 1)
sinValues = [math.sin(math.radians(i)) for i in degrees]
plt.plot(sinValues)
plt.xlabel('Degrees')
plt.ylabel('Sin Values')
plt.title('Sine Curve')
plt.grid()
def cosineCurve():
'''
To plot cos function
'''
plt.subplot(2, 2, 3)
degrees = range(0, 360 + 1)
cosValues = [math.cos(math.radians(i)) for i in degrees]
plt.plot(degrees, cosValues)
plt.xlabel('Degrees')
plt.ylabel('Cosine Values')
plt.title('Cosine Curve')
plt.grid()
def polynomialCurve():
'''
To plot a polynomial function
'''
def polynomial(x):
return (8*x*x)
plt.subplot(2, 2, 2)
x = range(-51, 50 + 2)
y = [polynomial(i) for i in x]
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y = 8x^2')
plt.title('Polynomial Curve')
plt.grid()
def expCurve():
'''
To plot sine function
'''
plt.subplot(2, 2, 4)
x = []
for i in range(0, 100*10):
x.append((-5) + (0.01)*i)
y = [math.exp(i) for i in x]
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y = e^x')
plt.title('Exponetial Curve')
plt.grid()
if __name__ == "__main__":
plt.figure(figsize=(9, 5)) # To set the figure size
sineCurve()
cosineCurve()
polynomialCurve()
expCurve()
plt.tight_layout()
plt.savefig('plot.png', dpi=275, bbox_inches='tight') # To save the plot
plt.show()
Output 13 :
Question 14 :
Write a function that reads a file file1 and copies only alternative lines to another file file2.
Alternative lines copied should be the odd numbered lines. Use Exception.
Solution 14 :
if __name__ == "__main__":
copyOddNumberedLines('file1.txt', 'file2.txt')
Output 14 :
File 1 :
File 2 :
Question 15 :
Define a class Student to store his/ her name and marks in three subjects.
Use a class variable to store the maximum average marks of the class.
Use constructor and destructor to initialize and destroy the objects.
Solution 15 :
class Student:
# Class Variable
max_avg = 0
# Constructor
def __init__(self, name='', marks=[0, 0, 0]):
self.name = name
self.marks = marks
# Destructor
def __del__(self):
del self.name
del self.marks
del self
def __str__(self):
str = '\nMarks: {}\n'.format(self.name)
str += '------------------\n'
str += 'Subject 1: {}\n'.format(self.marks[0])
str += 'Subject 2: {}\n'.format(self.marks[1])
str += 'Subject 3: {}\n'.format(self.marks[2])
str += 'Average: {:.2f}'.format(self.calcAvg())
return str
def calcAvg(self):
total = 0.0
for i in range(0, 3, 1):
total += self.marks[i]
return total/3
if __name__ == "__main__":
students = []
num = int(input('\nEnter the no. of students: '))
for i in range(1, num+1, 1):
name = input('\nEnter the name of Student {}: '.format(i))
marks = []
for j in range(1, 4, 1):
marks.append(float(input('Marks in Subject {}: '.format(j))))
END OF ASSIGNMENT