Musings

A random collection

Archive for December 2010

C++: Abstract Classes

Abstract Classes

  1. A class which does not fully represent an object. It only provides a partial description of its objects. The common description. It is expected that it’s subclasses will add to its structure and behavior.
  2. Example: Mammal does not fully represent any particular animal, but a particular animal may belong to the class of all Mammals
  3. Abstract classes organize features common to several classes. Common features that are features of the class’s interface.
Advertisements

Written by curious

December 25, 2010 at 10:57 am

Posted in C++

PROG: Language Comparison

TOC

Command Line Arguments

  1. Python
          import sys
          argc = len(argv)
          if argc > 1:
              print "Script: %s" % argv[0]
          
  2. Ruby http://www.fincher.org/tips/Languages/Ruby/
          ARGV[0]
          

Data Types

  1. Python: Everything is an object, even code becomes objects
    • None – signifies absence of a value (as a boolean it is False)
    • NotImplemented – (boolean value is True)
    • Ellipsis – indicates the presence of … in a slice (boolean value is True)
    • Numbers – integers (Plain,Long/Unlimited,Booleans), Floating Point (Real), Complex
    • Callable types (function)
  2. Ruby: every variable is an object. strings are objects, numeric types are also objects
      2.1.floor()            # 2
      x.between?(10,15)      # is 10 < x < 15
      
      x.class.to_s()         # display class name of x
      
      i = 1; j = 2
      i,j = j,i              # swap variables
      

Collections Containers

  1. python
    • Sequences(ordered) – list a[i]; slicing a[i:j]; extended slicing a[i:j:step], len(collection)
    • Immutable Sequences – strings s = ‘string’, s = “string”, s[0], s[-from_end], s[i:j], s.capitalize(), s.is*(), s.count(), s.join(seq), s.find(s2), s.split(), ; tuples t = (e1, e2, e3), tuple(fromList), t = e1,e2,e3, t=t1+t2, t[0]
    • Mutable Sequences – lists — l = [e1, e2, e3], l=list(tuple1), l=[2]*4, l = [i*3 for i in range(10) ], l.sort(), l.extend(l2), l.append(v), l.pop(), l[i], len(l); byte arrays — bytearray()
    • Set Types(unordered) – (mutable) set — set(), immutable frozen set — frozenset()
    • Mappings – dictionary — d = { key : value }, d = dict([(key,value)]), d.keys(), d.values(), d[key] , key in d, del d[key], d.update(d2)
  2. ruby
    Arrays

      arr = [1, 2.0, "string"]
      puts arr[0]                    # 0-based array indexing
      puts arr[-1]                   # negative indexing starts from end
      arr.first
      arr.last
      arr.length
      

    Arrays have Set operations: intersection “&”, concatenation “+”, set-minus “-“, pop, push, shift, unshift

      a = [1, 2, 3]; b = [3, 4, 5];
      c = a&b
      d = a+b
      e = a-b
      f = a.pop
      a.push(10)
      h = a.shift
      a.unshift(7,8,9)   # add to the front
      
      %w(hello world)    # creates an array of 2 strings
      

    Hashes

      animals = {
        'pet' => 'dog',
        'wild' => 'lion'
        }
      puts animals['wild']
      animals['bird'] = 'parrot'
      animals.values
      animals.keys
      animals.length
      
      ingredients = Hash["dosa","batter", "shake", "milk"]
      

    Ranges

      (1..10)    # 1 through 10, including 10
      (1...10)   # 1 through 9, excluding 10
      

    Operators on collections

      collection.each{|x| puts x}
      collection.select{|key,val| val < 100}
      collection.length
      
      ('a'..'g').each{|l| puts l}
      

Operators

Fn C++/C C# Java Python Ruby Perl
Power **
Arithmetic +,-,*,/,% +,-,*,/,% +,-,*,/,% +,-,*,//,%,/ +,-,*,/,% +,-,*,/,%
Boolean ||,&&,! ||,&&,! or, and, not
Comparison ==,<,≤,>,≥,!=

Conditional Statement

  1. Python
      if x < 0:
          print 'Negative'
      elif x == 0:
          print 'Zero'
      else:
          print 'Positive'
      

    There are no switch-case in python

  2. Ruby
        if v1 < 100
          ...
        elsif v1 > 200
          ...
        else
          ...
        end
      

    switch-case statement

        s =
          case v
          when 0..5
            "low"
          when 6..8
            "medium"
          else
            "high"
          end
      

