Python

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

What is main function in python? How do you invoke it?

def main(): print("Hi Interviewbit!") if __name__=="__main__": main()

Self

define an instance of an object of a class. In Python, it is explicitly used as the first parameter, unlike in Java where it is optional. It helps in distinguishing between the methods and attributes of a class from its local variables

response.json()

deserialized JSON content from json.loads()

How will you combine different pandas dataframes?

df1.append(df2): - horizontally pd.concat([df1, df2]) - vertically df1.join(df2)

Can you get items of series A that are not available in another series B?

df1=df1[~df1.isin(df2)]

Are access specifiers used in python?

does not make use of access specifiers specifically like private, public, protected, etc. However, it does not deprive this to any variables. It has the concept of imitating the behaviour of variables by making use of a single (protected) or double underscore (private) as prefixed to the variable names. By default, the variables without prefixed underscores are public.

To delete row/column from dataframe:

drop() method is used to delete row/column from dataframe.

break

ends the execution of loop and skips any code inside the loop body

What to use to find substring at end of text?

endswith

. What are Python namespaces?

ensures that object names in a program are unique and can be used without any conflict. Python implements these namespaces as dictionaries with 'name as key' mapped to a corresponding 'object as value'. This allows for multiple namespaces to use the same name and map it to a separate object. A few examples of namespaces are as follows:

What is PYTHONPATH in Python?

environment variable which you can set to add additional directories where Python will look for modules and packages. This is especially useful in maintaining Python libraries that you do not wish to install in the global default location.

What are decorators in Python?

essentially functions that add functionality to an existing function in Python without changing the structure of the function itself. They are represented the @decorator_name in Python and are called in a bottom-up fashion. For example:

How will you read CSV data into an array in NumPy?

from numpy import genfromtxt csv_data = genfromtxt('sample_file.csv', delimiter=',')

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) print(x)

What are generators in Python?

functions that return an iterable collection of items, one at a time, in a set manner. Generators, in general, are used to create iterators with a different approach. They employ the use of yield keyword rather than return to return a generator object.

How is memory managed in Python?

handled by the Python Memory Manager. The memory allocated by the manager is in form of a private heap space dedicated to Python. All Python objects are stored in this heap and being private, it is inaccessible to the programmer. Though, python does provide some core API functions to work upon the private heap space.

What is the use of help() and dir() functions?

help() function in Python is used to display the documentation of modules, classes, functions, keywords, etc. If no parameter is passed to the help() function, then an interactive help utility is launched on the console.dir() function tries to return a valid list of attributes and methods of the object it is called upon. It behaves differently with different objects, as it aims to produce the most relevant data, rather than the complete information.

What's the difference between a tuple and a list?

hold a list of values. Tuples are immutable and can't be change.

How to test whether a sub-string is anywhere inside a text you've been handed?

if "word" in text

Are strings mutable?

immutable, which means that you can't change a string after you created it.

Write a program for counting the number of every character of a given text file.

