Advanced Python Interview Questions Flashcards

1
Q

What is the lambda function in Python?

A

A lambda function is an anonymous function (a function that does not have a name) in Python. To define anonymous functions, we use the ‘lambda’ keyword instead of the ‘def’ keyword, hence the name ‘lambda function’. Lambda functions can have any number of arguments but only one statement.

For example:

l = lambda x,y : x*y

print(a(5, 6))

Output: 30

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is self in Python?

A

Self is an object or an instance of a class. This is explicitly included as the first parameter in Python. On the other hand, in Java it is optional. It helps differentiate between the methods and attributes of a class with local variables.

The self variable in the init method refers to the newly created object, while in other methods, it refers to the object whose method was called.

Syntax:

Class A:

def func(self):

print(“Hi”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the difference between append() and extend() methods?

A

Both append() and extend() methods are methods used to add elements at the end of a list.

  • append(element): Adds the given element at the end of the list that called this append() method
  • extend(another-list): Adds the elements of another list at the end of the list that called this extend() method
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How does Python Flask handle database requests?

A

Flask supports a database-powered application (RDBS). Such a system requires creating a schema, which needs piping the schema.sql file into the sqlite3 command. Python developers need to install the sqlite3 command to create or initiate the database in Flask.

Flask allows to request for a database in three ways:

  • before_request(): They are called before a request and pass no arguments.
  • after_request(): They are called after a request and pass the response that will be sent to the client.
  • teardown_request(): They are called in a situation when an exception is raised and responses are not guaranteed. They are called after the response has been constructed. They are not allowed to modify the request, and their values are ignored.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is docstring in Python?

A

Python lets users include a description (or quick notes) for their methods using documentation strings or docstrings. Docstrings are different from regular comments in Python as, rather than being completely ignored by the Python Interpreter like in the case of comments, these are defined within triple quotes.

Syntax:

””” Using docstring as a comment.

This code add two numbers “””

x=7

y=9

z=x+y

print(z)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How is Multithreading achieved in Python?

A

Python has a multi-threading package ,but commonly not considered as good practice to use it as it will result in increased code execution time.

  • Python has a constructor called the Global Interpreter Lock (GIL). The GIL ensures that only one of your ‘threads’ can execute at one time.The process makes sure that a thread acquires the GIL, does a little work, then passes the GIL onto the next thread.
  • This happens at a very Quick instance of time and that’s why to the human eye it seems like your threads are executing parallely, but in reality they are executing one by one by just taking turns using the same CPU core.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is slicing in Python?

A

Slicing is a process used to select a range of elements from sequence data type like list, string and tuple. Slicing is beneficial and easy to extract out the elements. It requires a : (colon) which separates the start index and end index of the field. All the data sequence types List or tuple allows us to use slicing to get the needed elements. Although we can get elements by specifying an index, we get only a single element whereas using slicing we can get a group or appropriate range of needed elements.

Syntax:

List_name[start:stop]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is functional programming? Does Python follow a functional programming style? If yes, list a few methods to implement functionally oriented programming in Python.

A

Functional programming is a coding style where the main source of logic in a program comes from functions.

Incorporating functional programming in our codes means writing pure functions.

Pure functions are functions that cause little or no changes outside the scope of the function. These changes are referred to as side effects. To reduce side effects, pure functions are used, which makes the code easy-to-follow, test, or debug.

Python does follow a functional programming style. Following are some examples of functional programming in Python.

filter(): Filter lets us filter some values based on a conditional logic.

list(filter(lambda x:x>6,range(9))) [7, 8]

map(): Map applies a function to every element in an iterable. list(map(lambda x:x**2,range(5))) [0, 1, 4, 9, 16, 25]

reduce(): Reduce repeatedly reduces a sequence pair-wise until it reaches a single value.

from functools import reduce

reduce(lambda x,y:x-y,[1,2,3,4,5]) -13

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Which one of the following is not the correct syntax for creating a set in Python?

A
  1. set([[1,2],[3,4],[4,5]])
  2. set([1,2,2,3,4,5])
  3. {1,2,3,4}
  4. set((1,2,3,4))

Ans. set([[1,2],[3,4],[4,5]])

Explanation: The argument given for the set must be iterable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is monkey patching in Python?

A

Monkey patching is the term used to denote the modifications that are done to a class or a module during the runtime. This can only be done as Python supports changes in the behavior of the program while being executed.

The following is an example, denoting monkey patching in Python:

monkeyy.py

class X:

def func(self):

print “func() is being called”

The above module (monkeyy) is used to change the behavior of a function at the runtime as shown below:

import monkeyy

def monkey_f(self):

print “monkey_f() is being called”

replacing address of “func” with “monkey_f”

monkeyy.X.func = monkey_f

obj = monk.X()

calling function “func” whose address got replaced

with function “monkey_f()”

obj.func()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the difference between / and // operator in Python?

A
  • /: is a division operator and returns the Quotient value.

10/3

  1. 33
    * // : is known as floor division operator and used to return only the value of quotient before decimal

10//3

3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is pandas?

A

Pandas is an open source python library which supports data structures for data based operations associated with data analyzing and data Manipulation . Pandas with its rich sets of features fits in every role of data operation,whether it be related to implementing different algorithms or for solving complex business problems. Pandas helps to deal with a number of files in performing certain operations on the data stored by files.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are dataframes?

A

A dataframe refers to a two dimensional mutable data structure or data aligned in the tabular form with labeled axes(rows and column).

Syntax:

pandas.DataFrame( data, index, columns, dtype)

data: It refers to various forms like ndarray, series, map, lists, dict, constants and can take other DataFrame as Input.

index: This argument is optional as the index for row labels will be automatically taken care of by pandas library.

columns: This argument is optional as the index for column labels will be automatically taken care of by pandas library.

Dtype: refers to the data type of each column.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How to combine dataframes in pandas?

A

The different dataframes can be easily combined with the help of functions listed below:

  • Append():

This function is used for horizontal stacking of dataframes.

data_frame1.append(data_frame2)

  • concat(): This function is used for vertical stacking and best suites when the dataframes to be combined possess the same column and similar fields.
    pd. concat([data_frame1, data_frame2])
  • join(): This function is used to extract data from different dataframes which have one or more columns common.

data_frame1.join(data_frame2)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How do you identify missing values and deal with missing values in Dataframe?

A

Identification:

isnull() and isna() functions are used to identify the missing values in your data loaded into dataframe.

missing_count=data_frame1.isnull().sum()

Handling missing Values:

There are two ways of handling the missing values :

  1. Replace the missing values with 0

df[‘col_name’].fillna(0)

  1. Replace the missing values with the mean value of that column

df[‘col_name’] = df[‘col_name’].fillna((df[‘col_name’].mean()))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is regression?

A

Regression is termed as supervised machine learning algorithm technique which is used to find the correlation between variables and help to predict the dependent variable(y) based upon the independent variable (x). It is mainly used for prediction, time series modeling, forecasting, and determining the causal-effect relationship between variables.

Scikit library is used in python to implement the regression and all machine learning algorithms.

There are two different types of regression algorithms in machine learning :

Linear Regression: Used when the variables are continuous and numeric in nature.

Logistic Regression: Used when the variables are continuous and categorical in nature.

17
Q

What is classification?

A

Classification refers to a predictive modeling process where a class label is predicted for a given example of input data. It helps categorize the provided input into a label that other observations with similar features have. For example, it can be used for classifying a mail whether it is spam or not, or for checking whether users will churn or not based on their behavior.

These are some of the classification algorithms used in Machine Learning:

  • Decision tree
  • Random forest classifier
  • Support vector machine
18
Q

How do you split the data in train and test dataset in python?

A

This can be achieved by using the scikit machine learning library and importing train_test_split function in python as shown below:

Import sklearn.model_selection.train_test_split

test size =30% and train= 70 %

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=0).

19
Q

What is SVM?

A

Support vector machine (SVM) is a supervised machine learning model that considers the classification algorithms for two-group classification problems. Support vector machine is a representation of the training data as points in space are separated into categories with the help of a clear gap that should be as wide as possible.

20
Q

Write a code to get the indices of N maximum values from a NumPy array?

A

We can get the indices of N maximum values from a NumPy array using the below code:

import numpy as np

ar = np.array([1, 3, 2, 4, 5, 6])

print(ar.argsort()[-3:][::-1])

21
Q

What is the easiest way to calculate percentiles when using Python?

A

The easiest and the most efficient way you can calculate percentiles in Python is to make use of NumPy arrays and its functions.

Consider the following example:

import numpy as np
a = np.array([1,2,3,4,5,6,7])
p = np.percentile(a, 50) #Returns the 50th percentile which is also the median
print(p)

22
Q

Write a Python program to check whether a given string is a palindrome or not, without using an iterative method?

A

A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., madam, nurses run, etc.

Consider the below code:

def fun(string):
s1 = string
s = string[::-1]
if(s1 == s):
 return true
else:
 return false
print(fun(“madam”))
23
Q

Write a Python program to calculate the sum of a list of numbers?

A
def sum(num):
if len(num) == 1:
 return num[0] #with only one element in the list, the sum result will be equal to the element.
else:
 return num[0] + sum(num[1:])
print(sum([2, 4, 5, 6, 7]))
24
Q

Write a program in Python to execute the Bubble sort algorithm?

A

def bubbleSort(x):

n = len(x)

Traverse through all array elements

for i in range(n-1):

for j in range(0, n-i-1):

if x[j] > x[j+1] :

x[j], x[j+1] = x[j+1], x[j]

Driver code to test above

arr = [25, 34,47, 21, 22, 11,37]

bubbleSort(arr)

print (“Sorted array is:”)

for i in range(len(arr)):

print (“%d” %arr[i]),

Output:

11,21,22,25,34,37,47

25
Q

Write a program in Python to produce Star triangle?

A
def Star\_triangle(n):
 for x in range(n):
 print(' '\*(n-x-1)+'\*'\*(2\*x+1))

Star_triangle(9)

Output:

*
***
*****
*******
*********
***********
*************
***************
*****************

26
Q

Write a program to produce Fibonacci series in Python?

A

Fibonacci series refers to the series where the element is the sum of two elements prior to it.

n = int(input(“number of terms? “))
n1, n2 = 0, 1
count = 0

if n <= 0:
print(“Please enter a positive integer”)
elif n == 1:
print(“Fibonacci sequence upto”,terms,”:”)
print(n1)
else:
print(“Fibonacci sequence:”)
while count < n:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1

27
Q

Write a program in Python to check if a number is prime?

A

num = 13

if num > 1:

for i in range(2, int(num/2)+1):

if (num % i) == 0:

print(num, “is not a prime number”)

break

else:

print(num, “is a prime number”)

else:

print(num, “is not a prime number”)

Output:

13 is a prime number

28
Q

Write a sorting algorithm for a numerical dataset in Python?

A

code to sort a list in Python:

my_list = [“8”, “4”, “3”, “6”, “2”]

my_list = [int(i) for i in list]

my_list.sort()

print (my_list)

Output:

2,3,4,6,8

29
Q

Write a Program to print ASCII Value of a character in python?

A

x= ‘a’

print the ASCII value of assigned character stored in x

print(“ ASCII value of ‘” + x + “’ is”, ord(x))
Output: 65