Sunday, August 29, 2010

Programming in Python : Dictionaries

Dictionaries are another data type in python. It can be think as a unordered collection of keys associated with values. The keys can be numbers, strings, or tuples. An empty dictionary is denoted by '{ }'. We can view all keys by simply calling keys(). The dict() constructor is using to build a dictionary.

>>> dic = {'one':1,'two':2,'three':3,'four':4,'five':5}

>>> dic
{'four': 4, 'three': 3, 'five': 5, 'two': 2, 'one': 1}

>>> dic['six'] = 6

>>> dic
{'six': 6, 'three': 3, 'two': 2, 'four': 4, 'five': 5, 'one': 1}

>>> del dic['five']

>>> dic
{'six': 6, 'three': 3, 'two': 2, 'four': 4, 'one': 1}

>>> dic['seven'] = 7

>>> dic
{'seven': 7, 'six': 6, 'three': 3, 'two': 2, 'four': 4, 'one': 1}

>>> dic.key()

Traceback (most recent call last):
File "", line 1, in
AttributeError: 'dict' object has no attribute 'key'

>>> dic.keys()
['seven', 'six', 'three', 'two', 'four', 'one']

>>> dic['seven']
7
>>> dic['one']
1

>>> 'one' in dic
True

>>> 'three' in dic
True

>>> 'kjkk' in dic
False

>>> del dic['one']

>>> dic
{'seven': 7, 'six': 6, 'three': 3, 'two': 2, 'four': 4}

>>> dic.keys()
['seven', 'six', 'three', 'two', 'four']

>>> dic.values()
[7, 6, 3, 2, 4]

>>> a=[('aass',23),('iiii',56),('dftj',38)]

>>> a
[('aass', 23), ('iiii', 56), ('dftj', 38)]

>>> dict(a)
{'aass': 23, 'iiii': 56, 'dftj': 38}

>>> b = dict(a)

>>> b
{'aass': 23, 'iiii': 56, 'dftj': 38}

>>> dict(jhjkhk = 433,jkhjkhk = 3434,iuijmkm = 344343)
{'jkhjkhk': 3434, 'jhjkhk': 433, 'iuijmkm': 344343}

>>> c = dict(jhjkhk = 433,jkhjkhk = 3434,iuijmkm = 344343)

>>> c
{'jkhjkhk': 3434, 'jhjkhk': 433, 'iuijmkm': 344343}

Programming in Python : Sets

Set is a data type in python. It is an unordered set of elements without duplicates. We can test an element is a member of the set. Set operations can operate on unique letters as given below.

>>> list1 = ['apple','mango','pineapple','mango','apple','orange']

>>> fruit = set(list1)

>>> fruit
set(['orange','mango','apple','pineapple'])

>>> 'mango' in fruit
True

>>> 'grape' in fruit
False

>>> a = ('abhilash')

>>> a
'abhilash'

>>> b = ('abhijith')

>>> b
'abhijith'

>>> set(a)
set(['a', 'b', 'i', 'h', 'l', 's'])

>>> set(b)
set(['a', 'b', 'i', 'h', 'j', 't'])

>>> c = set(a)

>>> d = set(b)

>>> c
set(['a', 'b', 'i', 'h', 'l', 's'])

>>> d
set(['a', 'b', 'i', 'h', 'j', 't'])

>>> c-d
set(['s', 'l'])

>>> d-c
set(['j', 't'])

>>> c |d
set(['a', 'b', 'i', 'h', 'j', 'l', 's', 't'])

>>> c & d
set(['a', 'i', 'b', 'h'])

>>> c ^ d
set(['s', 't', 'j', 'l'])

Programming in python: Tuples and sequences

Tuples consists of elements that are enclosed in parenthesis. The empty tuples is represented by '()'. The single element tuple is ending with a comma.

>>> t = ('one','two','three')

>>> t
('one','two','three')

>>> e = ()

>>> e
()

>>> len(e)
0

>>> single = ('one',)

>>> single
('one',)

