0% found this document useful (0 votes)
19 views

!! Core Python !! Chapter - 7 !!

Python

Uploaded by

bhavikgelotar999
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
19 views

!! Core Python !! Chapter - 7 !!

Python

Uploaded by

bhavikgelotar999
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 56
© scanned with OKEN Scanner 152 |Chapter7 @ Arrays can increase or decrease their size dynamically. It means, we Neeq the size of the array. When the elements are added, it will increase o y its size gr “tare the elements are removed, it will automatically decrease its size in memory, "4 Whey In Python, there is a standard module by the name ‘array’ that help: 8 US to creat arrays, To get help on ‘array’ module, we can type help() at Python prompt ys a a Use prompt as: © help >>>helpO help> Then we should type simply ‘array’ at the help prompt to sce all information oboe array module as shown in Figure 7.1: the helps array Help on built-in module array: NAME, array DESCRIPTION efficiently represent : characters, integers, floating point sequence types and behave very mich like lists type of objects stored in them is constrained. builtins object. array ArrayType = class array (builtins object) array (typecode [, initializer]) -> array Return a new array whose items are initialized from the o 1 1 1 estricted by typecode, and 1 | string or iterable ove: 1 1 1 1 ptional initializer value, which must be a list, e elements of the appropriate type Arrays represent basic values and behave very much like lists, except the type of objects stored in them is constrained. The type is specified at object creation tine by using a type code, which is a single sharectar Figure 7.1: Getting Help on Array Module Advantages of Arrays The following are some advantages of arrays: Q Arrays are similar to lists. The main differe: of elements; whereas, lists can store di huge number of « execution than lists. nce is that arrays can store only one {YP ifferent types of elements. When dealin ‘a jents, arrays use less memory than lists and they offer fa5% Q The size of the array is not fixed in ow many thon. Hence, we need not specify elements we are going to store into an ai ray in the beginning. © scanned with OKEN Scanner © scanned with OKEN Scanner © scanned with OKEN Scanner © scanned with OKEN Scanner 156 | Chapter 7 It is possible to create an array from another array. For example, there is an array ‘ary, as: arrl = array('d', (1.5, 2.5, -3.5, 41) This is a float type array with 4 elements. We want to create another array with the name ‘arr2’ from arrl, It means, ‘arr2’ should have same type code and same elements as that of ‘arrl’. For this purpose, we can write: arr2 = array(arrl.typecode, (a for a in arr1)) Here, ‘arrl.typecode’ gives the type code character of the array ‘arrl’. This type code ig used for ‘arr2’ array also. Observe the expression: a for a in arri The first ‘a’ represents that its value is stored as elements in the array ‘arr2’. This value is got from ‘a’ (each element) in arr. So, all the elements in arr will be stored into arr2. Suppose, we write the expression, arr2 = array(arrl.typecode, (a*3 for a in arrl)) In this case, the value of ‘a’ obtained from arrl, is multiplied by 3 and then stored as element into arr2. So, arr2 will get the elements: 4.5, 7-5, -10.5, and 12.0. This can be verified from Program 4. Program 4: A Python program to create one array from another array. # creating one array from another array from array import * arrl = array("d', [1.5, 2.5, -3-5, 4]) # use same type code and multiply each element of arrl with 3 arr2 + array(arrl.typecode, (a*3 for a in arrl)) print(‘The arr2 elements are: ' for i in arr2: printGi) Output: C:\>python_arr.py The arr2 elements are: : 4.5 = 7.5 -10.5 12.0 Indexing and Slicing on Arrays An index represents the position number of an element-in an array. For example, when we create the following integer type array: x = array("i", [10, 20, 30, 40, 50]) . 1 © scanned with OKEN Scanner © scanned with OKEN Scanner © scanned with OKEN Scanner © scanned with OKEN Scanner Chapter 7 Processing the Arrays Fe aanch cart can pation ete should understand that a method is similar to a func But methods are written inside a class whereas a outside the class. Methods are generally called as: obj 7.2 for methods that can be used on arrays: Table 7.2: Array Methods [Matnod Descrption oa | a.append(x) a.count(x) Returns the numbers of occurrences of a.extend(x) Appends x at the end of the am : another array iterable object. oe : a xin the array a, a.fromfile(f, n) and appends to the EOFError’ if fewer a.fromlist(Ist) Appends items from the Ist to the end of the array » Ist” iterable object. po afromstring(s) | Appends items from String s to the end of the array a. a.index(x) Returns the position number of the first Occurrence of x in the anay, Raises ‘ValueError’ if not found. a.insert(i, x) Inserts x in the position i in the array a.pop(x) Removes the item x from the array a and returns it. a.pop() Remove last item from the array a, a.remove(x) Rethoves the Stet occurence of x in the aay a Rael SU z not found. a.reverse() Reverses the order of elemenis in the array a. | a.tofile(f) _| Writes all elements to the file f. é a.tolist() Converts the array ‘a’ into a list. a.tostring() Converts the array into a string, J © scanned with OKEN Scanner © scanned with OKEN Scanner Output: c:\>python arr.py Ar Original arvayi jarray(ei after appending 30 a 2’ arrayC’ After inserting 99 in Ist position: 50, 30, 60] {10,20 301926) 30 40, 50 efeaa: arrayc'i", £16, 98, °26,°%9, 90 601),5. anray('i, (10, 99, 30, 40, 50, 30, 60) Rn SE pop): arrayC'i!, (10, $9, 30, 40, $0, 303) Popped element: 60 eee First occurrence,of element 30,19 at: 2 List: [10, 99, 30, 40, 50, array: oe chien (10, 99, 30, 40, 50, 30]) Let’s write a program to accept marks of a student and find the total marks ang percentage of marks. This is done in Program 10. In this program, we first use inputg function to accept marks into a string ‘str’ as: “str = inputC'enter marks: ').split(' ') When this statement is executed, the user should type marks separating them by a space as indicated by split(‘) method. These marks are stored into the string ‘str’. Then we should convert this string into an array as: marks = [int(num) for num in str] Here, ‘marks’ is the name of the array. Observe the for loop at right hand side. It takes each number from ‘str’ and stores it into ‘num’. The ‘num’ value is converted into ‘nt’ using int(num). This integer number is then stored into ‘marks’ array. To represent that ‘marks’ is an array, we used square brackets for the expression at right side. These brackets store the numbers as a list into ‘marks’ array. To find total marks, we can use another for loop as: for x in marks: printGo sumt=x This for loop is doing two things. It is printing %’ value that represents each element of the ‘marks’ array and then adding that %’ value to sum. So, finally, ‘sum’ represents the total marks of the student. To find percentage, we divide the ‘sum’ using number of element as: percent = sum/n Here, ‘n’ represents the number of elements in the ‘marks’ array which can be obtained by calling the len() function as len(marks). Program 1 Python program to storing student’s marks into an array and finding total marks and percentage of marks, pion array pears me re accept marks from keyboard into a lis Ist= Tint() for 1 in’inputC'enter marks: *).splie¢',")] © scanned with OKEN Scanner © scanned with OKEN Scanner 164 | Chapter 7 re shown in Figure 7.3 by taking ‘These steps 4! e will be 2 and ‘b’ value will be 1. swapping is done, ‘a’ valu value 1 and ‘b’ value a=b Figure 7.3: Swapping a and b Values using a Temporary Variable t Program 1 # sorting an array using Bubble sort technique from array import : # create an empty array to store integers xs arrayci’, ED # store elements into the array x PrintC'How many elements? ; end= f= intGinputQ) # accept input into n for i in range(n): # repeat for n times print('enter element: ', end=" 2 initiany her : A Python program to sort the array elements using bubble sort technique X.append(int(input())) # add he elewencara the array x print(‘original array: ', x) # bubble sort flag = False # when swapping is done, flag becomes True for i in range(n-1): #1 is from 0 to n-1 for jin range(n-1-i) aad ‘is from 0 to one element lesser than 1 i Vf x(j] > xfj+1): t= xt) # swap j and j+l element xq xii 2 . Ist element is bigger than the 2nd one xGH = : ag = True # swapping done, hence flag is True At: aoe ee # no swapping means array is fn sorted order break “# come out of inner for loop else: flag = False # assign initial value to flag print('Sorted array= ', x) Output: €:\>python arr. py How many elements? 5 -_| © scanned with OKEN Scanner © scanned with OKEN Scanner © scanned with OKEN Scanner © scanned with OKEN Scanner 168 | Chapter 7 pach row of the above array can be again represented as a sin, Thus the above array contains 3 single dimensional arrays, 11 dimensional array. A two dimensional array is a combin, dimensional arrays. Similarly, a three dimensional array is gle dimen, lence, it ig ation of 56 sional ay, called 4 a vera) 2% a comi Si two dimensional arrays. ination of = In Python, we can create and work with single dimensional arrays on) examples and methods discussed by us are applicable to single ding; S° far Python does not support multi-dimensional arrays. But that is not 4 Won!" a bad new. Tas, construct multidimensional arrays using third party packages lik EWS. We ce nui an python). The following sections are devoted for a discussion on ‘numyy 2d, Meta, important for Python programmers. PY’ Which is very Working with Arrays using numpy numpy is a package that contains several classes, functions, variables etc, scientific calculations in Python. numpy is useful to create and also proces multi-dimensional arrays. In addition, numpy contains a large library of mathema functions like linear algebra functions and Fourier transforms. To get complete heiy s numpy, the reader can refer to the following link at aaa http:/ /docs.scipy.org/doc/numpy/reference/ a to deal with S single ang The arrays which are created using numpy are called n dimensional arrays where n can be any integer. If n=1, it represents a one dimensional array. If n=2, it is a two dimensional array. Similarly, if n-3, it is a three dimensional array. The arrays created in numpy can accept only one type of elements. We cannot store different datatypes into same array. To work with numpy, we should first import numpy module into our Python programs as: ‘import numpy ‘This will import numpy module into our program so that we can use arly of the objects from that package. But, to refer to an object we should use the format: numpy.object. See the Program 14 to know how to create an array in numpy. Program 14: A Python program to create a simple array using numpy. # creating single dimensional array using numpy import numpy arr = numpy.array({10, 20, 30, 40, 50]) # create array print(arr) # display array Output: ® ¢:\>python arr. ~—$202P80°309 "40, ”501 © scanned with OKEN Scanner © scanned with OKEN Scanner 170 | Chapter 7 Creating Arrays using array() numpy module to create an array. When we create array() function of : | arn SY nts either as ‘int’ or ‘float’. We ¢, ‘aN create array, we can specify the datatype of the eleme an integer type array as arr = array((10, We can also eliminate ‘int’ in the above statemen' of elements. 20, 30; 40, 50], int) t since Python can assess the datatype s To create an array with float type elements, we should specify ‘float’ as: arr = array((1.5, 2.5, 3, 4+ -5.1], float) The same statement can be rewritten by eliminating float’ as Python can judge tha datatypes of the elements. In the array, if Python interpreter finds one element belongi to ‘float type’, then it will convert all the other elements also into float type by adding q decimal point after the element as: arr = array([10, 20, 30.1, 401) If we display this array using print() function, we can see the array as: [10., 20., 30.1, 40.) To create an array with character type elements, we need not specify the datatype. We can simply write: anneiarray¢atsaibaetyatd')) a Program 17: A Python program to create a character type array with a group of characters. # creating an array with characters from numpy import, * arr = array(['a’,'b','c','d’]) # create array print(arr) # display array Output: c: the os Sera To create a string type array where can store a group of strings, we should use additional attribute ‘dtype = str’ in the array() function as: arr = array(['Delhi', ‘Hyderabad’, 'mumbai', ‘ahmedabad’, dtype=str) Alternately, we can omit the ‘dtype=str’ in the above statement and write it as: arr = array(["Delhi', ‘Hyderabad', ‘mumbai’, 'ahmedabad"]) © scanned with OKEN Scanner Arrays in Python f "8: A Python program to create a string type arr ith charact eating an array Wi ers stay ane - e eis # creatrray({'pelhi', ‘Hyderabad’, ‘mumbai at Gare) # display’ array : ? je to create an array from other arrays, as shown in Program 19. ‘ay using numpy. ‘ahmedabad'], dtype=str) ~ possi ni * WEL creating an array from another array on numpy import ae SE CESS Dt ote ary = array (a. eb from a usin ‘ = arr create © by assigning a toe 1 aYO. function 4 display the arrays int("a = V5 a, peinehe =! creating Arrays using linspace The linspace() function is used to create an array with evenly spaced points between a sarting point and ending point. The form of the linspace() function is: linspace(start, stop, n) ‘sar!’ represents the starting element and ‘stop’ represents the ending element. ‘n’ is an integer that represents the number of parts the elements should be divided. If ‘n’ is omitted, then it is taken as 50. Let’s take one example to understand this. a= linspace(O, 10, 5) Inthe above statement, we are creating an array ‘a’ with starting element 0 and ending ement 10. This range is divided into 5 equal parts and hence the points will be 0, 2.5, 5, "Sand 10. These elements are stored into ‘a’. Please remember the staring and elements and 10 are included Program 20 shows how to create an array with 5 equal points “sing the linspace() function. © scanned with OKEN Scanner 172 | Chapter 7 Program 20: A Python program to creat # creating an array using TinspaceQ From numpy import # divide 0 to 10 into 5 a = linspace(O, 10, 5) ing an array with 5 equal points using linspacey parts and take those points in the array print('a=', @ Output: 2 hi _ EO Creating Arrays using logspace The logspace() function is similar to linspace(). The linspace() function produces the evenly spaced points. Similarly, logspace() produces evenly spaced points on a logarithmically spaced scale. The logspace() function is used in the following format: Jogspace(start, stop, n) The logspace() function starts at a value which is 10 to the power of ‘start’ and ends at a value which is 10 to the power of ‘stop’ . If ‘n’ is not specified, then its value is taken as 50. For example, if we write: a = logspace(1, 4, 5) ‘This function represents values starting from 10! to 10. These values are divided into 5 equal points and those points are stored into the array ‘a’. This can be seen in sample Program 21. Program 2: # creating an array using logspaceQ from numpy import * # divide the range: 10 power 1 to 10 power 4 into 5 equal parts # and take those points in the array a = logspace(1, 4, 5) Python program to create an array using logspace() # find no. of elements in a n = len(a) # repeat from 0 to n-1 times for i in range(n): print('%.1f' % ali], end=' ') # display 1 digit after decimal point Output: c:\spython acr-py 10.0 56.2 316.2 1778.3 1000.0 © scanned with OKEN Scanner creating Arrays using arange() Function arange() function in numpy is sam, fpectioe is used in the following format. arange(start, stop, stepsize) © 8 Tange() function in Python. The arange() qhis creates an array with a group of elements from ‘ sieps of ‘stepsize” If the ‘stepsize’ is omitted, then it pen it is taken as 0. For example, arange(10) Start’ to one element prior to ‘stop’ in is taken as 1. If the ‘start’ is omitted, will produce an array with elements 0 to 9, arange(5, 10) will produce an array with elements from 5 to 9. arange(1, 10, 3) will create an array with the elements startin Since the stepsize is 3, we should 3 to get the subsequent elements. Thus, the second element can be obtained as 1+3 = 4 and the third element can be obtained as 4+3 = 7 and so on. Hence, the array will contain the following elements: [1 4 7] arange(10, 1, -1) ig from 1 to 9. So, the first element will be 1. Since the stepsize is -1, it represents the elements in descending order from 10 to 2, as: 09876543 2), ‘The following example creates a float type array with stepsize 1.5: arange(O, 10, 1.5) In this case, the array elements will be: (0. 1.5 3. 4.5 6. 7.5 9. ]. We will now write a Python program to create an array with even numbers up to 10. In this program, we will use the arange() function as: a= arange(2, 11, 2) the starting even number is 2 and everytime we are adding 2 (stepsize) to get the next even number. This will continue till 10 (one element prior to 11). Program 22: A Python program to create an array with even number up to 10. # creating an array with even numbers up to 10 from numpy import * # create an array using arange() function a = arange(2, 11, 2) print(a) Output: Peers EB > © scanned with OKEN Scanner

You might also like