Array of numpy to display conversion problems

For some reason, evalRow(list(array([0, 1, 0, 0, 0])))they evalRow([0, 1, 0, 0, 0])give different results. However, if I use magicConvert(here to debug this) instead list, to go from a numpy array to a list, it works as expected. Is this a bug in numpy?

def magicConvert(a):
  ss = str(list(a))[1:-1]
  return map(int, ss.split(","))

# You don't actually need to read these functions, just here to reproduce the error:
from itertools import *
def evalRow(r):
  grouped = map(
    lambda (v, l): (v, len(tuple(l))),
    groupby(chain([2], r, [2])))
  result = 0
  for player in (1, -1):
    for (pre, mid, post) in allTuples(grouped, 3):
      if mid[0] == player:
        result += player * streakScore(mid[1], (pre[0] == 0) + (post[0] == 0))
  return result

def streakScore(size, blanks):
  return 0 if blanks == 0 else (
    100 ** (size - 1) * (1 if blanks == 1 else 10))

def allTuples(l, size):
  return map(lambda i: l[i : i + size], xrange(len(l) - size + 1))
+4
source share
2 answers

The difference in behavior is related to the fact that execution list(some_array)returns a list numpy.int64, while conversion through a string representation (or equivalently using a method tolist()) returns a list of python ints:

In [21]: import numpy as np

In [22]: ar = np.array([1,2,3])

In [23]: list(ar)
Out[23]: [1, 2, 3]

In [24]: type(list(ar)[0])
Out[24]: numpy.int64

In [25]: type(ar.tolist()[0])
Out[25]: builtins.int

I believe the culprit is 100 ** (size - 1)part of your code:

In [26]: 100 ** (np.int64(50) - 1)
Out[26]: 0

In [27]: 100 ** (50 - 1)
Out[27]: 100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

In [28]: type(100 ** (np.int64(50) - 1))
Out[28]: numpy.int64

, , int64, "", python int .

:

  • numpy python, , array.tolist()
  • , numpy , . , numpy, ( ).
  • ​​python/ numpy/ . . , 99,999% , - . , , , .
+9

, differnet. , , , ?

tolist() numpy .

evalRow(array([0, 1, 0, 0, 0]).tolist()) == evalRow([0, 1, 0, 0, 0])
#output: True
+3

All Articles