Home>

Beginner of python.

I don't know the type declaration method in python, and I can't fix type errors.
How should I describe it?

The program is
a1 and a2 as constants
Converts a list of length a1a2 to a1 * a2 matrix.
(Example)
a1 = 3
a2 = 3
data = [0,1,2,3,4,5,6,7,8]
When
make_matrix (data) = [[0,1,2], [3,4,5], [6,7,8]]

Error message
Traceback (most recent call last):
  File "test2.py", line 14, in<module>
    print (make_matrix (data))
  File "test2.py", line 12, in make_matrix
    return make_matrix (data [a2:]). insert (0, data [: a2-1])
  File "test2.py", line 12, in make_matrix
    return make_matrix (data [a2:]). insert (0, data [: a2-1])
AttributeError: 'NoneType' object has no attribute 'insert'
Applicable source code
a1 = 3
a2 = 3
N = a1 * a2
data = list (range (N))
print (data)
def make_matrix (data):
    if data == []:
        return []
    else:
        return make_matrix (data [a2:]). insert (0, data [: a2-1])
print (make_matrix (data))

Line 1
from typing import List

make_matrix (data) to make_matrix (data)->List [List [int]]
It was useless even if it changed to.

Supplemental information (FW/tool version etc.)

python 3.8.0

  • Answer # 1

    list.insertdoes not return a value, so you will need to write:

    def make_matrix (data):
        if data == []:
            return []
        else:
            ret = make_matrix (data [a2:])
            ret.insert (0, data [: a2])
            return ret

    It doesn't matter if there is a type declaration.


    You can also write:

    else:
        return [data [: a2], * make_matrix (data [a2:])]

  • Answer # 2

    make_matrix (data [a2:])
    Since the result of is NoneType, the subsequent insert will result in an error
    Let's check what is returned

  • Answer # 3

    a1 = 3
    a2 = 3
    N = a1 * a2
    data = list (range (N))
    def make_matrix (data):
        # print (data)
        if data == []:
            return []
        else:
            tmp = make_matrix (data [a2:])
            tmp.insert (0, data [: a2]) # The return value of insert () is None
            return tmp
    print (make_matrix (data))

Trends