Archive

Posts Tagged ‘reverse’

Reverse a part (slice) of a list

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

Solution
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

Exercise
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.

Solution
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]
't'
>>> 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.

Categories: python

Reverse an integer

September 29, 2010 1 comment

Exercise

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

Solution

```#!/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.

Notes

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

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.

Categories: python Tags: , , ,

Reverse a file

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
```

Output:

```"!yletelpmoc em esrever ,esaelP" tnirp
nohtyp vne/nib/rsu/!#
```
Categories: python Tags: , ,

Reverse a string

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

Solution:

```#!/usr/bin/env python

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.

Solution:

```#!/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: , , ,