Chapter 11: Dynamic Memory Allocation

Example 1, page no. 407

In [1]:
g = 50
def func(p):
    s = 200
    i = 10
    print i, s
a = 1
print a
print g
func(-16)
print "over!"
1
50
10 200
over!

Example 2, page no. 409

In [2]:
#there is no concept of malloc & free in Python

print "How many elements?: ",
n = int(raw_input())
ary = []
print "Enter the elements: "
for i in range(n):
    ary.append(int(raw_input()))
print "The entered array is: "
for ele in ary:
    print ele,
How many elements?: 3
 Enter the elements: 
1
2
3
The entered array is: 
1 2 3

Example 11.1, page no. 412

In [4]:
marks = []
size = 3
n = 0
print "Enter marks (-1 to stop: )"
mark = int(raw_input())
while mark != -1:
    if n >= size:
        print "realloc 3 more integers..."
        size += 3
    marks.append(mark)
    mark = int(raw_input())
    n += 1

for mark in marks:
    print mark,
Enter marks (-1 to stop: )
12
50
60
70
realloc 3 more integers...
80
90
100
realloc 3 more integers...
-1
12 50 60 70 80 90 100

Example 11.2, page no. 413

In [1]:
import numpy
n = int(raw_input("Rows: "))
m = int(raw_input("Columns: "))
mat = numpy.zeros((n, m))
print "Input the elements: "
for i in range(n):
    for j in range(m):
        mat[i][j] = int(raw_input())
print "Input two rows to swap: "
i = int(raw_input())
j = int(raw_input())
mat[i], mat[j] = mat[j], mat[i]
for i in range(n):
    for j in range(m):
        print mat[i][j],
    print ""
Rows: 3
Columns: 5
Input the elements: 
1
2
3
4
5
6
7
8
9
0
2
4
6
8
10
Input two rows to swap: 
0
2
2.0 4.0 6.0 8.0 10.0 
6.0 7.0 8.0 9.0 0.0 
2.0 4.0 6.0 8.0 10.0 

Example 11.3, page no. 415

In [15]:
def get(x, r, c):
    for i in range(r):
        for j in range(c):
            x[i][j] = int(raw_input())
    return x
def display(x, r, c):
    for i in range(r):
        for j in range(c):
            print x[i][j],
        print ""
def mul(a, b, c, row, m, col):
    for i in range(row):
        for j in range(col):
            c[i][j] = 0
            for k in range(m):
               c[i][j] = c[i][j] + a[i][k] * b[k][j]
    return c
a = numpy.zeros((30, 30))            
b = numpy.zeros((30, 30))            
c = numpy.zeros((30, 30))            
print "Size of matrix A: "
r1 = int(raw_input("row: "))
c1 = int(raw_input("col: "))
print "Size of matrix B: "
r2 = int(raw_input("row: "))
c2 = int(raw_input("col: "))
if c1 != r2:
    print "Multiplication not possible."
    print "columns of matrix A are not equal"
    print "to rows of Matrix B"
else:
    print "Multiplication possible"
    print "Matrix A(%d X %d) elements?" %(r1, c1)
    a = get(a, r1, c1)
    print "Matrix B(%d X %d) elements?" %(r2, c2)
    b = get(a, r1, c1)
    c = mul(a, b, c, r1, c1, c2)
    print "Product matrix C(%d X %d): " %(r1, c2)
    display (c, r1, c2)
Size of matrix A: 
row: 3
col: 4
Size of matrix B: 
row: 4
col: 3
Multiplication possible
Matrix A(3 X 4) elements?
1
2
3
4
5
6
7
8
9
10
11
12
Matrix B(4 X 3) elements?
1
2
3
4
5
6
7
8
9
10
11
12
Product matrix C(3 X 3): 
38.0 44.0 50.0 
98.0 116.0 134.0 
158.0 188.0 218.0 

Exmaple 11.4, page no. 419

In [ ]:
import sys

class node:
    def __init__(self, data=0, link=None):
        self.data = data
        self.link = link

start = None
    
def add_front(data):
    global start
    tmp = node(data)
    if(start == None):
        start = tmp
    else:
        tmp.link = start
        start = tmp

def del_pos(pos):
    global start
    if (pos == 0):
        tmp = start
        start = start.link
        return
    q = start
    count = 1
    while(q.link != None):
        if(count == pos):
            tmp = q.link
            q.link = tmp.link
            return
        count += 1
        q = q.link
    print "\n\nThere is no element at %d position" %pos
        
def del_elem(data):
    global start
    if (start.data == data):
        tmp = start
        start = start.link
        return
    q = start
    while(q.link.link != None):
        if(q.link.data == data):
            tmp = q.link
            q.link = tmp.link
            return
        q = q.link
    if(q.link.data == data):
        tmp = q.link;
        q.link = None
        return
    print "\n\nThere is no element whose value is %d" %data

def display_list():
    global start
    if(start == None):
        print "\n\nList empty"
        return
    q=start
    print "\nThe List is..."
    while(q != None):
        print q.data,
        q = q.link
    print "\n"

def get_data():
    data = int(raw_input("Enter the data: "))
    return data

while(1):
    print "\n1.Insert at the beginning of the list"
    print "2.Delete an element at a give position"
    print "3.Delete an element with a give value"
    print "4.Quit"
    print "Choice: ",
    choice =int(raw_input())
    if choice == 1:
        data = get_data()
        add_front(data)
    elif choice == 2:
        if (start == None):
            print "\nList empty"
            continue
        print "\n\nEnter the position:"
        pos = int(raw_input())
        del_pos(pos)
    elif choice == 3:
        if (start == None):
            print "\nList empty"
            continue
        data = get_data()
        del_elem(data)
    elif choice == 4:
        break
    display_list()
 
1.Insert at the beginning of the list
2.Delete an element at a give position
3.Delete an element with a give value
4.Quit
Choice: 1
Enter the data: 1
 
The List is...
1 


1.Insert at the beginning of the list
2.Delete an element at a give position
3.Delete an element with a give value
4.Quit
Choice: 1
Enter the data: 2
 
The List is...
2 1 


1.Insert at the beginning of the list
2.Delete an element at a give position
3.Delete an element with a give value
4.Quit
Choice: 1
Enter the data: 3
 
The List is...
3 2 1 


1.Insert at the beginning of the list
2.Delete an element at a give position
3.Delete an element with a give value
4.Quit
Choice: 2
 

Enter the position:
1

The List is...
3 1 


1.Insert at the beginning of the list
2.Delete an element at a give position
3.Delete an element with a give value
4.Quit
Choice: 1
Enter the data: 2
 
The List is...
2 3 1 


1.Insert at the beginning of the list
2.Delete an element at a give position
3.Delete an element with a give value
4.Quit
Choice: 1
Enter the data: 1
 
The List is...
1 2 3 1 


1.Insert at the beginning of the list
2.Delete an element at a give position
3.Delete an element with a give value
4.Quit
Choice: 1
Enter the data: 5
 
The List is...
5 1 2 3 1 


1.Insert at the beginning of the list
2.Delete an element at a give position
3.Delete an element with a give value
4.Quit
Choice: 2
 

Enter the position:
4

The List is...
5 1 2 3 


1.Insert at the beginning of the list
2.Delete an element at a give position
3.Delete an element with a give value
4.Quit
Choice: 

Example 11.5, page no. 424

In [4]:
def bubble(x, upbound):
    pas = upbound
    while pas >= 0:
        for i in range(pas):
            if x[i] > x[i+1]:
                x[i], x[i+1] = x[i+1], x[i]
        pas -= 1
    return x
vector = []
n = int(raw_input("Size of array? "))
for i in range(n):
    vector.append(int(raw_input()))
vector = bubble(vector, n-1)
print "Sorted array "
for ele in vector:
    print ele,
Size of array? 8
98
1
5
34
62
12
88
0
Sorted array 
0 1 5 12 34 62 88 98

Example 11.6, page no. 425

In [5]:
s1 = raw_input("Enter string one ")
s2 = raw_input("Enter string two ")
print "Concatenated string is: ", s1+s2
Enter string one Tejaswi
Enter string two .V.
Concatenated string is:  Tejaswi.V.

Example 11.7, page no. 425

In [6]:
def sort_strings(strarr):
    return sorted(strarr)

n = int(raw_input("Number of strings: "))
str_array = []
print "Enter the strings: "
for i in range(n):
    str_array.append(raw_input())

strarr = sort_strings(str_array)
print "The sorted array is"
for string in strarr:
    print string
Number of strings: 5
Enter the strings: 
Tejaswi
Anand
Rajkumar
Maya
Sudeep
The sorted array is
Anand
Maya
Rajkumar
Sudeep
Tejaswi

Example 11.8, page no. 427

In [16]:
import sys

class node:
    def __init__(self, data=0, link=None):
        self.data = data
        self.link = link

start = None
    
def add_front(data):
    global start
    tmp = node(data)
    if(start == None):
        start = tmp
    else:
        tmp.link = start
        start = tmp

def del_pos(pos):
    global start
    if (pos == 0):
        tmp = start
        start = start.link
        return
    q = start
    count = 1
    while(q.link != None):
        if(count == pos):
            tmp = q.link
            q.link = tmp.link
            return
        count += 1
        q = q.link
    print "\n\nThere is no element at %d position" %pos
        
