Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Exam Preparation Python - Jupyter Notebook

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

5/28/23, 4:56 PM Exam Preparation Python - Jupyter Notebook

Mapping Variables Description You're given two lists, the first of which contains the name of some people
and the second contains their corresponding 'response'. These lists have been converted to a dataframe.
Now, the values that the 'response' variable can take are ‘Yes’, ‘No’, and ‘Maybe’. Write a code to map these
variables to the values ‘1.0’, ‘0.0’, and ‘0.5’.

Note: It also might happen the the first letter of the three responses are not in uppercase, i.e. you might also
have the values 'yes', 'no', and 'maybe' in the dataframe. So make sure you handle that in your code.

Example: Input 1: ['Reetesh', 'Shruti', 'Kaustubh', 'Vikas', 'Mahima', 'Akshay'] ['No', 'Maybe', 'yes', 'Yes',
'maybe', 'Yes'] Output 1: 

localhost:8888/notebooks/Exam preperation/Course 1 Revision/Exam Preparation Python.ipynb 1/17


5/28/23, 4:56 PM Exam Preparation Python - Jupyter Notebook

In [2]:

# Reading the input


import ast,sys
#input_str = sys.stdin.read()
input_str = input()
inlist = input_str.split(" ")
#input_list = ast.literal_eval(input_str.split(" "))
# Storing the names in a variable 'name'
name = ast.literal_eval(inlist[0])
# Storing the responses in a variable 'repsonse'
response = ast.literal_eval(inlist[1])

# Importing pandas and converting the read lists to a dataframe. You can print
# the dataframe and run the code to see what it will look like
import pandas as pd
df = pd.DataFrame({'Name': name,'Response': response})

# Define a function to map the categorical variables to appropriate numbers


def response_map(x):
return x.map({'Yes': 1, 'yes': 1, 'No': 0, 'no': 0, 'Maybe': 0.5, 'maybe': 0.5})

# Apply the function to the 'Response' column of the dataframe


df[['Response']] = df[['Response']].apply(response_map)

# Print the final DataFrame


print(df)

Traceback (most recent call last):

File D:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactive
shell.py:3369 in run_code
exec(code_obj, self.user_global_ns, self.user_ns)

Input In [2] in <cell line: 8>


name = ast.literal_eval(inlist[0])

File D:\ProgramData\Anaconda3\lib\ast.py:62 in literal_eval


node_or_string = parse(node_or_string, mode='eval')

File D:\ProgramData\Anaconda3\lib\ast.py:50 in parse


