Created
February 24, 2015 15:02
-
-
Save CAridorc/9c58bea97c00e640ee29 to your computer and use it in GitHub Desktop.
Some easy tasks solved
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import doctest | |
def reverse(string): | |
""" | |
Reverses a string. | |
>>> reverse("hello") | |
'olleh' | |
>>> reverse("panda") | |
'adnap' | |
""" | |
result = [] | |
start = len(string) - 1 | |
for index in range(start,-1,-1): | |
result.append(string[index]) | |
return ''.join(result) | |
def gen_fibs(limit): | |
""" | |
Generates the first 'limit' fibonacci numbers. | |
>>> list(gen_fibs(10)) | |
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34] | |
""" | |
a,b = 0,1 | |
for _ in range(limit): | |
yield a | |
a,b = b,a+b | |
def get_fib(n): | |
""" | |
Returns the 'n'th fibonacci numbers. | |
>>> get_fib(0) | |
0 | |
>>> get_fib(4) | |
2 | |
""" | |
if n == 0: return 0 | |
return list(gen_fibs(n))[-1] | |
def multiplication_tables(limit): | |
""" | |
Returns the multiplication tables up to 'limit'. | |
>>> multiplication_tables(2) | |
[[1, 1, 1], [1, 2, 2], [2, 1, 2], [2, 2, 4]] | |
""" | |
return [[i,j,i*j] for i in range(1,limit+1) | |
for j in range(1,limit+1)] | |
def sum_from_file(filename): | |
""" | |
Returns the sum of all the integers in a textfile, | |
one integer per line. | |
""" | |
with open(filename) as f: | |
return sum([int(i) for i in f.splitlines()]) | |
def odd_numbers(limit): | |
""" | |
Returns all the odd numbers up to 'limit'. | |
>>> odd_numbers(10) | |
[1, 3, 5, 7, 9] | |
""" | |
return [i for i in range(1,limit+1) if i % 2 != 0] | |
def largest(array): | |
""" | |
Returns the largest value of the array. | |
>>> largest([3,5,7,8,2,1]) | |
8 | |
>>> largest([5,2,10,12]) | |
12 | |
""" | |
largest_so_far = array[0] | |
for i in array: | |
if i > largest_so_far: | |
largest_so_far = i | |
return largest_so_far | |
def to_hex(n): | |
""" | |
Converts the given number to hexadecimal. | |
>>> to_hex(20) | |
'14' | |
>>> to_hex(50) | |
'32' | |
""" | |
digit_symbol_dict = { | |
10 : "A", | |
11 : "B", | |
12 : "C", | |
13 : "D", | |
14 : "E", | |
15 : "F" | |
} | |
result = [] | |
while n: | |
digit = n % 16 | |
digit = str(digit) if digit <= 9 \ | |
else digit_symbol_dict[digit] | |
result.append(digit) | |
n //= 16 | |
return reverse(''.join(result)) | |
def format_rgb(triplet): | |
""" | |
Converts and rgb triplet to hexadecimal. | |
>>> format_rgb((100,122,255)) | |
'647AFF' | |
""" | |
return ''.join([to_hex(i) for i in triplet]) | |
def _test(): | |
doctest.testmod() | |
if __name__ == "__main__": | |
_test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment