Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (2 votes)
4K views

Data Toolkit - Programming in Python: Basic Refresher

The document contains a series of multiple choice questions about Python programming concepts such as operators, loops, conditionals, and functions. It also includes examples of small coding problems and solutions related to input/output, string manipulation, and conditional logic. The questions cover a variety of basic Python topics to help refresh programming skills using MCQ format and hands-on coding exercises.

Uploaded by

zakiya Bano
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
4K views

Data Toolkit - Programming in Python: Basic Refresher

The document contains a series of multiple choice questions about Python programming concepts such as operators, loops, conditionals, and functions. It also includes examples of small coding problems and solutions related to input/output, string manipulation, and conditional logic. The questions cover a variety of basic Python topics to help refresh programming skills using MCQ format and hands-on coding exercises.

Uploaded by

zakiya Bano
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

Classification: Internal

Data Toolkit _ Programming in Python


Basic Refresher
MCQs
Question_1:

Predict Output

p = 4**3

print(p)

What will be the output of the above code snippet?

 12
 7
 64
 81
In [ ]:
p = 4**3
print(p)
# Explanation: p=4**3 is same as saying p = 4^3 = 64
Question_2:

Predict Output

Can you predict what will be the value of 'a' after executing the following code?

a = 21 % 4

 1
 5
 6
 9
In [ ]:
a = 21 % 4
a
# Explanation: The '%' operator gives the remainder. a = 21 % 4
# will store the remainder after division of 21 by 4 in 'a'.
Question_3:

Division

Predict the output of the following code.


Classification: Internal

d = 23//5

print(d)

 4
 3
 4.6
 5
In [ ]:
d = 23//5
print(d)
# Explanantion: // operator returns quotient after division.
# Think of this as integer division, where the float part of the division is
neglected.
Question_4:

Syntax Error

Which of the following will give a syntax error?

if (1): print (True)

- ```

if (1):

print (True)

if (1) print(True)

- ```

if (-1):

print('True')

if (1): print ('True')

- ```

if (1):
Classification: Internal

print ('True')

if (1) print (True)


In [ ]:
if (1):
print (True)

In [ ]:
if (1):
print (True)
In [ ]:
if (1) print(True)
In [ ]:
if (-1):
print('True')
In [ ]:
if (1):
print ('True')
In [ ]:
if (1)

print (True)
Question_5:

Output

What will be the output of the following code?

for i in range(3):

print(i)

 123

 012

 0
1
2

 1
2
3
In [ ]:
for i in range(3):
Classification: Internal

print(i)

# Expalanation: print() goes to a new line after printing by default.range(3) will


make i go over 0 1 2
Question_6:

Print

Which of the following will give output as:

11 12 13

14

print('11 12 13 \n14')

- ```

a=11

b=12

c=13

d=14

print(a+b+c)

print(d)

a=11 b=12 c=13 d=14 print(a,b,c) print(d)

- ```

a=11

b=12

c=13

d=14

print('{0} {1} {2}'.format(a,b,c) )

print(d)
Classification: Internal

a=11 b=12 c=13 d=14 print('%d %d %d' %(a,b,c)) print(d)

- ```

a=11

b=12

c=13

d=14

print(f'{a}{b}{c}')

print(d)

In [ ]:
print('11 12 13 \n14')
In [ ]:
a=11
b=12
c=13
d=14
print(a+b+c)
print(d)
In [ ]:
a=11
b=12
c=13
d=14
print(a,b,c)
print(d)
In [ ]:
a=11
b=12
c=13
d=14
print('{0} {1} {2}'.format(a,b,c) )
print(d)
In [ ]:
a=11
b=12
c=13
d=14
print('%d %d %d' %(a,b,c))
print(d)
In [ ]:
a=11
b=12
Classification: Internal

c=13
d=14
print(f'{a}{b}{c}')
print(d)
In [ ]:
# try to print factorial of given number
n = int(input())
from functools import reduce
if n == 0:
print(1)
else:
fact = reduce(lambda x,y : x*y,range(1,n+1))
print(fact)
Coding Practice
Swapping

Description

You are given two integer variables, x and y. You have to swap the values stored in x and y.

Input:
Two numbers x and y separated by a comma.

Output:
Print 5 lines. The first two lines will have values of variables shown before swapping, and the last two
lines will have values of variables shown after swapping. The third line will be blank.

Sample input:
20, 50

Sample output:

x before swapping: 20

y before swapping: 50

x after swapping: 50

y after swapping: 20

In [ ]:
# Solution 1: using temprory varaible
in_str = input()
in_list = in_str.split(", ")
x = int(in_list[0])
y = int(in_list[1])
Classification: Internal

print("x before swapping:",x)


print("y before swapping:",y)

z = x
x = y
y = z

print("\nx after swapping:",x)


print("y after swapping:",y)
In [ ]:
# Solution 1: using x,y = y,x
in_str = input()
in_list = in_str.split(", ")
x = int(in_list[0])
y = int(in_list[1])