>>> len(single)
1

The statement t = 1223,5676,'one','two' is an example of tuple packing. The elements are packed together in a tuple. The sequence unpacking is also possible. ex: a,b,c,d = t

>>> t = 1223,5676,'one','two'

>>> t
(1223,5676,'one','two')

>>> a,b,c,d = t

>>> a
1223

>>> d
'two'

Programming in Python : Lists

The list data type in python allows more operations compared to the other data types. The items in the lists are enclosed by brackets '[]'. It may contain numbers, srtings, tuples or lists (nesting of lists).

>>> list1 = [1,2,3,'how','are','you']

>>> list1
[1, 2, 3, 'how', 'are', 'you']

>>> list1[3]
'how'

>>> list1[3:]
['how', 'are', 'you']

>>> list1[:2]
[1, 2]

>>> list1[:2] = 'and'

>>> list1
['a', 'n', 'd', 3, 'how', 'are', 'you']

>>> list1[:2] = ['and']

>>> list1
['and', 3, 'how', 'are', 'you']

>>> list1 = [12,34,56,'s','y']

>>> list1
[12, 34, 56, 's', 'y']

>>> list2 = [22,'22']

We can add members of one list to the members of another list.
>>> list1[3:3] = list2

>>> list1
[12, 34, 56, 22, '22', 's', 'y']

>>> list3 = [33,list2,'33']

The following list is nested.
>>> list3
[33, [22, '22'], '33']

>>> list3[1][1]
'22'

>>> list3[1][0]
22


The del statement :

It is used to remove an element from a list when the index of that element is given. It can be used to clear the entire list or remove the variable.

Programming in Python : Strings

