Coding Interview Flashcards
DRY
Don’t Repeat Yourself
MVC
Model Review Controller
USER uses CONTROLLER manipulates MODEL updates VIEW sees USER
- A Model , which represents the underlying, logical structure of data in a software application and the high-level class associated with it. This object model does not contain any information about the user interface.
- A View , which is a collection of classes representing the elements in the user interface (all of the things the user can see and respond to on the screen, such as buttons, display boxes, and so forth)
- A Controller , which represents the classes connecting the model and the view, and is used to communicate between classes in the model and view.
ORM
Object Relational Mapping
A technique that lets you query and manipulate data from a database using an object-oriented paradigm.
ORM Pros
SAVES TIME:
- DRY: You write your data model in only one place, and it’s easier to update, maintain, and reuse the code.
- A lot of stuff is done automatically, from database handling to I18N.
- It forces you to write MVC code, which, in the end, makes your code a little cleaner.
- You don’t have to write poorly-formed SQL (most Web programmers really suck at it, because SQL is treated like a “sub” language, when in reality it’s a very powerful and complex one).
- Sanitizing; using prepared statements or transactions are as easy as calling a method.
FLEXIBILITY:
- It fits in your natural way of coding (it’s your language!).
- It abstracts the DB system, so you can change it whenever you want.
- The model is weakly bound to the rest of the application, so you can change it or use it anywhere else.
- It lets you use OOP goodness like data inheritance without a headache.
ORM Cons
- You have to learn it, and ORM libraries are not lightweight tools;
- You have to set it up. Same problem.
- Performance is OK for usual queries, but a SQL master will always do better with his own SQL for big projects.
- It abstracts the DB. While it’s OK if you know what’s happening behind the scene, it’s a trap for new programmers that can write very greedy statements, like a heavy hit in a for loop.
ORM Examples
Java: Hibernate.
PHP: Propel or Doctrine (I prefer the last one).
Python: the Django ORM or SQLAlchemy
C#: NHibernate or Entity Framework
Python Requests Module
Requests allows you to send organic, grass-fed HTTP/1.1 requests, without the need for manual labor. There’s no need to manually add query strings to your URLs, or to form-encode your POST data. Keep-alive and HTTP connection pooling are 100% automatic, thanks to urllib3.
Python Arrow Module
Arrow is a Python library that offers a sensible, human-friendly approach to creating, manipulating, formatting and converting dates, times, and timestamps. It implements and updates the datetime type, plugging gaps in functionality, and provides an intelligent module API that supports many common creation scenarios.
Python More_Itertools Module
Toolbox for all kinds of operations.
Examples of DBs
MySQL, SQLite, Postgres, Oracle, MongoDB
Celery
Celery is an asynchronous task queue/job queue based on distributed message passing. It is focused on real-time operation, but supports scheduling as well. … Tasks can execute asynchronously (in the background) or synchronously (wait until ready). Celery is used in production systems to process millions of tasks a day.
Python Redis Module
Redis is an in-memory key-value pair NoSQL data store often used for web application sessions, transient data and as a broker for task queues. redis-py is a common Python code library for interacting with Redis.
RPC
Remote Procedure Call (RPC) RPC is the earliest, simplest form of API interaction. It is about executing a block of code on another server, and when implemented in HTTP or AMQP it can become a Web API. There is a method and some arguments, and that is pretty much it.
WUI
Web User Interface (Browser?)
CLI
Command Line Interface
5 Values of XP
communication, simplicity, feedback, courage, and respect
Retrospectives
- Planning session done after one stage of Agile development
- Those who have participated in agile development processes will evaluate these processes carefully to think about what methods may have worked better than others
Cloud Services Examples
AWS, GCP, Azure, DO, Rackspace
CI/CD
Continuous Integration / Continuous Deployment
https://dzone.com/articles/learn-how-to-setup-a-cicd-pipeline-from-scratch
PEP-20
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one– and preferably only one –obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea – let’s do more of those!
PEP-8
Style guide
Python 2-3 History
- Python 2.0 was first released in 2000. Its latest version, 2.7, was released in 2010.
- Python 3.0 was released in 2008. Its newest version, 3.6, was released in 2016, and version 3.7 is currently in development.
- Although Python 2.7 is still widely used, Python 3 adoption is growing quickly. In 2016, 71.9% of projects used Python 2.7, but by 2017, it had fallen to 63.7%. This signals that the programming community is turning to Python 3–albeit gradually–when developing real-world applications.
- Notably, on January 1, 2018, Python 2.7 will “retire” and no longer be maintained. (The clock is literally ticking!)
python 2 vs 3 differences
Python 3:
- Takes over python 2 by 2020 in users
- Actively maintained libraries
- Unicode rather than ASCII
- 5/2 = 2.5 rather than rounding to 2
- print(“hello”) rather than print “hello”
why people are moving to python 3
- Python 3 supports typing
- Future versions of python 3 will be faster unlike 2
- Community support is better for 3
when does it make sense to use python 2
- If you want to become a DevOps engineer and work with configuration management tools like Fabric or Ansible, you might have to work with both Python 2 and 3 (because parts of these libraries don’t have full Python 3 support).
- If your company has legacy code written in Python 2, you’ll need to learn to work with that.
- If you have a project that depends on certain third-party software or libraries that can’t be ported to Python 3, you’ll have no choice but to use Python 2 for it.
Python vs other languages
- It’s free
- Compatability
- Simplicity
- Libraries
- Object-oriented
https://www.cleveroad.com/blog/python-vs-other-programming-languages
OrderedDict
from collections import OrderedDict
odict = OrderedDict(a list of tuples with key and value)
DefaultDict
from collections import defaultdict
d = defaultdict(list)
sets a default value if no value set
Counter
from collections import counter
A Counter is a container that keeps track of how many times equivalent values are added.
Warnings
When exceptions are too much.
One might want to issue a warning when a program uses an obsolete module.
How to suppress warnings?
import warnings
def fxn(): warnings.warn("deprecated", DeprecationWarning)
with warnings.catch_warnings():
warnings.simplefilter(“ignore”)
fxn()
While within the context manager all warnings will simply be ignored. This allows you to use known-deprecated code without having to see the warning while not suppressing the warning for other code that might not be aware of its use of deprecated code.
Ask for forgiveness, not permission
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.
What are python sets?
A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.
What is hashable?
An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects which compare equal must have the same hash value.
Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.
All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal, and their hash value is their id().
What is immutable?
Mutable objects can change their state or contents and immutable objects can’t change their state or content.
Immutable Objects : These are of in-built types like int, float, bool, string, unicode, tuple.
Mutable Objects : These are of type list, dict, set .
Does python have bags?
No. collections.Counter is used for that
Comprehensions
Comprehensions in Python provide us with a short and concise way to construct new sequences (such as lists, set, dictionary etc.) using sequences which have been already defined. Python supports the following 4 types of comprehensions:
List Comprehensions
Dictionary Comprehensions
Set Comprehensions
Generator Comprehensions
Iterable vs Iterator
An ITERABLE is:
anything that can be looped over (i.e. you can loop over a string or file) or
anything that can appear on the right-side of a for-loop: for x in iterable: … or
anything you can call with iter() that will return an ITERATOR: iter(obj) or
an object that defines __iter__ that returns a fresh ITERATOR, or it may have a __getitem__ method suitable for indexed lookup.
An ITERATOR is an object:
with state that remembers where it is during iteration,
with a __next__ method that:
returns the next value in the iteration
updates the state to point at the next value
signals when it is done by raising StopIteration
and that is self-iterable (meaning that it has an __iter__ method that returns self).
https://stackoverflow.com/questions/9884132/what-exactly-are-iterator-iterable-and-iteration
Generators
Generator functions allow you to declare a function that behaves like an iterator, i.e. it can be used in a for loop.
Docker vs VMs
Docker does not require Hypervisor or Guest OS.
Docker starts in milliseconds, not minutes.
Docker uses less resources.
Docker vs VEs
VEs are OS dependent
VEs CPython modules can become problematic
VEs are lacking in unified tooling
VEs are mutable
Why is Docker exciting?
Containers Not only Python Has just enough libraries Libraries can be packaged in container Remote or local Provides ecosystem and utilities for managing containers Heavily favours immutability
What is GitFlow?
Git-Flow is one of several branching models. It offers a clear model on how to structure your branches and how to track releases, features, current development state and hotfixes.
Git branches vs clones
Clone copies the whole repository including all branches, allowing you to work on a completely separate version of the repository. Any changes will then be pushed to your local copy.
Branches are used for adding features or fixing bugs on the same project. Any changes made to the branch will stay on that branch until you merge or rebase them with the main branch.
https://stackoverflow.com/questions/3329943/what-are-the-differences-between-git-branch-fork-fetch-merge-rebase-and-clon
Git merge vs rebase
The resulting tree structure of the history (generally only noticeable when looking at a commit graph) is different (one will have branches, the other won’t).
Merge will generally create an extra commit (e.g. node in the tree).
Merge and rebase will handle conflicts differently. Rebase will present conflicts one commit at a time where merge will present them all at once.
.gitkeep vs .gitignore
Git does not track empty directories. Both are used to keep empty directoies,
.gitkeep does nothing else
.gitignore tells git which files not to track
Name version control systems
GitHub AWS Code Commit Bitbucket GitLab Git
FIXME vs TODO
TODO works but needs improvement
FIXME doesn’t work
d.get(“key”) vs d.key vs. d[“key”]
d. get(“key”) allows for default return value. Useful for not throwing errors
d. key == d[“key”] for the most part.
Steps to make a new Django project
virtualenv venv venv/Scripts/Activate pip install Django git init django-admin startproject x python manage.py startapp x add app to settings.py python manage.py migrate