Start with Python

This commit is contained in:
Kenneth Mendonca
2015-07-22 16:44:07 -04:00
parent 94031a251f
commit 57cb3981a0
100 changed files with 2085 additions and 0 deletions

View File

@ -0,0 +1,21 @@
Python Variables, Lists and Dictionaries
========================================
Create a variable named byte and set it equal to "school".
Create a [list](http://www.tutorialspoint.com/python/python_lists.htm) named instructors and have it contain the strings "Armen", "Chris", and "Greg"
Create an [tuple](http://www.tutorialspoint.com/python/python_tuples.htm) named students and have it contain the strings "Adolfo", "Benny", "Billy", "Brendan"
What's the difference between a list and a tuple? Why use one over the other?
Create a dictionary with the following key-value pairs- "byteAcademy":byte, "instructors":instructors, "students":students
Print the keys and values of the dictionary. It should look like this:
```
byteAcademy - School
instructors - Armen, Chris, Greg
students - Adolfo, Benny, Billy, Brendan
```
Check out [.format](https://infohost.nmt.edu/tcc/help/pubs/python/web/new-str-format.html)

View File

View File

@ -0,0 +1,41 @@
Reverse Polish Notation
=======================
You've never done it until you've done it reverse polish.
I don't know what that means, but check this out on [reverse polish notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation).
Reverse polish notation is a mathematical notation in which every operator follows all of its operands. For example:
```
3 4 + = 7
4 2 / = 2
10 7 2 - * 5 / = 10
```
Write a program that accepts a RPN equation as a command line argument, such that you would execute your program:
```
python3 rpn_calc.py 10 9 - 5 +
```
Which would then return you 6, the result of that equation.
#### ARGV
To run the program like this you need to import the sys library and access sys.argv.
ARGV gives us the arguments used to launch the program as an array. The first position is always the application name / file. The next are all others divided by spaces.
Read about sys.argv [here](http://www.pythonforbeginners.com/system/python-sys-argv)
Sandbox with it, so you know what you are getting as an input.
Here's a nice hint - we can "slice" arrays in Python like in JS just by doing:
```
>>> array = ['hi', 'wut', 'm8', 'lol', 'doge']
>>> array[2:4]
['m8', 'lol']
```
#### Testing
Write some assert statements after you've solved the challenge.
**NOTE**: You might need to escape the multiplication operator * when you pass it in. You can escape things by adding a backslash (\) in front of it.

View File

@ -0,0 +1,18 @@
Factorial!
==========
Get the factorial of a given number. Using sys.argv, pass in a number and return it's factorial.
To calculate the factorial of 5, for example, the equation is ```5 * 4 * 3 * 2 * 1 = 120```
#### Iterative
Write the equation iteratively, using a for or while loop. How to use loops in Python is well documented [here](https://docs.python.org/3.4/tutorial/controlflow.html)
#### Bonus
Write this function [recursively](http://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3/Recursion). If you run into difficulty, think about how your stack will develop as your function recurses and remember to define your base case.
Write assert statements to test your code in both cases.
[Wikipedia on Factorials](http://en.wikipedia.org/wiki/Factorial)

View File

@ -0,0 +1,13 @@
import sys
def factorial(num):
#write assert statements below
assert(factorial(5) == 120), "5! should return 120"
assert(factorial(20) == 2432902008176640000), "Well that escalated quickly"

View File

@ -0,0 +1,13 @@
import sys
def factorial(num):
#write assert statements below
assert(factorial(5) == 120), "5! should return 120"
assert(factorial(20) == 2432902008176640000), "Well that escalated quickly"

View File

@ -0,0 +1,13 @@
Sarah Palindrome
================
Write a function that when given a word or sentence returns True if it is a palindrome and False if it isn't.
Your program should accept input using sys.argv.
```
python3 palindrome.py Taco Cat # returns true
```
You will want to make this case insensitive (Cat == cat). You can do this by make all letters upper or lower case.
You will also want to use strip to remove all non word characters.
Make the asserts pass and write more assert statements to test your code.

View File

@ -0,0 +1,12 @@
import sys
def is_palindrome(string):
pass
#TESTS
assert(is_palindrome("greg is the man") == False), "Presumably random sentence should return false"
assert(is_palindrome("No Mel Gibson is a casino's big lemon") == True), "Palindrome should return true"

View File

@ -0,0 +1,9 @@
String Scramble
===============
Write an algorithm that takes a string, and checks if all of the letters of the string are inside of a second string. For example:
```
string_scramble('hello', 'goodbye') # False
string_scramble('hello', 'lolfrhe') # True
```
Write your own assert statements.

View File

@ -0,0 +1,2 @@
def string_scramble(string_one, string_two):
pass

View File

@ -0,0 +1,10 @@
Largest Prime Factor
====================
Write a function that takes a number as input, and returns the largest prime factor of a given number. If the number is prime itself, then it's largest prime factor is itself.
```
largest_prime(15) # 5
largest_prime(18) # 3
largest_prime(19) # 19
largest_prime(302) # 151
```

View File

@ -0,0 +1 @@
def largest_prime(number):

View File

@ -0,0 +1,12 @@
Sieve of Eratosthenes
=====================
The [Sieve of Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) is an algorithm used to determine all the prime numbers below a given number.
#### Pseudocode
Use the wikipedia explanation above (under the "Example" header) to write some pseudocode to solve this problem. Here is a [pseudocode refresher](http://www.unf.edu/~broggio/cop2221/2221pseu.htm). Write this in comments at the top of the sieve.py file.
#### Solve in Python
Write a function that implements this algorithm to determine all the prime numbers below a given number. The program should take a number as an argument, and return an array of all the primes.

View File

@ -0,0 +1,6 @@
###PSEUDOCODE HERE
###real code below

View File

@ -0,0 +1,20 @@
Benchmarking your Code
=======================
How fast is your code? Do you want to find out? Yes!
#### Write a Benchmark function
Write a Benchmark function that takes the following as inputs:
* the function you want to benchmark
* the amount of times you want it to run
Have your Benchmark function return the total amount of time it took.
The datetime library is imported at the top of the file. Look it up and how it's going to help you solve this problem. Do not import any other libraries.
#### Test your Factorial Functions
Test your Iterative Factorial function versus your recursive - which is faster??
Import this file into at least one other of your assignments and test some of your functions.

View File

@ -0,0 +1,6 @@
import datetime
import imp
##what is this code doing? figure out how to call your fibonacci functions in this file.
fibonacci = imp.load_source('fibonacci', '../2-is-fibonacci/fibonacci.py')
def benchmark(func, times):

View File

@ -0,0 +1,21 @@
Python Dictionaries In Depth
============================
Model these people as dictionaries:
Name: Michaela
Gender: Female
Height in cm: 178
Job: Visual Artist
Parents: Aimee, Louis
Pets: Fezzy, Rufus
Name: Steve
Gender: Male
Height in cm: 160
Job: Graphic Designer
Nickname: The Cow
Friends: Stephen, Stephanie, Stefan
Jobs: Graphic Designer at Acme Corp, Bartender at Banter
Print out the keys and values of each person object. Look into iterating over dictionaries in Python

View File

@ -0,0 +1,76 @@
Conditionals and For Loops
==========================
Get ready for FizzBuzz, again!
#### For Loop
For loop syntax in Python is slightly different.
The 'for in' pattern is still available in Python:
```
>>> for thing in list:
... print(thing)
```
Python also has what's known as a range:
```
>>> lst = ['a', 'b', 'c']
>>> for i in range(len(lst)):
... print(i)
0
1
2
```
If we wanted to print the element in the list, rather than the index, we could do it like this:
```
>>> lst = ['a', 'b', 'c']
>>> for i in range(len(lst)):
... print(lst[i])
a
b
c
```
With range, you have the option to choose the start and stop points, as well as increment.
```
>>> for i in range(2, 10, 2):
... print(i)
2
4
6
8
```
As you can see, the end point is not included as part of the range.
Fire up your Python interpreter and try it out.
#### Conditionals - Switch
Switch statements are basically the same in Python. You can write if statements in two ways:
```
if(some condition):
do something
```
or
```
if some condition:
do something
```
for else clauses, it's also pretty similar.
Here is an example:
```
if condition:
do something
elif another condition:
do something else
else:
catch all of the other possibilities
```
#### FizzBuzz
Time for FizzBuzz in Python.
Write code that does the following:
* if i is divisible by 3, print "Fizz"
* if i is divisible by 5, print "Buzz"
* if i is divisible by 3 & 5, print "FizzBuzz"
* if i is not divisble by 3 or 5, print i

View File

@ -0,0 +1,11 @@
def fizzbizz(num):
pass
def assertion(actual, expected):
print(str(actual) + " == " + str(expected) + " : " + str(actual==expected))
assertion(fizzbuzz(33), "Fizz")
assertion(fizzbuzz(20), "Buzz")
assertion(fizzbuzz(30), "FizzBuzz")
assertion(fizzbuzz(32), 32)

View File

@ -0,0 +1,40 @@
While Loops in Python
=====================
A while loop iterates until a condition is no longer true. For example:
```
i = 0
while i < 10:
print(i)
i += 1
```
Be careful with while loops. If your while loop doesn't have a way to end, it will go on until it crashes.
```
i = 10
while i > 5:
print(i)
i += 1
```
#### Multiplication Tables
Using any loop / loops of your choosing, write code that prints the multiplication tables up to a number
Your return should look something like this:
```
# userinput = 7
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
1 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
2 | 2 | 4 | 6 | 8 | 10| 12| 14|
3 | 3 | 6 | 9 | 12| 15| 18| 21|
4 | 4 | 8 | 12| 16| 20| 24| 28|
5 | 5 | 10| 15| 20| 25| 30| 35|
6 | 6 | 12| 18| 24| 30| 36| 42|
7 | 7 | 14| 21| 28| 35| 42| 49|
```
Python does not change data types for you. If you would like to mix an integer and "|" into a string, you have to explicitly change the integer into a string. the method str() will do this for you.
```
1 + "c" # this won't work
str(1) + "c" # this will be "1c"
```

View File

@ -0,0 +1,2 @@
def multiplication_table(number):
pass

View File

@ -0,0 +1,17 @@
Print a Triangle
================
Using nested for loops, print a triangle like so:
```
>>> triangle(10)
*
**
***
****
*****
******
*******
********
*********
**********
```

View File

@ -0,0 +1,2 @@
def triangle(num):
pass

View File

@ -0,0 +1,20 @@
Print a Mario End of Level Stairs
=================================
Remember this from Mario?
![Mario stairs](http://www.nintendoninja.com/images/stairs.png)
Create it!
```
>>> triangle(10)
*
**
***
****
*****
******
*******
********
*********
**********
```

View File

@ -0,0 +1,2 @@
def mario_triangle(num):
pass

View File

@ -0,0 +1,29 @@
Regular Expressions
===================
Regular Expressions (regex for short) are a way to represent patterns in strings. They aren't as bad as people make them out to be. When used on the right problem, they are a great solution.
Go to [Rubular](http://rubular.com/). We're going to sandbox inside it a bit to get acquainted with regex syntax. At the bottom of the page is a regex cheat sheet.
Note: Depending on the language, you may have to escape certain characters. For example, instead of `a{3}`, you may have to type `a\{3\}`.
Also, be careful with periods (`.`). A period means any character in regex, so you have to escape it if you want to pattern match a period.
Here are some examples of regex and matching string patterns:
* `a{3}` => `aaa`
* `a{3,}` => `aaaaaaaa`
* `[a-z]` => any lowercase letter
* `[A-Z]{4,6}` => between 4 and 6 uppercase letters, ex. `FASDV`
* `.` => any character
* `\w\.` => `_.`
* `hello\d?` => `hello` or `hello5`
* `[a-nO-Z]*` => abcOZZ
Make a regex to match each of these strings:
* match 'byte academy' 3 different ways
* an 8 character password, do not allow non word characters
* an 8 character password that has at least 1 number and 1 capital letter
* byteacademy@example.com
* byte.academy@example.com
* byteacademy22@example.co.uk
See if you can get all three with 1 regex, but not invalid emails (not having an @, etc...)

View File

@ -0,0 +1,14 @@
Temperature Converters
======================
#### Fahrenheit to Celsius
Write a function that converts fahrenheit temperatures to celsius. The equation to do this is ```C = (F - 32) * 5/9```.
#### Celsius to Fahrenheit
Write a similar function that converts celsius to fahrenheit.
The equation for this is ```F = (C * 9/5) + 32```.
#### Testing
Make sure the tests pass. Write 3 of your own tests.

View File

@ -0,0 +1,12 @@
def fahrenheit_to_celsius(temp):
pass
def celsius_to_fahrenheit(temp):
pass
assert(fahrenheit_to_celsius(32) == 0), "Freezing temp should return true"
assert(fahrenheit_to_celsius(212) == 100), "Boiling temp should return true"
assert(fahrenheit_to_celsius(-13) == -25), "Negative number should return true"
assert(celsius_to_fahrenheit(37) == 98.6), "Body temp should return true"
assert(celsius_to_fahrenheit(10) == 50), "Random temp should return true"

View File

@ -0,0 +1,15 @@
The Fibonacci Sequence
======================
The fibonacci sequence are the numbers in the following integer sequence:
```
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...and so on
```
Write a function that detects whether its input is a fibonacci number or not.
Make sure the assert statements all pass. Write two of your own Python assert statements.
## Resources
[Fibonacci Numbers](http://en.wikipedia.org/wiki/Fibonacci_number)
[Fibonacci in Nature](http://jwilson.coe.uga.edu/emat6680/parveen/fib_nature.htm)

View File

@ -0,0 +1,16 @@
def fibonacci(num):
pass
# TESTS
import random
def random_fibonacci():
fib = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025]
return random.sample(fib, 1)[0]
assert(fibonacci(random_fibonacci()) == True), "Random Fibonacci number should return true"
assert(fibonacci(50) == False), "50 should return false"
assert(fibonacci(97450) == False), "50 should return false"
assert(fibonacci(1) == True), "1 should return true"
assert(fibonacci(7540113804746346429) == True), "A massive number in sequence should return true"