Katas in Python (III)

Continuing with the kata series started here, let’s solve the following problem in Python:

Problem

Given an integers array, which has a length between 2 and 26 elements, analyze it and make a new array with letters, representing the order of numbers in input array. Letter A must represent the biggest number, B the second one, etc. Assume that numbers are not repeated.

Write a function which solves this problem.

Sample input:

[7, -20, 900, 87, 0]

Sample output:

[C, E, A, B, D]

Solution

numbers = [2,3,4,67,8,97,6,54,3,4,5,6,7,0,8,9,8,65,4,33,34,556,-34,-23,66,-1]
alphabet = ['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']

sortedNumbers = sorted(numbers, None, None, True)

# create a dictionary to map the list of numbers ordered and the alphabet
map = {}
i = 0
for number in sortedNumbers:
    map[number] = alphabet[i]
    i = i + 1

# print the input mapped to the alphabet
output = "The correspondence between the list of numbers %r and the alphabet is: [" % (numbers)
for number in numbers:
    output = output +  map[number] + ","

output = output + "]"

print output

The first line is an input example. The first thing I is to sort the list of numbers from the biggest to the smallest. Then I make a correspondence between the alphabet and the sorted list. Finally I print it. The key here is the sorted function and how I use it to order a list of numbers from the biggest to the lowest.

More solutions

This is a very interesting solution written by someone who has more Python in his / her fingers than me:

import string

def order_with_letters(list):
    b = {}
    for i,v in enumerate(sorted(list, reverse=True)):
        b[v] = string.ascii_uppercase[i]

    return [b[i] for i in list]

print order_with_letters([7, -20, 900, 87, 0])

This function uses the sorted function along with enumerate, which is quite useful to iterate on a list, because it links a number to a item list; this way it works as an iterator. Finally, the ascii_uppercase function, which is the alphabet itself. Therefore there’s no need to create a list containing the alphabet because this constant list does exactly this!

Katas in Python (II)

Continuing with the kata series started here, let’s solve the following problem in Python:

Problem

You have to write 3 functions to reverse a string in 3 different forms (one function to each one):

  • Reversing the string characters: "this is text" -> "txet si siht"
  • Reversing words (not characters) in the string: "this is text" -> "text is this"
  • Reversing characters in every word of the string: "this is text" -> "siht si txet"

Each function must receive the original string and return a new reversed string. But you can’t use reversing predefined functions of your favourite language. Use only pure code, without facilities.

Solution

from sys import argv

script, text = argv

def printArray(array):
    output = ""
    for item in array:
        output = output + item
    return output

def function_1(text):
    size = len(text)
    result = [None] * size
    i = size - 1
    for letter in text:
        result[i] = letter
        i = i - 1
    return result

def function_2(text):
    words = text.rsplit(" ")
    size = len(words)
    result = [None] * size
    i = size - 1
    for word in words:
        result[i] = word
        result.insert(i," ")
        i = i - 1
    return result

def function_3(text):
    words = text.rsplit(" ")
    size = len(words)
    result = []
    i = size - 1
    for word in words:
        result.append(printArray(function_1(word)))
        result.append(" ")
        i = i - 1
    return result

print "First specification: reverse string -> %r " % (printArray(function_1(text)))
print "Second specification: reverse string -> %r " % (printArray(function_2(text)))
print "Third specification: reverse string -> %r " % (printArray(function_3(text)))

function_1 just reverses the string manually, character by character; function_2 does the same but firstly reading the words of the sentence and reverting word by word. Finally function_3 reads the sentence, and reverses the letters in every word using function_1. Quite simple. I know, I know, the function names are not good ones but it’s an exercise with three parts so I identified part 1, part 2 and part3; so please take it easy 😉

Other interesting solutions

Almost all the solutions I found follow the same approach. The idea is to reverse the string iterating over letters or words depending on the case. A simpler code but still readable is the following:

def reverseStringCharacters(inputString):
final = ""
for letter in inputString:
    final = letter + final
return final.strip()

def reverseWords(inputString):
final = ""
for word in inputString.split():
    final = word + " " + final
return final.strip()

def reverseWordsCharacters(inputString):
final = ""
for word in inputString.split():
    final = final + " " + reverseStringCharacters(word)
return final.strip()

I’d rather this last solution because pre-concatenates the string instead of iterating on a list from the last item backwards to the beginning, which I think it’s less understandable for humans.