Python Forum
Create a Tensor without importing any modules or libraries
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Create a Tensor without importing any modules or libraries
#1
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
Reply
#2
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
It is more important to do the right thing, than to do the thing right.(P.Drucker)
Better is the enemy of good. (Montesquieu) = French version for 'kiss'.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  importing libraries u18sc11 3 4,238 Jul-26-2017, 05:05 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020