pythonlexicographic

Printing list of list (containing integers) in lexicographic order


Task: You are given three integers x, y and z along with an integer n. You have to print a list of all possible coordinates where the sum of is not equal to n. Print Print the list in lexicographic increasing order.

Below is my code. It works fine except for printing in lexicographic order. Is there a better approach to get lexicographic order of list containing integers?

from itertools import combinations
lst=[]
if __name__ == '__main__':
    x = int(input())
    y = int(input())
    z = int(input())
    n = int(input())
    lst=[[a,b,c]  for b in range(y+1) for c in range(z+1)   for a in range(x+1) ]
   
finallst=[]
for items in combinations(lst,3):
    for nums in items:
       x=sum(nums)
       if x!=n and nums not in finallst:
            finallst.append(nums)

f_finallst= (sorted(map(str,(finallst)))) #converted to string to get lexicographic order
print (f_finallst)

My result

['[0, 0, 0]', '[0, 0, 1]', '[0, 1, 0]', '[1, 0, 0]', '[1, 1, 1]']

Expected result

[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]]

Solution

  • print([coords 
           for coords in itertools.product(range(x+1), range(y+1), range(z+1))
           if sum(coords) != n])