MA336: Scientific Computing With R and Python
𝐋𝐞𝐜𝐭𝐮𝐫𝐞 − 𝟖
Input Statement
Accept more than one input in the same line
• Use input() function with for loop
• Syntax is
a, b = [ i for i in input(‘Enter two numbers : ’). split()]
• enter data using spaces
• [ ] represents a list / we can use () also
• data are strings
• a, b = [ i for i in input(‘ Enter two numbers : ’). split(‘ , ’)]
• enter data using comma
• a, b = [ int(i) for i in input(‘ Enter two numbers : ’). split()]
• data are integers
a, b = (i for i in input('Enter two numbers : '). split(','))
print('entered numbers are', a,b)
• eval() function takes a string and evaluates it
a, b = 2, 3
c = eval('a+b-5+a')
print(c)
• Enter an expression using keyboard
a = eval( input('enter expression : '))
print('result= %d' %a)
• we can use the combination of eval() and input() functions to accept
lists and tuples from the keyboard
a = eval(input('enter a list: '))
print('The entered list is', a)
• If we use [ ], eval() understands that it is a list
• If we use (), eval() understands that it is a tuple
a = eval(input('enter a list: '))
print('The entered list is', a)
a[0]=100
print(a)
Arrays
Array
• An array is an object that stores a group of elements or values of same
datatype
• Array can increase or decrease their size dynamically (i.e, we need not
declare the size of the array)
• when dealing with a huge number of elements, arrays use less memory
compared to lists and arrays offer faster execution than lists
• In Python, there is a standard module by the name array that helps us to
create and use arrays
Creating an array object
• Syntax is
arrayname = array(type code, [elements])
• a = array(‘i’, [2, 5, 7, 9])
b = array(‘u’, [‘a’, ‘b’, ‘c’])
Importing the Array module
• To create an array, we have to first import array module into our program
• There are three ways to import the array module
1. import array # import the entire array module
a = array.array(‘i’, [1, 2, 3, 4])
module name class name
2. import array as ar # array is imported with an alternate name ar
a = ar.array(‘i’, [1, 2, 3, 4])
3. from array import ∗ # import all classes, objects, variables etc. from array
module into our program
a = array(‘i’, [1, 2, 3, 4])
# creating an array
from array import*
a = array('i', [9, -8, 6, 5] )
print('Array elements are : ')
print(a)
for i in a :
print(i, end = ' ')
It is possible to create an array from another array
• a = array(‘i’, [1, 2, 3, 4, 5])
b = array(a.typecode, (x for x in a))
from array import*
a = array('i', [1, 2, 3, 4, 5])
b = array(a.typecode, (x for x in a))
for i in b :
print(i, end = ' ')
print()
c = array(a.typecode, (x for x in a[1:4]))
for i in c :
print(i, end = ' ')
from array import*
a=array('i',[1,2,3,4,5])
b=array(a.typecode,(x**2 for x in a[0:4]))
print(b)
for i in b :
print(i, end = ' ')
Indexing on Arrays
• An index represents the position number of an element in an array
• a = array(‘i’, [10, 20, 30, 40, 50])
10 20 30 40 50
a[0] a[1] a[2] a[3] a[4]
• len(a) returns the number of elements in the array a
from array import*
a = array('i', [10, 20, 30, 40, 50]) write this program
n = len(a) using while loop
for i in range(n):
print(a[i], end = ' ')
Slicing on Arrays
• A slice represents a piece of the array
• Indexing is useful to retrieve element by element from the array,
but slicing is useful to retrieve a range of elements
• The syntax is
arrayname[start : stop : stride]
• stride represents step size
0 1 2 3 4 5 6 7
10 20 30 40 50 60 70 80
-8 -7 -6 -5 -4 -3 -2 -1
from array import*
a = array('i', [10, 20, 30, 40, 50, 60, 70, 80])
print(a[1 : 6])
print(a[1 : ])
print(a[0 : 6 : 2])
print(a[-2])
print(a[-7 : ])
print(a[-7 : -2])
print(a[-7 : -1 : 2])
print(a[:2])
• slicing can be used to update an array
from array import*
a = array('i', [10, 20, 30, 40, 50, 60, 70, 80])
a[1 : 4] = array('i', [100, 200, 300])
print(a)
Processing the Arrays
• Methods are written inside a class,
whereas a function can be written inside or outside the class
• Methods are generally called as
object_name.method_name()
from array import*
a=array('i',[10,10,20,30,40,50,60,70,80])
a.append(90)
print(a)
print(a.count(10))
a.extend([100])
print(a)
a.extend([100,200])
print(a)
b=array('i', [3,4,5])
a.extend(b)
print(a)
l=[-1,0,1]
a.fromlist(l)
print(a)
from array import*
a=array('i',[40,10,5,20,30,5,40,50,60,70,80,10])
print(a.index(10))
a.insert(3,-20)
print(a)
a.pop()
print(a)
a.remove(5)
print(a)
a.reverse()
print(a)
b=a.tolist()
print(b)
from array import*
a=array('i',[40,10,5,20,30,5,40,50,60,70,80,10])
print(a)
x=a.pop(6) # returns the element in 6th location
print(a)
print(x)
#program to store student's marks and find total marks
from array import*
a=[int(i) for i in input('enter marks with spaces: ').split(' ')]
m=array('i',a)
sum=0
for i in m:
sum=sum+i
print('total= ',sum)
Sorting
The Basic Problem
• Given an array A[size]
reorder the entries such that
A[0] <= A[1] <= . . . <= A[size-1]
Selection Sort
Basic Idea
Input array A[n]
• First find the smallest element of A, and exchange it
with A[0]
• Find the second smallest of A, and exchange it with A[1]
• ……….
• Continue this till n-2 element of A
Algorithm
Input: A[n]
for i=0 to n-2
{ small=i
// find smallest in the sub array A[i]…A[n-1]
for j=i+1 to n-1
{ if(A[j]<A[small])
small=j
}
swap(A[i], A[small])
}
Insertion Sort
Basic Idea
• The insertion sort scans input array A[n]
from A[0] to A[n-1]
• It inserts each element A[k] into its proper position in
the previously sorted sub array A[0], A[1], …., A[k-1].
Algorithm
Input: A[n]
for j=1 to n-1
{ key=A[j]
// insert A[j] into the sorted sub array A[0]…A[j-1]
i=j-1
while (i>=0 and A[i]>key)
{ A[i+1]=A[i]
i=i-1
}
A[i+1]=key
}
Searching
Check if a given element (called key) occurs
in the array.
Example: array of student records;
rollno can be the key.
Two methods to be discussed:
• If the array elements are unsorted.
Linear search
• If the array elements are sorted.
Binary search
Linear Search
Basic idea:
• Start at the beginning of the array.
• Inspect elements one by one to see
if it matches the key.
Algorithm
Input: A[n], key
boolean=false
for i=0 to n-1
{ if (key=A[i])
{ pos=i+1
boolean=true
break
}
}
if(boolean)
key is found and its position is pos
else
key is not found
from array import*
a=[int(i) for i in input('enter elements with spaces: ').split(' ')]
m=array('i',a)
key=int(input('enter key: '))
try:
pos=m.index(key)
print('key found at position: ',pos+1)
except ValueError:
print('key not found')
# else suite with loops
n=int(input('enter number: '))
i=1
while i<=n:
if i==6:
break
print(i)
i=i+1
else: print("prime")
Lab Assignment (2-9-2023)
• Write a program to generate first n Fibonacci numbers
• Write a program to print the following pattern
∗ ∗ ∗ ∗ ∗
∗ ∗
∗ ∗
∗ ∗
∗ ∗ ∗ ∗ ∗
• Write a program to store student’s marks into an array and find
total marks and average
• Write a program to sort the array elements using insertion sort
• Write a program to sort the array elements using selection sort
• Write a program to search for the position of an element in an array
using linear search