Skip to content
Snippets Groups Projects
Commit 139a1414 authored by Morten Hannemose's avatar Morten Hannemose
Browse files

Added week6

parent f6a1bdbd
No related branches found
No related tags found
No related merge requests found
Showing
with 282 additions and 3 deletions
......@@ -21,14 +21,14 @@ cp/tests/unitgrade_data/Week01Palindrome.pkl
cp/exam
#cp/project1
#cp/project2
cp/project3
#cp/project3
cp/project4
cp/project5
cp/project6
cp/tests/tests_week01.py
#*04*
*05*
*06*
#*05*
#*06*
*07*
*08*
*09*
......
"""DO NOT EDIT/ADD TO THIS FILE."""
"""Exercise 6.5: Languages."""
def get_people_by_language(language: str, name_languages: dict)-> list:
"""Return the names of people who speak a specific language.
:param language: A string containing the desired language.
:param name_languages: A dictionary containing the names of people along with their spoken languages
:return: The names of people that speak the desired language.
"""
# TODO: Code has been removed from here.
if __name__ == "__main__":
name_languages = {
'Peter': ['Danish', 'English'],
'Alice': ['English', 'French'],
'John': ['Spanish', 'English'],
'Maria': ['Danish', 'Spanish'],
'Anna': ['German', 'English']
}
print(get_people_by_language('English', name_languages))
"""Exercise 6.2: Letter histogram."""
def letter_histogram(input_string : str) -> dict:
"""Return the histogram of letter occurrences.
:param input_string: The word based on which the letter histogram is calculated.
:return: The alphabet characters as keys with their corresponding occurrences as values.
"""
# TODO: Code has been removed from here.
if __name__ == "__main__":
# here you can try out your functions
print("What is the letter histogram of the word banana?", letter_histogram('banana'))
"""Exercise 6.9: Multi-tap."""
def multi_tap(keys : list, times : list) -> str:
"""Return the string corresponding to the multi-tap key presses.
:param keys: The list of keys pressed.
:param times: The list of times of when the keys were pressed.
:return: The string corresponding to the key presses.
"""
# TODO: Code has been removed from here.
if __name__ == "__main__":
keys = [7, 7, 7, 7, 6, 6, 6]
times = [0, 0.7, 0.8, 0.9, 1, 1.1, 1.2]
print(multi_tap(keys, times), '==', 'PRO')
"""Exercise 6.1: The NATO alphabet."""
def text_to_nato(plaintext : str) -> str:
"""Return the NATO version of a word separated by dashes.
:param plaintext: The word to replace with its phrase according to the NATO alphabet.
:return: The NATO representation of the input word.
"""
# TODO: Code has been removed from here.
if __name__ == "__main__":
# here you can try out your functions
print("What is the NATO representation of hello?", text_to_nato('hello'))
"""Exercise 6.7: Sentiment analysis."""
def sentiment_analysis(text: str) -> int:
"""Return the sentence sentiment score, according to the rules of words scoring, as described in the text above.
:param text: The sentence to check for sentiment scoring.
:return: The total sentiment scoring of the sentence.
"""
# TODO: Code has been removed from here.
if __name__ == "__main__":
# here you can try out your functions
text='I think the food was excellent and great, but the service was horrible '
sentiment_analysis(text)
"""Exercise 6.8: Spell check."""
def spell_check(text: str, corrections: dict) -> str:
"""Return the corrected text for spelling errors according to a set of rules.
:param text: The sentence to check for spelling.
:param corrections: The dictionary of wrongly spelled words and their equivalent corrected version.
:return: The correctly spelled sentence.
"""
# TODO: Code has been removed from here.
if __name__ == "__main__":
# here you can try out your functions
corrections = {
'apsolute': 'absolute',
'teh': 'the',
'acess': 'access',
'occured': 'occurred',
'exampel': 'example'
}
text = "The apsolute acsess to teh data occured in this exampel."
print(spell_check(text, corrections))
"""Exercise 6.6: Truncate and normalize."""
def truncate_values(float_list : list, settings: dict) -> list:
"""Return a truncated list of floats given the initial list and the settings for truncating. If normalize is True, the values are first normalized to the [0,1] range and then truncated.
:param float_list: list of floats
:param settings: Dictionary containing the keys vmin, vmax and normalize with their corresponding values.
:return: Truncated/Normalized+Truncated values.
"""
# TODO: Code has been removed from here.
if __name__ == "__main__":
# here you can try out your functions
settings = {'vmin': 0, 'vmax': 2, 'normalize': False}
float_list = [0.5,0.4,-0.3, 1.5, 2.5, 3.5]
result=truncate_values(float_list=float_list,settings=settings)
print(result)
"""Exercise 6.3-6.4."""
def word_histogram(lines : list) -> list:
"""Return the word count histogram from the input lines.
:param lines: The lines that are analyzed for word count.
:return: The histogram of word occurrences.
"""
# TODO: Code has been removed from here.
def extract_keyword(lines : str, ignore_list : list) -> dict:
"""Return the five most frequent words that are not on the ignore list and their occurrences.
:param lines: The sentence to extract keywords from.
:param ignore_list: The words that should ignored.
:return: The five most frequent words in the sentence as keys with their count as values.
"""
# TODO: Code has been removed from here.
if __name__ == "__main__":
# here you can try out your functions
print(word_histogram('I think therefore I am.'))
# Ignore list of common words
ignore_list = [
'a', 'an', 'the', 'above', 'across', 'against', 'along', 'among', 'around',
'at', 'before', 'behind', 'below', 'beneath', 'beside', 'between', 'by',
'down', 'from', 'in', 'into', 'near', 'of', 'off', 'on', 'to', 'toward',
'under', 'upon', 'with', 'within','function', 'for', 'and', 'nor', 'but', 'or', 'yet', 'so']
# Example usage:
lines = [ "Write the function word_histogram, which takes as argument a list containing lines of a text.", "The function should ... ... ... ... ... make a histogram of words that occur in the text."]
keywords_result = extract_keyword(lines, ignore_list)
# Print the 5 most occurring keywords
print(keywords_result)
"""DO NOT EDIT/ADD TO THIS FILE."""
This diff is collapsed.
from unitgrade import UTestCase, Report, hide
import string
from cp import minput
from unittest.mock import patch
import io
import unittest
import math
class WaterHeight(UTestCase):
def test_water_height(self):
from cp.ex05.water_height import water_height
self.assertEqual(water_height(5, [1,2,3]), 5)
self.assertEqual(water_height(2, [1,1]), 0)
self.assertEqual(water_height(0, [1,3]), 1)
self.assertEqual(water_height(1,[1,2,3,4,5]),6)
self.assertEqual(water_height(2,[1,12,8,4,5]),22)
self.assertEqual(water_height(5,[1,10,3,4,5]),18)
class Week05BestBuy(UTestCase):
def test_bestbuy(self):
from cp.ex05.best_buy import best_buy
self.assertEqual(best_buy([3, 2, 1, 3, 5], 10, 0, False), 4)
self.assertEqual(best_buy([3, 2, 1, 3, 5], 3, 1, False), 2)
self.assertEqual(best_buy([3, 2, 1, 3, 5], 8, 4, True), 2)
self.assertEqual(best_buy([3, 2, 1, 3, 5], 15, 4, True), 5)
class Week05TicTacToePrintBoard(UTestCase):
def test_print_board(self):
from cp.ex05.tictactoe import print_board
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
print_board([['-','X','-'],['-','-','O'],['X','-','-']])
out = mock_stdout.getvalue().splitlines()
self.assertEqual(len(out), 3, msg="You did not print out 3 separate lines")
self.assertEqual(out[0], "-X-")
self.assertEqual(out[1], "--O")
self.assertEqual(out[2], "X--")
class Week05TicTacToeGetGameState(UTestCase):
def test_get_game_state(self):
from cp.ex05.tictactoe import get_game_state
self.assertEqual(get_game_state([['-','-','-'],['-','-','-'],['-','-','-']]),'-')
self.assertEqual(get_game_state([['X','X','X'],['-','-','-'],['-','-','-']]),'X')
self.assertEqual(get_game_state([['-','-','-'],['X','X','X'],['-','-','-']]),'X')
self.assertEqual(get_game_state([['X','-','-'],['-','X','-'],['O','O','X']]),'X')
self.assertEqual(get_game_state([['X','-','-'],['-','X','-'],['O','O','O']]),'O')
self.assertEqual(get_game_state([['X','O','X'],['X','O','O'],['O','X','X']]),'Draw')
class Week05TicTacToeUpdateBoard(UTestCase):
def test_update_board(self):
from cp.ex05.tictactoe import update_board
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
self.assertEqual(update_board([['-','-','-'],['-','-','-'],['-','-','-']],'X',[1,0]),[['-', '-', '-'], ['X', '-', '-'], ['-', '-', '-']])
self.assertEqual(update_board([['X','X','-'],['-','-','-'],['-','-','-']],'O',[0,2]),[['X', 'X', 'O'], ['-', '-', '-'], ['-', '-', '-']])
self.assertEqual(update_board([['-','-','-'],['X','X','X'],['-','-','-']],'X',[2,0]),[['-', '-', '-'], ['X', 'X', 'X'], ['X', '-', '-']])
self.assertEqual(update_board([['X','-','-'],['-','X','-'],['O','O','X']],'O',[1,2]),[['X', '-', '-'], ['-', 'X', 'O'], ['O', 'O', 'X']])
self.assertEqual(update_board([['X','-','-'],['-','X','-'],['O','O','O']],'X',[0,2]),[['X', '-', 'X'], ['-', 'X', '-'], ['O', 'O', 'O']])
self.assertEqual(update_board([['O','-','-'],['O','X','-'],['O','X','X']],'O',[0,2]),[['O', '-', 'O'], ['O', 'X', '-'], ['O', 'X', 'X']])
out = mock_stdout.getvalue()
self.assertEqual(out, "", "You should not print anything for valid moves")
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
update_board([['O','-','-'],['O','X','-'],['O','X','X']],'O',[0,0])
out = mock_stdout.getvalue().strip()
self.assertEqual(out, "Invalid move!")
class Week05TicTacToeMain(UTestCase):
def test_tictactoe_main(self):
from cp.ex05.tictactoe import tictactoe
with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout:
tictactoe([['X','X','-'],['-','O','-'],['O','-','-']],'O',[0,2])
out = mock_stdout.getvalue().splitlines()
self.assertEqual(len(out), 4, msg="You did not print out 4 separate lines")
self.assertEqual(out[0], "XXO")
self.assertEqual(out[1], "-O-")
self.assertEqual(out[2], "O--")
self.assertEqual(out[3],"Player O won!")
class Week06SentimentAnalysis(UTestCase):
def test_sentiment_analysis(self):
from cp.ex06.sentiment_analysis import sentiment_analysis
self.assertEqual(sentiment_analysis('I think the food was excellent and great, but the waiter service was horrible '),-5)
self.assertEqual(sentiment_analysis('When I woke up, I was feeling very bad, but then I had a coffee, and my day turned out to be excellent '),4)
self.assertEqual(sentiment_analysis('I know it is good not to complain, but the selection criteria were genuinely inadequate and unfair '),-1)
class Week06MultiTap(UTestCase):
def test_multi_tap(self):
from cp.ex06.multi_tap import multi_tap
self.assertEqual(multi_tap([7, 7, 7, 7, 6, 6, 6], [0, 0.7, 0.8, 0.9, 1, 1.1, 1.2]), 'PRO')
self.assertEqual(multi_tap([4, 4, 4, 0, 2, 6, 0, 4, 4, 2, 7, 7, 9, 9, 9], [0.1, 0.3, 0.6, 1.0, 1.2, 1.4, 1.7, 2.0, 2.2, 2.5, 2.9, 3.9, 4.3, 4.4, 4.8]), "I AM HAPPY")
self.assertEqual(multi_tap([7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 8, 8, 3], [0.1, 0.5, 0.8, 1.2, 2.6, 3.7, 4.1, 4.2, 4.5, 4.9, 5.1, 5.4, 5.6, 5.9]), "SPROUD")
self.assertEqual(multi_tap([4, 4, 4, 2, 2, 2, 3, 3, 0, 4, 4, 4, 2, 2, 2, 3, 3, 0, 2, 2, 2, 2, 2, 9, 9, 9], [0.3, 0.7, 0.8, 1.1, 1.3, 1.5, 1.7, 1.8, 2.1, 2.4, 2.7, 3.0, 3.4, 3.7, 3.9, 4.0, 4.3, 4.5, 4.7, 5.0, 6.4, 7.9, 8.3, 8.5, 8.7, 9.0]), "ICE ICE BABY")
self.assertEqual(multi_tap([5, 5, 5, 4, 4, 4, 8, 8, 8, 3, 3, 0, 5, 5, 5, 2, 8, 8, 4, 4, 4, 0, 5, 5, 5, 4, 4, 4, 7, 7, 7, 7, 8], [0.7, 0.9, 1.2, 1.6, 1.7, 2.0, 2.4, 2.5, 2.8, 3.2, 3.5, 3.7, 3.9, 4.3, 4.6, 4.8, 5.0, 5.3, 5.6, 6.3, 6.7, 6.8, 7.1, 7.3, 7.5, 7.8, 8.0, 8.1, 8.3, 8.5, 8.7, 8.9, 9.3]), "LIVE LAUGH LIST")
class Project3(Report):
title = "Project 3"
remote_url = "https://cp.pages.compute.dtu.dk/02002public/_static/evaluation/"
abbreviate_questions = True
questions = [(Week05BestBuy,10),
(WaterHeight,10),
(Week05TicTacToePrintBoard,5),
(Week05TicTacToeGetGameState,10),
(Week05TicTacToeUpdateBoard,10),
(Week06SentimentAnalysis,20),
(Week06MultiTap,20),
]
import cp
pack_imports = [cp]
if __name__ == "__main__":
from unitgrade import evaluate_report_student
evaluate_report_student(Project3())
File added
File added
File added
File added
File added
File added
File added
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment