📖
Introduction to programming with Python
  • Introduction to programming with Python 3
  • Preface
    • Common misconceptions about learning to program
    • The Hard truth about learning to program
    • Personal qualities for success
  • 1 - The way of the program
    • Python Programming Language
    • The first program
    • What is debugging?
    • Glossary
    • Exercises
  • 2 - Variables, expressions and statements
    • Values, types and variables
    • Common Built-in data types
    • Expressions
    • Code Format
    • Debugging
    • Glossary
    • Exercises
  • 3 - Functions
    • Python "built-in" Functions
    • Math Functions
    • Composition
    • User Defined Functions
    • PEP 8 Recommendations
    • Debugging
    • Glossary
    • Exercises
  • 4 - Conditionals
    • Boolean expressions
    • Conditional statements
    • PEP 8 Recommendations
  • 5 - Iteration
    • The while statement
    • The for statement
    • break and continue statements
    • Nested Loops
    • PEP 8 Recommendations
    • Debugging
    • Glossary
    • Exercises
  • 6 - A short introduction to testing: Building Reliable Software
  • 7 - A deeper dive into Strings, Lists and Tuples
    • More on Strings
    • More on Lists
    • More on Tuples
    • Debugging
    • Glossary
    • Exercises
  • 8 - A deeper look at Functions in Python
    • Function Preconditions and Postconditions
    • Positional and Keywords arguments
    • Nested Functions
    • Scope of a variable
    • Recursion
    • Functions' side effects
    • Glossary
    • Exercises
  • 9 - Code Documentation
    • Basics of Commenting Code
    • Documenting Code via Python Docstring
  • 10 - Sets and dictionaries
    • Sets
    • Dictionaries
    • Which data structure should I use?
    • Debugging
    • Glossary
    • Exercises
  • 11 - File I/O
    • Read/Write to a file
    • File management
    • Debugging
    • Glossary
    • Exercises
  • 12 - Handling Errors and Exceptions
  • 13 - Writing modules
  • 14 - Classes
    • Classes and Objects
    • Classes and Functions
    • Classes and Methods
    • Pythonic Magic: Understanding and Implementing Dunder Methods
    • Glossary
    • Exercises
  • 15 - Python's Type Hinting
  • Acknowledgements
Powered by GitBook
On this page
  • Exercise 1
  • Exercise 2: rotate-pairs
Edit on GitHub
  1. 10 - Sets and dictionaries

Exercises

PreviousGlossaryNext11 - File I/O

Last updated 1 year ago

Exercise 1

If you did the exercise duplicate you already have a function named has_duplicates that takes a list as a parameter and returns True if there is any object that appears more than once in the list.

Use a set to write a faster, simpler version of has_duplicates.

Answer

Checking the membership of an element in a set (line 4) is very fast (constant time) compared to checking the membership in a list (linear time). This is why this implementation should be preferred to the one given in a .

def has_duplicates(elements):
    visited = set()
    for i in range(len(elements)):
        if elements[i] in visited:
            return True
        else:
            visited.add(elements[i])
    return False

Exercise 2: rotate-pairs

Two words are "rotate pairs" if you can rotate one of them and get the other (see ). Write a program that reads a wordlist and finds all the rotate pairs.

Answer

For convenience, we provide the implementation of rotate_word, that rotates a word by a given shift.

from string import ascii_lowercase

def rotate_word(word, shift):
    rotated = ''
    for letter in word.lower():
        index = ascii_lowercase.find(letter)
        index = (index + shift) % len(ascii_lowercase)
        rotated += ascii_lowercase[index]
    return rotated

def find_rotate_pairs(words_list):
    words_set = {word.strip().lower() for word in words_list}
    rotate_pairs = []
    for word in words_set:
        for shift in range(1, len(ascii_lowercase)):
            rotated = rotate_word(word, shift)
            if rotated in words_set:
                rotate_pairs.append((word, rotated, shift))
    return rotate_pairs

Although there is an overhead for transforming the list of words into a set (line 10), for large list it improve considerably the performance when checking the membership of the rotated word (line18).

previous exercise
rotate_word