def del_elem(data):
    global start
    if (start.data == data):
        tmp = start
        start = start.link
        return
    q = start
    while(q.link.link != None):
        if(q.link.data == data):
            tmp = q.link
            q.link = tmp.link
            return
        q = q.link
    if(q.link.data == data):
        tmp = q.link;
        q.link = None
        return
    print "\n\nThere is no element whose value is %d" %data

def display_list():
    global start
    if(start == None):
        print "\n\nList empty"
        return
    q=start
    print "\nThe List is..."
    while(q != None):
        print q.data,
        q = q.link
    print "\n"

def smallest():
    global start
    q = start
    min = q.data
    pos = 0
    min_pos = 0
    while(q != None):
        if q.data < min:
            min = q.data
            mis_pos = pos
        pos += 1
        q = q.link
    return min, min_pos+1

def largest():
    global start
    q = start
    max = q.data
    pos = 0
    max_pos = 0
    while(q != None):
        if q.data > max:
            max = q.data
            max_pos = pos
        pos += 1
        q = q.link
    return max, max_pos+1

def get_data():
    data = int(raw_input("Enter the data: "))
    return data

while(1):
    print "\n1.Insert at the beginning of the list"
    print "2.Delete an element at a give position"
    print "3.Delete an element with a give value"
    print "4.Find smallest in the list"
    print "5.Find largest in the list"
    print "6.Quit"
    print "Choice: ",
    choice =int(raw_input())
    if choice == 1:
        data = get_data()
        add_front(data)
    elif choice == 2:
        if (start == None):
            print "\nList empty"
            continue
        print "\n\nEnter the position:"
        pos = int(raw_input())
        del_pos(pos)
    elif choice == 3:
        if (start == None):
            print "\nList empty"
            continue
        data = get_data()
        del_elem(data)
    elif choice == 4:
        min, pos = smallest()
        print "The smallest element has value ", min
        print "Its position is ", pos
    elif choice == 5:
        max, pos = largest()
        print "The largest element has value ", max
        print "Its position is ", pos
    elif choice == 6:
        break
    display_list()
1.Insert at the beginning of the list
2.Delete an element at a give position
3.Delete an element with a give value
4.Find smallest in the list
5.Find largest in the list
6.Quit
Choice: 1
Enter the data: 56
 
The List is...
56 


1.Insert at the beginning of the list
2.Delete an element at a give position
3.Delete an element with a give value
4.Find smallest in the list
5.Find largest in the list
6.Quit
Choice: 1
Enter the data: 34
 
The List is...
34 56 


1.Insert at the beginning of the list
2.Delete an element at a give position
3.Delete an element with a give value
4.Find smallest in the list
5.Find largest in the list
6.Quit
Choice: 1
Enter the data: 45
 
The List is...
45 34 56 


1.Insert at the beginning of the list
2.Delete an element at a give position
3.Delete an element with a give value
4.Find smallest in the list
5.Find largest in the list
6.Quit
Choice: 4
 The smallest element has value  34
Its position is  1

The List is...
45 34 56 


1.Insert at the beginning of the list
2.Delete an element at a give position
3.Delete an element with a give value
4.Find smallest in the list
5.Find largest in the list
6.Quit
Choice: 5
 The largest element has value  56
Its position is  3

The List is...
45 34 56 


1.Insert at the beginning of the list
2.Delete an element at a give position
3.Delete an element with a give value
4.Find smallest in the list
5.Find largest in the list
6.Quit
Choice: 1
Enter the data: 3
 
The List is...
3 45 34 56 


1.Insert at the beginning of the list
2.Delete an element at a give position
3.Delete an element with a give value
4.Find smallest in the list
5.Find largest in the list
6.Quit
Choice: 1
Enter the data: 80
 
The List is...
80 3 45 34 56 


1.Insert at the beginning of the list
2.Delete an element at a give position
3.Delete an element with a give value
4.Find smallest in the list
5.Find largest in the list
6.Quit
Choice: 2
 

Enter the position:
9


There is no element at 9 position

The List is...
80 3 45 34 56 


1.Insert at the beginning of the list
2.Delete an element at a give position
3.Delete an element with a give value
4.Find smallest in the list
5.Find largest in the list
6.Quit
Choice: 2
 

Enter the position:
2

The List is...
80 3 34 56 


1.Insert at the beginning of the list
2.Delete an element at a give position
3.Delete an element with a give value
4.Find smallest in the list
5.Find largest in the list
6.Quit
Choice: 3
Enter the data: 80
 
The List is...
3 34 56 


1.Insert at the beginning of the list
2.Delete an element at a give position
3.Delete an element with a give value
4.Find smallest in the list
5.Find largest in the list
6.Quit
Choice: 6