This page is located in archive. Go to the latest version of this course pages. Go the latest version of this page.

Computer Lab 05, non-trivial loops, iterators, sets, dictionaries


Iterator in python is an object that is used to iterate over iterable objects like lists, tuples, dicts and sets. Iterator object is initialised using the iter() method. It uses the next() method for iteration.

  1. __iter(iterable)__ method that is called for initialization of an iterator. This returns an iterator object.
  2. __next__. The next method returns the next value for the iterable. When we use a for loop to traverse any iterable object, internally it uses the iter() method to get an iterator object which further uses next() method to iterate over. This method raises a StopIteration to signal the end of the iteration.

mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)

mytuple = ("apple", "banana", "cherry")
# create an iterator object from that iterable
myit = iter(mytuple)
# infinite loop
while True:
        # get the next item
        element = next(myit)
        # do something with element
    except StopIteration:
        # if StopIteration is raised, break from loop

mytuple = ("apple", "banana", "cherry")
for x in mytuple:

Non-trivial loops

Sum of digits in a string

Let s be a string containing several characters some of which may be digits. Write a function that returns the sum of all digits in that string.

def sum_digits_in_string(s):
    """Return sum of all digits in a string.
    :param s: string containing the digits and other characters
    :return: numeric value, sum of all digits
    >>> sum_digits_in_string('1')
    >>> sum_digits_in_string('hi 1 hello 2')
    >>> sum_digits_in_string('Values: 1.26, 2.3, 1.76')

Sum of decimal numbers in a string

Let s be a string containing decimal numbers separated by commas, e.g. s = '1.26,2.3,1.76'. Write a function that returns the sum of all decimal numbers in that string.

def sum_decimals_in_string(s):
    """Return sum of decimal numbers in a string.
    :param s: string containing the decimal numbers separated by ','
    :return: float, sum of all decimals
    >>> sum_decimals_in_string('1.2')
    >>> sum_decimals_in_string('1.2,3.4')
    >>> sum_decimals_in_string('1,2,0.000001')

Weekly Homework 05 - Chemical compounds

Write a function combine_elements(el1, el2) which takes 2 iterables (e.g. lists) of chemical elements, and returns a list of all possible compounds that can arise by combining an element from the first list with an element from the second list.

Required filename: 05_weekly_hw.py.

def combine_elements(el1, el2):
    """Return a list of possible compounds each containing a single element from both the first and second list.
    :param el1: list of strings, symbols of chemical elements for the first place of compound
    :param el2: list of strings, symbols of chemical elements for the second place of compound
    :return: list of strings, possible chemical compounds
    >>> metals = 'Li Na K'.split()
    >>> halogens = 'F Cl Br'.split()
    >>> print(combine_elements(metals, halogens))
    ['LiF', 'LiCl', 'LiBr', 'NaF', 'NaCl', 'NaBr', 'KF', 'KCl', 'KBr']


  • string: immutable ordered sequence of characters
  • tuple: immutable ordered sequence of items of any data type
  • list: mutable ordered sequence of items of any data type
  • set: mutable unordered collection of unique items of any type

Exercise: Consider the following excerpts from 2 famous books by Jane Austin (Project Gutenberg). Using operations on strings and sets, derive a list of:

  1. common words to these two texts
  2. words unique to Pride & Prejudice only

# Pride and Prejudice by Jane Austen
text1 = '''It is a truth universally acknowledged, that a single man in
        possession of a good fortune, must be in want of a wife.
        However little known the feelings or views of such a man may be
        on his first entering a neighbourhood, this truth is so well
        fixed in the minds of the surrounding families, that he is
        considered the rightful property of some one or other of their
# Sense and Sensibility by Jane Austen
text2 = '''The family of Dashwood had long been settled in Sussex.  Their estate
was large, and their residence was at Norland Park, in the centre of
their property, where, for many generations, they had lived in so
respectable a manner as to engage the general good opinion of their
surrounding acquaintance.  The late owner of this estate was a single
man, who lived to a very advanced age, and who for many years of his
life, had a constant companion and housekeeper in his sister.  But her
death, which happened ten years before his own, produced a great
alteration in his home; for to supply her loss, he invited and received
into his house the family of his nephew Mr. Henry Dashwood, the legal
inheritor of the Norland estate, and the person to whom he intended to
bequeath it.  In the society of his nephew and niece, and their
children, the old Gentleman's days were comfortably spent.  His
attachment to them all increased.  The constant attention of Mr. and
Mrs. Henry Dashwood to his wishes, which proceeded not merely from
interest, but from goodness of heart, gave him every degree of solid
comfort which his age could receive; and the cheerfulness of the
children added a relish to his existence.'''


Exercise: Now, consider the following excerpt from Alice's Adventures in Wonderland by Lewis Carroll.

  1. Create a dictionary which will work as a counter (yes, there is a built-in Counter. Let's pretend it does not exist for now), i.e., it will hold key-value pair word:count. Try two different techniques:
  • manually check if the word is already in the dictionary and branch the program appropriately.
  • use the dict.get() function with 2 parameters.
  1. Using the dictionary, print only those words appearing more than 3 times in the text.

text = '''Down the Rabbit-Hole
Alice was beginning to get very tired of sitting by her sister on the
bank, and of having nothing to do: once or twice she had peeped into
the book her sister was reading, but it had no pictures or
conversations in it, "and what is the use of a book," thought Alice
"without pictures or conversations?"
So she was considering in her own mind (as well as she could, for the
hot day made her feel very sleepy and stupid), whether the pleasure of
making a daisy-chain would be worth the trouble of getting up and
picking the daisies, when suddenly a White Rabbit with pink eyes ran
close by her.
There was nothing so very remarkable in that; nor did Alice think it
so very much out of the way to hear the Rabbit say to itself, "Oh
dear! Oh dear! I shall be late!" (when she thought it over afterwards,
it occurred to her that she ought to have wondered at this, but at the
time it all seemed quite natural); but when the Rabbit actually took a
watch out of its waistcoat-pocket, and looked at it, and then hurried
on, Alice started to her feet, for it flashed across her mind that she
had never before seen a rabbit with either a waistcoat-pocket, or a
watch to take out of it, and burning with curiosity, she ran across the
field after it, and fortunately was just in time to see it pop down a
large rabbit-hole under the hedge.'''

courses/be5b33prg/labs/week_05.txt · Last modified: 2020/10/19 15:13 by nemymila