python 50 q

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Implement depth first search (DFS) in Python

# Using a Python dictionary to act as an adjacency listgraph = { 'A' : ['B','C'], 'B' : ['D', 'E'], 'C' : ['F'], 'D' : [], 'E' : ['F'], 'F' : []}...dfs(visited, graph, 'A')

What are Python decorators?

A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate. e.g. use @[decorator] above a 'def' could have the same effect

!!! How would you make a deep copy in Python?

A deep copy refers to cloning an object. When we use the = operator, we are not cloning the object; instead, we reference our variable to the same object (a.k.a. shallow copy). This means that changing one variable's value affects the other variable's value because they are referring (or pointing) to the same object. This difference between a shallow and a deep copy is only applicable to objects that contain other objects, like lists and instances of a class. To make a deep copy (or clone) of an object, we import the built-in copy module in Python. This module has the deepcopy() method which simplifies our task. !!!nums = oldnums (one change, the other one change too) To make a new copy: (change the newone oldone wont change) new_list = old_list.copy() new_list = list(old_list) import copy new_list = copy.copy(old_list) import copy new_list = copy.deepcopy(old_list) P3 newlist = [*mylist]

Difference Between list and tuple

A list consists of mutable objects. (objects which can be changed after creation) List has a large memory LKist is sotord in two blocks of memoryu ( oine is fixed sized and the other is vcarable sized for store ing data) Creaeting a list is slower beciase two memeoryyu bnloicks need to besaccessed. Anelement in a list fcan be removed aor repalced. A kist has data store sin [] brackets for exampoles [1,2,3] A tuple consists of immiutable objects (objectgs whiuch adcann ot change afrter creasuioin) Tuple has a small memory Tuyple ios sotred in a single bloick of memroryu Crteating a tuiple is faster than creatring a slist Anelement is a tiple cannnoit be removed or replaced. Atuyple has data stopre in () brakjcckeetes. Fore exaomple (1,m2,3)

How would you convert a list into a tuple?

All we have to do is create a tuple with three elements. The first element of the tuple is the first element of the list, which can be found using my_list[0]. The second element of the tuple is the last element in the list. my_list[len(my_list) - 1] will give us this element. We could also have used the pop() method, but that would alter the list.

How is try/except used in Python?

An exception is an error that occurs while the program is executing. When this error occurs, the program will stop and generate an exception which then gets handled in order to prevent the program from crashing. The exceptions generated by a program are caught in the try block and handled in the except block. Try: Lets you test a block of code for errors. Except: Lets you handle the error.

Explain the difference between a generator and an iterator in Python.

An iterator in Python serves as a holder for objects so that they can be iterated over; a generator facilitates the creation of a custom iterator. Generator:Implemented using a function. Iterator:Implemented using a class. Generator: Uses the yield keyword. Does not use the yield keyword. Generator: Usage results in a concise code. Iterator:Usage results in a relatively less concise code. Generator: All the local variables before the yield statements are stored. Iterator:No local variables are used.

What is dictionary comprehension?

Dictionary comprehension is one way to create a dictionary in Python. It creates a dictionary by merging two sets of data which are in the form of either lists or arrays. The data of one of the two lists/arrays will act as the keys of the dictionary while the data of the second list/array will act as the values. Each key acts as a unique identifier for each value, hence the size of both lists/arrays should be the same. Here we'll look at simple merging: Simple merging is merging or combining two lists without any restrictions. In other words, it is the unconditional merging. rollNumbers =[122,233,353,456] names = ['alex','bob','can', 'don'] NewDictionary={ i:j for (i,j) in zip (rollNumbers,names)} print(NewDictionary) opt: {456: 'don', 233: 'bob', 122: 'alex', 353: 'can'}

Explain the differences between Flask and Django

Django is a Python web framework that offers an open-source, high-level framework that "encourages rapid development and clean, pragmatic design." It's fast, secure, and scalable. Django offers strong community support and detailed documentation. Flask is minimalistic and lightweight, meaning that you add extensions and libraries that you need as you code without automatically being provided with it by the framework.it's un-opinionated

Explain the difference between range() and 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. The only difference is that range returns a Python list object and xrange 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.

What are global and local 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.

How would you convert a list to an array?

Here we'll be using numpy.array(). This function of the numpy library takes a list as an argument and returns an array that contains all the elements of the list. See the example below:

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: Single Inheritance - where a derived class acquires the members of a single super class. Multi-level inheritance - a derived class d1 in inherited from base class base1, and d2 are inherited from base2. Hierarchical inheritance - from one base class you can inherit any number of child classes Multiple inheritance - a derived class is inherited from more than one base class.

How would you check if a key exists in a Python dictionary?

It is a safe practice to check whether or not the key exists in the dictionary prior to extracting the value of that key. For that purpose, Python offers two built-in functions: has_key() The has_key method returns true if a given key is available in the dictionary; otherwise, it returns false. if-in statement This approach uses the if-in statement to check whether or not a given key exists in the dictionary.

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.

How would you achieve memoization in Python?

Memoization can be achieved through Python decorators

How is memory managed in Python?

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. 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. 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.

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.

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 for polymorphism

How do you achieve multithreading in Python?

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. 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. 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. 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.

What is the difference between an array and a list?

Python list are very fleexible and can hold arbitrary data. list are a part of python ;s syusmtax so they do not need to be decalred first klist can also be resized quickly in a tume efficiernt m,ammer this ios because pythjon initializes some extrea elements ion the list at initializtrion. lists can hold heterogeneous data. M<athematicalk funtions cannot be directly applied to list instead they have to be individually apoplied to each element listr consime more meomory as theyare allocated a few extera elements to allow for quicker aoppmnend of tiewms Pythoin arrays are jhust a thguinkj rapper on C array.s Arrays nbeed tio first be imported or declared foreom ohter libraries,.(nu oy) Arrays canbjot be resizzed, IOnstead an array;s vaklues would bneed to be copied to anohber larger arrauy. Arrays can onlyu stoer homogenous da5ta5. they ahve avalues with uniforma data types arrauy oare speciafllu optimzied for arithmetic computatioms. Since arrays stay the zied that theya were when they were first oinitialized, theya re compact.

What are Python modules?

Python module is a Python file containing a set of functions and variables to be used in an application. The variables can be of any type (arrays, dictionaries, objects, etc.) Modules can be either: Built in User-defined Benefits of modules in Python There are a couple of key benefits of creating and using a module in Python: Structured Code Code is logically organized by being grouped into one Python file which makes development easier and less error-prone. Code is easier to understand and use. Reusability Functionality defined in a single module can be easily reused by other parts of the application. This eliminates the need to recreate duplicate code.

What advantages do NumPy arrays offer over (nested) Python lists?

Python's lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion, appending, and concatenation, and Python's list comprehensions make them easy to construct and manipulate. They have certain limitations: they don't support "vectorized" operations like elementwise addition and multiplication, and the fact that they can contain objects of differing types mean that Python must store type information for every element, and must execute type dispatching code when operating on each element. NumPy is not just more efficient; it is also more convenient. You get a lot of vector and matrix operations for free, which sometimes allow one to avoid unnecessary work. And they are also efficiently implemented. NumPy array is faster and You get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, etc.

Explain the differences between Python 2 and Python 3

Python2: String Encoding: ASCII; P3: Unicode P2: Division 5/2=floor(2.5)=2 P3: 5/2=2.5 p2: Printing print p3: print() p2: libraries some just for p2 P3: some just for p3 Python 2 is entrenched in the software landscape to the point that co-dependency between several softwares makes it almost impossible to make the shift.

What is the @property in Python?

The @property is a decorator. In Python, decorators enable users to use the class in the same way (irrespective of the changes made to its attributes or methods). The @property decorator allows a function to be accessed like an attribute.

What is a Python Docstring?

The Python docstrings provide a suitable way of associating documentation with: Python modules Python functions Python classes It is a specified document for the written code. Unlike conventional code comments, the doctoring should describe what a function does, not how it works. The docstring can be accessed using __doc__ method of the object help function def hello_world(): """Demonstrating docstring.""" return None

What is the join method in python?

The join method in Python takes elements of an iterable data structure and connects them together using a particular string connector value. How does join work? The join method in Python is a string method, which connects elements of a string iterable structure, which also contains strings or characters (array, list, etc.) by using a particular string as the connector. array = ['H','E','L','L','O'] connector = ""joined_string = connector.join(array)print(joined_string) OUTPUT: HELLO

How would you sort a dictionary in Python?

We can sort this type of data by either the key or the value and this is done by using the sorted() function. Dictionary.keys() : Returns only the keys in an arbitrary order. Dictionary.values() : Returns a list of values. Dictionary.items() : Returns all of the data as a list of key-value pairs. Sorted() syntax This method takes one mandatory and two optional arguments: Data (mandatory): The data to be sorted. We will pass the data we retrieved using one of the above methods. Reverse (optional): Setting the third parameter as true will sort the list in descending order. Leaving this empty sorts in ascending order.

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.

How and when would you use any() and all()? What is any()?

any() is a function that takes in an iterable (such as a list, tuple, set, etc.) and returns True if any of the elements evaluate to True, but it returns False if all elements evaluate to False. all() is another Python function that takes in an iterable and returns True if all of the elements evaluate to True, but returns False if otherwise.

What is default dict in Python?

defaultdict_demo = defaultdict(int) defaultdict_demo.update([('1','what'),('2',"dafc")]) print(defaultdict_demo['3']) the dictionary is created and when any key, that does not exist in the defaultdict is added or accessed, it is assigned a default value as opposed to giving a KeyError.

sort

sorted is fast, since it is implemented in C. Much faster than an equivalent sort in Python.

Check if a Python string contains another string

string.find(substring) string.find(value, start, end)

Reverse a string in Python

stringname[stringlength::-1] # method 1 stringname[::-1] # method2

What is the ternary operator?

var = true_val if condition else false_val

Implement breadth first search (BFS) in Python

visited = [] # List to keep track of visited nodes.queue = [] #Initialize a queue

Implement wildcards in Python

wordlist = ["color", "colour", "work", "working", "fox", "worker", "working"] for word in wordlist: # The . symbol is used in place of ? symbol if re.search('col.r', word) : print (word)


Kaugnay na mga set ng pag-aaral

health and wellness, professional nursing

View Set

Chapter 14- Integration of Nervous System Functions

View Set

Chapter 6: Governing Institutions In Democracies

View Set

Cells and Human Body Study Guide

View Set

RAD Tech Boot Camp - Image Production

View Set