<jupyter_start><jupyter_text>20-07-09: Daily Practice ------ Daily practices* [ ] [Practice & learn](Practice-&-learn)  * [ ] Coding, algorithms & data structures  * [ ] Data science: access, manipulation, analysis, visualization  * [ ] Engineering: SQL, PySpark, APIs, TDD, OOP  * [ ] Machine learning: Scikit-learn, TensorFlow, PyTorch  * [ ] Interview questions (out loud)* [ ] [Meta-data: reading & writing](Meta-data:-reading-&-writing)  * [ ] Blog* [ ] [2-Hour Job Search](2-Hour-Job-Search)  * [ ] LAMP List  * [ ] Networking  * [ ] Social media ------ Practice & learn --- Coding, algorithms & data structures  [Permutations (medium)](https://leetcode.com/problems/permutations/)Given a collection of distinct integers, return all possible permutations.Example:    Input: [1,2,3]    Output:    [      [1,2,3],      [1,3,2],      [2,1,3],      [2,3,1],      [3,1,2],      [3,2,1]    ]<jupyter_code>nums = [1, 2, 3]

nums_out = [
  [1, 2, 3],
  [1, 3, 2],
  [2, 1, 3],
  [2, 3, 1],
  [3, 1, 2],
  [3, 2, 1],
]

from typing import List

def permute(nums: List[int]) -> List[List[int]]:
    # === Base case: nums is length 1 === #
    if len(nums) < 2:
        return [nums]
    
    permutations = []
    
    for i in range(len(nums)):
        nums2 = nums.copy()
        # Freeze index i
        frozen = nums2.pop(i)
        # Permute recursively on the rest of the numbers
        new_nums = permute(nums2)
        for num in new_nums:
            permutations.append([frozen, *num])

    return permutations

nums = [1, 2, 3]
permute(nums)
# Just testing out list unpacking
def ret(nums):
    return [*nums]

ret(nums)<jupyter_output><empty_output><jupyter_text>Success* Runtime: 48 ms, faster than 31.31% of Python3 online submissions for Permutations.* Memory Usage: 14 MB, less than 47.86% of Python3 online submissions for Permutations.<jupyter_code># === Pretty genius solution found on SO === #
# Doesn't work in my case because of yield, but thought it was interesting

def permute(nums: List[int]) -> List[List[int]]:
    if not nums:
        yield []
    for i in range(len(nums)):
        for p in permute(nums[:i] + nums[i + 1 :]):
            yield [nums[i], *p]


nums = [1, 2, 3]
print(list(permutations(nums)))<jupyter_output>[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
StarcoderdataJupyterStructuredCleanDedup