Iterating over a custom ‘Jagged Array’ in Python

A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays." C# natively differentiates between a jagged and a multidimensional array.

To iterate over a every single element of a Jagged Array in Python, you will need to override the default iterator func. I’m simply iterating over 2-levels but you can scale this up to n-levels by using conventional graph traversal algorithms.

class JaggedArray(list):
    ''' An array of arrays! '''

    def __iter__(self):
        if self:
            ptr     = len(self) - 1
            count   = 0

            while count <= ptr:
                item = self[count]

                if isinstance(item, (tuple, list,)):
                    newPtr      = len(item) - 1
                    newCount    = 0

                    while newCount <= newPtr:
                        newItem = item[newCount]
                        yield newItem
                        newCount += 1
                else:
                    yield item

                count += 1

def main():
    obj = JaggedArray()
    obj.append((1, 2, 3,))
    obj.append([4, 5, 6, 7])
    obj.append((8, 9,))

    for item in obj:
        print item,

    raw_input()

if __name__ == '__main__':
    main()

Output >>

1 2 3 4 5 6 7 8 9
0  

Go Avengers!!!

Wow, I’m glad I saw this movie yesterday! 😉

0  

read(), readline(), readlines() & xreadlines() func in Python

While doing a regression analysis, I had to read & parse through a large .dat file. I called readline() func but was surprised to see that I was actually iterating through every single character in the first line!

with open(filePath, 'r') as f:
    for line in f.readline():
        print line

Then realization dawned upon me!

* read(size) >> size is an optional numeric argument and this func returns a quantity of data equal to size. If size if omitted, then it reads the entire file and returns it

* readline() >> reads a single line from file with newline at the end

* readlines() >> returns a list containing all the lines in the file

* xreadlines() >> Returns a generator to loop over every single line in the file

2  

Convert vowels to uppercase in a string

Given a string – say “hello world”, I was interested in capitalizing the vowels in it – IN A CLEAN & EFFICIENT WAY!

In the first approach, I use a StringBuilder object to hold the intermediate String while in the second approach, I’m using a C# feature – Linq. In the second approach, there is no lazy initialization taking place because we call the toArray() immediately & pass the contents to the String constructor. Looks a lot cleaner! Third approach is simply the best but it’s in Python!

First approach >>

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Output: {0}", CapitalizeWords("hello World"));
            Console.ReadLine();
        }

        static string CapitalizeWords(string input)
        {
            if (string.IsNullOrEmpty(input))
                return string.Empty;

            var sb = new StringBuilder();
            var lookup = new HashSet<Char>() {'a', 'e', 'i', 'o', 'u'};
            foreach (var x in input)
                sb.Append(lookup.Contains(x) ?
                    Char.ToUpper(x) : x);

            return sb.ToString();
        }
    }

Second approach >> much cleaner version using Linq!

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Output: {0}", CapitalizeWords("hello World"));
            Console.ReadLine();
        }

        static string CapitalizeWords(string input)
        {
            if (string.IsNullOrEmpty(input))
                return string.Empty;

            var lookup = new HashSet<Char>() {'a', 'e', 'i', 'o', 'u'};
            return new String(input.Select(x => lookup.Contains(x) ? 
                Char.ToUpper(x) : x).ToArray());
        }
    }

Third approach >> Python takes the cake!

from string import maketrans

def main():
    s = 'hello world'
    print 'Output: {0}'.format(s.translate(maketrans('aeiou', 'AEIOU')))
0  

Error 1 error LNK1104: cannot open file

I had a similar issue few years back

The same solution helped me in this case as well. You simply have to turn on ‘Application Experience’ feature under services.msc to get rid of the error!

0