Tuesday, February 25, 2014

Arrays and Indexers in IronPython



Today's post is about Arrays and Indexers in IronPython. Here below you will find a very easy to follow program, that demonstrate arrays and indexer, by implementing some simple tasks that will make you grasp the idea of those 2 features real quick. The main goal of this post, is not really teaching arrays because, come on, you probably already know "all" about them, in fact, it is more to show you how you do that in IronPython, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.

This is the second post of a dynamic language. As with Phalanger's version of the program, code structure changed slightly from previous posts. Besides that, because you normally don't use Arrays per se in Python (except for numerical arrays when better performance is required), it is more practical to use Python's List object instead of .NET's System.Array, which can definitely be used in IronPython, specially when you need to inter operate with other CLS languages. You can even initialize a System.Array with a Python List like this: System.Array[int]([1, 2, 3]).

By the way, if you missed my most recent post, "New Series - Arrays and Indexers", check it out. It has more details about the following program, and a bunch of definitions for the concepts used on this, and the following, posts. Or you can check my previous posts about arrays in Boo (or Cobra or Jython later on) just to compare.

I encourage you to copy the code below and try it yourself, normally, all programs you find in this blog are source code complete, just paste it on your IDE and run it.

There is room for improvement of the code, using generics is one example, but Generics, Collections, lambdas, etc. will have their own "series" of posts.


import clr
clr.AddReference("System")
import System
from System import Random
 
# Console Program   
def main():   
    # Single-dimensional Array(s)   
    printtitle('Reverse Array Elements'); 

    # Declare and Initialize Array (Python List) of Chars   
    # or letters = list('AEIOU')
    # or letters = 5 * [' ']      
    letters = list(' ' * 5) # letters = []
    letters[0] = 'A'        # letters.append('A')
    letters[1] = 'E'        # letters.append('E')
    letters[2] = 'I'        # letters.append('I')
    letters[3] = 'O'        # letters.append('O')
    letters[4] = 'U'        # letters.append('U')
    
    printarray(letters)
    inverse_letters = reversechar(letters)
    printarray(inverse_letters)

    printtitle('Sort Integer Array Elements')
    # Declare and Initialize Array of Integers   
    numbers = [10, 8, 3, 1, 5]
    
    printarray(numbers)   
    ordered_numbers = bubblesort(numbers)   
    printarray(ordered_numbers)

    printtitle('Sort String Array Elements')  

    # Declare and Initialize and Array of Strings   
    names = ['Damian', 'Rogelio', 'Carlos', 'Luis', 'Daniel']

    printarray(names)   
    ordered_names = bubblesort(names)   
    printarray(ordered_names)

    # Multi-dimensional Array (Matrix row,column)   
    printtitle('Transpose Matrix')   

    matrix = [[6, 4, 24],      
              [1, -9, 8]]

    printmatrix(matrix)
    transposed_matrix = transposematrix(matrix)   
    printmatrix(transposed_matrix)  

    # Jagged Array (Array-of-Arrays)   
    printtitle('Upper Case Random Array & Graph Number of Elements')   

    '''
    Creating an array of string arrays using the String.Split method   
    instead of initializing it manually as follows:   
 
    $text = [    
        [ ["word1", "word2, "wordN"],    
        [ ["word1", "word2, "wordN"],    
        ...
    ]   
     
    Text extract from: "El ingenioso hidalgo don Quijote de la Mancha"        
    '''
    text = [
    'Hoy es el dia mas hermoso de nuestra vida, querido Sancho;'.split(' '),    
    'los obstaculos mas grandes, nuestras propias indecisiones;'.split(' '),    
    'nuestro enemigo mas fuerte, miedo al poderoso y nosotros mismos;'.split(' '),    
    'la cosa mas facil, equivocarnos;'.split(' '),    
    'la mas destructiva, la mentira y el egoismo;'.split(' '),    
    'la peor derrota, el desaliento;'.split(' '),    
    'los defectos mas peligrosos, la soberbia y el rencor;'.split(' '),    
    'las sensaciones mas gratas, la buena conciencia...'.split(' ')
    ]

    printjaggedarray(text)   
    uppercaserandomarray(text)   
    printjaggedarray(text)   
    graphjaggedarray(text)

    # Array Exceptions
    printtitle('Common Array Exceptions')
    
    printcommonarrayexceptions(None)   
    printcommonarrayexceptions(text)  

    # Accessing Class Array Elements through Indexer
    printtitle('Alphabets')  
    
    vowels = Alphabet(5)
    vowels[0] = 'a'
    vowels[1] = 'e'
    vowels[2] = 'i'
    vowels[3] = 'o'
    vowels[4] = 'u'

    print '\nVowels = {%s}' % ','.join([vowels[0],vowels[1],vowels[2],vowels[3],vowels[4]])

    en = Alphabet('abcdefghijklmnopqrstuvwxyz')   
    print 'English Alphabet = {%s}' % (str(en))

    print 'Alphabet Extract en[9..19] = {%s}' % (str(Alphabet(en.slice(9, 10))))
   
    word1 = ''.join([en[6], en[14], en[14], en[3]])
    word2 = ''.join([en[1], en[24], en[4]])   
    word3 = ''.join([en[4], en[21], en[4], en[17], en[24], en[14], en[13], en[4]])   
    print "\n%s %s, %s!\n" % (word1, word2, word3)  

    raw_input()

def reversechar(arr):
    return list(reversed(arr))
    # or 
    # return arr[::-1]
    # or 
    # reversedarr = [], i = 0
    # for j in range(len(arr) - 1,-1,-1):
    #   reversedarr[i] = arr[j]
    # return reversedarr
    #

def bubblesort(arr):
    for i in reversed(arr):   
        for j in range(len(arr) - 1):   
            if arr[j] > arr[j + 1]:   
                swap = arr[j]   
                arr[j] = arr[j + 1]   
                arr[j + 1] = swap   
    return arr

def transposematrix(m):   
    ''' Transposing a Matrix 2,3  
     
     A =  [6  4 24]T [ 6  1]  
          [1 -9  8]  [ 4 -9]  
                     [24  8]  
    '''
    transposed = [len(m)*[0] for i in range(len(m[0]))]
    for i in range(len(m)):   
        for j in range(len(m[0])):   
        transposed[j][i] = m[i][j]
    return transposed  

def uppercaserandomarray(arr):   
    r = Random()   
    i = r.Next(len(arr))   
    for j in range(len(arr[i])):
        arr[i][j] = arr[i][j].upper()

def printarray(arr):
    print '\nPrint Array Content ' + arr.GetType().Name.Replace(']', str(len(arr)) + ']')
    for i in range(len(arr)):   
        print ' array [{0:2}'.format(i) + '] = {0:2}'.format(arr[i])

def printmatrix(m):   
    print '\nPrint Matrix Content ' + m.GetType().Name + '[' + str(len(m)) + ',' + str(len(m[0])) + ']'
    for i in range(len(m)):   
        for j in range(len(m[0])):   
            print ' array [{0:2},{1:2}] = {2:2} '.format(i, j, m[i][j])

def graphjaggedarray(arr):   
    '''When using Arrays, we can use for(each) instead of for by index:
    for s as (string) in arr:  
        for w as string in s: 
    ''' 
    print '\nPrint Text Content ' + arr.GetType().Name  
    for i in range(len(arr)):   
        line = ''
        line += 'Line{0:2}|'.format(i+1)
        for j in range(len(arr[i])):   
            line += '{0:3}'.format('*')   
        line += '(' + str(len(arr[i])) + ')'
        print line
        

def printjaggedarray(arr):
    print '\nPrint Jagged Array Content ' + arr.GetType().Name
    for i in range(len(arr)):
        line = ''
        for j in range(len(arr[i])):      
            line += ' ' + arr[i][j]
        if line == line.upper():
            line += ' <-- [UPPERCASED]'
        print line

def printcommonarrayexceptions(arr):
    try:
        arr[100][100] = 'hola'     
    except System.Exception as ex:
        print '\nException: \n%s\n%s' % (ex.GetType().Name, ex.Message)
    #except:
    #else:

def printtitle(message):    
    print ''  
    print '=' * 54   
    print message   
    print '=' * 54 


class Alphabet:
    # Array Field   
    _letters = []
    
    # Indexer Get/Set Property
    def __getitem__(self, idx):
        return self._letters[idx]
    def __setitem__(self, idx, value):
        self._letters[idx] = str(value).upper()
    
    # Read-Only Property
    def get_Length(self):
        return len(self._letters)   
    Length = property(fget=get_Length)

    # Constructor
    def __init__(self, param=None):           
        if type(param) == type(1):
            self._letters = list(' ' * param)
        elif type(param) == type(''):
            self._letters = list(str(param).upper())
        elif type(param) == type([]):
            self._letters = param
        else:
            self._letters = None

    # Overridden Method    
    def __str__(self):
        return ','.join(self._letters)

    # Method   
    def slice(self, start, length):
        return self._letters[start:start+length]

if __name__ == '__main__':
    main()


The output:






















































































VoilĂ , that's it. Next post in the following days.

No comments:

Post a Comment