1.01 renamed exercise folder for correct sorting 2 years ago
1.02 renamed exercise folder for correct sorting 2 years ago
1.03 renamed exercise folder for correct sorting 2 years ago
1.04 renamed exercise folder for correct sorting 2 years ago
1.05 renamed exercise folder for correct sorting 2 years ago
1.06 renamed exercise folder for correct sorting 2 years ago
1.07 renamed exercise folder for correct sorting 2 years ago
1.08 renamed exercise folder for correct sorting 2 years ago
1.09 renamed exercise folder for correct sorting 2 years ago
1.10 Completed 1.10 2 years ago
1.11 Completed 1.11 2 years ago
1.12 Completed 1.12 2 years ago
1.13 Completed 1.13 2 years ago
1.14 Completed 1.14 2 years ago
1.15 Completed 1.15 2 years ago
1.16 Completed 1.16 2 years ago
1.17 Completed 1.17 2 years ago
1.19 Completed 1.19 2 years ago
1.20 Completed 1.20 2 years ago
1.21 Completed 1.21 2 years ago
1.22 Completed 1.22 2 years ago
1.26 Completed 1.26 2 years ago
1.27 Completed 1.27 2 years ago
1.28 Completed 1.28 2 years ago
.gitignore Initial Commit 2 years ago
README.md added ReadMe 2 years ago
README.md

Basic Python Syntax

This collection of exercises are for getting used to Python syntax and Pythons built-in types.

Exercise 1.1 - FizzBuzz

Kattis problem https://open.kattis.com/problems/fizzbuzz

Övning 1.2 - Multiplication table

Write a program that performs calculation of the multiplication table for a number inputted by the user. Use a for-loop in your implementation. Running the program should look like this:

This program prints out a multiplication table.
Enter a number: 7
0 * 7 = 0
1 * 7 = 7
2 * 7 = 14
3 * 7 = 21
4 * 7 = 28
5 * 7 = 35
6 * 7 = 42
7 * 7 = 49
8 * 7 = 56
9 * 7 = 63

Exercise 1.3 - Guess the Number

Implement a simple guessing game.

The rules for playing are:

  1. The program picks a random number from 1 up to 100.
  2. The player guesses a number.
  3. Depending on the guess, the program responds with one of three possible choices: (i) The guess was too high. (ii) The guess was too low. (iii) The guess was correct. 4. and 3. repeats until the guess is correct.
  4. The program presents how many guesses were used, thereafter the program terminates.

Extra challenge: Ask the user before the game program finishes if the user like to play again. Y(es)/N(o). If the answer is Y, let the game start over. To make that happen you need another (outer) loop in your program.

Exercise 1. 4 - Calculator

This task is to implement a simple calculator dealing with the operations +, -, ·, /. That is, it should be possible to add, subtract, multiply or divide two integer numbers inputted by the user. The user interface should be a menu looking like this:

1. Enter two integers
2. Add
3. Subtract
4. Multiply
5. Divide
0. Exit
Your choice:

If you input an invalid choice,for example -1, then an error message shall show on the screen and the menu shall be shown again. A successful run of your program can look like this:

1. Enter two integers
2. Add
3. Subtract
4. Multiply
5. Divide
0. Exit
Your choice: -1
Input must be either 0,1,2,3,4 or 5.

1. Enter two integers
2. Add
3. Subtract
4. Multiply
5. Divide
0. Exit
Your choice : 1
Input first number : 20
Input second number : 34

1. Enter two integers
2. Add
3. Subtract
4. Multiply
5. Divide
0. Exit
Your choice : 2
The result is 54

1. Enter two integers
2. Add
3. Subtract
4. Multiply
5. Divide
0. Exit
Your choice : 0
Exiting ... Goodbye !

Functions

Exercise 1.5 - Pythagora's Theoreme

