eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I have a dataset which is sorted in this order:    col1 col2 col3     a 1 r   a 1 s   a 2 t   a 2 u   a 3 v   a 3 w   b 4 x   b 4 y   b 5 z   b 5 q   b 6 w   b 6 e    I want it to be sorted in the following order:    col1 col2 col3     a 1 r   a 2 t   a 3 v   a 1 s   a 2 u   a 3 w   b 4 x   b 5 z   b 6 w   b 4 y   b 5 q   b 6 e    I want the col2 to be in repetitive fashion, as in, for col1 'a' values, it should be 1,2,3,4 and then 1,2,3,4 again instead of 1,1,2,2,3,3,4,4. I have used the following code, but it is not working: import pandas as pd # Creating the DataFrame data = { 'col1': ['a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b', 'b'], 'col2': [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6], 'col3': ['r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'q', 'w', 'e'] } df = pd.DataFrame(data) # Sort by col1, then reorder col2 within each group df_sorted = df.sort_values(by=['col1', 'col2']).reset_index(drop=True) df_sorted = df_sorted.groupby('col1', group_keys=False).apply(lambda x: x.sort_values('col2')) # Display the sorted dataframe print(df_sorted) 

Answer: Use groupby.cumcount to form a secondary key for sorting: out = (df.assign(key=lambda x: x.groupby(['col1', 'col2']).cumcount()) .sort_values(by=['col1', 'key', 'col2']) .drop(columns='key') )  Note that you can avoid creating the intermediate column using numpy.lexsort: import numpy as np out = df.iloc[np.lexsort([df['col2'], df.groupby(['col1', 'col2']).cumcount(), df['col1']])]  Output:  col1 col2 col3 0 a 1 r 2 a 2 t 4 a 3 v 1 a 1 s 3 a 2 u 5 a 3 w 6 b 4 x 8 b 5 z 10 b 6 w 7 b 4 y 9 b 5 q 11 b 6 e  Intermediate (before sorting):  col1 col2 col3 key 0 a 1 r 0 1 a 1 s 1 2 a 2 t 0 3 a 2 u 1 4 a 3 v 0 5 a 3 w 1 6 b 4 x 0 7 b 4 y 1 8 b 5 z 0 9 b 5 q 1 10 b 6 w 0 11 b 6 e 1
Question: Hi I have two dictionaries defined which contains lists dict_1 = {'V1': ['2024-11-07', '2024-11-08'], 'V2': ['2024-11-07', '2024-11-08']} dict_2 = {'V1': ['2024-11-08'], 'V2': ['2024-11-07']}  both items (key and val) from dict_2 above are subset of dict_1 so I wanted return true in both cases. I tried to use res = set(dict_2.items()).issubset(set(dict_1.items())) However it works if its simple dictionary like dict_1 = {'abc' : 1, 'pqr' : 2} dict_2 = {'abc' : 1}  in my case is there any way this can be done?

Answer: You can check for each key of dict_2 that its sublist is a subset of the corresponding sublist of dict_1: def dict_issubset(maybe_subset, maybe_superset): return { key: set(sublist).issubset(maybe_superset[key]) for key, sublist in maybe_subset.items() }  so that: dict_1 = {'V1': ['2024-11-07', '2024-11-08'], 'V2': ['2024-11-07', '2024-11-08']} dict_2 = {'V1': ['2024-11-08'], 'V2': ['2024-11-07']} print(dict_issubset(dict_2, dict_1))  outputs: {'V1': True, 'V2': True}  Demo: https://ideone.com/wuvTET
Question: I am given a regex expression that consists of raw text and capture groups. How can I extract all raw text snippets from it? For example: pattern = r"Date: (\d{4})-(\d{2})-(\d{2})" assert extract(pattern) == ["Date: ", "-", "-", ""]  Here, the last entry in the result is an empty string, indicating that there is no raw text after the last capture group. The solution should not extract raw text within capture groups: pattern = r"hello (world)" assert extract(pattern) == ["hello ", ""]  The solution should work correctly with escaped characters too, for example: pattern = r"\(born in (.*)\)" assert extract(pattern) == ["(born in ", ")"]  Ideally, the solution should be efficient, avoiding looping over the string in Python.

Answer: What you are asking for is to extract literal tokens from a parsed regex pattern at the top level. If you don't mind tapping into the internals of the re package, you can see from the list of tokens of a given pattern parsed by re._parser.parse: import re pattern = r"\(born in (.*)\)" print(*re._parser.parse(pattern).data, sep='\n')  which outputs: (LITERAL, 40) (LITERAL, 98) (LITERAL, 111) (LITERAL, 114) (LITERAL, 110) (LITERAL, 32) (LITERAL, 105) (LITERAL, 110) (LITERAL, 32) (SUBPATTERN, (1, 0, 0, [(MAX_REPEAT, (0, MAXREPEAT, [(ANY, None)]))])) (LITERAL, 41)  that all you need is to group together the LITERAL tokens and join their codepoints for output: def extract(pattern): literal_groups = [[]] for op, value in re._parser.parse(pattern).data: if op is re._constants.LITERAL: literal_groups[-1].append(chr(value)) else: literal_groups.append([]) return list(map(''.join, literal_groups))  so that: for pattern in ( r"Date: (\d{4})-(\d{2})-(\d{2})", r"hello (world)", r"\(born in (.*)\)" ): print(extract(pattern))  outputs: ['Date: ', '-', '-', ''] ['hello ', ''] ['(born in ', ')']  Demo here
Question: I have an interactive plot in altair/vega where I can select points and I see a pie chart with the ratio of the colors of the selected points. import altair as alt import numpy as np import polars as pl selection = alt.selection_interval(encodings=["x"]) base = ( alt.Chart( pl.DataFrame( { "x": list(np.random.rand(100)), "y": list(np.random.rand(100)), "class": list(np.random.choice(["A", "B"], 100)), } ) ) .mark_point(filled=True) .encode( color=alt.condition( selection, alt.Color("class:N"), alt.value("lightgray") ), ) .add_params(selection) ) alt.hconcat( base.encode(x="x:Q", y="y:Q"), ( base.transform_filter(selection) .mark_arc() .encode(theta="count()", color="class:N") ), )  The outcome looks like this:  Now I'd like to add two more charts that show the ratio of selected / unselected points for each color. I.e. one pie chart that is orange / gray and one pie chart that is blue / gray with ratios depending on the number of selected points. I tried to use the selection like this  ( base.mark_arc().encode( theta="count()", color=alt.condition( selection, alt.Color("class:N"), alt.value("gray") ), row="class:N", ) ),  But it's not what I want:  What's the best way to add the pie charts I want?

Answer: There might be an easier way to do this, but the following works: alt.hconcat( base.encode(x="x:Q", y="y:Q"), ( base.mark_arc(theta=4) .transform_joinaggregate(class_total='count()', groupby=['class']) .transform_filter(selection) # Including class_total in the groupby just so that column is not dropped since we need it in the calculate .transform_aggregate(count_after_filter='count()', groupby=['class', 'class_total']) .transform_calculate(proportion_selected=alt.datum.count_after_filter / alt.datum.class_total) .encode( # Setting the domain to reflect that we computed a proportion theta=alt.Theta('proportion_selected:Q').scale(domain=(0, 1)), row='class', color='class' # tooltip='proportion_selected:Q' ) ) )   Together with your initial chart, this could make for an interesting gallery example if you want to create a PR. For a grey background, I think you would have to layer with a completely filled in grey chart, similar to this layered histogram here https://altair-viz.github.io/gallery/interval_selection_map_quakes.html (should just be alt.Chart().mark_arc(color='lightgrey')
Question: I'm trying to build a Monte Carlo simulator for my data in Polars. I am attempting to group by a column, resample the groups and then, unpack the aggregation lists back in their original sequence. I've got it worked out up until the last step and I'm stuck and beginning to think I've gone about this in the wrong way. df_original = pl.DataFrame({ 'colA': ['A','A','B','B','C','C'], 'colB': [11,12,13,14,15,16], 'colC': [21,22,23,24,25,26]})  shape: (6, 3) ┌──────┬──────┬──────┐ │ colA ┆ colB ┆ colC │ │ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 │ ╞══════╪══════╪══════╡ │ A ┆ 11 ┆ 21 │ │ A ┆ 12 ┆ 22 │ │ B ┆ 13 ┆ 23 │ │ B ┆ 14 ┆ 24 │ │ C ┆ 15 ┆ 25 │ │ C ┆ 16 ┆ 26 │ └──────┴──────┴──────┘  I am grouping and resampling like this. Please note that I am using a seed here so this example is reproducible but this would get run many many times with no seeds in he end. df_resampled = ( df_original .group_by('colA', maintain_order=True) .agg(pl.all()) .sample(fraction=1.0, shuffle=True, seed=9) )  shape: (3, 3) ┌──────┬───────────┬───────────┐ │ colA ┆ colB ┆ colC │ │ --- ┆ --- ┆ --- │ │ str ┆ list[i64] ┆ list[i64] │ ╞══════╪═══════════╪═══════════╡ │ B ┆ [13, 14] ┆ [23, 24] │ │ C ┆ [15, 16] ┆ [25, 26] │ │ A ┆ [11, 12] ┆ [21, 22] │ └──────┴───────────┴───────────┘  What I can't figure out is how to explode the lists and end up with this. The original order within each group is preserved. Only the groups themselves are reshuffled on each run. shape: (6, 3) ┌──────┬──────┬──────┐ │ colA ┆ colB ┆ colC │ │ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 │ ╞══════╪══════╪══════╡ │ B ┆ 13 ┆ 23 │ │ B ┆ 14 ┆ 24 │ │ C ┆ 15 ┆ 25 │ │ C ┆ 16 ┆ 26 │ │ A ┆ 11 ┆ 21 │ │ A ┆ 12 ┆ 22 │ └──────┴──────┴──────┘ 

Answer: As @jqurious pointed out in the comments, this is easily solved with... df_resampled.explode(pl.exclude("colA"))
Question: I'm trying to upsize OpenCV images in Python in such a manner that the individual pixels are spread out by an integral factor; I use this to visually examine deep detail and individual pixel values can be seen (using cv2.imshow in this instance). For example, an array:  [[1,2], [3,4]]  And a factor of 2 means I'd get:  [[1,1,2,2], [1,1,2,2], [3,3,4,4], [3,3,4,4]]  I've done this by generating an array of size*factor using np.zeros, then iterating each point in the original array and copying it to the target array using (for example) for y in range(src.shape[0]): for x in range(src.shape[1]): tgt[y*f:y*f+f, x*f:x*f+f, :] = src[y,x,:]  But as you can imagine, it's not the fastest approach, and I'm hoping I'm just not finding the right thing. OpenCV (and PIL) do not have a resize capability that doesn't interpolate by one method or another, which seems weird all by itself. I looked over & tried numpy broadcast*, numpy stride_trickks, opencv functions, PIL functions. The semi-manual method works as long as I don't need interactivity, but I'm trying to adjust parameters to several opencv functions quickly so I can find the right combinations to solve my problem. (Which is proprietary, so I can't share imagery...) Waiting a significant time between results is counterproductive.

Answer: You can use opencv's cv.resize with nearest-neighbor as interpolation method (cv.INTER_NEAREST) to achieve what you need: import cv2 as cv import numpy as np src = np.array([[1,2], [3,4]]) dst = cv.resize(src, (4,4), interpolation=cv.INTER_NEAREST) print(dst)  Output: [[1 1 2 2] [1 1 2 2] [3 3 4 4] [3 3 4 4]]  Live demo
Question: I have a dataset that contains 3 columns. These are edge connections between nodes and the strength of the connection. What I am trying to do is find and merge the extra edges that can occur when the direction goes in the opposite direction. as a short example data_frame = pd.DataFrame({"A":["aa", "aa", "aa", "bb", "bb", "cc", "dd", "dd"], "B":["bb", "cc", "dd", "aa", "dd", "aa", "ee", "aa"], "C":[4,3,4,5,3,4,2, 5]})  the resulting node graph  aa - bb | \ | cc dd -- ee  From the nodes, we have overlap as "aa - bb" is the same as "bb - aa" and same with "aa - dd" and "dd - aa" I thought about merging A and B together both forward and reverse, concatenating the two dataframes and than performing a group_by().sum() but I end up with extras that need to be removed afterwards. ideally this is how it would work  A | B | C A | B | C aa bb 4 aa bb 9 aa cc 3 aa cc 7 aa dd 4 aa dd 9 bb aa 5 bb dd 3 bb dd 3 --> dd ee 2 cc aa 4 dd ee 2 dd aa 5 

Answer: You can aggregate as frozenset, then perform a groupby.sum: out = (data_frame['C'] .groupby(data_frame[['A', 'B']].agg(frozenset, axis=1)) .sum() .reset_index() )  Output:  index C 0 (bb, aa) 9 1 (cc, aa) 7 2 (dd, aa) 9 3 (bb, dd) 3 4 (ee, dd) 2  Variant to get the original columns: cols = ['A', 'B'] out = (data_frame .groupby(data_frame[['A', 'B']].agg(frozenset, axis=1), as_index=False) .agg(dict.fromkeys(cols, 'first')|{'C': 'sum'}) )  Output:  A B C 0 aa bb 9 1 aa cc 7 2 aa dd 9 3 bb dd 3 4 dd ee 2  Since converting to frozenset is quite slow, you can also sort the values in a consistent order using numpy, and groupby.sum: import numpy as np tmp = data_frame.copy() # avoid modifying the original frame tmp[['A', 'B']] = np.sort(data_frame[['A', 'B']], axis=1) out = tmp.groupby(['A', 'B'], as_index=False).sum()  Variant of the similar method suggested by @PandaKim, with improved efficiency: cols = ['A', 'B'] out = (data_frame.groupby([*np.sort(data_frame[cols]).T])['C'] .sum().rename_axis(cols).reset_index() )  Output:  A B C 0 aa bb 9 1 aa cc 7 2 aa dd 9 3 bb dd 3 4 dd ee 2  timings:
Question: df = pl. DataFrame({"col1": [1, 2, 3], "col2": [4, 5, 6]}) print(df) shape: (3, 2) ┌──────┬──────┐ │ col1 ┆ col2 │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞══════╪══════╡ │ 1 ┆ 4 │ │ 2 ┆ 5 │ │ 3 ┆ 6 │ └──────┴──────┘  I am looking for the polars equivalent of numpy.tile. Something along the line such as df.tile(2) or df.select(pl.all().tile(2)). The expected result should look like this: shape: (6, 2) ┌──────┬──────┐ │ col1 ┆ col2 │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞══════╪══════╡ │ 1 ┆ 4 │ │ 2 ┆ 5 │ │ 3 ┆ 6 │ │ 1 ┆ 4 │ │ 2 ┆ 5 │ │ 3 ┆ 6 │ └──────┴──────┘ 

Answer: You could concat several times the same DataFrame: out = pl.concat([df]*2) # for contiguous memory out = pl.concat([df]*2, rechunk=True)  Or, for just 2 repeats vstack: out = df.vstack(df)  Alternatively, using Expr.repeat_by + explode: N = 2 (df.with_columns(pl.all().repeat_by(pl.lit(N)), pl.int_ranges(pl.lit(N))) .explode(pl.all()) .sort(by='literal', maintain_order=True).drop('literal') )  Output: ┌──────┬──────┐ │ col1 ┆ col2 │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞══════╪══════╡ │ 1 ┆ 4 │ │ 2 ┆ 5 │ │ 3 ┆ 6 │ │ 1 ┆ 4 │ │ 2 ┆ 5 │ │ 3 ┆ 6 │ └──────┴──────┘
Question: I'm trying to perform a groupby sum on a specific column in a pandas df. But I only want to execute of count after a certain threshold. For this example, it will be where  B > 2. The groupby is on A and the count is on C. The correct output should be: x = 3 y = 9 df = pd.DataFrame(dict(A=list('ababaa'), B=[1, 1, 3, 4, 5, 6], C=[9, 9, 0, 9, 1, 2])) df.loc[(df['B'] > 2), 'Count'] = df.groupby('A')['C'].transform('sum') df['Count'] = df['Count'].replace(np.NaN, 0).astype(int)  Out:  A B C Count 0 x 1 9 0 1 y 1 9 0 2 x 3 0 12 *3 3 y 4 9 18 *9 4 x 5 1 12 *3 5 x 6 2 12 *3 

Answer: Use mask in both sides: m = df['B'] > 2 df['Count'] = 0 df.loc[m, 'Count'] = df[m].groupby('A')['C'].transform('sum') print (df) A B C Count 0 a 1 9 0 1 b 1 9 0 2 a 3 0 3 3 b 4 9 9 4 a 5 1 3 5 a 6 2 3  Another idea is use Series.where: m = df['B'] > 2 df['Count'] = m.groupby(df['A']).transform('sum').where(m, 0)  Or numpy.where: m = df['B'] > 2 df['Count'] = np.where(m, m.groupby(df['A']).transform('sum'), 0)  Or multiple by mask: m = df['B'] > 2 df['Count'] = m.groupby(df['A']).transform('sum').mul(m)
Question: I'm having trouble sending code in Python file to the interactive REPL in VS Code (using Shift + Enter). Single line code and functions with one line work fine, but any code chunks with multiple lines raise IndentationErrors. Also KeyboardInterrupt shows up in the REPL every time code is sent. Tried updating and restarting VS Code and the Python Extension.    VS Code Version: 1.95.2 (Universal), configured to use 4 spaces instead of tabs Python Extension from Microsoft: v2024.20.0 Python: 3.13.0 (venv) MacOS Sonoma 14.2.1 

Answer: It's a known issue: https://github.com/microsoft/vscode-python/issues/24256  Yes, that KeyboardInterrupt is handled via #24422 So you give it a try tomorrow (it just got merged today Nov 12), and it wont be there!  So apparently it will be fixed in the next vscode-python build (v2024.20.0 is currently the latest).
Question: I am trying to create a system to take an array of floats which range from 0.0 to 1.0 and convert them into RGBA values based on a lookup table. The output should be an array that is one dimension larger that the input with the last dimension being size 4 and consisting of the RGBA values. Currently I have only been able to do this via loops. Dose anyone know of any numpy indexing methods that could achieve this same result more efficiently. import numpy as np import matplotlib.pyplot as plt cyan = np.array([(x*0,x*1,x*1,255) for x in range(256)]) input_array = np.arange(0,0.8,0.05).reshape(4,4) input_array = input_array*256 colour_array = [] for x in range(input_array.shape[0]): for y in range(input_array.shape[1]): colour_array.append(cyan[int(input_array[x,y])]) colour_array = np.array(colour_array).reshape(4,4,4) plt.imshow(colour_array)  

Answer: Use the following: shape = input_array.shape index = input_array[*np.indices(shape).reshape(2, -1)].astype(int) colour_array1 = cyan[index].reshape(4, *shape)   Confirm the two are equal: np.allclose(colour_array, colour_array1,atol=0) Out[62]: True   USE THE OTHER SOLUTION!!!
Question: I feel very silly asking this. I want to set a value in a DataFrame depending on some other columns. I.e: (Pdb) df = pd.DataFrame([['cow'], ['dog'], ['trout'], ['salmon']], columns=["animal"]) (Pdb) df animal 0 cow 1 dog 2 trout 3 salmon (Pdb) df["animal"] = np.select(df["animal"] == "dog", "canine", "not-canine")  But the problem is that the above doesn't work! It's because I'm providing a single value, not an array. Arrgh, numpy. *** ValueError: list of cases must be same length as list of conditions (Pdb)  I know about df.where and df.mask - but there seems to be no df.select. What ought I do?

Answer: np.select can be used here, but you need to wrap the conditions/assigned values in a list: df = pd.DataFrame([['cow'], ['dog'], ['trout'], ['salmon']], columns=['animal']) df['animal'] = np.select([df['animal'] == 'dog'], ['canine'], 'not-canine')  Since you have a single condition here, better use numpy.where: df['animal'] = np.where(df['animal'] == 'dog', 'canine', 'not-canine')  Output:  animal 0 not-canine 1 canine 2 not-canine 3 not-canine  To complement a bit @Tricky's answer, if you use case_when (a novel addition since pandas 2.2), you can have a default value by passing a catch-all condition: df['animal'].case_when([(df['animal'].eq('dog'), 1), (df['animal'].eq('trout'), 'B'), (np.repeat(True, len(df)), 3), ], )  Also note that np.select and case_when do not handle the dtypes the same way. np.select will force a type change to have an homogeneous array, case_when will allow to create an object column keeping the original type: df['select'] = np.select([df['animal'].eq('dog'), df['animal'].eq('trout')], [1, 'B'], -1 ) df['case_when'] = df['animal'].case_when([(df['animal'].eq('dog'), 1), (df['animal'].eq('trout'), 'B'), (np.repeat(True, len(df)), -1), ], )  Output:  animal select case_when 0 cow -1 -1 1 dog 1 1 2 trout B B 3 salmon -1 -1  Difference in type: df['select'].to_list() # ['-1', '1', 'B', '-1'] # forced type change: 1 -> '1' df['case_when'].to_list() # [-1, 1, 'B', -1] # preserved type
Question: See below my attempt at implementing the block tridiagonal thomas algorithm. If you run this however, you get a relatively large (10^-2) error in the block TMDA compared to the np direct solve (10^-15), even for this very simple case. More complicated test cases give larger errors - I think the errors start growing on the back substitution. Any help as to why would be much appreciated! import numpy as np import torch def solve_block_tridiagonal(a, b, c, d): N = len(b) x = np.zeros_like(d) # Forward elimination with explicit C* and d* storage C_star = np.zeros_like(c) d_star = np.zeros_like(d) # Initial calculations for C_0* and d_0* C_star[0] = np.linalg.solve(b[0], c[0]) d_star[0] = np.linalg.solve(b[0], d[0]) # Forward elimination for i in range(1, N - 1): C_star[i] = np.linalg.solve(b[i] - a[i-1] @ C_star[i-1], c[i]) d_star[i] = np.linalg.solve(b[i] - a[i-1] @ C_star[i-1], d[i] - a[i-1] @ d_star[i-1]) # Last d_star update for the last block d_star[-1] = np.linalg.solve(b[-1] - a[-2] @ C_star[-2], d[-1] - a[-2] @ d_star[-2]) # Backward substitution x[-1] = d_star[-1] for i in range(N-2, -1, -1): x[i] = d_star[i] - C_star[i] @ x[i+1] return x def test_block_tridiagonal_solver(): N = 4 a = np.array([ [[1, 0.5], [0.5, 1]], [[1, 0.5], [0.5, 1]], [[1, 0.5], [0.5, 1]] ], dtype=np.float64) b = np.array([ [[5, 0.5], [0.5, 5]], [[5, 0.5], [0.5, 5]], [[5, 0.5], [0.5, 5]], [[5, 0.5], [0.5, 5]] ], dtype=np.float64) c = np.array([ [[1, 0.5], [0.5, 1]], [[1, 0.5], [0.5, 1]], [[1, 0.5], [0.5, 1]] ], dtype=np.float64) d = np.array([ [1, 2], [2, 3], [3, 4], [4, 5] ], dtype=np.float64) x = solve_block_tridiagonal(a, b, c, d) # Construct the equivalent full matrix A_full and right-hand side d_full A_full = np.block([ [b[0], c[0], np.zeros((2, 2)), np.zeros((2, 2))], [a[0], b[1], c[1], np.zeros((2, 2))], [np.zeros((2, 2)), a[1], b[2], c[2]], [np.zeros((2, 2)), np.zeros((2, 2)), a[2], b[3]] ]) d_full = d.flatten() # Flatten d for compatibility with the full system # Solve using numpy's direct solve for comparison x_np = np.linalg.solve(A_full, d_full).reshape((N, 2)) # Print the solutions for comparison print("Solution x from block tridiagonal solver (TMDA):\n", x, "\nResidual:", torch.sum(torch.abs(torch.tensor(A_full)@torch.tensor(x).flatten() - torch.tensor(d).flatten()))) print("Solution x from direct full matrix solver:\n", x_np, "\nResidual np:", torch.sum(torch.abs(torch.tensor(A_full)@torch.tensor(x_np).flatten() - torch.tensor(d).flatten()))) # Run the test function test_block_tridiagonal_solver() 

Answer: It is dangerous to define a and c with a different number of elements to b, as it could lead to the wrong indexing in the TDMA. If you change the line setting the last element of d_star to the following: d_star[-1] = np.linalg.solve(b[-1] - a[-1] @ C_star[-1], d[-1] - a[-1] @ d_star[-2])  this should now work. Note the TWO occurrences of a[-1], NOT a[-2] and the occurrence of C_star[-1] rather than C_star[-2] ... but these are consequences of how you have sent under-length arrays a and c to the routine.
Question: Consider this curly brace expansion in bash: for i in {1..10}; do echo $i; done;  I call this script from the shell (on macOS or Linux) and the curly brace does expand: $ ./test.sh 1 2 3 4 5 6 7 8 9 10  I want to call this script from Python, for example: import subprocess print(subprocess.check_output("./test.sh", shell=True))  On macOS, this Python call expands the curly brace and I see this output: b'1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n'  On Linux, this Python call fails to expand the curly brace and I see this output: b'{1..10}\n'  Why does curly brace expansion work on the interactive shell (macOS or Linux) and when called from Python on macOS, but fails when called from Python on Linux?

Answer: {1..10} is a bash feature, it is not defined in POSIX sh. It seems that subprocess.check_output("./test.sh", shell=True) invokes bash (or another shell which supports this feature) in the first example (macOS) and sh in your second example (Linux). See:  https://www.shellcheck.net/wiki/SC3009 Actual meaning of 'shell=True' in subprocess Does the `shell` in `shell=True` in subprocess mean `bash`?