Bitwise Operators in C

Bitwise operator is an operator that manipulates individual bits. The bitwise operators are similar to the logical operators, except that they work on a smaller scale — binary representations of data. We need to know about the precedences and associativities of different bitwise operators for efficient and error prone coding. Precedence is the priority for grouping different types of operators with their operands. Associativity is the left-to-right or right-to-left order for grouping operands to operators that have the same precedence. An operator’s precedence is meaningful only if other operators with higher or lower precedence are present. Expressions with higher-precedence operators are evaluated first. The grouping of operands can be forced by using parentheses.

The following table lists C operators in order of precedence (highest to lowest). Their associativity indicates in what order operators of equal precedence in an expression are applied.

Operator Description Associativity
( )[ ].– >

++, —

Parentheses (function call)
Brackets (array subscript)
Member selection via object name
Member selection via pointerPostfix increment/decrement
left-to-right
++  —
+  –
!  ~
(type)
*
&
sizeof
 
Prefix increment/decrement
Unary plus/minus
Logical negation/bitwise complement
Cast (change type)
Dereference
Address
Determine size in bytes
right-to-left
*  /  % Multiplication/division/modulus left-to-right
+  – Addition/subtraction left-to-right
<<  >> Bitwise shift left, Bitwise shift right left-to-right
<  <=
>  >=
Relational less than/less than or equal to
Relational greater than/greater than or equal to
left-to-right
==  != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
| | Logical OR left-to-right
? : Ternary conditional right-to-left
=
+=  -=
*=  /=
%=  &=
^=  |=

<<=  >>=

Assignment
Addition/subtraction assignment
Multiplication/division assignment
Modulus/bitwise AND assignment
Bitwise exclusive/inclusive OR assignment
Bitwise shift left/right assignment
right-to-left
, Comma (separate expressions) left-to-right
Advertisements

Implementation of some graph algorithms in C

A graph is simply a set of points together with a set of lines connecting various points. A graph may be undirected, meaning that there is no distinction between the two vertices associated with each edge, or its edges may be directed from one vertex to another. According to wikipedia: In mathematics and computer science, graph theory is the study of graphs, mathematical structures used to model pairwise relations between objects from a certain collection. Graph algorithms solve problems related to graph theory.

I implemented BFS,DFS, minimum spanning tree, Dijkstra’s and Floyd’s algorithms.

Breadth-First Search(BFS).

BFS begins at the root node and explores all the neighbouring nodes. Then for each of those nearest nodes, it explores their unexplored neighbour nodes, and so on, until it finds the goal.

The following figure illustrates the order in which the nodes are expanded.

The code of this program is available at: https://bitbucket.org/vidyakv/graph-algorithms-in-c/changeset/d00d940c1a8d#chg-bfs2.c

Depth-First Search(DFS)

Depth-first search (DFS) is an algorithm for traversing or searching a tree, tree structure, or graph. One starts at the root (selecting some node as the root in the graph case) and explores as far as possible along each branch before backtracking.
The following figure illustrates the order in which the nodes are expanded.


The code of this program is available at: https://bitbucket.org/vidyakv/graph-algorithms-in-c/changeset/d00d940c1a8d#chg-dfs_path.c

Minimum Spanning Tree

A spanning tree of an undirected graph is a subgraph that is a tree and connects all the vertices together. A single graph can have many different spanning trees. A minimum spanning tree (MST) or minimum weight spanning tree is then a spanning tree with weight less than or equal to the weight of every other spanning tree.

The following figure illustrates the minimum spanning tree of a planar graph. Each edge is labeled with its weight, which here is roughly proportional to its length.


The code of this program is available at: https://bitbucket.org/vidyakv/graph-algorithms-in-c/changeset/d00d940c1a8d#chg-min_span_tree.c

Dijkstra’s algorithm

It is a graph search algorithm that solves the single-source shortest path problem for a graph with nonnegative edge path costs, producing a shortest path tree. This algorithm is often used in routing and as a subroutine in other graph algorithms. For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex. It can also be used for finding costs of shortest paths from a single vertex to a single destination vertex by stopping the algorithm once the shortest path to the destination vertex has been determined.

The code of this program is available at: https://bitbucket.org/vidyakv/graph-algorithms-in-c/changeset/d00d940c1a8d#chg-dijkstra.c

Floyd-Warshall algorithm

It is a graph analysis algorithm for finding shortest paths in a weighted graph (with positive or negative edge weights). A single execution of the algorithm will find the lengths (summed weights) of the shortest paths between all pairs of vertices though it does not return details of the paths themselves. The algorithm is an example of dynamic programming.

The code of this program is available at: https://bitbucket.org/vidyakv/graph-algorithms-in-c/changeset/0772753fa848#chg-floyd1.c

Note: The images used in this post is taken from wikipedia.

Graph colouring using PyGame

In graphtheory, graph coloring is a special case of graph labeling; it is an assignment of labels traditionally called “colors” to elements of a graph subject to certain constraints. In its simplest form, it is a way of coloring the vertices of a graph such that no two adjacent vertices share the same color; this is called a vertex coloring.  

In my program, I implemented the graph coloring in Python. The colouring code is given below:

The PyGame library is used here to visualize the graph colouring in Python. Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language.

The complete code of this program is available in my bitbucket account. Here is the link: https://bitbucket.org/vidyakv/graph-colouring-using-pygame/changeset/0698b8122965#chg-graph3.py

AVL Tree (Adelson-Velskii-Landis) – Implementation in C

An AVL tree is a self balancing binary search tree, and it was the first such data structure to be invented. In an AVL tree, the heights of the two child subtrees of any node differ by at most one. Lookup, insertion, and deletion all take O(log n) time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree-rotations.

   The balance factor of a node is the height of its left subtree minus the height of its right subtree (sometimes opposite) and a node with balance factor 1, 0, or −1 is considered balanced. A node with any other balance factor is considered unbalanced and requires rebalancing the tree. The balance factor is either stored directly at each node or computed from the heights of the subtrees.

AVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log n) time for the basic operations. Because AVL trees are more rigidly balanced, they are faster than red-black trees for lookup intensive applications. However, it looks like red-black trees could be faster for insertion and element removal.

Basic operations of an AVL tree involve carrying out the same actions as would be carried out on an unbalanced binary search tree, but modifications are preceded or followed by one or more operations called tree rotations, which help to restore the height balance of the subtree.

Lookup

Lookup in an AVL tree is performed exactly as in an unbalanced binary search tree. Because of the height-balancing of the tree, a lookup takes O(log n) time. No special actions need to be taken, and the tree’s structure is not modified by lookups. If each node additionally records the size of its subtree (including itself and its descendants), then the nodes can be retrieved by index in O(log n) time as well. 

Insertion

After inserting a node, it is necessary to check each of the node’s ancestors for consistency with the rules of AVL. For each node checked, if the balance factor remains −1, 0, or +1 then no rotations are necessary. However, if the balance factor becomes ±2 then the subtree rooted at this node is unbalanced. If insertions are performed serially, after each insertion, at most one of the following cases needs to be resolved to restore the entire tree to the rules of AVL.

There are four cases which need to be considered, of which two are symmetric to the other two. Let P be the root of the unbalanced subtree, with R and L denoting the right and left children of P respectively.

Right-Right case and Right-Left case:

  • If the balance factor of P is -2 then the right subtree outweights the left subtree of the given node, and the balance factor of the right child (R) must be checked. The left rotation with P as the root is necessary.
  • If the balance factor of R is -1, a double left rotation(with respect to P and then R) is needed (Right-Right case).
  • If the balance factor of R is +1, two different rotations are needed. The first rotation is a right rotation with R as the root. The second is a left rotation with P as the root (Right-Left case).