The Pythagoras’ Theorem for a right-angle triangle can be written as a2 + b2 = c2, where a and b are sides of the right angle and c is the hypotenuse. Write a function to compute the hypotenuse given sides a and b of the triangle. The result shall be returned as a number. Hint: You can use math.sqrt(num) or the ** operator to compute the square root of num.

Exercise 1.6 - Units and Tens

Define two functions unit(int_num) and ten(int_num) that picks up the ones digit and the tens digit in an integer number int_num. The functions shall return the picked digit as an integer number. Running the functions in the Python interpreter console should look like this:

>>> unit(123) 
3
>>> ten(123) 
2

Exercise 1.7 - Swap Units and tens

Define a function swap_units_and_tens(int_num) that swaps the order between the ones digit and the tens digit in an integer number using the two functions from the previous exercise. The function shall return the result as an integer number. Running the function in the Python interpreter console should look like this:

>>> swap_units_and_tens(123) 
132

Strings

Exercise 1.8 - Transform by using ASCII Code

Write a function of your own that transforms a lower case letter to an upper case. The function shall return a string containing one character. If the string contains a character that is not a lower case letter it should be returned as it is. You must not use any string methods, but you may use the built-in functions ord(char) and chr(num).

Hint! Inspect the ASCII table!

Exercise 1.9 - Count Vowels

Write a function count_vowels(string) that takes in a word as an argument and returns the total number of vowels (’a’, ’e’, ’i’, ’o’, ’u’) in the word. The function shall return the result as an integer number. Run example:

>>> count_vowels('elephant')
3
>>> count_vowels('apple')
2

Exercise 1.10 - Palindrome

Write a program that checks whether an inputted word is a palindrome or not. The program shall ask for a new word repeatedly until the user type quit. Run example:

Write a word: carrot
carrot is not a palindrome

Write a word: Mom
Mom is not a palindrome

Write a word: racecar
racecar is a palindrome

Write a word: quit
Exiting ...

Extra: See to that uppercase letters does not impact the result in your program. That means Racecar as well as racecar is a palindrome.

Lists and Tuples

##Exercise 1.11 - Add First end Last Element Define a function called add_first_and_last(num_list) that takes in a list of numbers and returns the sum of the first and last numbers. See to that the special cases when the list length is 0 or 1 are taken care of.

Run example:

>>> add_first_and_last([])
0
>>> add_first_and_last([2, 7, 4, 3])
5
>>> add_first_and_last([10])
10

Exercise 1.12 - Matrix Dimensions

A 2D matrix with dimensions m × n can be represented in Python by a nested list. Example of 3 × 2 matrix (3 rows with 2 numbers in each row, that is 2 columns):

Write a function matrix_dimensions(matrix)that returns the dimensions of a 2D matrix sent to the function as a nested list argument. The function shall return an information string (see run example below). Run example:

>>> A = [ [1, 3], [-5, 6], [2, 4]]
>>> matrix_dimensions(A)
'This is a 3x2 matrix.'
>>> B = [ [1, 3, 2], [-5, 6, 0] ]
>>> matrix_dimensions(B)
'This is a 2x3 matrix.'
>>> C = [ [1, 3], [-5, 6, 0] ]
>>> matrix_dimensions(C)
'This is not a valid matrix.'

Exercise 1.13 - Transpose Matrix

The transpose of a matrix AT is obtained if you flip the matrix over its diagonal, that is it you switch the row and column indices of the matrix by producing another matrix .

Example with 3 × 2 matrix:

Write a function transpose(matrix) that returns the transpose of a 2D matrix as a nested list. Run example:

>>> A = [[1, 2, 3], [4, 5, 6]]
>>> transpose(A)
[[1, 4], [2, 5], [3, 6]]
>>> transpose([[1, 2]])
[[1], [2]]
>>> transpose([[3]])
[[3]]

Övning 1.14 - Duplicate List and Distribute Values to Sublists

Construct a function distribute(my_item, my_list) that takes an element and a list of lists as arguments. The function shall return a new list that has a duplicate from the list content sent into to the function, where the value my_item is inserted as an element in each sublist. The original list must not change. See example of a run below.

>>> old_list = [[’kangar’], [’z’], [’f’]]
>>> distribute(’oo’, old_list)
[[’kangar’, ’oo’], [’z’, ’oo’], [’f’, ’oo’]]
>>> old_list
[[’kangar’], [’z’], [’f’]]

Exercise 1.15 - Extend Each

Construct a function extend_each(my_item, my_list) that takes an element and a list of lists, and extends every sublist with that element. The difference between this function and the previous one is that this time the function returns nothing, but changes the original list. See example of a run below.

Run example:

>>> old_list = [[’kangar’], [’z’], [’f’]]
>>> extend_each(’oo’, old_list)
>>> old_list
[[’kangar’, ’oo’], [’z’, ’oo’], [’f’, ’oo’]]

Exercise 1.16 - Sort by Length

Write a function sort_by_len(tup, direction) that takes in a tuple of strings. Return a new tuple where the strings are sorted with aspect of their lengths. The sort order is defined by a second argument containing 'asc' for ascending order or 'des' for descending order.

Run example:

>>> sort_by_len(('Windows', 'Linux', 'OSX'), 'asc')
('OSX', 'Linux', 'Windows')

>>> sort_by_len(('apple', 'orange', 'pear'), 'des')
('orange', 'apple', 'pear')

>>> sort_by_len(('begin', 'python', 'programming'), 'des')
('programming', 'python', 'begin')

>>> sort_by_len(('begin', 'python', 'programming'), 'asc')
('begin', 'python', 'programming')

Dictionaries

Övning 1.17 - Dictionary

In a dictionary you pair up data with a key. Then you can access data using the key. You could think of a dictionary as an advanced list, where instead of using a number as the index, using virtually any type of data. Try typing the following in the Python interpreter console:

>>> numbers = {'one': 1, 'two': 2, 'seven': 6, 'eight': 9}
>>> numbers[’one’]
1

To get used to handling dictionaries now type commands to do the following:

  • add the key 'three' linked with an appropriate number
  • make a change in the dictionary numbers so that numbers['eight'] will be linked with the number 8 instead

Exercise 1.18 - Dictionary Properties

Here we see two suggestions how to create a dictionary. One way will work and the other will not. Try to predict which one works. Then try to type them at the Python prompt to see if you were right.

>>> coordinates_one = {(1, 0): 'x-axis', (0, 1): 'y-axis'}
>>> coordinates_two = {[1, 0]: 'x-axis', [0, 1]: 'y-axis'}

Also try to figure out why one version works and the other does not.

Exercise 1.19 - Show Wordlist

Write a function show_wordlist(w_list) that goes through a dictionary and writes the values to the corresponding keys. Running the function on the numbers dictionary from Exercise 1.x should look something like this. Remember dictionaries are not ordered in any particular order.

>>> show_wordlist(numbers)
--
one - 1
seven - 6
eight - 9
two - 2
--

Exercise 1.20 - Genes

In gene expression, mRNA (messenger-RNA) is transcribed from a DNA template. The 4 nucleotide bases of A, T, C, G corresponds to the U, A, G, C bases of the mRNA. Write a function mRNA_transcript(template) that returns the mRNA transcript given the sequence of a DNA strand. Run example:

>>> mRNA_transcript("ATCGATTG")
'UAGCUAAC'

Hint! Use a dictionary to provide the mapping of DNA to RNA bases.

Exercise 1.21 - More Genes

A DNA strand consisting of the 4 nucleotide bases is usually represented with a string of letters: A, T, C, G. Write a function that computes the base composition of a given DNA sequence. The function shall return a dictionary with the four keys ’A’, ’T’, ’C’ and ’G’ and the count of each nucleotide base as values. Run example:

>>> base_composition("CTATCGGCACCCTTTCAGCA")
{'A': 4, 'C': 8, 'T': 5, 'G': 3}
    
