Python: Check if all elements in a list are equal

# Pythonic ways of checking if all
# items in a list are equal:

>>> lst = ['a', 'a', 'a']

>>> len(set(lst)) == 1
True

>>> all(x == lst[0] for x in lst)
True

>>> lst.count(lst[0]) == len(lst)
True

# I ordered those from "most Pythonic" to "least Pythonic" 
# and  "least efficient" to "most efficient". 
# The len(set()) solution is idiomatic,  but constructing 
# a set is less efficient memory and speed-wise.

Python: Dict get with default value to void key not found error

# The get() method on dicts
# and its "default" argument

name_for_userid = {
    382: "Aseem",
    590: "Bob",
    951: "Dilbert",
}

def greeting(userid):
    return "Hi %s!" % name_for_userid.get(userid, "there")

>>> greeting(382)
"Hi Aseem!"

>>> greeting(333333)
"Hi there!"

Python: emulate switch/case statements by using dict with lambda functions

# Because Python has first-class functions they can
# be used to emulate switch/case statements

def dispatch_if(operator, x, y):
    if operator == 'add':
        return x + y
    elif operator == 'sub':
        return x - y
    elif operator == 'mul':
        return x * y
    elif operator == 'div':
        return x / y
    else:
        return None


def dispatch_dict(operator, x, y):
    return {
        'add': lambda: x + y,
        'sub': lambda: x - y,
        'mul': lambda: x * y,
        'div': lambda: x / y,
    }.get(operator, lambda: None)()


>>> dispatch_if('mul', 2, 8)
16

>>> dispatch_dict('mul', 2, 8)
16

>>> dispatch_if('unknown', 2, 8)
None

>>> dispatch_dict('unknown', 2, 8)
None

Python : List of Python Tutorials

If you are looking for a single list of python tutorial, then you landed on a very good blog post.

Learn Python online – A curated list of courses on Python

Here is the link : http://bafflednerd.com/learn-python-online/

This will allow you to try our different python courses available online.

Python : How to set a global variable in a function

x = 1 # make a global module variable

def f():
      print x # try to print the global
      ...
      for j in range(100):
           if q > 3:
              x=4

Any variable assigned in a function is local to that function, unless it is specifically declared global. Since a value is bound to x as the last statement of the function body, the compiler assumes that x is local. Consequently the “print x” statement attempts to print an uninitialized local variable and will trigger aUnboundLocalError (or in earlier Python versions, a NameError).

The solution is to insert an explicit global declaration at the start of the function:

def f():
      global x
      print x # try to print the global
      ...
      for j in range(100):
           if q > 3:
              x=4

In this case, all references to x are interpreted as references to the x from the module namespace.

Note that the global declarations must be placed at the beginning of the function, and that it affects all uses of the variable inside the function.

API : Profanity alert api by google – http://www.wdylike.appspot.com/?q=love

API : http://www.wdylike.appspot.com/?q=love
This is a cool api to check the profane words in contents. It could be used to scan emails, documents and even public comments on your blog 🙂

A simple and sweet sample program to understand and consume it.

__author__ = 'premaseem'
import urllib

# file reader functions
def read_file():
    doc= open('/Users/asee2278/gitRepo/petProjects/python_mini_projects/Profinity_alert/document.txt')
    contents = doc.read()
    print contents
    doc.close()
    return contents

# function with google api to check profanity in contents
def check_contenct_profanity(contents):
    connection = urllib.urlopen('http://www.wdylike.appspot.com/?q='+contents)
    output = connection.read()
    print output
    connection.close()
    if 'true' in output :
        print " Profanity Alert !! "
    elif 'false' in output :
        print " This document has not curse words :-)"
    else :
        print "sorry could not scan the doc "

# read the file and grab contents
contents = read_file()

# check for profanity
check_contenct_profanity(contents)

Python : What is pip or PyPi

pip is a package management system used to install and manage software packages written in Python. Many packages can be found in thePython Package Index (PyPI).

