Multiplying all combinations of three variables in a table

Question:

I’m new to Python and taking a class for it. I’m stuck on one part of my homework, where I have to create a table that calculates the volume (length x width x height) of all rectangular shapes where the length, width, and heights must be between 1 and 5. So the table should be like this:

Length Width Height Volume
1 1 1 1
1 1 2 2
1 1 5 5
1 2 1 2
1 2 2 4
1 2 3 6

I have tried this but it got me an error.

length = range (1,5)
width = range (1,5)
height = range (1,5)
volume = length * width * height
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    volume = length * width * height
TypeError: unsupported operand type(s) for *: 'range' and 'range'

I also tried a zip command I saw online but it didn’t help much either. I guess how would I start the code?

length = [1, 2, 3, 4, 5]
width = [1, 2, 3, 4, 5]
height = [1, 2, 3, 4, 5]
volume = [i * j * n for i, j, n in zip(length, width, height)]

print("length", "width", "height", "volumen", length, width, height, volume)
length width height volume
[1, 2, 3, 4, 5] [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] [1, 8, 27, 64, 125]

#This doesn't do all of the combinations like I wanted
Asked By: ForeverLost20

||

Answers:

I think what you want may be something like

length = [1, 2, 3, 4, 5]
width = [1, 2, 3, 4, 5]
height = [1, 2, 3, 4, 5]
table = [(l, w, h, l*w*h) for l in length for w in width for h in height]

The command zip creates tuples that you can then work with, which is useful if you want to do something with the first element of list 1 and the first element of list 2, then with the second element of list 1 and the second element of list 2 and so on. But if you want to actually use all combinations you can use list comprehension like I have written above. Understanding list comprehension is a really useful skill for when you are starting python, so I really recommend looking into it!

One thing you might also run into, is that range(5) and [1,2,3,4,5]are not exactly the same thing. The first one is a generator which is a bit different. Don’t worry too much about it at the beginning. Just sometimes things will only work on list, and then doing something like list(range(5))might help.

Good luck 🙂

Answered By: Wormfan
length = [1,2,3,4,5]
height = [1,2,3,4,5]
width = [1,2,3,4,5]
volume_list = []

for i in length:
    for j in height:
        for k in width:
            print(f'length {i}, width {j}, height {k}, volume {i*j*k}')


            #store each volume in the list called volume_list.
            volume_list.append(i*j*k)

# Remove Hastag to print the volumes in list.
#print(volume_list)

You may try this code. This code will display your table and construct a list of all volumes.

Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.