Skip to content

Instantly share code, notes, and snippets.

@blueset

blueset/README.md

Last active Aug 16, 2020
Embed
What would you like to do?
UniMelb COMP10001 2016S2 Worksheet My Solution

This is the place for me to share my solutions to the Grok Learning Worksheets for the COMP10001 Foundation of Computing course in the University of Melbourne in Semester 2, 2016.

Take note that all code released here are EXPIRED, i.e. they are no longer available to be submitted as examinable works. And all codes below is licensed under MIT license.

Note that some codes used below may include advanced contents that may not be taught before the deadline. Also, some “dirty tricks”, like joining code into one long line, is strongly not recommended to be used in your projects.

In the meanwhile, you might be interested in my solution to the Practice Projects.

- -------------------------------- !ALERT! --------------------------------- -
! All solutions below are registered with the university. Any attempt of     !
! plagiarising from this page will be immediately detected by the system at  !
! the time of marking. The author strongly advise against plagiarism in any  !
! form in your assignment or project.                                        !
!                                                                            !
! You have been warned.                                                      !
- -------------------------------- !ALERT! --------------------------------- -
Copyright (c) 2016 Eana Hufwe

Permission is hereby granted, free of charge, to any person obtaining a 
copy of this software and associated documentation files (the "Software"), 
to deal in the Software without restriction, including without limitation 
the rights to use, copy, modify, merge, publish, distribute, sublicense, 
and/or sell copies of the Software, and to permit persons to whom the 
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included 
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 
IN THE SOFTWARE.
# Worksheet 1: Introductory Exercises
# First exercise!
# Expired on Mon 8 Aug 2016, 11:59 pm
print("Bonjour World!\nHow are you?")
# Worksheet 1: Introductory Exercises
# Python as a calculator
# Expired on Mon 8 Aug 2016, 11:59 pm
import math
print(math.factorial(10))
# Worksheet 1: Introductory Exercises
# Order of operations
# Expired on Mon 8 Aug 2016, 11:59 pm
print(5 * (8 + 20 - 18) / 2)
print(5 * (8 + 20) - 18 / 2)
# Worksheet 1: Introductory Exercises
# Musical notes
# Expired on Mon 8 Aug 2016, 11:59 pm
print("CEG" * 2 + "E" * 36 + "C" * 24)
# Worksheet 1: Introductory Exercises
# Input exercise
# Expired on Mon 8 Aug 2016, 11:59 pm
print("Hello %s" % input("Enter your name: "))
# Worksheet 2: Numerical expressions
# Floating point calculation
# Expired on Mon 8 Aug 2016, 11:59 pm
print(1.395e5 + 5.55e2)
# Worksheet 2: Numerical expressions
# Type conversion exercise 1
# Expired on Mon 8 Aug 2016, 11:59 pm
print(float(float(input("Enter val1: ")) + float(input("Enter val2: "))))
# Worksheet 2: Numerical expressions
# Type conversion exercise 2
# Expired on Mon 8 Aug 2016, 11:59 pm
print("%skg" % (float(input("Enter weight in grams: ")) / 1000))
# Worksheet 2: Numerical expressions
# Happy Birthday Mr Frodo
# Expired on Mon 8 Aug 2016, 11:59 pm
a = int(input("How many days have you lived? "))
print("You are %s years young!\nYou have %s days until you next get to boogie down." % (a // 365, 365 - (a % 365)))
# Worksheet 2: Numerical expressions
# Mr Frodo goes to the bank
# Expired on Mon 8 Aug 2016, 11:59 pm
print("After that time you will have: $%s" % (int(input("How much money would you like to invest, Mr Frodo? ")) * (1 + .045 / 12) ** (int(input("How many days would you like to invest this for? ")) // 31)))
# Worksheet 3: Conditionals
# Detecting Enemies
# Expired on Mon 15 Aug 2016, 11:59 pm
a = input("Enter your name, soldier: ")
print("HAHA! A phone number! You may not pass!!" if a.isdigit() else "Welcome to the camp, %s, if that really is your name." % a if a else "A luddite! GO AWAY AT ONCE!")
# Worksheet 3: Conditionals
# Telephone Number (In)validator
# Expired on Mon 15 Aug 2016, 11:59 pm
import re
if not re.match("^[1-9]{8}$", input("Enter your phone number: ")):
print("ERROR: Invalid input")
# Worksheet 3: Conditionals
# Loose Change
# Expired on Mon 15 Aug 2016, 11:59 pm
a = float(input("How much does it cost? ")) * 20
print("The price didn't change or was rounded down! Pay cash!" if round(a) < a else "The price was rounded up! Pay card.")
# Worksheet 3: Conditionals
# Science Classifier
# Expired on Mon 15 Aug 2016, 11:59 pm
a = input("Hit me: ")
print("Life science hipster!" if a.endswith("omics") else "Computing ftw!" if a.startswith("comp") or a.startswith("info") else "Au naturel!" if a.endswith("y") else "Can't keep up!")
# Worksheet 3: Conditionals
# Season's Greetings
# Expired on Mon 15 Aug 2016, 11:59 pm
l = ["It's summer. Have fun in the sun!",
"It's autumn. Enjoy the beautiful sunsets!",
"It's winter. Go skiing!",
"It's spring. Check out the spring racing carnival!"]
a = int(input("Enter the month (1-12): "))
if a in range(1, 13):
print(l[a // 12])
else:
print("Invalid input. Please enter any number between 1 and 12.")
# Worksheet 4: Sequences
# String Indexing
# Expired on Mon 15 Aug 2016, 11:59 pm
a = input("Enter some text: ")
print("%s\n%s" % (a[2], a[-3]))
# Worksheet 4: Sequences
# String Slicing
# Expired on Mon 15 Aug 2016, 11:59 pm
a = input("Enter some text: ")
print("%s\n%s" % (a[:3], a[-3:]))
# Worksheet 4: Sequences
# Your Name, Backwards
# Expired on Mon 15 Aug 2016, 11:59 pm
print("Well hello there, mr", input("What is your name? ")[::-1])
# Worksheet 4: Sequences
# A and an
# Expired on Mon 15 Aug 2016, 11:59 pm
a = input("Enter a phrase: ")
print(("an %s" % a) if a and a[0] in "aeiouAEIOU" else ("a %s" % a))
# Worksheet 4: Sequences
# The Culprit
# Expired on Mon 15 Aug 2016, 11:59 pm
suspects = [("Max Zorin", "Kills with guns", "Chip Tycoon"),
("Hugo Drax",),
("Jaws", "Bites people", "Mutant"),
("Nick Nack", "Really short"),
("Le Chiffre", "Good at poker", "Really evil"),
("Francisco Scaramanga", "Has a Golden Gun", "Probably will melt"),
("Mr Big", "Also the name of a rock band", "Dictator of San Monique")]
i = int(input("WHO DID IT HUGO!? ")) % 7
print("It was %s\nData: %s" % (suspects[i][0], suspects[i][1:]))
# Worksheet 5: Basic Functions
# Woodchuck Functionality
# Expired on Mon 22 Aug 2016, 11:59 pm
def animal_chuck(beastie):
"""" animal_chuck takes a string beastie (assumed to be an animal) and returns a string containing an important question about the animal """
# write your code here
return "How much wood could a %s chuck" % beastie
# Worksheet 5: Basic Functions
# More Woodchuck Functionality
# Expired on Mon 22 Aug 2016, 11:59 pm
def animal_chuck2(beastie):
""" animal_chuck2 takes a string beastie (assumed to be an animal) and returns a string containing a grammatically correct and important question about the animal """
# code here.
beastie = "an %s" % beastie if beastie and beastie[0] in "AEIOUaeiou" else "a %s" % beastie
return "How much wood could %s chuck" % beastie
# Worksheet 5: Basic Functions
# Goldilocks String
# Expired on Mon 22 Aug 2016, 11:59 pm
between_len = lambda a, minlen, maxlen: minlen <= len(a) <= maxlen
# Worksheet 6: Basic Methods
# Word Counter
# Expired on Mon 22 Aug 2016, 11:59 pm
def word_count(input_str):
""" The function word_count returns the number of words in the string input_str. """
# code here.
return len(input_str.split())
# Worksheet 6: Basic Methods
# String Slicing and Dicing
# Expired on Mon 22 Aug 2016, 11:59 pm
import re
n, r = re.match(r"^(\d+) .*? cost \$(\d+\.\d{2})\.$", input("What did you buy: ")).groups()
print("$%.2f" % (float(r) / float(n)))
# Worksheet 7: Review
# Chess Problem v1
# Expired on Mon 29 Aug 2016, 11:59 pm
def check_move(x, y):
if x in 'ABCDEFGH' and y in range(1,9):
return 'The piece is moved to %s%s.' % (x, y)
else:
return 'The position is not valid.'
# Worksheet 7: Review
# Chess Problem v2
# Expired on Mon 29 Aug 2016, 11:59 pm
def check_move(x, y):
x = x.upper()
if x in 'ABCDEFGH' and y in range(1,9):
return 'The piece is moved to %s%s.' % (x, y)
else:
return 'The position is not valid.'
# Worksheet 7: Review
# Chess Problem v3
# Expired on Mon 29 Aug 2016, 11:59 pm
def check_move(x, y):
x = x.upper()
if not x in 'ABCDEFGH':
return 'The column value is not in the range a-h or A-H!'
if not y in range(1,9):
return 'The row value is not in the range 1 to 8!'
return 'The piece is moved to %s%s.' % (x, y)
# Worksheet 7: Review
# Chess Problem v4
# Expired on Mon 29 Aug 2016, 11:59 pm
def check_move(x):
if not (len(x) == 2 and x[0].isalpha() and x[1].isdigit()):
return 'The position is not valid.'
y = int(x[1])
x = x[0].upper()
if not x in 'ABCDEFGH':
return 'The column value is not in the range a-h or A-H!'
if not y in range(1,9):
return 'The row value is not in the range 1 to 8!'
return 'The piece is moved to %s%s.' % (x, y)
# Worksheet 7: Review
# Card Security Code problem
# Expired on Mon 29 Aug 2016, 11:59 pm
import re
check_csc = lambda a: type(a) == str and bool(re.fullmatch("[0-9]{3}", a))
# Worksheet 8: Iteration
# while Loop
# Expired on Mon 29 Aug 2016, 11:59 pm
num = input("Enter the number for 'num': ")
n = input("Enter the number for 'N': ")
try:
num = int(num)
n = int(n)
if not (n > 0 and num > 0):
raise Exception
for i in range(1, n + 1):
print("%s * %s = %s" % (i, num, i*num))
except:
print("Invalid input")
# Worksheet 8: Iteration
# Word formation problem
# Expired on Mon 29 Aug 2016, 11:59 pm
l = input("Enter the initial letters: ")
s = input("Enter the common suffix: ")
for i in l:
print(i + s)
# Worksheet 8: Iteration
# Gamertag Problem, v1
# Expired on Mon 29 Aug 2016, 11:59 pm
make_gamertag = lambda a: ''.join([i + "*" for i in a])
# Worksheet 8: Iteration
# Left Aligned Triangle
# Expired on Mon 29 Aug 2016, 11:59 pm
print("\n".join(["*"*(i+1) for i in range(int(input("Enter height: ")))]))
# Worksheet 8: Iteration
# Right Aligned Triangle
# Expired on Mon 29 Aug 2016, 11:59 pm
n = int(input("Enter height: "))
for i in range(n):
print("{l:>{n}}".format(n=n, l="*"*(i+1)))
# Worksheet 8: Iteration
# Diamond
# Expired on Mon 29 Aug 2016, 11:59 pm
n = int(input("Enter triangle height: "))
for i in range(n - 1, 0, -1):
print("{l:<{n}}".format(n=n, l="*"*(i+1)) + "{l:>{n}}".format(n=n, l="*"*(i+1)))
for i in range(n):
print("{l:<{n}}".format(n=n, l="*"*(i+1)) + "{l:>{n}}".format(n=n, l="*"*(i+1)))
# Worksheet 8: Iteration
# Credit Card Validation
# Expired on Mon 29 Aug 2016, 11:59 pm
validate_card = lambda a: len(a) == 16 and sum([int(i) for i in a]) % 10 == 0
# Worksheet 9: Mutability and Advanced Sequences
# Cycling Lists
# Expired on Mon 12 Sep 2016, 11:59 pm
cycle = lambda a: a.append(a.pop(0))
# Worksheet 9: Mutability and Advanced Sequences
# ReCycling Lists
# Expired on Mon 12 Sep 2016, 11:59 pm
cycle = lambda a: a[1:] + [a[0]]
# Worksheet 9: Mutability and Advanced Sequences
# for Loop with break
# Expired on Mon 12 Sep 2016, 11:59 pm
def wordlist(a):
a = a.split()
l = []
i = 0
while i < len(a) and a[i].isalpha():
l.append(a[i])
i += 1
return l
# Worksheet 9: Mutability and Advanced Sequences
# Sorted Words
# Expired on Mon 12 Sep 2016, 11:59 pm
sorted_words = lambda a: sorted([i for i in a if list(i) == sorted(i)])
# Worksheet 9: Mutability and Advanced Sequences
# Preceding Word Length
# Expired on Mon 12 Sep 2016, 11:59 pm
l = {'how': 4.0, 'ship.': 3.0, 'cherish': 6.0, 'it': 6.333333333333333, 'long': 3.0, 'pistol': 3.0, 'and': 6.714285714285714, 'into': 8.0, 'warehouses,': 6.0, 'deliberately': 4.0, 'It': 6.0, "people's": 8.0, 'moral': 6.0, 'world.': 3.0, 'street,': 3.0, 'methodically': 3.0, 'upon': 7.0, 'requires': 2.0, 'bringing': 3.0, 'flourish': 13.0, 'knew': 3.0, 'particular': 7.0, 'every': 2.0, 'stepping': 12.0, 'get': 3.5, 'sword;': 3.0, 'me': 6.333333333333333, 'or': 5.0, 'Call': 0.0, 'the': 4.4, 'take': 7.0, 'This': 4.0, 'nothing': 2.5, 'with': 5.0, 'a': 4.2, 'part': 6.0, 'circulation.': 3.0, 'would': 1.0, 'my': 3.5, 'hats': 8.0, 'damp,': 1.0, 'this.': 2.0, 'whenever': 7.0, 'involuntarily': 6.0, 'feelings': 4.0, 'off': 5.5, 'Ishmael.': 2.0, 'regulating': 3.0, 'way': 1.0, 'time': 4.0, 'never': 1.0, 'their': 2.0, 'they': 2.0, 'of': 4.0, 'but': 4.0, 'to': 6.0, 'soul;': 2.0, 'growing': 6.0, 'from': 2.0, 'throws': 4.0, 'thought': 1.0, 'other,': 2.0, 'degree,': 5.0, 'mouth;': 3.0, 'find': 1.0, 'quietly': 1.0, 'an': 4.0, 'With': 5.0, '-': 5.0, 'driving': 2.0, 'philosophical': 1.0, 'If': 5.0, 'strong': 1.0, 'ago': 5.0, 'years': 4.0, 'see': 3.0, 'account': 1.0, 'hand': 5.0, 'especially': 3.0, 'little': 3.5, 'for': 10.0, 'no': 2.0, 'as': 3.5, 'is': 3.25, 'shore,': 2.0, 'watery': 3.0, 'myself': 4.0, 'have': 1.0, 'nearly': 4.0, 'on': 2.0, 'that': 3.0, 'grim': 7.0, 'such': 3.0, 'it,': 4.0, 'surprising': 7.0, 'in': 6.5, 'Whenever': 12.0, 'meet;': 1.0, 'high': 2.0, 'interest': 2.0, 'sea': 2.0, 'me.': 4.0, 'funeral': 5.0, 'hypos': 2.0, 'upper': 2.0, 'soon': 2.0, 'same': 3.0, 'rear': 3.0, 'men': 3.0, 'some': 7.0, 'There': 5.0, 'about': 4.0, 'me,': 2.0, 'can.': 1.0, 'money': 2.0, 'knocking': 12.0, 'precisely': 4.0, 'mind': 5.0, 'up': 8.0, 'having': 1.0, 'principle': 5.0, 'almost': 3.0, 'towards': 8.0, 'drizzly': 5.0, 'November': 7.0, 'sail': 5.0, 'coffin': 6.0, 'his': 4.0, 'ball.': 3.0, 'himself': 6.0, 'substitute': 2.0, 'before': 7.0, 'ocean': 3.0, 'purse,': 2.0, 'spleen': 3.0, 'Cato': 8.0, 'very': 7.0, 'pausing': 13.0, 'Some': 8.0, 'then,': 1.0, 'all': 6.0, 'prevent': 2.0, 'I': 5.777777777777778}
prevword_ave_len = lambda w: w in l and l[w]
# Generation of `l`
#
# t = "Call me Ishmael. Some years ago - never mind how long precisely - having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen and regulating the circulation. Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the street, and methodically knocking people's hats off - then, I account it high time to get to sea as soon as I can. This is my substitute for pistol and ball. With a philosophical flourish Cato throws himself upon his sword; I quietly take to the ship. There is nothing surprising in this. If they but knew it, almost all men in their degree, some time or other, cherish very nearly the same feelings towards the ocean with me.".split()
# l = {}
# l[t[0]] = [0]
# for i in range(1, len(t)):
# if t[i] in l:
# l[t[i]].append(len(t[i - 1]))
# else:
# l[t[i]] = [len(t[i - 1])]
# l = {k: sum(v)/len(v) for k, v in l.items()}
# print(l)
# Text:
"Call me Ishmael. Some years ago - never mind how long precisely - having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen and regulating the circulation. Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the street, and methodically knocking people's hats off - then, I account it high time to get to sea as soon as I can. This is my substitute for pistol and ball. With a philosophical flourish Cato throws himself upon his sword; I quietly take to the ship. There is nothing surprising in this. If they but knew it, almost all men in their degree, some time or other, cherish very nearly the same feelings towards the ocean with me."
# Worksheet 9: Mutability and Advanced Sequences
# Find the Middle Word(s)
# Expired on Mon 12 Sep 2016, 11:59 pm
middle_words = lambda a: a[len(a) // 2: len(a) // 2 + 1] if len(a) % 2 == 1 else a[len(a) // 2 - 1: len(a) // 2 + 1]
# Worksheet 9: Mutability and Advanced Sequences
# Longest Sentence
# Expired on Mon 12 Sep 2016, 11:59 pm
longest_sentence_length = lambda a: max([len(i.split()) for i in a.split(".")])
# Worksheet 9: Mutability and Advanced Sequences
# Longer, Higher Strings
# Expired on Mon 12 Sep 2016, 11:59 pm
long_high_word = lambda a: sorted([(len(i), i) for i in a])[-1][1]
# Worksheet 11: Dictionaries and Sets
# Capital City Testing
# Expired on Mon 19 Sep 2016, 11:59 pm
d = {
"New South Wales": "Sydney",
"Queensland": "Brisbane",
"South Australia": "Adelaide",
"Tasmania": "Hobart",
"Victoria": "Melbourne",
"Western Australia": "Perth"
}
is_capital = lambda a, b: a in d and b == d[a]
# Worksheet 11: Dictionaries and Sets
# Number of Frequent Characters
# Expired on Mon 19 Sep 2016, 11:59 pm
# import various text constants from `constants`
from constants import *
freq_threshold = lambda t, c: sum([1 for i in set(t) if t.count(i) > c])
# --constants.py--
# MOBY = "Call me Ishmael. Some years ago - never mind how long precisely - having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen and regulating the circulation. Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the street, and methodically knocking people's hats off - then, I account it high time to get to sea as soon as I can. This is my substitute for pistol and ball. With a philosophical flourish Cato throws himself upon his sword; I quietly take to the ship. There is nothing surprising in this. If they but knew it, almost all men in their degree, some time or other, cherish very nearly the same feelings towards the ocean with me."
#
# PETER_PAN = "All children, except one, grow up. They soon know that they will grow up, and the way Wendy knew was this. One day when she was two years old she was playing in a garden, and she plucked another flower and ran with it to her mother. I suppose she must have looked rather delightful, for Mrs Darling put her hand to her heart and cried, 'Oh, why can't you remain like this for ever!' This was all that passed between them on the subject, but henceforth Wendy knew that she must grow up. You always know after you are two. Two is the beginning of the end."
#
# WHITE_FANG = "Dark spruce forest frowned on either side of the frozen waterway. The trees had been stripped by a recent wind of their white covering of frost, and they seemed to lean toward each other, black and ominous, in the fading light. A vast silence reigned over the land. The land itself was a desolation, lifeless, without movement, so lone and cold that the spirit of it was not even that of sadness. There was a hint in it of laughter, but of a laughter more terrible than any sadness - a laughter that was mirthless as the smile of the Sphinx, a laughter cold as the frost and partaking of the grimness of infallibility. It was the masterful and incommunicable wisdom of eternity laughing at the futility of life and the effort of life. It was the Wild, the savage, frozenhearted Northland Wild."
# Worksheet 11: Dictionaries and Sets
# Duplicate Word
# Expired on Mon 19 Sep 2016, 11:59 pm
repeat_word_count = lambda t, c: sorted([i for i in set(t.split())
if t.split().count(i) >= c])
# Worksheet 11: Dictionaries and Sets
# Mode List
# Expired on Mon 19 Sep 2016, 11:59 pm
from collections import Counter as Cc
mode = lambda a: sorted([i[0] for i in Cc(a).items()
if i[1] == max(Cc(a).items(), key=lambda a: a[1])[1]])
# Worksheet 11: Dictionaries and Sets
# Top-5 Frequent Words
# Expired on Mon 19 Sep 2016, 11:59 pm
from collections import Counter as Cc
top5_words = lambda a: [i[0] for i in sorted(
Cc(a.split()).most_common(len(a.split())),
key=lambda a: (-a[1], a[0]))][:5]
# Worksheet 11: Dictionaries and Sets
# Mutual Friends
# Expired on Mon 19 Sep 2016, 11:59 pm
mutual_friends = lambda a, b: len(set(a) & set(b))
# Worksheet 12: Advanced Functions
# The function of None return
# Expired on Mon 19 Sep 2016, 11:59 pm
mymax = lambda a: None if not a else max(a)
# Worksheet 12: Advanced Functions
# Multi-returning Functions
# Expired on Mon 19 Sep 2016, 11:59 pm
def maxby(a):
maxn = lambda a: max(a) if a else None
n = maxn(a)
if n is None:
return (None, None)
a.remove(n)
y = maxn(a) and n - maxn(a)
return (n, y)
# Worksheet 12: Advanced Functions
# Timely return
# Expired on Mon 19 Sep 2016, 11:59 pm
def issorted(numlist):
for i in range(1, len(numlist)):
if numlist[i] < numlist[i-1]:
return False
return True
# Worksheet 12: Advanced Functions
# Base-n Number Validation
# Expired on Mon 19 Sep 2016, 11:59 pm
def basenum(a, b):
try:
a and int(str(a), b)
return True
except:
return False
# Worksheet 13: Libraries, Nested Loops and 2D Data
# Triangle Leg Lengths
# Expired on Mon 26 Sep 2016, 11:59 pm
from math import cos, sin, radians
triangle_legs = lambda a, b: tuple(sorted([a * cos(radians(b)),
a * sin(radians(b))]))
# PEP8 Check is introduced from now on
# Worksheet 13: Libraries, Nested Loops and 2D Data
# Donald Trump's Speech
# Expired on Mon 26 Sep 2016, 11:59 pm
from collections import defaultdict, Counter
def count_lengths(text):
# Your code here.
l = [len(i) for i in text.split()]
return defaultdict(int, Counter(l))
def top5_word_lengths(text):
# Your code here.
l = [len(i) for i in text.split()]
t = Counter(l).items()
return [i[0] for i in sorted(t, key=lambda a: [-a[1], -a[0]])][:5]
# Worksheet 13: Libraries, Nested Loops and 2D Data
# Visualising Factors
# Expired on Mon 26 Sep 2016, 11:59 pm
n = int(input("Maximum number to factorise: "))
for i in range(1, n + 1):
l = [j for j in range(1, i + 1) if i % j == 0]
print("".join(["* " if j in l else "- " for j in range(1, n + 1)]))
# Worksheet 13: Libraries, Nested Loops and 2D Data
# Matching Codons
# Expired on Mon 26 Sep 2016, 11:59 pm
matching_codons = lambda c, p1, p2: [(i, "".join([c[j] for j in i if j in c]))
for i in p1
if "".join([c[j] for j in i if j in c])
in p2]
# Worksheet 13: Libraries, Nested Loops and 2D Data
# Image Grey Value
# Expired on Mon 26 Sep 2016, 11:59 pm
grey_value = lambda a: sum([sum(i) for i in a]) / sum([len(i) for i in a])
# Worksheet 14: List Comprehensions and Iterators
# Disentangling list comprehensions
# Expired on Mon 10 Oct 2016, 11:59 pm
aha = lambda a, b: list(map(lambda c: c**2 % 10, range(a, b+1)))
# Worksheet 14: List Comprehensions and Iterators
# Hack the System
# Expired on Mon 10 Oct 2016, 11:59 pm
from itertools import permutations
LIKELY_WORDS = ["Frenchy", "INTENSE", "ComputerScienceFTW", "HelloMrGumby"]
MIDDLE = "Horse20"
CREME_PUFF = 38
def hack_it(start=LIKELY_WORDS, middle=MIDDLE, end=CREME_PUFF):
# your code here
s = ["".join(i) for i in permutations(start, 2)]
l = []
for i in s:
for j in range(end + 1):
l.append("%s%s%02d" % (i, middle, j))
return l
# Worksheet 15: File IO and CSV Files
# Forgetful Karaoke
# Expired on Mon 10 Oct 2016, 11:59 pm
from collections import Counter
def approximate_song(fn):
with open(fn) as f:
return sorted(Counter(f.read().split()).most_common(),
key=lambda a: (-a[1], a[0]))[0][0]
# Text files examples:
somebody_txt = """Now and then I think of when we were together
Like when you said you felt so happy you could die
Told myself that you were right for me
But felt so lonely in your company
But that was love and it's an ache I still remember
You can get addicted to a certain kind of sadness
Like resignation to the end, always the end
So when we found that we could not make sense
Well you said that we would still be friends
But I'll admit that I was glad that it was over
But you didn't have to cut me off
Make out like it never happened and that we were nothing
And I don't even need your love
But you treat me like a stranger and that feels so rough
No you didn't have to stoop so low
Have your friends collect your records and then change your number
I guess that I don't need that though
Now you're just somebody that I used to know
Now you're just somebody that I used to know
Now you're just somebody that I used to know
Now and then I think of all the times you screwed me over
But had me believing it was always something that I'd done
But I don't wanna live that way
Reading into every word you say
You said that you could let it go
And I wouldn't catch you hung up on somebody that you used to know
But you didn't have to cut me off
Make out like it never happened and that we were nothing
And I don't even need your love
But you treat me like a stranger and that feels so rough
No you didn't have to stoop so low
Have your friends collect your records and then change your number
I guess that I don't need that though
Now you're just somebody that I used to know
Somebody
I used to know
Somebody
Now you're just somebody that I used to know
Somebody
I used to know
Somebody
Now you're just somebody that I used to know
I used to know
That I used to know
I used to know
Somebody"""
barbrastreisand_txt = """Barbra Streisand
Oo-oo who-oo-oo whooo-oo oo-oo
Oo-oo who-oo-oo whooo-oo oo-oo
Oo-oo who-oo-oo whooo-oo oo-oo
Barbra Streisand
Oo-oo who-oo-oo whooo-oo oo-oo
Oo-oo who-oo-oo whooo-oo oo-oo
Oo-oo who-oo-oo whooo-oo oo-oo
Oo-oo who-oo-oo whooo-oo
Barbra Streisand
Oo-oo who-oo-oo whooo-oo oo-oo
Oo-oo who-oo-oo whooo-oo oo-oo
Oo-oo who-oo-oo whooo-oo
Barbra Streisand
Oo-oo who-oo-oo whooo-oo oo-oo
Oo-oo who-oo-oo whooo-oo oo-oo
Oo-oo who-oo-oo whooo-oo oo-oo
Oo-oo who-oo-oo whooo-oo oo-oo
Oo-oo who-oo-oo whooo-oo oo-oo
Oo-oo who-oo-oo whooo-oo oo-oo
Oo-oo who-oo-oo whooo-oo oo-oo
Oo-oo who-oo-oo whooo-oo
Barbra Streisand
Oo-oo who-oo-oo whooo-oo oo-oo
Oo-oo who-oo-oo whooo-oo oo-oo
Oo-oo who-oo-oo whooo-oo oo-oo
Oo-oo who-oo-oo whooo-oo
Barbra Streisand
Oo-oo oo-oo oo-oo whooo-oo
Oo-oo who-oo-oo whooo-oo oo-oo
Oo-oo oo-oo oo-oo whooo-oo
Oo-oo who-oo-oo whooo-oo
Barbra Streisand
Oo-oo whooo-oo
Oo-oo whooo-oo oo-oo whooo-oo
Oo-oo whooo-oo
Barbra Streisand
Oo-oo who-oo-oo whooo-oo oo-oo
Oo-oo who-oo-oo whooo-oo oo-oo
Oo-oo who-oo-oo whooo-oo oo-oo"""
fakesong_txt = """la la la
ho ho ho
dum dum
di dum"""
# Worksheet 15: File IO and CSV Files
# Concatenate Files
# Expired on Mon 10 Oct 2016, 11:59 pm
def concatenate_files(a, b, c):
a = open(a, 'rb').read()
b = open(b, 'rb').read()
with open(c, 'wb') as f:
f.write(a)
f.write(b)
part1_txt = "Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next.\n"
part2_txt = "First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs.\n"
# Worksheet 15: File IO and CSV Files
# Sorting CSV Records
# Expired on Mon 10 Oct 2016, 11:59 pm
def sort_records(a, b):
a = open(a)
with open(b, 'w') as f:
f.write(a.readline())
l = a.read().split('\n')
if not l[-1]:
l = l[:-1]
l.sort(key=lambda a: a.split(',')[0])
for i in l:
f.write(i + '\n')
max_temp_csv = """city/month,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec
Melbourne,41.2,35.5,37.4,29.3,23.9,16.8,18.2,25.7,22.3,33.5,36.9,41.1
Brisbane,31.3,40.2,37.9,29,30,26.7,26.7,28.8,31.2,34.1,31.1,31.2
Darwin,34,34,33.2,34.5,34.8,33.9,32,34.3,36.1,35.4,37,35.5
Perth,41.9,41.5,42.4,36,26.9,24.5,23.8,24.3,27.6,30.7,39.8,44.2
Adelaide,42.1,38.1,39.7,33.5,26.3,16.5,21.4,30.4,30.2,34.9,37.1,42.2
Canberra,35.8,29.6,35.1,26.5,22.4,15.3,15.7,21.9,22.1,30.8,33.4,35
Hobart,35.5,34.1,30.7,26,20.9,15.1,17.5,21.7,20.9,24.2,30.1,33.4
Sydney,30.6,29,35.1,27.1,28.6,20.7,23.4,27.7,28.6,34.8,26.4,30.2
"""
# Worksheet 15: File IO and CSV Files
# Hottest Month
# Expired on Mon 10 Oct 2016, 11:59 pm
def max_city_temp(f, c):
f = open(f)
for i in f:
i = i.split(',')
if i[0] == c:
return max(map(float, i[1:]))
max_temp_csv = """city/month,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec
Melbourne,41.2,35.5,37.4,29.3,23.9,16.8,18.2,25.7,22.3,33.5,36.9,41.1
Brisbane,31.3,40.2,37.9,29,30,26.7,26.7,28.8,31.2,34.1,31.1,31.2
Darwin,34,34,33.2,34.5,34.8,33.9,32,34.3,36.1,35.4,37,35.5
Perth,41.9,41.5,42.4,36,26.9,24.5,23.8,24.3,27.6,30.7,39.8,44.2
Adelaide,42.1,38.1,39.7,33.5,26.3,16.5,21.4,30.4,30.2,34.9,37.1,42.2
Canberra,35.8,29.6,35.1,26.5,22.4,15.3,15.7,21.9,22.1,30.8,33.4,35
Hobart,35.5,34.1,30.7,26,20.9,15.1,17.5,21.7,20.9,24.2,30.1,33.4
Sydney,30.6,29,35.1,27.1,28.6,20.7,23.4,27.7,28.6,34.8,26.4,30.2
"""
# Worksheet 15: File IO and CSV Files
# Hottest City
# Expired on Mon 10 Oct 2016, 11:59 pm
def hottest_city(fn):
f = open(fn)
cn = []
cv = 0
for i in f:
i = i.split(',')
n = i[0]
for j in i[1:]:
try:
j = float(j)
if j > cv:
cv = j
cn = [n]
elif j == cv:
cn.append(n)
except:
pass
return (cv, sorted(cn))
max_temp_tiny_csv = """city/month,Jan,Feb,Mar,Apr
Melbourne,41.2,35.5,37.4,29.3
Brisbane,31.3,40.2,37.9,29
Darwin,34,34,33.2,34.5"""
max_temp_csv = """city/month,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec
Melbourne,41.2,35.5,37.4,29.3,23.9,16.8,18.2,25.7,22.3,33.5,36.9,41.1
Brisbane,31.3,40.2,37.9,29,30,26.7,26.7,28.8,31.2,34.1,31.1,31.2
Darwin,34,34,33.2,34.5,34.8,33.9,32,34.3,36.1,35.4,37,35.5
Perth,41.9,41.5,42.4,36,26.9,24.5,23.8,24.3,27.6,30.7,39.8,44.2
Adelaide,42.1,38.1,39.7,33.5,26.3,16.5,21.4,30.4,30.2,34.9,37.1,42.2
Canberra,35.8,29.6,35.1,26.5,22.4,15.3,15.7,21.9,22.1,30.8,33.4,35
Hobart,35.5,34.1,30.7,26,20.9,15.1,17.5,21.7,20.9,24.2,30.1,33.4
Sydney,30.6,29,35.1,27.1,28.6,20.7,23.4,27.7,28.6,34.8,26.4,30.2
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment