Solved Problems

Output a string to the console

Write the string "Hello World!" to STDOUT
python
print "Hello World!"
# python 3 requires parentheses for print

print('Hello, world!\n')

Retrieve a string containing ampersands from the variables in a url

My PHP script first does a query to obtain customer info for a form. The form has first name and last name fields among others. The customer has put entries such as "Ron & Jean" in the first name field in the database. Then the edit form script is called with variables such as

"http://myserver.com/custinfo/edit.php?mode=view&fname=Ron & Jean&lname=Smith".

The script variable for first name $_REQUEST['firstname'] never gets beyond the "Ron" value because of the ampersand in the data.

I have tried various functions like urldecode but all to no avail. I even tried encoding the url before the view screen is painted so that the url looks like "http://myserver/custinfo/edit.php?mode=view&fname="Ronxxnbsp;xxamp;xxnbsp;Jean"&lname=SMITH". (sorry I had to add the xx to replace the ampersand or it didn't display meaningful url contents the browser sees.)

Of course this fails for the same reasons. What is a better approach?
python
# I'm not really sure this is what the site is for,
# but the one unsolved problem for python was grating me.
# Anyway, I think this is what you're looking for.

from urllib import urlencode

query_dict = {'mode': 'view',
'fname': 'Ron & Jean',
'lname': 'Smith'}

print urlencode(query_dict.items())

# Which will be 'lname=Smith&mode=view&fname=Ron+%26+Jean'.

string-wrap

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> "

Expected output:
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps over t
> he lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox
> jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The qui
> ck brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy
> dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps o
> ver the lazy dog. The quick brown fox jumps over the lazy dog.
python
def wrap(string, length):

while len(string):
print("> " + string[0:length - 1])
string = string[length - 1:].strip()


wrap("The quick brown fox jumps over the lazy dog. " * 10, 78)

Define a string containing special characters

Define the literal string "\#{'}${"}/"
python
# yes, Python has way too many forms of string literals :)
print "\\#{'}${\"}/"
print "\\#{'}${"'"'"}/"
print r"""\#{'}${"}/"""
print '\\#{\'}${"}/'
print '\\#{'"'"'}${"}/'
print r'''\#{'}${"}/'''

Define a multiline string

Define the string:
"This
Is
A
Multiline
String"
python
text = """This
Is
A
Multiline
String"""
# with proper indentation
text = (
"This\n"
"Is\n"
"A\n"
"Multiline\n"
"String"
)

Define a string containing variables and expressions

Given variables a=3 and b=4 output "3+4=7"
python
class EvalDict(dict):
def __getitem__(s, k):
return eval(k, s)

a=3; b=4
"%(a)d+%(b)d=%(a+b)d" % EvalDict(locals())
a=3; b=4
"%d+%d=%d" % (a, b, a+b)

Reverse the characters in a string

Given the string "reverse me", produce the string "em esrever"
python
"reverse me"[::-1]

Reverse the words in a string

Given the string "This is a end, my only friend!", produce the string "friend! only my end, the is This"
python
' '.join(reversed("This is a end, my only friend!".split()))

Text wrapping

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> ", yielding this result:

> The quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog.
python
import textwrap
print textwrap.fill("The quick brown fox jumps over the lazy dog. " * 10,
72, initial_indent="> ", subsequent_indent="> ")

Remove leading and trailing whitespace from a string

Given the string "  hello    " return the string "hello".
python
assert 'hello' == ' hello '.strip()

Simple substitution cipher

Take a string and return the ROT13 and ROT47 (Check Wikipedia) version of the string.
For example:
String is: Hello World #123
ROT13 returns: Uryyb Jbeyq #123
ROT47 returns: w6==@ (@C=5 R`ab
python
# rot13, readable
rot13_tbl = string.maketrans("ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz", "NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm")
string.translate("Hello World #123", rot13_tbl)


#
# "a bad programmer can write bad code in any language"
#

# rot13, "clever"
string.translate("Hello World #123", string.maketrans(string.lowercase+string.uppercase, string.lowercase[13:]+string.lowercase[:13]+string.uppercase[13:]+string.uppercase[:13]))

# rot47, very "clever"
''.join([ord(c) in range(33,127) and chr(((ord(c)-33+47)%(127-33))+33) or c for c in "Hello World #123"])

"Hello World #123".encode('rot13')

Make a string uppercase

Transform "Space Monkey" into "SPACE MONKEY"
python
"Space Monkey".upper()

Make a string lowercase

Transform "Caps ARE overRated" into "caps are overrated"
python
"Caps ARE overRated".lower()

Capitalise the first letter of each word

Transform "man OF stEEL" into "Man Of Steel"
python
from string import capwords
capwords("man OF stEEL")
' '.join(s.capitalize() for s in "man OF stEEL".split())
"man OF stEEL".title()

Find the distance between two points

python
# problem description doesn't say 2D points ;)
from math import sqrt
print sqrt(sum((x-y)**2 for x,y in zip(a, b)))
from math import hypot
print hypot(x2-x1, y2-y1)

Zero pad a number

Given the number 42, pad it to 8 characters like 00000042
python
"%08d" % 42

Right Space pad a number

Given the number 1024 right pad it to 6 characters "1024  "
python
"%-6s" % 1024
str(1024).rjust(6)
'{0: <6}'.format(1024)

Format a decimal number

Format the number 7/8 as a decimal with 2 places: 0.88
python
"%.2f" % (7 / 8.0)
round(7./8., 2)

Left Space pad a number

Given the number 73 left pad it to 10 characters "        73"
python
"%10s" % 73

Generate a random integer in a given range

Produce a random integer between 100 and 200 inclusive
python
import random
random.randint(100, 200)
# uses best entropy source available (e.g. /dev/urandom, CryptGenRandom, ...)

import random
print random.SystemRandom().randint(100,200)

Generate a repeatable random number sequence

Initialise a random number generator with a seed and generate five decimal values. Reset the seed and produce the same values.
python
import random

random.seed(12345)
list1 = [random.randint(1,10) for x in range(5)]

random.seed(12345)
list2 = [random.randint(1,10) for x in range(5)]

assert(list1==list2)

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/
python
found = re.match(r'[A-Z][a-z]+', 'Hello')
if found:
print 'ok'

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/
python
match = re.match(r'one (.*) three', 'one two three')
if match:
print match.group(1)

Check if a string contains a match to a regular expression

Display "ok" if "abc 123 @#$" matches /\d+/
python
found = re.search(r'\d+', 'abc 123 @#$')
if found:
print 'ok'

Loop through a string matching a regex and performing an action for each match

Create a list [fish1,cow3,boat4] when matching "(fish):1 sausage (cow):3 tree (boat):4" with regex /\((\w+)\):(\d+)/
python
map(''.join, re.findall(r"\((\w+)\):(\d+)", "(fish):1 sausage (cow):3 tree (boat):4"))
--------------------------------------------------------------------------
(''.join(m.groups()) for m in re.finditer(r"\((\w+)\):(\d+)", "(fish):1 sausage (cow):3 tree (boat):4"))

Replace the first regex match in a string with a static string

Transform "Red Green Blue" into "R*d Green Blue" by replacing /e/ with "*"
python
print re.sub(r'e', '*', 'Red Green Blue', 1)

Replace all regex matches in a string with a static string

Transform "She sells sea shells" into "She X X shells" by replacing /se\w+/ with "X"
python
transformed = re.sub(r'se\w+', 'X', 'She sells sea shells')

Replace all regex matches in a string with a dynamic string

Transform "The {Quick} Brown {Fox}" into "The kciuQ Brown xoF" by reversing words in braces using the regex /\{(\w+)\}/.
python
transformed = re.sub(r'\{(\w+)\}',
lambda match: match.group(1)[::-1],
'The {Quick} Brown {Fox}')

Define an empty list

Assign the variable "list" to a list with no elements
python
list = []

Define a static list

Define the list [One, Two, Three, Four, Five]
python
list = ['One', 'Two', 'Three', 'Four', 'Five']
print list

Join the elements of a list, separated by commas

Given the list [Apple, Banana, Carrot] produce "Apple, Banana, Carrot"
python
print ", ".join(['Apple', 'Banana', 'Carrot'])

Join the elements of a list, in correct english

Create a function join that takes a List and produces a string containing an english language concatenation of the list. It should work with the following examples:
join([Apple, Banana, Carrot]) = "Apple, Banana, and Carrot"
join([One, Two]) = "One and Two"
join([Lonely]) = "Lonely"
join([]) = ""
python
def join(*x):
if len(x) <= 2:
return ' and '.join(x)
else:
return ', '.join(x[:-1] + ('and ' + x[-1],))

if __name__ == "__main__":
assert join("Apple", "Banana", "Carrot") == "Apple, Banana, and Carrot"
assert join("One", "Two") == "One and Two"
assert join("Lonely") == "Lonely"
assert join(*[]) == ""

Produce the combinations from two lists

Given two lists, produce the list of tuples formed by taking the combinations from the individual lists. E.g. given the letters ["a", "b", "c"] and the numbers [4, 5], produce the list: [["a", 4], ["b", 4], ["c", 4], ["a", 5], ["b", 5], ["c", 5]]
python
[(x, y) for y in [1,2] for x in ['a','b','c']]
import itertools
[x for x in itertools.product(["a", "b", "c"], [4, 5])]

From a List Produce a List of Duplicate Entries

Taking a list:
["andrew", "bob", "chris", "bob"]

Write the code to produce a list of duplicates in the list:
["bob"]
python
import itertools
input = ["andrew", "bob", "chris", "bob"]
input.sort()
output = [k for k, g in itertools.groupby(input, lambda x: x) if len(list(g)) > 1]

Fetch an element of a list by index

Given the list [One, Two, Three, Four, Five], fetch the third element ('Three')
python
list = ['One', 'Two', 'Three', 'Four', 'Five']
list[2]

Fetch the last element of a list

Given the list [Red, Green, Blue], access the last element ('Blue')
python
list = ['Red', 'Green', 'Blue']
list[-1]
Seaton India

Find the common items in two lists

Given two lists, find the common items. E.g. given beans = ['broad', 'mung', 'black', 'red', 'white'] and colors = ['black', 'red', 'blue', 'green'], what are the bean varieties that are also color names?
python
beans = ['broad', 'mung', 'black', 'red', 'white']
colors = ['black', 'red', 'blue', 'green']

common = [b for b in beans if b in colors]
beans = ['broad', 'mung', 'black', 'red', 'white']
colors = ['black', 'red', 'blue', 'green']

common = set(beans) & set(colors)

Display the unique items in a list

Display the unique items in a list, e.g. given ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18], display the unique elements, i.e. with duplicates removed.
python
ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18]

unique_ages = list(set(ages))

Remove an element from a list by index

Given the list [Apple, Banana, Carrot], remove the first element to produce the list [Banana, Carrot]
python
myList = ['Apple', 'Banana', 'Carrot']
print myList
del myList[0]
# or
myList.pop(0) # returns 'Apple'
print myList
Easy trick

a=[Apple, Banana, Carrot]
a=a[1:]

remove first n entry:

a=[n:]

remove last n entry=>

a=[0:-n]

Remove the last element of a list

python
myList = ['Apple', 'Banana', 'Carrot']
myList.pop()

Rotate a list

Given a list ["apple", "orange", "grapes", "bananas"], rotate it by removing the first item and placing it on the end to yield ["orange", "grapes", "bananas", "apple"]
python
l = ["apple", "orange", "grapes", "bananas"]
first, l = l[0], l[1:] + l[:1]
fruit = ['apple', 'orange', 'grapes', 'bananas']
fruit.append(fruit.pop(0))

Assign the natural numbers to the elements of a list in order of their appearance

Convert list elements to unique indices 0, 1, 2, ... based on their order of appearance.

Example:

Input:

["hello", "world", "world", "hello", "!"]

Output:

[0, 1, 1, 0, 2]
python
from functools import partial
from itertools import count
from collections import defaultdict

f = partial(map, defaultdict(count().next).__getitem__)

f(["hello", "world", "world", "hello", "!"])

Gather together corresponding elements from multiple lists

Given several lists, gather together the first element from every list, the second element from every list, and so on for all corresponding index values in the lists. E.g. for these three lists, first = ['Bruce', 'Tommy Lee', 'Bruce'], last = ['Willis', 'Jones', 'Lee'], years = [1955, 1946, 1940] the result should produce 3 actors. The middle actor should be Tommy Lee Jones.
python
first = ['Bruce', 'Tommy Lee', 'Bruce']
last = ['Willis', 'Jones', 'Lee']
years = [1955, 1946, 1940]

actors = zip(first, last, years)

assert len(actors) == 3
assert actors[1] == ('Tommy Lee', 'Jones', 1946)

List Combinations

Given two source lists (or sets), generate a list (or set) of all the pairs derived by combining elements from the individual lists (sets). E.g. given suites = ['H', 'D', 'C', 'S'] and faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'], generate the deck of 52 cards, confirm the deck size and check it contains an expected card, say 'Ace of Hearts'.
python
suites = ('H', 'D', 'C', 'S')
faces = ('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A')
deck = [(face,suite) for suite in suites for face in faces]
assert len(deck) == 52
assert ('A', 'H') in deck

Perform an operation on every item of a list

Perform an operation on every item of a list, e.g.
for the list ["ox", "cat", "deer", "whale"] calculate
the list of sizes of the strings, e.g. [2, 3, 4, 5]
python
print map(lambda x: len(x), ["ox", "cat", "deer", "whale"])
print [len(x) for x in ['ox', 'cat', 'deer', 'whale']]

Split a list of things into numbers and non-numbers

Given a list that might contain e.g. a string, an integer, a float and a date,
split the list into numbers and non-numbers.
python
import re
data = '34234aff340980adf0e0fa0fefl' ## or ''.join(array)

nonDigits = re.findall(re.compile('\D'), data)
digits = re.findall(re.compile('\d'), data)


Test if a condition holds for all items of a list

Given a list, test if a certain logical condition (i.e. predicate) holds for all items of the list.
python
all(x > 1 for x in [2,3,4])

Test if a condition holds for any items of a list

Given a list, test if a certain logical condition (i.e. predicate) holds for any items of the list.
python
any(x > 3 for x in [2, 3, 4])

Define an empty map

python
map = {}

Define an unmodifiable empty map

python
import collections
EmptyDict = collections.namedtuple("EmptyDict", "")
e = EmptyDict()

Define an initial map

Define the map {circle:1, triangle:3, square:4}
python
shapes = {'circle': 1, 'square': 4, 'triangle': 2}
shapes = dict(circle=1, square=4, triangle=2)

Check if a key exists in a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print "ok" if an pet exists for "mary"
python
pets = dict(joe='cat', mary='turtle', bill='canary')
if ("mary" in pets) print "ok"

Retrieve a value from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print the pet for "joe" ("cat")
python
print pets['joe']

Add an entry to a map

Given an empty pets map, add the mapping from "rob" to "dog"
python
pets['rob'] = 'dog'

Remove an entry from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} remove the mapping for "bill" and print "canary"
python
print pets.pop('bill')

Create a histogram map from a list

Given the list [a,b,a,c,b,b], produce a map {a:2, b:3, c:1} which contains the count of each unique item in the list
python
from collections import defaultdict
h = defaultdict(int)
for k in "abacbb":
h[k] += 1

h = {}
for k in "abacbb":
h[k] = h.setdefault(k, 0) + 1
from collections import Counter
h = Counter("abacbb")
print(h)

Categorise a list

Given the list [one, two, three, four, five] produce a map {3:[one, two], 4:[four, five], 5:[three]} which sorts elements into map entries based on their length
python
c = defaultdict(list)
for k in ["one", "two", "four", "three", "five"]:
c[len(k)].append(k)
from itertools import groupby
lst = ["one", "two", "four", "three", "five"]
c = dict((k, list(g)) for k,g in
groupby(sorted(lst, key=lambda x: len(x)), key=lambda x: len(x)))
print(c)

Perform an action if a condition is true (IF .. THEN)

Given a variable name, if the value is "Bob", display the string "Hello, Bob!". Perform no action if the name is not equal.
python
if name == 'Bob':
print 'Hello, Bob!'

Perform different actions depending on a boolean condition (IF .. THEN .. ELSE)

Given a variable age, if the value is greater than 42 display "You are old", otherwise display "You are young"
python
if age > 42:
print 'You are old'
else:
print 'You are young'
print age > 42 and 'You are old' or 'You are young'

Perform different actions depending on several boolean conditions (IF .. THEN .. ELSIF .. ELSE)

python
if age > 84:
print 'You are really ancient'
elif age > 30:
print 'You are middle-aged'
else:
print 'You are young'

Replacing a conditional with many branches with a switch/case statement

Many languages support more compact forms of branching than just if ... then ... else such as switch or case or match. Use such a form to add an appropriate placing suffix to the numbers 1..40, e.g. 1st, 2nd, 3rd, 4th, ..., 11th, 12th, ... 39th, 40th
python
def affix(num):
num = num == 1 and str(num) + 'st' or num == 2 and str(num) + 'nd' or \
num == 3 and str(num) +'rd' or str(num) + 'th'
return num

print [affix(x) for x in xrange(1,41)]

Perform an action multiple times based on a boolean condition, checked before the first action (WHILE .. DO)

Starting with a variable x=1, Print the sequence "1,2,4,8,16,32,64,128," by doubling x and checking that x is less than 150.
python
x = 1
while x < 150:
print '%s, ' % x,
x *= 2

Perform an action multiple times based on a boolean condition, checked after the first action (DO .. WHILE)

Simulate rolling a die until you get a six. Produce random numbers, printing them until a six is rolled. An example output might be "4,2,1,2,6"
python
import random, itertools

def dice():
while True:
yield random.randint(1,6)

print ", ".join(str(d) for d in itertools.takewhile(lambda x: x < 6, dice()))

Perform an action a fixed number of times (FOR)

Display the string "Hello" five times like "HelloHelloHelloHelloHello"
python
print "Hello" * 5
for i in range(5):
print "Hello"

Perform an action a fixed number of times with a counter

Display the string "10 .. 9 .. 8 .. 7 .. 6 .. 5 .. 4 .. 3 .. 2 .. 1 .. Liftoff!"
python
print " .. ".join(str(i) for i in range(10, 0, -1)), ".. liftoff!"

Read the contents of a file into a string

python
contents = open('myFile.txt', 'rt').read()

Process a file one line at a time

Open the source file to your solution and print each line in the file, prefixed by the line number, like:
1> First line of file
2> Second line of file
3> Third line of file
python
for no, line in enumerate(open(__file__)):
print "{0}> {1}".format(no+1, line.rstrip())

Write a string to a file

python
open('test.txt', 'wt').write('Hello World!')

Append to a file

python
open('test.txt', 'at').write('Hello World!\n')

Process each file in a directory

python
import os
results = (process(f) for f in os.listdir(".") if os.path.isfile(f))

Process each file in a directory recursively

python
import os
results = (process(os.path.join(p, n)) for p,d,l in os.walk(".") for n in l)

Parse a date and time from a string

Given the string "2008-05-06 13:29", parse it as a date representing 6th March, 2008 1:29:00pm in the local time zone.
python
import time
time.strptime("2008-05-06 13:29", "%Y-%m-%d %H:%M")

Display information about a date

Display the day of month, day of year, month name and day name of the day 8 days from now.
python
from datetime import datetime, timedelta

eightDaysFromNow = datetime.now() + timedelta(days=8)

print eightDaysFromNow.strftime('%d') # day of month
print eightDaysFromNow.strftime('%j') # day of year
print eightDaysFromNow.strftime('%B') # month name FULL
print eightDaysFromNow.strftime('%A') # day of week name FULL

Display a date in different locales

Display a language/locale friendly version of New Year's Day for 2009 for several languages/locales. E.g. for languages English, French, German, Italian, Dutch the output might be something like:

Thursday, January 1, 2009
jeudi 1 janvier 2009
giovedì 1 gennaio 2009
Donnerstag, 1. Januar 2009
donderdag 1 januari 2009

(Indicate in comments where possible if any language specific or operating system configuration needs to be in place.)
python
from datetime import datetime
from locale import setlocale, LC_TIME

now = datetime(2009, 1, 1)

locales = ('en_us', 'fr_fr', 'it_it', 'de_de', 'nl_nl')
for locale in locales:
setlocale(LC_TIME, locale)
print now.strftime('%A, %B %d %Y')

Display the current date and time

Create a Date object representing the current date and time. Print it out.
If you can also do this without creating a Date object you can show that too.
python
from datetime import datetime
print datetime.utcnow()
OOP

Define a class

Declare a class named Greeter that takes a string on creation and greets using this string if you call the "greet" method.
python
class Greeter(object):
""" Greet someone.
"""
def __init__(self, whom):
self._whom = whom
def greet(self):
print "Hello, %s!" % self._whom

Greeter("world").greet()

Instantiate object with mutable state

Reimplement the Greeter class so that the 'whom' property or data member remains private but is mutable, and is provided with getter and setter methods. Invoke the setter to change the greetee, invoke 'greet', then use the getter in displaying the line, "I have just greeted {whom}.".

For example, if the greetee is changed to 'Tommy' using the setter, the 'greet' method would display:

Hello, Tommy!

The getter would then be used to display the line:

I have just greeted Tommy.
python

class Greeter(object):
_whom = None

def __init__(self, whom):
self._whom = whom

@property
def whom(self):
return self._whom

@propset(whom)
def whom(self, value=None):
self._whom = value

def greet(self):
print 'Helo, %s!' % self._whom

greeter = Greeter('Winston')
greeter.greet()
greeter.whom = 'Tommy'
greeter.greet()
# required for Python 2.5 or less
def propset(prop):
assert isinstance(prop, property)
def helper(func):
return property(prop.fget, func, prop.fdel, prop.__doc__)
return helper

class Greeter(object):
_whom = None

def __init__(self, whom):
self._whom = whom

@property
def whom(self):
return self._whom

@propset(whom)
def whom(self, value=None):
self._whom = value

def greet(self):
print 'Helo, %s!' % self._whom

greeter = Greeter('Winston')
greeter.greet()
greeter.whom = 'Tommy'
greeter.greet()

Implement Inheritance Heirarchy

Implement a Shape abstract class which will form the base of an inheritance hierarchy that models 2D geometric shapes. It will have:

* A non-mutable 'name' property or data member set by derived or descendant classes at construction time
* A 'area' method intended to be overridden by derived or descendant classes ( double precision floating point return value)
* A 'print' method (also for overriding) will display the shape's name, area, and all shape-specific values

Two derived or descendant classes will be created:
* Circle    -> Constructor requires a '
radius' argument, and a 'circumference' method to be implemented  
* Rectangle -> Constructor requires '
length' and 'breadth' arguments, and a 'perimeter' method to be implemented 

Instantiate an object of each class, and invoke each objects '
print' method to show relevant details.
python
#Start with the import statements.
import math # necessary to get the value of pi

class Shape(object):
"""Shape Class"""
def __init__(self):
"""Constructor method"""
pass #Do nothing here
def area(self):
"""The area method"""
pass #Do nothing here
def print_(self):
"""
The print method. Note the trailing underscore - this is because
there is a reserved statement called 'print' in python 2.x. The
trailing underscore is the accepted method of re-using names without
rebinding them
"""
print 'The name is: %s' % self.name #Print the only property we currently have

def _getName(self):
"""The getter method for the 'name' property.
Note that getter methods are generally discouraged in python"""
return self._name

_name = None # The leading underscore gives a weak non-public value
# to a variable. Two leading underscores will mangle its
# name at runtime, to make it more difficult to access.
# Note there is no real 'private' variable type in python.
name = property(_getName, doc='The name of this object')
# property statements work like: property(fget=None, fset=None, fdel=None, doc=None)

class Circle(Shape):
"""Circle Class - a sub class of shape"""
def __init__(self, radius, name='Circle'):
"""Constructor method again"""
Shape.__init__(self) # init the super class
self.radius = radius # Store the radius
self._setCircumference()# Function call
self._name = name

def _setCircumference(self):
self.circumference = 2*math.pi*self.radius

def area(self):
'''Return the area of this circle'''
tmpAera = math.pi * self.radius**2
return tmpAera
def print_(self):
'''The print method'''
super(Circle, self).print_() # This calls the print_ method in
# the super classes of Circle, in
# this case Shape
print 'The radius is: %f' % self.radius
print 'The circumference is %f' % self.circumference
print 'The area is: %f' % self.area()

class Rectangle(Shape):
"""The Rectangle Class"""
def __init__(self, length, breadth, name='Rectangle'):
Shape.__init__(self)
self._name = name
self.length = length
self.breadth = breadth
self.perimeter()
def area(self):
return self.breadth*self.length
def perimeter(self):
self._perimeter = self.breadth*2+self.length*2
return self._perimeter # You have a method return a value and still
# safely call it without handling the return
# value. This would be collected by garbage
# collection.
def print_(self):
super(Rectangle, self).print_()
print 'The length is %f and the breadth is %f' %(self.length, self.breadth)
print 'The perimeter is: %f' %self._perimeter
print 'The area is: %f' % self.area()

if __name__ == '__main__':
rectangle = Rectangle(5,3)
circle = Circle(5, name='Round and Round')
rectangle.print_()
circle.print_()

Implement and use an Interface

Create a Serializable interface consisting of 'save' and 'restore' methods, each of which:

* Accept a stream or handle or descriptor argument for the source or destination
* Save to destination or restore from source the properties or data members of the implementing class (restrict yourself to the primitive types 'int' and 'string')

Next, create a Person class which has 'name' and 'age' properties or data members and implements this interface. Instantiate a Person object, save it to a serial stream, and instantiate a new Person object by restoring it from the serial stream.
python
import pickle

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return "Name: {name}, age: {age}".format(name=self.name, age=self.age)


person = Person("Gaylord Focker", 21)
with open("person.pickle", "wb") as outstream:
pickle.dump(person, outstream)
with open("person.pickle", "rb") as instream:
deserialized_person = pickle.load(instream)
print(deserialized_person)

Check your language appears on the langref.org site

Your language name should appear within the HTML found at the http://langreg.org main page.
python
from urllib import urlopen
print urlopen('http://langref.org').read().find('python') >= 0 and 'found' or 'not found'

Send an email

Use library functions, classes or objects to create a short email addressed to your own email address. The subject should be, "Greetings from langref.org", and the user should be prompted for the message body, and whether to cancel or proceed with sending the email.
python
import smtplib
import locale

from email.mime.text import MIMEText

encoding = locale.getpreferredencoding()

def main():
smtp_servername = "smtp.example.com"

from_addr = "ernie@example.com"
to_addr = "cookie.monster@mailinator.com"

body = raw_input("Enter the email message ")
if not raw_input("Send email? y/N ") in ["y", "Y"]:
print "aborting"
return

message = MIMEText(body, _charset=encoding)

message["From"] = from_addr
message["To"] = to_addr
message["Subject"] = "Greetings from langref.org"

server = smtplib.SMTP(smtp_servername)
server.sendmail(from_addr, to_addr, message.as_string())


if __name__ == "__main__":
main()
XML

Process an XML document

Given the XML Document:

<shopping>
  <item name="bread" quantity="3" price="2.50"/>
  <item name="milk" quantity="2" price="3.50"/>
</shopping>

Print out the total cost of the items, e.g. $14.50
python
from xml.dom.minidom import parseString
document = parseString(
"""<shopping>
<item name="bread" quantity="3" price="2.50"/>
<item name="milk" quantity="2" price="3.50"/>
</shopping>""").documentElement
total = sum([float(item.getAttribute('price')) *
int(item.getAttribute('quantity'))
for item in document.getElementsByTagName('item')])
print '$%.2f' % total

create some XML programmatically

Given the following CSV:

bread,3,2.50
milk,2,3.50

Produce the equivalent information in XML, e.g.:

<shopping>
  <item name="bread" quantity="3" price="2.50" />
  <item name="milk" quantity="2" price="3.50" />
</shopping>
python
from xml.dom import minidom

csv = """bread,3,2.50
milk,2,3.50"""

doc = minidom.Document()
shopping = doc.createElement("shopping")

for line in csv.split("\n"):
name, quantity, price = line.split(",")
el = doc.createElement("item")
el.setAttribute("name", name)
el.setAttribute("quantity", quantity)
el.setAttribute("price", price)
shopping.appendChild(el)

print shopping.toprettyxml()
from xml.etree.ElementTree import Element, SubElement, tostring

csv = """bread,3,2.50
milk,2,3.50"""

root = Element('shopping')

for line in csv.split("\n"):
name, quantity, price = line.split(",")
SubElement(root,'item', {'name' : name,
'quantity' : quantity,
'price' : price })

print tostring(root)

Find all Pythagorean triangles with length or height less than or equal to 20

Pythagorean triangles are right angle triangles whose sides comply with the following equation:

a * a + b * b = c * c

where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides. Find all such triangles where a, b and c are non-zero integers with a and b less than or equal to 20. Sort your results by the size of the hypotenuse. The expected answer is:

[3, 4, 5]
[6, 8, 10]
[5, 12, 13]
[9, 12, 15]
[8, 15, 17]
[12, 16, 20]
[15, 20, 25]
python
from math import sqrt

a = 1
ret = []
while a <= 20:
b = 1
while b <= 20:
c = sqrt((a**2)+(b**2))
if int(c) == c and sorted([a,b,int(c)]) not in ret:
ret.append(sorted([a,b,int(c)]))
b +=1
a +=1
print ret


or if you wanna get snarky..

print sorted(set([tuple(sorted((a,b,int(sqrt((a**2)+(b**2)))))) for a in xrange(1,21) for \
b in xrange(1,21) if int(sqrt((a**2)+(b**2))) == sqrt((a**2)+(b**2))]))

Greatest Common Divisor

Find the largest positive integer that divides two given numbers without a remainder. For example, the GCD of 8 and 12 is 4.

python
def gcd_recursive(i, j):
if min(i, j) == 0:
return max(i, j)
else:
return gcd_recursive(min(i, j), abs(i - j))

def gcd_iterative(i, j):
while min(i, j) != 0:
i, j = min(i, j), abs(i - j)
return max(i, j)

if __name__ == "__main__":
print gcd_recursive(8, 12)
print gcd_iterative(8, 12)
from fractions import gcd
print gcd(8, 12)
Fun

produces a copy of its own source code

In computing, a quine is a computer program which produces a copy of its own source code as its only output.
python
# adapted from a Quine by Sean B. Palmer

print (lambda s='print (lambda s=%r: (s %% s))()': (s % s))()
x='x=%r;print(x%%x)';print(x%x)

Subdivide A Problem To A Pool Of Workers (No Shared Data)

Take a hard to compute problem and split it up between multiple worker threads. In your solution, try to fully utilize available cores or processors. (I'm looking at you, Python!)

Note: In this question, there should be no need for shared state between worker threads while the problem is being solved. Only after every thread completes computation are the answers recombined into a single output.

Example:

-Input-

(In python syntax)

["ab", "we", "tfe", "aoj"]

In other words, a list of random strings.

-Output-

(In python syntax)

[ ["ab", "ba", "aa", "bb", "a", "b"], ["we", "ew", "ww", "ee", "w", "e"], ...

In other words, all possible permutations of each input string are computed.
python
import multiprocessing
import itertools

task_input = ["ab", "we", "tfe", "aoj"]

def all_subperms(s):
return set(reduce(
list.__add__,
([''.join(p) for p in itertools.product(s, repeat=r) if p]
for r in xrange(len(s) + 1))))

p = multiprocessing.Pool(len(task_input))
task_output = p.map(all_subperms, task_input)
print map(list, task_output)

Create a multithreaded "Hello World"

Create a program which outputs the string "Hello World" to the console, multiple times, using separate threads or processes.

Example:

-Output-

Thread one says Hello World!
Thread two says Hello World!
Thread four says Hello World!
Thread three says Hello World!

-Notice that the threads can print in any order.
python
#!/usr/bin/python
from threading import Thread
Nthread = ['one','two','three','four']
def ThreadSpeaks(number):
print "Thread", number, "says Hello World!"
if __name__ == "__main__":
for n in range(0,len(Nthread)):
th =Thread(target=ThreadSpeaks, args=(Nthread[n],))
th.start()

Create read/write lock on a shared resource.

Create multiple threads or processes who are either readers or writers. There should be more readers then writers.

(From Wikipedia):

Multiple readers can read the data in parallel but an exclusive lock is needed while writing the data. When a writer is writing the data, readers will be blocked until the writer is finished writing.

Example:

-Output-

Thread one says that the value is 8.
Thread three says that the value is 8.
Thread two is taking the lock.
Thread four tried to read the value, but could not.
Thread five tried to write to the value, but could not.
Thread two is changing the value to 9.
Thread two is releasing the lock.
Thread four says that the value is 9.
...

--Notice that when a needed resource is locked, a thread can set a timer and try again in the future, or wait to be notified that the resource is no longer locked.
python
#!/usr/bin/python
from threading import Thread, Lock
import time
thread_readers = ['one','two','three']
thread_writer = ['four','five']
lock = Lock()
value = 0

def Threadread(number):
global value
while True:
if lock.acquire(False):
print "Thread", number, "is taking the lock"
value += 1
print "Thread", number, "is changing the value to", value
print "Thread", number, "is releasing the lock."
lock.release()
else:
print "Thread", number, "tried to write to the value, but could not."
def Threadwrite(number):
global value
while True:
if lock.acquire(False):
print "Thread", number ,"four says that the value is", value
else:
print "Thread", number ,"tried to read the value, but could not."
if __name__ == "__main__":
for n in range(0,len(thread_readers)):
th =Thread(target=Threadread, args=(thread_readers[n],))
th.start()
for n in range(0,len(thread_writer)):
th =Thread(target=Threadwrite, args=(thread_writer[n],))
th.start()