return compile(source, filename, mode, flags,

File <unknown>

^
SyntaxError: unexpected EOF while parsing

Fibonacci Series Description Compute and display Fibonacci series upto n terms where n is a positive
integer entered by the user. You can go here to read about Fibonacci series. Sample Input: 5 Sample
Output: 0 1 1 2 3

localhost:8888/notebooks/Exam preperation/Course 1 Revision/Exam Preparation Python.ipynb 2/17


5/28/23, 4:56 PM Exam Preparation Python - Jupyter Notebook

In [ ]:

import ast,sys
import pandas as pd
import numpy as np

#n=int(input())
n=8
secondLast=0
last=1
if n>0:
print(secondLast)
if n>1:
print(last)
for i in range(3,n+1):
nextNumber=last+secondLast
print(nextNumber)
secondLast=last
last=nextNumber

Prime Numbers Description Determine whether a positive integer n is a prime number or not. Assume n>1.
Display “number entered is prime” if n is prime, otherwise display “number entered is not prime”. Sample
Input: 7 Sample Output: number entered is prime

In [ ]:

n=int(input())
out=True
for i in range(2,n):
if(n%i==0):
out=False
break
if out==True:
print("number entered is prime")
else:
print("number entered is not prime")

Armstrong number Description Any number, say n is called an Armstrong number if it is equal to the sum of
its digits, where each is raised to the power of number of digits in n. For example: 153=13+53+33

Write Python code to determine whether an entered three digit number is an Armstrong number or not.
Assume that the number entered will strictly be a three digit number. Print "True" if it is an Armstrong number
and print "False" if it is not. Sample Input: 153 Sample Output: True Execution Time Limit 10 seconds

localhost:8888/notebooks/Exam preperation/Course 1 Revision/Exam Preparation Python.ipynb 3/17


5/28/23, 4:56 PM Exam Preparation Python - Jupyter Notebook

In [ ]:

n=407
sum=0

for i in str(n):
num1 = int(i)
sum=sum+(num1*num1*num1)

if sum==n:
print("True")
else:
print("False")

In [ ]:

import sys,ast

n=int(input())
digits=list(map(int,str(n)))
num=sum(list(map(lambda x:x**3,digits)))
print(num==n)

Selecting dataframe columns Description Write a program to select all columns of a dataframe except the
ones specified. The input will contain a list of columns that you should skip. You should print the first five
rows of the dataframe as output where the columns are alphabetically sorted.

Sample Input: ['PassengerId', 'Pclass', 'Name', 'Sex','Embarked'] Sample Output:

Age Cabin Fare Parch SibSp Ticket

0 34.5 NaN 7.8292 0 0 330911 1 47.0 NaN 7.0000 0 1 363272 2 62.0 NaN 9.6875 0 0 240276 3 27.0 NaN
8.6625 0 0 315154 4 22.0 NaN 12.2875 1 1 3101298

In [ ]:

import pandas as pd
import sys , ast

df=pd.read_csv("https://media-doselect.s3.amazonaws.com/generic/X0kvr3wEYXRzONE5W37xWWYYA
cols= "['PassengerId','Pclass','Name','Sex','Embarked']"
cols_arr = ast.literal_eval(cols)

cols = list(df.columns[~df.columns.isin(cols_arr)])
df = df[cols]
df = df.sort_index(axis=1)
df.head()

Given two pandas series, find the position of elements in series2 in series1. You can assume that all
elements in series2 will be present in series1. The input will contain two lines with series1 and series2
respectively. The output should be a list of indexes indicating elements of series2 in series 1. Note: In the
output list, the indexes should be in ascending order. Sample Input: [1,2,3,4,5,6,7] [1,3,7] Sample Output:
[0,2,6]

localhost:8888/notebooks/Exam preperation/Course 1 Revision/Exam Preparation Python.ipynb 4/17


5/28/23, 4:56 PM Exam Preparation Python - Jupyter Notebook

In [ ]:

import pandas as pd
import numpy as np
import sys,ast

print(type(inp1))
series1 = list()
series2 = list()

inp1 = ast.literal_eval("[1,2,3,4,5,6,7]")
for s in inp1:
series1.append(int(s))

inp2 = ast.literal_eval("[1,3,7]")
for s in inp2:
series2.append(int(s))

print(series1)
print(series2)
out=list()

print("=======")
index=0
for i in series1:
for j in series2:
if(i==j):
out.append(index)
index=index+1

print(out)

Cleaning columns
Description For the given dataframe, you have to clean the "Installs" column and print its correlation with
other numeric columns of the dataframe.(print df.corr()) You have to do the following: 1. Remove characters
like ',' from the number of installs. 2. Delete rows where the Installs column has irrelevant strings like 'Free'
3. Convert the column to int type You can access the dataframe using the following URL in your Jupyter
notebook: https://media-
doselect.s3.amazonaws.com/generic/8NMooe4G0ENEe8z9q5ZvaZA7/googleplaystore.csv Note: You
should try this problem on your own Jupyter notebook before submitting. Do not clean any column other
than "Installs". Sample Output: Rating Installs Rating 1.000000 0.051355 Installs 0.051355 1.000000

localhost:8888/notebooks/Exam preperation/Course 1 Revision/Exam Preparation Python.ipynb 5/17


5/28/23, 4:56 PM Exam Preparation Python - Jupyter Notebook

In [ ]:

import pandas as pd
df = pd.read_csv("https://media-doselect.s3.amazonaws.com/generic/8NMooe4G0ENEe8z9q5ZvaZA

df.Installs = df.Installs.str.replace('+','').str.replace(',','')
df.Installs = df.Installs[df.Installs!='Free']
df.Installs = df[['Installs']].fillna(value=0)
df.Installs = df[['Installs']].astype(int)
#df.head()

print(df.corr())

Prime Numbers Description Given a positive integer n, your task is to print prime numbers up to the number
n, starting from 2. Note: n>=2 Sample Input: 5 Sample Output: 2 3 5

In [89]:

n=5
for x in [x for x in range(2, n+1) if all(x % y != 0 for y in range(2, x))]:
print(x)

2
3
5

In [90]:

input_num=10
for x in range(2,input_num+1):
flag=0
for y in range(2,x):
if(x%y==0):
flag=1
if(flag==0):
print(x,flag)

2 0
3 0
5 0
7 0

Substring in Alphabetical order Description There is some code written below for you. The Python program
is supposed to find the longest consecutive sub-string in alphabetical order in a given string. Note that the
order determination is case insensitive, i.e. the string "Ab" is considered to be in alphabetical order. You can
assume that the input will not have string where the number of possible consecutive sub-strings in
alphabetical order is 0. i.e. the input will not have a string like "zxec".

For example: Sample Input 1: Hello Sample Output 1: ello

Sample Input 2: HelloUpgrad Sample Output 2: elloU

localhost:8888/notebooks/Exam preperation/Course 1 Revision/Exam Preparation Python.ipynb 6/17


5/28/23, 4:56 PM Exam Preparation Python - Jupyter Notebook

The code given to you has errors and would not produce correct output. Your task is to correct the code
such that it gives desired result. Note: If there are two such substrings(of the longest length and in
alphabetical order) the string starting at a lower index should be printed i e in "abczabdz" "abcz" should be
In [ ]:

input_str = 'HelloUpgrad'
input_list = list(input_str)
alphabet_list = list('abcdefghijklmnopqrstuvwxyz')

index=0
output=list()
out=''
for i in range(0,len(input_list)):
for j in range(0,len(alphabet_list)):
if(input_list[i]==alphabet_list[j]):
#print(index,input_list[i],alphabet_list[j])
if(index<=j or index==0):
if(1==1):
output.append(input_list[i])
out=out+input_list[i]
#print(i,j,input_list[i])
index=j

print(out)

In [ ]:

inputstring="HelloUpgrad"
inputstring="abczabdz"
#inputstring="Hello"

prevChar = ""
curr_longest = ""
longest = ""

for char in inputstring:


print("p=>",prevChar.lower(),"ch=>",char.lower(),"lenCL=>",len(curr_longest),"lenLON

if (prevChar.lower()<=char.lower()):
print("i")
curr_longest += char
if len(curr_longest) > len(longest):
longest= curr_longest
else:
print("e")
curr_longest = char
prevChar = char
print(longest)

Reverse Pyramid Description Print an n level reverse pyramid as follows where n is a positive integer taken
as input. Each triangle will be made out of “*” symbols and the spaces will be filled by "#" symbols for each
row. For example, a 3 level reverse pyramid will look as follows:

#**# ####

localhost:8888/notebooks/Exam preperation/Course 1 Revision/Exam Preparation Python.ipynb 7/17


5/28/23, 4:56 PM Exam Preparation Python - Jupyter Notebook

Note: There should be no space between the stars. Remember to not print any extra character or spaces or
else your solution could be rejected. Sample input: 4 Sample output:

In [ ]:

input_n=4

input_num=(input_n*2)-1

for i in reversed(range(input_num+1)):
if(i%2!=0):
hsh=int((input_num-i)/2)+1
lbl = "#"*hsh+"*"*i+"#"*hsh
print(lbl)

In [ ]:

n=3
i=n-1
while i>-1:
print(n,i)
print('#'*(n-i-1) + '*'*(2*i+1)+'#'*(n-i-1))
i=i-1

Printing A Pyramid Description Print an n level pyramid as follows where n is a positive integer taken as
input. Each triangle will be made out of “*” symbols and the spaces will be filled by "#" symbols for each row.
For example, a 3 level pyramid will look as follows

#### #**#

Note: There should be no space between the stars. Remember to not print any extra character or spaces or
else your solution could be rejected. Sample input: 4 Sample output: ###### ##**## #*****#

n=4 i=1

while i<=n: print("#"(n-i)+""((i*2)-1)+"#"(n-i)) i=i+1

localhost:8888/notebooks/Exam preperation/Course 1 Revision/Exam Preparation Python.ipynb 8/17


5/28/23, 4:56 PM Exam Preparation Python - Jupyter Notebook

In [ ]:

Local Minima
Description
Given a list, your job is to find values which are surrounded by greater values on both
Such values are called local minima.

For example, the number '1' (present at index 1) is a local minimum


in the given series:
[2,1,2]

Note: Do not consider the first and last element of the list as local minima.
A point is local minima if the two elements surrounding it are greater than the number.
For example, there is not minim in this list: [1,2,2,2,1].

Input format:
The input will be a list of numbers.
Output Format:
The output should be a list of indices of the local minima stored in increasing order.

Hint: You can convert it into a numpy/pandas series to use the inbuilt functions from pa

Sample Input:
[2,1,3,4,1,5,6,1,7]
Sample Output:
[1, 4, 7]

Note: There are multiple ways to do this. Try to choose a method other than using simple

In [ ]:

input="[2,1,2,4,1,5,6,1,7]"
list1 = pd.Series(ast.literal_eval(input))
out=[]
for i in range(0,len(list1)):
if(i==0 or i==len(list1)-1):
continue
else:
if(list1[i]<list1[i-1] and list1[i]<list1[i+1]):
out.append(i)
print(out)

In [ ]:

s = "Naian"
s = s.lower()
# Check if the given string is a palindrome or not? Naian, Madam
t = s[::-1]
print(t,s)

localhost:8888/notebooks/Exam preperation/Course 1 Revision/Exam Preparation Python.ipynb 9/17


5/28/23, 4:56 PM Exam Preparation Python - Jupyter Notebook

In [ ]:

l = "I love Python"


# Return the reverse of the the given string: Python love I
s= l.split(" ")
o = " ".join(s[::-1])
print(o)

In [ ]:

l = ['A', 'B', 'C', 'D', 'E']


# Given the list, find the elements that are at even index position

for s in range(len(l)):
if(s%2==0):
print(l[s])

In [ ]:

l = ['A', 'B', 'C', 'D', 'E']


list(enumerate(l))

In [ ]:

l1 = ['a', 'b', 'c', 'd']


l2 = [1,2,2,4]
l3 = ['a','b','c','d']

print(list(zip(l1,l2)))
print(l1+l2)
print(l1.append(l3))

In [ ]:

l2 = [1,2,2,4]
print(set(l2)) # set will give the unique elements
sorted(list(l2))

localhost:8888/notebooks/Exam preperation/Course 1 Revision/Exam Preparation Python.ipynb 10/17


5/28/23, 4:56 PM Exam Preparation Python - Jupyter Notebook

In [ ]:

# ZIP

l1 = ['a', 'b', 'c', 'd']


l2 = [1,2,2,4]

# You are given with two list, l1 is having name of students


# while l2 is having their rank in the class.

# Find those students having the second lowest rank


l3 = list(zip(l1,l2))
print(l3)

second_lowest = sorted(set(l2))[1]

for name,st in l3:


#print(st,second_lowest)
if(st==second_lowest):
print(name)

In [ ]:

d = {'a':1, 'b':2, 'c':3, 'd': 4}


# Find out those keys which have even values
for key in d:
if(d[key]%2==0):
print(key, d[key])

for i, j in d.items():
if j%2==0:
print(i)

In [ ]:

l1 = ['a', 'b', 'c', 'd']


l2 = ['d', 'e', 'g', 'c']

# Find those elements which are present in both the lists


l3= list(set(l1) & set(l2))
print(l3)

list(set(l1).intersection(set(l2)))

In [ ]:

l1 = [1,2,3,4]
print(l1*2)
print(l1+l1)
#print(l1-l1)
#print(l1/l1)

arange
reshape
T : ROWS TO COLUMNS
Linspace
localhost:8888/notebooks/Exam preperation/Course 1 Revision/Exam Preparation Python.ipynb 11/17
5/28/23, 4:56 PM Exam Preparation Python - Jupyter Notebook

random
fill diagonal
fill
zeros, ones

In [ ]:

import numpy as np
a = np.arange(1, 10)
a

In [ ]:

b = a.reshape(3,3)
b

In [ ]:

b.T

In [ ]:

# linspace(star, end, number of elements between start and end)


np.linspace(1,100,25)

In [ ]:

import pandas as pd
df_1 = pd.DataFrame({"Name": ["Sumit", "Rajat", "Shukla", "Ruchi"], "Age": [18,22,25,28]
df_2 = pd.DataFrame({"Name": ["Ajay", "Atul", "Sanjay"], "Age": [18,22,25], "Edu":["B.Te

print(df_1.head())
print(df_2.head())

In [ ]:

# axis = 0: Rows
# aixs = 1: Columns
pd.concat([df_1, df_2], axis = 0)

In [ ]:

# axis = 0: Rows
# aixs = 1: Columns
pd.concat([df_1, df_2], axis = 1)

In [ ]:

# append is specific to rows only


df_1.append(df_2)

Alphabetic patterns Description Given a positive integer 'n' less than or equal to 26, you are required to print
the below pattern
localhost:8888/notebooks/Exam preperation/Course 1 Revision/Exam Preparation Python.ipynb 12/17
5/28/23, 4:56 PM Exam Preparation Python - Jupyter Notebook

Sample Input: 5

Sample Output : --------e-------- ------e-d-e------ ----e-d-c-d-e---- --e-d-c-b-c-d-e-- e-d-c-b-a-b-c-d-e --e-d-c-b-c-


d-e-- ----e-d-c-d-e---- ------e-d-e------ --------e--------

Sample Input : 3

Sample Output : ----c---- --c-b-c-- c-b-a-b-c --c-b-c-- ----c----

Please note that this question was asked in a Data Scientist interview. Execution Time Limit 25 seconds

In [ ]:

inp_num=3
inp_range = inp_num*2

alph='abcdefghijklmnopqrstuvwxyz'
alphlist = list(alph)
st_idx=inp_num
row_num=1
cols = (inp_num*2)-1 + (inp_range-2)
final_arr = []
final_rev_arr=[]

for r in range(0,inp_range):

if(r%2==0):

fwdlist=[]
rwslist=[]

for rn in range(0,row_num):
fwdlist.append(alphlist[st_idx-rn-1])
rwslist = fwdlist[::-1]
rwslist.pop(0)
outline = outline+"-".join(fwdlist)

row_num = row_num+1
midstring=''
if(len(fwdlist)>1):
midstring ="-".join(fwdlist)+"-"+"-".join(rwslist)
else:
midstring ="-".join(fwdlist)+"-".join(rwslist)
dash = cols - len(midstring)
dash = int(dash/2)

final_arr.append(dash*"-"+midstring+dash*"-")

final_rev_arr = final_arr[::-1]
final_rev_arr.pop(0)

arr = final_arr + final_rev_arr


for a in arr:
print(a)

Armstrong number Description Any number, say n is called an Armstrong number if it is equal to the sum of
its digits, where each is raised to the power of number of digits in n. For example: 153=13+53+33

localhost:8888/notebooks/Exam preperation/Course 1 Revision/Exam Preparation Python.ipynb 13/17


5/28/23, 4:56 PM Exam Preparation Python - Jupyter Notebook

Write Python code to determine whether an entered three digit number is an Armstrong number or not.
Assume that the number entered will strictly be a three digit number. Print "True" if it is an Armstrong number
and print "False" if it is not. Sample Input: 153 Sample Output: True Execution Time Limit 10 seconds

In [26]:

import numpy as np
n = "153"
numlist = n.strip()
power = int(len(n))
sum=0

for i in numlist:
sum = sum + (int(i)**power)

if(sum==int(n)):
print("True")
else:
print("False")

3
True

Fibonacci Series Description Compute and display Fibonacci series upto n terms where n is a positive
integer entered by the user. You can go here to read about Fibonacci series. Sample Input: 5 Sample
Output: 0 1 1 2 3

In [51]:

n = 7

last=1
second_last=0

if(n==0 or n==1):
print(second_last)
if(n>1):
print(second_last)
print(last)

for i in range(2,n):

sum = last+second_last
second_last = last
last = sum
print(sum)

0
1
1
2
3
5
8

Sum of Primes Description Write python code to find the sum of prime numbers from 2 to n where n is a
positive integer entered by the user.

localhost:8888/notebooks/Exam preperation/Course 1 Revision/Exam Preparation Python.ipynb 14/17


5/28/23, 4:56 PM Exam Preparation Python - Jupyter Notebook

Note: n can be non-prime or prime. You have to find sum of primes till n and not sum of n prime numbers.
i.e. for input 10, output should be 17.

Hint: You can try using lambda functions and comprehensions to reduce the lines of code you have to write.

Input: A positive integer n.

Output: A integer denoting the sum of primes less than or equal to n

Sample Input:

Sample Output:

10

In [124]:

n=10

sum=0
primelist=[]

for x in range(2,n+1):
isPrime=1
for y in range(2,x):
if(x%y==0):
isPrime=0
break;
if(isPrime==1):
sum=sum+x

print(sum)
'''sum=0
for x in [x for x in range(2, n+1) if all(x % y != 0 for y in range(2, x))]:
print(x,y)
sum=sum+x
print(sum)
'''

17

Out[124]:

'sum=0\nfor x in [x for x in range(2, n+1) if all(x % y != 0 for y in rang


e(2, x))]:\n print(x,y)\n sum=sum+x\nprint(sum)\n'

Generalised Chocolate Description Earlier you solved the chocolate problem where Sanjay had m rupees
and cost of each chocolate was c rupees. Shopkeeper gave away one chocolate for three wrappers. In this
problem lets generalise the question saying, Sanjay has m rupees, each chocolate costs c rupees,
shopkeeper will give away k chocolates for w wrappers. Can you find now how many chocolates Sanjay will
be able to eat?

Input: 4 integers separated by commas in order m c w k

integers c and w will be >0

integers m and k will be >=0

localhost:8888/notebooks/Exam preperation/Course 1 Revision/Exam Preparation Python.ipynb 15/17


5/28/23, 4:56 PM Exam Preparation Python - Jupyter Notebook

integer k will be <w

Output: An integer denoting number of chocolates Sanjay will be able to get.

Sample input:

15, 2, 3, 1

Sample output:

10

Explanation:

Sanjay has 15 rupees, buys 7 chocolates for 2 rupees each.

Sanjay now has 7 wrappers, exchanges 6 of them for 2 more chocolates.

Sanjay now has 3 wrappers and exchanges them for 1 more chocolate making a total of 10 chocolates

Sample input:

15, 2, 3, 2

Sample output:

17

Explanation:

Sanjay has 15 rupees, buys 7 chocolates for 2 rupees each.

Sanjay now has 7 wrappers, exchanges 6 of them for 4 more chocolates.

Sanjay now has 5 wrappers and exchanges 3 of them for 2 more chocolates.

Sanjay now has 4 wrappers and exchanges 3 of them for 2 more chocolates.

Sanjay now has 3 wrappers and exchanges them for 2 chocolates making a total of 17 chocolates.

In [ ]:

In [ ]:

In [ ]:

In [ ]:

localhost:8888/notebooks/Exam preperation/Course 1 Revision/Exam Preparation Python.ipynb 16/17


5/28/23, 4:56 PM Exam Preparation Python - Jupyter Notebook

In [ ]:

Type Markdown and LaTeX: 𝛼2

localhost:8888/notebooks/Exam preperation/Course 1 Revision/Exam Preparation Python.ipynb 17/17

You might also like