print("x before swapping:",x)


print("y before swapping:",y)

x,y = y,x

print("\nx after swapping:",x)


print("y after swapping:",y)
Even Or Odd

Description

Given an integer, print whether it is Even or Odd.

Input:
An integer

Output:
'Even' or 'Odd'

Sample input_1:
3

Sample output_1:
Odd

Sample input_2:
6

Sample output_2:
Even

In [ ]:
num = int(input())
Classification: Internal

if num%2 == 0:
print("Even")
else:
print("Odd")
Beautiful Pretty Sexy

Description

A number k is beautiful if it is of the form 3n+1, is pretty if it is of the form 3n+2 and is sexy if it is of
form 3n.
Given a number k, print if it is beautiful, pretty or sexy.

Input:
int

Output:
beautiful, pretty or sexy

Sample input_1:
21

Sample output_1:
sexy

Sample input_2:
22

Sample output_2:
beautiful

Sample input_3:
23

Sample output_3:
pretty

In [ ]:
k = int(input())

if k%3 == 0:
print("sexy")
elif k%3 == 1:
print("beautiful")
elif k%3 == 2:
print("pretty")
Alarm Clock
Classification: Internal

Description

You're trying to automate your alarm clock by writing a function for it. You're given a day of the
week encoded as 1=Mon, 2=Tue, ... 6=Sat, 7=Sun, and whether you are on vacation as a boolean
value (a boolean object is either True or False. Google "booleans python" to get a better
understanding). Based on the day and whether you're on vacation, write a function that returns a
time in form of a string indicating when the alarm clock should ring.

When not on a vacation, on weekdays, the alarm should ring at "7:00" and on the weekends
(Saturday and Sunday) it should ring at "10:00".

While on a vacation, it should ring at "10:00" on weekdays. On vacation, it should not ring on
weekends, that is, it should return "off".

Input:
The input will be a list of two elements. The first element will be an integer from 1 to 7, and the
second element will be a boolean value.

Output:
The output will be a string denoting the time alarm will ring or 'off'

Sample input_1:
[7, True]

Sample output_1:
off

Sample input_2:
[3, True]

Sample output_2:
10:00

In [ ]:
# Solution_1: nested if else
import ast
input_list = ast.literal_eval(input())
day_of_the_week = input_list[0]
is_on_vacation = input_list[1]
weekend = [6,7]

if is_on_vacation:
if day_of_the_week in weekend:
print('off')
else:
print('10:00')
else:
Classification: Internal

if day_of_the_week in weekend:
print('10:00')
else:
print('7:00')
In [ ]:
# Solution_2: nested if elif
import ast
input_list = ast.literal_eval(input())
day_of_the_week = input_list[0]
is_on_vacation = input_list[1]
weekend = [6,7]

if is_on_vacation == True and day_of_the_week in weekend:


print('Off')
elif is_on_vacation == True and day_of_the_week not in weekend:
print('10:00')
elif is_on_vacation == False and day_of_the_week in weekend:
print('10:00')
else:
print('7:00')
In [ ]:
# Solution_3: using user defined function with nested if else
import ast
input_list = ast.literal_eval(input())
day_of_the_week = input_list[0]
is_on_vacation = input_list[1]

def alarm(day_of_the_week,is_on_vacation):
weekend = [6,7]
if is_on_vacation:
if day_of_the_week in weekend:
return 'off'
else:
return '10:00'
else:
if day_of_the_week in weekend:
return '10:00'
else:
return '7:00'

print(alarm(day_of_the_week,is_on_vacation))
In [ ]:
# Solution_4: with user defined function
import ast
input_list = ast.literal_eval(input())
day_of_the_week = input_list[0]
is_on_vacation = input_list[1]

def alarm_clock(day_of_the_week,is_on_vacation):
weekend = [6,7]
if is_on_vacation == True and day_of_the_week in weekend:
return 'off'
Classification: Internal

elif is_on_vacation == True and day_of_the_week not in weekend:


return '10:00'
elif is_on_vacation == False and day_of_the_week in weekend:
return '10:00'
else:
return '7:00'

print(alarm_clock(day_of_the_week,is_on_vacation))
Factorial

Description

Factorial is a mathematical function denoted by '!'. It is defined as

n factorial = n!= 123...*(n-1)*n.

In this question, you have to make a function that will take an integer as input, and return the
factorial of that integer if that integer is greater than or equal to zero and return -1 if the number is
less than zero or negative.

Note: the function doesn't return print the factorial but returns it.

Input:
An integer n

Output:
The function returns n! if n is greater than or equal to 0.
0! = 1
and the function returns -1 if the number is less than 0.

Sample input_1:
3

Sample output_1:
6

Sample input_2:
-4

Sample output_2:
-1

In [ ]:
# Solution_1: using user defined function
n = int(input())
def factorial(n):
if n == 0:
Classification: Internal

return 1
elif n < 0:
return -1
else:
f = 1
for i in range(1,n+1):
f = f*i
return f

k = factorial(n)
print(k)

In [ ]:
# Solution_2: using if elese and for loop
n = int(input())
if n == 0:
print(1)
elif n < 0:
print(-1)
else:
f = 1
for i in range(1,n+1):
f *= i
print(f)
In [ ]:
# Solution_3: using reduce and lambda
from functools import reduce
n = int(input())
if n == 0:
print(1)
elif n < 0:
print(-1)
else:
print(reduce(lambda x,y: x*y,range(1,n+1)))
Reverse The Digits

Description

You will be given a number. You have to reverse the digits of the number and print it.

Input:
A positive integer greater than zero

Output:
The number in reverse order. Check sample outputs for more details.

Sample input_1:
345200
Classification: Internal

Sample output_1:
2543

Sample input_2:
6752343

Sample output_2:
3432576

In [ ]:
# Solution_1: using slicing step
num = input()
reverse_num = int(n[::-1])
print(reverse_num)
In [ ]:
# Solution_2: using reverse function
num = input()
reverse_num = num.
print(int(reverse_num))
In [ ]:
# Solution_2 using while loop
n = int(input())
r = 0
while n>0:
r = r*10 + n%10
n = n//10
print(r)
How Many Chocolates?

Description

Sanjay loves chocolates. He goes to a shop to buy his favourite chocolate. There he notices there is
an offer going on, upon bringing 3 wrappers of the same chocolate, you will get new chocolate for
free. If Sanjay has m Rupees. How many chocolates will he be able to eat if each chocolate costs c
Rupees?

Input:
Two positive integers m and c separated by a comma. The first integer is m and the second integer is
c

Output:
A single integer denoting the number of chocolates Sanjay was able to eat in total.

Sample input_1:
15, 2
Classification: Internal

Sample output_1:
10

Explanation:
First, he will get 15/2=7 chocolates. He then will return 6 wrappers for 2 chocolates. And lastly, these
two wrappers and the one he previously had will get him one more chocolate, making a total of
7+2+1=10 chocolates.

Sample input_2:
3,1

Sample output_2:
4

In [ ]:
in_list = input().split(',')
m = int(in_list[0])
c = int(in_list[1])

choc = m//c
w = m//c

while w//3 != 0:
choc += w//3
w = w//3 + w%3

print(choc)
Print The Pattern

Description

Printing different patterns is a very good exercise to reinforce iteration through loops and strong
logic building. Here you will be given a positive integer and you will generate pattern based on that
integer.

Input:
A positive integer n
1 <= n <=20

Output:
A pattern as described by the Sample input and outputs below.

Sample input_1:
5

Sample output_1:
Classification: Internal

*_*

*_*_*

*_*_*_*

*_*_*_*_*

Sample input_2:
3

Sample output_2:

*_*

*_*_*

In [ ]:
n = int(input())
for row in range(1,n+1):
for col in range(n-row):
print(" ",end="")
for col in range(row-1):
print("*_",end="")
print('*')
List
MCQs
Question_1:

List Which of the following will make a list?

 L = [1, 2, 3, 4]
 L = [i for i in range(1, 5)]
 L = [for i in range(1, 5) i]
 L = [for i in range(1, 5): i]
In [ ]:
L = [1, 2, 3, 4]
L
In [ ]:
L = [i for i in range(1, 5)]
L
In [ ]:
L = [for i in range(1, 5) i]
L
Classification: Internal

In [ ]:
L = [for i in range(1, 5): i]
L
Question_2:

List What will be the output of the following code

L=[2, 3, 4, 2, 1, 2, 3]

print(L.index(2))

 0
 1
 5
 6
 3
In [ ]:
L=[2, 3, 4, 2, 1, 2, 3]
print(L.index(2))
# Explanation: L.index(k) will return the index of the first occurrence of the
element k in L
Question_3:

What is K What is K in the following code?

L = [2, 1, 2, 4, 5, 3, 6]

K = 4 in L

 All index's of element 4 in the list L


 Boolean saying if 4 is in List or not
 Will give an updated list after adding 4 to the list
 Will give an updated list after adding 4 to the list if 4 is not present in the list
In [ ]:
L = [2, 1, 2, 4, 5, 3, 6]
K = 4 in L
K
# Explanation: in functionality checks if the element is in the list or no.
Question_4:

Many Ways

Given L=[10,20,30,40,50,60,70,80,90,100], how will you get a list [20, 40,


60, 80]
Classification: Internal

 L[[1, 3, 5, 7]]
 L[1, 3, 5, 7]
 L[1::2]
 L[1:-1:2]
 L[2:-1:2]
 [L[i] for i in range(1,9,2)]
In [ ]:
L=[10,20,30,40,50,60,70,80,90,100]
L[[1, 3, 5, 7]]
In [ ]:
L=[10,20,30,40,50,60,70,80,90,100]
L[1, 3, 5, 7]
In [ ]:
L=[10,20,30,40,50,60,70,80,90,100]
L[1::2]
In [ ]:
L=[10,20,30,40,50,60,70,80,90,100]
L[1:-1:2]
In [ ]:
L=[10,20,30,40,50,60,70,80,90,100]
L[2:-1:2]
In [ ]:
[L[i] for i in range(1,9,2)]
Question_5:

How to Append

How will you add the list A = [10, 20, 30] at the end of list B = [45, 35,
25], making the final list as [45, 35, 25, 10, 20, 30].

 B.append(A)
 B.extend(A)
 [A, B]
 [A.append(i) for i in B]
In [ ]:
A = [10, 20, 30]
B = [45, 35, 25]
B.append(A)
B
In [ ]:
A = [10, 20, 30]
B = [45, 35, 25]
B.extend(A)
B
Classification: Internal

In [ ]:
A = [10, 20, 30]
B = [45, 35, 25]
[A, B]
In [ ]:
A = [10, 20, 30]
B = [45, 35, 25]
[A.append(i) for i in B]
Coding Practice
Smallest Element

Description

You have to find and print the smallest element of the list given as input.

Input:
A non-empty list of integers.

Output:
The smallest integer of the input list.

Sample input_1:
[2, -3, 0, 7, 21]

Sample output_1:
-3

In [ ]:
# Solution_1: Using min() function
import ast
input_list = ast.literal_eval(input())
print(min(input_list))
In [ ]:
# Solution_2: using for loop
import ast
input_list = ast.literal_eval(input())
small = input_list[0]

for i in input_list:
if i<small:
small = i
print(small)
Above Average

Description

Finding the average of the data and comparing it with other values is often encountered while
analysing the data. Here you will do the same thing. The data will be provided to you in a list. You
Classification: Internal

will also be given a number check. You will return whether the number check is above average or no.

Input:
A list with two elements:
The first element will be the list of data of integers and
The second element will be an integer check.

Output:
True if check is above average and False otherwise

Sample input_1:
[[2,4,6,8,10], 4]

Sample output_1:
False

Sample input_2:
[ [2,4,6,8,-10], 4]

Sample output_1:
True

In [ ]:
# Solution_1: using inbuilt function
import ast
input_list = ast.literal_eval(input())
avg_list = input_list[0]
check = input_list[1]

average = sum(avg_list)/len(avg_list)

if average < check:


print(True)
else:
print(False)
In [ ]:
# Solution_2: using conventional function

import ast
input_list = ast.literal_eval(input())
avg_list = input_list[0]
check = input_list[1]

total = 0

for i in avg_list:
total += i

average = total/len(avg_list)
Classification: Internal

if average < check:


print(True)
else:
print(False)
Recruit New Members

Description

Suppose you are a manager as a big firm and now are looking for new members for your team. You
sent out an advertisement and have received a few applications. You have a habit of scoring people
on a scale of 100. You have given scores to all the members of your team and the new applications.
The process of selection is going to be very straightforward if the applicant improves the average of
the team then you hire the applicant to join the team or else reject the application. Remember the
order of processing applications is going to be important here.

You may see this as an extension of the previous problem, which it is. You may use the code written
in the previous question as a function to improve the code quality.

Input:
Two lists on two separate lines.
The first line will have the list of scores of current team members
The second line will have the list of scores of the applicants.

Output:
The list consisting of scores of the final team after hiring from the pool of applicants.

Sample input_1:
[23,45,34,76]
[70,34,94]

Sample output_1:

[23, 45, 34, 76, 70, 94]

Explanation:
The first applicant has score 70, and the team average is 44.5 hence the applicant is hired making the
team average 49.6
The second applicant has score 34, and the team average is 49.6 hence the applicant is rejected
keeping the team average same 49.6
The third applicant has score 94, and the team average is 49.6 hence the applicant is hired making
the team average 57

Sample input_1:
Classification: Internal

[10,20,30,40,50]
[30,60,80,40]

Sample output_1:

[10, 20, 30, 40, 50, 60, 80]

In [ ]:
# solution_1: using user defind function
import ast
team_list = ast.literal_eval(input())
applicant_list = ast.literal_eval(input())

def check_above_avg(data,check):
avg = sum(data)/len(data)
if avg < check:
return 1
else:
return 0

for applicant in applicant_list:


finalist = check_above_avg(team_list,applicant)
if finalist == 1:
team_list.append(applicant)

print(team_list)

In [ ]:
# not correct need to check
import ast
team_list = ast.literal_eval(input())
applicant_list = ast.literal_eval(input())

avg = sum(team_list) / len(team_list)

for applicant in applicant_list:


if applicant > avg:
team_list.append(applicant)

print(team_list)
Calendar

Description

You are planning to go to your friend's wedding and you have long events all month, lasting at least
a few days. You have the start and end dates of events and your task is to find out events
overlapping with the wedding date.

The code for taking input has already been written for you, please don't modify that, but do read and
try to understand the way input has been taken. You will be asked to take input on your own for
Classification: Internal

