Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Firstly, the approach looks pretty good for a beginner, thumbs up! Now, to answer your question from the title, the error comes from accessing an element of a sequence that doesn't exist, like e.g. the fifth element of a sequence of four elements. In your case, I guess this is triggered by the <code>cformula[index + 1]</code>, where the index could already be that of the last element. Note that it would also be interesting to know which input triggered this error, my guess is "CO" or "C2H5OH", because both have a compound letter not followed by a numer at the end.</p> <p>Now, how to get around it? A very simple approach is to simply take the rest of the string (which can be empty) and handle its content.</p> <pre><code>count = '' for d in cformula[index + 1:]: if d.isdigit(): count += d else: break </code></pre> <p>This code store all digits after <code>cformula[index]</code> up to the next non-digit. If there are no digits, it store an empty string. Note that this doesn't even care which atom (C, H, O) you are looking at, so it is a good example for code that you could move to a separate function. Then, after calling that function, you check the string of digits:</p> <pre><code>if count == '': # number of atoms is implicitly 1 atoms = 1 else: # number of atoms is explicitly given atoms = int(count) # TODO: discard len(count) elements from the input string </code></pre> <p>BTW: There is a <code>dict</code> type which you could use to store the number of atoms for each element. Similarly, you could use it to store the weight of each atom type:</p> <pre><code>atom_weight = {'C': 15.994, 'H': 1.0079, 'O': 12.011,} weight = atom_weight['C'] * C1 + atom_weight['H'] * H1 + atom_weight['O'] * O1 </code></pre> <p>This doesn't make your code correct, but makes it easier to extend that to the rest of the periodic table. :)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload