Welcome to namasudra.blogspot.com. Glad to see you here!
Showing posts with label Python. Show all posts

Friday, March 15, 2019

Insertion Sort


Insertion Sort is a simple sorting technique widely used in many situations. In this sorting algorithm we start by picking the second element as key, compare it with the first element and put it in the right position. After that, the 3rd element is selected as key and compared with the elements from 1st to 2nd position and placed in the correct position. We repeat the same till the last element. In this process we have a total of n-1 passes starting from the 2nd element to the last element. This technique is similar to how we sort playing cards in our hand. Watch the video below to understand how Insertion Sort works.



Code for Insertion Sort in Python:


Output:

Unsorted List: [16, 9, 12, 37, 5, 68, 3]
Sorted List: [3, 5, 9, 12, 16, 37, 68]

Bubble Sort


In bubble sort we compare two adjoining elements and exchange them if they are not in proper order. We repeat this process for next two adjacent elements. In the first pass the heaviest element gets settled to the bottom of the list. Similarly, in the second pass the second heaviest element settles on top of the first heaviest element, and so on we repeat the process for n-1 passes in total. To understand this, see the bubble sort animation in this video:


Here is the code for bubble sort:

The Guessing Game!

Here is a simple and fun, number guessing game. This game illustrates the use of the function randint() from the random library.

A little about the randint() funtion:
The randint() function takes 2 numbers as arguments and returns a random number between the 2 numbers (inclusive of the lower and upper limit numbers). The randint() function is used as shown below,

import random
c = random.randint(50,250)
print(c)

Here, a random number between 50 and 250 will be stored in c. Both 50 and 250 are also included in the range.

Code for the Guessing Game:

Bouncing Ball Example with PyGame

Here is simple code to get you started with bouncing a ball against the boundaries of the window. I have used two images, one for the icon of the application and one for the ball. The image files are given under the code for you to download and use with the code. Download the image files and put them in the same folder where you save the code.

Code:


Graphic for the icon:


Graphic for the ball:


Output:


Adding a Paddle to Bouncing Ball

In the previous post we created the Bouncing Ball example. We will be adding a paddle to the Bouncing Ball example here, so that we can make it a bit interactive to play with. I have changed the title from Bouncing Ball to Paddle Ball. I have also changed the screen size to have more room to play. The images for the icon, ball and the paddle are given below the code. You can download them and put them in the same folder where you save the code.

Code:


Graphic for the icon:


Graphic for the ball:


Graphic for the paddle:


Output:


Adding Bricks to the Game

In the previous step, we have added a paddle to our game. In this step, we will be adding some bricks, so that the ball can strike and break them. There might be some weird movements of the ball as I have not added too much complexity to the program. I have done so intentionally, so that the code remains simple to understand. Further fine tuning can be done and some extra features can be added like the paddle shooting the ball at different angles depending on where on the paddle the ball strikes. You can also add different levels to the game and end the game if the ball misses the paddle.

Code:


Output:


Graphic for the icon:


Graphic for the ball:


Graphic for the paddle:


Graphic for the bricks:


Discount App

Here is a simple Discount App made with tkinter. This program will run only in Python 3. To run this program in Python 2, you will need to modify it accordingly.

Code:

Output:

To know more about TkInter, please visit tkinter documentation page here.

Using Combobox in tkinter

Here is a simple Trigonometry App made with tkinter. This program will run only in Python 3. To run this program in Python 2, you will need to modify it accordingly. In this example you will learn how to use the Combobox control with tkinter.

Code:


Output:


To know more about TkInter, please visit tkinter documentation page here.

Sunday, February 10, 2019

Fibonacci Series (in Python)

Q. Write a Python program to generate the first n terms of the Fibonacci Series.

Solution:

Program to generate first n terms of the Fibonacci Series.

Code:


Adding two integers using function

Q. Write a program in python to add two integers using function.

Solution:

Program to add two integers using function.

Code:


Saturday, February 9, 2019

Bitwise Operators

Bitwise operators are used to logical operations on each bit in binary form of a number. The operation takes place bit by bit of the number.

+-------+------------------+
|   &   |   Bitwise and    |
|   |   |   Bitwise  or    |
|   ^   |   Bitwise  xor   |
|   ~   |   Bitwise not    |
+-------+------------------+

To understand this lets take two numbers, a = 58 and b = 30. The binary representation of a and b is,

a = 00111010
b = 00011110

Now let us perform bitwise operations on these numbers. The table below lists the results of the operations.

+------------+-----------+---------------+
|  Examples  |  Results  | Decimal Value |
+------------+-----------+---------------+
|    a & b   |  00011010 |      26       |
|    a | b   |  00111110 |      62       |
|    a ^ b   |  00100100 |      36       |
|     ~a     | -00111011 |     -59       |
|     ~b     | -00011111 |     -31       |
+------------+-----------+---------------+

.

Identity Operators

Identity Operators:

+-----------+--------------------------------+
|   is      |  is having the same id()?      |
|   is not  |  is not having the same id()?  |
+-----------+--------------------------------+

Using identity operators we can check if two objects share the same memory location. We can check this with the id() function also. The expression a is b results in True if id(a) is equal to id(b).

Example:

a = 5
b = 5
if a is b:
    print("a and b have same identity:")
    print("id:",id(a),"and",id(b))
else:
    print("a and b have different identities:")
    print("id:",id(a),"and",id(b))
b = 10
if a is b:
    print("a and b have the same identity: ")
    print("id:",id(a),"and",id(b))
else:
    print("a and b have different identities:")
    print("id:",id(a),"and",id(b))


Output:

a and b have same identity:
id: 140719525389264 and 140719525389264
a and b have different identities:
id: 140719525389264 and 140719525389424


We can also find the type of an object using identity operators. The following example converts the variable code to a string if code is not of type string.

code = 91
if type(code) is not str:
    print("Country code: +" + str(code))

Output:

Country code: +91

.

Printing Shapes

The image below contains some question for printing different shapes.


Solutions:

Code for Question 11:


Alternative Method:


Code for Question 12:


Alternative Method:


Code for Question 13:


Alternative Method:


Code for Question 14:


Alternative Method:


While loops in Python

We use while loop to execute a bunch of statements repeatedly as long as a condition is true. The loop stops as soon as the condition becomes false.

Example:

To print 1 to 10 using while loop we can use the following code.

i = 1
while i <= 10:
    print(i)
    i = i + 1


The break statement:

The break statement is useful to stop the while loop in the middle of its iteration.

Example:

The following code will print 1, 2


i = 0
while i <= 5:
    i = i + 1
    if i == 3:
        break
    print(i)


The continue statement:

The continue statement is used to skip the current iteration of a while loop and move to the next iteration.

Example:

The following code will skip 3 print 1, 2, 4, 5, 6

i = 0
while i <= 5:
    i = i + 1
    if i == 3:
        continue
    print(i)


Using else with while loop:

Python lets us use an else block with while loops. The else block is executed after the while loop finishes all the iteration. The else block won't be executed if the loop exits abruptly through a break statement.

i = 1
while i < 6:
    print(i)

    i += 1
else:
    print('Tasks to do after the loop finishes')

If .. Else in Python

The if statement:

In python, the if statement is used for decision making. The if statement checks for a condition and executes a bunch of instructions if the condition is true.

if a > 5:
    print("Hello World!")

The above code will print Hello World! if the value of a is greater than 5, otherwise nothing will be printed.

The if - else statement:

An else block can also be used with the if statement. In this form, the if statement checks for a condition and if the condition is true, it executes the statements contained in the if block. And if the condition is false, the statements in the else block get executed.

if a>5:
    print("Greater than 5")
else:
    print("Less than or equal to 5")

The above code will print Greater than 5 if the value of a is greater than 5, otherwise it will print Less than or equal to 5.

The if - elif - else statement:

In some cases, we need to test another condition if the condition of if evaluates to false. In such cases we use elif. We can use as many elif blocks as we need, before we finally pass the control to the else block. The following example demonstrates this.

if marks >= 60:
    print("First Division")
elif marks >= 45:
    print("Second Division")
elif marks >= 30:
    print("Third Division")
else:
    print("Failed")

.

Quadratic Equation

This program calculates the roots of a quadratic equation from the co-efficient a, b and c. This program also calculates the roots if they are imaginary.

Code:


Python Tuples

A tuple in Python is a collection of data that is written within round brackets. Tuples are ordered collection of data, which means its has an index for every element. A tuple once created cannot be modified.

Creating a tuple:

We can create a tuple in the following way.

colorTuple = ("red","green","blue")
print(colorTuple)

Accessing tuple items:

The following will print 'green'. The index starts from 0, hence the element at index 1 is 'green'.

colorTuple = ("red","green","blue")
print(colorTuple[1])

Adding, Removing and Changing tuple items:

Items in tuples cannot be added, removed, changed or modified.

Tuple Length:

The len() function can be used to find the number of items in a tuple.

colorTuple = ("red","green","blue")
print(len(colorTuple))

Traversing through the items in a tuple:

This will print all the items in the tuple, one by one.

colorTuple = ("red","green","blue")
for x in colorTuple:
    print(x)

Checking if a tuple contains an item:

This following code will check if colorTuple contains green.

colorTuple = ("red","green","blue")
if "green" in colorTuple:
    print('The color green is present in the tuple.')

Python Strings

Strings are arrays of characters surrounded by quotation marks. Python allows both single and double quote to represent a string.

Creating a string variable:

In Python we can create a string variable just by assigning a string value to it. The following shows different ways to create a string variable.

x = "Hello Python, how are you?"
y = 'Python is fun to learn'

To create an empty string we simply write, z = ""

Accessing characters of a string:

Square brackets can be used with an index to fetch characters of a string. The index start from 0. The following code will print 'P'.

x = "Hello Python, how are you?"
print(x[6])

Getting a sub-string from a string:

To get a smaller sub-string from a longer string we use a range in square brackets. We need to specify the start and end index in the range. The sub-string is picked from the start index to one less than the end index. For example, if the range specified is 1 to 7, then the sub-string will be picked from index 1 to index 6 of the longer string.

The following code will print 'ello P' as index of 'e' is 1 and index of 'P' is 6, which is one less than 7.

x = "Hello Python, how are you?"
sub = x[1:7]

If no start index is specified, the sub-string will start from 0. The following code will print 'Hello P'.

x = "Hello Python, how are you?"
sub = x[:7]

Similarly, if no end index is specified, the sub-string will be picked from start index to last. The following code will print 'Python, how are you?'.

x = "Hello Python, how are you?"
sub = x[6:]

Finding string length:

We can use the len() function to find the length of a string. The following will print 26.

x = "Hello Python, how are you?"
print(len(x))

Trimming a string:

We can use the strip() method to remove the starting and ending spaces of a string. The following will print 'Hello there' removing the starting and ending spaces.

x = "    Hello there!   "
print(x.strip())

Converting a string to lower or upper case:

Using the lower() and upper() methods we can convert a string to lower and upper case.

This will print 'hello python'.

x = "Hello Python"
print(x.lower())

This will print 'HELLO PYTHON'.

x = "Hello Python"
print(x.upper())

Replacing a sub-string:

The replace() method is used to replace a sub-string with another. The following will print 'Hello Marathon'.

x = "Hello Python"
print(x.replace("Py", "Mara")

Splitting a string:

The split() method can be used to split a string into parts using a separator. The split() method returns a list of separated sub-strings. In the following example we are using comma(,) as the separator and it will print a list ['apple', 'mango', 'banana'].

x = "apple,mango,banana"
print(x.split(","))

Note: If no separator is passed to the function as an argument, it assumes space to be the separator, by default. The following code will split the string y into a list ['This', 'is', 'a', 'book'].

y = "This is a book"
print(y.split())

.

Membership Operators

Membership operators are used to check if an item exists in a sequence, such as strings, tuples, lists, dictionaries etc. The table below shows the two membership operators in Python.

+----------+--------------------------------+
|  in      |  if present in a sequence      |
|  not in  |  if not present in a sequence  |
+----------+--------------------------------+

The following examples show how membership operators work.

a = 5
b = 10
c = 'a'
d = 'x'
e = 'hi'
numList = [1, 2, 3, 4, 5]
line = "This is a book"

+--------------------+-----------+
|      Examples      |  Results  |
+--------------------+-----------+
|    a in numList    |   True    |
|    b in numList    |   False   |
|  7 not in numList  |   True    |
|  3 not in numList  |   False   |
|     c in line      |   True    |
|   d not in line    |   True    |
|    'y' in line     |   False   |
|     e in line      |   True    |
|   'his' in line    |   True    |
+--------------------+-----------+

.