25% found this document useful (4 votes)
4K views92 pages

Py

The document describes a Python function that takes a dictionary as input where the keys are correct spellings of words and the values are spellings provided by a contestant. The function returns a list identifying the degree of correctness for each input based on: - CORRECT for an exact match - ALMOST CORRECT if no more than 2 letters differ - WRONG if more than 2 letters differ or the lengths do not match

Uploaded by

Shravan Apte
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
25% found this document useful (4 votes)
4K views92 pages

Py

The document describes a Python function that takes a dictionary as input where the keys are correct spellings of words and the values are spellings provided by a contestant. The function returns a list identifying the degree of correctness for each input based on: - CORRECT for an exact match - ALMOST CORRECT if no more than 2 letters differ - WRONG if more than 2 letters differ or the lengths do not match

Uploaded by

Shravan Apte
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 92

'''--------------------------------------------------------------------------------------------------------------

Register Number – 191805


Date – 04/12/2019
Program no – 32
Write a recursive function, is_palindrome() to find out whether a string is a palindrome or
not. The function should return true, if it is a palindrome. Else it should return false.
---------------------------------------------------------------------------------------------------------------'''
def is_palindrome(word):
if len(word) == 1:
return True
if len(word) == 2:
if word[0] == word[-1]:
return True
else:
return False
if word[0] == word[-1]:
return is_palindrome(word[1:-1])
else:
return False

def main():
word=input("Enter the word: ")
word = word.lower()
result = is_palindrome(word)
if result == 1:
print("The given word is a Palindrome")
else:
print("The given word is not a Palindrome")

main()
OUTPUT:
Enter the word: click
The given word is not a Palindrome

Enter the word: madam


The given word is a Palindrome
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 33
A 10-substring of a number is a substring of its digits that sum up to 10.
For example, the 10-substrings of the number 3523014 are:
3523014, 3523014, 3523014, 3523014
Write a python function, find_ten_substring(num_str) which accepts a string and returns
the list of 10-substrings of that string.
Handle the possible errors in the code written inside the function.

Sample Input Expected Output


'3523014' ['5230', '23014', '523', '352']

---------------------------------------------------------------------------------------------------------------'''
def find_ten_substring(num_str):
str1 = ""
list1 = []
a=0
for i in range(0, len(num_str)):
a = a + int(num_str[i])
str1 += str(num_str[i])
if (a == 10):
a=0
list1.append(str1)
str1 = ""
return (list1)

num_str = "2825302"
print("The number is:", num_str)
result_list = find_ten_substring(num_str)
print(result_list)
OUTPUT:

The number is: 3523014

['352']
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 34
Given a number n, write a program to find the sum of the largest prime factors of each of nine
consecutive numbers starting from n.
g(n) = f(n) + f(n+1) + f(n+2) + f(n+3) + f(n+4) + f(n+5) + f(n+6) + f(n+7) + f(n+8)
where, g(n) is the sum and f(n) is the largest prime factor of n.
---------------------------------------------------------------------------------------------------------------'''
def largest_prime(n):
# list to store prime nunumber
prime_list = []

for i in range(2, n + 1):