Strings are also manupulated by python. Strings are represented within single quotes or double quotes. We can assign a string to a variable, and printed by using 'print'. Strings can be surrounded by triple quotes """. If there is \n the end of line, is echoed in the output.

>>> "Hello"+"world"
'Helloworld'

>>> a='how are you?'

>>> print a
how are you?

The slice notation :

The slice notation is used to return the elements of a list or characters of a string as specified by the indices.

>>> string1 = 'hello world'

>>> string1
'hello world'

>>> string1[0:1]
'h'

>>> string1[0:4]
'hell'

>>> string1[2:4]
'll'

>>> string1[:4]
'hell'

>>> string1[3:]
'lo world'

>>> string1[:0] = 'Hai'
Traceback (most recent call last):
File "", line 1, in
TypeError: 'str' object does not support item assignment

>>> string1[:0] + 'Hai'
'Hai'

>>> string1
'hello world'

>>> string1[:] + 'Hai'
'hello worldHai'

>>> 'Hai' + string1[:]
'Haihello world'

The negative indices are using to indicate from the right to the begining of the string.

>>> string1[-1]
'd'

>>> string1[-4:-1]
'orl'

>>> string1[-4:-2]
'or'

>>> string1[-4:0]
''

>>> string1[-1:-4]
''

>>> string1[-11:-1]
'hello worl'

Programming in Python : Arithmetic operations in python

Python is a functional programming language. Arithmetic operations are simply done as shown below in python interactive mode.

>>> 3+5
8

>>> (10+40)/10
5
A value can be assigned to sevaral variables simultaneously. Complex numbers are also supported. Imaginary numbers are written with a suffix j or J. In a complex number z, z.real and z.imag returns real and imaginary parts respectively. In interactive mode the last printed character is assigned to a variable'_'.

>>> x = y = z = 0

>>> -1j * 1j
(1+0j)

>>> a=678

>>> a*23
15594

>>> print _
15594

>>> _/22
708

Tuesday, August 24, 2010

Programming in Unix Environment : Using the shell

Command line structure :

A command usually ends with a newline but a semicolon ';' is also a command terminator. Parentheses can be used to group commands. Data flowing through a pipe can be trapped and placed in a file by using 'tee' command. tee copies its input to the file and its output. Another command terminator is '&' ampersand, which tells the shell not to wait for the command to complete, and we can enter another command to execute. The 'sleep' command waits the specified number of seconds before exiting. Here shows an example in which the the command after ampersand is 'who' it executes first and date executes after five seconds.

$ (date ; who) | wc
$ (who ; date) | tee file | wc
$ long-running-command &
$ sleep 5
$ (sleep 5 ; date) & who

Metacharacters :

The way to specify the metacharacters without its meaning - within single quotes.

$ echo '**'

Friday, August 13, 2010

UNIX file system : An Overview

A file is nothing more than a collection of data. Here describes a set of commands.

The command 'od' prints a visible representation of a file. The '-c' option is for interpreting bytes as characters. '-b' for printing the bytes as octal numbers.

$od -c file_name
$od -b file_name

The 'file' command guesses the type of the file. 'od' command with no option dumps the file in 16 bit words.

$od file_name
$file file_name



The command 'du' (disc usage) is to display the disc usage that consumed by the files in that directory. The -a option is for displaying all including the files in a directory. To search a specific file, the output is piped through grep.

$du
$du -a
$du -a | grep file_name

A directory consists of 16 byte chunks, the last 14 bytes of which hold the file name padded with ascii NULs. The first two of which tell the system where the administrative information resides.

The 'find' command finds the file specified.

$find file_name

Programming in C: Remember these points on constants.

A 'long' constant is written like 1234567697L or 567874338l. Big integer type constant is also taken as long. 'unsigned' constants written with a terminal u or U. 'unsigned' long type constants written with the terminal ul or UL. Floating point constants contain decimal point or an exponent (1e-1) or both. They are declared as 'double' type. The value of an integer can be specified as octal or hexadecimal. A leading zero on an integer constant means octal and a leading 0x or 0X means hexadecimal.

decimal : 31 octal : 031 hex : 0x1F

Character constants :

It is an integer. eg.'x'. A constant expression is an expression that involves only constants. They are used in any place where a constant occurs. A string constant or a string literal is a sequence of zero or more characters surrounded by double quotes.

In switch each case is labeled by integer valued constants or constant expressions. In the while and do loops 'continue' means that the test part is executed immediately. In for loop the control passes to the increment step. The continue statement applies only to loops not to 'switch'.

Programming in C : Remember these points on operators.

The cast operator has same high degree of precedence as other unary operators. The increment and decrement operators can only be applied to variables. An expression like '(exp) ++' is illegal. Bitwise shift operators can be used with constants or variables.

Var >> n

Here 'Var' is shifted n positions to the right. 'n' must be a positive value. Bitwise operators are using only on integral operands.

Tuesday, August 10, 2010

Programming in C: Remember these points on Datatypes.

'int' is 32 or 16 bit long and it depend upon machines. 'short' is often 16 bit long. 'signed' and 'unsigned' may be applied to char. But is plain chars are signed or unsigned ? It is machine dependent. If 'x' is float and 'i' is int, x = i and i = x both cause conversions.

Specify type correctly:

Please take a nice look to these points,
In C when we write an expression we must ensure that we specified the types correctly.
In an expression even if the left hand side is declared as floating point and the right hand side contain integer arithmetic & constant division, these constant division results the number truncated to integer. So we must represent these constants, as floating point number.
Consider the following expression

(float) a = (b - 18) * 7 / 9 ;

false result will goes to ' a '
we must write as,

(float) a = (b - 18) * 7 .0 / 9.0 ;

or

(float) a = (float) (b - 18) * 7 / 9 ;
Now,
when talking about the range of int , float it depends on the machines,
16 - bit int that is 2^16 = 65536 , dividing by 2 , 65536 / 2 it equals 32768
that is range - 32768 to 32767 for signed integers.


Consider the following expression,

(n > 0) ? f : n ;

If 'f' is float and 'n' is int the expression has type 'float' according to the conversion rule, not by the result of the condition.

Programming in C: Remember these points on Variables.

Don't begin variable names with underscore, since library routines often use such names. Upper and lower case letters are distinct. Atleast first 31 characters of an internal name are significant. External names may be used by assemblers and loaders over which the language has no control. The definition of C gurantees that any character in the machine's standard printing character set will never be negative.

Programming in C: A Small note on Functions.

printf, getchar(),putchar() all are C functions. No fuction can be split between files. 'main' function returns a value ,zero if normal termination or nonzero erroneous termination. The function prototype agree with the definition and uses of the function. If the actual arguments are more than the formal arguments, the extra arguments are discarded. And if the actual arguments are smaller than the formal arguments extra formal arguments are initialized to some garbage values. Automatic variables do not retain their values from one call to the next and must be set upon each entry. Any expression may follow a return statement. To assure a high degree of portability between programs a function should generally be coded without involving any I/O operations.Function returns int as default.To assure a high degree of portability between programs, a function should generally be coded without involving any I/O operations.

If a function fails to return a value its value is certain to be garbage. We can also compile three source files using 'cc' command which contain the program functions.

$ gcc main.c fun1.c fun2.c

Consider the statement, x = function1() + function2();

Here the order in which the calculation, function1() may be evaluated first or function2() may. C cannot specify such an order.

Programming in UNIX Environment : Commands - echo, rm, whoami

Take a look to the following UNIX commands.
who am i -This command shows your user name,teletype,date and time.

whoami - Shows only user name.

In UNIX systems,

parent directory is denoted by '..'
current directory is denoted by '.'

rmdir - for remove a directory. It removes only empty directories.

About shell :

When we type the commands it goes to the shell.It is an ordinary program.

cat c* //prints all file that begins with c.

when * occurs shell takes it and it means any string of characters. Note the * is not the property of the cat command.

The echo command lists what we type.

echo word

echo ch* //lists all begin wth ch.

echo * //lists all.

rm * - removes all.

rm *.text - removes all with .text.

pr r[1234]* // prints all that begin wth r and followed by 1,2,3 or 4.

rm te[a-z] //removes all files starting with te and followed by a lower case.


You cannot make up new files using pattern matching.

ls \? or ls '?' loses its meaning.

echo * // prints all.

We can redirect the output by using '>'. Take input from a file by using '<' followed by filename.When the file does not exist it will be created. For redirecting output to a file without losing the data of yhe file we uses '>>'.

ls > filelist

pr -3
cat file1.c file2.c > file3

cat file4.c >> file3.c

grep num.c

Thursday, August 5, 2010

Programming in UNIX environment : Commands - ed, cat, ls, pr,

In UNIX environment we use a lot of commands. Some commands are explaining here.
For editing a file we use ed command.
$ed file1
no such file or...
a
Enter the text
.
w file1
q
$

When we type the command 'ed' and the filename, if the file does not exist, it shows a message. Type 'a' for appending. After adding types a '.' character in the next line to indicate writing is over.Then write it into the file by typing 'w' and the file name.And 'q' to quit.
The command 'cat' shows the content of the file.
$cat sachin
$cat sachin num
'pr' instead shows the content by pages and the file name.In 'pr -m filename' the 'm' indicates the columns.
pr sachin
pr sachin num
$pr -3 sachin num
$pr -m // a set of files in parallel columns.

The 'ls' command lists all the files. The ls * lists all including the files in the directories.

ls DIRname
$ls *
$ls -t // list by time.
$ls -l //list by details.
$ls -lt //list by details by recent first.
$ls -u // infn abt when files were used.
$ls -ult // most recent.

Monday, August 2, 2010

Programming in C : A small note on arrays

The subscript of an array can be ' an expression ' which yields integers. Note that any reference to the array outside the declared limit would not necessarily cause an error.

If array size declared as 10 , then we declare first element to zero , as

int array [10] = {10} ;

then all elements are declared as zero automatically.

Here is an example of wrong declaration to an array.

char alpha [3] = {a,b,c} .

If you want to store alphabets into an array store its integer values ,

char alpha [3] = { 'a' , 'b' , 'c' }
and print them as characters.