Archive

Posts Tagged ‘file’

A to Z, then Z to A

September 28, 2010 Leave a comment

Challenge

Write a Python script which prints the alphabet from “a” to “z”. Reverse its source code as explained in the previous post, i.e. reverse the order of lines and reverse the order of characters in each line. This reversed script should now print the alphabet from “z” to “a”!

Demonstration:

$ python fromAtoZ.py                                        
a b c d e f g h i j k l m n o p q r s t u v w x y z
$ ./reverse-file.py fromAtoZ.py >za.py
$ python za.py 
z y x w v u t s r q p o n m l k j i h g f e d c b a
$ ./reverse-file.py za.py >az.py
$ python az.py 
a b c d e f g h i j k l m n o p q r s t u v w x y z
$ diff fromAtoZ.py az.py 
$

You can find the script reverse-file.py in my previous post. As you can see, applying reverse-file.py twice, you get back the original file.

Note that this challenge is not specific to Python. It can be solved in C++ too, for instance.

The solution is below, but first try to solve it yourself.
Read more…

Categories: python Tags: , , ,

Reverse a file

September 27, 2010 3 comments

Exercise

Take a text file and reverse it the following ways: (1) reverse characters in each line, and (2) reverse the order of lines too. Let’s see an example:

Input:

#!/usr/bin/env python
print "Please, reverse me completely!"

Output:

"!yletelpmoc em esrever ,esaelP" tnirp
nohtyp vne/nib/rsu/!#

Read more…

Categories: python Tags: , ,