Python Forum

Full Version: Create a Tensor without importing any modules or libraries
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am unable to solve this. Tried Nested lists and a variety of different other combinations, but not getting the exact output. Can someone help me with this?

Using Python, construct a class without importing any modules (such as numpy) given the following guidelines:
-Given 2 inputs, data and shape, construct a tensor using nested lists.
-A tensor is a general term for n-dimension matrix. (order goes scalar, vector, matrix, tensor)
-Data and shape inputs are given as lists of numbers. Data can be any number (float, int, etc.), but shape needs to be a list of positive integers.
-Data and shape inputs can be lists of any length.
-The constructed tensor can be saved as an instance variable, printed in standard output, or both.
-If too many data numbers, cut it off after the tensor fills up. If not enough, pad the tensor w/ zeroes.


Examples:
class Tensor():
  ...
  
  def __init__(self, data, shape):
    self.data = data
    self.shape = shape
    self.tensor = ...

  def shape_data(self, ...):  
    ...

  ...

# For Example
>>> data0 = [0, 1, 2, 3, 4, 5, 0.1, 0.2, -3]
>>> shape0 = [2, 3, 2]
>>> tensor0 = Tensor(data0, shape0)

output:
[[[0, 1], [2, 3], [4, 5]], [[0.1, 0.2], [-3, 0], [0, 0]]]



>>> data1 = [0, 1, 2, 3, 4, 5, 0.1, 0.2, -3, -2, -1, 3, 2, 1]
>>> shape1 = [5, 2]
>>> tensor1 = Tensor(data1, shape1)

output:
[[0, 1], [2, 3], [4, 5], [0.1, 0.2], [-3, -2]]
REMEMBER NOT TO IMPORT ANY MODULES OR LIBRARIES
I am unsure if it is the "best" way to do it, but it works for me.
Try this approach:
Imagine you need a 4D "tensor".
Define 4 lists: a, b, c, d
Append d to c, c to b, b to a.
All this in loops.
Once the append to loop is completed, reset the used lists.
Loop again.
Paul