#!/usr/bin/env python# -*- coding: utf-8 -*-############################ Autor: Ariel Rodriguez# fecha: 07/11/2012# Factorizar string###########################def fact_str(s, sp, so): """fact_str(string, sp, so) factoriza los valores de la lista y retorna un string con la factorizacion.""" facto=[] no_facto=[] ss = s.split(" "+so+" ") ss.sort() fc, cadena_nueva = fact_comun(ss,sp) if [''] in cadena_nueva: cadena_nueva.remove(['']) if fc: for si in cadena_nueva: if fc[1] in si: #factorizo el texto ff = si ff.remove(fc[1]) #agrego el factor if ff: facto.append(', '.join(ff)) else: facto.append('1') else: no_facto.append(', '.join(si)) if facto: if no_facto: s_no = ' + ' s_no_facto = ' + '.join(no_facto) else: s_no_facto = '' s_no = '' return fc[1] + '(' + fact_str(' + '.join(facto),",","+") + ')' + s_no + fact_str(s_no_facto,",","+") else: n_cad = [] for n in cadena_nueva: n_cad.append(', '.join(n)) return ' + '.join(n_cad) def fact_comun(s,sp): claves = {} lst_claves=[] s_nueva=[] for si in s: si = si.split(sp+" ") s_nueva.append(si) for x in si: claves[x] = claves.get(x, 0) + 1 for x in claves: lst_claves.append((claves[x],x)) lst_claves.sort() del claves fc = lst_claves[-1] menor = fc[0] for i in lst_claves: if i[0]<menor: menor = i[0] if fc[0]> menor: return fc, s_nueva else: return None, s_nueva
#!/usr/bin/env python# -*- coding: utf-8 -*-from fact_string import fact_strcadena = "a, b, c, d + a, b, d, f + x, w + b, z + c, x + w"print "#"*25print "Factorizador de Cadena"print "#"*25print "Cadena a factorizar"print cadenanueva_c = fact_str(cadena,",","+")print "#"*25print "Nueva Cadena Factorizada"print nueva_c