Language Phenotypes: C#, Python - Part 6
Doing a convert a line of text into a 2 dimensional array choice. In this case I will show the answers in C# and Python
Given the problem
Convert this line input "5.0,100,5.5,99,6.0,101:L10;5.0,18,5.5,98,6.0,110:L20;"
into the following output
10 20
5.0 100 18
5.5 99 98
6.0 101 110
As you can see there are delimiters spaced throughout the input to split of the data, the ;
splits the line inputs for columns (all columns starts with L
). Then the :
splits the column value from the row values. Finally each row inputs comes in a pair of the key, value
Therefore column 10 comes from this part of the line 5.0,100,5.5,99,6.0,101:L10;
and then the keys to make this representation of that line only
10
5.0 100
5.5 99
6.0 101
Python
data_to_parse = "5.0,100,5.5,99,6.0,101:L10;5.0,18,5.5,98,6.0,110:L20;"
column_headers = []
rows_lines = {}
for input_line in data_to_parse.split(";"):
if input_line == "":
continue
line_segments = input_line.split(":")
column = line_segments.pop()[1:]
column_headers.append(column)
row_values = line_segments.pop().split(",")
while len(row_values) > 0:
value = row_values.pop()
key = row_values.pop()
current_values = rows_lines.get(key)
if current_values is None:
rows_lines[key] = [value]
else:
current_values.append(value)
rows_lines[key] = current_values
print(f'\t{str.join("\t", column_headers)}')
for row_key, row_items in dict(reversed(list(rows_lines.items()))).items():
print(f'{row_key}\t{str.join("\t", row_items)}')
C#
public class TestProgram
{
static public void Main()
{
var input ="5.0,100,5.5,99,6.0,101:L10;5.0,18,5.5,98,6.0,110:L20;";
var columnHeaders = new List<string>();
var rows = new Dictionary<string, List<string>>();
foreach (var inputLine in input.Split(";", StringSplitOptions.RemoveEmptyEntries))
{
var line = inputLine.Split(":", StringSplitOptions.RemoveEmptyEntries);
columnHeaders.Add(line[1].Replace("L", ""));
var rowLines = line[0].Split(",", StringSplitOptions.RemoveEmptyEntries);
var index = 0;
while (index < rowLines.Length)
{
var key = rowLines[index];
var value = rowLines[index + 1];
if (rows.ContainsKey(key))
{
var current = rows[key];
current.Add(value);
rows[key] = current;
}
else
{
rows.Add(key, [value]);
}
index = index + 2;
}
}
Console.WriteLine($"\t{string.Join("\t", columnHeaders)}");
foreach (var row in rows)
{
Console.WriteLine($"{row.Key}\t{string.Join("\t", row.Value)}");
}
}
}
}
Note
When I was asked this question the online tester tool kept saying the code was causing an out of index exception and I couldn't find out why. I think the compiler was broken or some kind of strange bug I ran into. Anyway should have just done it with python ☹️