0

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. Works fine except for printing in lexicographic order. Below is my code.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]]
Sel_Python
  • 191
  • 2
  • 7
  • 16
  • 1
    Just do `finallst.sort()` without converting the lists to strings. – Aran-Fey Aug 30 '18 at 17:46
  • When you say lexicographical order, you mean character by character or element by element? By example, which of these is ordered: [[100, 0], [90, 0]] or [[90, 0], [100, 0]] – Olivier Melançon Aug 30 '18 at 17:50

4 Answers4

1
x = int(input())
y = int(input())
z = int(input())
n = int(input())
lists=[[i,j,k] for i in range(x+1)
               for j in range(y+1)
               for k in range(z+1) if (i+j+k)!=n]
print(lists)
Dmitry Kuzminov
  • 6,180
  • 6
  • 18
  • 40
0
print([coords 
       for coords in itertools.product(range(x+1), range(y+1), range(z+1))
       if sum(coords) != n])
BallpointBen
  • 9,406
  • 1
  • 32
  • 62
0

By using map(str, finallst), you cast each of the element in the list to a str. You want to keep the elements as they are, but use str as a sorting key.

f_finallst= sorted(finallst, key=str)
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
0

I found out that adding the lambda function, which basically works as the key for the sort comparison will do the trick. For a detailed explanation read here

if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())

orginal_list = [[i, j, k] for k in range(z+1) for j in range(y+1) for i in range(x+1) if i + j + k != n]

sorted_list = sorted(orginal_list, key = lambda i: (len(i), i)) 


print(sorted_list)