Python Program to Access Environment Variables

Python provides a number of built-in modules and functions for commonly needed programming tasks. For example, to access operating system properties, python provides the module os. You can use the environ object of os module to access operating system environment variables.

The object os.environ behaves like a dictionary of environment variable names and its values. The following python program prints all the environment variables and its values when it is run,

import os

env_obj = os.environ
for x in env_obj:
    print(x,env_obj[x],sep=' => ')

If you want to get the value of an environment variable and if it doesn't exist, a default value, you can use the getenv() method of os module,

temp_dir = os.getenv('TMPDIR','defaultvalue')
print(temp_dir)

How to Find Sum of Digits of a Number in Python

Python's built-in support for lists, strings and data conversion enables us to write very concise code which usually takes much more code in other languages. For example, the following python 3 code computes sum of digits of a number using a generator expression and an implicit iterator.

# python3 code
number = int(input("Please enter a number:"))
sum_of_digits = sum(int(digit) for digit in str(number))
print("Sum of digits of {} is {}".format(number,sum_of_digits))

The above program illustrates a number of cool features of python language,

  • Convert a number to a string using the built-in str() function
  • Implicitly convert a string to a sequence of characters to a list when used in looping context
  • Use int() built-in function to convert each digit character to a number
  • The use of generator expression which return sequence items on demand
  • The sum() aggregate built-in function which finally computes the sum of digits

Following is a more traditional way of computing sum of digits of a number in python. Note the use of divmod() function which can compute the remainder and modulus in a single call. The resultant tuple is unpacked into 2 variables.

# python3 code
number = int(input("Please enter a number:"))

sum_of_digits = 0
n = number
while n:
    n,remainder = divmod(n,10)
    sum_of_digits += remainder

print("Sum of digits of {} is {}".format(number,sum_of_digits))

How to Compute Factorial in Python

Formula for computing factorial is,

Factorial(n) = n*(n-1)*(n-2).... *1

This can be written as Factorial(n) = n*Factorial(n-1).

Hence we can use recursion to find factorial of a number.The following Python 3 program computes factorial of a number using recursion.

# python 3.6+ needed
def factorial(n):
    if n==1 or n==0:
        return 1
    else:
        return n * factorial(n-1)

number = int(input("Enter number for factorial calculation:"))
fact = factorial(number)
print(f"factorial({number}) = {fact}")

However, python does have a built-in method for computing factorial. The following sample program computes factorial in python 3 using the built-in factorial method in math module,

# python 3.6+ needed
import math
number = int(input("Enter number for factorial calculation:"))
fact = math.factorial(number)
print(f"factorial({number}) = {fact}")

If you have a program which computes factorial of multiple numbers, we can use a method level cache to speed up calculation of factorial. The following program stores any factorial computed in a cache. When a call is made to calculate the factorial of the same number, it is picked from the cache. This substantially speeds up factorial computation since we are using recursion in this program. See lru_cache documentation to learn more about this technique.

# python 3.6+ needed
import math
import functools

# caches calculated values for input number n.
@functools.lru_cache()
def factorial(n):
    return math.factorial(n)

# find factorial of 1 to 100. Uses lru_cache for performance.
for num in range(1,101):
    fact = factorial(num)
    print(f"factorial({num}) = {fact}")

First few lines of the output is given below,

factorial(1) = 1
factorial(2) = 2
factorial(3) = 6
factorial(4) = 24
factorial(5) = 120
factorial(6) = 720
factorial(7) = 5040
factorial(8) = 40320
factorial(9) = 362880
factorial(10) = 3628800

Following is a python 2.7 program for finding factorial of a number,

# python 2.x solution for factorial
import math
number = int(raw_input("Enter number for factorial calculation:"))
fact = math.factorial(number)
print "factorial({0}) = {1}".format(number,fact)

C Program to Create Multiplication Table

Multiplication table is a table of products of decimal sequence of numbers. For example, a multiplication table of 5 by 5 contains a top most row with values ranging from 1 to 5 and a left most row with values ranging from 1 to 5. The middle cells contains the algebraic product of the corresponding value in the top row and left most row. Following table is a 5x5 multiplication table,

  1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25

The following c program prints an n by n multiplication table. For example, if user inputs a value of 10, multiplication tables of all numbers from 1 to 10 are printed.

C Program to Create n by n Multiplication Table

We use the scanf and printf functions to generate multiplication table in c.

#include <stdio.h>

// Multiplication table generator
void printMultTable(int tableSize) {
  printf("      ");
  for(int i = 1; i<=tableSize;i++ ) {
    printf("%4d",i);
  }
  printf("\n");
  for(int i=0;i<tableSize;i++) {
    printf("----");
  }
  printf("--------\n");
  for(int i = 1 ;i<=tableSize;i++) {
      // print left most column first
      printf("%4d |",i);
      for(int j=1;j<=tableSize;j++) {
          printf("%4d",i*j);
      }
      printf("\n");
  }
}

int main() {
  printf("Please enter multiplication table size: ");
  int tableSize;
  scanf("%d",&tableSize);
  printMultTable(tableSize);
  return 0;
}

The output for the program for an input of 6 is given below,

Please enter multiplication table size: 6
         1   2   3   4   5   6
--------------------------------
   1 |   1   2   3   4   5   6
   2 |   2   4   6   8  10  12
   3 |   3   6   9  12  15  18
   4 |   4   8  12  16  20  24
   5 |   5  10  15  20  25  30
   6 |   6  12  18  24  30  36

Students memorize the multiplication tables of numbers from 1 to 10. Using these tables it is possible to multiply large numbers without a calculator.

C Program to Generate Multiplication Table for a Number

The following c program prints the multiplication table of a given number. This table is actually a subset of the table we created earlier. Here we print the column corresponding to the given number in the first row.

#include <stdio.h>

// Multiplication table for a number
void printTable(int number) {
  for(int i = 1; i<=10;i++ ) {
    printf("%dx%d=%d\n",i,number,i*number);
  }
}

int main() {
  printf("Please enter a number from 1 to 10: ");
  int number;
  scanf("%d",&number);
  printTable(number);
  return 0;
}

The output from the c program is given below,

Please enter a number from 1 to 10: 9
1x9=9
2x9=18
3x9=27
4x9=36
5x9=45
6x9=54
7x9=63
8x9=72
9x9=81
10x9=90

Java Byte Code Modification Using Cglib and Asm

This article looks at how cglib library can be used for java byte code manipulation at runtime. A number of popular java projects such as spring framework, guice and hibernate internally use cglib for byte code manipulation.

Byte code modification enables manipulation or creation of new classes after compilation phase of java applications. In java, classes are linked dynamically at runtime and hence it is possible to switch the compile dependency with a different implementation. For example, spring framework uses byte code manipulation to return a modified version of the original class at runtime. This allows spring framework add new features to existing classes. For example, spring AOP heavily uses this feature.

An interesting example of this behavior is java configuration classes in spring. When we write a java configuration class for beans (@Configuration and @Bean), we create new instances of the bean. However at runtime spring replaces this class with an implementation that internally reuses an existing instance for a bean (making it a singleton). Spring uses cglib (which internally uses low level asm library) for byte code manipulation. The following sections contain a number of example of byte code modification using cglib.

This example uses the following tools,

Create a simple gradle java project using eclipse. Modify the build.gradle to add the dependency on cglib 3.2.5,

apply plugin: 'application'

repositories {
    jcenter()
}

dependencies {
    compile 'cglib:cglib:3.2.5'
}

Using Cglib Enhancer Class

The cglib Enhancer class can be used to create dynamic subclasses for method interception. Note that all methods of the class are intercepted. A derived instance of Callback interface can be used handle method interception. For example, the derived interface FixedValue can be used return a fixed value instead of invoking the method of the original class. The following class demonstrates the use of Enhancer and Fixedvalue,

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.FixedValue;

public class EnhancerFixedValueDemo {

    public static void main(String[] args) {

        Enhancer er = new Enhancer();
        er.setSuperclass(SimpleClass.class);
        er.setCallback(new FixedValue() {

            @Override
            public Object loadObject() throws Exception {
                // This is called for every method call of the original class
                // We return a fixed value of the same type as the original
                // method
                return "Hello FixedValue!";
            }

        });

        SimpleClass sc = (SimpleClass) er.create();
        // We think we are using Simple Class!
        // But instead Hello FixedValue! is printed
        System.out.println(sc.getHello());

    }

}

class SimpleClass {
    public String getHello() {
        return "Hello World!";
    }
}

We can use the MethodInterceptor interface to invoke the original method call and optionally return a modified version. Check out the following example which uses Enhancer and MethodInterceptor,

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class EnhancerMethodInterceptorDemo {
    public static void main(String[] args) {

        Enhancer er = new Enhancer();
        er.setSuperclass(SimpleClass2.class);
        er.setCallback(new MethodInterceptor() {

            @Override
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
                // Call the method of the original class
                Object o = proxy.invokeSuper(obj, args);

                // Take a look at what original class returned
                System.out.println("Inspecting " + o);

                // We can even modify it if needed.
                // if you have mutliple methods, return type should be checked
                // (use method.getReturnType())
                return ((String) o).toUpperCase();
            }
        });

        SimpleClass2 sc = (SimpleClass2) er.create();
        System.out.println(sc.getHello());

    }

}

class SimpleClass2 {
    public String getHello() {
        return "Hello World!";
    }
}

Using Cglib ImmutableBean

The ImmutableBean in cglib can be used to return a read only copy of a java bean. Any modification attempted will throw a runtime error. Check out the following example,

import net.sf.cglib.beans.ImmutableBean;

public class ImmutableBeanDemo {
    public static void main(String[] args) {
        SimpleBean bean = new SimpleBean();
        bean.setName("QPT");

        SimpleBean bean2 = (SimpleBean) ImmutableBean.create(bean);

        // This throws a runtime exception
        // java.lang.IllegalStateException
        bean2.setName("QPT2");

    }

}

class SimpleBean {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Using Cglib BeanCopier

The BeanCopier in cglib can be used to copy properties from one bean class to another bean class. The copying is done looking at the matching property name. Check out the following example,

import net.sf.cglib.beans.BeanCopier;

public class BeanCopierDemo {
    public static void main(String[] args) {
        SimpleBeanA beanA = new SimpleBeanA();
        beanA.setName("QPT");

        SimpleBeanB beanB = new SimpleBeanB();

        BeanCopier copier = BeanCopier.create(SimpleBeanA.class, SimpleBeanB.class, false);
        copier.copy(beanA, beanB, null);

        System.out.println(beanB.getName());
    }

}

class SimpleBeanA {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

class SimpleBeanB {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}