def isLucky(t): s0 = 0; s1 = 0 n = len(t) k = n//2 for i in range(k): s0 += t[i] for i in range(k, n): s1 += t[i] ### if s0 == s1: ### return True ### else: ### return False return s0 == s1 def nextTicket(t): '''Change list jf digits t to the next list in the lexicographic order''' i = len(t) - 1 while i >= 0: if t[i] < 9: t[i] += 1 return True t[i] = 0 i -= 1 return False def printLuckyTickets(n): t = [0]*n while True: if isLucky(t): print(t) if not nextTicket(t): break def luckyTickets(n): '''Return the list of lucky tickets of length n''' res = [] t = [0]*n while True: if isLucky(t): res.append(t.copy()) if not nextTicket(t): break return res def numLuckyTickets(n): numLucky = 0 t = [0]*n while True: if isLucky(t): numLucky += 1 if not nextTicket(t): break return numLucky