All the major supported packages / modules in python are hosted and listed at site called as Pypi Python Index – https://pypi.python.org/pypi/pip with pre-registered name. User can install / uninstall any package with its respective version using pip.

One major advantage of pip is the ease of its command-line interface, which makes installing Python software packages as easy as issuing one command:

pip install some-package-name

Users can also easily remove the package:

pip uninstall some-package-name

Most importantly pip has a feature to manage full lists of packages and corresponding version numbers, possible through a “requirements” file.This permits the efficient re-creation of an entire group of packages in a separate environment (e.g. another computer) or virtual environment. This can be achieved with a properly formatted requirements.txt file and the following command:

pip install -r requirements.txt

Install some package for a specific version python, where ${version} is replaced for 2, 3, 3.4, etc:

pip${version} install some-package-name

Python : What is Virtual Environment

Each project might need some set of dependencies with their specific version to work properly. Usually, we might have multiple projects running on different versions / packages. For example

  • some project on python2 others python 3
  • some project using pymongo2.7 others pymongo3.2

Normally, we have installed python 2.7, then we might not run python3 without upgrading to python3, however there is solution called virtual Environment which allows us to have an environment for specific required for each project and it is called as virtual environment. This can be installed using below command

$ [sudo] pip install virtualenv

The trick is to create separate folder for each project and activate virtual environment over there, that way requirements might not clash with each other. 

for example, i have 2 projects named make_money and spend_money wh

So I have to make 2 different directories and install virtual environment in them, I can run my project from any where, however the dependencies would be installed in that specific project. 

It is kind of similar to NPM for node, and pip is similar to maven in java

Helpful link : https://www.dabapps.com/blog/introduction-to-pip-and-virtualenv-python/

Python : Regular Expression

Regular expressions are text matching patterns described with a formal syntax. You’ll often hear regular expressions referred to as ‘regex’ or ‘regexp’ in conversation. Regular expressions can include a variety of rules, fro finding repetition, to text-matching, and much more.

 

# List of patterns to search for
pattern = ‘term1’

# Text to parse
text = ‘This is a string with term1, but it does not have the other term.’

match = re.search(pattern, text)

type(match)
# Returns a list of all matches
re.findall(‘match’,’test phrase match is in middle’)

 

Repetition Syntax

There are five ways to express repetition in a pattern:

1.) A pattern followed by the metacharacter * is repeated zero or more times. 
2.) Replace the * with + and the pattern must appear at least once. 
3.) Using ? means the pattern appears zero or one time. 
4.) For a specific number of occurrences, use {m} after the pattern, where m is replaced with the number of times         the pattern should repeat. 
5.) Use {m,n} where m is the minimum number of repetitions and n is the maximum. Leaving out n ({m,}) means the           value appears at least m times, with no maximum.

Python : Profiling / timing your code

A good code not only gives expected results but also performs better (i.e takes less time ).

Sometimes its important to know how long your code is taking to run, or at least know if a particular line of code is slowing down your entire project. Python has a built-in timing module to do this.

This module provides a simple way to time small bits of Python code. It has both a Command-Line Interface as well as a callable one. It avoids a number of common traps for measuring execution times.

Lets learn about timeit!

We’ll pass two arguments the actual line we want to test encapsulated as a string and the number of times we wish to run it. Here we’ll choose 10,000 runs to get some high enough numbers to comapre various methods.

import timeit

# For loop
time_to_execute = timeit.timeit(‘”-“.join(str(n) for n in range(100))’, number=10000)
print time_to_execute

# List comprehension
time_to_execute = timeit.timeit(‘”-“.join([str(n) for n in range(100)])’, number=10000)
print time_to_execute

# Map()
time_to_execute = timeit.timeit(‘”-“.join(map(str, range(100)))’, number=10000)
print time_to_execute

 

$$$$$  Output $$$$$$$$$
/usr/bin/python /Users/asee2278/gitRepo/petProjects/pythonPlayground/oop/Debugger.py

0.225734949112
0.197602033615
0.122097969055

We observed that all blocks of code were doing exact same thing, but map() wins over other in terms of performance.