Форум сайта python.su
Здравствуйте!
Завис. По идее долно быть просто, но пока какие-то очень устрашающие алгоритмы в голову приходят.
Помогите,пожалуйста, если есть возможность.
Вам дан список молекул и их атомная масса:
H (водород) — 1.008
O (кислород) — 15.999;
S (сера) — 32.066;
Na (натрий) — 22.990;
Cl (хлор) — 35.453;
K (калий) — 39.098.
Посчитайте молярную массу молекул, используя методы функционального программирования. Выведите значения в порядке возрастания молярной массы.
Входные данные
Вывод программы
H2-O 18.015
H-CL 36.461
NA-CL 58.443
K-CL 74.551
H2-S-O4 98.078
Офлайн
Что на вход подаётся?
Офлайн
Входные данные
Офлайн
список формул молекул:
'H2-S-O4', ‘H2-O’, ‘NA-CL’, ‘H-CL’, ‘K-CL’
Офлайн
ant976
По идее долно быть просто, но пока какие-то очень устрашающие алгоритмы в голову приходят.
…
список формул молекул:['H2-S-O4', 'H2-O', 'NA-CL', 'H-CL', 'K-CL']
def count_mols(lst): pass
def count_mols(lst): out = [count_mol(i) for i in lst] return out
def count_mols(lst): out = [count_mol(i) for i in lst] return out def count_mol(mol): pass
def count_mols(lst): out = [count_mol(i) for i in lst] return out def count_mol(mol): atom_lst = mol.split('-') out = sum([count_atom(i) for i in atom_lst]) return out
def count_mols(lst): out = [count_mol(i) for i in lst] return out def count_mol(mol): atom_lst = mol.split('-') out = sum([count_atom(i) for i in atom_lst]) return out def count_atom(atom): pass
def count_mols(lst): out = [count_mol(i) for i in lst] return out def count_mol(mol): atom_lst = mol.split('-') out = sum([count_atom(i) for i in atom_lst]) return out def count_atom(atom): element = '' number = '' for c in atom: if c.isalpha(): element += c elif c.isdigit(): number += c num = 1 if number: num = int(number) out = count_mass(element, num) return out
def count_mols(lst): out = [count_mol(i) for i in lst] return out def count_mol(mol): atom_lst = mol.split('-') out = sum([count_atom(i) for i in atom_lst]) return out def count_atom(atom): element = '' number = '' for c in atom: if c.isalpha(): element += c elif c.isdigit(): number += c num = 1 if number: num = int(number) out = count_mass(element, num) return out def count_mass(element, number): pass
def count_mols(lst): out = [count_mol(i) for i in lst] return out def count_mol(mol): atom_lst = mol.split('-') out = sum([count_atom(i) for i in atom_lst]) return out def count_atom(atom): element = '' number = '' for c in atom: if c.isalpha(): element += c elif c.isdigit(): number += c num = 1 if number: num = int(number) out = count_mass(element, num) return out def count_mass(element, number): dct = { 'H': 1.008 ... } out = dct[element] * number return out
>>> def count_mols(lst): ... out = [count_mol(i) for i in lst] ... return out ... >>> def count_mol(mol): ... atom_lst = mol.split('-') ... out = sum([count_atom(i) for i in atom_lst]) ... return out ... >>> def count_atom(atom): ... element = '' ... number = '' ... for c in atom: ... if c.isalpha(): ... element += c ... elif c.isdigit(): ... number += c ... num = 1 ... if number: ... num = int(number) ... out = count_mass(element, num) ... return out ... >>> def count_mass(element, number): ... dct = { ... 'H': 1.008 ... } ... out = dct[element] * number ... return out ... >>> count_mols(['H', 'H2', 'H2-H3']) [1.008, 2.016, 5.04] >>>
Отредактировано py.user.next (Ноя. 12, 2024 11:54:57)
Офлайн
py.user.next
зачем так сложно?
d ={} d['H'] = '1.008' d['O'] = '15.999' d['S'] = '32.066' d['NA'] = '22.990' d['CL'] = '35.453' d['K'] = '39.098' arr = ['H2-S-O4','H-CL','NA-CL','K-CL','H2-O'] out = [] for i in arr: t = i for k in d: if k in t: t = t.replace(k,d[k]+'*') t = t.replace('-','+') t = t.replace('*+','+') if t.endswith('*'): t = t[:-1] out.append([i,round(eval(t),3)]) out.sort(key=lambda x: x[1]) for i in out: print('{0:10}{1}'.format(*i))
Офлайн
vic57Вот я добавил в твой код углерод и соляную кислоту
зачем так сложно?
>>> d = {} >>> d['H'] = '1.008' >>> d['O'] = '15.999' >>> d['S'] = '32.066' >>> d['C'] = '12.011' >>> d['NA'] = '22.990' >>> d['CL'] = '35.453' >>> d['K'] = '39.098' >>> arr = ['H-CL', 'H2-S-O4','H-CL','NA-CL','K-CL','H2-O'] >>> out = [] >>> for i in arr: ... t = i ... for k in d: ... if k in t: ... t = t.replace(k,d[k]+'*') ... t = t.replace('-','+') ... t = t.replace('*+','+') ... if t.endswith('*'): ... t = t[:-1] ... out.append([i,round(eval(t),3)]) ... Traceback (most recent call last): File "<stdin>", line 10, in <module> File "<string>", line 1, in <module> NameError: name 'L' is not defined >>> out.sort(key=lambda x: x[1]) >>> for i in out: print('{0:10}{1}'.format(*i)) ... >>>
>>> def count_mols(lst): ... out = [count_mol(i) for i in lst] ... return out ... >>> def count_mol(mol): ... atom_lst = mol.split('-') ... out = sum([count_atom(i) for i in atom_lst]) ... return out ... >>> def count_atom(atom): ... element = '' ... number = '' ... for c in atom: ... if c.isalpha(): ... element += c ... elif c.isdigit(): ... number += c ... num = 1 ... if number: ... num = int(number) ... out = count_mass(element, num) ... return out ... >>> def count_mass(element, number): ... dct = { ... 'H': 1.008, ... 'C': 12.011, ... 'CL': 35.453 ... } ... out = dct[element] * number ... return out ... >>> count_mols(['H', 'H2', 'H2-H3', 'H-CL', 'C-H4']) [1.008, 2.016, 5.04, 36.461000000000006, 16.043] >>>
Отредактировано py.user.next (Ноя. 12, 2024 20:45:55)
Офлайн
vic57
зачем так сложно?)))
import re; molar_mass = lambda f: sum(int(n or 1) * {"H": 1.008, "O": 15.999, "S": 32.066, "Na": 22.990, "Cl": 35.453, "K": 39.098}[e] for e, n in re.findall(r"([A-Z][a-z]*)(\d*)", f)) print(molar_mass("H2-SO4"))
ant976
Завис. По идее долно быть просто, но пока какие-то очень устрашающие алгоритмы в голову приходят.
Офлайн
xam1816Я добавил соляную кислоту в код xam1816import re; molar_mass = lambda f: sum(int(n or 1) * {"H": 1.008, "O": 15.999, "S": 32.066, "Na": 22.990, "Cl": 35.453, "K": 39.098}[e] for e, n in re.findall(r"([A-Z][a-z]*)(\d*)", f)) print(molar_mass("H2-SO4"))
>>> import re; molar_mass = lambda f: sum(int(n or 1) * {"H": 1.008, "O": 15.999, "S": 32.066, "Na": 22.990, "Cl": 35.453, "K": 39.098}[e] for e, n in re.findall(r"([A-Z][a-z]*)(\d*)", f)) >>> print(molar_mass("H-CL")) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <lambda> File "<stdin>", line 1, in <genexpr> KeyError: 'C' >>>
Отредактировано py.user.next (Ноя. 13, 2024 00:15:00)
Офлайн
py.user.next
недосмотрел, согласен
ИМХО тут все что надо - преобразовать выражение H2-S-O4 к виду H*2+O+S*4
import re d ={} d['H'] = 1.008 d['O'] = 15.999 d['S'] = 32.066 d['NA'] = 22.990 d['CL'] = 35.453 d['K'] = 39.098 d['C'] = 10 # d['L'] = 5 #для примера arr = ['H2-S-O4','H-CL','NA-CL','K-CL','H2-O','C-O2'] out = [] for i in arr: t = i.split('-') for j in range(len(t)): match = re.search('\d',t[j]) if match: idx = match.start() m,n = t[j][:idx],int(t[j][idx:]) else: m,n = t[j],1 if m in d: t[j] = d[m]*n out.append([i,round(sum(t),3)]) out.sort(key=lambda x: x[1]) for i in out: print('{0:10}{1}'.format(*i))
H2-O 18.015 H-CL 36.461 C-O2 41.998 NA-CL 58.443 K-CL 74.551 H2-S-O4 98.078
Офлайн