views:

848

answers:

13

I need an IronPython\Python example that would show C#/VB.NET developers how awesome this language really is.

I'm looking for an easy to understand code snippet or application I can use to demo Python's capabilities.

Any thoughts?

+17  A: 

Peter Norvig's spelling corrector in 21 lines of Python 2.5.

Dominic Rodger
It's an amazing application - but I'd need to explain a lot for the audience to understand what going on there, I need something simpler.
Dror Helper
FWIW, at DevDays London Michael Sparks explained it fairly comprehensively in one hour, and IMHO it made an excellent introduction to Python.
Dominic Rodger
if it takes an hour to explain a 21-line program, choose a different program!
Steven A. Lowe
I'm afraid that one hour is a bit too long for my needs
Dror Helper
Actually, apart from the edits1 method (which creates similar words for a given word), its not that hard to understand.
Rasmus Kaj
In addition to explaining Python, the spelling algorithm would have to be explained, which is not the goal of the Original Poster.
EOL
@EOL - true, but surely that's the case for any non-trivial bit of code, and it's hardly like the spelling algorithm is massively complex.
Dominic Rodger
In C# can be also write written in 21 lines.http://www.codegrunt.co.uk/code/spell.cs
ralu
@ralu, yeah, but look at it. :-/
Nosredna
+3  A: 

Something simple but cool with generators, maybe?

def isprime(n):
    return all(n%x!=0 for x in range(2, int(n**0.5)+1))

def containsPrime(start, limit):
    return any(isPrime(x) for x in xrange(start, limit))
Rasmus Kaj
Nice. List comprehension and generators would be some of my starting points in showing off Python.
mavnn
+8  A: 

Rewrite any small C# app in IronPython, and show them how many lines of code it took you. If that's not impressing, I don't know what is.

I'm referring to one of your internal apps.

Geo
thing is I'd take readability over less lines any day.
Zeus
It's inevitable that the number of lines will greatly decrease. I'm pretty sure Python's readability won't have to suffer.
Geo
+2  A: 

Generators, defining an iterator, simple

http://ttsiodras.googlepages.com/yield.html

dagoof
+1  A: 

How about a prime number generator.

>>> def sieve(x):
...    if x: return [ x[0] ] + sieve([ y for y in x if y % x[0] > 0 ])
...    return []
... 
>>> sieve(range(2,100))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
eduffy
+3  A: 

How about a demonstration of duck typing? Redirecting StdOut to a gui, for example.

Or some of the exceptionally useful pure python libraries out there (SqlAlchemy springs to mind in my line of work, your mileage may vary).

Some of the short cut bits of syntax would be good as well, for example:

Get a quick overview of a large dataset:

print data[::1000]

Find all the strings that begin with 'a':

[s for s in list_of_strings if s.startswith('a')]

Then show them the generator version:

the_as = (s for s in really_big_list_of_strings if s.startswith('a'))
the_as.next()
mavnn
+1  A: 

Show them an example from the IronPython cookbook like this one on DataGridView Custom Formatting. It's not terribly flashy, but it is something that everyone will be familiar with because just about everyone has built an app with a gridview (or wants to do so).

The most important part of your demo will be the code walkthrough where you point out how things are less verbose than C# and more similar to VB.

Make sure to change the example from the cookbook to show some of the batteries included from Python. Perhaps use the os module to get a directory listing and populate the grid with filename, size, date created, etc.

Michael Dillon
+5  A: 

I'd do a quick demo of something trivial (in Python, at least) but cool in IDLE. For instance:

>>> text = # some nice long text, e.g. the Gettysburg Address
>>> letters = [c.lower() for c in text if c.isalpha()]
>>> letters
    ['f', 'o', 'u', 'r', 's', 'c', 'o', 'r', 'e', 'a', 'n', 'd', 's', 'e', 'v', 'e',
    ...
>>> freq = {}
>>> for c in letters:
        freq[c] = freq.get(c, 0) + 1

>>> freq
    {'a': 102, 'c': 31, 'b': 14, 'e': 165, 'd': 58, 'g': 28, 'f': 27, 'i': 68, 'h': 80, 
    ...
>>> for c in sorted(freq.keys(), key=lambda x: freq[x], reverse=True):
        print c, freq[c]

e 165
t 126
a 102
...

This shows off what the basic list and dictionary classes look like, how list comprehensions work, named arguments, lambda expressions, the usefulness of an interactive interpreter, and it accomplishes a fairly complicated task in seven lines of code.

Edit:

Oh, and I'd then show off how the code works if you set letters using a generator expression:

letters = (c.lower() for c in text if c.isalpha())

...which is to say, exactly the same.

Robert Rossney
it's a shame that [`collections.Counter`](http://docs.python.org/3.1/library/collections.html#collections.Counter) would do all the work for you then :)
SilentGhost
It astonishes me how often it happens that I build something in Python that turns out to already exist.
Robert Rossney
OK, it doesn't exist in 2.6. I feel marginally less dumb now.
Robert Rossney
+2  A: 

You could use CherryPy's helloworld example:

import cherrypy

class HelloWorld(object):
    def index(self):
        return "Hello World!"
    index.exposed = True

cherrypy.quickstart(HelloWorld())
Jason Baker
+3  A: 

I have to agree Geo. Show a C# or VB app next to the same app written in IronPython. When I've done my IronPython talks, I've had a lot of success morphing C# code into Python. It makes for a very dramatic presentation.

I'm also a big fan of showing off how duck typing makes your code more testable.

Darrell Hawley
+3  A: 

At the very basic level you could show a string reversal program in C# and Python.

In C#:

public static string ReverseString(string s)
{
    char[] arr = s.ToCharArray();
    Array.Reverse(arr);
    return new string(arr);
}

In Python:

s[::-1]

I feel that you should demo multiple examples rather than just one. Build up from something simple, like the one above, and go to more complex ones.

Rohit
To someone unfamiliar with Python, s[::-1] probably appears to be cat-like typing.
Nosredna
+3  A: 
import clr
clr.AddReference('System.Speech')
clr.AddReference('System.Xml')

from System.Speech.Synthesis import SpeechSynthesizer
from System.Net import WebClient
from System.Xml import XmlDocument, XmlTextReader


content = WebClient().DownloadString("http://twitter.com/statuses/public_timeline.xml")
xmlDoc = XmlDocument()
spk = SpeechSynthesizer()

xmlDoc.LoadXml(content)
statusesNode = xmlDoc.SelectSingleNode("statuses")
for status in statusesNode:
    s = "<?xml version=\"1.0\"?><speak version=\"1.0\" xml:lang=\"en-US\"><break/>"
    s = s + status.SelectSingleNode("text").InnerText + "</speak>"
    spk.SpeakSsml(s)

A talking Twitter client. For more examples http://www.ironpython.info/index.php/Main_Page

daftspaniel
Wouldn't be just as easy doing it using C#?
Dror Helper
Hi Dror, I suspect the c# would be more LOC. This example demos ease of .Net integration and shows Python's readability. Agree that you would probably want an example some ninja stuff with lists or dictionaries in addition to this. Good luck!
daftspaniel
A: 

The possibility of doing this thanks to IronPython ability to add new members to a type at runtime impressed me

http://ironpython-resource.com/post/2008/08/23/IronPython-Dynamically-creating-objects-and-binding-them-to-a-form.aspx

Pablo