Home » 46 Simple Python Exercises : part 2

46 Simple Python Exercises : part 2

Oracle Java Certification
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Programmer II [1Z0-816] Practice Tests
Spring Framework Basics Video Course
Java SE 11 Developer (Upgrade) [1Z0-817]
1 Year Subscription

This was an original idea by generated by Torbjoern Lager – link I checked did not work but these are great ideas for learning python, you are supposed to come up with solutions to these exercises.

There are many solutions already out there especially on github

Exercise 24 – Third Person Transformer

The third person singular verb form in English is distinguished by the suffix -s, which is added to the stem of the infinitive form: run -> runs. A simple set of rules can be given as follows:

If the verb ends in y, remove it and add ies If the verb ends in o, ch, s, sh, x or z, add es By default just add s

Your task in this exercise is to define a function make_3sg_form() which given a verb in infinitive form returns its third person singular form.

Test your function with words like try, brush, run and fix. Note however that the rules must be regarded as heuristic, in the sense that you must not expect them to work for all cases.

Tip: Check out the string method endswith().

Exercise 25 – Present Participle Form

In English, the present participle is formed by adding the suffix -ing to the infinite form: go -> going. A simple set of heuristic rules can be given as follows:

If the verb ends in e, drop the e and add ing (if not exception: be, see, flee, knee, etc.)

If the verb ends in ie, change ie to y and add ing
For words consisting of consonant-vowel-consonant, double the final letter before adding ing
By default just add ing

Your task in this exercise is to define a function make_ing_form() which given a verb in infinitive form returns its present participle form.

Test your function with words such as lie, see, move and hug. However, you must not expect such simple rules to work for all cases.

Exercise 26 – Reduce or Max

Using the higher order function reduce(), write a function max_in_list() that takes a list of numbers and returns the largest one.

Then ask yourself: why define and call a new function, when I can just as well call the reduce() function directly?

Exercise 27 – Mapping Words

Write a program that maps a list of words into a list of integers representing the lengths of the corresponding words.

Write it in three different ways: 1) using a for-loop, 2) using the higher order function map(), and 3) using list comprehensions.

Exercise 28 – Find Longest Word (Higher order functions)

Write a function find_longest_word() that takes a list of words and returns the length of the longest one. Use only higher order functions.

Exercise 29 – Filter Long Words (Higher order functions)

Using the higher order function filter(), define a function filter_long_words() that takes a list of words and an integer n and returns the list of words that are longer than n.

Exercise 30 -Translator (Higher order functions)

Represent a small bilingual lexicon as a Python dictionary in the following fashion {“merry”:”god”, “christmas”:”jul”, “and”:”och”, “happy”:gott”, “new”:”nytt”, “year”:”år”} and use it to translate your Christmas cards from English into Swedish.

Use the higher order function map() to write a function translate() that takes a list of English words and returns a list of Swedish words.

Exercise 31 – Student becomes more like master

Implement the higher order functions map(), filter() and reduce(). (They are built-in but writing them yourself may be a good exercise.)

Exercise 32 – Palindrome in File

Write a version of a palindrome recogniser that accepts a file name from the user, reads each line, and prints the line to the screen if it is a palindrome.

Exercise 33 – Semordnilap

According to Wikipedia, a semordnilap is a word or phrase that spells a different word or phrase backwards. (“Semordnilap” is itself “palindromes” spelled backwards.) Write a semordnilap recogniser that accepts a file name (pointing to a list of words) from the user and finds and prints all pairs of words that are semordnilaps to the screen.

For example, if “stressed” and “desserts” is part of the word list, the the output should include the pair “stressed desserts”.

Note, by the way, that each pair by itself forms a palindrome!

Exercise 34- Terminal Character Frequency

Write a procedure char_freq_table() that, when run in a terminal, accepts a file name from the user, builds a frequency listing of the characters contained in the file, and prints a sorted and nicely formatted character frequency table to the screen.

Exercise 35 – International Civil Aviation Organization

The International Civil Aviation Organization (ICAO) alphabet assigns code words to the letters of the English alphabet acrophonically (Alfa for A, Bravo for B, etc.) so that critical combinations of letters (and numbers) can be pronounced and understood by those who transmit and receive voice messages by radio or telephone regardless of their native language, especially when the safety of navigation or persons is essential.

Here is a Python dictionary covering one version of the ICAO alphabet:

d = {‘a':'alfa', ‘b':'bravo', ‘c':'charlie', ‘d':'delta', ‘e':'echo', ‘f':'foxtrot', ‘g':'golf', ‘h':'hotel', ‘i':'india', ‘j':'juliett', ‘k':'kilo', ‘l':'lima', ‘m':'mike', ‘n':'november', ‘o':'oscar', ‘p':'papa', ‘q':'quebec', ‘r':'romeo', ‘s':'sierra', ‘t':'tango', ‘u':'uniform', ‘v':'victor', ‘w':'whiskey', ‘x':'x-ray', ‘y':'yankee', ‘z':'zulu'}

Your task in this exercise is to write a procedure speak_ICAO() able to translate any text (i.e. any string) into spoken ICAO words. You need to import at least two libraries: os and time.

On a mac, you have access to the system TTS (Text-To-Speech) as follows: os.system(‘say ‘ + msg), where msg is the string to be spoken. (Under UNIX/Linux and Windows, something similar might exist.)

Apart from the text to be spoken, your procedure also needs to accept two additional parameters: a float indicating the length of the pause between each spoken ICAO word, and a float indicating the length of the pause between each word spoken.