Left-Left case and Left-Right case:

  • If the balance factor of P is +2, then the left subtree outweighs the right subtree of the given node, and the balance factor of the left child (L) must be checked. The right rotation with P as the root is necessary.
  • If the balance factor of L is +1, a double right rotation (with respect to P and then L) is needed (Left-Left case).
  • If the balance factor of L is -1, two different rotations are needed. The first rotation is a left rotation with L as the root. The second is a right rotation with P as the root (Left-Right case). The pictorial representation is given below:

                                                                                                                         

I have done the implementation of AVL tree in C.

The program for rotation is shown below: 

For left-right,  

      

For left-left,

For right-left,

For right-right,

The complete code of implementation of AVL tree in C is available here: https://bitbucket.org/vidyakv/avl-tree/changeset/a112ab2dd2f4 

Deletion

If the node is a leaf or has only one child, remove it. Otherwise, replace it with either the largest in its left subtree (inorder predecessor) or the smallest in its right subtree (inorder successor), and remove that node. The node that was found as a replacement has at most one subtree. After deletion, retrace the path back up the tree (parent of the replacement) to the root, adjusting the balance factors as needed.

Note: The image of tree used in this post is taken from wikipedia.

Version Control Systems

Version control or source control is the management of changes to documents, programs, and other information stored as computer files. It is most commonly used in software develoment, where a team of people may change the same files. Changes are usually identified by a number or letter code, termed the “revision number”, “revision level”, or simply “revision”. So it is also known as revision control.

Version control systems (VCSs – singular VCS) most commonly run as stand-alone applications, but revision control is also embedded in various types of software such as word processor (e.g., Microsoft Word, Openoffice.org Writer, K Word, Pages, etc.), spreadsheets (e.g., Microsoft Excel, Openoffice.org Calc, K Spread, Numbers, etc.), and in various content management systems (e.g.,joomla, WordPress).

Distributed revision control

Distributed revision control (DRCS) takes a peer-to-peer approach, as opposed to the client-server approach of centralized systems. Rather than a single, central repository on which clients synchronize, each peer’s working copy of the codebase is a bona-fide repository. Distributed revision control conducts synchronization by exchanging patches (change-sets) from peer to peer. This results in some important differences from a centralized system:

  • No canonical, reference copy of the codebase exists by default; only working copies.
  • Common operations (such as commits, viewing history, and reverting changes) are fast, because there is no need to communicate with a central server.

Rather, communication is only necessary when pushing or pulling changes to or from other peers.

    • Each working copy effectively functions as a remote backup of the codebase and of its change-history, providing natural protection against data loss.

Mercurial

Mercurial is a modern, open source, distributed version control system, and a compelling upgrade from older systems like Subversion. Developers use it to manage source code.

In Mercurial every developer has a copy of the entire repository on their hard drive. It’s actually safer. And anyway, almost every Mercurial team uses a central repository, too, which you can back up compulsively, and you can build a three-ringed security zone complete with layers of Cylons, Stormtroopers, and adorable labradoodles.

Branching causes problems in Subversion because Subversion doesn’t store enough information to make merging work. In Mercurial, merging is painless and easy, and so branching is commonplace and harmlessn Mercurial, every developer has their own repository.So you can commit your code to your private repository, and get all the benefit of version control, whenever you like. Every time you reach a logical point where your code is a little bit better, you can commit it.Once it’s solid, and you’re willing to let other people use your new code, you push your changes from your repository to a central repository that everyone else pulls from, and they finally see your code. When it’s ready.

Mercurial separates the act of committing new code from the act of inflicting it on everybody else.

And that means that you can commit (hg com) without anyone else getting your changes. When you’ve got a bunch of changes that you like that are stable and all is well, you push them (hg push) to the main repository.

Subversion likes to think about revisions. A revision is what the entire file system looked like at some particular point in time.In Mercurial, you think about changesets. A changeset is a concise list of the changes between one revision and the next revision.

