My ultimate aim is to convert the below code in python to C#, but I'd like to do it my self by learning the python syntax. I understand that the code is recursive.
The code produces polynomials of degree n with k variables. More specifically the list of exponents for each variable.
def multichoose(n,k):
if k < 0 or n < 0: return "Error"
if not k: return [[0]*n]
if not n: return []
if n == 1: return [[k]]
return [[0]+val for val in multichoose(n-1,k)] + \
[[val[0]+1]+val[1:] for val in multichoose(n,k-1)]
Here is the conversion I have so far:
public double[] MultiChoose(int n, int k)
{
if (k < 0 || n < 0)
{
throw new Exception();
}
if (k == 0)
{
return [[0]*n]; // I have no idea what the [[0]*n] syntax means
}
if (n == 0)
{
return new double[0]; // I think this is just an empty array
}
if (n == 1)
{
return new double[1] {k}; // I think this is just an empty array
}
//Part I don't understand
return [[0]+val for val in MultiChoose(n-1,k)] + \
[[val[0]+1]+val[1:] for val in MultiChoose(n,k-1)]
}
My question is: How do I convert the python code?
I would use LINQ in C# to translate the code:
[]
is the empty list.
Enumerable.Empty<T>()
[x]
is the list containing a single item, x.
Enumerable.Repeat(x, 1)
[[0]*n]
is the list containing the list containing n copies of 0.
Enumerable.Repeat(Enumerable.Repeat(0, n), 1)
[X for Y in Z]
is a list comprehension.
from Y in Z select X
- or -
Z.Select(Y => X);
X + Y
(where X and Y are lists) is list concatenation.
Enumerable.Concat(X, Y)
The signature of MultiChoose would be:
public IEnumerable<IEnumerable<double>> MultiChoose(int n, int k);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With