Showing posts with label codecademy. Show all posts
Showing posts with label codecademy. Show all posts

# Codecademy: Ruby


1. Introduction to Ruby

my_num = 25
my_boolean = true
my_string = "Ruby"

3+3
3-3
3*3
3/3
3**3
3%3

puts "What's up" # newline
print "Montalvo"

"I love espresso".length
"Eric".reverse
puts "eric".upcase
puts "ERIC".downcase
puts "Eric".downcase.reverse.upcase

=begin
I'm a comment!
I don't need any # symbols.
=end

print "What's your first name?"
first_name = gets.chomp
first_name.capitalize!
puts "Your name is #{first_name}"
2. Control Flow in Ruby

x = 1
y = 2
if x < y
  puts "x is less than y!"
elsif x > y
  puts "x is greater than y!"
else
  puts "x equals y!"
end

hungry = false
unless hungry
  puts "I'm writing Ruby programs!"
else
  puts "Time to eat!"
end

is_true = 2 != 3
is_false = 2 == 3
test_1 = 17 > 16
test_2 = 21 < 30
test_3 = 9 >= 9
test_4 = -11 <= 4

true && true # => true
false || false # => false
!true # => false
(3 < 4 || false) && (false || true)
3. Looping with Ruby

counter = 1
while counter < 11
  puts counter
  counter += 1
end

counter = 1
until counter > 11
  puts counter
  counter += 1
end

for num in 1...10 # 1-9
  puts num
end

for num in 1..10 # 1-10
  puts num
end

i = 20
loop do
  i -= 1
  next if i % 2 != 0
  print "#{i}"
  break if i <= 0
end

my_array = [1,2,3,4,5]

array = [1,2,3,4,5]
array.each do |x|
  x += 10
  print "#{x}"
end

odds = [1,3,5,7,9]
odds.each do |n|
  print n*2
end

10.times { print "Chunky bacon!" }
4. Arrays and Hashes

demo_array = [100, 200, 300, 400, 500]
print demo_array[2]

multi_d_array = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
multi_d_array.each { |x| puts "#{x}\n" }

my_hash = {
  "name" => "Eric",
  "age" => 26,
  "hungry?" => true
}
puts my_hash["name"]
puts my_hash["age"]
puts my_hash["hungry?"]

pets = Hash.new
pets["Stevie"] = "cat"
pets["John"] = "dog"
pets.each { |x, y| puts "#{x}: #{y}" }
5. Blocks and Sorting

def puts_1_to_10
  (1..10).each { |i| puts i }
end
puts_1_to_10

def cubertino(n)
  puts n ** 3
end
cubertino(8)

def what_up(greeting, *bros)
  bros.each { |bro| puts "#{greeting}, #{bro}!" }
end
what_up("What up", "Justin", "Ben", "Kevin Sorbo")

my_array = [3, 4, 8, 7, 1, 6, 5, 9, 2]
my_array.sort!

book_1 = "A Wrinkle in Time"
book_2 = "A Brief History of Time"
c = book_1 <=> book_2 # -1 (>), 0 (=), 1 (<)
6. Hashes and Symbols

symbol_hash = {
  :symbol1 => 1, # symbol1: 1,
  :symbol2 => 2, # symbol2: 2,
  :symbol3 => 3  # symbol3: 3
}

strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
symbols = Array.new
strings.each do |string|
    symbols.push(string.to_sym) # or string.intern
end

movie_ratings = {
  memento: 1,
  primer: 2,
  the_matrix: 3,
}
good_movies = movie_ratings.select { |m, r| r > 2 }
movie_ratings.each_key { |k| puts k }
movie_ratings.each_value { |v| puts v }
7. Refactoring

ruby_is_eloquent = true
ruby_is_ugly = false
puts "Ruby is eloquent!" if ruby_is_eloquent
puts "Ruby's not ugly!" unless ruby_is_ugly

puts 1>0 ? "True" : "False" # Ternary conditional expression

case greeting
  when "English" then puts "Hello!"
  when "French"  then puts "Bonjour!"
  when "German"  then puts "Guten Tag!"
  when "Finnish" then puts "Haloo!"
  else puts "I don't know that language!"
end

favorite_book = nil
favorite_book ||= "Guide to Ruby" # set
favorite_book ||= "Guide to Perl" # not set

def add(a,b)
  return a + b # a + b (without return)
end

"L".upto("P") { |l| puts l }

age = 26
age.respond_to?(:next) # true (27)

alphabet = ["a", "b", "c"]
alphabet << "d" # alphabet.push("d")
caption = "A giraffe surrounded by "
caption << "weezards!" # caption += "weezards!"

age = 26
I am " + age.to_s + " years old."
I am " << age.to_s << " years old."
I am #{age} years old."
8. Blocks, Procs, and Lambdas

fibs = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
doubled_fibs = fibs.collect { |f| f*2 }

def double(p)
  yield p
end
double(1){ |x| x*2 }

floats = [1.2, 3.45, 0.91, 7.727, 11.42, 482.911]
round_down = Proc.new { |x| x.floor }
ints = floats.collect(&round_down)

hi = Proc.new { puts "Hello!" }
hi.call

numbers_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
strings_array = numbers_array.collect(&:to_s)

strings = ["leonardo", "donatello", "raphael", "michaelangelo"]
symbolize = lambda { |s| s.to_sym }
symbols = strings.collect(&symbolize)
9. Object-Oriented Programming, Part I

class Person
  def initialize(name)
    @name = name
  end
end
me = Person.new("Eric")

class MyClass
  $my_variable = "Hello!" # global var
end
puts $my_variable

class Person
  @@people_count = 0 # class variable
  def initialize(name,age,profession)
    @name = name # instance var
    @age = age
    @profession = profession
  end
end

class ApplicationError
  def display_error
    puts "Error! Error!"
  end
end
class SuperBadError < ApplicationError # inheritance
  def display_error # override
    puts "SuperError! SuperError!"
    super # call parent method
  end
end
err = SuperBadError.new
err.display_error
10. Object-Oriented Programming, Part II

class Dog
  def initialize(name,breed)
    @name = name
    @breed = breed
  end
  public
  def bark
    puts "Woof!"
  end
  private
  def id
    @id_number = 12345
  end
end

module Circle
  PI = 3.141592653589793
  def Circle.area(radius)
    PI * radius**2
  end
  def Circle.circumference(radius)
    2 * PI * radius
  end
end

puts Math::PI
require 'date'
puts Date.today

module Action
  def jump
    @distance = rand(4) + 2
    puts "I jumped forward #{@distance} feet!"
  end
end
class Rabbit
  include Action
  attr_reader :name
  def initialize(name)
    @name = name
  end
end
peter = Rabbit.new("Peter")
peter.jump

module ThePresent
  def now
    puts "Time"
  end
end
class TheHereAnd
  extend ThePresent
end
TheHereAnd.now

# Codecademy: Python


1. Python Syntax

print "Welcome to Python!"
my_int = 7
my_float = 1.23
my_bool = True

my_int = 7
my_int = 3
print my_int

def spam():
    eggs = 12
    return eggs
print spam()

# just a comment
"""
first comment
second comment
third comment
"""

count_to = 1 + 2
count_to = 5 - 2
ni = 2 * 10
ni = 20 / 4
eggs = 10 ** 2
spam = 3 % 2
2. Strings and Console Output

'Help! Help! I\'m being repressed!'

fifth_letter = "MONTY"[4]

parrot = "Norwegian Blue"
print len(parrot)
print parrot.lower()
print parrot.upper()

pi = 3.14
print str(pi)

print "Spam " + "and " + "eggs"
print "The value of pi is around " + str(3.14)

string_1 = "Camelot"
string_2 = "place"
print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)

name = raw_input("What is your name?")
quest = raw_input("What is your quest?")
color = raw_input("What is your favorite color?")
print "Ah, so your name is %s, your quest is %s, and your favorite color is %s." % (name, quest, color)
3. Conditionals and Control Flow