Mercurial thinks in terms of “changesets” instead of “revisions” it can merge code much better than Subversion.”

Subversion is basically revision control for files, but in Mercurial, revision control always applies to an entire directory—including all subdirectories.

Actually Mercurial serves two important purposes:

  1. It keeps track of every old version of every file
  2. It can merge different versions of your code, so that teammates can work independently on the code and then merge their changes

The command for Mercurial is hg:

basic commands:
use "hg help" for the full list of commands or "hg -v" for details

hg init         –    creates a repository
hg add         – schedules files to be added to the repository. They won’t actually be added until you commit
hg commit   –  saves the current state of all files to the repository
hg log         –   shows the history of changes committed to the repository
hg revert     –   revert changed files back to committed version
hg status   –   shows a list of changed files
hg diff      –    shows what changed in a file
hg remove – schedules files to be removed from the repository. They won’t actually be removed until you commit.
hg cat        –  shows any revision of any file.
hg update  – update the working directory to a particular revision
hg serve    – runs a web server to make the current repository accessible over the Internet
hg clone   –  make a complete copy of an entire repository
hg push   –   push new changes from this repository into another
hg outgoing – list changes in current repository waiting to be pushed
hg merge   –   merge two heads
hg parent   –   show the changeset that’s in the working directory

Python Dictionaries

A dictionary is mutable and is another container type that can store any number of Python objects, including other container types.Dictionaries consist of pairs (called items) of keys and their corresponding values.Python dictionaries are also known as associative arrays or hash tables. The general syntax of a dictionary is as follows:

dict = {'A': '2341', 'B': '9102', 'C': '3258'}

You can create dictionary in the following way as well:

dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };

Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.

Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

Accessing Values in Dictionary:

To access dictionary elements, you use the familiar square brackets along with the key to obtain its value: 

dict = {'Name': 'Rahul', 'Age': 7, 'Class': 'First'};
print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age']; 

This will produce following result :

dict['Name']: Rahul dict['Age']: 7 

If we attempt to access a data item with a key which is not part of the dictionary, we get an error as follows:

dict = {'Name': 'Rahul', 'Age': 7, 'Class': 'First'};
print "dict['Alice']: ", dict['Alice'];

This will produce following result:

dict['Rahul']:
Traceback (most recent call last):
  File "test.py", line 4, in <module>
    print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'

Updating Dictionary:

You can update a dictionary by adding a new entry or item (i.e., a key-value pair), modifying an existing entry, or deleting an existing entry as shown below:

dict = {'Name': 'Rahul', 'Age': 7, 'Class': 'First'};

dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry

print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];

This will produce following result:

dict['Age']: 8
dict['School']: DPS School

Delete Dictionary Elements:

You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation.

To explicitly remove an entire dictionary, just use the del statement:

dict = {'Name': 'Rahul', 'Age': 7, 'Class': 'First'};

del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary

print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];

This will produce following result. Note an exception raised, this is because after del dict dictionary does not exist any more:

dict['Age']:
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable

Note: del() method is discussed in subsequent section.

Properties of Dictionary Keys:

Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys.There are two important points to remember about dictionary keys:

(a) More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins.

dict = {'Name': 'Rahul', 'Age': 7, 'Name': 'Manni'};
 print "dict['Name']: ", dict['Name'];

This will produce following result:

dict['Name']: Manni

(b) Keys must be immutable. Which means you can use strings, numbers, or tuples as dictionary keys but something like [‘key’] is not allowed.

dict = {['Name']: 'Rahul', 'Age': 7};

print "dict['Name']: ", dict['Name'];

This will produce following result. Note an exception raised:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    dict = {['Name']: 'Rahul', 'Age': 7};
TypeError: list objects are unhashable

Built-in Dictionary Functions & Methods:

Python includes following dictionary functions

SN Function with Description
1 cmp(dict1, dict2)
Compares elements of both dict.
2 len(dict)
Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.
3 str(dict)
Produces a printable string representation of a dictionary
4 type(variable)
Returns the type of the passed variable. If passed variable is dictionary then it would return a dictionary type.