if n % i == 0:
isprime = 1
for j in range(2, ((i // 2) + 1)):
if i % j == 0:
isprime = 0
break
if isprime == 1:
prime_list.append(i)
return max(prime_list)

def main():
n = int(input("Enter a number: "))
sum_of_prime = 0

# nine consecutive 0 to 8
for num in range(n, n + 9):
sum_of_prime += largest_prime(num)

print(sum_of_prime)

main()
OUTPUT:
Enter a number: 15
92
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 35
Write a python function find_smallest_number() which accepts a number n and returns the
smallest number having n divisors.
Handle the possible errors in the code written inside the function.

Sample Input Expected Output


16 120
---------------------------------------------------------------------------------------------------------------'''
def find_smallest_number(num):
div_count = 0
n=0
while div_count != num:
n=n+1
div_count = 0
for i in range(1, n + 1):
if n % i == 0:
div_count = div_count + 1
return n

def main():
num=int(input("Enter the number: "))
print("The number of divisors :", num)
result = find_smallest_number(num)
print("The smallest number having", num, " divisors:", result)

main()
OUTPUT:
Enter the number: 45
The number of divisors : 45
The smallest number having 45 divisors: 3600

Enter the number: 32


The number of divisors : 32
The smallest number having 32 divisors: 840
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 36
Write a python function find_duplicates(), which accepts a list of numbers and returns
another list containing all the duplicate values in the input list. If there are no
duplicate values, it should return an empty list.

Sample Input Expected


Output
[12,54,68,759,24,15,12,68,987,758,25,69] [12, 68]
---------------------------------------------------------------------------------------------------------------'''
def find_duplicates(list_of_numbers):
dup_list = set()
for i in range(0, len(list_of_numbers)):
for j in range(i+1, len(list_of_numbers)):
if list_of_numbers[i] == list_of_numbers[j]:
dup_list.add(list_of_numbers[i])
return list(dup_list)

def main():
list_of_numbers = [1, 6, 6, 3, 7, 3, 4, 2, 4, 4]
list_of_duplicates = find_duplicates(list_of_numbers)
print(list_of_duplicates)

main()
OUTPUT:
[3, 4, 6]
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 37
Write a python function, nearest_palindrome() which accepts a number and returns the
nearest palindrome greater than the given number.
---------------------------------------------------------------------------------------------------------------'''
def nearest_palindrome(number):
if number == 0:
return
else:
flag = 0
while flag != 1:
temp_num = number
new_num = 0
rem = 0
while temp_num != 0:
rem = temp_num % 10
new_num = new_num * 10 + rem
temp_num = temp_num // 10

if new_num == number:
flag = 1
else:
number = number + 1

return new_num

def main():
number=int(input("Enter the number: "))
print(nearest_palindrome(number))

main()
OUTPUT:
Enter the number: 32
33

Enter the number: 50


55
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 38
Write a python function, encrypt_sentence() which accepts a message and encrypts it based
on rules given below and returns the encrypted message.

Words at odd position -> Reverse It


Words at even position -> Rearrange the characters so that all consonants appear
before the vowels and their order should not change

Note:
1. Assume that the sentence would begin with a word and there will be only a
single space between the words.
2. Perform case sensitive string operations wherever necessary.

Sample Input Expected Output


the sun rises in the east eht snu sesir ni eht stea
---------------------------------------------------------------------------------------------------------------'''
def encrypt_sentence(sentence):
sentence_list = sentence.split(' ')
print(sentence_list)

for i in range(1, len(sentence_list)+1):


if i % 2 == 0:
consonants = vowels = ''
for letter in sentence_list[i-1]:
if letter in ['a', 'e', 'i', 'o', 'u']:
vowels += letter
else:
consonants += letter
sentence_list[i-1] = consonants + vowels
else:
sentence_list[i-1] = sentence_list[i-1][::-1]
return sentence_list

def main():
sentence = "life is not easy".lower()
encrypted_sentence_list = encrypt_sentence(sentence)
for i in encrypted_sentence_list:
print(i, end=' ')

main()
OUTPUT:

['i', 'really', 'love', 'python']


i rllyea love onhtyp
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 39
Write a python function, find_correct() which accepts a dictionary and
returns a list as per the rules mentioned below.
The input dictionary will contain correct spelling of a word as key and the
spelling provided by a contestant as the value.
The function should identify the degree of correctness as mentioned below:
CORRECT, if it is an exact match
ALMOST CORRECT, if no more than 2 letters are wrong
WRONG, if more than 2 letters are wrong or if length (correct spelling versus
spelling given by contestant) mismatches.
and return a list containing the number of CORRECT answers, number of
ALMOST CORRECT answers and number of WRONG answers.
Assume that the words contain only uppercase letters and the maximum word
length is 10.
---------------------------------------------------------------------------------------------------------------'''
def find_correct(word_dict):
correct_count = 0
almost_count = 0
wrong_count = 0
for word, input_word in word_dict.items():
if len(word) == len(input_word):
flag = 0
for i in range(0, len(word)):
if word[i] != input_word[i]:
flag = flag + 1
if flag == 0:
correct_count = correct_count + 1
elif flag <= 2:
almost_count = almost_count + 1
else:
wrong_count = wrong_count + 1
else:
wrong_count = wrong_count + 1
return list((correct_count, almost_count, wrong_count))

word_dict = {"THIS": "THESE", "SUBJECT":


"SUJBECT","IS":"SI","PYTHO":"PYTHON"}
print(find_correct(word_dict))
OUTPUT:
[0, 2, 2]
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 40
In a fair coin we have an equal chance (50%) of either getting a ‘head’ or ‘tail’. That is if we
toss the coin a large number of times we would observe head approximately 50% of the time.
Write a program to implement a biased coin toss where the chance of getting a head is 70%
(and tail 30%). That is if we invoke the program 1000 times we should see the head randomly
approximately 700 times.
---------------------------------------------------------------------------------------------------------------'''
import random

def main():
head_count = tail_count = 0
for i in range(0, 1000):
if random.randint(1, 10) > 3:
head_count += 1
else:
tail_count += 1
print("Total number of times head occurs: ", head_count)
print("Total number of times tail occurs: ", tail_count)

main()
OUTPUT:

Total number of times head occurs: 571


Total number of times tail occurs: 103
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 41
Write python function, sms_encoding() which accepts a sentence and converts
it into an abbreviated sentence to be sent as SMS and returns the abbreviated
sentence.
Rules are as follows:
a. Spaces are to be retained as is
b. Each word should be encoded separately
 If a word has only vowels then retain the word as is
 If a word has a consonant (at least 1) then retain only those consonants

Note: Assume that the sentence would begin with a word and there will be
only a single space between the words.
Sample Input Expected Output
I love Python I lv Pythn
MSD says I love cricket and MSD sys I lv crckt nd tnns t
tennis too
I will not repeat mistakes I wll nt rpt mstks
---------------------------------------------------------------------------------------------------------------'''
def sms_encoding(sentence):
vowels = ['a', 'e', 'i', 'o', 'u']
for word in sentence.split(' '):
converted_word = ''
for letter in word:
if letter not in vowels:
converted_word += letter
if converted_word != '':
print(converted_word, end=' ')
else:
print(word, end=' ')

def main():
sentence = input('Enter sentence to be converted: ')
sentence=sentsce.lower()
sms_encoding(sentence)

main()
OUTPUT:
Enter sentence to be converted: I love Python
I lv Pythn
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 42
Create two functions: odd() and even()
The function even() returns a list of all the even numbers from sample_data
The function odd() returns a list of all the odd numbers from sample_data
Create a function sum_of_numbers() which will accept the sample data and/or
a function.
If a function is not passed, the sum_of_numbers() should return the sum of all
the numbers from sample_data
If a function is passed, the sum_of_numbers() should return the sum of
numbers returned from the function passed.
---------------------------------------------------------------------------------------------------------------'''
def sum_of_numbers(list_of_num, filter_func=None):
num_sum = 0
if filter_func is None:
for i in list_of_num:
num_sum = num_sum + i
print("Even Numbers:", even(list_of_num))
print("Odd Numbers:", odd(list_of_num))
return num_sum
else:
return filter_func(list_of_num)

def calulate_sum(data):
num_sum = 0
for i in data:
num_sum = num_sum + i
return num_sum

def even(data):
even_list = list()
for i in data:
if i % 2 == 0:
even_list.append(i)
return even_list

def odd(data):
odd_list = list()
for i in data:
if i % 2 != 0:
odd_list.append(i)
return odd_list
def even(data):
total = 0
for i in data:
if i % 2 == 0:
total += i
return total

def odd(data):
total = 0
for i in data:
if i % 2 != 0:
total += i
return total

def main():
sample_data = range(1, 11)
print("Total: ", sum_of_numbers(sample_data,None))
print("Even Total: ", sum_of_numbers(sample_data, even(sample_data)))
print("Odd Total: ", sum_of_numbers(sample_data, odd(sample_data)))

main()
OUTPUT:

Even Numbers: [6, 12, 18, 24, 30]


Odd Numbers: [3, 6, 9, 12, 15]
135
Even Total: 90
Odd Total: 45
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 43
Assume that a poem is given. Write the regular expressions for the following:
Print how many times the letter 'v' appears in the poem.
Remove all the newlines from the poem and print the poem in a single line.
If a word has 'ch' or 'co', replace it with 'Ch' or 'Co'.
If the pattern has characters 'ai' or 'hi', replace the next three characters with
*\*.
---------------------------------------------------------------------------------------------------------------'''
import re

def main():
poem = '''
If I can stop one heart from breaking,
I shall not live in vain;
If I can ease one life the aching,
Or cool one pain,
Or help one fainting robin
Unto his nest again,
I shall not live in vain.
'''

print(len(re.findall("v", poem)))
print(re.sub(r"\n", "", poem))
temp_poem = re.sub('ch', 'Ch', poem)
print(re.sub('co', 'Co', temp_poem))
print(re.sub(r'(ai|hi)(...)', r'\1*\*', poem))

main()
OUTPUT

4
If I can stop one heart from breaking, I shall not live in vain; If I can ease one life the
aching, Or cool one pain, Or help one fainting robin Unto his nest again, I shall not
live in vain.

If I can stop one heart from breaking,


I shall not live in vain;
If I can ease one life the aChing,
Or Cool one pain,
Or help one fainting robin
Unto his nest again,
I shall not live in vain.

If I can stop one heart from breaking,


I shall not live in vain;
If I can ease one life the achi*\*
Or cool one pain,
Or help one fai*\*ng robin
Unto hi*\*est again,
I shall not live in vain.
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 44
Write a python function, check_anagram() which accepts two strings and returns True, if
one string is an anagram of another string. Otherwise returns False.
The two strings are considered to be an anagram if they contain repeating characters but none
of the characters repeat at the same position. The length of the strings should be the same.

Sample Input Expected Output


eat, tea True
backward,drawback False
(Reason: character 'a' repeats at position
6, not an anagram)
Reductions,discounter True
About, table False
---------------------------------------------------------------------------------------------------------------'''
def check_anagram(data1, data2):
data1 = data1.lower()
data2 = data2.lower()
if len(data1) != len(data2):
return False
else:
for ch in data1:
if ch not in data2:
return False
for ch in data2:
if ch not in data1:
return False
for i in range(0, len(data1)):
if data1[i] == data2[i]:
return False
return True

def main():
str1=input("Enter the 1st string: ")
str2=input("Enter 2nd string: ")
print(check_anagram(str1, str2))

main()
OUTPUT:

Enter the 1st string: Reductions


Enter 2nd string: discounter
True

Enter the 1st string: coffee


Enter 2nd string: tea
False
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 45
Write a python program to help an airport manager to generate few statistics
based on the ticket details available for a day.
---------------------------------------------------------------------------------------------------------------'''
import re

# Global variable
ticket_list = ["AI567:MUM:LON:014", "AI077:MUM:LON:056",
"BA896:MUM:LON:067", "SI267:MUM:SIN:145",
"AI077:MUM:CAN:060", "SI267:BLR:MUM:148",
"AI567:CHE:SIN:015", "AI077:MUM:SIN:050",
"AI077:MUM:LON:051", "SI267:MUM:SIN:146"]

def find_passengers_flight(airline_name="AI"):
count = 0
for item in ticket_list:
data = item.split(":")
if re.search('^'+airline_name, data[0]):
count += 1
return count

def find_passengers_destination(destination):
count = 0
for item in ticket_list:
data = item.split(":")
if destination == data[2]:
count += 1
return count

def find_passengers_per_flight():
flights = list()
for i in ticket_list:
flights.append(i.split(':')[0])
unique_flights = set(flights)
result_list = list()

for i in unique_flights:
count = 0
for j in flights:
if i == j:
count += 1
result_list.append(i + ':' + str(count))
return result_list

def sort_passenger_list():
passengers_per_flight = find_passengers_per_flight()
for i in range(0, len(passengers_per_flight) - 1):
for j in range(i+1, len(passengers_per_flight)):
if passengers_per_flight[i].split(':')[1] > passengers_per_flight[j].split(':')[1]:
passengers_per_flight[i], passengers_per_flight[j] = passengers_per_flight[j],
passengers_per_flight[i]

return passengers_per_flight

def main():
# Provide different values for airline_name and destination and test your program.
airline_name = input("Enter Flight Name: ").upper()
print("Number of passengers flying :", find_passengers_flight(airline_name))

destination = input("Enter destination: ".upper())


print("Number of passengers flying to %s: " % destination,
find_passengers_destination("MUM".upper()))

print("Passengers sorted based on count: ", sort_passenger_list())

main()
OUTPUT

Enter Flight Name: SI


Number of passengers flying : 3
ENTER DESTINATION: MUMBAI
Number of passengers flying to MUMBAI: 1
Passengers sorted based on count: ['SI267:0', 'SI267:0', 'SI267:0', 'AI077:0', 'BA896:0',
'BA896:0', 'AI567:1', 'AI567:1', 'AI567:1', 'AI567:1', 'AI567:1', 'SI267:1', 'AI077:1',
'AI077:1', 'AI077:1', 'SI267:1', 'AI567:1', 'BA896:1', 'BA896:1', 'BA896:1', 'BA896:1',
'BA896:1', 'BA896:1', 'BA896:1', 'BA896:1', 'AI077:2', 'AI567:2', 'AI567:2', 'AI567:2',
'AI567:2', 'SI267:2', 'SI267:2', 'SI267:2', 'SI267:2', 'AI077:2', 'AI077:2', 'SI267:3', 'AI077:3',
'AI077:4', 'AI077:4']
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 46
Write a python program that accepts a text and displays a string which
contains the word with the largest frequency in the text and the frequency
itself separated by a space.
Rules:
The word should have the largest frequency.
In case multiple words have the same frequency, then choose the word that has
the maximum length.
Assumptions:
The text has no special characters other than space.
The text would begin with a word and there will be only a single space
between the words.
Perform case insensitive string comparisons wherever necessary.
Sample Input Expected Output
"Work like you do not need money love like you have never been hurt like 3
and dance like no one is watching"
"Courage is not the absence of fear but rather the judgement that fear 2
something else is more important than fear"
---------------------------------------------------------------------------------------------------------------'''
def max_frequency_word_counter(data):
word = ""
frequency = 0
data_word = data.split(" ")
distinct_data_words = set()
dict_word_freq = dict()

for words in data_word:


distinct_data_words.add(words)

for words in distinct_data_words:


word = words
frequency = 0
for ch in data_word:
if word == ch:
frequency = frequency + 1
dict_word_freq[word] = frequency

max_freq = 0
for i in dict_word_freq:
if dict_word_freq[i] > max_freq:
max_freq = dict_word_freq[i]
for word, frequency in dict_word_freq.items():
if frequency == max_freq:
print(word, frequency)

data = " Courage is not the absence of fear but rather the judgement that something else is
more important than fear "
max_frequency_word_counter(data.lower())
OUTPUT:

fear 2
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 47
Write a python program to find and display the number of circular primes less than the given
limit.
---------------------------------------------------------------------------------------------------------------'''
def prime(number):
return number > 1 and all(number % i != 0 for i in range(2, number))

def rotations(num):
rotated = []

m = str(num)

for _ in m:
rotated.append(int(m))
m = m[1:] + m[0]

return rotated

def prime_count(limit):
counter = 0

for number in range(1, limit + 1):

if all(prime(rotation) for rotation in rotations(number)):


counter += 1

return counter

print(prime_count(480))
OUTPUT:
20
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 48
Write a function, validate_credit_card_number(), which accepts a 16 digit credit card number
and returns true if it is valid as per Luhn’s algorithm or false, if it is invalid. Also write the
pytest test cases to test the program.
---------------------------------------------------------------------------------------------------------------'''
def validate_credit_card_number(card_number):
odd_pos_num = 0
even_pos_num = 0
temp_num = card_number
flag = 0
while temp_num != 0:
flag = flag + 1
rem = temp_num % 10
temp_num = temp_num // 10
if flag % 2 != 0:
even_pos_num = even_pos_num * 10 + rem
else:
odd_pos_num = odd_pos_num * 10 + rem
temp_num = odd_pos_num
odd_sum = 0
while temp_num != 0:
rem = temp_num % 10
temp_num = temp_num // 10
rem = rem * 2
if rem > 9:
rem = (rem % 10) +(rem // 10)
odd_sum = odd_sum + rem
temp_num = even_pos_num
while temp_num != 0:
rem = temp_num % 10
temp_num = temp_num // 10
odd_sum = odd_sum + rem
if odd_sum % 10 == 0:
return True
else:
return False

#card_number = 1456734512345698 #4539869650133101 #1456734512345698 #


#5239512608615007 #3245627890761450

card_number = int(input("Enter the credit card number"))


result = validate_credit_card_number(card_number)
if result:
print("credit card number is valid")
else:
print("credit card number is invalid")
OUTPUT :

Enter the credit card number5239512608615007


credit card number is valid

Enter the credit card number3245627890761450


credit card number is invalid
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 49
Write a python function to check whether the given number is a perfect number or not. The
function should returns true if the number is a perfect number, else it should returns false
---------------------------------------------------------------------------------------------------------------'''
def check_perfect_number(number):
divisors_sum = 0
if number == 0:
return False
for i in range(1, number):
if number % i == 0:
divisors_sum = divisors_sum + i
if divisors_sum == number:
return True
else:
return False

def check_perfectno_from_list(no_list):
perfect_num_list = list()
for num in no_list:
if check_perfect_number(num):
perfect_num_list.append(num)
return perfect_num_list

perfectno_list = check_perfectno_from_list([3, 13, 6, 23, 41, 29])


print(perfectno_list)
OUTPUT:
[6]
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 50
Write a python function, remove_duplicates() which accepts a string and removes all
duplicate characters from the given string and return it.
---------------------------------------------------------------------------------------------------------------'''
def remove_duplicates(value):
clean_value = ""
for ch in value:
if ch not in clean_value:
clean_value = clean_value + ch
return clean_value

print(remove_duplicates(""227700448833asd&7**SS""))
OUTPUT:
270483asd&*S
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 51
Write a python program to validate the details provided by a user as part of
registering to a web application.
Write a function validate_name(name) to validate the user name
Name should not be empty, name should not exceed 15 characters
Name should contain only alphabets

Write a function validate_phone_no(phoneno) to validate the phone number


Phone number should have 10 digits
Phone number should not have any characters or special characters
All the digits of the phone number should not be same.
Example: 9999999999 is not a valid phone number

Write a function validate_email_id(email_id) to validate email Id


It should contain one '@' character and '.com'
'.com' should be present at the end of the email id.
Domain name should be either 'gmail', 'yahoo' or 'hotmail'

All the functions should return true if the corresponding value is valid.
Otherwise, it should return false.
Write a function validate_all(name,phone_no,email_id) which should invoke
appropriate functions to validate the arguments passed to it and display
appropriate message. Refer the comments provided in the code.
---------------------------------------------------------------------------------------------------------------'''
def validate_name(name):
if name == "":
return False
if len(name) > 15:
return False
for ch in name:
if not ch.isalpha():
return False
return True

def validate_phone_no(phno):
phone_len = 0
num_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
for ch in phno:
unique_count = 0
for i in phno:
if i == ch:
unique_count = unique_count + 1
if unique_count == 10:
return False
phone_len = phone_len + 1
if ch not in num_list:
return False
if phone_len >= 11 or phone_len <= 9:
return False
return True

def validate_email_id(email_id):
at_count = 0
com_count = 0
email_len = len(email_id)
last_com = '.com'
domain_list = ['yahoo', 'gmail', 'hotmail']
for i in range(0, email_len - 3):
if last_com == email_id[i:i+4]:
com_count = com_count + 1
for i in range(0, len(email_id)):
if email_id[i] == '@':
at_flag = i
at_count = at_count + 1
if email_id[i] == '.':
dot_flag = i
if at_count >= 2 or com_count >= 2:
return False
if email_id[at_flag + 1:dot_flag] not in domain_list:
return False
return True

def validate_all(name, phone_no, email_id):


if not validate_name(name):
print("Invalid Name")
elif not validate_phone_no(phone_no):
print("Invalid phone number")
elif not validate_email_id(email_id):
print("Invalid email id")
else:
print("All the details are valid")

validate_all("Sevil", "9876543210", "[email protected]")


validate_all("Rajat","9823848272","[email protected]")
OUTPUT:

Invalid email id

All the details are valid


'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 52
Implement the Customer class based on the identified class structure and
details given below:
1. Consider all instance variables and methods to be public
2. Assume that bill_amount is initialized with total bill amount of the customer
3. Customer is eligible for 5% discount on the bill amount
4. purchases(): Compute discounted bill amount and pay bill
5. pays_bill(amount): Display, <customer_name> pays bill amount of Rs. <amount>
Represent few customers, invoke purchases() method and display the details.
---------------------------------------------------------------------------------------------------------------'''
class Customer:
def __init__(self, amount, name):
self.bill_amount = amount
self.customer_name = name

def purchases(self):
self.bill_amount = self.bill_amount - (self.bill_amount * 0.05)
self.pays_bill(self.bill_amount)

def pays_bill(self, amount):


print(self.customer_name, " pays bill amount of Rs.", self.bill_amount)

def main():
cust1 = Customer(35000, 'Sana')
cust1.purchases()

main()
OUTPUT:

Sana pays bill amount of Rs. 33250.0


'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 53
Write a Python program to implement the class chosen with its attributes and methods.
Note:
 Consider all instance variables to be private and methods to be public
 Include getter and setter methods for all instance variables
 Display appropriate error message, if the vehicle type is invalid
 Perform case sensitive string comparison
 Represent few objects of the class, initialize instance variables using setter methods,
invoke appropriate methods and test your program.
---------------------------------------------------------------------------------------------------------------'''
class Vehicle:
def __init__(self):
self.vehicle_id = 0
self.vehicle_type = ''
self.vehicle_cost = 0
self.premium_amount = 0

def set_vehicle_id(self, v_id):


self.vehicle_id = v_id

def get_vehicle_id(self):
return self.vehicle_id

def set_vehicle_type(self, v_type):


self.vehicle_type = v_type

def get_vehicle_type(self):
return self.vehicle_type

def set_vehicle_cost(self, v_cost):


self.vehicle_cost = v_cost

def get_vehicle_cost(self):
return self.vehicle_cost

def calculate_premium(self):
if self.vehicle_type == "Two Wheeler":
self.premium_amount = self.vehicle_cost * 0.02
else:
self.premium_amount = self.vehicle_cost * 0.06

def get_premium_amount(self):
return self.premium_amount
def display_vehicle_details(self):
print("Vehicle ID : ", self.get_vehicle_id())
print("Vehicle Type : ", self.get_vehicle_type())
print("Vehicle Cost : ", self.get_vehicle_cost())
print("Vehicle Premium Amount : ", self.get_premium_amount())

def main():
veh_obj = Vehicle()
v_type = ["Two Wheeler", "Four Wheeler"]
veh_obj.set_vehicle_id(int(input("Enter vehicle id : ")))
veh_type = input("Enter vehicle type : ")
if veh_type not in v_type:
print("Error Invalid vehicle Type!!!")
exit()
else:
veh_obj.set_vehicle_type(veh_type)
veh_obj.set_vehicle_cost(float(input("Enter vehicle Cost : ")))
veh_obj.calculate_premium()
veh_obj.display_vehicle_details()

main()
OUTPUT:

Enter vehicle id : 2001


Enter vehicle type : Two Wheeler
Enter vehicle Cost : 35000
Vehicle ID : 2001
Vehicle Type : Two Wheeler
Vehicle Cost : 35000.0
Vehicle Premium Amount : 700.0
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 54
Write a Python program to implement the class chosen with its attributes and methods.
Note:
 Consider all instance variables to be private and methods to be public
 An instructor may have multiple technology skills, so consider instance variable,
technology_skill to be a list
 check_eligibility(): Return true if eligibility criteria is satisfied by the instructor. Else,
return false
 allocate_course(technology): Return true if the course which requires the given
technology can be allocated to the instructor. Else, return false
 Perform case sensitive string comparison
 Represent few objects of the class, initialize instance variables using setter methods,
invoke appropriate methods and test your program.
---------------------------------------------------------------------------------------------------------------'''
class Instructor:
def __init__(self, name, avg_feedback, technology_skill, experience):
self.__inst_name = name
self.__inst_avg_feedback = avg_feedback
self.__inst_tech_skill = technology_skill
self.__inst_exp = experience

def check_eligibility(self):
if self.__inst_exp > 3:
if self.__inst_avg_feedback >= 4.5:
return True
else:
if self.__inst_avg_feedback >= 4:
return True
return False

def allocate_course(self, technology):


if self.check_eligibility():
if technology in self.__inst_tech_skill:
return True
else:
return False
return False

def main():
name = input("Enter Instructor Name: ")
feedback = float(input("Enter average feedback: "))
exp = int(input("Enter experience "))
tech_skill = list()
n = int(input("Enter no. technology skills known: "))
print("Enter Skills")
for i in range(0, n):
tech_skill.append(input("Skill Name: "))
inst_obj = Instructor(name, feedback, tech_skill, exp)
tech = input("Enter the course to allocate to him: ")
if inst_obj.allocate_course(tech):
print("The instructor is eligible for the course")
else:
print("The instructor is not eligible for the course")

main()
OUTPUT:

Enter Instructor Name: Rajat


Enter average feedback: 5
Enter experience 8
Enter no. technology skills known: 3
Enter Skills
Skill Name: C
Skill Name: Pythomn
Skill Name: Java
Enter the course to allocate to him: C
The instructor is not eligible for the course

Enter Instructor Name: Seville

Enter average feedback: 9

Enter experience 6

Enter no. technology skills known: 2

Enter Skills

Skill Name: SQL

Skill Name: Ruby

Enter the course to allocate to him: Ruby

The instructor is eligible for the course


'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 55
A university wants to automate their admission process. Students are admitted based on
marks scored in a qualifying exam.
A student is identified by student id, age and marks in qualifying exam. Data are valid, if:
 Age is greater than 20
 Marks is between 0 and 100 (both inclusive)
A student qualifies for admission, if
 Age and marks are valid and
 Marks is 65 or more
Write a python program to represent the students seeking admission in the university.
---------------------------------------------------------------------------------------------------------------'''
class Student:
def __init__(self):
self.__student_id = 0
self.__marks = 0
self.__age = 0

def validate_marks(self):
if self.__marks>= 0 and self.__marks<= 100:
return True
else:
return False

def validate_age(self):
if self.__age> 20:
return True
else:
return False

def check_qualification(self):
if self.validate_age() and self.validate_marks():
if self.__marks>= 65:
return True
return False
else:
return False:

def set_student_id(self):
global student_id_counter
self.__student_id = student_id_counter
student_id_counter = student_id_counter + 1

def get_student_id(self):
return self.__student_id
def set_marks(self, marks):
self.__marks = marks

def get_marks(self):
return self.__marks

def set_age(self, age):


self.__age = age

def get_age(self):
return self.__age

def main():
s1 = Student()
s1.set_student_id(int(input(“Enter Student ID)))
print(s1.get_student_id())
input_age=int(input("enter age"))
s1.set_age(input_age)
print(s1.get_age())
input_marks =int(input("enter marks"))
s1.set_marks(input_marks)
print(s1.get_marks())
s1.check_qualification()
print(s1.check_qualification())

main()
OUTPUT:

Enter Student ID: 101


enter age21
21
enter marks70
70
True

Enter Student ID: 102


enter age26
26
enter marks110
110
False
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 56
A telecom company wants to generate reports on the call details of the customers.
The data of each call detail include the phone number which made the call, phone number
which was called, duration of the call and the type of call. Data of such calls are provided as a
list of comma separated string.

Problem Statement:
 Complete the CallDetail class with necessary attributes
 Complete the logic inside the parse_customer() method of the Util Class. This method
should accept a list of string of the call details and convert it into a list of CallDetail
object and assign this list as a value to the attribute of the Util class.
---------------------------------------------------------------------------------------------------------------'''
class CallDetail:
def __init__(self, phoneno, called_no, duration, call_type):
self.__phoneno = phoneno
self.__called_no = called_no
self.__duration = duration
self.__call_type = call_type

def display_user(self):
print(self.__phoneno, "\t", self.__called_no, "\t", self.__duration, "\t", self.__call_type)

class Util:
def __init__(self):
self.list_of_call_objects = None

def parse_customer(self, list_of_call_string):


self.list_of_call_objects = list()
print("Called From\t Called To\t Duration\tCall Type")
for call in list_of_call_string:
call = call.split(',')
call_obj = CallDetail(call[0], call[1], call[2], call[3])
self.list_of_call_objects.append(call_obj)
call_obj.display_user()

return self.list_of_call_objects

call = '9876543210,9876501234,20,STD'
call2 = '9988776655,9844332211,04,Local'

call_list = [call, call2]


util_obj = Util()
util_obj.parse_customer(call_list)
OUTPUT:
Called From Called To Duration Call Type
9876543210 9876501234 20 STD
9988776655 9844332211 04 Local
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 57
Royal Orchid is a florist. They want to be alerted when stock of a flower goes below a
particular level.
The flowers are identified using name, price per kg and stock available (in kgs).
Write a Python program to implement the above requirement.
---------------------------------------------------------------------------------------------------------------'''
flowers = ['Orchid', 'Rose', 'Jasmine']
levels = [15, 25, 40]
class Flower:
def __init__(self):
self.__flower_name = None
self.__price_per_kg = None
self.__stock_available = None

def validate_flower(self):
if self.__flower_name in flowers:
return True
else:
return False

def validate_stock(self, required_quantity):


if self.__stock_available>= required_quantity:
return True
else:
return False

def sell_flower(self, required_quantity):


if self.validate_flower() and self.validate_stock(required_quantity):
self.__stock_available -= required_quantity

def check_level(self):
if self.validate_flower():
flower_level = levels[flowers.index(self.__flower_name)]
if self.__stock_available<flower_level:
return True
return False

def get_flower_name(self):
return self.__flower_name
def get_price_per_kg(self):
return self.__price_per_kg

def get_stock_available(self):
return self.__stock_available

def set_flower_name(self, flower_name):


self.__flower_name = flower_name.title()

def set_price_per_kg(self, price_per_kg):


self.__price_per_kg = price_per_kg

def set_stock_available(self, stock_available):


self.__stock_available = stock_available
def main():
flower = Flower()
input_flower = input("enter the flower name ")
flower.set_flower_name(input_flower)
input_price = int(input("enter the price "))
flower.set_price_per_kg(input_price)
input_stock_available = int(input("enter the available stock"))
flower.set_stock_available(input_stock_available)
print(flower.check_level())

main()
OUTPUT:
enter the flower name: Orchid
enter the price: 100
enter the available stock: 20
True

enter the flower name: Rose


enter the price: 120
enter the available stock: 2
False
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 58
Write a Python program to implement the class diagram given below.

---------------------------------------------------------------------------------------------------------------'''
class Bill:
def __init__(self, bill_id, patient_name):
self.__bill_id = bill_id
self.__patient_name = patient_name
self.__bill_amount = None

def calculate_bill_amount(self, consultation_fees, quantity_list, price_list):


self.__bill_amount = consultation_fees
for item in range(0, len(price_list)):
self.__bill_amount += quantity_list[item] * price_list[item]

def get_bill_id(self):
return self.__bill_id

def get_patient_name(self):
return self.__patient_name

def get_bill_amount(self):
return self.__bill_amount
def main():
bill = Bill(123,"Karen")
consultation_fee = 100
quantity_list = [4,2,1]
price_list = [200,400,600]
bill.calculate_bill_amount(consultation_fee, quantity_list, price_list)
a = bill.get_bill_id()
b = bill.get_patient_name()
print("Patient Id =" ,a)
print("Patient Name =", b)
c = bill.get_bill_amount()
print("Patient Total Bill Amount =", c)

main()
OUTPUT:
Patient Id = 123
Patient Name = Karen
Patient Total Bill Amount = 2300
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 59
Write a python program to find out if a given classroom is present in the left wing of a
university building. Implement the class, Classroom given below.

---------------------------------------------------------------------------------------------------------------'''
class Classroom:
classroom_list = None

@staticmethod
def search_classroom(class_room):
for room in Classroom.classroom_list:
print(class_room)
if class_room.lower() == room.lower():
return "The given class room is in left wing of the university building"
return -1

def main():
class_room = input("Enter the class room number:")
Classroom.classroom_list = ["BCA","BSc","BCom"]
class_found = Classroom.search_classroom(class_room)

if(class_found == -1):
print("The given class room is not in left wing of the university building")
else:
print(class_found)

main()
OUTPUT:
Enter the class room number:BSc
BSc
The given class room is not in left wing of the university building
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 60
Write a Python program to implement the class chosen with its attributes and methods.
Represent few parrots, display their names, color and unique number.
---------------------------------------------------------------------------------------------------------------'''
class Parrot:
__counter = 201

def __init__(self, name, color):


self.__name = name
self.__color = color
Parrot.__counter += 1
self.__unique_number = Parrot.__counter

def get_name(self):
return self.__name

def get_color(self):
return self.__color

def get_unique_number(self):
return self.__unique_number

def main():

number = int(input("Enter the number of Parrots:"))


for i in range(0,number):
name = input("Enter Parrot name:")
color = input("Enter the parrot color:")
p = Parrot(name,color)
name1 = p.get_name()
color1 = p.get_color()
counter = p.get_unique_number()
print("Parrot Details")
print("Name of parrot= ",name1)
print("Color of parrot= ",color1)
print("Unique Number of this parrot is =",counter)

main()
OUTPUT:
Enter the number of Parrots:2
Enter Parrot name:raju
Enter the parrot color:green
Parrot Details
Name of parrot= raju
Color of parrot= green
Unique Number of this parrot is = 202
Enter Parrot name:alien
Enter the parrot color:red
Parrot Details
Name of parrot= alien
Color of parrot= red
Unique Number of this parrot is = 203
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 61
Freight Pvt. Ltd, a cargo company, forwards cargos/freights between its customers.30 min
Freight charges are applied based on weight and distance of the shipment.
Write a python program to implement the class diagram given below.
---------------------------------------------------------------------------------------------------------------'''
class Freight:
counter = 132

def __init__(self, recipient_customer, from_customer, weight, distance):

self.__recipient_customer = recipient_customer
self.__from_customer = from_customer
self.__weight = weight
self.__distance = distance
self.__freight_charge = None
self.__freight_id = None

def validate_weight(self):
if self.__weight % 5 == 0:
return True
else:
return False

def validate_distance(self):
if 500 <= self.__distance <= 5000:
return True
else:
return False

def forward_cargo(self):
Freight.counter += 2
self.__freight_id = Freight.counter
self.__freight_charge = (150 * self.__weight) + (60 * self.__distance)
def get_recipient_customer(self):
return self.__recipient_customer

def get_from_customer(self):
return self.__from_customer

def get_weight(self):
return self.__weight

def get_distance(self):
return self.__distance

def get_freight_charge(self):
return self.__freight_charge

def get_freight_id(self):
return self.__freight_id

class Customer:
def __init__(self, customer_id, customer_name, address):
self.__customer_id = customer_id
self.__customer_name = customer_name
self.__address = address

def validate_customer_id(self):

if (200000 > self.__customer_id >= 100000):


return True
else:
return False
def get_customer_id(self):
return self.__customer_id

def get_customer_name(self):
return self.__customer_name

def get_address(self):
return self.__address

def main():
c = Customer(500000,"Suraj","Kerla")

if(c.validate_customer_id()):
print("Customer ID",c.get_customer_id())
print("Customer Name",c.get_customer_name())
print("Customer Address",c.get_address())

f = Freight("Kim",c.get_customer_name(),100,10000)
if (f.validate_weight()):
print("There is no problem for",f.get_weight(),"kg weight")

if (f.validate_distance()):
print("This distance is valid for shippment")
f.forward_cargo()
print("Freight ID ",f.get_freight_id())
print("Goods Sending Customer ", f.get_from_customer())
print("Goods Receiving Customer ",f.get_recipient_customer())
print("Weight of the good ",f.get_weight())
print("Distance ", f.get_distance())
print("Charge for Freight ",f.get_freight_charge())

main()
OUTPUT:
There is no problem for 100 kg weight
Freight ID 134
Goods Sending Customer Suraj
Goods Receiving Customer Kim
Weight of the good 100
Distance 10000
Charge for Freight 615000
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 62

Write a python program to implement the class diagram given below.


---------------------------------------------------------------------------------------------------------------'''
class Customer:
def __init__(self, customer_name):
self.__customer_name = customer_name
self.__payment_status = None

def get_customer_name(self):
return self.__customer_name

def get_payment_status(self):
return self.__payment_status

def pays_bill(self):
self.__payment_status = "Paid"

class Bill:
counter = 1000

def __init__(self):
self.__bill_id = None
self.__bill_amount = None

def get_bill_id(self):
return self.__bill_id
def get_bill_amount(self):
return self.__bill_amount

def generate_bill_amount(self, item_quantity, items):


Bill.counter += 1

self.__bill_amount = 0
self.__bill_id = 'B' + str(Bill.counter)

tmp_dict = item_quantity
a = {}

for item in tmp_dict:


a[item.lower()] = tmp_dict[item]

for prod, quan in a.items():


for item in items:
if item.get_item_id().lower() == prod:
self.__bill_amount += quan * item.get_price_per_quantity()
break

class Item:
def __init__(self, item_id, description, price_per_quantity):
self.__item_id = item_id
self.__description = description
self.__price_per_quantity = price_per_quantity

def get_item_id(self):
return self.__item_id

def get_description(self):
return self.__description
def get_price_per_quantity(self):
return self.__price_per_quantity

def main():

dictnry = {'item1': 4, 'item2': 3}

one = Item('item1', 'Pen', 100)


two = Item('item2', 'Pencil', 120)
customer = Customer("karen")

i = [one,two]
b1 = Bill()
b1.generate_bill_amount(dictnry, i)
print("Details")
print("Customer Name",customer.get_customer_name())
print("Item ID ",one.get_item_id())
print("Item Description ",one.get_description())
print("Item Price Per Quantity ",one.get_price_per_quantity())
print("Item ID ", two.get_item_id())
print("Item Description ", two.get_description())
print("Item Price Per Quantity ", two.get_price_per_quantity())

print("Bill Id ",b1.get_bill_id())
print("Bill amount ",b1.get_bill_amount())
print("Information about payment ",customer.pays_bill())

main()
OUTPUT:
Details
Customer Name Karen
Item ID item1
Item Description Pen
Item Price Per Quantity 200
Item ID item2
Item Description Pencil
Item Price Per Quantity 120
Bill Id B1001
Bill amount 760
Information about payment Paid
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 63
Write a Python program to generate tickets for online bus booking, based on the class
diagram given below.

---------------------------------------------------------------------------------------------------------------'''
class Ticket:
counter = 0

def __init__(self, passenger_name, source, destination):


self.__passenger_name = passenger_name
self.__ticket_id = None
self.__source = source
self.__destination = destination

def validate_source_destination(self):
dest = ['goa', 'thane', 'delhi', 'kerla']
if self.__source.lower() == 'mangalore' and self.__destination.lower() in dest:
return True
return False

def generate_ticket(self):
Ticket.counter += 1
if self.validate_source_destination():
if Ticket.counter < 10:
self.__ticket_id = self.__source[0] + self.__destination[0] + '0' + str(Ticket.counter)
else:
self.__ticket_id = self.__source[0] + self.__destination[0] + str(Ticket.counter)

def get_ticket_id(self):
return self.__ticket_id

def get_passenger_name(self):
return self.__passenger_name

def get_source(self):
return self.__source

def get_destination(self):
return self.__destination

def main():
tkt = Ticket("Rajat","Mangalore","Goa")
if tkt.validate_source_destination():
print("Source and destination selected is valid")

tkt.generate_ticket()
print("Ticket ID ",tkt.get_ticket_id())
print("Passenger Name ",tkt.get_passenger_name())
print("Source",tkt.get_source())
print("Destination",tkt.get_destination())

main()
OUTPUT:
Source and destination selected is valid

Ticket ID MK01

Passenger Name Rajat

Source Mangalore

Destination Goa
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 64

"Infinity" IT solution wants to automate their recruitment process. They have decided to
accept 5 applications for each of the three job bands ("A", "B" and "C") in the company.
Write a Python program to implement the class diagram given below.

---------------------------------------------------------------------------------------------------------------'''
class Applicant:
__application_dict = {'A': 0, 'B': 0, 'C': 0}
__applicant_id_count = 1000

def __init__(self, applicant_name):


self.__applicant_id = None
self.__applicant_name = applicant_name
self.__job_band = None

def generate_applicant_id(self):
Applicant.__applicant_id_count += 1
self.__applicant_id = Applicant.__applicant_id_count

def apply_for_job(self, job_band):


appli_list = Applicant
if Applicant.get_application_dict()[job_band] >= 5:
return -1
else:
Applicant.get_application_dict()[job_band] += 1
self.generate_applicant_id()
self.__job_band = job_band

@staticmethod
def get_application_dict():
return Applicant.__application_dict

def get_applicant_id(self):
return self.__applicant_id

def get_applicant_name(self):
return self.__applicant_name

def get_job_band(self):
return self.__job_band

def main():
n = int(input("Enter no. of applicants: "))
for i in range(0, n):
print("Applicant ", i + 1)
applicant_obj = Applicant(input("Enter Applicant Name : "))
if applicant_obj.apply_for_job(input("Enter Job Band(A/B/C) : ")) == -1:
print("Cant Apply for the band")
else:
print("Applicant ID : ", applicant_obj.get_applicant_id())
print("Name : ", applicant_obj.get_applicant_name())
print("Applied Job Band : ", applicant_obj.get_job_band())

main()
OUTPUT:

Enter no. of applicants: 5


Applicant 1
Enter Applicant Name : Rashid
Enter Job Band(A/B/C) : A
Applicant ID : 101
Name : Sonal
Applied Job Band : A
Applicant 2
Enter Applicant Name : Suresh
Enter Job Band(A/B/C) : A
Applicant ID : 102
Name : Suresh
Applied Job Band : A
Applicant 3
Enter Applicant Name : Kim
Enter Job Band(A/B/C) : A
Cant Apply for the band
Applicant 4
Enter Applicant Name : Shiva
Enter Job Band(A/B/C) : B
Applicant ID : 103
Name : Shiva
Applied Job Band : B
Applicant 5
Enter Applicant Name : Harry
Enter Job Band(A/B/C) : B
Applicant ID : 104
Name : Harry
Applied Job Band : B
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 65

Care hospital management wants to calculate the charge of lab tests done by its patients.Write
a python program to implement the class diagram given below

---------------------------------------------------------------------------------------------------------------'''
class Patient:
def __init__(self, patient_id, patient_name, list_of_lab_test_ids):
self.__patient_id = patient_id
self.__patient_name = patient_name
self.__list_of_lab_test_ids = list_of_lab_test_ids
self.__lab_test_charge = None

def get_patient_id(self):
return self.__patient_id

def get_patient_name(self):
return self.__patient_name

def get_list_of_lab_test_ids(self):
return self.__list_of_lab_test_ids

def get_lab_test_charge(self):
return self.__lab_test_charge

def calculate_lab_test_charge(self):
self.__lab_test_charge = 0
for test in self.__list_of_lab_test_ids: # looping for no. of tests
price = LabTestRepository.get_test_charge(test) # assigning cost as Price
if price == -1: # if get_test_charge in LabTestRepositry is invalid then price is 0
price = 0
self.__lab_test_charge += price

class LabTestRepository:
__list_of_hospital_lab_test_ids = ["I111", "I112", "I113", "I114"]
__list_of_lab_test_charge = [123, 1000, 799, 8000.50]

@staticmethod
def get_test_charge(lab_test_id):
if lab_test_id not in LabTestRepository.__list_of_hospital_lab_test_ids:
return -1
else:
index = LabTestRepository.__list_of_hospital_lab_test_ids.index(lab_test_id)
return LabTestRepository.__list_of_lab_test_charge[index]
pass
# Remove pass and write the logic here.

lab_test_list1 = ["I111", "I113", "I114", 'I115']


patient1 = Patient(101, "Clint", lab_test_list1)
patient1.calculate_lab_test_charge()
print("Patient id:", patient1.get_patient_id(), "\nPatient name:", patient1.get_patient_name(),
"\nPatient's test ids:",
patient1.get_list_of_lab_test_ids(), "\nTotal lab test charge:", patient1.get_lab_test_charge())
OUTPUT:
Patient id: 101
Patient name: Clint
Patient's test ids: ['I111', 'I113', 'I114', 'I115']
Total lab test charge: 8922.5
'''--------------------------------------------------------------------------------------------------------------
Register Number – 191805
Date – 04/12/2019
Program no – 66

"FairyLand Multiplex" wants to automate ticket booking and seat allocation process.
Write a python program to implement the class diagram given below.

---------------------------------------------------------------------------------------------------------------'''
class Multiplex:
__list_movie_name = ["movie1", "movie2"]
__list_total_tickets = [90, 80]
__list_last_seat_number = ["M-10", None]
__list_ticket_price = [120, 100]

def __init__(self):
self.__seat_numbers = None
self.__total_price = None

def calculate_ticket_price(self, movie_index, number_of_tickets):


self.__total_price = Multiplex.__list_ticket_price[movie_index] * number_of_tickets

def check_seat_availability(self, movie_index, number_of_tickets):


if (Multiplex.__list_total_tickets[movie_index] < number_of_tickets):
return False
else:
return True
def book_ticket(self, movie_name, number_of_tickets):
if movie_name.lower() not in Multiplex.__list_movie_name:
return 0
elif Multiplex.__list_total_tickets[Multiplex.__list_movie_name.index(movie_name)] <
number_of_tickets:
return -1
else:
movie_indx = Multiplex.__list_movie_name.index(movie_name)
self.__seat_numbers = self.generate_seat_number(movie_indx, number_of_tickets)
self.calculate_ticket_price(movie_indx, number_of_tickets)

'''Write the logic to book the given number of tickets for the specified movie.'''

def generate_seat_number(self, movie_index, number_of_tickets):

prefix, tkt_list, number_of_tickets = '', [], int(number_of_tickets)

if movie_index == 0:
if Multiplex.__list_last_seat_number[0] is None:
lst_tkt = 0

else:
lst_tkt = int(Multiplex.__list_last_seat_number[0].split('-')[-1])
prefix = "M1"

for i in range(lst_tkt + 1, lst_tkt + number_of_tickets + 1):


tkt_list.append(prefix + '-' + str(i))
Multiplex.__list_last_seat_number[0] = tkt_list[-1]
Multiplex.__list_total_tickets[0] -= number_of_tickets

else:
if Multiplex.__list_last_seat_number[1] is None:
lst_tkt = 0

else:
lst_tkt = int(Multiplex.__list_last_seat_number[1].split('-')[-1])
prefix = "M2"

for i in range(lst_tkt + 1, lst_tkt + number_of_tickets + 1):


tkt_list.append(prefix + '-' + str(i))
Multiplex.__list_last_seat_number[1] = tkt_list[-1]
Multiplex.__list_total_tickets[1] -= number_of_tickets

return tkt_list

def get_total_price(self):
return self.__total_price

def get_seat_numbers(self):
return self.__seat_numbers

booking1 = Multiplex()
status = booking1.book_ticket("movie1", 5)
if (status == 0):
print("invalid movie name")
elif (status == -1):
print("Tickets not available for movie-1")
else:
print("Booking successful")
print("Seat Numbers :", booking1.get_seat_numbers())
print("Total amount to be paid:", booking1.get_total_price())
print("-----------------------------------------------------------------------------")
booking2 = Multiplex()
status = booking2.book_ticket("movie2", 1)
if (status == 0):
print("invalid movie name")
elif (status == -1):
print("Tickets not available for movie-2")
else:
print("Booking successful")
print("Seat Numbers :", booking2.get_seat_numbers())
print("Total amount to be paid:", booking2.get_total_price())
OUTPUT:
Booking successful
Seat Numbers : ['M1-11', 'M1-12', 'M1-13', 'M1-14', 'M1-15']
Total amount to be paid: 600
-----------------------------------------------------------------------------
Booking successful
Seat Numbers : ['M2-1']
Total amount to be paid: 100

You might also like