0% found this document useful (0 votes)
4 views11 pages

Understanding Programing Lab 10

Lab 11 introduces Python sets and the random module, covering set properties, operations, and methods for managing collections of items. It explains how to use the random module for generating pseudorandom numbers, including functions for selecting random integers and floating-point numbers. The lab also includes exercises for practical application of the concepts learned.

Uploaded by

freelancerxlax
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)
4 views11 pages

Understanding Programing Lab 10

Lab 11 introduces Python sets and the random module, covering set properties, operations, and methods for managing collections of items. It explains how to use the random module for generating pseudorandom numbers, including functions for selecting random integers and floating-point numbers. The lab also includes exercises for practical application of the concepts learned.

Uploaded by

freelancerxlax
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

Lab 11 – Introduction to sets and Module Random

January 21, 2019

Student Name: Roll No: Section:

Experiment No. 11
Lab 11 – Introduction to sets and Module Random

Lab Objectives:

1. Introduction to sets
2. Module Random

1.1 Sets
In this lab, we introduce another built-in Python container type. The set class has all the
properties of a mathematical set. It is used to store an unordered collection of items, with no
duplicate items allowed. The items must be immutable objects. The set type supports operators
that implement the classical set operations: set membership, intersection, union, symmetric
difference, and so on. It is thus useful whenever a collection of items is modeled as a
mathematical set. It is also useful for duplicate removal.

A set is defined using the same notation that is used for mathematical sets: a sequence of items
separated by commas and enclosed in curly braces: { }. Here is how e would assign the set of
three phone numbers (as strings) to variable phonebook1:

>>> phonebook1 = {'123-45-67', '234-56-78', '345-67-89'}


We check the value and type of phonebook1:
>>> phonebook1
{'123-45-67', '234-56-78', '345-67-89'}
>>> type(phonebook1)
<class 'set'>
If we had defined a set with duplicate items, they would be ignored:
>>> phonebook1 = {'123-45-67', '234-56-78', '345-67-89',
'123-45-67', '345-67-89'}
>>> phonebook1
{'123-45-67', '234-56-78', '345-67-89'}

Using the set Constructor to Remove [Link] fact that sets cannot have duplicates
gives us the first great application for sets: removing duplicates from a list. Suppose we have
a list with duplicates, such as this list of ages of students in a class:

>>> ages = [23, 19, 18, 21, 18, 20, 21, 23, 22, 23, 19, 20]
To remove duplicates from this list, we can convert the list to a set, using the set
[Link] set constructor will eliminate all duplicates because a set is not supposed to
have them.
By converting the set back to a list, we get a list with no duplicates:
Lab 11 – Introduction to sets and Module Random
January 21, 2019

Student Name: Roll No: Section:


>>> ages = list(set(ages))

>>> ages
[18, 19, 20, 21, 22, 23]
There is, however, one major caveat: The elements have been reordered.

1.2 set Operators


The set class supports operators that correspond to the usual mathematical set operations.
Some are operators that can also be used with list, string, and dictionary types. For example,
the in and not in operators are used to test set membership:
>>> '123-45-67' in phonebook1
True
Lab 11 – Introduction to sets and Module Random
January 21, 2019

Student Name: Roll No: Section:

>>> '456-78-90' in phonebook1


False
>>> '456-78-90' not in phonebook1
True
The len() operator returns the size of the set:
>>> len(phonebook1)
3
Comparison operators ==, !=, <, <=, >, and >= are supported as well, but their meaning is
set-specific. Two sets are “equal” if and only if they have the same elements:
>>> phonebook3 = {'345-67-89','456-78-90'}
>>> phonebook1 == phonebook3
False
>>> phonebook1 != phonebook3
True
As shown in Figure-1, sets phonebook1 and phonebook3 do not contain the same elements.

Figure-1

A set is “less than or equal to” another set if it is a subset of it, and a set is “less than another
set” if it is a proper subset of it. So, for example:

>>> {'123-45-67', '345-67-89'} <= phonebook1


True

As Figure 1 shows, the set {'123-45-67', '345-67-89'} is a subset of set phonebook1.


However, phonebook1 is not a proper subset of phonebook1:

>>> phonebook1 < phonebook1


False
The mathematical set operations union, intersection, difference, and symmetric difference are
implemented as set operators |, &, -, and ^, respectively. Each set operation takes two sets and
returns a new set. The union of two sets contains all elements that are in either set:

>>> phonebook1 | phonebook3


{'123-45-67', '234-56-78', '345-67-89', '456-78-90'}
Lab 11 – Introduction to sets and Module Random
January 21, 2019

Student Name: Roll No: Section:

The intersection of two sets contains all elements that are in both sets:
>>> phonebook1 & phonebook3
{'345-67-89'}
The difference between two sets contains all elements that are in the first set but not the second
one:
>>> phonebook1 - phonebook3
{'123-45-67', '234-56-78'}

The symmetric difference of two sets contains all elements that are either in the first set or in
the second set, but not both:

>>> phonebook1 ^ phonebook3


{'123-45-67', '234-56-78', '456-78-90'}

Use Figure 1 to check that the set operators work as expected. Before we move on to
discussing the set class methods, we summarize in Table 1 the commonly used set operators
that we just covered.

Table-1

1.3 set Methods


In addition to operators, the set class supports a number of methods. The set method
add() is used to add an item to a set:
>>> [Link]('123-45-67')
>>> phonebook3
{'123-45-67', '345-67-89', '456-78-90'}
Lab 11 – Introduction to sets and Module Random
January 21, 2019

Student Name: Roll No: Section:


The method remove() is used to remove an item from a set:
>>> [Link]('123-45-67')
>>> phonebook3
{'345-67-89', '456-78-90'}
Finally, the method clear() is used to empty a set:
>>> [Link]()
We check that phonebook3 is indeed empty:
>>> phonebook3
set()
Exercise 1.1

Solution
The goal is to obtain the union of all the sets appearing in a list. The accumulator pattern
is the right loop pattern for doing this. The accumulator should be a set that is initialized to
be empty:

1.4 Module random


Random numbers are useful for running simulations in science, engineering, and finance.
They are needed in modern cryptographic protocols that provide computer security,
communication privacy, and authentication. They also are a necessary component in games
of chance, such as poker or blackjack, and help make computer games less predictable. Truly
random numbers are not easy to obtain. Most computer applications that require random
numbers use numbers generated by a pseudorandom number generator instead. The “pseudo”
in “pseudorandom” means fake, or not real. Pseudorandom number generators are

programs that produce a sequence of numbers that “look” random and are good enough for
most applications that need random numbers.
Lab 11 – Introduction to sets and Module Random
January 21, 2019

Student Name: Roll No: Section:


In Python, pseudorandom number generators and associated tools are available through
the random module. As usual, if we need to use functions in the random module, we need
to import it first:
>>> import random
Next we describe a few functions in the random module that are particularly useful.
Choosing a Random Integer
We start with function randrange(), which takes a pair of integers a and b and returns
some number in the range from—and including—a up to—and not including—b with each
number in the range equally likely. Here is how we would use this function to simulate
several (six-sided) die tosses:
>>> [Link](1,7)
2
>>> [Link](1,7)
6
>>> [Link](1,7)
5
>>> [Link](1,7)
1
>>> [Link](1,7)
2
Exercise 1.2
Implement function guess() that takes as input an integer n and implements a simple,
interactive number guessing game. The function should start by choosing a random number
in the range from 0 up to but not including n. The function will then repeatedly ask
the user to guess the chosen number; When the user guesses correctly, the function should
print a 'You got it.' message and terminate. Each time the user guesses incorrectly, the
function should help the user by printing message 'Too low.', or 'Too high.'.
>>> guess(100)
Enter your guess: 50
Too low.
Enter your guess: 75
Too high.
Enter your guess: 62
Too high.
Enter your guess: 56
Too low.
Enter your guess: 59
Too high.
Enter your guess: 57
You got it!
Lab 11 – Introduction to sets and Module Random
January 21, 2019

Student Name: Roll No: Section:

Solution

1.5 Randomness

