Advertisement
kingbode

Untitled

Aug 15th, 2022
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.88 KB | None | 0 0
  1.  
  2. # please get the 1st and 2nd largest number from the combination of a given number
  3.  
  4. perm_mem = {}
  5.  
  6. def perm(_list):
  7.     global perm_mem
  8.     if perm_mem.get(tuple(_list)) is not None:
  9.         return perm_mem[tuple(_list)]
  10.     if len(_list) == 1:
  11.         perm_mem[tuple(_list)] = [_list]
  12.         return [_list]
  13.     else:
  14.         result = []
  15.         for i in range(len(_list)):
  16.             x = _list[i]
  17.             y = _list[:i] + _list[i+1:]
  18.             for p in perm(y):
  19.                 if [x] + p not in result:
  20.                     result.append([x] + p)
  21.  
  22.         perm_mem[tuple(_list)] = result
  23.         return result
  24.  
  25.  
  26.  
  27. input = 4358
  28. result = perm(list(str(input)))
  29.  
  30. output = []
  31. [output.append(int(''.join(map(str, x)))) for x in result]
  32. print(result)
  33. print(output)
  34. output.sort(reverse=True)
  35. print(output)
  36. print(f'1st largest: {output[0]} and 2nd largest: {output[1]}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement