Skip to content

Commit

Permalink
added py folder
Browse files Browse the repository at this point in the history
  • Loading branch information
Alessandro Giordo committed Feb 8, 2016
1 parent c207564 commit a6b55c0
Show file tree
Hide file tree
Showing 20 changed files with 306 additions and 0 deletions.
11 changes: 11 additions & 0 deletions Py/apihelper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
def info(object, spacing=10, collapse=1):
"""Print methods and doc strings.
Takes module, class, list, dictionary, or string."""
methodList = [method for method in dir(object) if callable(getattr(object, method))]
processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
print "\n".join(["%s %s" %
(method.ljust(spacing),
processFunc(str(getattr(object, method).__doc__)))
for method in methodList])
if __name__ == "__main__":
print info.__doc__
46 changes: 46 additions & 0 deletions Py/battleship_game.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from random import randint

board = []

for x in range(5):
board.append(["O"] * 5)

def print_board(board):
for row in board:
print " ".join(row)

print "Let's play Battleship!"
print_board(board)

def random_row(board):
return randint(0, len(board)+1)

def random_col(board):
return randint(0, len(board)+1)

ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col

# Everything from here on should go in your for loop!
for turn in range(4):
print "Turn", turn + 1
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))

if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sunk my battleship!"
break
else:
if guess_row not in range(6) or guess_col not in range(6):
print "Oops, that's not even in the ocean."
elif(board[guess_row-1][guess_col-1] == "X"):
print "You guessed that one already."
else:
print "You missed my battleship!"
board[guess_row-1][guess_col-1] = "X"
# Print (turn + 1) here!
print_board(board)
if turn == 3:
print "Game Over"
38 changes: 38 additions & 0 deletions Py/censor_words.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
def censor(text,word):
new = []
text = text.split()
for b in text:
if word == b:
new.append("*" * len(b))
else:
new.append(b)
return " ".join(new)

censor("this is a test", "test")

# shorter

def censor(text,word):
return text.replace(word,"*"*len(word))

"""
.replace method syntax:
A.replace(B,C)
Let:
A = String that contains the word you want to replace.
B = Word/Sub string to be replaced.
C = Word/Sub string that will replace B.
What does "*"*len(word) do?
Example:
"a" * 3 produces "aaa"
"1" * 5 produces "11111"
"-" * 2 produces "--"
In other words it simply generates n number of asterisks based on the length of the variable word.
The text.split() approach is a crude approach however using it is fine. Remember "less is more" but don't go over board.
"""
8 changes: 8 additions & 0 deletions Py/count_sequence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
def count(sequence, item):
found = 0
for i in sequence:
if i == item:
found += 1
return found

count([1,2,1,1], 1) # should return 3
18 changes: 18 additions & 0 deletions Py/deduplicate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
def remove_duplicates(dedupe):
newlist = []
for i in dedupe:
if i not in newlist:
newlist.append(i)
print newlist
return newlist

remove_duplicates([1,1,2,2]) # should return [1,2].

# shorter below but against requirements:

def remove_duplicates(dedupe):
return list(set(dedupe))

# even shorter:

remove_duplicates = lambda dedupe: list(set(dedupe))
34 changes: 34 additions & 0 deletions Py/exam_statistics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

def print_grades(grades):
for grade in grades:
print grade

def grades_sum(grades):
total = 0
for grade in grades:
total += grade
return total

def grades_average(grades):
sum_of_grades = grades_sum(grades)
average = sum_of_grades / float(len(grades))
return average

def grades_variance(scores):
average = grades_average(scores)
variance = 0
for score in scores:
variance += (average - score) ** 2
return variance / float(len(scores))

def grades_std_deviation(variance):
return variance ** 0.5

variance = grades_variance(grades)

print print_grades(grades) # printing grades in separate rows
print grades_sum(grades) # sum of grades
print grades_average(grades) # average of sum of grades
print variance # how the grades varied against the average
print grades_std_deviation(variance) # The standard deviation is the square root of the variance. You can calculate the square root by raising the number to the one-half power.
8 changes: 8 additions & 0 deletions Py/factorial_formula.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
def factorial(x):
if x == 1 or x == 0:
print 1
return 1
else:
print x * factorial(x - 1)
return x * factorial(x - 1)
factorial(4)
21 changes: 21 additions & 0 deletions Py/fibonacci_seq.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# fill in this function
def fib()
a, b = 1, 1
while 1
yield a
print initial a is %d % a
a, b = b, a + b
print a is %d % a
print b is %d % b

# testing code
import types
if type(fib()) == types.GeneratorType
print Good, The fib function is a generator.

counter = 0
for n in fib()
print n
counter += 1
if counter == 10
break
12 changes: 12 additions & 0 deletions Py/find_median_list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
def median(x):
x = sorted(x)
if len(x) == 1:
return x[0]
elif len(x) % 2 != 0:
return float(x[(int(len(x)/2))])
else:
a = float(x[int(len(x)/2)])
b = float(x[int((len(x)/2)-1)])
return (a + b)/2

median([1,1,2]) # should return 1
15 changes: 15 additions & 0 deletions Py/insert_dash_odd_numbers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import re
def insert_dash(num):
# r'([02468])([02468])' performs capturing matches on two even numbers
# that are next to each other
# r'\1*\2' is a string consisting of the first match ([02468]) followed
# by an asterisk ('*') and the second match ([02468])
# example input: 48 [A representation of what happens inside re.sub()]
# r'([02468])([02468])' <- 48 = r'( \1 : 4 )( \2 : 8 )'
# r'\1*\2' <- {\1 : 4, \2 : 8} = r'4*8'
# This statement is much like the previous, but it matches on odd pairs
# of numbers
print re.sub(r'([13579])(?=[13579])',r'\1-', str(num))
return re.sub(r'([13579])(?=[13579])',r'\1-', str(num))

insert_dash(33345567899)
9 changes: 9 additions & 0 deletions Py/is_prime.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
def is_prime(x):
if x < 2:
return False
else:
for n in range(2, (x-1)):
if x % n == 0:
return False
else:
return True
14 changes: 14 additions & 0 deletions Py/list_benefits.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# return a list of strings as defined above
def list_benefits():
return "More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together"

# concatenate to each benefit - " is a benefit of functions!"
def build_sentence(benefit):
return benefit + " is a benefit of functions!"

def name_the_benefits_of_functions():
list_of_benefits = list_benefits()
for benefit in list_of_benefits:
print build_sentence(benefit)

name_the_benefits_of_functions()
7 changes: 7 additions & 0 deletions Py/list_product.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
def product(integers):
total = 1
for i in integers:
total = total * i
return total

product([4, 5, 5]) # should return 100 (because 4 * 5 * 5 is 100).
9 changes: 9 additions & 0 deletions Py/print_reverse_string.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
def reverse(text):
b = ""
for a in range(1,len(text)+1):
c = len(text) - a
print c
b += text[c]
a -= 1
return b
reverse("abcd")
8 changes: 8 additions & 0 deletions Py/purify.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
def purify(numbers):
pure = []
for i in numbers:
if i % 2 == 0:
pure.append(i)
return pure

purify([1,2,3]) # should return [2].
8 changes: 8 additions & 0 deletions Py/re_module_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import re

find_members = []
for member in dir(re):
if "find" in member:
find_members.append(member)

print sorted(find_members)
8 changes: 8 additions & 0 deletions Py/remove_vowels_string.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
def anti_vowel(text):
p = []
for c in text:
if c not in "ueoaiUEOAI":
p.append(c)
return "".join(p)

anti_vowel("Hey there")
15 changes: 15 additions & 0 deletions Py/scrabble_score.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
"f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
"l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
"r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
"x": 8, "z": 10}

def scrabble_score(word):
total = 0
for x in word.lower():
for key in score:
if x == key:
total += score[key]
return total

scrabble_score("scrabble")
9 changes: 9 additions & 0 deletions Py/stop_at_42.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
def stop_42():
for i in range(1, 100):
if i != 42:
print i
continue
else:
break

stop_42()
8 changes: 8 additions & 0 deletions Py/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import __builtin__

animal_sounds = {
"cat": ["meow", "purr"],
"dog": ["woof", "bark"],
"fox": [],
}
print animal_sounds["cat"]

0 comments on commit a6b55c0

Please sign in to comment.