most of the problems here onwards. Taking data in a suitable format is an important skill for a Data
Scientist.

Input:
The input will contain a list of lists where each sub-list has only two elements representing the start
and end date of an event, the start date will be less than or equal to the end date. The next line of
input will have a wedding date.

Output:
The output should have the number of events overlapping with the wedding date.

Sample input_1:
[ [29,31], [23,26], [24,25] ]
24

Sample output_1:
2

Explanation:
There are three events in the month.
Event 1= from date 29 to 31
Event 2= from date 23 to 26
Event 3= from date 24 to 25
Wedding is on 24. This means it will clash with Event 3 and Event 2, that is two events. The output is
therefore 2.

Sample input_1:
[ [1, 4], [7, 10], [8, 8], [14, 23] ]
26

Sample output_1:
0
In [ ]:
# Solution_1: elaborate if condition
import ast
event_list = ast.literal_eval(input())
marriage = int(input())

clash = 0

for dates in event_list:


if marriage >= dates[0] and marriage <= dates[1]:
clash += 1

print(clash)
In [ ]:
Classification: Internal

# Solution_2: consise if condition


import ast
event_list = ast.literal_eval(input())
marriage = int(input())

clash = 0

for dates in event_list:


if dates[0] <= marriage <= dates[1]:
clash += 1

print(clash)
Fenced Matrix

Description

You will be given two positive integers m and n. You have to make a list of lists (which can be
visualised as a matrix) of size m*n, that is m sublists (rows), with each sublists having n integers
(columns). The matrix should be such that it should have 1 on the border and 0 everywhere else. See
sample input and output for more clarification.

Input:
Two integers separated by a comma

Output:
The output should have the number of events overlapping with the wedding date.

Sample input_1:
4,5

Sample output_1:

[1, 1, 1, 1, 1]

[1, 0, 0, 0, 1]

[1, 0, 0, 0, 1]

[1, 1, 1, 1, 1]

__Sample input_2:__
3,3

__Sample output_2:__

[1, 1, 1]
Classification: Internal

[1, 0, 1]

[1, 1, 1]

Sample input_3:
3,2

Sample output_3:

[1, 1]

[1, 1]

[1, 1]

In [ ]:
# Not list way, it is pattern way
in_str = input().split(',')
m = int(in_str[0])
n = int(in_str[1])

for row in range(0,m):


for col in range(0,n):
if (row == 0 or row == m-1) or (col == 0 or col == n-1):
print(1,end=" ")
else:
print(0,end=" ")
print()

In [ ]:
# Solution_1:
in_str = input().split(',')
m = int(in_str[0])
n = int(in_str[1])

final = [0]*n
final = [list(final) for i in range(m)]

for row in range(m):


for col in range(n):
if row == 0 or row == m-1 or col == 0 or col == n-1:
final[row][col] = 1

for i in final:
print(i)
Strings
MCQs
Question_1:
Classification: Internal

Strings Strings is a data structure in python. There are two types of data structures- immutable and
mutable. Strings are under which category?

 Always Mutable
 Always Immutable
 Can be both depending on initialisation
In [ ]:
# Strings are immuatable
Question_2:

Character What will be the output of the following?

print(chr(51))

 3
 Will throw an error
 a
 'A'
 '3'
In [ ]:
print(chr(51))
# Explanation: 51 is ASCII code of '3'
Question_3:

ASCII Given an ASCII code, how will you find the character associated with it? Suppose the given
ASCII code is 123.

 char(123)
 ord(123)
 chr(123)
 ord('123')
In [ ]:
chr(123)
Question_4:

Strip What does the following line of code do to a string S

S.strip()

 Remove empty spaces from the left end of the string


 Remove empty spaces from the right end of the string
Classification: Internal

 Separate every character of the string


 Remove empty spaces from both ends of the string
In [ ]:
# Remove empty spaces from both ends of the string
Question_5:

Map, Filter, Reduce Will the functions map, reduce, filter work on Strings?

 None of them will work, they will work only on List and other mutable Data structures.
 Only map will not work.
 Only filter will not work
 All three will work
 Only reduce will not work
In [ ]:
# They will all work on strings and any other iterable Data structure.
Question_6:

String Which of the following will give the output as 'upGrad'?

Multiple answers may be correct.

s = upGrad

- ```

s = upgrad

s = s[:2] + s[2].upper() + s[3:]

'G'.join(['up','rad'])

- ```

s='aabupGradaab'.strip('aab')

s='aabupGradaab'.strip('a').strip('b').strip('a')
In [ ]:
s = upGrad
s
Classification: Internal

In [ ]:
s = upgrad
s = s[:2] + s[2].upper() + s[3:]

In [ ]:
'G'.join(['up','rad'])
In [ ]:
s='aabupGradaab'.strip('aab')
s
In [ ]:
s='aabupGradaab'.strip('a').strip('b').strip('a')
s
coding exercise
Palindrome String

Description

