What Is Monkey Patching In Python
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.pyclass X:def func:print "func is being called"
The above module is used to change the behavior of a function at the runtime as shown below:
import monkeyydef monkey_f:print "monkey_f is being called"# replacing address of func with monkey_fmonkeyy.X.func = monkey_fobj = monk.X# calling function func whose address got replaced# with function monkey_fobj.func
Q How Can I Mimic Cgi Form Submission I Would Like To Retrieve Web Pages That Are The Result Of Posting A Form
Yes. Here is a simple example that uses httplib:
#!/usr/local/bin/pythonimporthttplib, sys, time### build the query stringqs="First=Josephine& MI=Q& Last=Public"### connect and send the server a pathhttpobj=httplib.HTTPhttpobj.putrequest### now generate the rest of the HTTP headershttpobj.putheaderhttpobj.putheaderhttpobj.putheaderhttpobj.putheader)httpobj.endheadershttpobj.send### find out what the server said in responsereply, msg, hdrs=httpobj.getreplyifreply!=200:sys.stdout.write.read)
Note that in general for URL-encoded POST operations, query strings must be quoted by using urllib.quote. For example to send name=”Guy Steele, Jr.”:
Q We Know Python Is All The Rage These Days But To Be Truly Accepting Of A Great Technology You Must Know Its Pitfalls As Well
Of course. To be truly yourself, you must be accepting of your flaws. Only then can you move forward to work on them. Python has its flaws too:
Python’s interpreted nature imposes a speed penalty on it. While Python is great for a lot of things, it is weak in mobile computing, and in browsers.
Being dynamically-typed, Python uses duck-typing . This can raise runtime errors.
Python has underdeveloped database access layers. This renders it a less-than-perfect choice for huge database applications.
And even after these pitfalls, of course. Being easy makes it addictive. Once a Python-coder, always a Python coder.
So while it has problems, it is also a wonderful tool for a lot of things.
Read Also: Talk Show Interview Questions And Answers
Python For Machine Learning
As a data scientist, you must know how to build and interpret the performance of predictive algorithms using Python packages like Scikit-Learn.
Machine Learning Fundamentals with Python is a great course by Datacamp that you can take to learn the implementation of ML models in Python.
This program will take you through how to build, train, and evaluate supervised and unsupervised ML algorithms using the Scikit-Learn library. In addition, you will also learn about linear classifiers like support vector machines and the inner workings behind them.
Finally, this course will teach you to implement deep learning algorithms in Python using the Keras framework.
If youd like a free alternative to this course, I suggest coding along to Krish Naiks Machine Learning with Python playlist. This playlist contains all the concepts covered in the Datacamp course above, although the order and teaching style may differ slightly.
Passing Arguments To Sort Method
Python provides a built-in function called sort which sorts the list, by default, in ascending order. But it not just limited to sorting lists, rather, we can pass various arguments to this function to customize the results as per our needs. Firstly, we can pass reverse=True in the sort method so we can receive the list in descending order. Secondly, we can pass a value to the key which is a function and serves as a key for the sorting comparison. For example, if we have a list of strings and we want to sort them based on their height, we will follow this syntax: list_input.sort.
To read more about it, must read: sort in Python
Read Also: Qa Scenario Based Interview Questions
Q What Is Garbage Collection
The concept of removing unused or unreferenced objects from the memory location is known as a Garbage Collection. While executing the program, if garbage collection takes place then more memory space is available for the program and rest of the program execution becomes faster.
Garbage collector is a predefined program, which removes the unused or unreferenced objects from the memory location.
Any object reference count becomes zero then we call that object as a unused or unreferenced object Then no.of reference variables which are pointing the object is known as a reference count of the object.
While executing the python program if any object reference count becomes zero, then internally python interpreter calls the garbage collector and garbage collector will remove that object from memory location.
Using Generators As Opposed To List Comprehension
Using list comprehensions is great when working with smaller lists. If list comprehension is used for larger lists, it often ends up consuming a lot of time thereby slowing down your program. Therefore, Python provides generators that help to create your own iterator functions. It is a special type of Python function which rather than providing a single value, provides an iterator object with a sequence of values. In normal functions, we use a return keyword, but in generator functions, we use yield keyword. The return statement terminates the function whereas yield only pauses the execution while maintaining an internal state of the function.
To learn more about it, must read: Generators in Python
Also Check: How To Prepare For Apple Interview
What Are The Different Types Of Data Structures
The different types of data structures are:
- Arrays: A collection of data values stored sequentially
- Stacks: Last-in-first-out data structures where the element placed last is accessed first.
- Queues: A first-in-first-out data structure.
- Linked lists: A collection of data values stored in a linear order and connected to each other
- Graphs: A data structure in which data values are placed in nodes connected by edges
- Trees: Similar to a linked list, but with data values linked in a hierarchical fashion
- Heaps: A binary tree data structure wherein parent data values can be compared to child data values
- Hash table: A table where each value is assigned a key and then stored, making accessing individual values easy.
What Are Global Protected And Private Attributes In Python
The attributes of a class are also called variables. There are three access modifiers in Python for variables, namely
a. public The variables declared as public are accessible everywhere, inside or outside the class.
b. private The variables declared as private are accessible only within the current class.
c. protected The variables declared as protected are accessible only within the current package.
Attributes are also classified as:
Local attributes are defined within a code-block/method and can be accessed only within that code-block/method.
Global attributes are defined outside the code-block/method and can be accessible everywhere.
class Mobile: m1 = "Samsung Mobiles" //Global attributes def price: m2 = "Costly mobiles" //Local attributes return m2Sam_m = Mobileprint
Python Certification Course Overview
This Python certification training will help you understand the high-level, general-purpose dynamic programming language of the decade. In this Python course, you will be exposed to both the basic and advanced concepts of Python such as Machine Learning, Deep Learning, Hadoop streaming, and MapReduce, and you will work with packages such as Scikit and SciPy.Read More
What Is The Difference Between Append And Extend Methods
Both append and extend methods are methods used to add elements at the end of a list.
- append: Adds the given element at the end of the list that called this append method
- extend: Adds the elements of another list at the end of the list that called this extend method
For in-depth knowledge, check out our Python Tutorial and boost your Python skills!
Recommended Reading: How To Prepare For Green Card Interview
Interview Questions For Python Coding
Question 1: Convert a given string to int using a single line of code.
We can convert a given string to an integer using a built-in function int. e.g.-
a = 5print)
Variable a is a string that is now converted to an integer, as shown below:
Question 2: Write a code snippet to convert a string to a list.
Below is the code to convert string to list in Python.
str1 = "Analytics Vidhya"print)
The split function separates the given string by the defined delimiter i.e., space here. Therefore, Analytics and Vidhya break down to two strings in a list.
Question 3: Write a code snippet to reverse a string.
Here, we have reversed a string without using any in-built function.
str1 = "Analytics Vidhya"str2 = ""for i in str1: str2 = i + str2
The above code picks the first letter, i.e., A, then adds n at the beginning.
Further, nA is taken as str2, a is added before it, and so on.
Then anA becomes str2, and the next letter, i.e., l, is appended at the start of str2 to make it lanA.
This is how the above code works to reverse the string.
Question 4: Write a code snippet to sort a list in Python.
The list in Python can be sorted using the sort function. eg-
lst1 = lst1.sortprint
The above code sort the list using sort function.
Question 5: What is the difference between mutable and immutable.
Mutable objects: They cant be updated once defined. eg- list
Immutable objects: They can be updated when required. eg- tuples
Python Coding Interview Question #: Apartments In New York City And Harlem
Try and solve the question by Airbnb:
Find the search details of 50 apartment searches the Harlem neighborhood of New York City.
Link to the question:
Here are some hints. You need to set three conditions that will get you only apartment category, only those in Harlem, and the city has to be NYC. All three conditions will be set using the == operator. You dont need to show all apartments, so use the head function to limit the number of rows in the output.
Don’t Miss: Best Interview Outfits For Women
Q Name Few Methods That Are Used To Implement Functionally Oriented Programming In Python
Python supports methods , such as filter, map, and reduce, that are very useful when you need to iterate over the items in a list, create a dictionary, or extract a subset of a list.
- filter enables you to extract a subset of values based on conditional logic.
- map it is a built-in function that applies the function to each item in an iterable.
- reduce repeatedly performs a pair-wise reduction on a sequence until a single value is computed.
Python Practice: Word Games
If you are worried that learning programming will be boring, try this Python practice set. It contains 27 interactive exercises for beginners, similar to the Python Basics practice set. But here youll be working with many string functions and text files and practicing various iteration techniques.
This Python Practice training is organized into three fun thematic sections:
- Cipher Youll learn about Unicode by implementing a simple cipher in Python and use it to code and decode words. To complete this section, youll have to crack a code encrypted with Caesar’s cipher.
- Sherlock Holmes Do you know The Hound of the Baskervilles? In this section, youll analyze the text of this novel, find out how many unique words there are, and count how many times a given character occurs. And youll check for playful word-related concepts such as palindromes and semordnilaps .
- Scrabble In this final part, youll implement functions that can help in playing this popular word game. Youll learn how to list all possible words you can create from given letter tiles, how to calculate the value of a word, and how to find words with the greatest number of points.
Maybe you dont have weeks to polish up your coding skills. Even if you dont have much time left, do the best you can.
Q How Do You Create Your Own Package In Python
It overrides the any initialization from an inherited class and is called when the class is instantiated.
We know that a package may contain sub-packages and modules. A module is nothing but Python code.To create a package of our own, we create a directory and create a file __init__.py in it. We leave it empty. Then, in that package, we create a module with whatever code we want. For a detailed explanation with pictures, refer to Python Packages.
Define Default Values In Dictionaries With Get And Setdefault
One of the most common programming tasks involves adding, modifying, or retrieving an item that may or may not be in a dictionary. Python dictionaries have elegant functionality to make these tasks clean and easy, but developers often check explicitly for values when it isnt necessary.
Imagine you have a dictionary named cowboy, and you want to get that cowboys name. One approach is to explicitly check for the key with a conditional:
> > > cowboy=> > > if'name'incowboy:... name=cowboy... else:... name='The Man with No Name'...> > > name'The Man with No Name'
This approach first checks if the name key exists in the dictionary, and if so, it returns the corresponding value. Otherwise, it returns a default value.
While explicitly checking for keys does work, it can easily be replaced with one line if you use .get:
> > > name=cowboy.get
get performs the same operations that were performed in the first approach, but now theyre handled automatically. If the key exists, then the proper value will be returned. Otherwise, the default value will get returned.
But what if you want to update the dictionary with a default value while still accessing the name key? .get doesnt really help you here, so youre left with explicitly checking for the value again:
> > > if'name'notincowboy:... cowboy='The Man with No Name'...> > > name=cowboy
Checking for the value and setting a default is a valid approach and is easy to read, but again Python offers a more elegant method with .setdefault:
Don’t Miss: What To Do In A Job Interview
Sample Python Data Structure Interview Questions For Practice
Here, we glance over some additional Python data structure interview questions that you can prepare for your tech interview:
These top Python data structure interview questions will help you prepare for your software developer interview and ace it. After youve finished your preparation, you can take some mock interviews for self-evaluation.
Are you preparing for a tech interview? Check out our Technical Interview Prep Checklist to plan your prep.
What Do You Understand About Pandas Groupby
A pandas groupby is a feature supported by pandas that are used to split and group an object. Like the sql/mysql/oracle groupby it is used to group data by classes, and entities which can be further used for aggregation. A dataframe can be grouped by one or more columns.
To perform groupby type the following code:
Don’t Miss: Java Full Stack Developer Interview Questions
Set Up Your Development Environment
When using Python to write scripts that perform file system operations, we recommend you install Python from the Microsoft Store. Installing via the Microsoft Store uses the basic Python3 interpreter, but handles set up of your PATH settings for the current user , in addition to providing automatic updates.
If you are using Python for web development on Windows, we recommend a different setup using the Windows Subsystem for Linux. Find a walkthrough in our guide: Get started using Python for web development on Windows. If you’re brand new to Python, try our guide: Get started using Python on Windows for beginners. For some advanced scenarios , you may want to consider downloading a specific Python release directly from python.org or consider installing an alternative, such as Anaconda, Jython, PyPy, WinPython, IronPython, etc. We only recommend this if you are a more advanced Python programmer with a specific reason for choosing an alternative implementation.
Q How Can I Pass Optional Or Keyword Parameters From One Function To Another
Collect the arguments using the * and ** specifier in the function’s parameter list this gives you the positional arguments as a tuple and the keyword arguments as a dictionary. You can then pass these arguments when calling another function by using * and ** :
In the unlikely case that you care about Python versions older than 2.0, use ‘apply’:
Don’t Miss: How To Prepare For Machine Learning Interview
Top Python Programming Interview Questions
Q.7. What do you know about palindromes? Can you implement one in Python?
A palindrome is a phrase, a word, or a sequence that reads the same forward and backward. One such example will be pip! An example of such a phrase will be nurses run. Lets implement it, shall we?
> > > def isPalindrome: left,right=0,len-1 while right> =left: if not string==string: return False left+=1 right-=1 return True> > > isPalindrome
Well, there are other ways to do this too. Lets try using an iterator.
> > > def isPalindrome: left,right=iter,iter i=0 while i< len/2: if next!=next: return False i+=1 return True> > > isPalindrome
**kwargs takes keyword arguments when we dont know how many there will be.
> > > def func: for i in kwargs: print> > > func
a.1b.2c.7The words args and kwargs are a convention, and we can use anything in their place.
Q.9. What is a closure in Python?
A closure in Python is said to occur when a nested function references a value in its enclosing scope. The whole point here is that it remembers the value.
> > > def A: def B: print return B> > > A
Q.10. Are these statements optimal? If not, optimize them.
No, these are not optimal. Lets check the manual for this.
> > > help
The optimal solution:
Q.11. What is the iterator protocol?
> > > a=iter> > > next
> > > a=1> > > a,b=a+1,a+1> > > a,b