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

5-Module-2 - Working With SPL Data Structures-18-01-2024

Uploaded by

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

5-Module-2 - Working With SPL Data Structures-18-01-2024

Uploaded by

btclips72
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Problem

A farmer with a fox, a goose, and a sack of corn needs to


cross a river. Now he is on the east side of the river and
wants to go to west side. The farmer has a rowboat, but
there is room for only the farmer and one of his three items.
Unfortunately, both the fox and the goose are hungry. The
fox cannot be left alone with the goose, or the fox will eat
the goose. Likewise, the goose cannot be left alone with the
sack of corn, or the goose will eat the corn. Given a sequence
of moves find if all the three items fox, goose and corn are
safe. The input sequence indicate the item carried by the
farmer along with him in the boat. ‘F’ – Fox, ‘C’ – Corn, ‘G’ –
Goose, N-Nothing. As he is now on the eastern side the first
move is to west and direction alternates for each step.
Pseudocode
READ items_carried
SET east as G, C, F
SET west as empty
SET from_Dir = east and to_Dir = west
FOR each item in items_carried
IF from_Dir == east THEN
remove item from east and add to west
IF east or west contains ‘C’ and ‘G’ or ‘G’ and ‘F’ THEN
PRINT ‘NOT SAFE’
BREAK
ELSE
remove item from west and add to east
IF east or west contains ‘C’ and ‘G’ or ‘G’ and ‘F’ THEN
PRINT ‘NOT SAFE’
BREAK
END IF
IF from_Dir == east THEN
SET from_Dir = west
SET to_Dir = east
ELSE
SET from_Dir = east
SET to_Dir = west
END IF
END FOR
PRINT ‘SAFE’
While going for a Shopping ….!!!???

Imagine you have the scores in “Python


Programming” for 100 students. If you want to
find the average score in Python…?
Simple Statistics
• Many programs deal with large collections of
similar information.
– Words in a document
– Students in a course
– Data from an experiment
– Customers of a business
– Graphics objects drawn on the screen
– Cards in a deck

Python Programming, 1/e 4


List
Examples
• Apple, Banana, Berry, Mango
• Football, Basketball, Throwball, Tennis, Hockey
• Sunrise, Sugar, Cheese, Butter, Pickle, Soap,
Washing Powder, Oil….
• Agra, Delhi, Kashmir, Jaipur, Kolkata…
Introduction
• Contains multiple values that are logically related
• List is a type of mutable sequence in Python
• Each element of a list is assigned a number –
index / position
• Can do indexing, slicing, adding, multiplying, and
checking for membership
• Built-in functions for finding length of a sequence
and for finding its largest and smallest elements
What is a List?
• Most versatile data type in Python
• Comma-separated items can be collected in
square brackets
• Good thing is..
– THE ITEMS IN THE LIST NEED NOT BE OF SAME
TYPE
Creating a list
• Creating an EMPTY • Creating a list with items
list listname = [item1, item2, ….]
listname = [] Example:
Example: Temp = [100, 99.8, 103, 102]
L1 = [] S = [‘15BIT0001’, ‘Achu’, 99.9]
MyList = []
L2 = [1, 2, 3, 4, 5, 6, 7]
Books = []
Course = [‘Python’, ‘C’, ‘C++’,
‘Java’]
Accessing Values
• Using index or indices
>>>L1 = [1, 2, 3, 4, 5, 6]
>>>print (L1[3]) #indexing
>>>4
>>>print (L1[2:5]) #slicing
>>>[3, 4, 5]
Updating Elements
• Update an element in list using index
>>>L1 = [1, 2, 3, 4, 5, 6]
>>>L1[2] = 111
>>>L1
[1, 2, 111, 4, 5, 6]
Deleting Elements
• Delete an element in list using index
>>>L1 = [1, 2, 3, 4, 5, 6]
>>>del (L1[4])
>>>L1
[1, 2, 3, 4, 6]
Basic Operations in List
• >>> len([1, 2, 3]) # Length
3
• >>> [1, 2, 3] + [4, 5, 6] # Concatenation
[1, 2, 3, 4, 5, 6]

• >>> ['Ni!'] * 4 # Repetition


['Ni!', 'Ni!', 'Ni!', 'Ni!']
Basic Operations in List
• >>> str([1, 2]) + "34" # Same as "[1, 2]" + "34"
'[1, 2]34'

• >>> [1, 2] + list("34")


# Same as [1, 2] + ["3", "4"]
[1, 2, '3', '4‘]
List Iteration
• >>> 3 in [1, 2, 3] # Membership
True
• >>> for x in [1, 2, 3]:
print(x, end=' ')
# Iteration (2.X uses: print x,) ... 1 2 3
List Comprehensions
>>> res = [c * 4 for c in 'SPAM']
# List comprehensions
>>> res
['SSSS', 'PPPP', 'AAAA', 'MMMM']
• expression is functionally equivalent to a for
loop that builds up a list of results manually
• list comprehensions are simpler to code and
likely faster to run today:
List Comprehensions
# List comprehension equivalent ...
>>> res = []
>>> for c in 'SPAM':
res.append(c * 4)
>>> res
['SSSS', 'PPPP', 'AAAA', 'MMMM']
Indexing, Slicing
>>> L = ['spam', 'Spam', 'SPAM!']
>>> L[2] # Offsets start at zero
'SPAM!'
>>> L[−2] # Negative: count from the right
'Spam'
>>> L[1:] # Slicing fetches sections
['Spam', 'SPAM!']
Matrixes
• a basic 3 × 3 two-dimensional list-based array:
>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
• With one index, you get an entire row (really, a
nested sub list), and with two, you get an item
within the row:
>>> matrix[1]
[4, 5, 6]
Matrixes
>>> matrix[1][1]
5
>>> matrix[2][0]
7
>>> matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
>>> matrix[1][1]
5
Insertion, Deletion and Replacement
>>> L = [1, 2, 3]
>>> L[1:2] = [4, 5] # Replacement/insertion
>>> L
[1, 4, 5, 3]
>>> L[1:1] = [6, 7] # Insertion (replace nothing)
>>> L
[1, 6, 7, 4, 5, 3]
>>> L[1:2] = [] # Deletion (insert nothing)
>>> L
[1, 7, 4, 5, 3]
Insertion, Deletion and Replacement
>>> L = [1]
>>> L[:0] = [2, 3, 4]
# Insert all at :0, an empty slice at front
>>> L
[2, 3, 4, 1]
>>> L[len(L):] = [5, 6, 7]
# Insert all at len(L):, an empty slice at end
>>> L
[2, 3, 4, 1, 5, 6, 7]
List method calls
>>> L = ['eat', 'more', 'SPAM!']

>>> L.append('please')

# Append method call: add item at end

>>> L

['eat', 'more', 'SPAM!', 'please']

>>> L.sort() # Sort list items ('S' < 'e')

>>> L

['SPAM!', 'eat', 'more', 'please']


More on Sorting Lists
>>> L = ['abc', 'ABD', 'aBe']

>>> L.sort() # Sort with mixed case

>>> L

['ABD', 'aBe', 'abc']

>>> L = ['abc', 'ABD', 'aBe']

>>> L.sort(key=str.lower) # Normalize to lowercase

>>> L

['abc', 'ABD', 'aBe']


More on Sorting Lists
>>> L.sort(key=str.lower, reverse=True)
# Change sort order (descending)
>>> L ['aBe', 'ABD', 'abc']
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
vowels.sort(reverse=True)
# print vowels
print('Sorted list (in Descending):', vowels)
O/P: Sorted list (in Descending): ['u', 'o', 'i', 'e', 'a']
Other common list methods
>>> L = [1, 2]

>>> L.extend([3, 4, 5])

# Add many items at end (like in-place +)

>>> L [1, 2, 3, 4, 5]

>>> L.pop()

# Delete and return last item

5
Other common list methods
>>> L
[1, 2, 3, 4]
>>> L.reverse() # In-place reversal method
>>> L
[4, 3, 2, 1]
>>> list(reversed(L)) # Reversal built-in with a result
(iterator)
[1, 2, 3, 4]
seqString = 'Python‘
print(list(reversed(seqString)))
O/P:['n', 'o', 'h', 't', 'y', 'P']
Other common list methods
>>> L = ['spam', 'eggs', 'ham']
>>> L.index('eggs') # Index of an object (search/find)
1
>>> L.insert(1, 'toast') # Insert at position
>>> L
['spam', 'toast', 'eggs', 'ham']
>>> L.remove('eggs') # Delete by value
>>> L
['spam', 'toast', 'ham']
Other common list methods
>>> L.pop(1) # Delete by position 'toast'

>>> L

['spam', 'ham']

>>> L.count('spam') # Number of occurrences 1

1
Other common list methods

>>> L = ['spam', 'eggs', 'ham', 'toast']

>>> del L[0] # Delete one item

>>> L

['eggs', 'ham', 'toast']

>>> del L[1:] # Delete an entire section

>>> L # Same as L[1:] = []

['eggs‘]
Other common list methods
>>> L = ['Already', 'got', 'one']

>>> L[1:] = []

>>> L

['Already']

>>> L[0] = []

>>> L

[[]]
Hence…
• A list is a sequence of items stored as a single
object.
• Items in a list can be accessed by indexing, and
sub lists can be accessed by slicing.
• Lists are mutable; individual items or entire slices
can be replaced through assignment statements.
• Lists support a number of convenient and
frequently used methods.
• Lists will grow and shrink as needed.

Python Programming, 1/e 33


Strings and Lists
>>> S = 'spammy'
>>> L = list(S)
>>> L
['s', 'p', 'a', 'm', 'm', 'y']
>>> L[3] = 'x' # Works for lists, not strings
>>> L[4] = 'x‘
>>> L
['s', 'p', 'a', 'x', 'x', 'y']
>>> S = ''.join(L) #uses ‘’ for joining elements of list
>>> S
'spaxxy‘
Strings and Lists
>>> 'SPAM'.join(['eggs', 'sausage', 'ham', 'toast'])
'eggsSPAMsausageSPAMhamSPAMtoast‘
# uses ‘SPAM’ for joining elements of list
>>> line = 'aaa bbb ccc'
>>> cols = line.split()
>>> cols
['aaa', 'bbb', 'ccc']

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy