Advertisement
Sekai02

Sequence with product N (python)

Nov 25th, 2024 (edited)
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.15 KB | None | 0 0
  1. #Python 3.7.4
  2.  
  3. import sys
  4.  
  5. # Given two lists of numbers l1 and l2
  6. # returns True if l1 is lexicographically less
  7. # than l2
  8. def lexicographically_less(l1, l2):
  9.     for i in range(0,len(l1)):
  10.         if l1[i]>l2[i]:
  11.             return False
  12.     return True
  13.  
  14. def solve(n, ls):
  15.     def find_sequence(n, ls, prod, seq):    #Function to find the sequence with backtracking
  16.         nonlocal ans    #Best answer so far
  17.         if prod > n:    #If the product is greater than n, we can stop, these cases are not valid
  18.             return
  19.  
  20.         if prod == n:
  21.             if len(ans)==0: #If this is the first valid sequence found
  22.                 ans = seq[:]
  23.                 return
  24.             elif len(seq)<len(ans): #If this sequence is shorter than the best answer so far
  25.                 ans = seq[:]
  26.                 return
  27.             elif len(seq)==len(ans) and lexicographically_less(seq, ans):   #If this sequence has the same size and is lexicographically less than the best answer so far
  28.                 ans = seq[:]
  29.                 return
  30.        
  31.         for num in ls:
  32.             if num*prod > n:    #If the product is greater than n, we can stop, these cases are not valid
  33.                 break           #Break and not continue because values are sorted, any greater value will only increase the product
  34.  
  35.             #Backtrack step
  36.             seq.append(num)
  37.             find_sequence(n, ls, prod*num, seq)
  38.             seq.pop()
  39.  
  40.     ans=[]  #Best answer so far
  41.     seq=[1] #Current sequence
  42.  
  43.     #Remove all repeated elements
  44.     ls = list(set(ls))
  45.  
  46.     #Sort the list
  47.     ls.sort()
  48.  
  49.     #Remove all elements that do not divide n
  50.     #They do not contribute to finding a valid
  51.     #sequence
  52.     ls = [x for x in ls if n % x == 0]    
  53.  
  54.     find_sequence(n, ls, 1, seq)
  55.  
  56.     if len(ans)==0: #Answer not found
  57.         print(-1)
  58.     else:           #Answer found
  59.         for num in ans:
  60.             print(num, end=" ")
  61.         print('\n')
  62.  
  63. if __name__ == "__main__":
  64.     #Read the input
  65.     n, k = map(int, input().split())
  66.     ls = list(map(int, input().split()))
  67.  
  68.     #Call the function to solve the problem
  69.     solve(n, ls)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement