Compare commits

..

2 Commits

12 changed files with 79 additions and 371 deletions

View File

@ -1,16 +1,7 @@
#!/usr/bin/env python3
def titlecase( sentence, exceptions ):
sentence = sentence.lower().split(' ')
out = [sentence[0].title()]
for word in sentence[1:]:
if word in exceptions:
out.append(word)
else:
out.append(word.title())
return ' '.join(out)
def titlecase( string, exceptions ):
pass
assert( titlecase( 'the quick brown fox jumps over the lazy dog', ['jumps', 'the', 'over'] ) == 'The Quick Brown Fox jumps over the Lazy Dog' )
assert( titlecase( 'THE vitamins ARE IN my fresh CALIFORNIA raisins', ['are', 'is', 'in', 'your', 'my'] ) == 'The Vitamins are in my Fresh California Raisins' )

View File

@ -1,11 +1,13 @@
Float to Currency
==================
Write a method that gives the number of American coins and bills needed to represent that number (rounded to the nearest 1/100, i.e. the nearest penny).
Write a method that gives the number of currency coins and bills needed to
represent that number (rounded to the nearest 1/100, i.e. the nearest coin).
As an exmaple, if the float is 12.33, the result would be 1 $10, 2 $1 bills, 1 quarter, 1 nickel and 3 pennies.
As an exmaple, if the float is 12.33, the result would be 1 $10, 2 $1 bills,
1 quarter, 1 nickel and 3 pennies.
Use the following as denominations for your currencies:
Here is the the list USD banknotes. Feel free to use USD or you local currency.
Penny: 1 cent
Nickel: 5 cent
@ -14,5 +16,25 @@ Use the following as denominations for your currencies:
One-dollar bill
Five-dollar bill
Ten-dollar bill
Twenty-dollar bill
Fifty-dollar bill
Hundred-dollar bill
## Bonus
Write a second function to make the output look nice, something like this:
```
currency_converter_formater(12.23)
Penny: 3
Dime: 2
One-dollar: 2
Ten-dollar: 1
```
# Bonus II
Abjust your function so it takes a second argument of `denominations` so a
single currency is not hard coded.

View File

@ -1,24 +1,2 @@
units_USD = [
{'name': 'Penny', 'value': 1, 'count': 0},
{'name': 'Nickel', 'value': 5, 'count': 0},
{'name': 'Dime', 'value': 10, 'count': 0},
{'name': 'Quarter', 'value': 25, 'count': 0},
{'name': 'One-dollar', 'value': 100, 'count': 0},
{'name': 'Five-dollar', 'value': 500, 'count': 0},
{'name': 'Ten-dollar', 'value': 1000, 'count': 0},
{'name': 'Fifty-dollar', 'value': 5000, 'count': 0},
{'name': 'Hundred-dollar', 'value': 10000, 'count': 0},
]
def currency_converter(amount, units=None):
units = (units or units_USD).copy()
amount = 100*amount
for current in units[::-1]:
while amount >= current['value']:
amount -= current['value']
current['count'] += 1
return [i for i in units if i['count']]
print(currency_converter(12.23))
def currency_converter():
pass

View File

@ -1,16 +1,2 @@
def remove_duplicate(sentence):
out = sentence[0]
dupes = ''
last = sentence[0]
for letter in sentence[1:]:
if letter == last:
dupes += letter
else:
out += letter
last = letter
return out
assert(remove_duplicate('hello') == 'helo')
assert(remove_duplicate('hhhhheeeeelllllooooo') == 'helo')
def remove_duplicate(string):
pass

View File

@ -1,26 +1,5 @@
from datetime import datetime
def age_to_time(age):
pass
def to_time( delta ):
months = int( delta.days/30 )
days = delta.days
hours = delta.days*24
minutes = delta.days*24*60
return 'months : {}, days : {}, hours : {}, and minutes : {}'.format( months, days, hours, minutes )
def age_to_time( age ):
delta = datetime.now() - datetime.now().replace( year=datetime.now().year-age )
return to_time( delta )
def birthday_to_time( birthday ):
birthday = datetime.strptime( birthday, "%Y-%m-%d" )
delta = datetime.now() - birthday
return to_time( delta )
age = int( input('How old are you? ') )
print( age_to_time(age) )
birthday = input( 'What is your birth date?(YYYY-MM-DD) ')
print( birthday_to_time(birthday) )
def birthday_to_time(birthday):
pass

View File

@ -1,25 +1,18 @@
class int( int ):
# Use this function to get and return all the prime numbers below the input number
def roman( self ):
romanNum = []
symbols = ( ( 'M', 1000 ), ( 'C', 100 ), ( 'XC', 90 ), ( 'L', 50 ), ( 'X', 10 ),
( 'IX', 9 ), ('V', 5 ) , ( 'IV', 4 ), ( 'I', 1 ) )
def to_roman(num):
pass
for symbol, value in symbols:
while self >= value:
self -= value
romanNum.append( symbol )
return ''.join( romanNum )
n = int( 56 )
print( n, n.roman() )
# alias int.roman() not to change assert lines
roman = int.roman
assert roman( 11 ) == "XI", "11 should return XI"
assert roman( 60 ) == "LX", "60 should return LX"
assert roman( 78 ) == "LXXVIII", "78 should return LXXVIII"
assert roman( 4 ) == "IV", "4 should return IV"
assert roman( 99 ) == "XCIX", "99 should return XCIX"
assert to_roman(11) == "XI", "11 should return XI"
assert to_roman(60) == "LX", "60 should return LX"
assert to_roman(78) == "LXXVIII", "78 should return LXXVIII"
assert to_roman(4) == "IV", "4 should return IV"
assert to_roman(99) == "XCIX", "99 should return XCIX"
# Add your own assert tests below

View File

@ -1,72 +0,0 @@
def matrix_parse(matrix):
out = []
for row in matrix.split('\n'):
out.append([int(col) for col in row.split()])
return out
def matrix_from_file(file):
with open(file, 'r') as file:
return matrix_parse(file.read())
def matrix_sum(matrix):
row_sum = []
col_sum = [0 for col in range(len(matrix)+1)]
for row in matrix:
row_sum.append(sum(row))
for idx, col in enumerate(row):
col_sum[idx] += col
return row_sum, col_sum
def matrix_sort_row(matrix):
row_sum, col_sum = matrix_sum(matrix)
out = []
for index, row in sorted( [i for i in enumerate(row_sum)], key=lambda x:x[1] ):
out.append(matrix[index])
return out;
def matrix_sort_col(matrix):
row_sum, col_sum = matrix_sum(matrix)
out = []
places = sorted( [i for i in enumerate(col_sum)], key=lambda x:x[1])
for index, row in enumerate(matrix):
out.append([row[i[0]] for i in places])
return out
def matrix_get_element_width(matrix):
max = 0
for row in matrix:
for element in row:
if max < len(str(element)):
max = len(str(element))
return max
def matrix_print(matrix, width=None):
if not width:
return matrix_print(matrix, matrix_get_element_width(matrix))
for row in matrix:
print('', *['{:{}d}'.format(el, width) for el in row], '', sep=' | ')
m1 ='''10 5 4 20
9 33 27 16
11 6 55 3'''
# m1 = matrix_parse(m1)
# print(m1)
# print(matrix_sum(m1))
# print(matrix_get_element_width(m1))
# matrix_print(m1)
m2 = matrix_from_file('./matrix.txt')
print(matrix_sum(m2))

View File

@ -1,80 +0,0 @@
class Matrix:
def __init__(self, **kwargs):
if kwargs.get('file'):
self.matrix = self.__from_file(kwargs['file'])
elif kwargs.get('text'):
self.matrix = self.__parse(kwargs['text'])
elif kwargs.get('matrix'):
self.matrix = kwargs['matrix']
def __from_file(self, file):
with open(file, 'r') as file:
return self.parse(file.read())
def __parse(self, matrix):
out = []
for row in matrix.split('\n'):
out.append([int(col) for col in row.split()])
return out
@property
def sum(self):
row_sum = []
col_sum = [0 for col in range(len(self.matrix)+1)]
for row in self.matrix:
row_sum.append(sum(row))
for idx, col in enumerate(row):
col_sum[idx] += col
return row_sum, col_sum
@property
def sort_row(self):
row_sum, col_sum = self.sum
out = []
for index, row in sorted( [i for i in enumerate(row_sum)], key=lambda x:x[1]):
out.append(self.matrix[index])
return Matrix(matrix=out);
@property
def sort_col(self):
row_sum, col_sum = self.sum
out = []
places = sorted( [i for i in enumerate(col_sum)], key=lambda x:x[1])
for index, row in enumerate(self.matrix):
out.append([row[i[0]] for i in places])
return Matrix(matrix=out)
def __get_element_width(self):
max = 0
for row in self.matrix:
for element in row:
if max < len(str(element)):
max = len(str(element))
return max
def __str__(self, width=None):
width = self.__get_element_width()
out = ''
for row in self.matrix:
out +=' | '.join(['{:{}d}'.format(el, width) for el in row])
out += '\n'
return out
m1 ='''10 5 4 20
9 33 27 16
11 6 55 3'''
m1 = Matrix(text=m1)
# print(m1.sum)
print(m1.sort_row)
print(m1.sort_col)

View File

@ -1,27 +1,9 @@
def char_shift(char, shift):
start = ord('a') if char.isupper() else ord('A')
char = ord(char) - start
shift = (char + shift) % 26
return chr(shift + start)
def caesar(message, shift):
out = ''
for letter in message:
if letter.isalpha():
letter = char_shift(letter, shift)
out += letter
pass
# or in one line
# out += char_shift(letter, shift) if letter.isalpha() else letter
return out
def decrypt_caesar(message, shift):
return caesar(message, shift - (shift * 2))
# Add your own assert statements to test your code.
sentence = 'But the Caesar Cipher is [still used](http://en.wikipedia.org/wiki/ROT13)'
shift = 300
assert( decrypt_caesar(caesar(sentence, shift), 300) == sentence )
# Add your own assert statements to test your code.

View File

@ -1,40 +1,14 @@
import fractions
def compute_divisors(num):
divisors = [1]
for i in range( 2, num//2+1 ): # if num is even, one needs to be added
if num % i == 0:
divisors.append(i)
divisors.append( num )
return divisors
pass
def sum_of_divisors(num):
sumOf = 0
for i in compute_divisors( num ):
sumOf += i
return sumOf
pass
def divisor_count(num):
return len( compute_divisors(num) )
pass
def get_totatives(num):
totatives = []
for i in range(0, num):
gcd = fractions.gcd( i, num )
if gcd == 1:
totatives.append( i )
return totatives
pass
def totient(num):
return len( get_totatives(num) )
assert( compute_divisors(60) == [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60] )
assert( sum_of_divisors(60) == 168 )
assert( divisor_count(60) == 12 )
assert( get_totatives(30) == [1, 7, 11, 13, 17, 19, 23, 29] )
assert( totient(30) == 8 )
pass

View File

@ -1,23 +1,16 @@
def binary_to_decimal(num):
if num == 0: return 0
decimal = 0
t = [decimal += 2**i for i, char in enumerate(str(num)[:: -1]) if char != '0']
return int(decimal)
pass
def decimal_to_binary(num):
pass
print(binary_to_decimal(11100101),binary_to_decimal(10001101),binary_to_decimal(10010000))
assert binary_to_decimal(0) == 0, "0 to decimal should return 0"
assert binary_to_decimal(1011) == 11, "1011 to decimal should return 11"
assert binary_to_decimal(101011) == 43, "101011 to decimal should return 43"
assert binary_to_decimal(101011101) == 349, "101011101 to decimal should return 349"
# assert decimal_to_binary(0) == 0, "0 to binary should return 0"
# assert decimal_to_binary(5) == 101, "5 to binary should return 101"
# assert decimal_to_binary(10) == 1010, "10 to binary should return 1010"
# assert decimal_to_binary(113) == 1110001, "113 to binary should return 1110001"
assert decimal_to_binary(0) == 0, "0 to binary should return 0"
assert decimal_to_binary(5) == 101, "5 to binary should return 101"
assert decimal_to_binary(10) == 1010, "10 to binary should return 1010"
assert decimal_to_binary(113) == 1110001, "113 to binary should return 1110001"

View File

@ -1,98 +1,60 @@
class CreditCard:
card_types = [
# (starts with digits, card type, card length)
('4', 'VISA', 16),
('34', 'AMEX', 15),
('37', 'AMEX', 15),
('51', 'MASTERCARD', 16),
('52', 'MASTERCARD', 16),
('53', 'MASTERCARD', 16),
('54', 'MASTERCARD', 16),
('55', 'MASTERCARD', 16),
('6011', 'DISCOVER', 16),
]
@classmethod
def luna_check(cls, card_number):
digits = []
for index, digit in enumerate(card_number[::-1]):
if index % 2:
digits += [int(i) for i in str(int(digit)*2)]
else:
digits.append(int(digit))
return not bool(sum(digits) % 10)
def __init__(self, card_number):
self.card_number = card_number
self.is_valid, self.card_type = self.__is_valid() or (False, 'INVALID')
self.card_number = "the card number"
self.card_type = "a string"
self.valid = "a boolean"
def __card_type(self):
for start, type, length in self.card_types:
if self.card_number.startswith(start):
return type, length
def __is_valid(self):
card_type = self.__card_type()
if card_type:
length = len(self.card_number) == card_type[1]
luna = self.luna_check(self.card_number)
if length and luna:
return True, card_type[0]
#Create and add your method called `determine_card_type` to the CreditCard class here:
def determine_card_type(self):
pass
#Create and add your method called `check_length` to the CreditCard class here:
def check_length(self):
pass
#Create and add your method called 'validate' to the CreditCard class here:
def validate(self):
pass
# # print(CreditCard.luna_check('4485040993287616'))
# cc = CreditCard('4485040993287616')
# print(cc.is_valid)
# exit(0)
#do not modify assert statements
cc = CreditCard('9999999999999999')
assert(cc.is_valid == False)
assert(cc.card_type == "INVALID")
assert cc.valid == False, "Credit Card number cannot start with 9"
assert cc.card_type == "INVALID", "99... card type is INVALID"
cc = CreditCard('4440')
assert cc.is_valid == False, "4440 is too short to be valid"
assert cc.valid == False, "4440 is too short to be valid"
assert cc.card_type == "INVALID", "4440 card type is INVALID"
cc = CreditCard('5515460934365316')
assert cc.is_valid == True, "Mastercard is Valid"
assert cc.valid == True, "Mastercard is Valid"
assert cc.card_type == "MASTERCARD", "card_type is MASTERCARD"
cc = CreditCard('6011053711075799')
assert cc.is_valid == True, "Discover Card is Valid"
assert cc.valid == True, "Discover Card is Valid"
assert cc.card_type == "DISCOVER", "card_type is DISCOVER"
cc = CreditCard('379179199857686')
assert cc.is_valid == True, "AMEX is Valid"
assert cc.valid == True, "AMEX is Valid"
assert cc.card_type == "AMEX", "card_type is AMEX"
cc = CreditCard('4929896355493470')
assert cc.is_valid == True, "Visa Card is Valid"
assert cc.valid == True, "Visa Card is Valid"
assert cc.card_type == "VISA", "card_type is VISA"
cc = CreditCard('4329876355493470')
assert cc.is_valid == False, "This card does not meet mod10"
assert cc.valid == False, "This card does not meet mod10"
assert cc.card_type == "INVALID", "card_type is INVALID"
cc = CreditCard('339179199857685')
assert cc.is_valid == False, "Validates mod10, but invalid starting numbers for AMEX"
assert cc.valid == False, "Validates mod10, but invalid starting numbers for AMEX"
assert cc.card_type == "INVALID", "card_type is INVALID"