carriot share
carriot share

Reputation: 47

python permutations, including duplicates

I have created a program that determines when the surface area of a cuboid is the same as the area.

from itertools import permutations

def area(l, h, w):
    return(l*h*w)

def surf_area(l, h, w):
    return(((l*h)+(l*w)+(w*h))*2)

for length, height, width in permutations(range(1,100),3):
    if area(length, height, width)== surf_area(length, height, width):
        print("length = {}, height = {}, width = {}".format(length,height,width))

This iterates through the numbers 1-100 and puts them as the height length and width of the cuboid and only returns the answers which have the same area and surface area

This yields:

length = 3, height = 7, width = 42
length = 3, height = 8, width = 24
length = 3, height = 9, width = 18
length = 3, height = 10, width = 15
length = 3, height = 15, width = 10
length = 3, height = 18, width = 9
length = 3, height = 24, width = 8
length = 3, height = 42, width = 7
length = 4, height = 5, width = 20
length = 4, height = 6, width = 12
length = 4, height = 12, width = 6
length = 4, height = 20, width = 5
length = 5, height = 4, width = 20
length = 5, height = 20, width = 4
length = 6, height = 4, width = 12
length = 6, height = 12, width = 4
length = 7, height = 3, width = 42
length = 7, height = 42, width = 3
length = 8, height = 3, width = 24
length = 8, height = 24, width = 3
length = 9, height = 3, width = 18
length = 9, height = 18, width = 3
length = 10, height = 3, width = 15
length = 10, height = 15, width = 3
length = 12, height = 4, width = 6
length = 12, height = 6, width = 4
length = 15, height = 3, width = 10
length = 15, height = 10, width = 3
length = 18, height = 3, width = 9
length = 18, height = 9, width = 3
length = 20, height = 4, width = 5
length = 20, height = 5, width = 4
length = 24, height = 3, width = 8
length = 24, height = 8, width = 3
length = 42, height = 3, width = 7
length = 42, height = 7, width = 3

Now, if you look closely, none of the measurements are ever the same e.g. I would never get the answer (not correct answer)

length = 3, height = 3, width = 3

as it only iterates through the numbers once. How can I include these "doubled" answers?

Upvotes: 3

Views: 2312

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122154

I think you want itertools.product instead of permutations:

for l, w, h in itertools.product(range(1, 100), repeat=3):

This will exhaustively go through all possible combinations of three numbers from 1-99, including cases where l == w == h.

A smaller example:

>>> for l, w, h in itertools.product(range(1, 3), repeat=3):
    print(l, w, h)


(1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 2, 2)
(2, 1, 1)
(2, 1, 2)
(2, 2, 1)
(2, 2, 2)

Upvotes: 5

Related Questions