Exercise 36 – Hapax Legomenon

A hapax legomenon (often abbreviated to hapax) is a word which occurs only once in either the written record of a language, the works of an author, or in a single text.

Define a function that given the file name of a text will return all its hapaxes. Make sure your program ignores capitalization.

Exercise 37 – Text Novice

Write a program that given a text file will create a new text file in which all the lines from the original file are numbered from 1 to n (where n is the number of lines in the file).

Exercise 38 – Average Words in File

Write a program that will calculate the average word length of a text stored in a file (i.e the sum of all the lengths of the word tokens in the text, divided by the number of word tokens).

Exercise 39 – Guess The Number

Write a program able to play the “Guess the number”-game, where the number to be guessed is randomly chosen between 1 and 20. (Source: http://inventwithpython.com) This is how it should work when run in a terminal:

<<< import guess_number
Hello! What is your name?
Torbjörn
Well, Torbjörn, I am thinking of a number between 1 and 20.
Take a guess.
10
Your guess is too low.
Take a guess.
15
Your guess is too low.
Take a guess.
18
Good job, Torbjörn! You guessed my number in 3 guesses!

Exercise 40 – Anagram

An anagram is a type of word play, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once; e.g., orchestra = carthorse, A decimal point = I'm a dot in place.

Write a Python program that, when started 1) randomly picks a word w from given list of words, 2) randomly permutes w (thus creating an anagram of w), 3) presents the anagram to the user, and 4) enters an interactive loop in which the user is invited to guess the original word. It may be a good idea to work with (say) colour words only.

The interaction with the program may look like so:

import anagram

Colour word anagram: onwbr
Guess the colour word!
black
Guess the colour word!
brown
Correct!

Exercise 41 – Lingo

In a game of Lingo, there is a hidden word, five characters long.

The object of the game is to find this word by guessing, and in return receive two kinds of clues: 1) the characters that are fully correct, with respect to identity as well as to position, and 2) the characters that are indeed present in the word, but which are placed in the wrong position.

Write a program with which one can play Lingo. Use square brackets to mark characters correct in the sense of 1), and ordinary parentheses to mark characters correct in the sense of 2). Assuming, for example, that the program conceals the word “tiger”, you should be able to interact with it in the following way:

import lingo

snake
Clue: snak(e)
fiest
Clue: fis(t)
times
Clue: [t][i]m[e]s
tiger
Clue: [t][i][g][e][r]

Exercise 42- Sentence Splitter

A sentence splitter is a program capable of splitting a text into sentences. The standard set of heuristics for sentence splitting includes (but isn't limited to) the following rules:

Sentence boundaries occur at one of “.” (periods), “?” or “!”, except that

Periods followed by whitespace followed by a lower case letter are not sentence boundaries.

Periods followed by a digit with no intervening whitespace are not sentence boundaries.

Periods followed by whitespace and then an upper case letter, but preceded by any of a short list of titles are not sentence boundaries. Sample titles include Mr., Mrs., Dr., and so on.

Periods internal to a sequence of letters with no adjacent whitespace are not sentence boundaries (for example, www.aptex.com, or e.g).

Periods followed by certain kinds of punctuation (notably comma and more periods) are probably not sentence boundaries.

Your task here is to write a program that given the name of a text file is able to write its content with each sentence on a separate line.

Test your program with the following short text: Mr. Smith bought cheapsite.com for 1.5 million dollars, i.e. he paid a lot for it. Did he mind? Adam Jones Jr. thinks he didn't. In any case, this isn't true… Well, with a probability of .9 it isn't.

The result should be:

Mr. Smith bought cheapsite.com for 1.5 million dollars, i.e. he paid a lot for it.
Did he mind?
Adam Jones Jr. thinks he didn't.
In any case, this isn't true…
Well, with a probability of .9 it isn't.

Exercise 43 – Harder Anagram

An anagram is a type of word play, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once; e.g., orchestra = carthorse.

Using the word list at http://www.puzzlers.org/pub/wordlists/unixdict.txt, write a program that finds the sets of words that share the same characters that contain the most words in them.

Exercise 44 – Balance Brackets

Your task in this exercise is as follows:

Generate a string with N opening brackets (“[“) and N closing brackets (“]”), in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples:

[] OK ] [ NOT OK

[][] OK ] [] [ NOT OK
[[][]] OK []] [[] NOT OK

Exercise 45 – Pokemon Brainstorm

A certain childrens game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word.

Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the game. For example, with “animals” as the category,

Child 1: dog
Child 2: goldfish
Child 1: hippopotamus
Child 2: snake … Your task in this exercise is as follows: Take the following selection of 70 English Pokemon names (extracted from Wikipedia's list of Pokemon) and generate the/a sequence with the highest possible number of Pokemon names where the subsequent name starts with the final letter of the preceding name. No Pokemon name is to be repeated.

audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon cresselia croagunk darmanitan deino emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2 porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask

Exercise 46 – Alternade

An alternade is a word in which its letters, taken alternatively in a strict sequence, and used in the same order as the original word, make up at least two other words.

All letters must be used, but the smaller words are not necessarily of the same length. For example, a word with seven letters where every second letter is used will produce a four-letter word and a three-letter word. Here are two examples:

“board”: makes “bad” and “or”.

“waists”: makes “wit” and “ass”.

Using the word list at http://www.puzzlers.org/pub/wordlists/unixdict.txt, write a program that goes through each word in the list and tries to make two smaller words using every second letter. The smaller words must also be members of the list. Print the words to the screen in the above fashion.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More