Posts Tagged ‘reverse’

Reverse a part (slice) of a list

March 21, 2012 Leave a comment

You have a list and you want to reverse a part (slice) of it.

Let our list be [1,2,9,6,5] and say we want to reverse its end from element 9, i.e. we want to get [1,2,5,6,9].

a = [1,2,9,6,5]
i = 2    # reverse from this index position
j = 4    # reverse until this index position (included)
a[i:j+1] = reversed(a[i:j+1])
print a    # [1, 2, 5, 6, 9]
Categories: python Tags: ,

Reverse a string (or list) in place

June 29, 2011 7 comments

Take a string and reverse it in place, i.e. you are not allowed to use another string to store the result. The question concerns the algorithmic part.

Well, this problem cannot be solved in Python because strings are immutable, i.e. once you create a string, you cannot change it:

>>> s = 'test'
>>> s[0]
>>> s[0] = 'T'
Traceback (most recent call last):
  File "", line 1, in
TypeError: 'str' object does not support item assignment

Note that you would have a similar problem in Java too. However, in C you could change a string in place, but in C a string is actually an array of characters.

To solve this problem in Python, we need to work with an array of characters instead. So, let’s convert a string to a list of characters:

>>> a = 'Jabba Laci'
>>> li = []
>>> li.extend(a)
>>> li
['J', 'a', 'b', 'b', 'a', ' ', 'L', 'a', 'c', 'i']

Now let’s reverse the list in place:

>>> size = len(li)
>>> for i in range(0, size/2):
...     li[i], li[size-1-i] = li[size-1-i], li[i]
>>> li
['i', 'c', 'a', 'L', ' ', 'a', 'b', 'b', 'a', 'J']
>>> ''.join(li)
'icaL abbaJ'

Related post

See this problem @reddit.

Reverse an integer

September 29, 2010 3 comments


Take an integer and reverse its digits. The result is also an integer. Example: 83657 becomes 75638.


#!/usr/bin/env python

def reverse_int(n):
    return int(str(n)[::-1])

n = 83657
print n                 # 83657
print reverse_int(n)    # 75638

Summary: convert the number to string, reverse the string, then convert it back to integer. Details: 83657 -> str(83657) returns "83657" which is a string -> reverse it, we get "75638" -> int("75638") converts it to an integer.


If you want to concatenate a string and an integer, first you need to convert the integer to string. Example:

n = 83657
print "The value of n is " + n          # error, won't work
print "The value of n is " + str(n)     # OK
Categories: python Tags: , ,

A to Z, then Z to A

September 28, 2010 Leave a comment


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”!


$ python                                        
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
$ ./ >
$ python 
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
$ ./ >
$ python 
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 

You can find the script in my previous post. As you can see, applying 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


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:


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


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

Read more…

Categories: python Tags: , ,

Reverse a string

September 23, 2010 Leave a comment

Exercise #1: Take a string and reverse its characters. For instance “ab12” => “21ba”.


#!/usr/bin/env python

s = 'Python adventures'
print s         # Python adventures
print s[::-1]   # serutnevda nohtyP

Slice notation has the form [start:stop:step]. By default, start is at the beginning of a sequence, stop is at the end, and step is 1. So the slice [::-1] returns the full sequence in reverse order.

Exercise #2: Decide if a word is a palindrome.


#!/usr/bin/env python

def is_palindrome(str):
    return str == str[::-1]

print is_palindrome('1367631')      # True
print is_palindrome('Python')       # False
Categories: python Tags: , , ,