Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Well, the first problem is that your function just returns <code>None</code>, just throwing away the two lists, so there's no way to even see whether it's doing the right thing.</p> <p>If you fix that, you'll see that it <em>is</em> doing the right thing.</p> <pre><code>def balance_equation(species,coeff): data=zip(coeff,species) positive=[] negative=[] for (mul,el) in data: if mul&lt;0: negative.append((el,mul)) if mul&gt;0: positive.append((el,mul)) return negative, positive &gt;&gt;&gt; n, p = balance_equation(balance_equation('abcdef', range(-3,3)) &gt;&gt;&gt; n [('a', -3), ('b', -2), ('c', -1)] &gt;&gt;&gt; p [('e', 1), ('f', 2)] </code></pre> <p>So, there are two possibilities:</p> <ol> <li>Since the code you pasted is clearly not the actual code you're running, maybe you fixed the bug while rewriting it to post here.</li> <li>You're not calling it with sensible inputs. For example, if you pass the parameters backward, since <code>species</code> is presumably a collection of strings, they'll all end up positive. Or, likewise, if you pass the coeffs as string representations of integers.</li> </ol> <p>If it's the last problem—you're passing, say, <code>'abcdef', ['-3', '-2', '-1', '0', '1', '2', '3']</code>, and you want to deal with that within balance_equation instead of in the calling code, that's easy. Just add this line before the <code>zip</code>:</p> <pre><code>coeff = [int(x) for x in coeff] </code></pre> <p>Or change your <code>zip</code> to:</p> <pre><code>data = zip((int(x) for x in coeff), species) </code></pre> <p>By the way, I'm assuming you're on CPython 2. In Python 3, trying to compare a string to 0 will raise a <code>TypeError</code> instead of always returning <code>True</code>, while in other Python 2 implementations it might always return <code>False</code> instead of <code>True</code>…</p>
 

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