Result: 213 questions

Mention five benefits of using Python?


  • Python comprises of a huge standard library for most Internet platforms like Email, HTML, etc.
  • Python does not require explicit memory management as the interpreter itself allocates the memory to new variables and free them automatically
  • Provide easy readability due to use of square brackets
  • Easy-to-learn for beginners
  • Having the built-in data types saves programming time and effort from declaring variables

Mention the use of the split function in Python?


The use of the split function in Python is that it breaks a string into shorter strings using the defined separator. It gives a list of all words present in the string.


Explain what is Flask & its benefits?


Flask is a web micro framework for Python based on “Werkzeug, Jinja 2 and good intentions” BSD licensed. Werkzeug and jingja are two of its dependencies.

Flask is part of the micro-framework. Which means it will have little to no dependencies on external libraries.  It makes the framework light while there is little dependency to update and less security bugs.


Explain what is the common way for the Flask script to work?


The common way for the flask script to work is

  • Either it should be the import path for your application
  • Or the path to a Python file

Explain database connection in Python Flask?


Flask supports database powered application (RDBS). Such system requires creating a schema, which requires piping the shema.sql file into a sqlite3 command.  So you need to install sqlite3 command in order to create or initiate the database in Flask.

Flask allows to request database in three ways

  • before_request() : They are called before a request and pass no arguments
  • after_request() : They are called after a request and pass the response that will be sent to the client
  • teardown_request(): They are called in situation when exception is raised, and response are not guaranteed. They are called after the response been constructed.  They are not allowed to modify the request, and their values are ignored.

You are having multiple Memcache servers running Python, in which one of the memcacher server fails, and it has your data, will it ever try to get key data from that one failed server?


The data in the failed server won’t get removed, but there is a provision for auto-failure, which you can configure for multiple nodes. Fail-over can be triggered during any kind of socket or Memcached server level errors and not during normal client errors like adding an existing key, etc.


Explain how you can minimize the Memcached server outages in your Python Development?


•  When one instance fails, several of them goes down, this will put larger load on the database server when lost data is reloaded as client make a request. To avoid this, if your code has been written to minimize cache stampedes then it will leave a minimal impact
•  Another way is to bring up an instance of Memcached on a new machine using the lost machines IP address
•  Code is another option to minimize server outages as it gives you the liberty to change the Memcached server list with minimal work
•  Setting timeout value is another option that some Memcached clients implement for Memcached server outage. When your Memcached server goes down, the client will keep trying to send a request till the time-out limit is reached


Explain how Memcached should not be used in your Python project?


•  Memcached common misuse is to use it as a data store, and not as a cache
•  Never use Memcached as the only source of the information you need to run your application. Data should always be available through another source as well
•  Memcached is just a key or value store and cannot perform query over the data or iterate over the contents to extract information
•  Memcached does not offer any form of security either in encryption or authentication


Mention what is the difference between Amazon S3 and EC2?


The difference between EC2 and Amazon S3 is that

EC2 S3
  • It is a cloud web service used for hosting your application
  • It is a data storage system where any amount of data can be stored
  • It is like a huge computer machine which can run either Linux or Windows and can handle application like PHP, Python, Apache or any databases
  • It has a REST interface and uses secure HMAC-SHA1 authentication keys

What is Django?


Django is a free and open source web application framework, written in Python.


What are the inheritance styles in Django?


There are three possible inheritance styles in Django:

1. Abstract base classes: This style is used when you only want parent?s class to hold information that you don't want to type out for each child model.

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

3. Proxy models: This style is used, if you only want to modify the Python level behavior of the model, without changing the model's fields.


How can you set up the database in Djanago?


To set up a database in Django, you can use the command edit mysite/ , it is a normal python module with module level representing Django settings.

By default, Django uses SQLite database. It is easy for Django users because it doesn't require any other type of installation. In the case of other database 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', '' 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.

Note: You have to add setting likes setting like Password, Host, User, etc. in your database, if you are not choosing SQLite as your database.


How can you set up static files in Django?


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


2. run collectsatic

3. set up a Static Files entry on the PythonAnywhere web tab


What is Python really? You can (and are encouraged) make comparisons to other technologies in your answer


Here are a few key points:

  • Python is an interpreted language. That means that, unlike languages like C and its variants, Python does not need to be compiled before it is run. Other interpreted languages include PHP and Ruby.

  • Python is dynamically typed, this means that you don't need to state the types of variables when you declare them or anything like that. You can do things like x=111and then x="I'm a string" without error

  • Python is well suited to object orientated programming in that it allows the definition of classes along with composition and inheritance. Python does not have access specifiers (like C++'s publicprivate), the justification for this point is given as "we are all adults here"

  • In Python, functions are first-class objects. This means that they can be assigned to variables, returned from other functions and passed into functions. Classes are also first class objects

  • Writing Python code is quick but running it is often slower than compiled languages. Fortunately, Python allows the inclusion of C based extensions so bottlenecks can be optimised away and often are. The numpy package is a good example of this, it's really quite quick because a lot of the number crunching it does isn't actually done by Python

  • Python finds use in many spheres - web applications, automation, scientific modelling, big data applications and many more. It's also often used as "glue" code to get other languages and components to play nice.

  • Python makes difficult things easy so programmers can focus on overriding algorithms and structures rather than nitty-gritty low level details.


Looking at the below code, write down the final values of A0, A1, ...An.

A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
A1 = range(10)
A2 = sorted([i for i in A1 if i in A0])
A3 = sorted([A0[s] for s in A0])
A4 = [i for i in A1 if i in A3]
A5 = {i:i*i for i in A1}
A6 = [[i,i*i] for i in A1]

If you dont know what zip is don't stress out. No sane employer will expect you to memorize the standard library. Here is the output of help(zip).

    zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
    Return a list of tuples, where each tuple contains the i-th element
    from each of the argument sequences.  The returned list is truncated
    in length to the length of the shortest argument sequence.

If that doesn't make sense then take a few minutes to figure it out however you choose to.


A0 = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} # the order may vary
A1 = range(0, 10) # or [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] in python 2
A2 = []
A3 = [1, 2, 3, 4, 5]
A4 = [1, 2, 3, 4, 5]
A5 = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]


Python and multi-threading. Is it a good idea? List some ways to get some Python code to run in a parallel way.


Python doesn't allow multi-threading in the truest sense of the word. It 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.

There are reasons to use Python's threading package. If you want to run some things simultaneously, and efficiency is not a concern, then it's totally fine and convenient. Or if you are running code that needs to wait for something (like some IO) then it could make a lot of sense. But the threading library won't let you use extra CPU cores.

Multi-threading can be outsourced to the operating system (by doing multi-processing), some external application that calls your Python code (eg, Spark or Hadoop), or some code that your Python code calls (eg: you could have your Python code call a C function that does the expensive multi-threaded stuff).


What is monkey patching and is it ever a good idea?


Monkey patching is changing the behaviour of a function or object after it has already been defined. For example:

import datetime = lambda: datetime.datetime(2012, 12, 12)

Most of the time it's a pretty terrible idea - it is usually best if things act in a well-defined way. One reason to monkey patch would be in testing. The mock package is very useful to this end.


What do these mean to you: @classmethod@staticmethod@property?

Answer Background Knowledge:

These are decorators. A decorator is a special kind of function that either takes a function and returns a function, or takes a class and returns a class. The @ symbol is just syntactic sugar that allows you to decorate something in a way that's easy to read.

def my_func(stuff):

Is equivalent to

def my_func(stuff):

my_func = my_decorator(my_func)

You can find a tutorial on how decorators in general work here.

Actual Answer:


The decorators @classmethod@staticmethod and @property are used on functions defined within classes. Here is how they behave:

class MyClass(object):
    def __init__(self):
        self._some_property = "properties are nice"
        self._some_other_property = "VERY nice"
    def normal_method(*args,**kwargs):
        print("calling normal_method({0},{1})".format(args,kwargs))
    def class_method(*args,**kwargs):
        print("calling class_method({0},{1})".format(args,kwargs))
    def static_method(*args,**kwargs):
        print("calling static_method({0},{1})".format(args,kwargs))
    def some_property(self,*args,**kwargs):
        print("calling some_property getter({0},{1},{2})".format(self,args,kwargs))
        return self._some_property
    def some_property(self,*args,**kwargs):
        print("calling some_property setter({0},{1},{2})".format(self,args,kwargs))
        self._some_property = args[0]
    def some_other_property(self,*args,**kwargs):
        print("calling some_other_property getter({0},{1},{2})".format(self,args,kwargs))
        return self._some_other_property

