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 1/2] 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 +``` From 68690c570b0ec56050dd012d49dd5adc4b922acb Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Tue, 23 May 2023 23:40:04 +0300 Subject: [PATCH 2/2] Update and rename is-perm.md to iterable-is-permutation.md --- .../python/s/{is-perm.md => iterable-is-permutation.md} | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) rename snippets/python/s/{is-perm.md => iterable-is-permutation.md} (64%) diff --git a/snippets/python/s/is-perm.md b/snippets/python/s/iterable-is-permutation.md similarity index 64% rename from snippets/python/s/is-perm.md rename to snippets/python/s/iterable-is-permutation.md index 1319bbd7c..3ba479caf 100644 --- a/snippets/python/s/is-perm.md +++ b/snippets/python/s/iterable-is-permutation.md @@ -1,15 +1,17 @@ --- title: Check if two iterables are permutations of each other +shortTitle: Iterable permutations type: snippet language: python -tags: [list] +tags: [list,string] cover: apples -dateModified: 2023-05-23 10:48:03 +0100 +dateModified: 2023-05-23T10:48:03+03:00 --- 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. +- Use `len` to check if both iterables have the same length. +- Use `Counter` to verify that each element appears an equal number of times in both iterables. ```py from collections import Counter