# Untitled

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