markpasc (markpasc) wrote,
markpasc
markpasc

  • Music:

Python example

lapdragon mentioned he never completely grokked bubble sort, so I wrote this short Python implementation. I consider it a good example of what Python code looks like, though it doesn't show classes or anything.

>>> def bubble(array):
...    moved = 1
...    while moved:
...       moved = 0
...       for i in range(0, len(array)-1):
...          if array[i+1] < array[i]:
...             moved = 1
...             array[i], array[i+1] = array[i+1], array[i]
...    return array
...
>>> array = [85, 89, 33, 28, 58, 42, 64]
>>> bubble(array)
[28, 33, 42, 58, 64, 85, 89]
>>>

The >>> and ... are the prompts for the Python shell. The shell makes Python the wonderfullest language to program in: instead of writing a short test program, debugging it, compiling it, and running it, you can open the shell and write whatever you like and see what sticks. Then you can copy what works out of the shell and into your program.

premchai21 has been getting into Ruby. I'm kind of wary of the keyword-bracketed blocks; reminds me of Pascal, which wasn't very fun the few times I wrote in it. I love Python's whitespace demarcation of blocks. Maybe he could share a quick bubble sort in Ruby, though, so I could see what it's like...

Subscribe
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

  • 10 comments