0% found this document useful (0 votes)
27 views32 pages

Unit 4

Uploaded by

jeyasuriyaa16
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views32 pages

Unit 4

Uploaded by

jeyasuriyaa16
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

UNIT IV LISTS, TUPLES, DICTIONARIES

Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and
methods; advanced list processing – list comprehension; Illustrative programs: simple sorting,
histogram, Students marks statement, Retail bill preparation.

4.1 Lists:
The list is a most versatile data type available in Python which can be written as a list of
comma- separated values (items) between square brackets.
Like a string, a list is a sequence of data values of any type (int, float, str etc.,).
The values in a list are called elements or sometimes items.
There are several ways to create a new list; the simplest is to enclose the elements in
square brackets ([ ]):

Examples:
[12, 14, 35, 48] #list with integer
['crunchy frog', 'ram bladder', 'lark vomit'] #list with strings

It can have any number of items and they may be of different types (integer, float, string
etc.). my_list = [ ] # empty list
my_list = [1, 2, 3] # list of integers
my_list = [1, "Hello", 3.4] # list with mixed datatypes
Also, a list can even have another list as an item. This is called nested list.
my_list = ["mouse", [8, 4, 6]] # nested list

Accessing elements in a list


>>> first_year=["English","Maths","Physics","Chemistry","Python","Engineering Graphics"]
>>>first_year[0
] 'English'

>>>first_year[3
] 'Chemistry'

Index 0 1 2 3 4 5
String English Maths Physics Chemistry Python ngineering Graphi

>>> first_year=["English","Maths","Physics","Chemistry","Python","Engineering Graphics"]


>>>first_year[0][5]

Index 0 1 2 3 4 5 6
String E N g l i s h

O/P:
's'

Nested Indexing (List within a list is called as nested list)


Nested list are list objects, where the elements in the lists can be lists themselves.
It is possible to access a nested list by using nested indexing.
Ex:
# Nested List
list2 = ["Python", [2,4,6,8]]
print(list2[0][1]) # Output: y
print(list2[1][3]) # Output: 8

Negative Indexing
Python supports negative indexing for sequence types like lists.
The last item on the list takes the -1 index, the second to the last item has the -2 index, and so on.
Index 0 1 2 3 4 5
String P y t h o n
Negative Index -6 -5 -4 -3 -2 -1

Ex:
>>>my_list=["p","y","t","h","o","n"]
>>>my_list[-1]
'n'
>>>my_list[-3]
'h'
>>>my_list[-4]
't'
Assigning list values to variables
As you might expect, you can assign list values to variables:
Example:
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> numbers = [42, 123]
>>> empty = [ ]
>>>print(cheeses, numbers, empty)
['Cheddar', 'Edam', 'Gouda'] [42, 123] []

The in operator also works on lists.


>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False
4.1.1 List operations
The + operator concatenates lists:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> c
[1, 2, 3, 4, 5, 6]

The * operator repeats a list a given number of times:


>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

4.1.2 List slices


​ The values stored in the list can be accessed using slicing operator, the colon(:) with indexes
starting at 0 in the beginning of the list and ending with -1.
​ It is used to access a range of elements on a list.

Syntax:
list_name[start : finish-1]
start indicates the index of the initial number (start value)
finish indicates the index of the ending character (stop value)

Example 1
list1 =['P','Y','T','H','O','N']
print(list1[0])
print(list1[2])
print(list1[4])
print(list1[-1])
print(list1[-3])
print(list1[ :5])
print(list1[2:5])

OUTPUT
P
T
O
N
H
PYTHO
THO
Since lists are mutable, it is often useful to make a copy before performing operations that modify lists.

Updating List:
A slice operator on the left side of an assignment can update multiple elements:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>>t[1:3] = ['x', 'y']
>>> t
['a', 'x', 'y', 'd', 'e', 'f']
4.1.3 List methods
Python provides methods that operate on lists. They are as follows.

Python List Methods


append() - Add an element to the end of the list
extend() - Add all elements of a list to the another list
insert() - Insert an item at the defined index
remove() - Removes an item from the list
pop() - Removes and returns an element at the given index
clear() - Removes all items from the list
index() - Returns the index of the first matched item
count() - Returns the count of number of items passed as an argument
sort() - Sort items in a list in ascending order
reverse() - Reverse the order of items in the list
copy() - Returns a shallow copy of the list
Example program for List methods:
my_list=[10, 20, 30, 40, 50]
n=len(my_list)
print("No of elements in the
list:",n) print("original
list:",my_list) my_list.insert(0,5)
print("After insert 5:",my_list)
my_list.append(60)
print("After appending 60:",my_list)
my_list1=my_list.copy()
print("After copying my_list1:",my_list1)
my_list.extend(my_list1)
print("After extending my_list and my_list1:",my_list)
n=my_list.count(10)
print("No of times item 10 found in the list:",n)
my_list.remove(10)
print("After removing 10 from the list:",my_list)
my_list.pop()
print("After poping the list:",my_list)
my_list.sort()
print("After sorting the list:",my_list)
my_list.reverse()
print("After reversing the list:",my_list)
my_list.clear()
print("After clearing the list:",my_list)
Output:
No of elements in the list: 5
original list: [10, 20, 30, 40, 50]
After insert 5: [5, 10, 20, 30, 40, 50]
After appending 60: [5, 10, 20, 30, 40, 50, 60]
After copying my_list1: [5, 10, 20, 30, 40, 50, 60]
After extending my_list and my_list1: [5, 10, 20, 30, 40, 50, 60, 5, 10, 20, 30, 40, 50, 60]
No of times item 10 found in the list: 2
After removing 10 from the list: [5, 20, 30, 40, 50, 60, 5, 10, 20, 30, 40, 50, 60]
After poping the list: [5, 20, 30, 40, 50, 60, 5, 10, 20, 30, 40, 50]
After sorting the list: [5, 5, 10, 20, 20, 30, 30, 40, 40, 50, 50, 60]
After reversing the list: [60, 50, 50, 40, 40, 30, 30, 20, 20, 10, 5, 5]
After clearing the list: []

Using built functions with List


Python’s built-in functions such as len(), max(), min(),sum(), sorted() can be used to accomplish
various tasks.
len()
The len() function returns the number of items on a list
Example:
>>>my_list=[0,5,10,15,20,25]
>>>len(my_list)
6
max()
max() function returns item with maximum value from the list
Example
>>>my_list=[0,5,10,15,20,25]
>>> max(my_list)
25
min()
Min() function returns item with minimum value from the list.
Example
>>>my_list=[0,5,10,15,20,25]
>>> min(my_list)
0
sum()
The sum() function returns the sum of all items in a list.
Example
>>>my_list=[1,5,11,2,3]
>>> sum(my_list)
22
sorted()
The sorted() function returns a sorted list in ascending order.
Example
>>>my_list=[1,5,11,2,3]
>>> sorted(my_list)
[1, 2, 3, 5, 11]

4.1.4 Traversing a list


​ It means looping a list in python.
List loop
​ Using for loop we can iterate though each item in a list.
Example 1: (using for loop)
for fruit in ['apple','banana','mango']:
print("I like",fruit)
OUTPUT
I like apple
I like banana
I like mango

Example 2: (using for loop)


colors = ["red", "green", "blue", "purple"]
for i in range(len(colors)):
print(colors[i])
OUTPUT
red
green
blue
purple

Example 3: Finding maximum element in the list (using for loop)---Lab exercise
n=int(input("Enter the limit"))
list=[]
print("Enter list elements one by
one") for i in range(0,n):
x=int(input())
list.append(x)
print("The list elements are")
print(list)
large=list[0]
for i in range(1,n):
if(list[i]>large):
large=list[i]
print("The largest element in the list is", large)

OUTPUT:
Enter the limit 5
Enter list elements one by
one 10
20
30
100
40
The list elements are
[10, 20, 30, 100, 40]
The largest element in the list is 100

Example 4: Printing items from the list (Using while loop)


colors = ["red", "green", "blue",
"purple"] i = 0
while i<len(colors):
print(colors[i])
i += 1
OUTPUT
red
green
blue
purple

4.1.5 Mutabilit
y Lists are
mutable
​ Some of these objects like lists and dictionaries are mutable, meaning you can change their content
without changing their identity.
​ Other objects like integers, floats, strings and tuples are objects that cannot be changed.
Note:
Mutable means changeable
Example:
odd = [2, 4, 6, 8]
odd[0] = 1
print(odd)
# Output: [1, 4, 6, 8]
4.1.6 Aliasing
​ When more than one variables refers to the same objects or list, then it is called
aliasing. a= [5,10,50,100]
b=a
b[0] = 80
print ("original list",a) = [5,10,50,100]
print ("Aliasing list",b) = [80,5,10,50,100]
​ Here both a & b refers to the same list. Thus, any change made with one object will affect other, since
they are mutable objects.
​ In general, it is safer to avoid aliasing when we are working with mutable objects

4.1.7 Cloning Lists

​ Cloning creates a new list with same values under another name.

​ Taking any slice of list create new list.

​ Any change made with one object will not affect others.

​ the easiest way to clone a new list is to use "slice operators"


a = [5,10,50,100]
b= a[ : ]
b[0] = 80
print (" original list", a) = [5,10,50,100]
print (" cloning list", b) = [5,10,50,100]

4.1.8 List Parameters

​ List can be passed as arguments to functions the list arguments are always passed by reference only.

​ Hence, if the functions modifies the list the caller also


changes. Eg: def head (t):
del t[ 0 ]
letters = ['a','b','c']
head(letters)
print(letters)
['b','c']
​ In above, The parameters 't' and the variable 'letters' or aliases for the same objects.

​ An alternative way to write a function that creates and return a new


list Eq: def tail (t):
return t [1:]
letters = ['a','b','c']
result = tail (letters)
print(result )
['b','c']
​ In above, The function leaves the original list unmodified and return all element in list except
first element.

4.2 Tuples
​ A tuple is a sequence of values.

​ The values can be any type, and they are indexed by integers, so in that respect tuples are a lot like
lists.
​ The important difference is that tuples are immutable.

Note:
​ Immutable means not changeable.

​ Syntactically, a tuple is a comma-separated list of values:


>>> t = 'a', 'b', 'c', 'd', 'e'
​ Although it is not necessary, it is common to enclose tuples in parentheses:
>>> t = ('a', 'b', 'c', 'd', 'e')
​ To create a tuple with a single element, you have to include a final comma:
>>> t1 = 'a',
>>> type(t1)
<class 'tuple'>
​ A value in parentheses is not a tuple:
>>> t2 = ('a')
>>> type(t2)
<class 'str'>
​Another way to create a tuple is the built-in function tuple. With no argument, it creates an
empty tuple:
>>> t = tuple()
>>> t
()
​ If the argument is a sequence (string, list or tuple), the result is a tuple with the elements of the
sequence:
>>> t = tuple('lupins')
>>> t
('l', 'u', 'p', 'i', 'n', 's')
Because tuple is the name of a built-in function, you should avoid using it as a variable name.
Accessing tuple items:
Most list operators also work on tuples. The bracket operator indexes an element:
Index# 0 1 2 3 4
String a b c d e
>>> t = ('a', 'b', 'c', 'd', 'e')
>>>t[2]
'c'
And the slice operator selects a range of elements.
Index 0 1 2 3 4
String a b c d e
Negative Index -5 -4 -3 -2 -1
>>> t[1:3]
('b', 'c')
But if you try to modify one of the elements of the tuple, you get an error:
>>>t[0] = 'A'
TypeError: object doesn't support item assignment
Because tuples are immutable, you can’t modify the elements. But you can replace one tuple with
another:
>>> t = ('A') + t[1:]
>>> t
('A', 'b', 'c', 'd', 'e')
This statement makes a new tuple and then makes t refer to it.
​ The relational operators work with tuples and other sequences;

​ Python starts by comparing the first element from each sequence.

​ If they are equal, it goes on to the next elements, and so on, until it finds elements that differ.

​ Subsequent elements are not considered (even if they are big).


>>> (0, 1, 2) < (0, 3, 4)
True
Example 4
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
Output: ("mouse", [8, 4, 6], (1, 2, 3))

Example 5
# tuple can be created without parentheses
# also called tuple packing
my_tuple = 3, 4.6, "dog"
print(my_tuple)
# Output: 3, 4.6, "dog"

Example 6
# tuple unpacking is also possible
my_tuple = 3, 4.6, "dog"
a, b, c = my_tuple
print(a)
print(b)
print(c)
Output
:
#3
# 4.6
# dog
Note:
Tuple is immutable(not changeable)
We can modify the nested items within the list element

Replacing a tuple
To replace the item on index 2 of the list which is on index 3 of my_tuple.
>>>my_tuple=('a',5,4.5,['p','y','t','h','o','n'])
>>>my_tuple[3][2]='x'
>>>my_tuple
o/p:
('a', 5, 4.5, ['p', 'y', 'x', 'h', 'o', 'n'])

Reassigning a tuple
To reassign a tuple, list a different of elements and assign it to the tuple.
>>>my_tuple=('c','o','d','e','r')
>>>my_tuple
o/p:
('c', 'o', 'd', 'e', 'r')
Deleting a tuple
The keyword del is used to delete a tuple and all its items.
Syntax
del tuple_name

Example
del my_tuple

Tuple membership test


To test if a tuple contains a specific item, you can use the membership operators ‘in’ and ‘not in’.
>>> tuple_1=('c','o','m','p','u','t','e','r')
>>> 'm' in tuple_1
True
>>> 'r' in tuple_1
True
>>> 'a' in tuple_1
False
>>> 'p' not in tuple_1
False

Tuple Methods
In python count() and index() are the two methods that work with tuples.

1. Count(x)
The count() returns the number of elements in the tuple.
Syntax:
mytuple.count(‘character’)
Example
>>>new_tuple=("p","r","o","g","r","a","m","m","e","r")
>>>new_tuple.count('m')
2
>>>new_tuple.count('r')
3
2. Index(x)
It returns the index of the first element which is equal to the given element.
Syntax:
Mytuple.index(‘character’)
Example
>>>new_tuple=("p","r","o","g","r","a","m","m","e","r")
>>>new_tuple.index('m')
6
>>>new_tuple.index('r')
1
Built in functions with tuples
Several built in functions are often used with tuple to carry out specific task.
1. len()
It returns the number of elements in a tuple
Example
>>>new_tuple=("p","r","o","g","r","a","m","m","e","r")
>>>len(new_tuple)
10
2. max()
It returns the largest element in a tuple
Example
>>> tuple1=(2,5,6,11,4,5)
>>> max(tuple1)
11
3. min()
It returns the smallest element in a tuple
Example
>>> tuple1=(2,5,6,11,4,5)

>>> min(tuple1)
2
4. sorted()
It returns a sorted list but it does not sort tuple itself. The order of elements inside the tuple remains
unchanged.
Example
>>> tuple1=(2,5,6,11,4,5)

>>> sorted(tuple1)
[2, 4, 5, 5, 6, 11]
5. sum()
It returns the total of all the items in a tuple
Example
>>> tuple1=(2,5,6,11,4,5)

>>>
sum(tuple1) 33
​ A dictionary is like a list, but more general.

​ In a list, the indices have to be integers; in a dictionary they can be (almost) any type.

​ A dictionary contains a collection of indices, which are called keys, and a collection of values.

​ Each key is associated with a single value. The association of a key and a value is called a key-value
pair or sometimes an item.
​ 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.

Example 1: (Accessing elements in a dictionary)


>>>my_dict={'Name':'Sita','Age':25,'Ranking':'5th','Average':89.5}
>>>my_dict['Name'
] 'Sita'
>>>my_dict['Average']
89.5

Example 2: (Accessing values with the get() method)


>>>my_dict={'Name':'Sita','Age':25,'Ranking':'5th','Average':89.5}

>>>my_dict.get('Name')
'Sita'
>>>my_dict.get('Average')
89.5

Example 3: (Adding entries in a dictionary)


>>>my_dict={'Name':'Sita','Age':25,'Ranking':'5th','Average':89.5}

>>>my_dict['result']='pass'

>>>my_dict# to check the updated dictionary


{'Average': 89.5, 'Ranking': '5th', 'result': 'pass', 'Name': 'Sita', 'Age': 25}

Example 4: (Modifying entries in a dictionary)


>>>my_dict={'Name':'Sita','Age':25,'Ranking':'5th','Average':89.5}

>>>my_dict['Ranking']='1st'

>>>my_dict# to check the updated dictionary


{'Average': 89.5, 'Ranking': '1st', 'result': 'pass', 'Name': 'Sita', 'Age': 25}

4.3.1 Operations and Methods


​ The function dict() creates a new dictionary with no items.

​ Because dict() is the name of a built-in function, you should avoid using it as a variable name.
>>> a = dict()
>>> a
{}
​ The squiggly-brackets, {}, represent an empty dictionary.

​ To add items to the dictionary, you can use square brackets:


>>> a['one'] = 'uno'
​ This line creates an item that maps from the key 'one' to the value 'uno'.

​ If we print the dictionary again, we see a key-value pair with a colon between the key and value:
>>> a
{'one': 'uno'}
​ This output format is also an input format.
For example, you can create a new dictionary with three items:
>>> a = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
But if you print a, you might be surprised:
>>> a
{'one': 'uno', 'three': 'tres', 'two': 'dos'}
​ The order of the key-value pairs might not be the same.

​ If you type the same example on your computer, you might get a different result.

​ In general, the order of items in a dictionary is unpredictable.

​ But that’s not a problem because the elements of a dictionary are never indexed with integer indices.

​ Instead, you use the keys to look up the corresponding values:


>>> a['two']
'dos'
​ The key 'two' always maps to the value 'dos' so the order of the items doesn’t matter.

​ If the key isn’t in the dictionary, you get an exception:


>>> a['four']
KeyError: 'four'

The len() function works on dictionaries; it returns the number of key-value pairs:
>>>len(a)
3

Dictionary membership test


​The in operator works on dictionaries, too; it tells you whether something appears as a key in
the dictionary (appearing as a value is not good enough).
>>> 'one' in a
True
>>> 'uno' in a
False
​ To see whether something appears as a value in a dictionary, you can use the method values(),which
returns a collection of values, and then use the in operator:
>>> a
{'one': 'uno', 'three': 'tres', 'two': 'dos'}
>>>vals = a.values()
>>> 'uno' in vals
True
​For dictionaries, Python uses an algorithm called a hash table that has a remarkable property: the
in operator takes about the same amount of time no matter how many items are in the dictionary
Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or
deleting an existing entry as shown below in the simple example −
dict={'Name':'Zara','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']
When the above code is executed, it produces the 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. Following is a simple example −
dict={'Name':'Zara','Age':7,'Class':'First'}
del dict['Name'];# remove entry with key 'Name'
dict.clear();# remove all entries in dict
deldict;# delete entire dictionary
print"dict['Age']: ",dict['Age']
print"dict['School']: ",dict['School']
This produces the following result. Note that an exception is raised 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.

Built-in Dictionary Functions & Methods −


Python includes the following dictionary functions −
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 wo
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

3 dict.fromkeys()
Create a new dictionary with keys from seq and values set to value.

4 dict.get(key, default=None)
For key key, returns value or default if key not in dictionary

5 dict.has_key(key)
Returns true if key in dictionary dict, false otherwise

6 dict.items()
Returns a list of dict's (key, value) tuple pairs

7 dict.keys()
Returns list of dictionarydict's keys

8 dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if key is not already in dict

9 dict.update(dict2)
Adds dictionary dict2's key-values pairs to dict

10 dict.values()
Returns list of dictionary dict's values
1. Insertion sort
Insertion sort is an elementary sorting algorithm that sorts one element at a time.
Most humans, when sorting a deck of cards, will use a strategy similar to insertion sort.
The algorithm takes an element from the list and places it in the correct location in the list.
This process is repeated until there are no more unsorted items in the list.

Program for Insertion sort


def insertionSort(a):
for index in range(1,len(a)):
currentvalue = a[index]
position = index
while position>0 and
a[position-1]>currentvalue:
a[position]=a[position-1]
position = position-1
a[position]=currentvalue
a = [23,78,45,8,32,56]
insertionSort(a)
print("The sorted list using insertion sort is")
print(a)

O/P:
The sorted list using insertion sort is
[8, 23, 32, 45, 56, 78]
2. Selection Sort
​ The selection sort algorithm starts by finding the minimum value in the array and moving it to the
first position.
​ This step is then repeated for the second lowest value, then the third, and so on until the array is
sorted.

Program for Selection sort


A = [23, 78, 45, 8, 32,56]
for i in range(0,len(A)):
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
temp=A[i]
A[i]=A[min_idx]
A[min_idx]=temp
print("Sorted List using selection sort")
print(A)
O/P:
Sorted List using selection sort
[8, 23, 32, 45, 56, 78]

3. Merge sort
Merge sort works as follows:
a. Divide the unsorted list into n sub lists, each containing 1 element (a list of 1 element is
considered sorted).
b. Repeatedly merge sub lists to produce new sorted sub lists until there is only 1 sub list
remaining. This will be the sorted list.

def mergeSort(alist):
print("Splitting
",alist) if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf =
alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i <
len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j <
len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)

alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)

O/P:
Splitting [54, 26, 93, 17, 77, 31, 44, 55, 20]
Splitting [54, 26, 93, 17]
Splitting [54, 26]
Splitting [54]
Merging [54]
Splitting [26]
Merging [26]
Merging [26, 54]
Splitting [93, 17]
Splitting [93]
Merging [93]
Splitting [17]
Merging [17]
Merging [17, 93]
Merging [17, 26, 54, 93]
Splitting [77, 31, 44, 55, 20]
Splitting [77, 31]
Splitting [77]
Merging [77]
Splitting [31]
Merging [31]
Merging [31, 77]
Splitting [44, 55, 20]
Splitting [44]
Merging [44]
Splitting [55, 20]
Splitting [55]
Merging [55]
Splitting [20]
Merging [20]
Merging [20, 55]
Merging [20, 44, 55]
Merging [20, 31, 44, 55, 77]
Merging [17, 20, 26, 31, 44, 54, 55, 77, 93]
[17, 20, 26, 31, 44, 54, 55, 77, 93]

4. Histogram
def histogram( items ):
for n in items:
output=”
times = n
while( times > 0 ):
output += '*'
times = times - 1
print(output)

prices = []
sub_total = 0.0
n=int(input(" Enter the no of items :"))
for i in range(n):
item = float( input("Enter the price of item #" + str(i+1) + ": "))
sub_total = sub_total + item
prices.append(item)
#compute the tax on the sub total @ rate of 7.25%
tax = sub_total * (7.25/100)
total_price = sub_total + tax
print("Sub total: ",sub_total)
print("Tax: {:0.2f}".format(tax))
print("Total: {:0.2f}".format(total_price))

O/P :
Enter the no of items :2
Enter the price of item #1:
101.1 Enter the price of item
#2: 101.2 Sub total: 202.3
Tax: 14.67
Total: 216.97
Student Mark statement

Program:
a, b, c, d, e = 0, 0, 0, 0, 0
marks = [a, b, c, d, e]
for i in range(0, len(marks)):
marks[i] = int(input("Enter the marks out of 100 : "))
total = sum(marks)
print("The total mark is ", total, "out of 500.")
percent = total/500*100
print("Percentage is ", percent, "%.")

You might also like