Keyword

Result: 213 questions

Why And When Do You Use Generators In Python?

Answer:

A generator in Python is a function which returns an iterable object. We can iterate on the generator object using the <yield> keyword. But we can only do that once because their values don’t persist in memory, they get the values on the fly.

Generators give us the ability to hold the execution of a function or a step as long as we want to keep it. However, here are a few examples where it is beneficial to use generators.

  • We can replace loops with generators for efficiently calculating results involving large data sets.
  • Generators are useful when we don’t want all the results and wish to hold back for some time.
  • Instead of using a callback function, we can replace it with a generator. We can write a loop inside the function doing the same thing as the callback and turns it into a generator.
View

How Do You Count The Occurrences Of Each Item Present In The List Without Explicitly Mentioning Them?

Answer:

Unlike sets, lists can have items with same values. In Python, the list has a <count()> function which returns the occurrences of a particular item.

View

What Is NumPy And How Is It Better Than A List In Python?

Answer:

NumPy is a Python package for scientific computing which can deal with large data sizes. It includes a powerful N-dimensional array object and a set of advanced functions.

Also, the NumPy arrays are superior to the built-in lists. There are a no. of reasons for this.

  • NumPy arrays are more compact than lists.
  • Reading and writing items is faster with NumPy.
  • Using NumPy is more convenient than to the standard list.
  • NumPy arrays are more efficient as they augment the functionality of lists in Python.
View

Can you create singleton object in python?If yes, how do you do it?

Answer:

Yes, you can create singleton object. Here’s how you do it :

class Singleton(object):
      def __new__(cls,*args,**kwargs):
          if not hasattr(cls,'_inst'):
             cls._inst = super(Singleton,cls).__new__(cls,*args,**kwargs)
          return cls._inst

 

View

List out the inheritance styles in Django?

Answer:

In Django, there is three possible inheritance styles

  • Abstract base classes: This style is used when you only wants parent’s class to hold information that you don’t want to type out for each child model
  • Multi-table Inheritance: This style is used If you are sub-classing an existing model and need each model to have its own database table
  • Proxy models: You can use this model, If you only want to modify the Python level behavior of the model, without changing the model’s fields
View

Explain what is Django?

Answer:

Django is a web framework in python to develop a web application in python.

View

Why Django should be used for web-development?

Answer:

  • It allows you to divide code modules into logical groups to make it flexible to change
  • To ease the website administration, it provides auto-generated web admin
  • It provides pre-packaged API for common user tasks
  • It gives you template system to define HTML template for your web page to avoid code duplication
  • It enables you to define what URL be for a given function
  • It enables you to separate business logic from the HTML
  • Everything is in python
View

Explain how you can set up the Database in Django?

Answer:

You can use the command edit mysite/setting.py , it is a normal python module with module level representing Django settings.

Django uses SQLite by default; it is easy for Django users as such it won’t require any other type of installation. In the case your database choice is different that you have to the following keys in the DATABASE ‘default’ item to match your database connection settings

  • Engines: you can change database by using ‘django.db.backends.sqlite3’ , ‘django.db.backeneds.mysql’, ‘django.db.backends.postgresql_psycopg2’, ‘django.db.backends.oracle’ and so on
  • Name: The name of your database. In the case if you are using SQLite as your database, in that case database will be a file on your computer, Name should be a full absolute path, including file name of that file.

If you are not choosing SQLite as your database then setting like Password, Host, User, etc. must be added.

View

Explain how you can setup static files in Django?

Answer:

There are three main things required to set up static files in Django

  • Set STATIC_ROOT in settings.py
  • run manage.py collectsatic
  • set up a Static Files entry on the PythonAnywhere web tab
View

Which are the different languages supported by MongoDB?

Answer:

MonggoDB provides official driver support for C, C++, C#, Java, Node.js, Perl, PHP, Python, Ruby, Scala, Go and Erlang.

You can use MongoDB with any of the above languages. There are some other community supported drivers too but the above mentioned ones are officially provided by MongoDB.

View

What will be the output of the code below? Explain your answer.

def multipliers():
  return [lambda x : i * x for i in range(4)]
    
print [m(2) for m in multipliers()]

How would you modify the definition of multipliers to produce the presumably desired behavior?

Answer:

The output of the above code will be [6, 6, 6, 6] (not [0, 2, 4, 6]).

The reason for this is that Python’s closures are late binding. This means that the values of variables used in closures are looked up at the time the inner function is called. So as a result, when any of the functions returned by multipliers() are called, the value of i is looked up in the surrounding scope at that time. By then, regardless of which of the returned functions is called, the for loop has completed and i is left with its final value of 3. Therefore, every returned function multiplies the value it is passed by 3, so since a value of 2 is passed in the above code, they all return a value of 6 (i.e., 3 x 2).

(Incidentally, as pointed out in The Hitchhiker’s Guide to Python, there is a somewhat widespread misconception that this has something to do with lambdas, which is not the case. Functions created with a lambda expression are in no way special and the same behavior is exhibited by functions created using an ordinary def.)

Below are a few examples of ways to circumvent this issue.

One solution would be use a Python generator as follows:

def multipliers():
  for i in range(4): yield lambda x : i * x 

Another solution is to create a closure that binds immediately to its arguments by using a default argument. For example:

def multipliers():
  return [lambda x, i=i : i * x for i in range(4)]

Or alternatively, you can use the functools.partial function:

from functools import partial
from operator import mul

def multipliers():
  return [partial(mul, i) for i in range(4)]
View

What will be the output of the code below? Explain your answer.

class Parent(object):
    x = 1

class Child1(Parent):
    pass

class Child2(Parent):
    pass

print Parent.x, Child1.x, Child2.x
Child1.x = 2
print Parent.x, Child1.x, Child2.x
Parent.x = 3
print Parent.x, Child1.x, Child2.x

Answer:

The output of the above code will be:

1 1 1
1 2 1
3 2 3

What confuses or surprises many about this is that the last line of output is 3 2 3 rather than 3 2 1. Why does changing the value of Parent.x also change the value of Child2.x, but at the same time not change the value of Child1.x?

The key to the answer is that, in Python, class variables are internally handled as dictionaries. If a variable name is not found in the dictionary of the current class, the class hierarchy (i.e., its parent classes) are searched until the referenced variable name is found (if the referenced variable name is not found in the class itself or anywhere in its hierarchy, an AttributeError occurs).

Therefore, setting x = 1 in the Parent class makes the class variable x (with a value of 1) referenceable in that class and any of its children. That’s why the first print statement outputs 1 1 1.

Subsequently, if any of its child classes overrides that value (for example, when we execute the statement Child1.x = 2), then the value is changed in that child only. That’s why the second print statement outputs 1 2 1.

Finally, if the value is then changed in the Parent (for example, when we execute the statement Parent.x = 3), that change is reflected also by any children that have not yet overridden the value (which in this case would be Child2). That’s why the third print statement outputs 3 2 3.

View

What will be the output of the code below in Python 2? Explain your answer.

def div1(x,y):
    print "%s/%s = %s" % (x, y, x/y)
    
def div2(x,y):
    print "%s//%s = %s" % (x, y, x//y)

div1(5,2)
div1(5.,2)
div2(5,2)
div2(5.,2.)

Also, how would the answer differ in Python 3 (assuming, of course, that the above print statements were converted to Python 3 syntax)?

Answer:

In Python 2, the output of the above code will be:

5/2 = 2
5.0/2 = 2.5
5//2 = 2
5.0//2.0 = 2.0

By default, Python 2 automatically performs integer arithmetic if both operands are integers. As a result, 5/2 yields 2, while 5./2 yields 2.5.

Note that you can override this behavior in Python 2 by adding the following import:

from __future__ import division

Also note that the “double-slash” (//) operator will always perform integer division, regardless of the operand types. That’s why 5.0//2.0 yields 2.0 even in Python 2.

Python 3, however, does not have this behavior; i.e., it does not perform integer arithmetic if both operands are integers. Therefore, in Python 3, the output will be as follows:

5/2 = 2.5
5.0/2 = 2.5
5//2 = 2
5.0//2.0 = 2.0
View

What is Python? What are the benefits of using Python?

Answer:

Python is a programming language with objects, modules, threads, exceptions and automatic memory management. The benefits of pythons are that it is simple and easy, portable, extensible, build-in data structure and it is an open source.

View

What is PEP 8?

Answer:

PEP 8 is a coding convention, a set of recommendation, about how to write your Python code more readable.

View

What is pickling and unpickling?

Answer:

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.

View

How Python is interpreted?

Answer:

Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.

View

How memory is managed in Python?

Answer:

  • Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have an access to this private heap and interpreter takes care of this Python private heap.
  • The allocation of Python heap space for Python objects is done by Python memory manager.  The core API gives access to some tools for the programmer to code.
  • Python also have an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space.
View

What are the tools that help to find bugs or perform static analysis?

Answer:

PyChecker is a static analysis tool that detects the bugs in Python source code and warns about the style and complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard.

View

What are Python decorators?

Answer:

A Python decorator is a specific change that we make in Python syntax to alter functions easily.

View

© 2017 QuizBucket.org