Skip to content

Commit

Permalink
new exercises
Browse files Browse the repository at this point in the history
  • Loading branch information
Alessandro Giordo committed Feb 12, 2016
1 parent 2496d10 commit c6cda3d
Show file tree
Hide file tree
Showing 15 changed files with 262 additions and 0 deletions.
18 changes: 18 additions & 0 deletions Js/average.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
var average = function (n) {
if (typeof n === 'string') {return "Incorrect"}
var length = n.length;
return n.reduce(function (a, b) {return a + b;}) / length;
}

// or mine

var average = (n) => {
if (typeof n === "string") return "Incorrect";
else {
var x=0;
for (i=0;i<n.length;i++) {
x += n[i];
}
return parseFloat(x/n.length);
}
}
File renamed without changes.
51 changes: 51 additions & 0 deletions Js/parsing_time_regex.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
String.prototype.toSeconds = function(){
var re = /^(?:(?:(\d{2}):)?(\d{2}):)?(\d{2})$/; // very confusing regex but does the job
var reggy = re.exec(this);
if (reggy == null) return null;
if (reggy[2] > 59 || reggy[3] > 59) return null;
else {
var seconds = (3600*reggy[1]|0)+(60*reggy[2]|0)+(reggy[3]|0);
return seconds;
}
}

// or

String.prototype.toSeconds=function(){
var times = this.match(/^([0-9][0-9]):([0-5][0-9]):([0-5][0-9])$/); // this regex explains a lot
return (times) ? (+times[1] * 3600) + (+times[2] * 60) + (+times[3]) : null;
}

"00:00:00".toSeconds(); // 0
"01:02:60".toSeconds(); // 3723
"01:60:03".toSeconds(); // null
"\n00:00:00".toSeconds(); // null

// http://www.codingforums.com/javascript-programming/128474-regex-match-time-format-hh-mm-ss.html

/*
As for an explanation of the way the substitution function sent to the replace function works:
It takes n+3 arguments where n is the number of capturing groups in the regex.
The first argument is the entire matched string.
Then there is one argument per capturing group,
followed by one argument for the index of the match within the searched string,
and finally one argument containing the searched string.


http://stackoverflow.com/questions/8318236/regex-pattern-for-hhmmss-time-string
^(?:(?:([01]?\d|2[0-3]):)?([0-5]?\d):)?([0-5]?\d)$

^ # Start of string
(?: # Try to match...
(?: # Try to match...
([01]?\d|2[0-3]): # HH:
)? # (optionally).
([0-5]?\d): # MM: (required)
)? # (entire group optional, so either HH:MM:, MM: or nothing)
([0-5]?\d) # SS (required)
$


http://stackoverflow.com/questions/6267714/regex-find-time-values
[0-9]{1,2}:[0-9]{2} (AM|PM)
\d{1,2}:\d{2} (AM|PM)
6 changes: 6 additions & 0 deletions Js/polyfillisArray.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Array.isArray = function(value) {
return Object.prototype.toString.call(value) === '[object Array]';
};

Array.isArray([1,2,3]); // true
Array.isArray("no array"); // false
11 changes: 11 additions & 0 deletions Js/remove_duplicates_string_and_array.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
var uniqueInOrder = function(iterable){
if (iterable.constructor === Array){
iterable.forEach(function(x) { this.add(x); });
}
else {
var uniqueList = iterable.split('').filter(function(item,i,allItems){
return i == allItems.indexOf(item);
}).join(',');
return uniqueList;
}
}
3 changes: 3 additions & 0 deletions Js/sort_array_ascending.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
function liftoff(instructions){
return instructions.sort(function(a, b){return b-a}).join(" ") + " liftoff!";
}
30 changes: 30 additions & 0 deletions Js/test_us_phonenumber.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
function validPhoneNumber(phoneNumber){
return /^\(?([0-9]{3})\)\s([0-9]{3})-([0-9]{4})$/.test(phoneNumber);
}

// or

function validPhoneNumber(phoneNumber){
return /^\(\d{3}\) \d{3}\-\d{4}$/.test(phoneNumber);
}

/* from https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s02.html
Problem
You want to determine whether a user entered a North American phone number, including the local area code, in a common format. These formats include 1234567890, 123-456-7890, 123.456.7890, 123 456 7890, (123) 456 7890, and all related combinations. If the phone number is valid, you want to convert it to your standard format, (123) 456-7890, so that your phone number records are consistent.
Solution
A regular expression can easily check whether a user entered something that looks like a valid phone number. By using capturing groups to remember each set of digits, the same regular expression can be used to replace the subject text with precisely the format you want.
^\(?([0-9]{3})\)?[-.●]?([0-9]{3})[-.●]?([0-9]{4})$
var phoneRegex = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if (phoneRegex.test(subjectString)) {
var formattedPhoneNumber =
subjectString.replace(phoneRegex, "($1) $2-$3");
} else {
// Invalid phone number
}
*/
55 changes: 55 additions & 0 deletions Js/unique_in_order.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
var uniqueInOrder = function(iterable){
if (typeof iterable[0] === 'undefined') return [];
if (iterable.constructor === String){
var uniqueList = iterable.split('');
var ret = [uniqueList[0]];
for (var i = 1; i < uniqueList.length; i++) { // start loop at 1 as element 0 can never be a duplicate
if (uniqueList[i-1] !== uniqueList[i]) {
ret.push(uniqueList[i]);
}
}
return ret;
}
if (iterable.constructor === Array){
iterable = iterable.sort(function (a, b) { return a*1 - b*1; });
var ret = [iterable[0]];
for (var i = 1; i < iterable.length; i++) { // start loop at 1 as element 0 can never be a duplicate
if (iterable[i-1] !== iterable[i]) {
ret.push(iterable[i]);
}
}
return ret;
}
}

Test.assertSimilar(uniqueInOrder([1,2,2,3,3]), [1,2,3])
Test.assertSimilar(uniqueInOrder('AAAABBBCCDAABBB'), ['A','B','C','D','A','B'])

// way smaller :

function uniqueInOrder(it) {
var result = [];
var last
console.log(last); // this is undefined on purpose to check if undefined and return result (empty) if empty array
for (var i = 0; i < it.length; i++) {
console.log(it[i]);
if (it[i] !== last) {
result.push(last = it[i]);
}
}
return result;
}
uniqueInOrder("AAAABBBCCDAABBB"); // so strings can be counted as arrays no need to split or join

// another option

var uniqueInOrder = function(iterable){
var result = [];
for (var i = 0; i < iterable.length; i++) {
if (/*this doesn't make sense ->> iterable[i-1] === undefined || */iterable[i-1] !== iterable[i]) {
result.push(iterable[i]);
}
}
return result; // returns it empty if not true for the if statement
}
uniqueInOrder([1,2,2,3,3]);
9 changes: 9 additions & 0 deletions Py/class_namespace.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
class Person:
def __init__(self, name):
self.name = name

def greet(self, other_name):
return "Hi {0}, my name is {1}".format(other_name, self.name)

x = Person("Joe")
x.greet("Alex")
16 changes: 16 additions & 0 deletions Py/dice_rolling.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import random

def dice(minimum, maximum):
for x in range(minimum, maximum):
return random.randint(minimum, maximum)

dice(1, 12)

# or shorter


import random

def dice(minimum, maximum):
for x in range(minimum, maximum):
return random.randint(minimum, maximum)
8 changes: 8 additions & 0 deletions Py/disemvowel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import re
def disemvowel(string):
return re.sub(r'[aeiouAEIOU]','', string)

# or

def disemvowel(s):
return s.translate(None, "aeiouAEIOU") # removes right argument from s replacing with None
10 changes: 10 additions & 0 deletions Py/find_us_phone_number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import re
def validPhoneNumber(phoneNumber):
p = re.compile(ur'^\(?[0-9]{3}\)\s[0-9]{3}-[0-9]{4}$')
return bool(re.search(p, phoneNumber))

# shorter:

def validPhoneNumber(phoneNumber):
import re
return bool(re.match(r"^(\([0-9]+\))? [0-9]+-[0-9]+$", phoneNumber))
3 changes: 3 additions & 0 deletions Py/match_PIN.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import re
def validate_pin(pin):
return bool(re.match('^(\d{4}|\d{6})$', pin))
35 changes: 35 additions & 0 deletions Py/only_whitespace.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import re
def whitespace(string):
return bool(re.match('^\s*$', string))


# if we want to exclude empty string use '^\s+$'

# or

def whitespace(string):
return not string or string.isspace()


import re

def whitespace(string):
#your code here
if string == '':
return True
else:
return string.isspace()

# or


def whitespace(string):
if string.strip() == "":
return True
else:
return False

# or

def whitespace(string):
return not (string.strip())
7 changes: 7 additions & 0 deletions Py/time_in_milliseconds.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
def past(h, m, s):
return ((h * 60) * 60000) + (m * 60000) + (s * 1000)

# or

def past(h, m, s):
return (s + (m + h * 60) * 60) * 1000

0 comments on commit c6cda3d

Please sign in to comment.