Regular Bite Exercises Bites RSS feed

Hone your Python skills by coding and verifying exercises in the comfort of your browser.
 | Catalogue | Random Bite

Bite Tags User rated
More info /

Bite 1. Sum n numbers

Write a Python function that calculates the sum of a list of numbers: The function should accept a list of …

default args freebie None

range sum


Bite 5. Parse a list of names

In this Bite you will work with a list of names. 1. Write a function that accepts a list of …

freebie lambda list comprehensions

min sorting


Bite 8. Rotate string characters

Write a function that rotates characters in a string in either direction: - If n is positive, move n characters …

deque slicing 3.57⚬⚬⚬⚬


Bite 15. Enumerate 2 sequences

Iterate over the given names and countries lists, printing them prepending the number of the loop (starting at 1). Here …

enumerate string formatting 4.8⚬⚬⚬⚬⚬


Bite 16. PyBites date generator

Write a generator that returns every 100th day counting forward from the PYBITES_BORN date. Here is how the generator would work …

datetime generators 6.48⚬⚬⚬⚬⚬⚬


Bite 19. Write a property

Write a simple Promo class. Its constructor receives two variables: name (which must be a string) and expires (which must …

datetime properties 4.5⚬⚬⚬⚬


Bite 21. Query a nested data structure

Given the provided cars dictionary: Get all Jeeps Get the first car of every manufacturer. Get all vehicles containing the …

data structures dictionary comprehensions list comprehensions



Bite 26. Dictionary comprehensions are awesome

A dictionary comprehension is like a list comprehension, but it constructs a dict instead of a list. They are convenient …

dictionary comprehensions 3.14⚬⚬⚬


Bite 29. Martin's IQ test

Martin is preparing to pass an IQ test. The most frequent task in this test is to find out which …

enumerate string module 4.67⚬⚬⚬⚬⚬


Bite 32. Don't let mutability fool you

In this Bite you are presented with a function that copies the given items data structure.There is a problem though, …

deepcopy mutability 1.92⚬⚬


Bite 37. Rewrite a for loop using recursion

Although you have to be careful using recursion it is one of those concepts you want to at least understand. …

recursion reverse 2.58⚬⚬⚬


Bite 38. Using ElementTree to parse XML

In this Bite you will use ElementTree to parse some Nolan movies we extracted from OMDb.Luckily most APIs switched to …

movie data xml 5.36⚬⚬⚬⚬⚬


Bite 43. Force keyword arguments

Write a function called get_profile that only allows 2 keyword arguments: name and profession which default to julian and programmer …

function arguments kwargs 4.59⚬⚬⚬⚬⚬


Bite 44. License key generator

Write a function called gen_key that creates a license key with this format: KI80OMZ7-5OGYC1AC-735LDPT1-4L11XU1U The key consists of a combination …

list comprehensions secrets string module



Bite 45. Keep a queue of last n items

How about writing a queue that holds the last 5 items? Queue follows First-In-First-Out methodology, i.e., the data item stored …

deque 4.44⚬⚬⚬⚬


Bite 46. You are a programmer! Code Fizz Buzz

Here is a beginner Bite to write Fizz Buzz: Fizz buzz is a group word game for children to teach …

fizzbuzz 1.86⚬⚬


Bite 54. Nicer formatting of a poem or text

In this Bite you complete print_hanging_indents to print a poem (or text) in a nicer way. For example calling it …

string manipulation textwrap 5.56⚬⚬⚬⚬⚬⚬


Bite 55. Get the latest game releases from Steam's RSS feed

The Steam gaming platform has an RSS feed of their latest game releases. In this Bite, you'll pull down and …

feedparser namedtuple 3.12⚬⚬⚬


Bite 56. Add a command line interface to our BMI calculator

Complete create_parser below so that our BMI program can be called like this: $ python -h usage: [-h] …

argparse 4.15⚬⚬⚬⚬


Bite 64. Fix a truncating zip function

Bert is in charge of organizing an event and got the attendees names, locations and confirmations in 3 lists. Assuming …

itertools zip 2.61⚬⚬⚬


Bite 66. Calculate the running average of a sequence

Write a function that takes a sequence of items and returns the running average, so for example this: running_mean([1, 2, …

enumerate itertools mean



Bite 67. Working with datetimes

This Bite involves solving two problems using datetime:We kicked off our 100 Days of Code project on March 30th, 2017. …

datetime timedelta 3.16⚬⚬⚬


Bite 68. Remove punctuation characters from a string

Complete remove_punctuation which receives an input string and strips out all punctuation characters (!"#$%&\'()*+,-./:;<=>[email protected][\\]^_`{|}~).Return the resulting string. You can go …

string manipulation string module 2.18⚬⚬


Bite 74. What day of the week were you born on?

Complete weekday_of_birth_date which takes a date object of a birthday and returns the corresponding weekday string.For example Bob and Julian's …

calendar 1.82⚬⚬


Bite 77. New places to travel to

You want to find people who have as much exposure to different cultures as yourself.Complete the uncommon_cities helper that takes …

set set operations 1.87⚬⚬


Bite 80. Check equality of two lists

In this Bite we compare two list objects for equality, a fundamental thing to understand in Python. Complete the check_equality …

enum equality list



Bite 83. At what time does PyBites live?

Get to know pytz! pytz brings the Olson tz database into Python (docs). Let's see how many hours Bob and …

pytz timezones 3.11⚬⚬⚬


Bite 91. Matching multiple strings

Catching up after #PyCon2018 ... in this Bite you do multiple string matching. Complete contains_only_vowels, contains_any_py_chars, and contains_digits below. See …

all any string matching



Bite 96. Build Unix' wc program in Python

In this Bite you will convert Unix' wc command into Python. Your function takes a file (absolute path), reads it …

file processing tempfile Unix



Bite 100. Display the last part of a file (Unix tail)

Complete the function below simulating Unix' tail, for example: $ tail -3 # byte to str conversion and strip …

file processing slicing strip



Bite 115. Count leading spaces

A small but interesting Bite: given a string with leading indent spacing, calculate the amount of space (literal space, not …

counting string matching 2.64⚬⚬⚬


Bite 117. Round a number even (a.k.a. banker's rounding)

Bankers Rounding is an algorithm for rounding quantities to integers, in which numbers which are equidistant from the two nearest …

Decimal rounding 1.75⚬⚬


Bite 128. Work with datetime's strptime and strftime

In this Bite you get some more practice with datetime's useful strptime and stftime. Complete the two functions: years_ago and …

datetime strftime strptime



Bite 130. Analyze some basic Car Data

In this exercise you will analyze some basic car data. Here is the (fake) JSON data we created with Mockeroo …

Counter data analysis list comprehensions



Bite 133. Convert an Amazon URL into an affiliation link

Can you help PyBites automate their Amazon affiliation link creation?Complete the generate_affiliation_link(url) function below which should convert the following links: …

regular expressions string manipulation 2.21⚬⚬


Bite 136. Bloodtypes

Check red blood cell compatibility between donor and recipient. For simplicity, only eight basic types of blood are considered. The …

enum exception handling multi type input



Bite 143. Look up a value in 3 dictionaries

In this Bite you are presented with 3 dictionaries. Complete get_person_age that takes a name as argument and returns the …

collections dict 3.36⚬⚬⚬


Bite 149. Sorting words with constraint

Here is a list of words Jacob is trying to sort: >>> words = "It's almost Holidays and PyBites wishes …

lambda sorting string manipulation



Bite 153. Round a sequence of numbers

It's time to get mathematical! In this Bite we ask that you complete the round_up_or_down function that receives a transactions …

list comprehensions math rounding



Bite 161. Count the number of files and directories

Complete count_dirs_and_files traversing the passed in directory path. Return a tuple of (number_of_directories, number_of_files) Let's use the tree command to …

counting directories files

os module


Bite 165. Parse an /etc/passwd file output

The /etc/passwd file is a text-based database of information about users that may log into the system or other operating …

split string manipulation tuple unpacking



Bite 167. Complete a User class: properties and representation dunder methods

In this Bite you are presented with another class, User this time. Like last Bite you are asked to complete …

classes dunder methods f-strings

properties __repr__ __str__ string manipulation


Bite 169. Simple length converter

Your task is to complete the convert() function. It's purpose is to convert centimeters to inches and vice versa. As …

exception handling numbers rounding



Bite 172. Having fun with Python Partials

Meet another gem in the standard library: functools, which contains tools for functional-style programming. In this Bite you will play …

functools partial rounding



Bite 176. Create a variable length chessboard

In this Bite you are going to print a chessboard to stdout (use print).Complete create_chessboard that takes an optional argument …

modulo range stdout



Bite 180. Group names by country

In this Bite you are presented with a list of surnames, names, and countries. These 3 fields are in a …

collections defaultdict groupby



Bite 181. Keep a list sorted upon insert

Complete the add method of the OrderedList class which takes a num argument and adds that to the self._numbers list …

bisect classes data structures



Bite 188. Get statistics from PyBites test code

Did you know Python has a statistics module?For this Bite we did a line count on our test code for …

data analysis file processing statistics



Bite 189. Filter a list of names

Here is a Bite to practice the continue and break statements in Python.Complete filter_names that takes a list of names …

break continue generators



Bite 192. Some logging practice

You are to flesh out the log_it() function so that it will log to any LOG LEVEL and with any …

callable logging 5.25⚬⚬⚬⚬⚬


Bite 208. Find the number pairs summing up N

In this Bite you complete find_number_pairs which receives a list of numbers and returns all the pairs that sum up …

itertools looping numbers



Bite 209. Write a Sphinx docstring

Your team uses Sphinx and wants you to comply with its standards for docstrings. As per the Sphinx-RTD-Tutorial a typical …

data types docstring sphinx



Bite 210. Add Type Annotations

Continuing from where we left off in Bite 209, use the docstring you wrote in last Bite to add type …

annotations typing 2.83⚬⚬⚬


Bite 214. A countdown generator

Write a simple generator that counts from 100 to 1. It can just return the ints one by one, no …

generators 1.91⚬⚬


Bite 215. Validate a license key

Complete the validate_license function writing a regular expression that matches a PyBites license key which: Starts with PB, following 4 …

bool regular expressions 4.27⚬⚬⚬⚬


Bite 218. Create a sandwich decorator

After creating our Decorators and Context Managers learning path we realized we did not have a beginner decorator Bite, so …

decorators 3.31⚬⚬⚬


Bite 225. Swap case PyBites characters

In this Bite you will swap case all pybites characters (both lower- and upper case) for a given text.Not much …

looping string manipulation string parsing



Bite 231. Where are the emojis?

In this Bite you are given a list of strings that contain emojis. Complete get_emoji_indices returning a list of indices …

emojis list list comprehensions

looping regular expressions


Bite 238. Write tests for Fibonacci

Our first Test Bite! The concept is simple: to pass a Test Bite, you write tests for the program under …

fibonacci freebie pytest



Bite 241. Write tests for list_to_decimal

Our 4th test Bite. Michael made a calculator that will be able to accept a list of decimal digits and …

exception handling freebie pytest



Bite 246. Test print / standard output

In this Bite you test a function that prints to stdout. Check out pytest's Capturing of the stdout/stderr output how …

capfd capsys list comprehensions

pytest stdout


Bite 251. Introducing Pandas Series

Let's get started with Pandas! In case you are not aware of who, or what, pandas is, pandas is an …

pandas series string module



Bite 252. Let's play with Pandas Series

In Bite 251 we looked at creating some simple pandas Series. In this Bite we continue where we left off …

numpy pandas series

slicing type hinting


Bite 254. Global vs local variables

This Bite is to illustrate scoping. You will sum numbers while keeping track of number of hundreds in a global …

global sum 3.25⚬⚬⚬


Bite 257. Extract users dict from a multiline string

A quick Bite to practice some string parsing extracting a users dict from a password file. Complete get_users is how …

dict string parsing 3.57⚬⚬⚬⚬


Bite 262. GC content

The DNA of all organsims consists of the letters (bases) A, C, T and G. Every organism has a different …

bioinformatics collections 2.44⚬⚬


Bite 270. Most frequent digit in number

Given an integer number, find the most frequent digit in it. Examples: 1998 -> two 9's, one 1, one 8 …

Counter counting numbers



Bite 278. Major and minor numbers

You are given a list of integers. Write code to find the majority and minorty numbers in that list. Definition: …

collections max min



Bite 279. Armstrong numbers

In number theory there are many interesting numbers - eg. Armstrong numbers, Happy numbers, Meertens numbers, just to name a …

algorithms numbers 3.29⚬⚬⚬


Bite 283. Like there's no tomorrow?

Ever have difficulty remembering what today's date is? How about tomorrow's? I know I do...  Help me out by completing …

datetime 4.0⚬⚬⚬⚬


Bite 288. Smallest number

Write a function that accepts a list of digits and returns the smallest number that can be created by combining …

numbers 3.0⚬⚬⚬


Bite 289. Round to next number

Write a function that accepts a number and a multiple, then rounds the number towards the next multiple. Examples:   Number …

math 3.2⚬⚬⚬


Bite 293. N digit numbers

Write a function that accepts a list of numbers and converts them into n digit integers. Examples:   n_digit_numbers([1, 2, 3], 2)  …

numbers 6.33⚬⚬⚬⚬⚬⚬


Bite 295. Join lists

Write a function that accepts a list of lists and joins them with a separator character, therefore flattening and separating.   …

iteration joining list



Bite 314. Print names to columns

In this Bite you will use the modulo operation. You are presented with a function signature that receives a list …

f-strings modulo print



Bite 317. Pickling objects

In this Bite you will load (deserialize) and dump (serialize) a data structure from / to a pickle file which …

data wrangling pickle serialization



Bite 318. Decode base64 encoded data

In this Bite you are going to decode some Base64 encoded csv data. This is what the encoded data looks …

base64 decode encode



Bite 319. Identity and equality

Identity and equality are two important concepts in Python. Please correct the mistakes in the Car class (marked with # …

equality integer caching staticmethod



Bite 322. Reading progress

Happy New Year! How many books do you aim to read this year? In this Bite you will complete ontrack_reading …

datetime numbers 3.25⚬⚬⚬


Bite 323. Iterables intersection

In this bite we are going to work on coding a function intersection() that searches the common elements across its …

functools set operations 4.25⚬⚬⚬⚬


Bite 324. Pretty string

Write a function that returns a neatly formatted string representation of a python object. As you might have guessed, there …

pprint 2.0⚬⚬


Bite 336. FastAPI Hello World

Welcome to this FastAPI learning path. In the next 10 Bites you will write a simple API to track food …

FastAPI freebie 2.0⚬⚬


Bite 337. A little detour: Pydantic

Pydantic is an awesome library to do data validation and settings management using python type annotations. FastAPI is a heavy …

FastAPI freebie Pydantic



Bite 347. Which words can you type with one hand?

In this Bite you will write a function that takes a word and determines if it can be written with …

comparison enum set


Bite 353. Transform a Script Into a Command Line Interface (CLI)

There are several Python frameworks to create CLIs, check out this overview of CLI framework options.  In this Bite we …

command line Typer


Bite 355. Create Your First Typer Command Line Interface (CLI) Application

In the previous Bites, you have successfully transformed an existing script into a CLI using In this Bite, you …

command line Typer


Bite 357. Implement your First Subcommands and Command Groups

In the previous Bite, you learned how to create an application and added several commands for that app. Now, let's …

command line Typer


Bite 360. Add a progress bar to Your Command Line Interface (CLI)

In this Bite, you will create a simplistic CLI application with a simple progress bar. Refer to the progress bar …

command line rich Typer


Bite Tags User rated
More info /

Bite 3. Word Values

Find the dictionary word with the highest value using Scrabble rules. There are three tasks to complete for this Bite: Finish …

freebie max Scrabble



Bite 4. Top 10 PyBites tags

In this Bite you will find the top ten tags found in the PyBites blog XML feed (e.g. Python, Flask, Django, …

Counter xml 4.81⚬⚬⚬⚬⚬


Bite 6. PyBites Die Hard

Given a listing of files for our community branch, determine: - Who opened the most pull requests (excluding PyBites)? - …

Counter file processing generators



Bite 7. Parsing dates from logs

In this Bite we will look at this short server log, finding the first and last system shutdown events: INFO 2014-07-03T23:27:51 …

datetime file processing 5.7⚬⚬⚬⚬⚬⚬


Bite 9. Palindromes

Write a function to determine if a word or phrase is a palindrome. Then write a second function to receive …

algorithms list comprehensions max



Bite 10. Practice exceptions

In this Bite you'll learn to catch and raise Python exceptions. Write a simple division function meeting the following requirements: …

exception handling raise 2.92⚬⚬⚬


Bite 12. Write a user validation function

Create a function that takes a username and checks for a valid user: 1. The username is in USERS 2. The …

classes exception handling namedtuple



Bite 13. Convert dict to namedtuple/json

Write a function to convert the given blog dict to a namedtuple Write a second function to convert the resulting …

dict json namedtuple



Bite 14. Generate a table of n sequences

Write a function that receives one or more sequences. The sequences are already defined for you. The function should return …

generators zip 5.0⚬⚬⚬⚬⚬


Bite 17. Form teams from a group of friends

Write a function called friends_teams that takes a list of friends, a team_size (type int, default=2) and order_does_matter (type bool, …

itertools 3.55⚬⚬⚬⚬


Bite 18. Find the most common word

Write a function that returns the most common (non stop)word in this Harry Potter text.Make sure you convert to lowercase, …

Counter data analysis list comprehensions



Bite 22. Write a decorator with argument

Write a decorator called make_html that wraps text inside one or more html tags. As shown in the tests decorating …

decorators 5.71⚬⚬⚬⚬⚬⚬


Bite 25. No promo twice, keep state in a class

In this bite a real world scenario: PyBites has a growing set of Bites and gives away promos. They choose …

classes exception handling properties



Bite 27. Parse omdb movie json data

Working with APIs is very common these days and lucky for us they increasingly return JSON (over XML). We saved …

APIs glob json

movie data


Bite 28. Converting date strings to datetimes

In this Bite you are provided with a list of publish dates of all our PyBites blog posts. They are …

Counter datetime findall



Bite 30. Movie data analysis

In this Bite we are going to parse a csv movie dataset to identify the directors with the highest rated …

data analysis defaultdict freebie

mean movie data namedtuple sorting


Bite 33. Transpose a data structure

Sometimes you need to restructure a nested data structure. For example you can convert a dict in a list of …

dict zip 4.22⚬⚬⚬⚬


Bite 35. Having fun with heapq

In this Bite you are provided with 3 data structures: a list of ints, a list of datetimes, and a …

datetime heapq 2.82⚬⚬⚬


Bite 36. Having fun with *args and **kwargs

Write a function called get_profile that takes:a required name,a required age,one or more optional sports (args),one or more optional awards …

args function arguments kwargs



Bite 39. Calculate the total duration of a course

In this Bite you read in a text file with course times (MM:SS) per video. You extract these and calculate …

datetime findall numbers



Bite 41. Write a login_required decorator

If you worked with Flask or Django you must have seen routes being decorated to enforce authentication.In this Bite you …

decorators functools 3.83⚬⚬⚬⚬


Bite 47. Write a new password field validator

You know these Create a new password forms? They do a lot of checks to make sure you make a …

re string module 3.89⚬⚬⚬⚬


Bite 48. Make a bar chart of new Safari books

Some time ago we made a little Slack bot to post new titles added to Safari to Slack. And luckily …

bar chart data analysis 4.6⚬⚬⚬⚬⚬


Bite 49. Scrape Packt's html with BeautifulSoup

In this Bite you will parse Packt's free learning ebook site extracting the html for the daily free ebook: As …

beautifulsoup namedtuple requests



Bite 51. When does Python 2 die on Planet Miller?

Imagine you landed on Planet Miller (from the movie Interstellar) where 1 hour takes 7 Earth years (known as the …

datetime 3.57⚬⚬⚬⚬


Bite 57. Create a simple calculator that receives command line arguments

In this Bite you write a simple calculator that can perform additions (add), subtractions (sub), multiplications (mul) and divisions (div).You …

argparse functools reduce



Bite 59. Create a multiplication table class of variable length

Danny does not like rote learning (nor do we!). He is asked to remember multiplication tables of considerable size 😭Can …

classes dunder methods exception handling



Bite 60. Create a deck of Uno cards

In this Bite you will create a deck of Uno cards. Here is the equipment requirement as described here - …

list list comprehensions namedtuple



Bite 62. Data structures matter - speed up your Python code

In this Bite we provide you with 5 functions which you have to try to make faster. Some require different …

data structures performance 3.22⚬⚬⚬


Bite 65. Get all valid dictionary words for a draw of letters

This Bite focusses on the use of itertools. To that extend you complete get_possible_dict_words and _get_permutations_draw to get all valid …

itertools Scrabble set



Bite 70. Create your own iterator

In this Bite you make an iterator called EggCreator by implementing the __iter__ and __next__ dunder methods (as dictated by …

iterators random 3.43⚬⚬⚬


Bite 71. Keep state in a class + make its instance callable

In this Bite you write a small class to keep track of the max score in a game. When called …

classes dunder methods 2.67⚬⚬⚬


Bite 72. Retrieve the right Ninja Belt based on score

As you have probably seen on the dashboard you can now gain Ninja Belts based on the amount of points …

itertools OrderedDict 4.2⚬⚬⚬⚬


Bite 73. Organize a meeting between timezones (pytz)

Help PyBites community friends find a reasonable common time to meet! Complete the function below receiving a UTC datetime and …

pytz timezones 5.88⚬⚬⚬⚬⚬⚬


Bite 78. Find programmers with common languages

Similar as last Bite we do another comparison of sequences exercise.Here is the deal: you are in charge of huge …

set set operations 2.89⚬⚬⚬


Bite 79. Parse a csv file and create a bar chart

We played a bit with the Slack API today and wow: our PyBites community is super international! We really enjoy …

bar chart community csv



Bite 81. Filter and order tweets by polarity values

In this Bite we collected some random tweets and populated a list of namedtuples of text and a polarity rating …

namedtuple TextBlob Twitter



Bite 82. Define a Score Enum and customize it adding methods

Starting Python 3.4 there is support for enumerations (not to confuse with the enumerate builtin). You can define a class …

classmethod enum __str__



Bite 84. Flatten lists recursively (Droste Bite)

Complete flatten that takes a list of lists (which can have lists ad infinitum) and flatten them into a one …

list recursion 4.38⚬⚬⚬⚬


Bite 86. Create a RGB-to-Hex converter

Designer Mary wants to convert her CSS from statements like background-color: rgb(128, 128, 0); to: background-color: #808000;.Don't worry, you don't …

string formatting 2.75⚬⚬⚬


Bite 87. Convert Decimal to Roman Numerals

Complete romanize that takes a decimal number and converts it to its Roman Numeral equivalent.If a non int or invalid …

numbers OrderedDict 3.83⚬⚬⚬⚬


Bite 89. Playing with lists and dicts

In this Bite you are presented with a us_state_abbrev dict and a states list. Complete the four methods in the …

data structures dict list



Bite 90. What South Park characters talk most?

Did we already tell you we love the collections module? In this Bite we combine its defaultdict and Counter data …

Counter csv data analysis

defaultdict requests


Bite 92. Humanize a datetime

In this Bite you will convert a timedelta object into something readable. We know: there are modules to do it, …

datetime namedtuple 5.44⚬⚬⚬⚬⚬


Bite 95. Subclass the dict built-in

In this Bite you will subclass the dict built-in to support a birthday dictionary. This dictionary takes names as keys …

classes inheritance 4.5⚬⚬⚬⚬


Bite 97. BeautifulSoup II - scrape US holidays

In this Bite we use BeautifulSoup to scrape US holidays from OfficeHolidays to make a lookup of holidays per month.Check …

beautifulsoup defaultdict dict



Bite 99. Write an infinite sequence generator

Write a generator that produces the sequence [1, 'A', 2, 'B', 3, 'C', ... 'X', 25, 'Y', 26, 'Z'] infinitely. …

generators itertools string module



Bite 111. Use the ipinfo API to lookup IP country

In this Bite you will use the requests library to make a GET request to the ipinfo service.Use IPINFO_URL and …

APIs json mock.patch



Bite 113. Filter words with non-ascii characters

In this Bite you extract words from a text that contain non-ascii characters. So Fichier non trouvé would return a …

all ascii ord



Bite 114. Implement a Color class with staticmethod

As the new junior developer, you have been charged with enhancing the Color class. Your task will be to implement …

hex __repr__ staticmethod

__str__ string module


Bite 116. List and filter files in a directory

In this Bite you complete get_files that receives a dirname and size_in_kb (note kb, not bytes). There are two things …

generators glob os module



Bite 118. List exercise: return first occurrence indices of duplicated words

In this Bite you are presented with a list of words. Loop through them and find all the words that …

counting list comprehensions set



Bite 119. Xmas tree generator

In this Bite you complete generate_xmas_tree that takes a rows arg (= height of the tree). For each row you …

default args join range

string formatting


Bite 120. Write a numbers validation decorator

Let's get some more practice with decorators ... in this Bite you will write a decorator that checks if input …

decorators 2.82⚬⚬⚬


Bite 122. Check if two words are anagrams

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using …

anagram string matching 2.5⚬⚬


Bite 123. Find the user with most friends

In this Bite you are presented with a users dict of keys=id's and values=usernames and a friendships list of user …

defaultdict looping sorting



Bite 125. Get the most recommended books

The Tim Ferriss Show is full of wisdom and inspiration. It can also quickly fill up your book shelves because …

beautifulsoup Counter default args

list comprehensions requests


Bite 127. Return the right ordinal suffix for a number

In this Bite you complete a function that takes an int and returns it appended with the right suffix: 1 …

dict modulo numbers

string manipulation


Bite 129. Analyze Stock Data

In this Bite we will answer some questions about stocks, using some JSON data obtained from the awesome Mockeroo fake …

counting data analysis json

requests sorting string manipulation


Bite 132. Find the word with the most vowels

Finish the get_word_max_vowels function below that takes a text string as its input argument and returns a tuple of the …

counting lambda list comprehensions

string matching


Bite 135. Sort a list of book objects

In this Bite you are going to look at a list of Book namedtuples and sort them by various criteria. …

attrgetter datetime lambda

list namedtuple operator sorting


Bite 137. Gourmets' Nightmare

Many gourmets struggle to find the perfect pairing of wines and cheeses. A number of considerations are relevant, each of …

Counter intersection operator



Bite 138. OOP fun at the Zoo

Finish the Animal class below adding one or more class variables and a classmethod so that the following code: dog …

classes classmethod itertools



Bite 140. PyBites First Pandas Bite

This is a Pandas proof-of-concept Bite. We just added the library to our platform! For this Bite you find out …

csv data analysis pandas



Bite 141. Primitive date format inferrer

Complete the get_dates method given the following: a listing of date strings in unknown date format and an enum class …

classmethod datetime enum

exception handling


Bite 142. Exception Handling: Calculate the Winning Player

Complete the two functions below: calculate_score takes a list of dice roll scores and returns the total score only taking …

exception handling namedtuple numbers



Bite 144. Calculate the Number of Months Passed

Some more fun working with dates! In this Bite you will calculate the number of months between the fixed START_DATE …

datetime dateutil exception handling



Bite 146. Rhombus generator

In this Bite you make a generator of rhombus shapes. You will complete gen_rhombus that when called like this: gen …

format f-strings string formatting



Bite 147. 100 WEEKDays of Code Date Range

Doing a #100DaysOfCode can be challenging, and some of it is because you dedicate to do it on workdays AND …

datetime dateutil 3.86⚬⚬⚬⚬


Bite 148. Print Car Data Grouped by Manufacturer

In this Bite you are presented with a list of car (manufacturer, model) tuples. Group the data by manufacturer printing …

data structures itertools operator



Bite 150. Turn messy CSV into JSON

At the 1 year mark of our platform here is Bite 150! In this Bite you are presented with some …

csv json pandas

re string manipulation


Bite 151. Contemporary Composers

You are given a list of operas and a list of composers. For two given composers find operas (where one …

datetime dict exception handling

generators namedtuple


Bite 154. Write your own Data Class

As you might have noticed we are now on Python 3.7 so time for a Bite on data classes which …

dataclasses data structures hashable

sorting type hinting


Bite 155. Split a string by spaces or quoted text

Another text manipulation Bite. Code split_words_and_quoted_text that takes a text string and splits it by space, except words that are …

split string manipulation 4.22⚬⚬⚬⚬


Bite 156. Make an index of story characters

You know the index at the end of a book where you look up which pages people and terms occur? …

collections defaultdict enumerate

sorting string matching


Bite 157. Filter out accented characters

Another unicode Bite. Given some non-English text with accents (á, é, í, used in Spanish for example), extract the accented …

string matching unicode 3.25⚬⚬⚬


Bite 159. Create a simple calculator

In this Bite you will create a simple calculator. It takes a string of num1 operator num2 which you convert …

exception handling numbers operator



Bite 162. Vertically align output of counters

In this Bite you are tasked with "physically" aligning the number of comments on a webpage. For some reason you …

string formatting 1.88⚬⚬


Bite 163. Which packages were upgraded?

In this Bite you compare a list of packages (aka requirement.txt) from before vs. after (pip) upgrade. Check the TESTS …

comparison dict numbers

string manipulation


Bite 166. Complete a tox ini file parser class

The INI file format is an informal standard for configuration files for some platforms or software. (Wikipedia).In this Bite you …

classes configparser properties

string matching string parsing tox


Bite 173. Set up future notifications

Let's do another datetime processing Bite. Complete add_todo below that converts time units to future timestamps.Here is how it works …

datetime findall f-strings



Bite 175. Find missing dates

Complete get_misssing_dates that takes an (unordered) sequence of objects. It should determine what the start and end date of …

datetime dateutil pandas



Bite 178. Parse PyBites blog git commit log

In this Bite we want to figure out how active we've been on our blog. To start our data analysis …

Counter data analysis datetime

dateutil string parsing


Bite 182. Parse a bunch of quotes from HTML

Let's get some inspiration. Below you find the simplified HTML of Richard Branson's My top 10 quotes on living life …

dict regular expressions string manipulation

string parsing


Bite 184. Analyze some Bite stats data

In this Bite we will look at some Bite stats logs (usernames have been anonymized!): $ head -5 bite_output_log.txt bite,user,completed …

Counter csv data analysis



Bite 185. Create a simple spelling suggester

In this Bite you will write a simple spelling corrector. Complete suggest_word that receives a misspelled word argument and returns …

difflib SequenceMatcher string matching



Bite 186. Calculate number of books to have read at date ...

For this Bite you are asked to start working on a reading goal feature for PyBites My Reading List.Code up …

datetime dateutil exception handling



Bite 187. Actor/actress age at movie release

Ever wondered how old an actor/actress was in a particular movie? In this Bite you will write some code to …

dataclasses dateutil f-strings



Bite 190. Parse income distribution from Latin America XML

In this Bite you are going to parse some Latin American countries in xml, specifically the output of which …

data analysis defaultdict xml



Bite 191. Starwars character with highest BMI

In this Bite you will parse a multiline string of SWAPI Starwars characters. Calculate the BMI of each character returning …

max operator string manipulation

tuple unpacking


Bite 193. Most upvoted StackOverflow Python questions

In this Bite you parse a copy of StackOverflow Python questions which we cached here Retrieve + parse this URL …

beautifulsoup requests sorting

string matching web scraping


Bite 194. Add caching to a Fibonacci function

In this Bite you will learn about memoization: In computing, memoization or memoisation is an optimization technique used primarily to …

fibonacci functools lru_cache



Bite 195. Analyze NBA Data with sqlite3

In this Bite you are going to use sqlite3! We loaded some NBA data into a players DB table: Complete …

data analysis databases SQL



Bite 197. What date is Mother's Day celebrated?

It's the 12th of May 2019 when we write this so happy Mother's Day! In many countries this special day …

datetime dateutil 2.0⚬⚬


Bite 199. Multiple inheritance (__mro__)

Implement the following class structure: print(Child.__mro__): (<class '__main__.Child'>, <class '__main__.Father'>, <class '__main__.Mother'>, <class '__main__.Person'>, <class 'object'>) Each class has the …

classes inheritance __mro__

multiple inheritance


Bite 201. Call a Cisco Nexus 9k device

Cisco Nexus 9k devices is one of the first network equipment with comprehensive API programmatic access from Cisco. API capabilities …

networking requests 9.0⚬⚬⚬⚬⚬⚬⚬⚬⚬


Bite 202. Analyze some Bite stats data - part II

In this Bite you will analyze complexity levels of our first 200 Bites of Py exercises. We loaded this CSV …

csv data analysis sorting



Bite 203. Type hinting practice

It's time for some type hinting! For this bite, you have been provided a very simple Employee class object. I …

classes dataclasses type hinting



Bite 205. Female speakers @ Pycon US

After our Code Challenge 62 / Alicante PyDay last week, we thought it would be nice to branch off a …

beautifulsoup counting data wrangling



Bite 206. Calculate and evenly split the bill

Three old friends Bob, Mary, and Alice meet at PyCon and decide to go out to dinner together. They have …

Decimal numbers rounding



Bite 212. Suppressing exceptions

Ever wanted to suppress an exception? Check out Python's contextlib module. In this Bite you refactor sum_numbers which has some …

context managers exception handling 2.82⚬⚬⚬


Bite 217. Capture stdout

Sometimes you need to capture stdout in your script. Python makes it easy with contextlib's redirect_stdout. In this Bite you …

context managers StringIO 3.43⚬⚬⚬


Bite 219. Bite notification planner

Another real world use case. When we added notifications to our learning paths, we gave the user the option to …

datetime generators 3.17⚬⚬⚬


Bite 221. Parse best selling lists using the NY Times API

In this Bite you are going to parse NY Times Best Seller Lists using The New York Times Developer Network. …

APIs json mock



Bite 222. Split an iterable in groups of size n

In this Bite you will complete the group function that receives an iterable and splits it up in n groups. …

generators iterators itertools



Bite 223. Unix file permissions

Each file and directory in Unix has its permissions broken down into owner, group and other (world) attributes, see here. …

dict list comprehensions string manipulation



Bite 226. Get top titles from

There is a new Python news aggregator in town! Check it out here. In this Bite you will parse it! …

beautifulsoup namedtuple news

requests sorting string parsing web scraping


Bite 227. Convert Warcraft json data to csv

In this Bite we are going to convert some Warcraft Mount JSON data to csv. Here are the steps to …

csv exception handling json



Bite 228. Create a Gravatar URL

In this Bite you will generate a Gravatar URL, e.g.;=g&d;=robohash.In this URL 5b13356d467af88631503c27a3d0e0cf is a hash of a lowercase …

gravatar hashlib string formatting



Bite 230. Thumbs up for operator overloading

In this Bite we learn a bit of operator overloading. Finish the Thumbs class that returns an amount of thumbs …

classes dunder methods emojis

exception handling operator overloading


Bite 232. Analyze gold prices

In this Bite you will analyze how the price of gold evolved over the years 1950-2018. We loaded the gold …

comparison data analysis looping

pandas sorting string parsing


Bite 233. Make a zipfile of the latest log files

You added some monitoring the other day writing log files to a directory. In this Bite you will zip up …

datetime os module pathlib



Bite 234. Capitalize sentences

In this Bite you are going to capitalize sentences in a block of lowercased text. Correct grammar dictates that each …

regular expressions string manipulation string matching

string parsing


Bite 235. Which Bite has the fastest tests?

In this Bite you will parse a pytest output summary, calculating the Bite that has the fastest average tests. Log …

sorting string parsing type casting



Bite 236. User experience matters! Suggest matching files

We love it when CLI or web apps take the extra mile to be more user friendly. In this Bite …

difflib files pathlib



Bite 239. Test FizzBuzz

In our second Test Bite you will write tests for FizzBuzz. Refer to the "Code to Test" tab, then start …

fizzbuzz pytest 3.1⚬⚬⚬


Bite 243. Test code that parses JSON and IP ranges

Another Test Bite, we ❤️them 😁- today you will write tests for IPv4Network (ipaddress module) and dataclass objects 💪. Check …

dataclasses ipaddress json



Bite 244. Make mutpy's output more digestible

Another real world scenario. When we started using MutPy for our test Bites, we quickly learned that the verbose output …

data wrangling looping mutpy

string matching string parsing


Bite 245. Xmas Tree 2.0

In this Bite you have to complete generate_improved_xmas_tree that takes a rows arg (= number of rows with leafs). For …

range string formatting 3.0⚬⚬⚬


Bite 247. Mocking a standard library function

In this Bite you will mock out a function of the standard library, more specifically random.sample. We wrote a small …

mock.patch pytest random



Bite 253. More Pandas Series Practice

In Bite 251 and Bite 252 we looked at creating some simple pandas Series and then we looked at how …

math pandas series



Bite 255. Codon Usage

The genetic code of all organisms uses a 3 base (codon), 4 letter encoding (A, G, C or T/U) to …

bioinformatics collections textwrap



Bite 256. Scrape PyCon events

In this Bite, we want you to scrape PyCon 2019 data. The provided source via _get_pycon_data contains data for years …

beautifulsoup data analysis json

namedtuple pycon requests web scraping


Bite 258. What the flux?

One of the benefits of accounting is being able to see the financial position of a company at a point …

finance math pandas



Bite 259. Reverse complement

In the majority of organisms, the genetic code is encoded in a double helical DNA with each of both strands …

bioinformatics string manipulation translate



Bite 261. Visit all PyCons in Europe

In Bite 256 you scraped data on 2019 PyCons. Now it's time to go there! In this Bite you enrich …

data analysis dataclasses itertools



Bite 263. Count the number of islands in a grid

You are tasked with counting the amount of islands in a 2D matrix / grid. Islands are represented by 1s, …

algorithms looping string



Bite 264. Clamy Fernet

In this bite, you are going to get familiar with symmetrical encryption using the cryptography module and its Fernet class. …

cryptography dataclasses encode

encryption fernet typing


Bite 265. Optimal fund raising

Here is another classic algorithm problem wrapped in a Bite. Enjoy! A mayor in a remote mountain village faced an …

algorithms looping math



Bite 267. Measure the size of an island

In this algorithm Bite, the challenge is to measure the size of an island in the ocean, based on the …

algorithms looping math



Bite 271. Get all class names from a module

In this Bite you will write a function to get all the class names from the module passed in. Only …

inspect list comprehensions 2.5⚬⚬


Bite 272. Find common words

Given two sentences that each contains words in case insensitive way, you have to check the common case insensitive words …

algorithms set operations string matching



Bite 274. Number conversion problem

Recursion in computer science is a method of solving a problem where the solution depends on solutions to smaller instances …

algorithms numbers recursion



Bite 275. Get the most common email domains

In this Bite you will process a list of emails determining what are the most common domain names. You only …

Counter requests set

string parsing web scraping


Bite 284. Pascal triangle

A Pascal triangle is a triangular array of integers constructed with the following characteristics: 1. The first row consists of …

algorithms Pascal 6.33⚬⚬⚬⚬⚬⚬


Bite 285. Nested List Extraction

Sometimes dealing with data can be a real struggle. Sometimes it's delivered in a undesirable format that you have no …

data structures string parsing 5.67⚬⚬⚬⚬⚬⚬


Bite 286. Decompress

Write a function, called decompress(), that accepts a string and a dictionary as input. The dictionary maps special character strings …

recursion string manipulation 4.0⚬⚬⚬⚬


Bite 287. Sum indices

Write a function that accepts a list of strings and returns the total of the indices of the items.    …

looping sum 3.0⚬⚬⚬


Bite 290. Class Rosters Data Conversion

You have been given a comma-delimited .csv file containing class roster data. Your task is to re-format this data so …

csv string parsing tuple unpacking



Bite 291. Find the fastest speech

In this Bite you will parse an SRT (SubRip Subtitle file / video captions or subtitles).  This is a snippet …

datetime sorting string manipulation



Bite 296. Jagged list

Write a function that takes an irregular shaped list of lists and makes it symmetrical by adding a fillvalue to each …

iteration itertools list



Bite 298. Fasta to 2-Line Fasta

A very simple format to store biological sequence data is the (multi-)FASTA format. The first line of each record starts …

bioinformatics biopython 4.5⚬⚬⚬⚬