From 668a71638a6f6cac81d9174beef38e698d10f59d Mon Sep 17 00:00:00 2001 From: Matthew Taylor <100451342+MatthewAndreTaylor@users.noreply.github.com> Date: Tue, 23 May 2023 12:06:43 -0400 Subject: [PATCH] Added is-perm Added is-perm, a quick efficient way to check that two iterables are permutations of each other. --- snippets/python/s/is-perm.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 snippets/python/s/is-perm.md diff --git a/snippets/python/s/is-perm.md b/snippets/python/s/is-perm.md new file mode 100644 index 000000000..1319bbd7c --- /dev/null +++ b/snippets/python/s/is-perm.md @@ -0,0 +1,27 @@ +--- +title: Check if two iterables are permutations of each other +type: snippet +language: python +tags: [list] +cover: apples +dateModified: 2023-05-23 10:48:03 +0100 +--- + +Check if two iterables are permutations of each other. + +- Use `Counter` to verify that each element in both iterables appear an equal number of times. + +```py +from collections import Counter + +def is_perm(items0, items1): + return len(items0) == len(items1) and Counter(items0) == Counter(items1) +``` + +```py +is_perm([1, 2, 3], [4, 1, 6]) # False +is_perm([1, 2], [2, 1]) # True + +is_perm("dad", "add") # True +is_perm("snack", "track") # False +```