Write a program to check whether a string is a palindrome or not. Print 1 if the string is a palindrome
and 0 otherwise.

Note: Please ensure that your program should not be case-sensitive. So, if the input is, say,
“HAnnah”, then, its output should be 1.

Input:
A string

Output:
1 if the string is a palindrome, 0 otherwise

Sample input_1:
HAnnah

Sample output_1:
1

Sample input_2:
Rebecca

Sample output_2:
0
In [ ]:
# solution_1: using string slicing
s = input()
reverse_str = s[::-1]
if s.lower() == reverse_str.lower():
print(1)
else:
Classification: Internal

print(0)
In [ ]:
# Solution_2: using for loop
s = input().lower()
r = ""
for i in s:
r = i + r # it will create reverse string

if s == r:
print(1)
else:
print(0)
Reverse Words

Description

You will be given a sentence in the form of a string. You have to reverse the order of the words in the
sentence. Remember not to reverse the individual words, but the order of words. Check the sample
input-output for further clarification.

Input:
A string, which will consist of a few spaces.

Output:
The words in reverse order.

Sample input_1:
I love coding in python

Sample output_1:
python in coding love I

Sample input_2:
python is super easy and fun

Sample output_2:
fun and easy super is python
In [ ]:
# Solution_1: split and join method with slicing
sentence = input().split()
new_list = sentence[::-1]
print(" ".join(new_list))
In [ ]:
# Solution_2: using reversed function with slicing
sentence = input().split()
new_list = list(reversed(sentence))
print(" ".join(new_list))
Classification: Internal

No Spaces

Description

While naming entities, it is a common practice to avoid spaces. That is the reason you see so many
people using underscores instead of spaces.
You will be given a string, containing a few spaces and random upper and lower cases. You have to
write a code that will add underscore in place of spaces and also capitalise the letters properly, i.e.
the first letter after underscore should be in upper case and the first letter of the string should be in
upper case, all of the other letters should be lower case.
This type of activity is frequently encountered while starting to analyse data. This is called Data
cleaning and you will learn more about it in upcoming modules.

Input:
A string of only alphabets and spaces

Output:
A string formatted as stated above. See sample input/output for more clarification,

Sample input_1:
caloRie consuMed

Sample output_1:
Calorie_Consumed

Sample input_2:
data science

Sample output_2:
Data_Science
In [ ]:
# Solution_1: using built in functions without any loop
in_str = input().lower().split()
output_list = "_".join(in_str).title()
print(output_list)
In [ ]:
# Solution_2: using list comprehension
in_str = input().lower()
words = in_str.split()
final_list = [word[0].upper()+word[1:] for word in words]
final_str = "_".join(final_list)
print(final_str)
In [ ]:
# Solution_3: using list comprehension with builtin function
in_str = input().lower()
words = in_str.split()
final_list = [word.title() for word in words]
Classification: Internal

final_str = "_".join(final_list)
print(final_str)
Shift Vowels

Description

Write a program that receives a string and shifts all the vowels present in it to the beginning. Output
the resultant string. The order of all the vowels with respect to each other as well as the order of all
the other characters with respect to each other should stay the same.

Input:
A string

Output:
Vowels shifted to the beginning in the input string.

Sample input_1:
programming

Sample output_1:
oaiprgrmmng

Sample input_2:
You love Python!

Sample output_2:
ouoeoY lv Pythn!

In [ ]:
# Solution_1: using loop
in_str = input()
vowels_str = ""
other_str = ""

for letter in in_str:


if letter in 'AEIOUaeiou':
vowels_str += letter
else:
other_str += letter

print(vowels_str+other_str)
In [ ]:
# Solution_2: using list comprehension
in_str = input()
vowels_list = [word for word in in_str if word in 'AEIOUaeiou']
other_list = [word for word in in_str if word not in 'AEIOUaeiou']
vowels_str = "".join(vowels_list)
other_str = "".join(other_list)
Classification: Internal

print(vowels_str+other_str)
Common Prefix

Description

You will be given two strings. You have to find the largest prefix common in both the strings.

Input:
Two lines of input, one string on each line

Output:
The common largest prefix for both strings. Check sample input/output for clarification. -1 if no
prefix is common.

Sample input_1:
abshdksajd
abshiehand

Sample output_1:
absh

Sample input_2:
upgradData
upGradScience

Sample output_2:
upgrad

In [ ]:
# solution_1:
str1 = input().lower()
str2 = input().lower()

for i in range(min(len(str1),len(str2))):
if str1[i] != str2[i]:
break

if i == 0:
print(-1)
else:
print(str1[:i])

In [ ]:
# Reduce cannot be used because if len of list is more it is reducing more char
def prefix(str1,str2):
for i in range(min(len(str1),len(str2))):
if str1[i].lower() != str2[i].lower():
break
Classification: Internal

if i == 0:
return -1
else:
return (str1[:i].lower())

my_list = ["upgradData","upGradScience",'upgradAI',"upgradDS","UpgradML"]
# my_list = ["upgradData","upGradScience",'upgradAI']
from functools import reduce
print(reduce(prefix,my_list))
In [ ]:
# common prefix for multiple string in a list
my_list = ["upgradData","upGradScience",'upgradAI']

def common_prefix(my_list):
my_list1 = sorted(my_list,key=len)
prefix = ""
for i in range(len(my_list1[0])):
if my_list1[len(my_list1)-1][i].lower() == my_list1[0][i].lower():
prefix += my_list1[len(my_list1) -1][i].lower()
else:
break
return prefix

print(common_prefix(my_list))

# my_list1[len(my_list1) -1][i].lower(), here -1 given for we are comparing with one


element from the list
# so the len will be lengnth excluded one element
Anagrams

Description

Two strings are anagrams of each other if you can rearrange the characters of one string to make the
other string. Given two strings, can you find if they are anagrams or no?

Input:
Two lines of input, each line will contain a string without space.

Output:
True or False based on whether the strings are anagrams or not.

Sample input_1:
thing
night

Sample output_1:
Classification: Internal

True

Sample input_2:
upgrad found

Sample output_2:
False

Note: the code will be case-Sensitive


Hint: if the length of the strings doesn't match, the strings are obviously not anagrams.
In [ ]:
# Solution_1: using sorted() function
string1 = input()
string2 = input()

string1 = sorted(string1)
string2 = sorted(string2)

if string1 == string2:
print(True)
else:
print(False)
In [ ]:
# Solution_2: using user defined function
string1 = input()
string2 = input()

def anagrams(string1,string2):
if len(string1) != len(string2):
return False
for i in range(len(string1)):
if string1.count(string1[i]) != string2.count(string2[i]):
return False
return True

print(anagrams(string1,string2))
Other Data Structures
MCQs
Question_1:

Intersection

Which of the following codes can be used to find intersection of sets A, B and C.

 set.intersection(A, B, C)
 A.intersection(B, C)
 A.intersection([B, C])
Classification: Internal

 set.intersection([A, B, C])
In [ ]:
# set.intersection(A, B, C)
# A.intersection(B, C)
Question_2:

Immutables

Which of the following are immutable?

 Elements of sets
 Lists
 Dictionary
 Tuples
In [ ]:
# Elements of sets
# Tuples
Question_3:

Dictionary

Which of the following will create a dictionary?

 d = {}
 d = ('a':1, 'b':2)
 d=dict(a=1, b=2)
 d={'a'=1, 'b'=2}
 d={'a':1, 'b':2}
In [ ]:
# d = {}
# d=dict(a=1, b=2)
# d={'a':1, 'b':2}
Question_4:

Keys

What will the following code return?

d={'a':64, 'b':65, 'c':66, 'd':67}

print(d['e'])

 68
Classification: Internal

 0
 nan
 Error
In [ ]:
d={'a':64, 'b':65, 'c':66, 'd':67}
print(d['e'])
# Explanation: in the dictionary, there is no element 'e' in the keys of the
dictionary,
# trying to access value of a key that doesn't exist will give an error.
Question_5:

Keys

What will the following code return?

d={'a':64, 'b':65, 'c':66, 'd':67}

print(d.keys())

 [a, b, c, d]
 ('a', 'b', 'c', 'd')
 ['a':64, 'b':65, 'c':66, 'd':67]
 ['a', 'b', 'c', 'd']
 ('a':64, 'b':65, 'c':66, 'd':67)
In [ ]:
d={'a':64, 'b':65, 'c':66, 'd':67}
print(d.keys())
Question_6:

Values?

Dictionary can be seen as a map between two entities called keys and values. All the keys in the list
can be accessed by d.keys() where d is the dictionary. How are values accessed in the dictionary?

Assume name of the dictionary is d.

 d.vals
 d.vals()
 d.value()
 d.values()
 d.values
In [ ]:
d.values()
Classification: Internal

Question_7:

Deleting Key

Suppose dict_1 = {"Python'':40, "R'':45}. What command should be used to delete the entry?

 dict_1.delete('R':45)
 del dict_1['R']
 dict_1.delete('R')
 del dict_1('R':40)
In [ ]:
dict_1 = {'Python':40, 'R':45}
del dict_1["R"]
dict_1
Coding Exercise
Remove Duplicates

Description

Sometimes the data has few duplicate values which will affect the analysis done. In this problem, you
will be given a list. You have to find and delete the duplicates and print the updated list with no
duplicates.

Input:
A list of integers.

Output:
A list of integers, with duplicates removed if any.

Sample input_1:
[8, 9, 2, 2, 3, 4, 5, 2]

Sample output_1:
[8, 9, 2, 3, 4, 5]

Sample input_2:
[4, 4, 4, 4]

Sample output_2:
[4]

Note: the code will be case-Sensitive


Hint: if the length of the strings doesn't match, the strings are obviously not anagrams.
In [ ]:
Classification: Internal