o = MyClass()
# undecorated methods work like normal, they get the current instance (self) as the first argument

# >

# normal_method((<__main__.MyClass instance at 0x7fdd2537ea28>,),{})

# normal_method((<__main__.MyClass instance at 0x7fdd2537ea28>, 1, 2),{'y': 4, 'x': 3})

# class methods always get the class as the first argument

# >

# class_method((,),{})

# class_method((, 1, 2),{'y': 4, 'x': 3})

# static methods have no arguments except the ones you pass in when you call them


# static_method((),{})

# static_method((1, 2),{'y': 4, 'x': 3})

# properties are a way of implementing getters and setters. It's an error to explicitly call them
# "read only" attributes can be specified by creating a getter without a setter (as in some_other_property)

# calling some_property getter(<__main__.MyClass instance at 0x7fb2b70877e8>,(),{})
# 'properties are nice'

# calling some_property getter(<__main__.MyClass instance at 0x7fb2b70877e8>,(),{})
# Traceback (most recent call last):
#   File "", line 1, in 
# TypeError: 'str' object is not callable

# calling some_other_property getter(<__main__.MyClass instance at 0x7fb2b70877e8>,(),{})
# 'VERY nice'

# o.some_other_property()
# calling some_other_property getter(<__main__.MyClass instance at 0x7fb2b70877e8>,(),{})
# Traceback (most recent call last):
#   File "", line 1, in 
# TypeError: 'str' object is not callable

o.some_property = "groovy"
# calling some_property setter(<__main__.MyClass object at 0x7fb2b7077890>,('groovy',),{})

# calling some_property getter(<__main__.MyClass object at 0x7fb2b7077890>,(),{})
# 'groovy'

o.some_other_property = "very groovy"
# Traceback (most recent call last):
#   File "", line 1, in 
# AttributeError: can't set attribute

# calling some_other_property getter(<__main__.MyClass object at 0x7fb2b7077890>,(),{})
# 'VERY nice'

Describe Python's garbage collection mechanism in brief.


A lot can be said here. There are a few main points that you should mention:

  • Python maintains a count of the number of references to each object in memory. If a reference count goes to zero then the associated object is no longer live and the memory allocated to that object can be freed up for something else
  • occasionally things called "reference cycles" happen. The garbage collector periodically looks for these and cleans them up. An example would be if you have two objects o1 and o2 such that o1.x == o2 and o2.x == o1. If o1 and o2 are not referenced by anything else then they shouldn't be live. But each of them has a reference count of 1.
  • Certain heuristics are used to speed up garbage collection. For example, recently created objects are more likely to be dead. As objects are created, the garbage collector assigns them to generations. Each object gets one generation, and younger generations are dealt with first.

This explanation is CPython specific.


Place the following functions below in order of their efficiency. They all take in a list of numbers between 0 and 1. The list can be quite long. An example input list would be [random.random() for i in range(100000)]. How would you prove that your answer is correct?

def f1(lIn):
    l1 = sorted(lIn)
    l2 = [i for i in l1 if i<0.5]
    return [i*i for i in l2]

def f2(lIn):
    l1 = [i for i in lIn if i<0.5]
    l2 = sorted(l1)
    return [i*i for i in l2]

def f3(lIn):
    l1 = [i*i for i in lIn]
    l2 = sorted(l1)
    return [i for i in l1 if i<(0.5*0.5)]


Most to least efficient: f2f1f3. To prove that this is the case, you would want to profile your code. Python has a lovely profiling package that should do the trick.

import cProfile
lIn = [random.random() for i in range(100000)]'f1(lIn)')'f2(lIn)')'f3(lIn)')

For completion's sake, here is what the above profile outputs:

         4 function calls in 0.045 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.009    0.009    0.044    0.044 :1(f1)
        1    0.001    0.001    0.045    0.045 :1()
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        1    0.035    0.035    0.035    0.035 {sorted}

         4 function calls in 0.024 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.008    0.008    0.023    0.023 :1(f2)
        1    0.001    0.001    0.024    0.024 :1()
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        1    0.016    0.016    0.016    0.016 {sorted}

         4 function calls in 0.055 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.016    0.016    0.054    0.054 :1(f3)
        1    0.001    0.001    0.055    0.055 :1()
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        1    0.038    0.038    0.038    0.038 {sorted}

© 2017