Keen-ameteur
Keen-ameteur

Reputation: 125

Creating a set of sub arrays from a given array in Python

I've been trying to realize the following idea in Python:

Given an array of characters of length n, arr, I want to create a set all sub arrays of length k<n of the array. My idea is to generate an empty set in python and then adding the subarrays by a loop with the union operator '|' in python.

The problem I'm having is when I'm 'realising' this code it says it is not hashable, which I don't really understand the concept. This seems like a relatively simple idea, so I'm pretty sure the solution should be simple, but I'm a novice at coding.

I attach below the code I tried to write, in the hope that someone can point the error in the code and hopefully how to correct it:

...
# arr is the given array of characters, size is the given k, len(arr) is n
set = set()
for i in range ( len(arr)- size -1 ):
      temp = arr[i: i+size]
      set = set | {temp}
...

Upvotes: 0

Views: 1955

Answers (2)

solid.py
solid.py

Reputation: 2812

Instead of manually appending to a set you could make all combinations of a range based on a given size.

This function combinations(lis, r) produces all combinations for size r -> [0, k + 1] then chain.from_iterable() takes all combinations from each generator expression and returns them in a flattened iterable which is then converted to a set().

from itertools import chain, combinations

def sub_arrays(arr, k): # Produces a set of sub-arrays of size k.
    return set(chain.from_iterable(combinations(arr, r) for r in range(k + 1)))

arr = ['h', 'e', 'y']
print(sub_arrays(arr, k = 2)) # size = 2

Output:

{('h',), ('y',), ('e',), ('h', 'y'), ('e', 'y'), ('h', 'e'), ()}

Upvotes: 0

C14L
C14L

Reputation: 12548

If you are not planning to modify the partial lists later, you could simple use (hashable) tuples.

s = set()
for i in range ( len(arr)- size -1 ):
      temp = tuple(arr[i: i+size])
      s = s | {temp}

Upvotes: 2

Related Questions