We usually think of the result, heads or tails, of a coin toss as a random event. Most games of
chance depend on the generation of random events (die tosses, card shuffling, roulette spins,
etc.). The problem with these methods of generating random events is that they are not
appropriate for generating randomness quickly enough for a running computer program. It is,
in fact, not easy to get a computer program to generate truly random numbers. For this reason,
computer scientists have developed deterministic algorithms called pseudorandom number
generators that generate numbers that “appear” random.

Choosing a Random “Real”


Sometimes what we need in an application is not a random integer but a random number
chosen from a given number interval. The function uniform() takes two numbers a and b

and returns a float number x such that a x b (assuming a b), with each float
value in the range equally likely. Here is how we would use it to obtain several random
numbers between 0 and 1:
>>> [Link](0,1)
0.9896941090637834
>>> [Link](0,1)
0.3083484771618912
>>> [Link](0,1)
0.12374451518957152
Lab 11 – Introduction to sets and Module Random
January 21, 2019

Student Name: Roll No: Section:

Example 1.3

Hint: Figure 6.6 Dartboard inside a square. Shown are 10 random dart hits with 8 lying inside
the dartboard. In this case, the estimate for pi would be: 4*8/10 = 3:2.

Solution
Each random dart throw hit is simulated by choosing, uniformly at random, an x and a y
coordinate between -1 and 1. If the resulting point (x; y) is within distance 1 from the origin
(0; 0) (i.e., the center of the dartboard), the point represents a hit. An accumulator loop pattern
is used to add up all the “hits.”
Lab 11 – Introduction to sets and Module Random
January 21, 2019

Student Name: Roll No: Section:

1.4 Shuffling, Choosing, and Sampling at Random


Let’s illustrate a few more functions from the random module. The function shuffle() shuffles,
or permutes, the objects in a sequence not unlike how a deck of cards is shuffled prior to a
card game like blackjack. Each possible permutation is equally likely. Here is how we can use
this function to shuffle a list twice:
>>> lst = [1,2,3,4,5]
>>> [Link](lst)
>>> lst
[3, 4, 1, 5, 2]
>>> [Link](lst)
>>> lst
[1, 3, 2, 4, 5]
The function choice() allows us to choose an item from a container uniformly at random.
Given list
>>> lst = ['cat', 'rat', 'bat', 'mat']
here is how we would choose a list item uniformly at random:
>>> [Link](lst)
'mat'
>>> [Link](lst)
'bat'
>>> [Link](lst)
'rat'
>>> [Link](lst)
'bat'

If, instead of needing just one item, we want to choose a sample of size k, with every sample
equally likely, we would use the sample() function. It takes as input the container and the
number k.

Here is how we would choose random samples of list lst of size 2 or 3:


>>> [Link](lst, 2)
Lab 11 – Introduction to sets and Module Random
January 21, 2019

Student Name: Roll No: Section:


['mat', 'bat']
>>> [Link](lst, 2)
['cat', 'rat']
>>> [Link](lst, 3)
['rat', 'mat', 'bat']
Lab 11 – Introduction to sets and Module Random
January 21, 2019

Student Name: Roll No: Section:

Programming Exercise

1. Write function diceprob() that takes as input a possible result r of a roll of pair of dice (i.e.
an integer between 2 and 12) and simulates repeated rolls of a pair of dice until 100 rolls of r
have been obtained. Your function should print how many rolls it took to obtain
100 rolls of r.
>>> diceprob(2)
It took 4007 rolls to get 100 rolls of 2
>>> diceprob(3)
It took 1762 rolls to get 100 rolls of 3
>>> diceprob(4)
It took 1058 rolls to get 100 rolls of 4
>>> diceprob(5)
It took 1075 rolls to get 100 rolls of 5

2. Using a counter loop pattern, construct sets mult3, mult5, and mult7 of nonnegative
multiples of 3, 5, and 7, respectively, less than 100. Then, using these three sets, write set
expressions that return
(a) Multiples of 35
(b) Multiples of 105
(c) Multiples of 3 or 7
(d) Multiples of 3 or 7, but not both
(e) Multiples of 7 that are not multiples of 3

3. Implement function coin() that returns 'Heads' or 'Tails' with equal probability.
>>> coin()
'Heads'
>>> coin()
'Heads'
>>> coin()
'Tails'

You might also like