Python generator & C# IEnumerable

Skele·2022년 9월 21일

C#

목록 보기
1/1

Noticing Similarity

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.

python code

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'.

C# code

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.

Conclusion?

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.

profile
Tireless And Restless Debugging In Source : TARDIS

0개의 댓글