import ast
in_list = ast.literal_eval(input())
dict1 = {}
for i in in_list:
if i not in dict1:
dict1[i] = 1
print(list(dict1.keys()))
In [ ]:
# To count the number of repeting numbers
import ast
in_list = ast.literal_eval(input())
dict1 = {}
for i in in_list:
if i not in dict1:
dict1[i] = 1
else:
dict1[i] += 1
print(dict1)
In [ ]:
# Solution_2: Here set can notbe uses because order will change
import ast
in_list = ast.literal_eval(input())
in_set = set(in_list)
in_set = list(in_set)
in_set
Dictionary And List

Description

You will be converting a dictionary, of string(keys) and list of string (values), to a list of strings. Please
check the sample input/output for clarification.

Input:
A dictionary with keys as strings and values as a list of strings.

Output:
A list of strings

Sample input_1:
{‘Mobile’: [‘Redmi’, ‘Samsung’, ‘Realme’], ‘Laptop’: [‘Dell’, ‘HP’], ‘TV’: [‘Videocon’, ‘Sony’] }

Sample output_1:
[‘Mobile_Redmi’, ‘Mobile_Samsung’, ‘Mobile_Realme’, ‘Laptop_Dell’, ‘Laptop_HP’, ‘TV_Videocon’,
‘TV_Sony’]

Sample input_2:
{ 'Pen': ['Gel', 'Ink', 'ball'], 'Mobile': ['Android', 'apple'] }
Classification: Internal

Sample output_2:
['Pen_Gel', 'Pen_Ink', 'Pen_ball', 'Mobile_Android', 'Mobile_apple']

In [ ]:
# Solution_1:
import ast
input_dict = ast.literal_eval(input())
final_list = []
for key in input_dict.keys():
for value in input_dict[key]:
final_list.append(key+"_"+value)
print(final_list)
In [ ]:
# upGrad String

# Description

# For the purpose of this question, we will define something called an upGrad
string.
# Note that this definition is not valid outside this question.
# A string upGrad string if the frequency of its characters is something like 1, 2,
3, 4, ....
# That is a character appears only once, another appears twice, another appears
thrice and so on.
# For example string '$yrr$ssrsr%' is a beautiful string since the frequency of y:1,
$:2, s:3, r:4,
# however string will not be beautiful since it has two characters (y and %) with
frequency 1.
# The frequency of characters should be of form 1, 2, 3, 4, 5... only.
# Given a string, can you determine if the string is upGrad string or no?

# Input:
# A string

# Output:
# Boolean depending whether the string is upGrad string or not<br><br>

# Sample input_1:
# $yrr$ssrsr

# Sample output_1:
# True

# Sample input_2:
# $yrr$ssrsr%

# Sample output_2:
# False

# Sample input_3:
# ab#ab#ab6a
Classification: Internal

# Sample output_2:
# True
In [ ]:
# Solution_1:
upgrad_str = input()
dict1 = {}

for key in upgrad_str:


if key not in dict1:
dict1[key] = 1
else:
dict1[key] += 1

vals = dict1.values()
n = len(dict1)
def upgrad_string(vals):
for i in range(1,n+1):
if i not in vals:
return False
return True

print(upgrad_string(vals))
In [ ]:
# Solution_2: using dict comprehension
upgrad_str = input()
dict1 = {}

for key in upgrad_str:


if key not in dict1:
dict1[key] = 1
else:
dict1[key] += 1

dict2 = {k:v for k, v in sorted(dict1.items(),key=lambda x: x[1])}


to_check = list(dict2.values())

if to_check == list(range(1,len(dict1)+1)):
print(True)
else:
print(False)
In [ ]:
# Solution_3: using dict and sorted function
upgrad_str = input()
dict1 = {}

for key in upgrad_str:


if key not in dict1:
dict1[key] = 1
else:
dict1[key] += 1

dict2 = dict(sorted(dict1.items(),key=lambda x: x[1]))


Classification: Internal

to_check = list(dict2.values())

if to_check == list(range(1,len(dict1)+1)):
print(True)
else:
print(False)
Balanced Brackets

Description

You will be given a string with a lot of brackets. You have to print if the brackets are balanced or not.
Remember, there are three types of brackets: ‘( )’, ‘{ }’ and ‘[ ]’.

Input:
A string

Output:
Yes, if the brackets are balanced.
No otherwise.

Sample input_1:
){[[]]}())()

Sample output_1:
No

Sample input_2:
{(){}}

Sample output_2:
Yes

In [1]:
# Solution:
in_str = input()
stack = []

for i in in_str:
if len(stack) == 0:
stack.append(i)
else:
if i == ')' and stack[-1] == '(':
stack.pop()
elif i == '}' and stack[-1] == '{':
stack.pop()
elif i == "]" and stack[-1] == '[':
stack.pop()
else:
Classification: Internal

stack.append(i)
if len(stack) == 0:
print("Yes")
else:
print("No")
){[[]]}())() No

You might also like