🎲

Problem solving 1

Anh-Thi Dinh
draft
⚠️
This is a quick & dirty draft, for me only!
This note contains questions/puzzle and algorithms to answer these problems. Most of the codes in this type of note are in Python or JS.

[Python] Count number of element in an array or properties of an object

For example,
1countTheNumberOfLines([1, [1]]) // returns 3
2countTheNumberOfLines({"x": 1, "y": [1]}) // returns 3
1private countTheNumberOfLines(obj: any): number {
2  if (typeof obj === 'object') {
3    if (Array.isArray(obj)) {
4      let count = obj.length;
5      for (let i = 0; i < obj.length; i++) {
6        count += countTheNumberOfLines(obj[i]);
7      }
8      return count;
9    } else if (obj && typeof obj === 'object') {
10      let count = Object.keys(obj).length;
11      for (const key in obj) {
12        if (typeof obj[key] !== 'function') {
13          count += countTheNumberOfLines(obj[key]);
14        }
15      }
16      return count;
17    }
18    return 0;
19  }
20  return 0;
21}

[Python] Make chunkers / windows

Split a sequence into windows with size and slide.
1def chunker(seq, size, slide=None, exact_size=False):
2    if slide is None:
3        slide = size
4    if exact_size:
5        return [seq[pos:pos + size] for pos in range(0, len(seq), slide) if len(seq[pos:pos + size]) == size]
6    else:
7        return [seq[pos:pos + size] for pos in range(0, len(seq), slide)]
1seq = [i for i in range(10)]
2
3chunker(seq, 3)
4chunker(seq, 3, exact_size=True)
5chunker(seq, 3, slide=2)
1# Output
2[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3
4[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
5[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
6[[0, 1, 2], [2, 3, 4], [4, 5, 6], [6, 7, 8], [8, 9]]
Make all arrays equal in size, filled with np.nan
1def chunker2(seq, size, slide=None):
2    if slide is None:
3        slide = size
4    return [np.append( seq[pos:pos + size], np.repeat(np.nan, size-len(seq[pos:pos + size])) )
5            for pos in range(0, len(seq), slide)]
1seq = [i for i in range(10)]
2
3chunker2(seq, size=4, slide=2)
1# Output
2[array([0., 1., 2., 3.]),
3 array([2., 3., 4., 5.]),
4 array([4., 5., 6., 7.]),
5 array([6., 7., 8., 9.]),
6 array([ 8.,  9., nan, nan])]

[Python] Plot a grid of squares

Plot a square of NxN small other squares. Each one has a probability Pxi/N of being coloured, where i is the line where it stands.
1N = 100
2P = 0.5
3im_size = 5
4
5image = np.repeat(np.array(range(1,N+1)).reshape(N, 1), N, axis=1)
6
7# LESS understandable but executing FASTER
8image = (P/N * image) <= np.random.rand(N,N)
9
10# MORE understandable but executing SLOWER
11def bernoulli(num, P, N):
12  return 1-np.random.binomial(1, P*num/N)
13vfunc = np.vectorize(bernoulli)
14image = vfunc(image, P, N)
15
16plt.figure(figsize=(im_size, im_size))
17plt.imshow(image, cmap='gray')
18plt.show()

[JS] Find and replace text with span

Problem: given a sentence and an array containing words and their colors to be replaced in the sentence.