import collections import pprint with open("sample_file.txt", 'r') as data: count_data = collections.Counter(data.read().upper()) count_value = pprint.pformat(count_data) print(count_value

How will you find the nearest value in a given numpy array?

import numpy as np def find_nearest_value(arr, value): arr = np.asarray(arr) idx = (np.abs(arr - value)).argmin() return arr[idx] #Driver code arr = np.array([ 0.21169, 0.61391, 0.6341, 0.0131, 0.16541, 0.5645, 0.5742]) value = 0.52 print(find_nearest_value(arr, value)) # Prints 0.5645

Define pandas dataframe.

import pandas as pd dataframe = pd.DataFrame( data, index, columns, dtype)

While importing data from different sources, can the pandas library recognize dates?

import pandas as pd from datetime import datetime dateparser = lambda date_val: datetime.strptime(date_val, '%Y-%m-%d %H:%M:%S') df = pd.read_csv("some_file.csv", parse_dates=['datetime_column'], date_parser=dateparser)

Dunder or special methods

inbuilt methods. So, len() finds __len__

None

is an indicator for the absence of a value

How Python is interpreted?

is not interpreted or compiled. Interpreted or compiled is the property of the implementation. Python is a bytecode(set of interpreter readable instructions) interpreted generally.

What compares memory location of two values

is or is not

How will you check if a class is a child of another class?

issubclass() provided by python. The method tells us if any class is a child of another class by returning true or false accordingly.

iterdir

iterates over the files in directory

pass

keyword is generally used as a placeholder while building out your code functionality

Why do you use the zip() method in Python?

map the corresponding index of multiple containers so that we can use them using as a single unit.

What is __init__?

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.

Write a lambda

mul = lambda a, b : a * b print(mul(2, 5)) # output => 10

What are lambda functions?

mul_func = lambda x,y : x*y print(mul_func(6, 4)) # Output: 24

Pickling:

name of the serialization process in Python. Any object in Python can be serialized into a byte stream and dumped as a file in the memory. The process of pickling is compact but pickle objects can be compressed further. Moreover, pickle keeps track of the objects it has serialized and the serialization is portable across versions. The function used for the above process is pickle.dump().

What are iterators in Python?

objects with which we can iterate over iterable objects like lists, strings, etc.

What is monkey patching in Python?

only refers to dynamic modifications of a class or module at run-time.

How will you get the items that are not common to both the given series A and B?

p_union = pd.Series(np.union1d(df1, df2)) # union of series p_intersect = pd.Series(np.intersect1d(df1, df2)) # intersection of series

How will you find the shape of any given NumPy array?

print("2-D Array Shape: ", arr_two_dim.shape)

How can you generate random numbers?

print(random.randrange(5,100,2))

Deserialization

process of decoding the data that is in ie JSON format into native data type.

Create Virtual Env

python -m venv venv

serialization

refers to transforming it into a format that can be stored, so as to be able to deserialize it, later on, to obtain the original object.

requests package

send HTTP compliant requests using simple Python. It also allows you to easily access response data and work with information that is returned.

continue

skips the rest of the current iteration of your loop, jumps back to the beginning of the loop and next iteration, but doesn't quit

Explain split(), sub(), subn() methods of "re" module in Python.

split() - uses a regex pattern to "split" a given string into a list. sub() - finds all substrings where the regex pattern matches and then replace them with a different string subn() - it is similar to sub() and also returns the new string along with the no. of replacements.

Continue

terminates the current iteration of the statement, skips the rest of the code in the current iteration and the control flows to the next iteration of the loop.

What is "Call by Value" in Python?

the argument whether an expression or a value gets bound to the respective variable in the function. Python will treat that variable as local in the function-level scope. Any changes made to that variable will remain local and will not reflect outside the function.

Can you easily check if all characters in the given string is alphanumeric?

"abdc1321".isalnum() #Output: True

How to add new column to pandas dataframe?

#To add new column third df['third']=pd.Series([10,20,30],index=['a','b','c'])

s = "plumage" s[0:4:2]

#pu and every two steps

*args

*args is a special syntax used in the function definition to pass variable-length arguments. "*" means variable length and "args" is the name used by convention. You can use any other.

What is the starting index of Python?

0

Is Python list a linked list?

A Python list is a variable-length array which is different from C-style linked lists. Internally, it has a contiguous array for referencing to other objects and stores a pointer to the array variable and its length in the list head structure.

How do you access parent members in the child class?

By using Parent class name: You can use the name of the parent class to access the attributes as shown in the example below: By using super(): The parent class members can be accessed in child class using the super keyword.

Static Typing

Data Types are checked before execution.

Dynamic Typing

Data Types are checked during execution.

What is introspection/reflection and does Python support it?

Examine an object at runtime. dir(), type(), isinstance(), setattr(), getattr()

How will you delete indices, rows and columns from a dataframe?

Execute del df.index.name for removing the index by name. Alternatively, the df.index.name can be assigned to None.

Define GIL.

Global Interpreter Lock. This is a mutex used for limiting access to python objects and aids in effective thread synchronization by avoiding deadlocks. GIL helps in achieving multitasking (and not parallel computing). The following diagram represents how GIL works.

What is a dict and what's its most important limitation?

Hash map. It store key-values. The keys must be hashable

Explain the use of decorators.

Modify or inject code in functions or classes. You crap a class or function so that the piece of code can be executated before or after th original code. Decorators can be used for checking permission, modify or track arguments, logging calls.

Can you create a series from the dictionary object in pandas?

One dimensional array capable of storing different data types is called a series. We can create pandas series from a dictionary object as shown below: series_obj = pd.Series(dict_info)

What is the difference between response.content vs response.text

One returns the data in bytes and then other in str

What can list comprehensions good for?

Performing mathematical operations on the entire list Performing conditional filtering operations on the entire list Combining multiple lists into one Flattening a multi-dimensional list

object-oriented programming language

Programs include class and method definitions.

num_1=5 num_2=5 num_1 is num_2

Python Caches Small Immutable Objects

What are Dict and List comprehensions?

Python comprehensions, like decorators, are syntactic sugar constructs that help build altered and filtered lists, dictionaries, or sets from a given list, dictionary, or set. Using comprehensions saves a lot of time and code that might be considerably more verbose (containing more lines of code). Let's check out some examples, where comprehensions can be truly beneficial:

Explain how to delete a file in Python?

Use command os.remove(file_name)

How will you efficiently load data from a text file?

We can use the method numpy.loadtxt() which can automatically read the file's header and footer lines and the comments if any. This method is highly efficient and even if this method feels less efficient, then the data should be represented in a more efficient format such as CSV etc. Various alternatives can be considered depending on the version of NumPy used.

Explain split() and join() functions in Python?

You can use split() function to split a string based on a delimiter to a list of strings. You can use join() function to join a list of strings based on a delimiter to give a single string.

After creating a VE what do you need to do?

You need to activate it

Using list comprehension, print the odd numbers between 0 and 100.

[a for a in range(0,100) if a%2]

What does the __ Name __ do in Python?

a unique variable. Since Python doesn't expose the main() function, so when its interpreter gets to run the script, it first executes the code which is at level 0 indentation. To see whether the main() gets called, we can use the __name__ variable in an if clause compares with the value "__main__."

Shallow Copy

bit-wise copy of an object. The copied object created has an exact copy of the values in the original object. If either of the values is a reference to other objects, just the reference addresses for the same are copied.

What is the difference between Python Arrays and lists?

Arrays in python can only contain elements of same data types i.e., data type of array should be homogeneous. It is a thin wrapper around C language arrays and consumes far less memory than lists. Lists in python can contain elements of different data types i.e., data type of lists can be heterogeneous. It has the disadvantage of consuming large memory.

What is the purpose of "end" in Python?

Python's print() function always prints a newline in the end. The print() function accepts an optional parameter known as the 'end.' Its value is '\n' by default. We can change the end character in a print statement with the value of our choice using this parameter.

repr

Similar to str. But, The resulting string is intended more as a debugging aid for developers. And for that it needs to be as explicit as possible about what this object is. Kind of includes the type too

What is Scope Resolution in Python?

Sometimes objects within the same scope have the same name but function differently. In such cases, scope resolution comes into play in Python automatically.

Break

The break statement terminates the loop immediately and the control flows to the statement after the body of the loop.

Difference between == and is

The comparison operator == checks for the same values, and the identity operator is checks for whether they are the same object in memory

How are NumPy arrays advantageous over python lists?

The list data structure of python is very highly efficient and is capable of performing various functions. But, they have severe limitations when it comes to the computation of vectorized operations which deals with element-wise multiplication and addition. The python lists also require the information regarding the type of every element which results in overhead as type dispatching code gets executes every time any operation is performed on any element. This is where the NumPy arrays come into the picture as all the limitations of python lists are handled in NumPy arrays. Additionally, as the size of the NumPy arrays increases, NumPy becomes around 30x times faster than the Python List. This is because the Numpy arrays are densely packed in the memory due to their homogenous nature. This ensures the memory free up is also faster.

What is "Call by Reference" in Python?

and "pass-by-reference" interchangeably. When we pass an argument by reference, then it is available as an implicit reference to the function, rather than a simple copy. In such a case, any modification to the argument will also be visible to the caller. This scheme also has the advantage of bringing more time and space efficiency because it leaves the need for creating local copies. On the contrary, the disadvantage could be that a variable can get changed accidentally during a function call. Hence, the programmers need to handle in the code to avoid such uncertainty.

Explain *args and **kwargs

args is a tuple or kwargs is a dict

Protected attributes

attributes defined with an underscore prefixed to their identifier eg. _sara. They can still be accessed and modified from outside the class they are defined in but a responsible developer should refrain from doing so.

What is a callable

call function or an object implementing the __call__ special method

What is a generator?

callable object that acts as a iterable

metaclass

classes are instances of something - a metaclass

if __name__ == "__main__:

code that protects users from accidentally invoking the script when they didn't intend to

Unpickling:

complete inverse of pickling. It deserializes the byte stream to recreate the objects stored in the file and loads the object to memory. The function used for the above process is pickle.load().

What do you understand by reindexing in pandas?

conforming a dataframe to a new index with optional filling logic. If the values are missing in the previous index, then NaN/NA is placed in the location. A new object is returned unless a new index is produced that is equivalent to the current one. The copy value is set to False. This is also used for changing the index of rows and columns in the dataframe.

What is pickling/unpickling?

converting an object to a string representation in python. Generally used for caching and transferring objects

Deep Copy

copies all values recursively from source to target object, i.e. it even duplicates the objects referenced by the source object.

Yielding

crucial in applications where memory is a constraint. Creating a static list as in range() can lead to a Memory Error in such conditions, while, xrange() can handle it optimally by using just enough memory for the generator (significantly less in comparison).

What is the difference between .py and .pyc files?

the source code of a program. Whereas, .pyc file contains the bytecode of your program. We get bytecode after compilation of .py file (source code). .pyc files are not created for all the files that you run. It is only created for the files that you import.

Which is faster tuple or list?

tuple

Why is finalize used?

used for freeing up the unmanaged resources and clean up before the garbage collection method is invoked. This helps in performing memory management tasks.

**kwargs

used in the function definition to pass variable-length keyworded arguments. Here, also, "kwargs" is used just by convention. You can use any other name. Keyworded argument means a variable that has a name when passed to a function. It is actually a dictionary of the variable names and its value.

How will you identify and deal with missing values in a dataframe?

using the isnull() and isna() methods. missing_data_count=df.isnull().sum() df['column_name'].fillna(0)


Set pelajaran terkait

CHAPTER FOUR: TAXES, RETIREMENT, AND OTHER INSURANCE CONCEPTS

View Set

Lab 1.2: Networking Topologies and Characteristics

View Set

Character and Culture in Literature

View Set