0

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}
...

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Keen-ameteur
  • 123
  • 6
  • 2
    Python lists are not hashable due to being mutable. https://stackoverflow.com/questions/42203673/in-python-why-is-a-tuple-hashable-but-not-a-list. You just can't store lists in a set. – DownloadPizza Jan 04 '21 at 10:04
  • 3
    Als, its bad practice to call a variable `set`, since `set` is a reserved keyword for creating the type. – oskros Jan 04 '21 at 10:09

2 Answers2

2

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}
C14L
  • 12,153
  • 4
  • 39
  • 52
0

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'), ()}
solid.py
  • 2,782
  • 5
  • 23
  • 30