我正在编写一个代码,以查找加起来为用户指定的摩尔质量的元素的每个组合,这与著名的count-the-coins问题不同,只是我想输出的所有组合列表给出答案。到目前为止,我的工作效果很好,但是每个元素都依赖于嵌套的for循环:
target = int(input('Desired Mass? '))
max_H = int(input('max wt% hydrogen (30 suggested)? '))
for Cl37 in range(0, 1+target//37):
rem_Cl37 = target - 37*Cl37
for Cl35 in range(0, 1+rem_Cl37//35):
rem_Cl35 = rem_Cl37 - 35*Cl35
for S in range(0, 1+rem_Cl35//32):
rem_S = rem_Cl35 - 32*S
for P in range(0, 1+rem_S//31):
rem_P = rem_S - 31*P
for Si in range(0, 1+rem_P//28):
rem_Si = rem_P - 28*Si
for F in range(0, 1+rem_Si//19):
rem_F = rem_Si - 19*F
for O in range(0, 1+rem_F//16):
rem_O = rem_F - 16*O
for N in range(0, 1+rem_O//14):
rem_N = rem_O - 14*N
for C in range(0, 1+rem_N//12):
rem_C = rem_N - 12*C
for H in range(0, 1+rem_C//1):
rem_H = rem_C - 1*H
if 37*Cl37+35*Cl35+32*S+31*P+28*Si+19*F+16*O+14*N+12*C+1*H == target:
if H/target > (max_H/100):
break
nonzeroes = ''
elements = [['37Cl', Cl37],['35Cl', Cl35],['S',S],
['P',P],['Si',Si],['F',F],['O',O],
['N',N],['C',C],['H',H]]
for n in range(len(elements)):
if elements[n][1]>0:
nonzeroes += elements[n][0]+str(elements[n][1])+' '
print(nonzeroes)
break
if 37*Cl37+35*Cl35+32*S+31*P+28*Si+19*F+16*O+14*N+12*C+1*H>50:
break
很显然,如果要包括整个元素周期表,这会变得很快。有没有办法嵌套每个for循环,也许使用一个列表来包含当前代码包含在先前的for循环中的信息?