You are on page 1of 25

PYTHON QUESTION 1

This is the first question in TCS ION LITE XPLORE COURSE.


Create a class Account with the below attributes:

int accntNo
String accntName
int accntBalance
Create a constructor which takes all parameters in the above sequence.
Create a class AccountDemo
Create a default constructor in the AccountDemo class as below def __init__(self):
pass

Create a method depositAmnt which takes an Account object and amount to be deposited
(amount) as input parameters. Update the balance i.e. Add the amount to the existing
balance and return the updated balance

Create another method withdrawAmnt which takes an Account object and amount to be
deposited (amount) as input parameters. Deduct the amount from the balance and return
the updated balance. Minimum balance to be maintained is 1000. i.e if the balance is
becoming less than 1000 when deducting the withdrawal amount, the operation need to
be stopped with a message “No Adequate balance”

To test the code against your customized Input through console, the input data needs to
be entered in the below order( as shown below in the sample input).
The first three lines in the below sample input represents the input for three variables of
account object i.e account no. (accntNo),account name (accntName) and account balance
(accntBalance), with which the object will be created.
The fourth line in the sample input is the input for the amount to be deposited in the
account object and fifth line is the input for the amount to be withdrawn from the account
object

Note:
For more details on
a. Input data entered from standard input
b. How this data is processed
c. The order of the input data
please refer the below main program.
Note:
Please request you to use the below main program to test/run your code and submit this
main along
with your solution.
Dont write separate main function again on your own.
if __name__=__main__ :
acno=int(in put0)
acname= raw_input()
acntbal=int(input0)
depamnt=int(input())
withamnt=int(i nput0)
acnt=Account(acno,acname,acntbal)
acntdemoobj=AccountDemo()

print(acntdemoobj.depositAmnt(acnt,depamnt))
print(acntdemoobj.withdrawAmnt(acnt,withamnt))
Input / Output
Input:

120

Rajesh

1500

1200

2000

Output:

2700

No Adequate balance

Soln. 1:

#Define the Account class here

class Account:

def __init__(self,accntNo,accntName,accntBalance):
self.acctNo=accntNo

self.accntName=accntName

self.accntBalance=accntBalance

#Define the AccountDemo class here

class AccountDemo:

def __init__(self):

pass

def depositAmnt(self,acnt,amtdepo):

self.update=acnt.accntBalance+amtdepo

return self. update

def withdrawAmnt(self,Accnt,amtdep):

deduct=self.update-amtdep

if(deduct<1000):

return "No Adequate balance"

else:

return deduct

#Sample main section.

#Do not remove the below portion of code.

if __name__ == '__main__':

acno=int(input())

acname=input()
acntbal=int(input())

depamnt=int(input())

withamnt=int(input())

acnt=Account(acno,acname,acntbal)

acntdemoobj=AccountDemo()

print(acntdemoobj.depositAmnt(acnt,depamnt))

print(acntdemoobj.withdrawAmnt(acnt,withamnt))
Question 2:

Create a function with the name check.palindrome which takes a list of strings as input.
The function checks each string of the list whether it is a palindrome or not and returns
another list containing the pallndrome from the input string.
Note:
i. A palindrome is a a word, phrase, or sequence that reads the same backwards as
forwards, e.g. madam
ii. The check for the string to be palindrome should be case-insensitive, e.g. madam and
Madam both should be considered as palindrome.
You can use the below sample input and output to verify your solution.
The first line in the sample input is the count of strings to be included in the list as the 1 st
input.
The strings are then provided one by one as the next lines of input.
For more details, please refer to the below main section of code
You can use the below sample main section to test your code.
Sample Main Method:

if _name_=='_main_’: count=int(inputO) inp_str=[]

for i in range(count):
inp_str.append(input())

output=check-palindrome(inp_str)

if len(output)!=0:

for i in output: print(i) else: print('No palindrome found’)

Input / Output

Input:
3
Hello
Malayalam
Radar
Output:
Malayalam
Radar

Soln. 2:

def check_palindrome(inp_str):

output=[]

for i in inp_str:

if i.lower() == i.lower()[::-1]:

output.append(i)

return output

if __name__=='__main__':

count=int(input())

inp_str=[]

for i in range(count):

inp_str.append(input())

output=check_palindrome(inp_str)

if len(output)!=0:

for i in output:

print(i)

else:

print('No palindrome found')


Question 3:

Create a function with the name find_Novowels which takes a list of strings as input. The
function checks each string of the list whether it has at least one vowel or not and returns
another list containing the strings not having any vowel.
Note:
The check for the vowel should be case-insensitive
You can use the below sample input and output to verify your solution
The first line in the sample input is the count of strings to be included in the list to be
passed to the
method find_Novowels.
The strings are then provided one by one as the nexct lines of input.
For more details, please refer to the below main section of code
You can use the below sample main section to test your code.

sample Main Method:


if _name_==’__main_’: count=int(inputØ) inp_str=[I for i in range(count):
inp_str.append(inputO)
output=find_NovowelsQnp_str) If len(output)!=O: print('strlngs without vowels:’) for I In
output: prnt(l)
else: print(’No string found’)
Input / Output
Input:
4
almost
vtyw
sound
prtwy

Output:

Strings without vowels:

vtyw

prtwy
Soln. 3:
#Define the find_Novowels function here

def find_Novowels(inp_str):

res=[]

for i in inp_str:

c=0

for j in i:

if(j=='A' or j=='a' or j=='E' or j=='e' or j=='I' or j=='i' or j=='O' or j=='o' or


j=='U' or j=='u'):

break

else:

c+=1

if c==len(i):

res.append(i)

return res

#Sample main section.

#Do not remove the below portion of code.

if __name__=='__main__':

count=int(input())

inp_str=[]

for i in range(count):

inp_str.append(input())
output=find_Novowels(inp_str)

if len(output)!=0:

print('Strings without vowels:')

for i in output:

print(i)

else:

print('No string found')


Question 4:

Create a function with the name checkprime which takes a number as input and checks if
the given number is prime or composite. The function retumns 1 if the number is prime,O
if the number is composite and 0 otherwIse.
Create another function with the name prime_composite_list which takes a list of
numbers and checks whether the numbers in the list are prime or composite. Include all
the prime numbers in one list and all the composite numbers in another list. Create a 3rd
list and include the list of prime numbers and the list of composite numbers in the 3rd list
and return the 3rd list from this function. The third list should be a list of lists.
Note: use the function check.--prime to find whether the number is prime or composite.
To test the code against your customized Input through console, please refer to the below
instructions
The first line in the sample input is the count of numbers to be provided in the input list
The next few lines are the numbers to be included in the list provided one by one
Please use the below main program code to implement and to test/run your code and
submit the complete code along with this main code.
if __name__=__main__:
inp=[]
count=int(input0).
for i in range(count):
inp.append(int(input())
print(check_prime(inp(1))
result= prime_composite_list(inp)
print(result)

Input I Output
Input:
4
11
7
90
44
Output :
[[11, 7], [90, 44]]
Soln 4:

def check_prime(key):

res=0

for i in range(2,key//2):

if(key%i==0):

res+=1

if res==0:

return 1

else:

return 0

def prime_composite_list(inp):

prime=[]

comp=[]

res=[]

for i in range(len(inp)):

if(check_prime(inp[i])):

prime.append(inp[i])

else:

comp.append(inp[i])

res.append(prime)

res.append(comp)
return res

if __name__ ==”__main__”:

inp=[]

count=int(input())

for i in range(count):

inp.append(int(input()))

print(check_prime(inp[1]))

result=prime_composite_list(inp)

print(result)
Question 5:

Write a Python program to find the position of the second occurrence of a given number in
a given list of numbers.
Function will take as input a list of numbers as first argument and a numeric variable as
second argument This function should return the index where the given variable value
occurs in the list for the second time
Function signature:
getlndex(listoflntegers,NumericVariable):
In the above function signature, First argument represents list of integer values and
Second argument represents a number, whose second occurred position(index) to be
returned.
The function should retumn the index of the number(supplied as second argument),
occurred for the
second time in the list.
if the number does not occur for the second time in the input list or If the number does
not exist in the list then the fundtion should retumn 0.
Develop a main ogr, below sequence of actions:
a. Create an empty list.
b. Read the size of the list from standard input
c. Based on the size of the list read above, repeat reading and adding the elements to the
list created. d. Read the number, whose index is to be searched for its second occurrence..i
e. Then call getlndex function by supplying the Input list as first argument and numeric
value (whose index is to be searched for its second occurrence) as second argument.
Function should retumn the index of the second occurrence of the number(whose value
supplied as second argument to the main program through numeric variable)
Finally print the returned value of the function.
Look at the sample testcase below for more clarity to write the input and output
statements in the main section.

Input:

5
3
4
3
7
4
3
output
2

Description:
In the above Input, the first hne content(s) represents the number of elements in the list,
to be created.
From second line to 6th lmie represents the 5 elements as below and to be added to the
list created.
3
4
3
7
4

The last line content (3) represents the number to search for its second occurance
position(Index) in
the input list Output is 2 means, the element 3 is found second time at the index value 2,
in the given
input list

Input

4
2
3
4
5
5
Output:

0
Soln5:

def getIndex(l,key):

c=0

for i in range(len(l)):

if l[i]==key:

c+=1

if c==2:

return i

return 0

if __name__== "__main__":

n=int(input())

i_list=[]

for i in range(n):

i_list.append(int(input()))

key=int(input())

print(getIndex(i_list,key))
Question6:

During the CViD19 pandemic, the status of beds availability is to be tracked

Create a class city with the below attributes:


city_id of type Number
state_name of type string
city.name ot type string
covidbeds of type Number
avlblcovbeds of type Number
ventilbeds ot type Number
avlbiventilbeds ot type Number

Attribute description:
city_id represents Unique ID for the city
state.name represents the state name
city_name represents the city name
covidbeds represents the total covid beds in the city
avlblcovbeds represents the total available covid beds in the city
ventilbeds represents the total ventilator beds in the city
avlblventilbeds represents the total available ventilator beds in the city
Create the -init. method which takes all parameters in the above sequence. The method
should set the value of attributes to parameter values.
Create another class covBedsAnalysis with the below attributes:
analysis.name of type string
citylist of type List having city objects
Create the -iniL- method which takes all parameters in the above sequence. The method
should set the value of attributes to parameter values inside the method.
Create another method inside the class with the name get_StateWiseAvlblBedStats

This method is used to find the state wise available covid beds and available ventilator
beds and returns a list of tuples with state name,total available covid beds and total
available ventilator beds for each state, sorted by state name.
Note: A state contains multiple cities. Total number of available beds for a respective
category (covid or ventilator beds) in a state is the sum of the available beds of all the
cities in that state for the respective category (covid or ventilator), Refer testcase output
for more clarity,
create another method with the name gtCitieswithMoreThanAvgOccupiedbeds, which
takes state as argument and retums the dictionary with city as the key and tuple of
occupied covid beds and occupied ventilator beds as value, where number of covid beds
occupied and ventilator beds occupied are more than the state average for the respective
category of beds.
i.e. the city(cities) in the given state to be recorded/resulted (with the data mentioned),
should satisfy the below conditions:
whose occupied covid beds count Is more than the average of occupied covid beds of all
the cities of the given states and the respective city should also contain the occupied
ventilator beds count more than the average of occupied ventilator beds of all cities of the
given stat&.
For more clarity please refer the sample test case Input and output in below section
If no city is found with the occupied beds more than state average as mentioned above,
then return None and display No city available (without quotes) in main function.
Please note that the search operations (if any as per the requirement..) should be case
insensitive.

Instructions to write main function:

a. You would require to write the main section completely, hence please follow the below
instructions for the same.
b. You would require to write the main program which is inline to the TMsample input
description section” mentioned below and to read the data in the same sequence.
c. Create the respective objects(City and CovBedsAnalysis) with the given sequence of
arguments to fulfill the _init...... method requirement defined in the respective classes
referring to the below instructions.
i. Create a City object after reading the data related to it and add the object to the list of
city objects which will be provided to the CovBedsAnalysis object while creation.
This point repeats for the number of city objects(considered in the first line of input data).
ii. Create CovBedsAnalysis object by passing the CovBedsAnalysis name(you can hard-code
any name you want) and List of city objects (created as mentioned in above
point# c.i) as the arguments.
d. Take a string value as input depicting the state which is passed to the
get.ciitesWithMoreThanAvgOccupiedbeds
e. Call the method get_StatewiseAvlblBedstats mentioned above from the main section.
f. Display the State,total available covid beds and total available ventilator beds received
from the method, with a single space in between as shown in sample testcase output,
g. Call the method get_CiiteswithMoreThanAvgOccupiedbeds mentioned above from the
main section h. Display the city name, occupied covid beds and occupied ventilator beds
with a single space in between as shown in the sample testcase output.
I. if None is returned by the method geLCiiteswithMoreThanAvgOccupiedbeds, display the
message ‘No city available' (excluding the quotes).
You can use/refer the below given sample input and output to verify your solution using
‘Test against Custom lnput ' option in Hackerrank.
Input format for Custom Testing:
a. The 1st input taken in the main section is the number of city objects to be added to the
list of cities. b.The next set of inputs are the values for the attribtes:
cityJd,state...name,city_name, covidbeds,avlblcovbeds,ventilbeds,avlblventilbeds
respectively for each city taken one after other and

is repeated for number of objects given in the first line of testcase input

c.The last line of input refers the state name WIhch is passed to the function:

get.CirteswithMoremanAvgOccupiedbeds

Input / Output

Input

5
101
Delhi
Delhi
100000
20000
5000
2000
102
Telangana
Hyderabad
200000
40000
1000
500
103
Telangana
Warangal
100000
30000
2000
1000
104
AndhraPradesh
Vijayawada
800000
300000
30000
2500
105
AndhraPradesh
Vizag
500000
100000
6000
1000
AndhraPradesh

Output:

AndhraPradesh 400000 3500


Delhi 20000 2000
Telangana 70000 1500
Vijayawada 500000 27500

Input:

6
101
Delhi
Delhi
100000
20000
8000
3000
102
Telangana
Hyderabad
200000
100000
12000
6000
103
Telangana
Warangal
100000
50000
1000
500
104
AndhraPradesh
Vijayawada
800000
400000
7500
3750
105
AndhraPradesh
Vizag
500000
100000
11000
8500
106
Maharashtra
Mumbai
1000000
0
12500
0
Maharashtra

Output:

AndhraPradesh 500000 12250

Delhi 20000 3000

Maharashtra 0 0

Telangana 150000 6500

No city available

Soln6:

class City:

def __init__(self,c,s,cn,cb,avlcb,v,avlvb):

self.city_id=c

self.state_name=s

self.city_name=cn

self.covidbeds=cb

self.avlblcovbeds=avlcb

self.vetilbeds=v

self.avlblventilbeds=avlvb

class CovBedAnalysis:

def __init__(self,an,cl):
self.analysis_name=an

self.city_list=cl

def get_StateWiseAvalblBedStats(self):

l=[]

for i in self.city_list:

l.append(i.state_name)

l=set(l)

l=sorted(l)

res=[]

for i in l:

k=[]

acb=0

avb=0

for j in self.city_list:

if i==j.state_name:

acb+=j.avlblcovbeds

avb+=j.avlblventilbeds

k.append(i)

k.append(acb)

k.append(avb)

res.append(k)
return res

def get_CitiesWithMoreThanAvgOccpiedbeds(self,state):

res2=[]

temp=0

cvb=0

veb=0

for i in self.city_list:

if state==i.state_name:

temp+=1

cvb+=i.covidbeds-i.avlblcovbeds

veb+=i.vetilbeds-i.avlblventilbeds

if(temp > 0):

avg1=cvb//temp

avg2=veb//temp

for i in self.city_list:

if state==i.state_name:

k=[]

cb=i.covidbeds-i.avlblcovbeds

vb=i.vetilbeds-i.avlblventilbeds

if(avg1<cb and avg2<vb):

k.append(i.city_name)
k.append(cb)

k.append(vb)

res2.append(tuple(k))

return res2

if __name__ == '__main__':

count=int(input())

l=[]

for i in range(count):

c=int(input())

s=input()

cn=input()

cb=int(input())

avlblcb=int(input())

v=int(input())

avlvb=int(input())

l.append(City(c,s,cn,cb,avlblcb,v,avlvb))

c=CovBedAnalysis("covid",l)

state=input()

res1=c.get_StateWiseAvalblBedStats()

for i in range(len(res1)):
for j in range(len(res1[i])):

print(res1[i][j],end=" ")

print("")

res2=c.get_CitiesWithMoreThanAvgOccupiedbeds(state)

if(len(res2)>0):

for i in range(len(res2)):

for j in range(len(res2[i])):

print(res2[i][j],end=" ")

print("")

else:

print("No city available")

You might also like