# / and * are evaluated before + and -
bool_one = 17 < 118 % 100
bool_two = 100 == (33 * 3) + 1
bool_three = 19 <= 2**4
bool_four = -22 >= -18
bool_five = 99 != 98 + 1

# not is evaluated first, and is evaluated next, or is evaluated last
"""
True and True is True
False or False is False
Not True is False
Not False is True
"""

answer=7
if 5 <= answer:
    print 1
elif answer < 5:
    print -1
else:
    print 0
4. Functions

def square(n):
    """Returns the square of a number."""
    squared = n**2
    print "%d squared is %d." % (n, squared)
    return squared

def favorite_actors(*args):
    """Prints out your favorite actorS (plural!)"""
    print "Your favorite actors are:" , args
favorite_actors("Michael Palin", "John Cleese", "Graham Chapman")

def cube(number):
    return number**3
def by_three(number):
    if number%3 == 0:
        return cube(number)
    else:
        return False
by_three(9)

import math
print math.sqrt(25)
from math import sqrt
print sqrt(25)
from math import *
print sqrt(25)

print max(-10, -5, 5, 10)
print min(-10, -5, 5, 10)
print abs(-10)

print type(42) # => integer
print type(4.2) # => float
print type('spam') # => unicode
print type({'Name':'John Cleese'}) # => dict
print type((1,2)) # => tuple
5. Lists and Dictionaries

zoo_animals = ["pangolin", "cassowary", "sloth", "tiger"]
print zoo_animals[0]

suitcase = []
suitcase.append("sunglasses")
list_length = len(suitcase)

suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]
first = suitcase[0:2]
middle = suitcase[2:4]
last = suitcase[4:6]

animals = "catdogfrog"
cat = animals[:3]
dog = animals[3:6]
frog = animals[6:]

animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
duck_index = animals.index("duck")
animals.insert(duck_index,"cobra")

my_list = [1,9,3,8,5,7]
for number in my_list:
    print number * 2

start_list = [5, 3, 1, 2, 4]
square_list = []
for number in start_list:
    square_list.append(number**2)
square_list.sort()
print square_list

residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}
print residents['Puffin']
print residents['Sloth']
print residents['Burmese Python']

menu = {}
menu['Chicken Alfredo'] = 14.50
menu['Spam'] = 2.50
print "There are " + str(len(menu)) + " items on the menu."
zoo_animals = { 'Unicorn' : 'Cotton Candy House','Rockhopper Penguin' : 'Arctic Exhibit'}
del zoo_animals['Unicorn']
zoo_animals['Rockhopper Penguin'] = 'Anything other'

beatles = ["john","paul","george","ringo","stuart"]
beatles.remove("stuart")
6. Lists and Functions

n = [1, 3, 5]
n.pop(0)

n = [3, 5, 7]
def print_list(x):
    for i in range(0, len(x)):
        print x[i]
print_list(n)

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(x):
    r=[]
    for i in x:
        for j in i:
            r.append(j)
    return r
print flatten(n)
7. Loops

while count < 10:
    print "Hello, I am a while and count is", count
    count += 1

choice = raw_input('Enjoying the course? (y/n)')
while choice != 'y' and choice != 'n':
    choice = raw_input("Sorry, I didn't catch that. Enter again: ")

from random import randrange
random_number = randrange(1, 10)
count = 0
while count < 3:
    guess = int(raw_input("Enter a guess:"))
    if guess == random_number:
        print 'You win!'
        break
    count += 1
else:
    print 'You lose.'

for i in range(20):
    print i

word = "eggs!"
for c in word:
    print c

d = {'x': 9, 'y': 10, 'z': 20}
for key in d:
    print key,d[key]

choices = ['pizza', 'pasta', 'salad', 'nachos']
for index, item in enumerate(choices):
    print index+1, item

list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
for a, b in zip(list_a, list_b):
    print max(a,b)

for i in range(1,10):
    print i
else:
    print i+1
8. Advanced Topics in Python

my_dict = {"Name": "Guido", "Age": 56, "BDFL": True}
print my_dict.items()
print my_dict.keys()
print my_dict.values()
for i in my_dict:
    print i, my_dict[i]

