Straight-chain alkanes are hydrocarbons with the general stoichiometric formula $\mathrm{C}_n\mathrm{H}_{2n+2}$ in which the carbon atoms form a simple chain: for example, butane, $\mathrm{C_4H_{10}}$ has the structural formula which may be depicted $\mathrm{H_3CCH_2CH_2CH_3}$. Write a program to output the structural formula of such an alkane, given its stoichiometry (assume $n>1$). For example, given stoich='C8H18'
, the output should be:
H3C-CH2-CH2-CH2-CH2-CH2-CH2-CH3
Here's one solution, using stoich='C8H18'
as an example:
stoich = 'C8H18'
fragments = stoich.split('H')
nC = int(fragments[0][1:])
nH = int(fragments[1])
if nH != 2*nC + 2:
print('{} is not an alkane!'.format(stoich))
else:
print('H3C', end='')
for i in range(nC-2):
print('-CH2', end='')
print('-CH3')
The output is:
H3C-CH2-CH2-CH2-CH2-CH2-CH2-CH3