Python includes following dictionary methods

SN Methods with Description
1 dict.clear()
Removes all elements of dictionary
dict
2 dict.copy()
Returns a shallow copy of dictionary
dict
2 dict.fromkeys()
Create a new dictionary with keys from seq and values
set to value.
3 dict.get(key, default=None)
For
key key, returns value or default if key not in dictionary
4 dict.has_key(key)
Returns
true if key in dictionary dict, false otherwise
5 dict.items()
Returns a list of
dict‘s (key, value) tuple pairs
6 dict.keys()
Returns list of dictionary dict’s keys
7 dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if
key is not already in dict
8 dict.update(dict2)
Adds dictionary
dict2‘s key-values pairs to dict
9 dict.values()
Returns list of dictionary
dict2‘s values

Python Regular Expression

Regular expressions are a powerful language for matching text patterns. The module for regular expression is ‘re’.
match = re.search(pattern,string)  is a basic eg for the regular expression… Here, the search function searches for the pattern in the string. If match is obtained, it returns a matched object. If no match is obtained, then a None is returned.

Another commonly used extension of RE is the findall.
The expression : match = re.findall(pattern,string)
Returns a list of all non-overlapping matches in the string. If one or more groups are present in the pattern, returns a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result.

Patterns
The power of regular expressions is that they can specify patterns, not just fixed characters. Here are the most basic patterns which match single chars:

  • a, X, 9, < — ordinary characters just match themselves exactly. The meta-characters which do not match themselves because they have special meanings are: . ^ $ * + ? { [ ] \ | ( ) (details below)
  • . (a period) — matches any single character except newline ‘\n’
  • \w — (lowercase w) matches a “word” character: a letter or digit or underbar [a-zA-Z0-9_]. Note that although “word” is the mnemonic for this, it only matches a single word char, not a whole word. \W (upper case W) matches any non-word character.
  • \b — boundary between word and non-word
  • \s — (lowercase s) matches a single whitespace character — space, newline, return, tab, form [ \n\r\t\f]. \S (upper case S) matches any non-whitespace character.
  • \t, \n, \r — tab, newline, return
  • \d — decimal digit [0-9] (some older regex utilities do not support but \d, but they all support \w and \s)
  • ^ = start, $ = end — match the start or end of the string
  • \ — inhibit the “specialness” of a character. So, for example, use \. to match a period or \\ to match a slash. If you are unsure if a character has special meaning, such as ‘@’, you can put a slash in front of it, \@, to make sure it is treated just as a character.

When we need to specify the repetition of pattern that is required tobe found, we use the following patterns.

  • + — 1 or more occurrences of the pattern to its left, e.g. ‘i+’ = one or more i’s
  • * — 0 or more occurrences of the pattern to its left
  • ? — match 0 or 1 occurrences of the pattern to its left

findall can also be used with files. To do so, first the file is opened and read into a variable and placed in place of string.

eg:
f=open(filename,’r’)
a=f.read()
match = re.findall(r’pattern’,a)
the matched objects will be returned to a list, match.

The repetitions discussed above are all greedy.
If we are trying to match each tag with the pattern ‘(<.*>)’ the greedy aspect of the .* causes it to match the whole ‘<b>foo</b> and <i>so on</i>’ as one big match. The problem is that the .* goes as far as is it can, instead of stopping at the first > .

Hence we get many number of matches. In order to avoid this, these repetitions can be made Non-greedy by using a ? after the specified pattern. Now they stop as soon as they can. So the pattern ‘(<.*?>)’ will get just ‘<b>’ as the first match, and ‘</b>’ as the second match, and so on getting each <..> pair in turn.

Strings in Python

1. A string is a sequence

A string is a sequence of characters. You can access the characters one at a time with the bracket operator:

>>> fruit = 'banana'
>>> letter = fruit[1] 

The second statement selects character number 1 from fruit and assigns it to letter.
The expression in brackets is called an index. The index indicates which character in the sequence you want (hence the name).
But you might not get what you expect:

>>> print letter
a

For most people, the first letter of ‘banana’ is b, not a. But for computer scientists, the index is an offset from the beginning of the string, and the offset of the first letter is zero.

>>>letter = fruit[0]

b

So b is the 0th letter of ‘banana’, a is the 1th letter , and n is the 2th letter. You can use any expression, including variables and operators, as an index, but the value of the index has to be an integer. Otherwise you get:

>>> letter = fruit[1.5]
TypeError: string indices must be integers

2.len

len is a built-in function that returns the number of characters in a string:

>>>fruit = 'banana'
>>> len(fruit)
6

To get the last letter of a string, you might be tempted to try something like this:

>>> length = len(fruit)
>>> last = fruit[length]
IndexError: string index out of range

The reason for the IndexError is that there is no letter in ’banana’ with the index 6. Since we started counting at zero, the six letters are numbered 0 to 5. To get the last character, you have to subtract 1 from length:

>>>last = fruit[length-1]
>>>print last
a

 Alternatively, you can use negative indices, which count backward from the end of the string.

3  Traversal with a for loop

A lot of computations involve processing a string one character at a time. Often they start at the beginning, select each character in turn, do something to it, and continue until the end. This pattern of processing is called a traversal. One way to write a traversal is with a while loop:

index = 0
while index < len(fruit):
 letter = fruit[index]
 print letter
 index = index + 1

This loop traverses the string and displays each letter on a line by itself. The loop condition is index < len(fruit), so when indexis equal to the length of the string, the condition is false, and the body of the loop is not executed. The last character accessed is the one with the index len(fruit)-1, which is the last character in the string.
Another way to write a traversal is with a for loop:

for char in fruit:
 print char

Each time through the loop, the next character in the string is assigned to the variable char. The loop continues until no characters are left.
The following example shows how to use concatenation (string addition) and a for loop to generate an abecedarian series (that is, in alphabetical order). In Robert McCloskey’s book Make Way for Ducklings, the names of the ducklings are Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack. This loop outputs these names in order:

prefixes = 'JKLMNOPQ'
suffix = 'ack'
for letter in prefixes:
 print letter + suffix

The output is:

Jack
Kack
Lack
Mack
Nack
Oack
Pack
Qack

Of course, that’s not quite right because “Ouack” and “Quack” are misspelled

4  String slices.

A segment of a string is called a slice. Selecting a slice is similar to selecting a character:

>>> s = 'Monty Python'
>>> print s[0:5]
Monty
>>> print s[6:12]
Python

The operator [n:m] returns the part of the string from the “n-eth” character to the “m-eth” character, including the first but excluding the last. If you omit the first index (before the colon), the slice starts at the beginning of the string. If you omit the second index, the slice goes to the end of the string:

>>> fruit = 'banana'
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'

If the first index is greater than or equal to the second the result is an empty string, represented by two quotation marks:

>>> fruit = 'banana'
>>> fruit[3:3]
''

An empty string contains no characters and has length 0, but other than that, it is the same as any other string.

5  Strings are immutable.

It is tempting to use the [] operator on the left side of an assignment, with the intention of changing a character in a string. For example:

>>> greeting = 'Hello, world!'
>>> greeting[0] = 'J'
TypeError: object does not support item assignment

The “object” in this case is the string and the “item” is the character you tried to assign. For now, an object is the same thing as a value, but we will refine that definition later. An item is one of the values in a sequence.

The reason for the error is that strings are immutable, which means you can’t change an existing string. The best you can do is create a new string that is a variation on the original:

>>> greeting = 'Hello, world!'
>>> new_greeting = 'J' + greeting[1:]
>>> print new_greeting
Jello, world!

This example concatenates a new first letter onto a slice of greeting. It has no effect on the original string.

6  Searching

What does the following function do?

def find(word, letter):
 index = 0
 while index < len(word):
 if word[index] == letter:
 return index
 index = index + 1
 return -1

In a sense, find is the opposite of the [] operator. Instead of taking an index and extracting the corresponding character, it takes a character and finds the index where that character appears. If the character is not found, the function returns -1.
This is the first example we have seen of a return statement inside a loop. If word[index] == letter, the function breaks out of the loop and returns immediately.
If the character doesn’t appear in the string, the program exits the loop normally and returns -1.
This pattern of computation—traversing a sequence and returning when we find what we are looking for—is called a search.

7  Looping and counting

The following program counts the number of times the letter a appears in a string:

word = 'banana'
count = 0
for letter in word:
 if letter == 'a':
 count = count + 1
print count

This program demonstrates another pattern of computation called a counter. The variable count is initialized to 0 and then incremented each time an a is found. When the loop exits, count contains the result—the total number of a’s.

8  stringmethods

A method is similar to a function—it takes arguments and returns a value—but the syntax is different. For example, the method upper takes a string and returns a new string with all uppercase letters:
Instead of the function syntax upper(word), it uses the method syntax word.upper().

>>> word = 'banana'
>>> new_word = word.upper()
>>> print new_word
BANANA

This form of dot notation specifies the name of the method, upper, and the name of the string to apply the method to, word. The empty parentheses indicate that this method takes no argument.
A method call is called an invocation; in this case, we would say that we are invoking upper on the word.
As it turns out, there is a string method named find that is remarkably similar to the function we wrote:

>>> word = 'banana'
>>> index = word.find('a')
>>> print index
1

In this example, we invoke find on word and pass the letter we are looking for as a parameter.
Actually, the find method is more general than our function; it can find substrings, not just characters:

>>> word.find('na')
2

It can take as a second argument the index where it should start:

>>> word.find('na', 3)
4

And as a third argument the index where it should stop:

>>> name = 'bob'
>>> name.find('b', 1, 2)
-1

This search fails because b does not appear in the index range from 1 to 2 (not including 2).

9  The in operator

The word in is a boolean operator that takes two strings and returns True if the first appears as a substring in the second:

>>> 'a' in 'banana'
True
>>> 'seed' in 'banana'
False

For example, the following function prints all the letters from word1 that also appear in word2:

def in_both(word1, word2):
 for letter in word1:
 if letter in word2:
 print letter

With well-chosen variable names, Python sometimes reads like English. You could read this loop, “for (each) letter in (the first) word, if (the) letter (appears) in (the second) word, print (the) letter.”
Here’s what you get if you compare apples and oranges:

>>> in_both('apples', 'oranges')
a
e
s

10  String comparison

The relational operators work on strings. To see if two strings are equal:

if word == 'banana':
 print 'All right, bananas.'

Other relational operations are useful for putting words in alphabetical order:

if word < 'banana':
 print 'Your word,' + word + ', comes before banana.'
elif word > 'banana':
 print 'Your word,' + word + ', comes after banana.'
else:
 print 'All right, bananas.'

Python does not handle uppercase and lowercase letters the same way that people do. All the uppercase letters come before all the lowercase letters, so:

Your word, Pineapple, comes before banana.

A common way to address this problem is to convert strings to a standard format, such as all lowercase, before performing the comparison. Keep that in mind in case you have to defend yourself against a man armed with a Pineapple.

11  Debugging

When you use indices to traverse the values in a sequence, it is tricky to get the beginning and end of the traversal right. Here is a function that is supposed to compare two words and return True if one of the words is the reverse of the other, but it contains two errors:

def is_reverse(word1, word2):
 if len(word1) != len(word2):
 return False
 i = 0
 j = len(word2)
 while j > 0:
 if word1[i] != word2[j]:
 return False
 i = i+1
 j = j-1
 return True

The first if statement checks whether the words are the same length. If not, we can return False immediately and then, for the rest of the function, we can assume that the words are the same length.
i and j are indices: i traverses word1 forward while j traverses word2 backward. If we find two letters that don’t match, we can return False immediately. If we get through the whole loop and all the letters match, we return True.
If we test this function with the words “pots” and “stop”, we expect the return value True, but we get an IndexError:

>>> is_reverse('pots', 'stop')
...
 File "reverse.py", line 15, in is_reverse
 if word1[i] != word2[j]:
IndexError: string index out of range

For debugging this kind of error, my first move is to print the values of the indices immediately before the line where the error appears.

 while j > 0:
 print i, j # print here
 if word1[i] != word2[j]:
 return False
 i = i+1
 j = j-1

Now when I run the program again, I get more information:

>>> is_reverse('pots', 'stop')
0 4
...
IndexError: string index out of range

The first time through the loop, the value of j is 4, which is out of range for the string 'pots'. The index of the last character is 3, so the initial value for j should be len(word2)-1.
If I fix that error and run the program again, I get:

>>> is_reverse('pots', 'stop')
0 3
1 2
2 1
True

This time we get the right answer.

Starting with python

Python is a Programming Language

     Started by Guido van Rossum in 1990 as a way to write software for the Amoeba operating system. Influenced by ABC, which was designed to be easy to learn. It is also very useful for large programs written by expert programmers.The word “Python” comes from the comedy troupe “Monty Python”.

Guido Van Rossum
Python is an interpreted, general-purpose high-level programming language whose design philosophy emphasizes code readability. Python claims to “[combine] remarkable power with very clear syntax”, and its standard library is large and comprehensive. Its use of indentation for block delimiters is unique among popular programming languages.

How a python program runs

When we write a python program and execute it, there occurs the output or errors. But what actually happens behind them?? Let’s see..
First take the simplest of python program. The hello world program.


$ vi sample.py


print ‘Hello World’


The filename python.py has the extension .py to show that its a python file. Its not necessary as any filename will do as long as it contains a valid python code. We use the .py extension anyhow for consistency.
if we save the file and execute it,


$python sample.py

Hello World
Thats all the output that we see. And we think thats it!!! Well thats what happens on the outside and thats all that a normal programmer needs to know. But sometimes its good to know what actually happens under the hood when we execute the python program. There are a couple of common steps that the pyhton program does before executing the program.
These steps are:

Compiling the code to what is known as a byte code that is common to all the machines.

Running this bytecode using a Virtual Machine

Byte Code


When we give the command to execute the program, the python first compiles our souce code to a format that is known as a byte code. This byte code is a lower level and platform independent(but version dependent) representation. Hence these can be ported to any system that contains the same python version. This step is done to improve the speed of execution of the program. The byte code in python is of .pyc format. If we execute the program outside the interpreter, then the .pyc file is usually temporarily stored in the memory and discarded after the execution.But if we are running the program from the interpreter, a .pyc file is created in the same folder as the program. And the python will execute a pyc file even if the original py file is absent. If a program is being executed, the python looks if the .pyc file is present and it has the time stamp as the file. If so, that file is executed and not the py file for a faster execution.
Now once the Byte Code has been compiled, the program is ready for execution. The virtual machine steps in. The .pyc file is send to the Python Virtual Machine for execution. The virtual machine is a big loop that executes through our byte code instruction one by one to carryout our instructions. The PVM is the runtime engine of Python; it’s always present as part of the Python system, and is the component that truly runs our scripts. Technically, it’s just the last step of what is called the Python interpreter. Byte code compilation is automatic, and the PVM is just part of the Python system that we have on our system.

‘Innovation’ begins…

Hi…. I am Vidya. I am starting this blog as per the suggestion of Mr Pramode.C.E, a programmer and consultant on free and open source software based technologies. Now I am doing a programming course in IC Software under Mr. Pramode.C.E.

I think, this will be a good experience and a great start for my career.

The WordPress.com Blog

The latest news on WordPress.com and the WordPress community.