Skip to content

Instantly share code, notes, and snippets.

@LuchoLopez
Created January 19, 2013 08:18
Show Gist options
  • Save LuchoLopez/4571374 to your computer and use it in GitHub Desktop.
Save LuchoLopez/4571374 to your computer and use it in GitHub Desktop.
Procesa una palabra y es capaz de devolver la cantidad de veces que una letra se repite en la misma.
#!/usr/bin/env python
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
###########################################################
# Created by Luis Lopez <luislopez72@gmail.com>
###########################################################
# Esta funcion toma una palabra, analiza sus letras pasando todo a minuscula
# para no discriminar por capitalizacion. Genera un diccionario con la estructura:
# Clave = Letra ; Valor = lista [posicion letra, posicion letra, posicion letra]
def procesarPalabra( palabra ):
# Crea el Diccionario con los resultados
resultado = dict()
for posicion,letra in enumerate( palabra.lower() ):
# Recordar que el indice comienza de 0, por eso se pone posicion+1
if resultado.has_key( letra ):
resultado[letra].append( posicion + 1 )
else:
# Crea una Lista como valor de la clave Letra
resultado[letra] = list()
# Al ser la primera ocurrencia, agregamos a la lista la posicion
resultado[letra].append( posicion + 1 )
return resultado
# Esta funcion se encarga de tomar el diccionario de resultados
# generado por la funcion procesarPalabra y la letra que se quiere
# contar el numero de repeticiones.
def contarOcurrencias( diccionario, letra ):
valor = 0
if diccionario.has_key( letra ):
# Devuelve el numero de repeticiones de la letra en la palabra
valor = len( diccionario[letra] )
return valor
#
# Caso de prueba
#
producto = procesarPalabra( "Hipopotamo" )
print contarOcurrencias( producto, "o" )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment