Skip to content

Latest commit

 

History

History
733 lines (733 loc) · 48.6 KB

File metadata and controls

733 lines (733 loc) · 48.6 KB
Index Question Answer Type
1 What type of language is python ? Programming or Scripting ? Python is an interpreted, object-oriented, high-level programming language with dynamic semantic python-basic
 2 How is Python an interpreted language ?

An interpreted language is any programming language which is not in machine level code before runtime. 

Therefore, Python is an interpreted language.

python-basic
 3 What is pep 8 ? PEP stands for Python Enhancement Proposal. It is a set of rules that specify how to format Python code for maximum readability. python-basic
 4 What is namespace in Python ? A namespace is a naming system used to make sure that names are unique to avoid naming conflicts. python-basic
 5 What is PYTHONPATH ? 

It is an environment variable which is used when a module is imported. Whenever a module is imported,

PYTHONPATH is also looked up to check for the presence of the imported modules in various directories.

The interpreter uses it to determine which module to load.

python-basic
 6

What are python modules?

Name some commonly used built-in modules in Python?

Python modules are files containing Python code. This code can either be functions classes or variables. A Python module is a .py file containing executable code.

Some of the commonly used built-in modules are:

  • os
  • sys
  • math
  • random
  • data time
  • JSON
python-basic
 7 What are local variables and global variables in Python?

Global Variables:

Variables declared outside a function or in global space are called global variables. These variables can be accessed by any function in the program.

Local Variables:

Any variable declared inside a function is known as a local variable. This variable is present in the local space and not in the global space.

python-basic
 8 Is python case sensitive?

Yes. Python is a case sensitive language.

python-basic
 9 What is type conversion in Python?

Type conversion refers to the conversion of one data type iinto another.

int() – converts any data type into integer type

float() – converts any data type into float type

ord() – converts characters into integer

hex() – converts integers to hexadecimal

oct() – converts integer to octal

tuple() – This function is used to convert to a tuple.

set() – This function returns the type after converting to set.

list() – This function is used to convert any data type to a list type.

dict() – This function is used to convert a tuple of order (key,value) into a dictionary.

str() – Used to convert integer into a string.

complex(real,imag) – This functionconverts real numbers to complex(real,imag) number.

python-basic
 10 What are functions in Python?

A function is a block of code which is executed only when it is called. To define a Python function, the def keyword is used.

python-basic
 11 What is __init__?

__init__ is a method or constructor in Python. This method is automatically called to allocate memory when a new object/ instance of a class is created. All classes have the __init__ method.

python-basic
 12 What is a lambda function?

An anonymous function is known as a lambda function. This function can have any number of parameters but, can have just one statement.

python-basic
 13 What is self in Python?

Self is an instance or an object of a class. In Python, this is explicitly included as the first parameter. However, this is not the case in Java where it’s optional.  It helps to differentiate between the methods and attributes of a class with local variables.

python-basic
 14 How does break, continue and pass work?

Break - Allows loop termination when some condition is met and the control is transferred to the next statement.

Continue - Allows skipping some part of a loop when some specific condition is met and the control is transferred to the beginning of the loop.

Pass - Used when you need some block of code syntactically, but you want to skip its execution. This is basically a null operation. Nothing happens when this is executed.

python-basic
 15 What are python iterators?

Iterators are objects which can be traversed though or iterated upon.

python-basic
 16 What are the generators in python?

Functions that return an iterable set of items are called generators.

python-basic
 17 What does this mean: *args, **kwargs? And why would we use it?

We use *args when we aren’t sure how many arguments are going to be passed to a function, or if we want to pass a stored list or tuple of arguments to a function. **kwargs is used when we don’t know how many keyword arguments will be passed to a function, or it can be used to pass the values of a dictionary as keyword arguments. The identifiers args and kwargs are a convention, you could also use *bob and **billy but that would not be wise.

python-basic
 18 What are Python packages?

Python packages are namespaces containing multiple modules.

python-basic
 19 What are the built-in types of python?

Built-in types in Python are as follows –

  • Integers
  • Floating-point
  • Complex numbers
  • Strings
  • Boolean
  • Built-in functions
python-basic
 20 What is pickling and unpickling?

Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.

python-basic
 21 What is the difference between list and tuples in Python?

Lists are mutable. Lists are slower than tuples.

Tuples are immutable, Tuples are faster than list.

List is stored in two blocks of memory (One is fixed sized and the other is variable sized for storing data)

Tuple is stored in a single block of memory.

python data structure
 22 What is the difference between Python Arrays and lists?

