2

I have this code:

import sys
from scipy.stats import binom

def mcnemar_midp(b, c):
    n = b + c
    x = min(b, c)
    dist = binom(n, .5)
    p = 2. * dist.cdf(x)
    midp = p - dist.pmf(x)
    return midp

#get numbers from user
num1 = sys.argv[1]
num2 = sys.argv[2]

# calculate the result
myresult = mcnemar_midp(num1, num2)

# Display the sum
print myresult

which does not work if I call it like this: python mcnemar.py 87 89

However, if I hard-code 2 values for num1 and num2 it works fine. The error I get is the following:

Traceback (most recent call last):
File "mcnemar.py", line 28, in <module>
myresult = mcnemar_midp(num1, num2)
File "mcnemar.py", line 19, in mcnemar_midp
p = 2. * dist.cdf(x)
File "/usr/lib/python2.7/dist-packages/scipy/stats/distributions.py", line 440, in cdf
return self.dist.cdf(x, *self.args, **self.kwds)
File "/usr/lib/python2.7/dist-packages/scipy/stats/distributions.py", line 6635, in cdf
k = asarray((k-loc))
TypeError: unsupported operand type(s) for -: 'numpy.ndarray' and    'numpy.ndarray'

but this in only if I try to pass the numbers from the command line, if I write them inside the code, it works. Please help me, I am new to python!

  • 5
    `num1` and `num2` will be strings if you pass them as commnad-line arguments to a script. The error message doesn't make much sense to me, but I bet that if you use `num1 = int(sys.argv[1])` and `num2 = int(sys.argv[2])` your problem will disappear – juanpa.arrivillaga May 28 '17 at 15:15
  • @juanpa.arrivillaga is correct. The error makes sense because ``n = b + c`` and ``x = min(b, c)`` still work if ``b`` and ``c`` are strings. – GjjvdBurg May 28 '17 at 15:19
  • @GJJ ah yes, I tested it out. The issue is the error message is a bit vague. The `-` operator *is* supported for types `ndarray` and `ndarray`, but *not* if the `dtypes` of those arrays are incompatible, e.g. `object` and `int`. But the error message is a bit generic. But when I try to reproduce it, I'll get something like `TypeError: ufunc 'add' did not contain a loop with signature matching types dtype(' – juanpa.arrivillaga May 28 '17 at 15:22
  • 1
    Ok, can you either write up the solution as an answer and accept it or delete the question? – Sam Hartman May 28 '17 at 15:39

1 Answers1

0

The issue was fixed after the sys.argv values were cast to integers.

alex
  • 6,818
  • 9
  • 52
  • 103