>>> base_composition("AGT")
{'A': 1, 'C': 0, 'T': 1, 'G': 1}

Exercise 1.22 - Reverse Look-up

Write a function reverse_lookup(dictionary, value) that takes a dictionary and a value as arguments, and returns a sorted list with all keys associated with the given value. The function shall return an empty list if the value is not found in the dictionary. Run example:

>>> reverse_lookup({'a':1, 'b':2, 'c':2}, 1)
['a']

>>> reverse_lookup({'a':1, 'b':2, 'c':2}, 2)
['b', 'c']
    
>>> reverse_lookup({'a':1, 'b':2, 'c':2}, 3)
[]

Exercise 1.23 - Inverted Dictionary

Write a function invert_dictionary(my_dict) that takes a dictionary as an argument, and returns a new dictionary that inverts the keys and the values of the original dictionary. Run example:

>>> invert_dictionary({'a':1, 'b':2, 'c':3, 'd':2})
{1: ['a'], 2: ['b', 'd'], 3: ['c']}

>>> invert_dictionary({'a':3, 'b':3, 'c':3})
{3: ['a', 'c', 'b']}
    
>>> invert_dictionary({'a':2, 'b':1, 'c':2, 'd':1})
{1: ['b', 'd'], 2: ['a', 'c']}

Exercise 1.24 - ☆ Sparse Vector

A sparse vector is a vector whose entries are almost all zero, like [1, 0, 0, 0, 0, 0, 0, 2, 0]. Storing all those zeros wastes memory and dictionaries are commonly used to keep track of only the nonzero entries. For example, the vector shown earlier can be represented as {0:1, 7:2}, since the vector it is meant to represent has the value 1 at index 0 and the value 2 at index 7. Write a function list_to_dict(my_dict) that converts a sparse vector into a dictionary as described above. Run example:

>>> list_to_dict([1, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 4])
{0: 1, 3: 2, 7: 3, 12: 4}
    
>>> list_to_dict([1, 0, 1 , 0, 2, 0, 1, 0, 0, 1, 0])
{0: 1, 2: 1, 4: 2, 6: 1, 9: 1}
    
>>> list_to_dict([0, 0, 0, 0, 0])
{}

Exercise 1.25 - ☆ Back to Sparse Vector

See the exercise described above. Write a function dict_to_list(my_dict) that takes in a compressed description of a sparse vector as a dictionary and returns the corresponding list . Run example:

>>> dict_to_list({0: 1, 3: 2, 7: 3, 12: 4})
[1, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 4]

>>> dict_to_list({0: 1, 2: 1, 4: 2, 6: 1, 9: 1})
[1, 0, 1, 0, 2, 0, 1, 0, 0, 1]

>>> dict_to_list({})
[]

Sets

Exercise 1.26 - Remove Duplicates I

Write a program that accepts a sequence of whitespace separated words as user input and prints the words after removing all duplicate words and sorting them alphanumerically. Run example:

>>> User input: hello world and practice makes perfect and hello world again 
again and hello makes perfect practice world

Hint! You can use a set to remove duplicated data automatically and then use sorted() to sort the data.

Exercise 1.27 - Intersection

Write a function list_intersection(list1, list2)that takes two lists as arguments and returns a new list containing the elements that are the intersection between the two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], write a program to make a list whose elements are the intersection of the above given lists.

Run example

>>> list_intersection([1,3,6,78,35,55], [12,24,35,24,88,120,155])   
[35]

Hint! Use sets.

Exercise 1.28 - Remove Duplicates II

Write function remove_duplicates(my_list) that takes in a list and removes all duplicate values from this list with the original order preserved.

Run example

>>> my_list = [12,24,35,24,88,120,155,88,120,155]
>>> remove_duplicates(my_list)
>>> print(my_list)
[12, 24, 35, 88, 120, 155]

Hint! Use sets.