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

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