Advertisement
Nenogzar

Untitled

Aug 22nd, 2023
997
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | None | 0 0
  1. def permute(nums):
  2.     """
  3.    Return all permutations of the given list.
  4.    >>> permute([1, 2, 3])
  5.    [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]]
  6.    """
  7.     def backtrack(start):
  8.         """
  9.        Generate permutations by recursively swapping elements.
  10.        """
  11.         if start == len(nums) - 1:
  12.             output.append(nums[:])
  13.         else:
  14.             for i in range(start, len(nums)):
  15.                 nums[start], nums[i] = nums[i], nums[start]
  16.                 backtrack(start + 1)
  17.                 # backtrack
  18.                 nums[start], nums[i] = nums[i], nums[start]
  19.  
  20.     output = []
  21.     backtrack(0)
  22.     return output
  23.  
  24.  
  25. # input the list from keyboard
  26. while True:
  27.     input_str = input("enter a list of numbers separated by commas: ")
  28.     nums = [int(x) for x in input_str.split(',') if x.strip().isdigit()]
  29.  
  30.     if nums:
  31.         break
  32.     else:
  33.         print("Invalid input. Please, try again.")
  34.  
  35. res = permute(nums)
  36. print(f"Permutations of the list {nums} are: {res}")
  37.  
Tags: permutation
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement