Python - Combo

 
Vista:

Combo

Publicado por Pedro (2 intervenciones) el 03/07/2017 04:06:18
Dato 2 textos por ejemplo:

a = 'carne=10, leche=20, arroz=10, agua=5'
b = 'carne=4, arroz=5, azucar=10'

Devuelva la suma de valores, como el siguiente resultado:

agua=5
arroz=15
azucar=10
carne=14
leche=20

Input Format
carne=10, leche=20, arroz=10, agua=5
carne=4, arroz=5, azucar=10

Constraints
El resultado debe estar en orden alfabetico

Output Format
agua=5
arroz=15
azucar=10
carne=14
leche=20
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
-2
Responder
Imágen de perfil de [abZeroX]
Val: 425
Bronce
Ha mantenido su posición en Python (en relación al último mes)
Gráfica de Python

Combo

Publicado por [abZeroX] (109 intervenciones) el 04/07/2017 06:17:59
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from collections import OrderedDict
 
def sumar_valores(m, n):
    result = {}
    for k, v in m.items():
        if k in n:
            result[k] = v + n[k]
        else:
            result[k] = v
    for k, v in n.items():
        if k not in result:
            result[k] = v
    return result
 
a = 'carne=10, leche=20, arroz=10, agua=5'.replace(' ', '').split(',')
b = 'carne=4, arroz=5, azucar=10'.replace(' ', '').split(',')
x = {i.split('=')[0]:int(i.split('=')[1]) for i in a}
z = {i.split('=')[0]:int(i.split('=')[1]) for i in b}
 
result = OrderedDict(sorted(sumar_valores(z, x)items()))
for k, v in result.items():
    print(k, v)
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar