I'm still learning python and still not familiar with them yet, and I've used C# mostly.
While learning python, I've noticed some features similar to those I've used with C#, that is, the iterators.
On Python, it's called 'Generator'.
It's very similar to function, but has 'yield' instead of 'return' and as the iterators work, it returns iterable values.
It was the 'yield' statement that I've noticed the similarity.
I thought 'Oh, It works just like the IEnumerable on C#!'.
Then I got curious and decided to find it out.
def combarrs(arr, length) :
for i in range(len(arr)):
if length == 1 :
yield [arr[i]]
else :
for subarr in combarrs(arr[i:], length - 1):
yield [arr[i]] + subarr
This piece of code generates all the elements of a given length of combination with repetition from the given 'arr'.
IEnumerable<IEnumerable<int>> CombArr(IEnumerable<int> arr, int length)
{
for (int i = 0; i < arr.Count(); i++)
{
if (length == 1)
{
yield return new int[] { arr.ElementAt(i) };
}
else
{
foreach (var subArr in CombArr(arr.Skip(i), length - 1))
{
yield return (new int[] { arr.ElementAt(i) }).Concat(subArr);
}
}
}
}
This is the same code made out of C#.
It doesn't seem as smooth as the python code, but it works the same nonetheless.
Languages these days seem to support a lot of useful and similar features for the developers, and it was fun finding out these similarities.
Doing the work twice? hmm... still worth it.