even_squares = [i ** 2 for i in range(1,11) if i ** 2 % 2 == 0]
print even_squares

l = [i ** 2 for i in range(1, 11)]
print l[2:9:2]

my_list = range(1, 11)
print my_list[::2]

to_one_hundred = range(101)
backwards_by_tens = to_one_hundred[::-10]
print backwards_by_tens

languages = ["HTML", "JavaScript", "Python", "Ruby"]
print filter(lambda l: l == "Python", languages)

squares=[i ** 2 for i in range(1,11)]
print filter(lambda s: 30 <= s <= 70, squares)

garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX"
message = filter(lambda g: g != "X" , garbled[::])
print message
9. Introduction to Bitwise Operators

print 5 >> 4  # Right Shift
print 5 << 1  # Left Shift
print 8 & 5   # AND
print 9 | 4   # OR
print 12 ^ 42 # XOR
print ~88     # NOT

print 0b11 * 0b11 # 9

print bin(2) # 0b10

print int("0b11001001", 2) # 201

print bin(0b1110 & 0b101) # 0b100
print bin(0b1110 | 0b101) # 0b1111
print bin(0b1110 ^ 0b101) # 0b1011

def check_bit4(number):
    if number & 0b1000 == 0b1000:
        return "on"
    else:
        return "off"

a = 0b11101110
def flip(number):
    i = 0
    while 2**i-1 < number:
        i+=1
    return number^2**i-1
print bin(flip(a))
10. Introduction to Classes

class ShoppingCart(object):
    items_in_cart = {}
    def __init__(self, customer_name):
        self.customer_name = customer_name
    def add_item(self, product, price):
        if not product in self.items_in_cart:
            self.items_in_cart[product] = price
            print product + " added."
        else:
            print product + " is already in the cart."
    def remove_item(self, product):
        if product in self.items_in_cart:
            del self.items_in_cart[product]
            print product + " removed."
        else:
            print product + " is not in the cart."
my_cart = ShoppingCart("John")
my_cart.add_item("Aquarius",1)

class Employee(object):
    def __init__(self, employee_name):
        self.employee_name = employee_name
    def calculate_wage(self, hours):
        self.hours = hours
        return hours * 20.00
class PartTimeEmployee(Employee):
    def calculate_wage(self, hours):
        self.hours = hours
        return hours * 12
    def full_time_wage(self, hours):
        return super(PartTimeEmployee, self).calculate_wage(hours)
milton = PartTimeEmployee("Milton")
print milton.full_time_wage(10)
11. File Input and Output

my_list = [i**2 for i in range(1,11)]

f = open("output.txt", "w")
for item in my_list:
    f.write(str(item) + "\n")
f.close()

f = open("output.txt", "r")
print f.read()
f.close()

f = open("output.txt", "r")
print f.readline()
print f.readline()
f.close()

with open("text.txt", "w") as my_file:
    my_file.write("Success!")   
print my_file.closed # True

# Codecademy: JavaScript


1. Introduction

"text";
"text".length;
3 + 4;
4 / 2;
14 % 3;
//comment
confirm("I feel awesome");
prompt("What is your name?");
["I'm coding like a champ!".length] > 10
console.log("Hello");
console.log(15 > 4);
console.log("Xiao Hui".length < 122);
console.log("Goody Donaldson".length != 8);
console.log(8*2 === 16);
console.log(true !== true);
if ( 1 > 2 ) {
 alert("I am right");
} else {
 console.log("I am wrong");
}
"wonderful day".substring(3,7);
var myName = "Leng";
var myAge = 30;
var isOdd = true;
myName.length;
var age = prompt("What's your age?");
2. Functions

var divideByThree = function (number) {
 var val = number / 3;
 console.log("Result = " + val);
};
divideByThree(6);

var timesTwo = function(number) {
 return number * 2;
};
var newNumber = timesTwo(2);
console.log(newNumber);

var perimeterBox  = function(length, width) {
 return length*2 + width*2;
};
perimeterBox(2,2);

var multiplied = 5; // Global
var timesTwo = function(number) {
 var multiplied = number * 2; // Local
};
timesTwo(4);
console.log(multiplied);
3. 'For' Loops

for (var counter = 1; counter < 11; counter++) {
 console.log(counter);
}

for (var i = 5; i <= 50; i+=5) {
 console.log(i);
}

for (var i = 10; i >= 0; i--) {
 console.log(i);
}

for (var i = 100; i >= 1; i-=5) {
 console.log(i);
}

var junk = ["Mao","Gandhi",1,2];
console.log(junk);
console.log(junk[0]);
console.log(junk.length);
4. 'While' Loops

var understand = true;
while( understand ){
 console.log("I'm learning while loops!");
 understand = false;
}

loopCondition = false;
do {
 console.log("I'm gonna stop looping 'cause my condition is " + String(loopCondition) + "!");
} while (loopCondition);
5. More on Control Flow

var lunch = prompt("What do you want for lunch?","Type your lunch choice here");
switch(lunch){
 case 'sandwich':
  console.log("Sure thing! One sandwich, coming up.");
  break;
 case 'soup':
  console.log("Got it! Tomato's my favorite.");
  break;
 case 'salad':
  console.log("Sounds good! How about a caesar salad?");
  break;
 case 'pie':
  console.log("Pie's not a meal!");
  break;
 default:
  console.log("Huh! I'm not sure what " + lunch + " is. How does a sandwich sound?");
}

true && true // => true
false || false // => false
!true // => false
!false // => true
6. Data Structures

var newArray = [[11,12,13], [21,22,23], [31,32,33]];
var jagged = [[11,12,13], [21], [31,32]];
var phonebookEntry = {};
phonebookEntry.name = 'Oxnard Montalvo';
phonebookEntry.number = '(555) 555-5555';
phonebookEntry.phone = function() {
 console.log('Calling ' + this.name + ' at ' + this.number + '...');
};
phonebookEntry.phone();

var myObj = new Object();
myObj["name"] = "Charlie";
myObj.name = "Charlie";
7. Objects I

var bob = {};
var bob = {
 name: "Bob Smith",
 age: 30
};
var name = bob.name;
var age = bob.age;

var dog = {
 species: "greyhound",
 weight: 60,
 age: 4
};
var species = dog["species"];
var weight = dog["weight"];
var age = dog["age"];

var bob = new Object();
bob.name = "Bob Smith";
bob.age = 30;
bob.setAge = function (newAge){
 this.age = newAge;
};
bob.setAge(40);

function Person(name,age) {
 this.name = name;
 this.age = age;
}
var bob = new Person("Bob Smith", 30);

var family = new Array();
family[0] = new Person("alice", 40);
family[1] = new Person("bob", 42);

var ageDifference = function(person1, person2) {
  return person1.age - person2.age;
}
var alice = new Person("Alice", 30);
var billy = new Person("Billy", 25);
var diff = ageDifference(alice,billy);
8. Objects II

var myObj = { job: "I'm an object!" };
console.log( typeof myObj ); // => object
console.log( myObj.hasOwnProperty('job') ); // => true

var nyc = {
 fullName: "New York City",
 mayor: "Michael Bloomberg",
 population: 8000000,
 boroughs: 5
};
for (var property in nyc){
 console.log(property);
}
for (var i in nyc){
 console.log(nyc[i]);
}

function Dog (breed) {
 this.breed = breed;
};
var buddy = new Dog("golden Retriever");
Dog.prototype.bark = function() {
 console.log("Woof");
};

function Animal(name, numLegs) {
 this.name = name;
 this.numLegs = numLegs;
}
Animal.prototype.sayName = function() {
 console.log("Hi my name is " + this.name);
};
function Penguin(name){
 this.name = name;
 this.numLegs = 2;
}
Penguin.prototype = new Animal();

function Person(first,last,age) {
 this.firstname = first;
 this.lastname = last;
 this.age = age;
 var bankBalance = 7500; // Private var
 this.getBalance = function() {
  return bankBalance;
 };
 var returnBalance = function() { // Private function
  return bankBalance;
 };     
 this.askTeller = function() {
   return returnBalance;
 }
}