Katas in Python (III)

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


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]


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!



Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s