Functions

  1. Ruby
      def show2Strings(a,b)
        puts "String 1: "+a
        puts "String 2: #{b}"
      end
      show2Values "a", "b"
      
      def add2Nums(a,b)
        return a+b
      end
      puts add2Nums(10,11)
    
      # no return, value of last expression is returned
      def add2Nums(a,b)
        a+b
      end
      
      # default values for parameters
      def doSomething(a,b=1,c=3)
        x = a*b+c
        puts "#{a}*#{b}+#{c} = #{x}"
      end
      doSomething(2,3)
      
      # variable args
      def variableArgs(a,b,*c)
        c.each{|x| puts "#{x}"}
      end
      variableArgs(1,2,3,4,5)
      
      # returning multiple values
      def getDateAndTime
        date = "2/1/2011"
        time = "10:00 AM"
        return date,time
      end
      a,b = getDateAndTime()
      puts "Date = #{a}, Time = #{b}"
      

Looping Loops

  1. C++, C#, Java
      for (int i = lowerBound; i < upperBound; ++i)
      {
        // body
      }
      
  2. C++ (foreach)
    STL Way:

      using namespace std;
    
      vector<int> vec;
    
      // Example 1:
      void print_square(int);
      for_each(vec.begin(), vec.end(), print_square);
    
      // Example 2:
      struct print_cube : public unary_function<int, void>
      {
        void operator() (int x);
      }
      print_cube pc;
      for_each(vec.begin(), vec.end(), pc);
      

    Boost Way:

      #include <boost/foreach.hpp>
    
      vector<int> vec;
      BOOST_FOREACH(int i, vec)
      {
          // do something with i
          print_square(i);
      }
    
      // ok to use reference
      vector<MyType> vec;
      BOOST_FOREACH(MyType& e, vec)
      {
        // do something
      }
    
      list< vector<int> > aVecList;
      BOOST_REVERSE_FOREACH(vector<int>& v, aVecList)
      {
          // iterate in reverse order
      }
      
  3. C# (foreach)
      foreach (T tIter in IEnumerable<T>)
      {
        // do something with tIter
      }
      // Example:
      foreach (int i in Enumerable.Range(0,10))
      
  4. python
      aList = [1, 2, 3, 4]
      for v in aList:                 # foreach
          # do something with v
    
      for i in range(len(aList)):     # same as above
          if i % 2 == 0:
              print i, a[i]
              break
    
      for x in range(start,end,step):   # for(i = start; i < end; i+=step)
          print x, a[x]
    
      for x in xrange(start,end,step):  # for(i = start; i < end; i+=step)
          print x, a[x]
    
      while True:
          # do something forever
    
      while a < n
          print a
    
      print x for x in aList
      

    Create your own enumerable class

      class MyEnumerable:
          def __init__(self,count):
              self.count = count
    
          def __iter__(self):
              return self
    
          def next(self):
              if self.count > 0:
                  self.count -= 1
                  return self.count
              raise StopIteration
      for i in MyEnumerable(10):
        print i,
      
  5. ruby
      arr.each{|l| somecode(l)}    # foreach
    
      for i in 1..1000             # foreach
        puts i
      end
      
      i = 0
      loop do                      # looping
        break if i > 11
        i += 1
      end
      
  6. Visual Basic
      ' Note: in VB lowerBound <= i <= upperBound
      For i As Integer = lowerBound To upperBound
        ' body
      Next
      

Classes

  1. python
      class MyClassName:
        a1 = 12345             """ property """
    
        def __init__(self):    """ constructor """
          self.x = 0
          self.y = 0
    
        def __init__(self, x0, y0):
          self.x = x0
          self.y = y0
    
        def method1(self):
          return 'a string value'
    
        def aStaticMethod():
          return 'something'
    
      x = MyClassName()         """ Use a class """
      x.a1
      x.method()
    
      MyClassName.aStaticMethod()
      
  2. ruby
      class String
        # Add a method to builtin string class
        def IsNullOrEmpty
          return (self == nil || self == "")
        end
      end
      puts "".IsNullOrEmpty()
      

    Note: Class variables/Statics start with “@@”, Instance Variables with “@”.
    Also, functions or method names may end with “?, !, =”

Inheritance

  1. python
      class MyClassName(Base1, Base2):
        def method2(self):
          return 'a string value'
      

Generics/Templates

Exceptions

Miscellaneous Tricks

  1. Echo a line to console
    • python
            print "Hello world"
            print "To print many things", 10+3*3, "string value"
            print "variable args embdedded here %s, %d and %u" % ("string", -10, 20)
            print "Boolean: %s" % (2 == 3)
      
            while i < 10:
                i += 1
                print i,            # no newline at the end
            
    • ruby
            printf("Today is a %s day\n", "nice")
            puts "How r u?"                # adds a line break
            print "How r u?"               # no line break
            
  2. Reading from stdin
    • python
            x = int(raw_input("Enter a value: "))
            
    • ruby
            $name = STDIN.gets
            

Lambdas

Written by curious

December 18, 2010 at 9:35 am

Posted in programming