Arrays and lists, in Python, have the same way of storing data. But, arrays can hold only a single data type elements whereas lists can hold any data type elements.

python data structure
 23 What is slicing function in Python ? How to slicing a array ?

Array slicing can be easily done following the Python slicing method.  Using array[ start : stop : step ]

Python also provides a function named slice() which returns a slice object containing the indices to be sliced.  – slice(start, stop[, step])

python data structure
 24 What does array[::-1] do?

It is used to reverse the order of an array or a sequence.

python data structure
 25 How can you randomize the items of a list in place in Python?

from random import shuffle

x = ['Keep', 'The', 'Blue', 'Flag', 'Flying', 'High']

shuffle(x)

python data structure
 26 How can you generate random numbers in Python?

import random
arr = random.random()

python data structure
 27 What is the difference between range & xrange?

For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. The only difference is that range returns a Python list object and x range returns an xrange object.

This means that xrange doesn’t actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators. That means that if you have a really gigantic range you’d like to generate a list for, say one billion, xrange is the function to use.

This is especially true if you have a really memory sensitive system such as a cell phone that you are working with, as range will use as much memory as it can to create your array of integers, which can result in a Memory Error and crash your program. It’s a memory hungry beast.

python data structure
 28 What is a dictionary in Python?

The built-in datatypes in Python is called dictionary. It defines one-to-one relationship between keys and values. Dictionaries contain pair of keys and their corresponding values. Dictionaries are indexed by keys.

python data structure
 29 What are negative indexes and why are they used?

The sequences in Python are indexed and it consists of the positive as well as negative numbers. The numbers that are positive uses ‘0’ that is uses as first index and ‘1’ as the second index and the process goes on like that.

The index for the negative number starts from ‘-1’ that represents the last index in the sequence and ‘-2’ as the penultimate index and the sequence carries forward like the positive number.

The negative index is used to remove any new-line spaces from the string and allow the string to except the last character that is given as S[:-1]. The negative index is also used to show the index to represent the string in correct order.

python data structure
 30 How to add values to a python array?

Elements can be added to an array using the append()extend() and the insert (i,x) functions.

python data structure
 31 How to remove values from a python array?

Array elements can be removed using pop() or remove() method. The difference between these two functions is that the former returns the deleted value whereas the latter does not.

python data structure
 32 How is memory managed in Python?
  1. Memory management in python is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have access to this private heap. The python interpreter takes care of this instead.
  2. The allocation of heap space for Python objects is done by Python’s memory manager. The core API gives access to some tools for the programmer to code.
  3. Python also has an inbuilt garbage collector, which recycles all the unused memory and so that it can be made available to the heap space.
python advanced
 33 What Is the Python Global Interpreter Lock (GIL)?

The Python Global Interpreter Lock or GIL, in simple words, is a mutex (or a lock) that allows only one thread to hold the control of the Python interpreter.

This means that only one thread can be in a state of execution at any point in time. The impact of the GIL isn’t visible to developers who execute single-threaded programs, but it can be a performance bottleneck in CPU-bound and multi-threaded code.

python advanced
 34 How is Multithreading achieved in Python ?
  1. Python has a multi-threading package but if you want to multi-thread to speed your code up, then it’s usually not a good idea to use it.
  2. Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure that only one of your ‘threads’ can execute at any one time. A thread acquires the GIL, does a little work, then passes the GIL onto the next thread.
  3. This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but they are really just taking turns using the same CPU core.
  4. All this GIL passing adds overhead to execution. This means that if you want to make your code run faster then using the threading package often isn’t a good idea.
python advanced
 35 What is the difference between deep and shallow copy?

Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Shallow copy allows faster execution of the program and it depends on the size of the data that is used.

Deep copy is used to store the values that are already copied. Deep copy doesn’t copy the reference pointers to the objects. It makes the reference to an object and the new object that is pointed by some other object gets stored. The changes made in the original copy won’t affect any other copy that uses the object. Deep copy makes execution of the program slower due to making certain copies for each object that is been called.

python advanced
 36 What is List Comprehension in Python ?

List comprehensions are used for creating new lists from other iterables. As list comprehensions return lists, they consist of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element.

For example : 

numbers = [1, 2, 3, 4]
squares = [n**2 for n in numbers]
python advanced
 37 Does python support multiple inheritance?

Multiple inheritance means that a class can be derived from more than one parent classes. Python does support multiple inheritance.

python advanced
 38 Explain Inheritance in Python with an example.

Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class.

They are different types of inheritance supported by Python:

  1. Single Inheritance – where a derived class acquires the members of a single super class.
  2. Multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 are inherited from base2.
  3. Hierarchical inheritance – from one base class you can inherit any number of child classes
  4. Multiple inheritance – a derived class is inherited from more than one base class.
python advanced
 39 What is Polymorphism in Python?

Polymorphism means the ability to take multiple forms. So, for instance, if the parent class has a method named ABC then the child class also can have a method with the same name ABC having its own parameters and variables. Python allows polymorphism.

python advanced
 40 Define encapsulation in Python?

Encapsulation means binding the code and the data together. A Python class in an example of encapsulation.

python advanced
 41 How do you do data abstraction in Python? Data Abstraction is providing only the required details and hiding the implementation from the world. It can be achieved in Python by using interfaces and abstract classes. python advanced
 42 Explain what Flask is and its benefits? Flask is a web microframework for Python based on “Werkzeug, Jinja2 and good intentions” BSD license. Werkzeug and Jinja2 are two of its dependencies. This means it will have little to no dependencies on external libraries.  It makes the framework light while there is a little dependency to update and fewer security bugs. python-mvc
 43 Explain what Django and its benefits ?

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source.

python-mvc
 44  Is Django better than Flask?

Django is a full-stack web framework, whereas Flask is a micro and lightweight web framework. The features provided by Django help developers to build large and complex web applications. On the other hand, Flask accelerates development of simple web applications by providing the required functionality.

Technically both are equally good and both contain their own pros and cons.

python-mvc
 45 Describe Django architecture.

Django MVT Pattern:

 

Developer provides the Model, the view and the template then just maps it to a URL and Django does the magic to serve it to the user.

python-mvc
46  Explain what is a Restful API

A RESTful API is an architectural style for an application program interface (API) that uses HTTP requests to access and use data. That data can be used to GET, PUT, POST and DELETE data types, which refers to the reading, updating, creating and deleting of operations concerning resources.

python-mvc
 47 Explain HTTP method GET,PUT,POST and DELETE

The POST verb is most-often utilized to **create** new resources.

The HTTP GET method is used to **read** (or retrieve) a representation of a resource.

PUT is most-often utilized for **update** capabilities, PUT-ing to a known resource URI with the request body containing the newly-updated representation of the original resource.

DELETE is used to **delete** a resource identified by a URI.

python-mvc
 48 Is python numpy better than lists?

Use python numpy array instead of a list because of the below three reasons:

  1. Less Memory
  2. Fast
  3. Convenient
python-data analyze
 49

How to get indices of N maximum values in a NumPy array?

import numpy as np

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

print(arr.argsort()[-3:][::-1])
python-data analyze
 50

How do you calculate percentiles with NumPy?

import numpy as np

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

p = np.percentile(a, 50)

python-data analyze
 51 How do loading a csv file or excel file using Pandas ?

pandas.read_csv or pandas.read_excel

python-data analyze
 52

Define Series in Pandas?

A Series is defined as a one-dimensional array that is capable of storing various data types. The row labels of series are called the index. By using a 'series' method, we can easily convert the list, tuple, and dictionary into series. A Series cannot contain multiple columns.

python-data analyze
 53

Define DataFrame in Pandas?

A DataFrame is a widely used data structure of pandas and works with a two-dimensional array with labeled axes (rows and columns) DataFrame is defined as a standard way to store data and has two different indexes, i.e., row index and column index. It consists of the following properties:

  • The columns can be heterogeneous types like int and bool.
  • It can be seen as a dictionary of Series structure where both the rows and columns are indexed. It is denoted as "columns" in the case of columns and "index" in case of rows.
python-data analyze
 54

What are the significant features of the pandas Library?

  • Memory Efficient
  • Data Alignment
  • Reshaping
  • Merge and join
  • Time Series
python-data analyze
 55

Define the different ways a DataFrame can be created in pandas?


We can create a DataFrame using following ways:

  • Lists
  • Dict of ndarrays
python-data analyze
 56

How to get frequency counts of unique items of a series?


Using value_counts() method

  1. import pandas as pd  
  2. import numpy as np  
  3. p= pd.Series(np.take(list('pqrstu'), np.random.randint(6, size=17)))  
  4. p = pd.Series(np.take(list('pqrstu'), np.random.randint(6, size=17)))  
  5. p.value_counts()  
python-data analyze
 57

How can we sort the DataFrame?

We can efficiently perform sorting in the DataFrame through different kinds:

  • By label - using sort_index()
  • By Actual value - using sort_values()
python-data analyze
 58

 How to convert String to date in Pandas ?


using method pd.to_datetime()

python-data analyze
 59

What is Data Aggregation in pandas ?

The main task of Data Aggregation is to apply some aggregation to one or more columns. It uses the following:

  • sum: It is used to return the sum of the values for the requested axis.
  • min: It is used to return a minimum of the values for the requested axis.
  • max: It is used to return a maximum values for the requested axis
python-data analyze
 60

Define GroupBy in Pandas ?

In Pandas, groupby() function allows us to rearrange the data by utilizing them on real-world data sets. Its primary task is to split the data into various groups. These groups are categorized based on some criteria. The objects can be divided from any of their axes.

DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, **kwargs)

python-data analyze
 61 How to join, merge 2 dataframes in pandas ? Using pd.merge or dataframe.concat method  
 62

What should a data analyst do with missing or suspected data?

  • Use data analysis strategies like deletion method, single imputation methods, and model-based methods to detect missing data.
  • Prepare a validation report containing all information about the suspected or missing data.
  • Scrutinize the suspicious data to assess their validity.
  • Replace all the invalid data (if any) with a proper validation code.
python-data analyze
 63 What is an Outlier , how do you find it ?

An outlier is a term commonly used by data analysts when referring to a value that appears to be far removed and divergent from a set pattern in a sample. There are two kinds of outliers – Univariate and Multivariate.

The two methods used for detecting outliers are:

  • Box plot method – According to this method, if the value is higher or lesser than 1.5*IQR (interquartile range), such that it lies above the upper quartile (Q3) or below the lower quartile (Q1), the value is an outlier.
  • Standard deviation method – This method states that if a value is higher or lower than mean ± (3*standard deviation), it is an outlier.
python-data analyze
 64

What is K-mean Algorithm?

K-mean is a partitioning technique in which objects are categorized into K groups. In this algorithm, the clusters are spherical with the data points are aligned around that cluster, and the variance of the clusters is similar to one another.

python-data analyze
 65

What is “Collaborative Filtering” ? 

Collaborative filtering is an algorithm that creates a recommendation system based on the behavioral data of a user. For instance, online shopping sites usually compile a list of items under “recommended for you” based on your browsing history and previous purchases. The crucial components of this algorithm include users, objects, and their interest.

python-data analyze
 66 What is “Time Series Analysis” ? Series analysis can usually be performed in two domains – time domain and frequency domain.
Time series analysis is the method where the output forecast of a process is done by analyzing the data collected in the past using techniques like exponential smoothening, log-linear regression method, etc.
python-data analyze
 67 What kind of model will you choose for Time Series problem ? 

Tradition model: Moving Average, exponential smoothing, ARIMA, SARIMA, Liner regression ect.

Machine Learning & Deep Learning: LigthGBM, LSTM, Fully connected NN ect.

python-data analyze
 68

Steps of a Data Analysis project.

  • The foremost requirement of a Data Analysis project is an in-depth understanding of the business requirements. 
  • The second step is to identify the most relevant data sources that best fit the business requirements and obtain the data from reliable and verified sources. 
  • The third step involves exploring the datasets, cleaning the data, and organizing the same to gain a better understanding of the data at hand. 
  • In the fourth step, Data Analysts must validate the data.
  • The fifth step involves implementing and tracking the datasets.
  • The final step is to create a list of the most probable outcomes and iterate until the desired results are accomplished.
python-data analyze
 69

Differentiate between variance and covariance.

Variance and covariance are both statistical terms. Variance depicts how distant two numbers (quantities) are in relation to the mean value. So, you will only know the magnitude of the relationship between the two quantities (how much the data is spread around the mean). On the contrary, covariance depicts how two random variables will change together. Thus, covariance gives both the direction and magnitude of how two quantities vary with respect to each other.

python-data analyze
 70

Explain “Normal Distribution.”

Normal distribution, better known as the Bell Curve or Gaussian curve, refers to a probability function that describes and measures how the values of a variable are distributed, that is, how they differ in their means and their standard deviations. In the curve, the distribution is symmetric. While most of the observations cluster around the central peak, probabilities for the values steer further away from the mean, tapering off equally in both directions.

python-data analyze
 71

Explain the difference between R-Squared and Adjusted R-Squared.

The R-Squared technique is a statistical measure of the proportion of variation in the dependent variables, as explained by the independent variables. The Adjusted R-Squared is essentially a modified version of R-squared, adjusted for the number of predictors in a model. It provides the percentage of variation explained by the specific independent variables that have a direct impact on the dependent variables.

python-data analyze