Personal Website

My Web: MindEchoes.com

Sunday, June 21, 2009

Alien Numbers (Code Jam)

Ayer empece a practicar haciendo ejercicios de la competencia de Programacion "Code Jam" de Google, y de paso para ir agarrandole mejor la mano a Python que empece hace poco.

El primer ejercicio era el siguiente:

Problem "Alien Number"

The decimal numeral system is composed of ten digits, which we represent as "0123456789" (the digits in a system are written from lowest to highest). Imagine you have discovered an alien numeral system composed of some number of digits, which may or may not be the same as those used in decimal. For example, if the alien numeral system were represented as "oF8", then the numbers one through ten would be (F, 8, Fo, FF, F8, 8o, 8F, 88, Foo, FoF). We would like to be able to work with numbers in arbitrary alien systems. More generally, we want to be able to convert an arbitrary number that's written in one alien system into a second alien system.

En la pagina se puede seguir viendo las entradas que tiene el programa y las salidas que debe generar, etc.
Aca esta el Codigo que hice para resolver ese ejercicio (conociendo lo que es Python seguramente se puede resolver de manera mas corta jeje)


import sys

def main():
if(len(sys.argv) > 1):
f = open(sys.argv[1], 'r')
cant = int(f.readline())
l = [] #list

#Create list of inputs
for i in range(0, cant):
l.append((f.readline().replace('\n', '')).split(' '))

#Create dictionaries of input lists
line_number = 0
for element in l:
d = {} #dict
value = 0
for num in element[1]:
d[num] = value
value += 1
#convert to decimal
alien_number = element[0]
decimal = 0
for i in range(0, len(alien_number)):
decimal += d[alien_number[i:i+1]] * (len(element[1]) **
(len(alien_number)-i-1))

#convert to the proper base
newNumber = convertBase(decimal, len(element[2]))
converted = ''
for c in newNumber.split('-'):
converted += element[2][int(c)]
print 'Case #'+str(line_number)+':', converted
line_number += 1
else:
print 'FileName Missing'

def convertBase(num, base):
if int(num/base) == 0:
return str(num % base)
return str(convertBase((num/base), base)) + '-' + str(num % base)

if __name__ == '__main__':
main()

Al programa se le pasa al ejecutarlo como argumento el archivo que contiene las entradas como se especifica en la pagina del problema.

Se aceptan Mejoras!! Toda Recomendacion Sirve!!

No comments: