How Many People Are Visible

Python Puzzles

Back to the Python! homepage


There are 5 people, each with a different height. They all stand in a straight line, and you stand directly in front of them looking at them.

How many different arrangements of those 5 people are possible that would have exactly 3 people visible to you?


There are 35 different arrangements.

[(1, 2, 5, 3, 4), (1, 2, 5, 4, 3), (1, 3, 2, 5, 4), (1, 3, 5, 2, 4), (1, 3, 5, 4, 2), 
(1, 4, 2, 3, 5), (1, 4, 2, 5, 3), (1, 4, 3, 2, 5), (1, 4, 3, 5, 2), (1, 4, 5, 2, 3), 
(1, 4, 5, 3, 2), (2, 1, 3, 5, 4), (2, 1, 4, 3, 5), (2, 1, 4, 5, 3), (2, 3, 1, 5, 4), 
(2, 3, 5, 1, 4), (2, 3, 5, 4, 1), (2, 4, 1, 3, 5), (2, 4, 1, 5, 3), (2, 4, 3, 1, 5), 
(2, 4, 3, 5, 1), (2, 4, 5, 1, 3), (2, 4, 5, 3, 1), (3, 1, 2, 4, 5), (3, 1, 4, 2, 5), 
(3, 1, 4, 5, 2), (3, 2, 1, 4, 5), (3, 2, 4, 1, 5), (3, 2, 4, 5, 1), (3, 4, 1, 2, 5), 
(3, 4, 1, 5, 2), (3, 4, 2, 1, 5), (3, 4, 2, 5, 1), (3, 4, 5, 1, 2), (3, 4, 5, 2, 1)]
The number of different arrangements is 35
# import the itertools module to create permutations of the list [1, 2, 3, 4, 5]
import itertools

# create a list of all possible permutations of the list [1, 2, 3, 4, 5]
permutations = list(itertools.permutations([1, 2, 3, 4, 5]))

my_list = []

# loop through each permutation of the list
for my_tuple in permutations:
    
    i = 0
    visible = 1
    
    #initialize the largest value in the tuple to the first value
    largest_value = my_tuple[0]
    
    # loop through each element of the tuple
    while i < len(my_tuple) - 1:
        
        # if the current element is larger than the largest value so far, increment visible and update largest_value
        if largest_value < my_tuple[i+1]:        
            visible = visible + 1
            largest_value = my_tuple[i+1]
            
        i = i + 1
               
    # if there are 3 visible towers, add the tuple to my_list
    if visible == 3: 
        my_list.append(my_tuple)

# print the list of tuples with 3 visible towers and the number of different arrangements
print(my_list) 
print('The number of different arrangements is', len(my_list))