Posts

Showing posts from March, 2017

Save a file in model without using Django forms

If you want to store the document without using Django forms then you can use below code :  in models.py ... class UserProfile(models.Model) :     user = models.OneToOneField(User)     doc = models.FileField(upload_to='uploads/', blank=True) in python script from core.models import UserProfile from django.core.files import File user1 = UserProfile(pk = 1) user1.doc.save('resume.pdf', File(open('/tmp/resume.pdf', 'r')))

Explain Inheritance in python.

Inheritance : Inheritance enables us to define a class that takes all the functionality from a parent class and allows us to add more. Classes can inherit from other classes. A class can inherit attributes and behavior methods from another class, called the superclass. A class which inherits from a superclass is called a subclass, also called heir class or child class. Superclasses are sometimes called ancestors as well. Syntax : class DerivedClass(BaseClass) :    body_of_derived_class A derived class inherits features from the base class, adding new features to it. This results in re-usability of code. If an attribute is not found in the class, the search continues to the base class. This repeats recursively if the base class is derived from other classes. Ex : class Polygon:    def __init__(self, no_of_sides):        self.n = no_of_sides       ...

What are Iterators and Generators in python?

Iterators : An iterator is an object which allows us to traverse through all the elements of a collection, regardless of its specific implementation. An iterator is an object which implements the iterator protocol. The iterator protocol consists of two methods : The __iter__() method, which must return the iterator object The next() method, which returns the next element from a sequence Python has several built-in objects, which implement the iterator protocol. For example lists, tuples, strings, dictionaries or files. Advantages : Cleaner code Iterators can work with infinite sequences Iterators save resources By saving system resources means that when working with iterators, we can get the next element in a sequence without keeping the entire dataset in memory. Generators : Generators functions allow us to declare a function that behaves like an iterator. A generator yields one value at a time, this requires less memory. Gene...

What is a design pattern?

Design patterns : Design patterns represent the best practices Design patterns are solutions to general problems that software developers faced during software development. Gang of Four (GOF)? : In 1994, four authors Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides published a book titled Design Patterns - Elements of Reusable Object-Oriented Software which initiated the concept of Design Pattern in Software development. These authors are collectively known as Gang of Four (GOF) According to these authors design patterns are primarily based on the following principles of object orientated design: Program to an interface not an implementation Favor object composition over inheritance Usage of Design Pattern : Common platform for developers Best Practices Types of Design Patterns : Creational Patterns : These design patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects...

Explain map, filter, reduce and zip functions?

map : It is a built-in higher-order function that operates on iterable. Functions that can accept other functions as arguments and return function to the caller is known as Higher-order functions. It takes a function and an iterable as arguments and returns a new iterable with the function applied to each item of iterable. filter : It filters an iterable by removing items that don’t match a predicate. A predicate is a function that returns a Boolean. reduce : It continuously applies the function to sequence and returns a single value. zip : It takes two equal-length collections and merges them together in pairs. Example : nums = [ 11,22,33,44,55 ] list1  = [ 1,2,3  ] list2 = [ ‘a’,’b’,’c’ ] >> zip( list1 , list2 ) # [(1, 'a'), (2, 'b'), (3, 'c')] >> res = list( filter ( lambda x : x % 2 == 0 , nums ) ) >> print(res) # [ 22, 44 ] >> print(map(lambda x : x + 5 , nums)) >...

How to sort Dictionaries over values?

It is not possible to sort a dict, only to get a representation of a dict that is sorted. Dicts are inherently orderless, but other types, such as lists and tuples, are not. So we need a sorted representation, which will be a list—probably a list of tuples. Soln 1 : To sort on values : import operator x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = sorted(x.items(), key=operator.itemgetter(1)) sorted_x will be a list of tuples sorted by the second element in each tuple.dict(sorted_x) == x To sort on keys : import operator x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = sorted(x.items(), key=operator.itemgetter(0)) Soln 2 : x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} sorted_x = sorted( x.items(), key=lambda a : a[1] )

What can be key of a dictionary?

Key of a dictionary can be : String Numbers tuples List can’t be a key of a dictionary and also tuple of list can’t be same. If we assign a tuple of list as key then it will generate a TypeError: unhashable type: 'list'.

What is GIL (Global Interpreter Lock) in python?

Mutex : A mutex is a program object that allows multiple program threads to share the same resource, such as file access, but not simultaneously. When a program is started, a mutex is created with a unique name. GIL ( Global Interpreter Lock ) : A global interpreter lock (GIL) is a mechanism used in computer language interpreters to synchronize the execution of threads so that only one native thread can execute at a time. An interpreter that uses GIL always allows exactly one thread to execute at a time, even if run on a multi-core processor. C Python has a gil. GIL is a mutex that prevents multiple native threads from executing Python byte-codes at once. This lock is necessary because C Python's memory management is not thread-safe. The GIL is controversial because it prevents multi-threaded C Python programs from taking full advantage of multiprocessor systems in certain situations.

Difference between range and xrange

range vs xrange : range creates a list, so if you do range(1, 10000000) it creates a list in memory with 9999999 elements. xrange is a sequence object that evaluates lazily. xrange is not exactly a generator but it evaluates lazily and acts like a generator. In Python 3, range will be implemented by the Python 2 xrange(). If you need to actually generate the list, you will need to do: list(range(1,100))