bdavs3 / lmu-programming-languages-projects Goto Github PK
View Code? Open in Web Editor NEWSpring 2018 – Homework assignments and other material relevant to LMU CMSI 386: Programming Languages.
Spring 2018 – Homework assignments and other material relevant to LMU CMSI 386: Programming Languages.
All tests pass and linter is happy
You should use the built-in crypto module in Node and not bring in a deprecated one (-2)
function change(amt) {
Don't use abbreviations like amt
, str
, lim
. You have way too many abbreviations all over the place. Not a good habit. (-3)
if (amt < 0) { throw new RangeError(); }
const result = [];
let remaining = amt;
[25, 10, 5, 1].forEach((coin) => {
result.push(Math.floor(remaining / coin));
remaining %= coin;
});
return result;
}
function stripQuotes(str) {
let result = '';
for (let i = 0; i < str.length; i += 1) {
if (str.charAt(i) !== '"' && str.charAt(i) !== '\'') {
Use square brackets, not charAt
(-1)
result += str.charAt(i);
}
}
return result;
}
function scramble(str) {
let result = '';
const charArr = str.split('');
charArr.forEach((char) => {
const random = Math.floor(Math.random() * str.length);
[charArr[str.indexOf(char)], charArr[random]] =
[charArr[random], charArr[str.indexOf(char)]];
});
for (let i = charArr.length; i > 0; i -= 1) {
const random = Math.floor(Math.random() * i);
[charArr[i - 1], charArr[random]] = [charArr[random], charArr[i - 1]];
}
Your swapping code appears twice (-2)
charArr.forEach((char) => { result += char; });
return result;
}
function powers(base, lim, callback) {
for (let currentPow = 1; currentPow <= lim; currentPow *= base) {
callback(currentPow);
}
}
function* powersGenerator(base, lim) {
let currentPow = 1;
while (currentPow <= lim) {
yield currentPow;
currentPow *= base;
}
}
function say(str) {
if (str === undefined) { return ''; }
let result = `${str} `;
const nextWord = (next) => {
if (next !== undefined) {
result += `${next} `;
return nextWord;
}
return result.trim();
I get that the trim is because you always add words with a space and then you have to remove the last space when you're done, but it really feels like a hack (-1)
};
return nextWord;
}
function interleave(arr, ...args) {
const a = arr.slice();
const b = args.slice();
const result = [];
while (a.length > 0 || b.length > 0) {
if (a[0] !== undefined) { result.push(a.shift()); }
if (b[0] !== undefined) { result.push(b.shift()); }
}
return result;
}
function cylinder(spec) {
let { radius = 1, height = 1 } = spec;
const volume = () => Math.PI * radius * radius * height;
const surfaceArea = () =>
(2 * Math.PI * radius * height) + (2 * Math.PI * radius * radius);
const widen = (factor) => { radius *= factor; };
const stretch = (factor) => { height *= factor; };
const result = {
volume, surfaceArea, widen, stretch,
};
Object.defineProperty(result, 'radius', { get: () => radius });
Object.defineProperty(result, 'height', { get: () => height });
return Object.freeze(result);
}
const crypto = require('crypto');
Requires look better at the top (-1)
function makeCryptoFunctions(key, alg) {
const encrypt = (str) => {
const cipher = crypto.createCipher(alg, key);
let crypted = cipher.update(str, 'utf8', 'hex');
crypted += cipher.final('hex');
return crypted;
};
const decrypt = (str) => {
const decipher = crypto.createDecipher(alg, key);
let decrypted = decipher.update(str, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
};
return [encrypt, decrypt];
}
const rp = require('request-promise');
function randomName(spec) {
const options = {
uri: 'http://uinames.com/api/',
qs: {
amount: 1,
gender: spec.gender,
region: spec.region,
},
json: true,
};
return rp(options).then(response => `${response.surname}, ${response.name}`)
.catch(err => err.status);
}
module.exports = {
change,
stripQuotes,
scramble,
powers,
powersGenerator,
say,
interleave,
cylinder,
makeCryptoFunctions,
randomName,
};
Score = 90/100
Problem | Out of | You got | Comments |
---|---|---|---|
1 | 5 | 5 | |
2 | 5 | 5 | |
3 | 5 | 4 | It's not called a rest parameter and also better to say "accepts" than "passes" |
4 | 5 | 3 | Nice work but there is more you could have researched / tried because the true answer is more involved than this. |
5 | 5 | 5 | |
6 | 5 | 2 | Need templates; raw array needs length |
7 | 15 | 11 | Approach with hard coded delimiters is not sustainable and not what was asked. I used the program itself as input and got crazy (incorrect output). Code itself has too much in main and is not modular enough. Good effort fixing up the output though. |
8 | 15 | 4 | https://github.com/bdavs3/lmu-cmsi-386/blob/master/homework3/say.cpp is not implemented. Partial credit for writing the tests. |
9 | 30 | 28 | Move constructor should be = default |
10 | 10 | 7 | Did not include queue.h so when I ran it I got compiler errors |
TOTAL | 100 | 74 |
# pragma pylint: disable=E0001
# pragma pylint: disable=C0111
# pragma pylint: disable=C0103
import math
from random import shuffle
from itertools import product
from Crypto.Cipher import AES
import requests
def change(amount):
if amount < 0:
raise ValueError('amount cannot be negative')
result = []
for c in (25, 10, 5, 1):
result += [amount // c]
append
looks better (more Pythonic) -1
amount %= c
return tuple(result)
def strip_quotes(string):
return string.replace('\'', '').replace('"', '')
def scramble(string):
result = list(string)
shuffle(result)
return ''.join(result)
def powers(base, limit):
current = 1
while current <= limit:
yield current
current *= base
def triples(largest_hypotenuse):
result = []
pairs = list(product(range(1, largest_hypotenuse), repeat=2))
I appreciate you trying to be clever but you can't be doing this in practice. First this pre-generates a massive list and sucks up too much memory. At least stick with the generator. Then you go through and remove things you don't need. Find a way to generate just the pairs you will be needed; never over generate then remove. A simple ((i,j) for i in range(limit+1) for j in range(i,limit+1))
is better. -2
for i, j in pairs:
if (j, i) in pairs:
pairs.remove((j, i))
for a, b in pairs:
c = math.sqrt(a * a + b * b)
if c % 1 == 0 and c <= largest_hypotenuse:
Use is_integer
rather than modding. In general, use this as a learning experience. Figure out what you want to do (at a high level) then google it. You should have googled "how to determine if Python float is an integer" rather than just using old knowledge, which frankly is out of data even in JS. When you took 185, we did % 1 === 0
but these days in Modern JS we have Number.isInteger
also. -1
result += [(a if a < b else b, b if b > a else a, int(c))]
Use min
and max
as they are more readable. -1
Also, again use append
return result
def say(string1=None):
if string1 is None:
return ''
def _inner_say(string2=None):
"""
if val is None we return _inner_adder.v
else we increment and return ourselves
"""
if string2 is None:
return _inner_say.string1
_inner_say.string1 += ' ' + string2
return _inner_say
_inner_say.string1 = string1 # save value
return _inner_say
Don't use names like _inner_say
. The innerness here refers to your implementation. Use names meaningful to the application, that is, the human reader. Note how I called mine say_more
. -1
def interleave(a, *b):
return [a[0]] + interleave(list(b), *a[1:]) if a else list(b)
Awwww, I like it!
class Cylinder(object):
def __init__(self, radius=1, height=1):
self.radius = radius
self.height = height
@property
def surface_area(self):
return 2 * math.pi * (self.radius * self.radius + self.radius * self.height)
@property
def volume(self):
return self.radius * self.radius * math.pi * self.height
def widen(self, factor):
self.radius *= factor
def stretch(self, factor):
self.height *= factor
def make_crypto_functions(key, initialization_vector):
def create_cipher():
return AES.new(key.encode(), AES.MODE_CBC, initialization_vector.encode())
def byte_encrypt(byte_string):
return create_cipher().encrypt(byte_string)
def byte_decrypt(byte_string):
return create_cipher().decrypt(byte_string)
return (byte_encrypt, byte_decrypt)
def random_name(gender, region):
I was looking for a way that you could force your caller to take kwargs -1
response = requests.get('http://uinames.com/api', \
params={'gender': gender, 'region': region, 'amount': '1'})
if response.status_code == 400:
FYI 400 is not the only possible error, but probably okay in this case.
raise ValueError(response.text)
person = response.json()
return '{}, {}'.format(person['surname'], person['name'])
Score 93/100
Debug.crash
and did not try to make the tests pass. -20(..)
from your module. Works in your case but is not good practice in general. -1(..)
-1change
(used numbers multiple times) -1List.sum
to List.foldr (+)
Score: 76/100
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.