mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 20:26:07 -04:00
add boilerplate for second edition
This commit is contained in:
parent
5fd154f3fd
commit
dc3ebf3173
41
First_edition_2014/ebook_src/abstract_structures/HashTableClass.py
Executable file
41
First_edition_2014/ebook_src/abstract_structures/HashTableClass.py
Executable file
@ -0,0 +1,41 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
class HashTable(object):
|
||||||
|
def __init__(self, slots=10):
|
||||||
|
self.slots = slots
|
||||||
|
self.table = []
|
||||||
|
self.create_table()
|
||||||
|
|
||||||
|
def hash_key(self, value):
|
||||||
|
return hash(value)%self.slots
|
||||||
|
|
||||||
|
def create_table(self):
|
||||||
|
for i in range(self.slots):
|
||||||
|
self.table.append([])
|
||||||
|
|
||||||
|
def add_item(self, value):
|
||||||
|
key = self.hash_key(value)
|
||||||
|
self.table[key].append(value)
|
||||||
|
|
||||||
|
def print_table(self):
|
||||||
|
for key in range(len(self.table)):
|
||||||
|
print "Key is %s, value is %s." %(key, self.table[key])
|
||||||
|
|
||||||
|
def find_item(self, item):
|
||||||
|
pos = self.hash_key(item)
|
||||||
|
if item in self.table[pos]:
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
dic = HashTable(5)
|
||||||
|
for i in range(1, 40, 2):
|
||||||
|
dic.add_item(i)
|
||||||
|
|
||||||
|
dic.print_table()
|
||||||
|
assert(dic.find_item(20) == False)
|
||||||
|
assert(dic.find_item(21) == True)
|
47
First_edition_2014/ebook_src/abstract_structures/QueueClass.py
Executable file
47
First_edition_2014/ebook_src/abstract_structures/QueueClass.py
Executable file
@ -0,0 +1,47 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
# Time: 5 min
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
class Queue(object):
|
||||||
|
def __init__(self):
|
||||||
|
self.enq = []
|
||||||
|
self.deq = []
|
||||||
|
|
||||||
|
def enqueue(self, item):
|
||||||
|
return self.enq.append(item)
|
||||||
|
|
||||||
|
def deque(self):
|
||||||
|
if not self.deq:
|
||||||
|
while self.enq:
|
||||||
|
self.deq.append(self.enq.pop())
|
||||||
|
return self.deq.pop()
|
||||||
|
|
||||||
|
def peak(self):
|
||||||
|
if not self.deq:
|
||||||
|
while self.enq:
|
||||||
|
self.deq.append(self.enq.pop())
|
||||||
|
if self.deq:
|
||||||
|
return self.deq[-1]
|
||||||
|
|
||||||
|
def size(self):
|
||||||
|
return len(self.enq) + len(self.deq)
|
||||||
|
|
||||||
|
def isempty(self):
|
||||||
|
return not (self.enq + self.deq)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
q = Queue()
|
||||||
|
for i in range(1,11):
|
||||||
|
q.enqueue(i)
|
||||||
|
print 'Size:', q.size()
|
||||||
|
print 'Is empty?', q.isempty()
|
||||||
|
print 'Peak: ', q.peak()
|
||||||
|
print
|
||||||
|
print 'Dequeuing...'
|
||||||
|
for i in range(10):
|
||||||
|
print q.deque()
|
||||||
|
print 'Size:', q.size()
|
||||||
|
print 'Is empty?', q.isempty()
|
||||||
|
print 'Peak: ', q.peak()
|
28
First_edition_2014/ebook_src/bitwise_operations/bit_array.py
Executable file
28
First_edition_2014/ebook_src/bitwise_operations/bit_array.py
Executable file
@ -0,0 +1,28 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
''' Example of how to use a bit array in python as a "counter" dict'''
|
||||||
|
|
||||||
|
def print_dupl_ba(l1):
|
||||||
|
'''
|
||||||
|
>>> l1 = [0, 1, 2, 3, 4, 2, 6, 7, 8, 9]
|
||||||
|
>>> print_dupl_ba(l1)
|
||||||
|
2
|
||||||
|
'''
|
||||||
|
|
||||||
|
bs = bytearray(10)
|
||||||
|
for i in range(len(l1)):
|
||||||
|
if i == l1[i]:
|
||||||
|
bs[i] = 1
|
||||||
|
for index, bit in enumerate(bs):
|
||||||
|
if bit == 0:
|
||||||
|
return l1[index]
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
||||||
|
|
33
First_edition_2014/ebook_src/bitwise_operations/bitwise.txt
Executable file
33
First_edition_2014/ebook_src/bitwise_operations/bitwise.txt
Executable file
@ -0,0 +1,33 @@
|
|||||||
|
BIT-WISE
|
||||||
|
----------------------
|
||||||
|
|
||||||
|
1. To find a number:
|
||||||
|
11000101 is 2^0+2^2+2^6+2^7 = 197
|
||||||
|
|
||||||
|
|
||||||
|
2. Left shifting:
|
||||||
|
0010 1011 << 4 ---> 1011 000
|
||||||
|
|
||||||
|
|
||||||
|
3. Right shifting:
|
||||||
|
0010 1011 >> 4 ---> 0000 0010
|
||||||
|
or it can be filled with the copy of the first bit, instead of 0:
|
||||||
|
1011 0010 >> 4 ---> 1111 1011
|
||||||
|
|
||||||
|
|
||||||
|
4. XOR can cancels out:
|
||||||
|
15 ^ 12 ^ 15 = 12
|
||||||
|
|
||||||
|
|
||||||
|
5. 2^x:
|
||||||
|
left-shift 1 by x:
|
||||||
|
0000 0001 << x
|
||||||
|
|
||||||
|
so if x = 2, 2^2 = 4 -> 100
|
||||||
|
|
||||||
|
0000 0001 << 2 ---> 0000 0100
|
||||||
|
|
||||||
|
|
||||||
|
6. Is power of 2?
|
||||||
|
just do x&(x-1).
|
||||||
|
if 0 --> yes!
|
37
First_edition_2014/ebook_src/bitwise_operations/clear_bits.py
Executable file
37
First_edition_2014/ebook_src/bitwise_operations/clear_bits.py
Executable file
@ -0,0 +1,37 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
''' Clear a bit in a binary number.
|
||||||
|
Like the reverse of set bit:
|
||||||
|
1) first create a number filled of 1s,
|
||||||
|
with 0 at i (can create 0001000 and ~)
|
||||||
|
2) AND the number so it clears the ith bit
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def clear_bit(num, i):
|
||||||
|
mask = ~ (1 << i) # -0b10001
|
||||||
|
return bin(num & mask)
|
||||||
|
|
||||||
|
|
||||||
|
def clear_all_bits_from_i_to_0(num, i):
|
||||||
|
mask = ~ ( (1 << (i+1)) - 1)
|
||||||
|
return bin(num & mask)
|
||||||
|
|
||||||
|
|
||||||
|
def clear_all_bits_from_most_sig_to_1(num, i):
|
||||||
|
mask = ( 1 << i) -1
|
||||||
|
return bin(num & mask)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
num = int('10010000', 2)
|
||||||
|
print clear_bit(num, 4) # '0b10000000'
|
||||||
|
|
||||||
|
num = int('10010011', 2)
|
||||||
|
print clear_all_bits_from_i_to_0(num, 2) # '0b10010000'
|
||||||
|
|
||||||
|
num = int('1110011', 2)
|
||||||
|
print clear_all_bits_from_most_sig_to_1(num, 2) #'0b11'
|
25
First_edition_2014/ebook_src/bitwise_operations/find_bit_len.py
Executable file
25
First_edition_2014/ebook_src/bitwise_operations/find_bit_len.py
Executable file
@ -0,0 +1,25 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
''' Find how many bits a int has:
|
||||||
|
1) Start with a mask of 1
|
||||||
|
2) Mask with AND
|
||||||
|
3) if result (if true): count += 1
|
||||||
|
(obs: to find the int of a bin do int('1001', 2)) and to show in bin
|
||||||
|
do bin(int))
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def find_bit_len(int_num):
|
||||||
|
lenght = 0
|
||||||
|
while int_num:
|
||||||
|
int_num >>= 1
|
||||||
|
lenght += 1
|
||||||
|
return lenght
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
for i in range(17):
|
||||||
|
print(find_bit_len(i))
|
||||||
|
print i.bit_length()
|
32
First_edition_2014/ebook_src/bitwise_operations/find_how_many_1_binary.py
Executable file
32
First_edition_2014/ebook_src/bitwise_operations/find_how_many_1_binary.py
Executable file
@ -0,0 +1,32 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
''' Find how many 1s in the binary:
|
||||||
|
1) Start with a mask of 1
|
||||||
|
2) Mask with AND
|
||||||
|
3) if result (if true): count += 1
|
||||||
|
(obs: to find the int of a bin do int('1001',
|
||||||
|
2)) and to show in bin do bin(int))
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def find_how_many_1_in_a_binary(n):
|
||||||
|
'''
|
||||||
|
>>> find_how_many_1_in_a_binary(9)
|
||||||
|
2
|
||||||
|
'''
|
||||||
|
|
||||||
|
counter = 0
|
||||||
|
while n:
|
||||||
|
if n & 1:
|
||||||
|
counter += 1
|
||||||
|
n >>= 1
|
||||||
|
return counter
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
||||||
|
|
27
First_edition_2014/ebook_src/bitwise_operations/get_bit.py
Executable file
27
First_edition_2014/ebook_src/bitwise_operations/get_bit.py
Executable file
@ -0,0 +1,27 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
''' Get a bit in a binary number:
|
||||||
|
1) Shifts 1 over by i bits
|
||||||
|
2) make an AND with the number
|
||||||
|
3) all the other than the bit at i are clean, now compare to 0
|
||||||
|
4) if the new value is not 0, bit i is 1
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def get_bit(num, i):
|
||||||
|
mask = 1 << i
|
||||||
|
return num & mask != 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
num = int('0100100', 2)
|
||||||
|
get_bit(num, 0) # 0
|
||||||
|
get_bit(num, 1) # 0
|
||||||
|
get_bit(num, 2) # 1
|
||||||
|
get_bit(num, 3) # 0
|
||||||
|
get_bit(num, 4) # 0
|
||||||
|
get_bit(num, 5) # 1
|
||||||
|
get_bit(num, 6) # 0
|
||||||
|
|
37
First_edition_2014/ebook_src/bitwise_operations/get_float_rep_bin.py
Executable file
37
First_edition_2014/ebook_src/bitwise_operations/get_float_rep_bin.py
Executable file
@ -0,0 +1,37 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
''' Given a real number between 0 and 1 (eg: 0.72), this method print the binary
|
||||||
|
representation. If the Number cannot be represented accurately in binary, with at
|
||||||
|
most 32 chars, print error:
|
||||||
|
'''
|
||||||
|
|
||||||
|
def get_float_rep(num):
|
||||||
|
'''
|
||||||
|
>>> get_float_rep(0.72)
|
||||||
|
('Error 2', '.1011100001010001111010111000010')
|
||||||
|
>>> get_float_rep(0.1)
|
||||||
|
('Error 2', '.0001100110011001100110011001100')
|
||||||
|
>>> get_float_rep(0.5)
|
||||||
|
'.1'
|
||||||
|
'''
|
||||||
|
|
||||||
|
if num >= 1 or num <= 0: return 'Error 1'
|
||||||
|
result = '.'
|
||||||
|
while num:
|
||||||
|
if len(result) >= 32: return 'Error 2', result
|
||||||
|
r = num*2
|
||||||
|
if r >= 1:
|
||||||
|
result += '1'
|
||||||
|
num = r - 1
|
||||||
|
else:
|
||||||
|
result += '0'
|
||||||
|
num = r
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
||||||
|
|
@ -0,0 +1,36 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
''' Given two 32-bit numbers, N and M, and two bit positions, i and j, this
|
||||||
|
method insert M into N such that M starts at bit j and ends at bit i:
|
||||||
|
1) clear the bits j thru i in N'
|
||||||
|
2) shift M so that it lines up with bits j thru i
|
||||||
|
3) merge M and N
|
||||||
|
'''
|
||||||
|
|
||||||
|
def insert_small_bin_into_big_bin(M, N, i, j):
|
||||||
|
'''
|
||||||
|
>>> N = 0b10000000000
|
||||||
|
>>> M = 0b10011
|
||||||
|
>>> j = 6
|
||||||
|
>>> i = 2
|
||||||
|
>>> insert_small_bin_into_big_bin(M, N, i, j)
|
||||||
|
'0b10001001100'
|
||||||
|
'''
|
||||||
|
|
||||||
|
allOnes = ~0
|
||||||
|
left = allOnes << (j+1) # 1110000
|
||||||
|
right = ( (1 << i) - 1) # 0000111
|
||||||
|
mask = left | right # 1110111
|
||||||
|
N_cleared = N & mask
|
||||||
|
M_shifted = M << i
|
||||||
|
|
||||||
|
return bin( N_cleared | M_shifted)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
||||||
|
|
59
First_edition_2014/ebook_src/bitwise_operations/next_with_same_num_1s.py
Executable file
59
First_edition_2014/ebook_src/bitwise_operations/next_with_same_num_1s.py
Executable file
@ -0,0 +1,59 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
''' Give a positive int, print the next smallest and next largest ints with
|
||||||
|
same number of 1 bits.
|
||||||
|
The brute force is:
|
||||||
|
1) find number of 1 bits
|
||||||
|
2) loop above and down until find same, checking for each
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def print_prev_same_1s(num):
|
||||||
|
n1s = find_num_1s(num)
|
||||||
|
# find prev
|
||||||
|
i = num-1
|
||||||
|
while True:
|
||||||
|
n1s_here = find_num_1s(i)
|
||||||
|
if n1s_here == n1s:
|
||||||
|
return bin(i)
|
||||||
|
i -= 1
|
||||||
|
if i < 0:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def print_next_same_1s(num):
|
||||||
|
n1s = find_num_1s(num)
|
||||||
|
# find next
|
||||||
|
i = num+1
|
||||||
|
while True:
|
||||||
|
n1s_here = find_num_1s(i)
|
||||||
|
if n1s_here == n1s:
|
||||||
|
return bin(i)
|
||||||
|
i += 1
|
||||||
|
if i < 0:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def find_num_1s(num):
|
||||||
|
counter = 0
|
||||||
|
while num:
|
||||||
|
if num & 1:
|
||||||
|
counter += 1
|
||||||
|
num >>= 1
|
||||||
|
return counter
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
num = 0b1001
|
||||||
|
n = '0b1010'
|
||||||
|
p = '0b110'
|
||||||
|
print_prev_same_1s(num) == p
|
||||||
|
print_next_same_1s(num) == n
|
||||||
|
|
@ -0,0 +1,40 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
''' This method returns the number of bits that are necessary to change to convert two
|
||||||
|
numbers A and B:
|
||||||
|
1) XOR
|
||||||
|
2) count 1s
|
||||||
|
'''
|
||||||
|
|
||||||
|
def count_bits_swap2(a, b):
|
||||||
|
count = 0
|
||||||
|
m = a^b
|
||||||
|
while m:
|
||||||
|
count +=1
|
||||||
|
m = m & (m-1)
|
||||||
|
return count
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def count_bits_swap(a, b):
|
||||||
|
m = a^b
|
||||||
|
return count_1s(m)
|
||||||
|
|
||||||
|
|
||||||
|
def count_1s(m):
|
||||||
|
count = 0
|
||||||
|
while m:
|
||||||
|
if m& 1 :
|
||||||
|
count +=1
|
||||||
|
m >>= 1
|
||||||
|
return count
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
a = int('10010000', 2)
|
||||||
|
b = int('01011010', 2)
|
||||||
|
print count_bits_swap(a, b) #4
|
||||||
|
print count_bits_swap2(a, b) #4
|
26
First_edition_2014/ebook_src/bitwise_operations/set_bit.py
Executable file
26
First_edition_2014/ebook_src/bitwise_operations/set_bit.py
Executable file
@ -0,0 +1,26 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
''' Set a bit in a binary number:
|
||||||
|
1) Shifts 1 over by i bits
|
||||||
|
2) make an OR with the number, only the value at bit i will change and all the others bit
|
||||||
|
of the mask are zero so will not affect the num
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def set_bit(num, i):
|
||||||
|
mask = 1 << i
|
||||||
|
return bin( num | mask )
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
num = int('0100100', 2)
|
||||||
|
print set_bit(num, 0) #'0b100101'
|
||||||
|
print set_bit(num, 1) #'0b100110'
|
||||||
|
print set_bit(num, 2) # nothing change '0b100100'
|
||||||
|
print set_bit(num, 3) #'0b101100'
|
||||||
|
print set_bit(num, 4) #'0b110100'
|
||||||
|
print set_bit(num, 5) # nothing change '0b100100'
|
23
First_edition_2014/ebook_src/bitwise_operations/swap_in_place.py
Executable file
23
First_edition_2014/ebook_src/bitwise_operations/swap_in_place.py
Executable file
@ -0,0 +1,23 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
'''
|
||||||
|
swapping values in place without extra memory
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def swap_bit(a, b):
|
||||||
|
'''
|
||||||
|
>>> swap_bit(14, 73)
|
||||||
|
(73, 14)
|
||||||
|
'''
|
||||||
|
a = a^b
|
||||||
|
b = a^b
|
||||||
|
a = a^b
|
||||||
|
return a, b
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
37
First_edition_2014/ebook_src/bitwise_operations/swap_odd_even.py
Executable file
37
First_edition_2014/ebook_src/bitwise_operations/swap_odd_even.py
Executable file
@ -0,0 +1,37 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
''' Swap odd and even bits in a smart way in a binary:
|
||||||
|
1) first for odds, take n and move the odd:
|
||||||
|
(a) Mask all odd bits with 10101010 (0xAA)
|
||||||
|
(b) shift by right by 1
|
||||||
|
2) do the same to ints with 01010101
|
||||||
|
3) merge
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def swap_odd_even(num):
|
||||||
|
'''
|
||||||
|
>>> num = 0b11011101
|
||||||
|
>>> result = '0b1101110'
|
||||||
|
>>> swap_odd_even(num) == result
|
||||||
|
True
|
||||||
|
'''
|
||||||
|
|
||||||
|
mask_odd = 0xAA # 0b10101010
|
||||||
|
mask_even = 0x55 # 0b1010101
|
||||||
|
odd = num & mask_odd
|
||||||
|
odd >>= 1
|
||||||
|
even = num & mask_even
|
||||||
|
even >>= 1
|
||||||
|
return bin(odd | even)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
||||||
|
|
22
First_edition_2014/ebook_src/bitwise_operations/update_bit.py
Executable file
22
First_edition_2014/ebook_src/bitwise_operations/update_bit.py
Executable file
@ -0,0 +1,22 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
''' This method merges set bit and clean bit:
|
||||||
|
1) first clear the bit at i using a mask such as 1110111
|
||||||
|
2) then shift the intended value v by i bits
|
||||||
|
3) this will create a number with bit i to v and all other to 0
|
||||||
|
4) finally update the ith bit with or
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def update_bit(num, i, v):
|
||||||
|
mask = ~ (1 << i)
|
||||||
|
return bin( (num & mask) | (v << i) )
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
num = int('10010000', 2)
|
||||||
|
print update_bit(num, 2, 1) # '0b10010100'
|
||||||
|
|
42
First_edition_2014/ebook_src/dynamic_programming/memo.py
Normal file
42
First_edition_2014/ebook_src/dynamic_programming/memo.py
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
from functools import wraps
|
||||||
|
from do_benchmark import benchmark
|
||||||
|
|
||||||
|
def memo(func):
|
||||||
|
''' an example of dynamic programming using a memoizing decorator '''
|
||||||
|
cache = {}
|
||||||
|
@wraps(func)
|
||||||
|
def wrap(*args):
|
||||||
|
if args not in cache:
|
||||||
|
cache[args] = func(*args)
|
||||||
|
return cache[args]
|
||||||
|
return wrap
|
||||||
|
|
||||||
|
@memo
|
||||||
|
def find_fibonacci_seq_rec(n):
|
||||||
|
''' implements the nth fibonacci value in a recursive exponential runtime '''
|
||||||
|
if n < 2: return n
|
||||||
|
return find_fibonacci_seq_rec(n - 1) + find_fibonacci_seq_rec(n - 2)
|
||||||
|
|
||||||
|
def test_memo():
|
||||||
|
n = 50
|
||||||
|
# find_fibonacci_seq_rec = memo(find_fibonacci_seq_rec)
|
||||||
|
# @benchmark
|
||||||
|
print(find_fibonacci_seq_rec(n))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
test_memo()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -0,0 +1,85 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
from itertools import combinations
|
||||||
|
from bisect import bisect
|
||||||
|
from memo import memo
|
||||||
|
from do_benchmark import benchmark
|
||||||
|
|
||||||
|
def naive_longest_inc_subseq(seq):
|
||||||
|
''' naive (exponential) solution to the longest increasing subsequence problem '''
|
||||||
|
for length in range(len(seq), 0, -1):
|
||||||
|
for sub in combinations(seq, length):
|
||||||
|
if list(sub) == sorted(sub):
|
||||||
|
return len(sub)
|
||||||
|
|
||||||
|
|
||||||
|
def longest_inc_subseq1(seq):
|
||||||
|
''' an iterative algorithm for the longest increasing subsequence problem '''
|
||||||
|
end = []
|
||||||
|
for val in seq:
|
||||||
|
idx = bisect(end, val)
|
||||||
|
if idx == len(end): end.append(val)
|
||||||
|
else: end[idx] = val
|
||||||
|
return len(end)
|
||||||
|
|
||||||
|
|
||||||
|
def longest_inc_subseq2(seq):
|
||||||
|
''' another iterative algorithm for the longest increasing subsequence problem '''
|
||||||
|
L = [1] * len(seq)
|
||||||
|
for cur, val in enumerate(seq):
|
||||||
|
for pre in range(cur):
|
||||||
|
if seq[pre] <= val:
|
||||||
|
L[cur] = max(L[cur], 1 + L[pre])
|
||||||
|
return max(L)
|
||||||
|
|
||||||
|
|
||||||
|
def memoized_longest_inc_subseq(seq):
|
||||||
|
''' a memoized recursive solution to find the longest increasing subsequence problem '''
|
||||||
|
@memo
|
||||||
|
def L(cur):
|
||||||
|
res = 1
|
||||||
|
for pre in range(cur):
|
||||||
|
if seq[pre] <= seq[cur]:
|
||||||
|
res = max(res, 1 + L(pre))
|
||||||
|
return res
|
||||||
|
return max(L(i) for i in range(len(seq)))
|
||||||
|
|
||||||
|
|
||||||
|
@benchmark
|
||||||
|
def test_naive_longest_inc_subseq():
|
||||||
|
print(naive_longest_inc_subseq(s1))
|
||||||
|
|
||||||
|
benchmark
|
||||||
|
def test_longest_inc_subseq1():
|
||||||
|
print(longest_inc_subseq1(s1))
|
||||||
|
|
||||||
|
@benchmark
|
||||||
|
def test_longest_inc_subseq2():
|
||||||
|
print(longest_inc_subseq2(s1))
|
||||||
|
|
||||||
|
@benchmark
|
||||||
|
def test_memoized_longest_inc_subseq():
|
||||||
|
print(memoized_longest_inc_subseq(s1))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
from random import randrange
|
||||||
|
s1 = [randrange(100) for i in range(25)]
|
||||||
|
print(s1)
|
||||||
|
test_naive_longest_inc_subseq()
|
||||||
|
test_longest_inc_subseq1()
|
||||||
|
test_longest_inc_subseq2()
|
||||||
|
test_memoized_longest_inc_subseq()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -0,0 +1,30 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import shutil
|
||||||
|
|
||||||
|
def change_file_ext():
|
||||||
|
""" read a file and an extension from the command line and produces a copy with its extension changed"""
|
||||||
|
if len(sys.argv) < 2:
|
||||||
|
print("Usage: change_ext.py filename.old_ext 'new_ext'")
|
||||||
|
sys.exit()
|
||||||
|
|
||||||
|
name = os.path.splitext(sys.argv[1])[0] + "." + sys.argv[2]
|
||||||
|
print (name)
|
||||||
|
|
||||||
|
try:
|
||||||
|
shutil.copyfile(sys.argv[1], name)
|
||||||
|
except OSError as err:
|
||||||
|
print (err)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
change_file_ext()
|
||||||
|
|
||||||
|
|
28
First_edition_2014/ebook_src/manipulating_files/count_unique_words_files.py
Executable file
28
First_edition_2014/ebook_src/manipulating_files/count_unique_words_files.py
Executable file
@ -0,0 +1,28 @@
|
|||||||
|
#!/usr/bin/python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
import collections
|
||||||
|
import string
|
||||||
|
import sys
|
||||||
|
|
||||||
|
def count_unique_word_file():
|
||||||
|
if len(sys.argv) < 2:
|
||||||
|
print "Usage: python count_unique_word.py NAMEFILE"
|
||||||
|
|
||||||
|
words = collections.defaultdict(int)
|
||||||
|
strip = string.whitespace + string.punctuation + string.digits + "\"'"
|
||||||
|
for filename in sys.argv[1:]:
|
||||||
|
with open(filename) as file:
|
||||||
|
for line in file:
|
||||||
|
for word in line.lower().split():
|
||||||
|
word = word.strip(strip)
|
||||||
|
if len(word) > 2:
|
||||||
|
words[word] = +1
|
||||||
|
for word in sorted(words):
|
||||||
|
print("'{0}' occurs {1} times.".format(word, words[word]))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
count_unique_word_file()
|
@ -0,0 +1,15 @@
|
|||||||
|
#!/usr/bin/python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
import collections
|
||||||
|
import sys
|
||||||
|
|
||||||
|
def count_unique_word_freq():
|
||||||
|
return collections.Counter(\
|
||||||
|
sys.stdin.read().lower().split()).most_common(n)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
count_unique_word_freq()
|
@ -0,0 +1,27 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
import sys
|
||||||
|
|
||||||
|
def grep_word_from_files():
|
||||||
|
''' using iterator enumerate to create a grep command '''
|
||||||
|
word = sys.argv[1]
|
||||||
|
for filename in sys.argv[2:]:
|
||||||
|
with open(filename) as file:
|
||||||
|
for lino, line in enumerate(file, start=1):
|
||||||
|
if word in line:
|
||||||
|
print("{0}:{1}:{2:.40}".format(filename, lino, line.rstrip()))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
if len(sys.argv) < 2:
|
||||||
|
print("Usage: grep_word_from_files.py word infile1 [infile2...]")
|
||||||
|
sys.exit()
|
||||||
|
else:
|
||||||
|
grep_word_from_files()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -0,0 +1,54 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
def read_data(filename):
|
||||||
|
lines = []
|
||||||
|
fh = None
|
||||||
|
try:
|
||||||
|
fh = open(filename)
|
||||||
|
for line in fh:
|
||||||
|
if line.strip():
|
||||||
|
lines.append(line)
|
||||||
|
except (IOError, OSError) as err:
|
||||||
|
print(err)
|
||||||
|
finally:
|
||||||
|
if fh is not None:
|
||||||
|
fh.close()
|
||||||
|
return lines
|
||||||
|
|
||||||
|
|
||||||
|
def write_data(lines, filename):
|
||||||
|
fh = None
|
||||||
|
try:
|
||||||
|
fh = open(filename, "w")
|
||||||
|
for line in lines:
|
||||||
|
fh.write(line)
|
||||||
|
except (EnvironmentError) as err:
|
||||||
|
print(err)
|
||||||
|
finally:
|
||||||
|
if fh is not None:
|
||||||
|
fh.close()
|
||||||
|
|
||||||
|
|
||||||
|
def remove_blank_lines():
|
||||||
|
""" read a list of filenames on the command line and for each one produces another file with the same content but with no blank lines """
|
||||||
|
|
||||||
|
if len(sys.argv) < 2:
|
||||||
|
print ("Usage: noblank.py infile1 [infile2...]")
|
||||||
|
|
||||||
|
for filename in sys.argv[1:]:
|
||||||
|
lines = read_data(filename)
|
||||||
|
if lines:
|
||||||
|
write_data(lines, filename)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
remove_blank_lines()
|
||||||
|
|
@ -0,0 +1,31 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
from collections import OrderedDict
|
||||||
|
|
||||||
|
def OrderedDict_example():
|
||||||
|
''' show some examples for OrderedDict '''
|
||||||
|
''' keep the order of insertion.
|
||||||
|
maintains a doubly linked list, so size is more than twice than normal dict'''
|
||||||
|
|
||||||
|
|
||||||
|
pairs = [('a', 1), ('b',2), ('c',3)]
|
||||||
|
|
||||||
|
d1 = {}
|
||||||
|
for key, value in pairs:
|
||||||
|
if key not in d1:
|
||||||
|
d1[key] = []
|
||||||
|
d1[key].append(value)
|
||||||
|
for key in d1:
|
||||||
|
print(key, d1[key])
|
||||||
|
|
||||||
|
d2 = OrderedDict(pairs)
|
||||||
|
for key in d2:
|
||||||
|
print(key, d2[key])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
OrderedDict_example()
|
||||||
|
|
||||||
|
|
17
First_edition_2014/ebook_src/python_examples/example_args.py
Executable file
17
First_edition_2014/ebook_src/python_examples/example_args.py
Executable file
@ -0,0 +1,17 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
def simple2(a, *args):
|
||||||
|
print args
|
||||||
|
|
||||||
|
def simple(*args):
|
||||||
|
print args
|
||||||
|
|
||||||
|
def simple3(**kwargs):
|
||||||
|
print kwargs
|
||||||
|
|
||||||
|
|
||||||
|
simple(1, 2, 3)
|
||||||
|
simple2(1, 2, 3)
|
||||||
|
simple3(x=1, y=2)
|
@ -0,0 +1,28 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
import random
|
||||||
|
|
||||||
|
def benchmark(func):
|
||||||
|
import time
|
||||||
|
def wrapper(*args, **kwargs):
|
||||||
|
t = time.clock()
|
||||||
|
res = func(*args, **kwargs)
|
||||||
|
print("\t%s" % func.__name__, time.clock()-t)
|
||||||
|
return res
|
||||||
|
return wrapper
|
||||||
|
|
||||||
|
|
||||||
|
@benchmark
|
||||||
|
def random_tree(n):
|
||||||
|
temp = [n for n in range(n)]
|
||||||
|
for i in range(n+1):
|
||||||
|
temp[random.choice(temp)] = random.choice(temp)
|
||||||
|
return temp
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
random_tree(10000)
|
||||||
|
|
@ -0,0 +1,62 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
|
||||||
|
import math
|
||||||
|
|
||||||
|
class Point(object):
|
||||||
|
def __init__(self, x=0, y=0): # self: object reference to the object itself
|
||||||
|
self.x = x # data attribute
|
||||||
|
self.y = y
|
||||||
|
|
||||||
|
def distance_from_origin(self):
|
||||||
|
return math.hypot(self.x, self.y)
|
||||||
|
|
||||||
|
def __eq__(self, other):
|
||||||
|
return self.x == other.x and self.y == other.y
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return "point ({0.x!r}, {0.y!r})".format(self)
|
||||||
|
|
||||||
|
def __str__(self): # cannot be passed to eval
|
||||||
|
return "({0.x!r}, {0.y!r})".format(self)
|
||||||
|
|
||||||
|
|
||||||
|
class Circle(Point):
|
||||||
|
|
||||||
|
def __init__(self, radius, x=0, y=0):
|
||||||
|
super().__init__(x,y) # creates and initializes self.x and self.y
|
||||||
|
self.radius = radius
|
||||||
|
|
||||||
|
def edge_distance_from_origin(self):
|
||||||
|
return abs(self.distance_from_origin() - self.radius)
|
||||||
|
|
||||||
|
def area(self):
|
||||||
|
return math.pi*(self.radius**2)
|
||||||
|
|
||||||
|
def circumference(self):
|
||||||
|
return 2*math.pi*self.radius
|
||||||
|
|
||||||
|
def __eq__(self, other): # let us avoid infinite recursion
|
||||||
|
return self.radius == other.radius and super().__eq__(other)
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return "circle ({0.radius!r}, {0.x!r})".format(self)
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return repr(self)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
a = Point(3,4)
|
||||||
|
print(a.distance_from_origin())
|
||||||
|
c = Circle(3,2,1)
|
||||||
|
print(c)
|
||||||
|
print(c.circumference())
|
||||||
|
print(c. edge_distance_from_origin())
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -0,0 +1,37 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
a = [3, 4, 5, 6, 7]
|
||||||
|
|
||||||
|
|
||||||
|
# Filter elements greater than 4
|
||||||
|
|
||||||
|
# Bad:
|
||||||
|
|
||||||
|
b = []
|
||||||
|
for i in a:
|
||||||
|
if i > 4:
|
||||||
|
b.append(i)
|
||||||
|
print b
|
||||||
|
|
||||||
|
# Good:
|
||||||
|
print [i for i in a if i > 4]
|
||||||
|
|
||||||
|
# Or:
|
||||||
|
print filter(lambda x: x > 4, a)
|
||||||
|
|
||||||
|
|
||||||
|
# Add three to all list members:
|
||||||
|
|
||||||
|
# Bad
|
||||||
|
b = []
|
||||||
|
for i in range(len(a)):
|
||||||
|
b.append(a[i] + 3)
|
||||||
|
print b
|
||||||
|
|
||||||
|
# Good:
|
||||||
|
print [i + 3 for i in a]
|
||||||
|
|
||||||
|
# Or:
|
||||||
|
print map(lambda i: i + 3, a)
|
@ -0,0 +1,32 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
from collections import Counter
|
||||||
|
|
||||||
|
def Counter_example():
|
||||||
|
''' it is a dictionary that maps the items to the number of occurrences '''
|
||||||
|
seq1 = [1, 2, 3, 5, 1, 2, 5, 5, 2, 5, 1, 4]
|
||||||
|
seq_counts = Counter(seq1)
|
||||||
|
print(seq_counts)
|
||||||
|
|
||||||
|
''' we can increment manually or use the update() method '''
|
||||||
|
seq2 = [1, 2, 3]
|
||||||
|
seq_counts.update(seq2)
|
||||||
|
print(seq_counts)
|
||||||
|
|
||||||
|
seq3 = [1, 4, 3]
|
||||||
|
for key in seq3:
|
||||||
|
seq_counts[key] += 1
|
||||||
|
print(seq_counts)
|
||||||
|
|
||||||
|
''' also, we can use set operations such as a-b or a+b '''
|
||||||
|
seq_counts_2 = Counter(seq3)
|
||||||
|
print(seq_counts_2)
|
||||||
|
print(seq_counts + seq_counts_2)
|
||||||
|
print(seq_counts - seq_counts_2)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
Counter_example()
|
||||||
|
|
||||||
|
|
@ -0,0 +1,19 @@
|
|||||||
|
#!/bin/python
|
||||||
|
#
|
||||||
|
# An example of Python Decorator
|
||||||
|
#
|
||||||
|
|
||||||
|
def pretty_sumab(func):
|
||||||
|
def inner(a,b):
|
||||||
|
print(str(a) + " + " + str(b) + " is ", end="")
|
||||||
|
return func(a,b)
|
||||||
|
|
||||||
|
return inner
|
||||||
|
|
||||||
|
@pretty_sumab
|
||||||
|
def sumab(a,b):
|
||||||
|
summed = a + b
|
||||||
|
print(summed)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sumab(5,3)
|
42
First_edition_2014/ebook_src/python_examples/example_decorators.py
Executable file
42
First_edition_2014/ebook_src/python_examples/example_decorators.py
Executable file
@ -0,0 +1,42 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def logger(func):
|
||||||
|
def inner(*args): #1
|
||||||
|
print "Arguments were: {0}".format(args)
|
||||||
|
return func(*args)
|
||||||
|
return inner
|
||||||
|
|
||||||
|
@logger
|
||||||
|
def foo(x, y):
|
||||||
|
return x+y
|
||||||
|
|
||||||
|
print foo(1, 2)
|
||||||
|
|
||||||
|
|
||||||
|
def sum(func):
|
||||||
|
s = 0
|
||||||
|
for i in func():
|
||||||
|
s += i
|
||||||
|
return s
|
||||||
|
|
||||||
|
@sum
|
||||||
|
def interate():
|
||||||
|
a = []
|
||||||
|
for i in range(10):
|
||||||
|
a.append(i)
|
||||||
|
return a
|
||||||
|
|
||||||
|
print interate
|
||||||
|
|
||||||
|
# which is the same as
|
||||||
|
def interate():
|
||||||
|
a = []
|
||||||
|
for i in range(10):
|
||||||
|
a.append(i)
|
||||||
|
return a
|
||||||
|
|
||||||
|
print sum(interate)
|
@ -0,0 +1,27 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
from collections import defaultdict
|
||||||
|
|
||||||
|
def defaultdict_example():
|
||||||
|
''' show some examples for defaultdicts '''
|
||||||
|
pairs = {('a', 1), ('b',2), ('c',3)}
|
||||||
|
|
||||||
|
d1 = {}
|
||||||
|
for key, value in pairs:
|
||||||
|
if key not in d1:
|
||||||
|
d1[key] = []
|
||||||
|
d1[key].append(value)
|
||||||
|
print(d1)
|
||||||
|
|
||||||
|
d2 = defaultdict(list)
|
||||||
|
for key, value in pairs:
|
||||||
|
d2[key].append(value)
|
||||||
|
print(d2)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
defaultdict_example()
|
||||||
|
|
||||||
|
|
@ -0,0 +1,15 @@
|
|||||||
|
#!/usr/bin/python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
'''
|
||||||
|
The doctest module automatically runs any statement beginning with >>>
|
||||||
|
and compares the following line with the output from the interpreter.
|
||||||
|
|
||||||
|
>>> 1 == 1
|
||||||
|
False
|
||||||
|
'''
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
@ -0,0 +1,45 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
from fractions import Fraction
|
||||||
|
|
||||||
|
def rounding_floats(number1, places):
|
||||||
|
return round(number1, places)
|
||||||
|
|
||||||
|
|
||||||
|
def float_to_fractions(number):
|
||||||
|
return Fraction(*number.as_integer_ratio())
|
||||||
|
|
||||||
|
|
||||||
|
def get_denominator(number1, number2):
|
||||||
|
a = Fraction(number1, number2)
|
||||||
|
return a.denominator
|
||||||
|
|
||||||
|
|
||||||
|
def get_numerator(number1, number2):
|
||||||
|
a = Fraction(number1, number2)
|
||||||
|
return a.numerator
|
||||||
|
|
||||||
|
|
||||||
|
def test_testing_floats(module_name='this module'):
|
||||||
|
number1 = 1.25
|
||||||
|
number2 = 1
|
||||||
|
number3 = -1
|
||||||
|
number4 = 5/4
|
||||||
|
number6 = 6
|
||||||
|
assert(rounding_floats(number1, number2) == 1.2)
|
||||||
|
assert(rounding_floats(number1*10, number3) == 10)
|
||||||
|
assert(float_to_fractions(number1) == number4)
|
||||||
|
assert(get_denominator(number2, number6) == number6)
|
||||||
|
assert(get_numerator(number2, number6) == number2)
|
||||||
|
|
||||||
|
s = 'Tests in {name} have {con}!'
|
||||||
|
print(s.format(name=module_name, con='passed'))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
test_testing_floats()
|
||||||
|
|
||||||
|
|
@ -0,0 +1,27 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
def interate(x):
|
||||||
|
for i in range(x):
|
||||||
|
yield i
|
||||||
|
|
||||||
|
def gen1():
|
||||||
|
a = interate(10)
|
||||||
|
print a.next()
|
||||||
|
print a.next()
|
||||||
|
print a.next()
|
||||||
|
|
||||||
|
|
||||||
|
def reverse(data):
|
||||||
|
for i in range(len(data)-1, -1, -1):
|
||||||
|
yield data[i]
|
||||||
|
|
||||||
|
def gen2():
|
||||||
|
for c in reverse('awesome'):
|
||||||
|
print c
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
gen1()
|
||||||
|
gen2()
|
@ -0,0 +1,7 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
test = lambda x: x**2
|
||||||
|
print test(3)
|
@ -0,0 +1,21 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
LOG_FILENAME = 'logging_example.out'
|
||||||
|
logging.basicConfig(filename=LOG_FILENAME,
|
||||||
|
level=logging.DEBUG,
|
||||||
|
)
|
||||||
|
|
||||||
|
logging.debug('This message should go to the log file')
|
||||||
|
|
||||||
|
f = open(LOG_FILENAME, 'rt')
|
||||||
|
try:
|
||||||
|
body = f.read()
|
||||||
|
finally:
|
||||||
|
f.close()
|
||||||
|
|
||||||
|
print 'FILE:'
|
||||||
|
print body
|
@ -0,0 +1,18 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
from functools import lru_cache
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=20)
|
||||||
|
def fib(n):
|
||||||
|
if n < 2:
|
||||||
|
return n
|
||||||
|
return fib(n-1) + fib(n-2)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
print([fib(n) for n in range(10)])
|
||||||
|
print(fib.cache_info())
|
@ -0,0 +1,60 @@
|
|||||||
|
|
||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
import time
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
def testing_numpy():
|
||||||
|
''' tests many features of numpy '''
|
||||||
|
ax = np.array([1,2,3])
|
||||||
|
ay = np.array([3,4,5])
|
||||||
|
print(ax)
|
||||||
|
print(ax*2)
|
||||||
|
print(ax+10)
|
||||||
|
print(np.sqrt(ax))
|
||||||
|
print(np.cos(ax))
|
||||||
|
print(ax-ay)
|
||||||
|
print(np.where(ax<2, ax, 10))
|
||||||
|
|
||||||
|
m = np.matrix([ax, ay, ax])
|
||||||
|
print(m)
|
||||||
|
print(m.T)
|
||||||
|
|
||||||
|
grid1 = np.zeros(shape=(10,10), dtype=float)
|
||||||
|
grid2 = np.ones(shape=(10,10), dtype=float)
|
||||||
|
print(grid1)
|
||||||
|
print(grid2)
|
||||||
|
print(grid1[1]+10)
|
||||||
|
print(grid2[:,2]*2)
|
||||||
|
|
||||||
|
|
||||||
|
def trad_version():
|
||||||
|
t1 = time.time()
|
||||||
|
X = range(10000000)
|
||||||
|
Y = range(10000000)
|
||||||
|
Z = []
|
||||||
|
for i in range(len(X)):
|
||||||
|
Z.append(X[i] + Y[i])
|
||||||
|
return time.time() - t1
|
||||||
|
|
||||||
|
def numpy_version():
|
||||||
|
t1 = time.time()
|
||||||
|
X = np.arange(10000000)
|
||||||
|
Y = np.arange(10000000)
|
||||||
|
Z = X + Y
|
||||||
|
return time.time() - t1
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
testing_numpy()
|
||||||
|
print(trad_version())
|
||||||
|
print(numpy_version())
|
||||||
|
|
||||||
|
|
||||||
|
'''
|
||||||
|
3.23564291
|
||||||
|
0.0714290142059
|
||||||
|
'''
|
@ -0,0 +1,10 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
filename = raw_input('Enter a file name: ')
|
||||||
|
try:
|
||||||
|
f = open(filename, "r")
|
||||||
|
except:
|
||||||
|
print 'There is no file named', filename
|
||||||
|
|
@ -0,0 +1,58 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
import pickle
|
||||||
|
|
||||||
|
def import_pickle(filename):
|
||||||
|
fh = None
|
||||||
|
try:
|
||||||
|
fh = open(filename, "rb")
|
||||||
|
mydict2 = pickle.load(fh)
|
||||||
|
return mydict2
|
||||||
|
|
||||||
|
except (EnvironmentError) as err:
|
||||||
|
print ("{0}: import error: {0}".format(os.path.basename(sys.arg[0]), err))
|
||||||
|
return false
|
||||||
|
|
||||||
|
finally:
|
||||||
|
if fh is not None:
|
||||||
|
fh.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_import_pickle():
|
||||||
|
pkl_file = 'test.dat'
|
||||||
|
mydict = import_pickle(pkl_file)
|
||||||
|
print(mydict)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def export_pickle(data, filename='test.dat', compress=False):
|
||||||
|
|
||||||
|
fh = None
|
||||||
|
try:
|
||||||
|
if compress:
|
||||||
|
fh = gzip.open(filename, "wb") # write binary
|
||||||
|
else:
|
||||||
|
fh = open(filename, "wb") # compact binary pickle format
|
||||||
|
pickle.dump(data, fh, pickle.HIGHEST_PROTOCOL)
|
||||||
|
|
||||||
|
except(EnvironmentError, pickle.PickingError) as err:
|
||||||
|
print("{0}: export error: {1}".format(os.path.basename(sys.argv[0], err)))
|
||||||
|
return False
|
||||||
|
|
||||||
|
finally:
|
||||||
|
if fh is not None:
|
||||||
|
fh.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_export_pickle():
|
||||||
|
mydict = {'a': 1, 'b': 2, 'c': 3}
|
||||||
|
export_pickle(mydict)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
test_export_pickle()
|
||||||
|
test_import_pickle()
|
13
First_edition_2014/ebook_src/python_examples/example_queue.py
Executable file
13
First_edition_2014/ebook_src/python_examples/example_queue.py
Executable file
@ -0,0 +1,13 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
import Queue
|
||||||
|
|
||||||
|
q = Queue.Queue()
|
||||||
|
|
||||||
|
for i in range(10):
|
||||||
|
q.put(i)
|
||||||
|
|
||||||
|
for i in range(10):
|
||||||
|
print q.get(i)
|
@ -0,0 +1,27 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
import random
|
||||||
|
|
||||||
|
def testing_random():
|
||||||
|
''' testing the module random'''
|
||||||
|
values = [1, 2, 3, 4]
|
||||||
|
print(random.choice(values))
|
||||||
|
print(random.choice(values))
|
||||||
|
print(random.choice(values))
|
||||||
|
print(random.sample(values, 2))
|
||||||
|
print(random.sample(values, 3))
|
||||||
|
|
||||||
|
''' shuffle in place '''
|
||||||
|
random.shuffle(values)
|
||||||
|
print(values)
|
||||||
|
|
||||||
|
''' create random integers '''
|
||||||
|
print(random.randint(0,10))
|
||||||
|
print(random.randint(0,10))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
testing_random()
|
||||||
|
|
@ -0,0 +1,38 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
def usual_dict(dict_data):
|
||||||
|
newdata = {}
|
||||||
|
for k, v in dict_data:
|
||||||
|
if k in newdata:
|
||||||
|
newdata[k].append(v)
|
||||||
|
else:
|
||||||
|
newdata[k] = [v]
|
||||||
|
return newdata
|
||||||
|
|
||||||
|
|
||||||
|
def setdefault_dict(dict_data):
|
||||||
|
newdata = {}
|
||||||
|
for k, v in dict_data:
|
||||||
|
newdata.setdefault(k, []).append(v)
|
||||||
|
return newdata
|
||||||
|
|
||||||
|
|
||||||
|
def test_setdef(module_name='this module'):
|
||||||
|
dict_data = (('key1', 'value1'),
|
||||||
|
('key1', 'value2'),
|
||||||
|
('key2', 'value3'),
|
||||||
|
('key2', 'value4'),
|
||||||
|
('key2', 'value5'),)
|
||||||
|
print(usual_dict(dict_data))
|
||||||
|
print(setdefault_dict(dict_data))
|
||||||
|
|
||||||
|
s = 'Tests in {name} have {con}!'
|
||||||
|
print(s.format(name=module_name, con='passed'))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
test_setdef()
|
||||||
|
|
37
First_edition_2014/ebook_src/python_examples/example_sets.py
Normal file
37
First_edition_2014/ebook_src/python_examples/example_sets.py
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
def difference(l1):
|
||||||
|
""" return the list with duplicate elements removed """
|
||||||
|
return list(set(l1))
|
||||||
|
|
||||||
|
def intersection(l1, l2):
|
||||||
|
""" return the intersection of two lists """
|
||||||
|
return list(set(l1) & set(l2))
|
||||||
|
|
||||||
|
def union(l1, l2):
|
||||||
|
""" return the union of two lists """
|
||||||
|
return list(set(l1) | set(l2))
|
||||||
|
|
||||||
|
|
||||||
|
def test_sets_operations_with_lists():
|
||||||
|
l1 = [1,2,3,4,5,9,11,15]
|
||||||
|
l2 = [4,5,6,7,8]
|
||||||
|
l3 = []
|
||||||
|
assert(difference(l1) == [1, 2, 3, 4, 5, 9, 11, 15])
|
||||||
|
assert(difference(l2) == [8, 4, 5, 6, 7])
|
||||||
|
assert(intersection(l1, l2) == [4,5])
|
||||||
|
assert(union(l1, l2) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 15])
|
||||||
|
assert(difference(l3) == [])
|
||||||
|
assert(intersection(l3, l2) == l3)
|
||||||
|
assert(sorted(union(l3, l2)) == sorted(l2))
|
||||||
|
print('Tests passed!')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
test_sets_operations_with_lists()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -0,0 +1,35 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
import socket
|
||||||
|
|
||||||
|
|
||||||
|
def netcat(hostname, port, content):
|
||||||
|
|
||||||
|
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
|
|
||||||
|
s.connect((hostname, port))
|
||||||
|
s.sendall(content)
|
||||||
|
|
||||||
|
adata = []
|
||||||
|
while 1:
|
||||||
|
data = s.recv(1024)
|
||||||
|
if data == '':
|
||||||
|
break
|
||||||
|
adata.append(data)
|
||||||
|
|
||||||
|
s.close()
|
||||||
|
return adata
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
|
||||||
|
PORT = 12345
|
||||||
|
HOSTNAME = '54.209.5.48'
|
||||||
|
|
||||||
|
message = netcat(HOSTNAME, PORT, 'Hello!')[1]
|
||||||
|
print message
|
@ -0,0 +1,11 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
foo = 'foo'
|
||||||
|
bar = 'bar'
|
||||||
|
|
||||||
|
print '%s%s' % (foo, bar) # It is OK
|
||||||
|
print '{0}{1}'.format(foo, bar) # It is better
|
||||||
|
print '{foo}{bar}'.format(foo=foo, bar=bar) # It is best
|
@ -0,0 +1,8 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
import subprocess,os
|
||||||
|
|
||||||
|
os.system('ls')
|
||||||
|
subprocess.call(['ls', '-1'], shell=True)
|
@ -0,0 +1,22 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
from telnetlib import Telnet
|
||||||
|
|
||||||
|
|
||||||
|
# examples of telnet connections
|
||||||
|
PORT = 12345
|
||||||
|
HOST = '54.209.5.48'
|
||||||
|
|
||||||
|
# creating connection
|
||||||
|
tn = Telnet(HOST ,PORT)
|
||||||
|
|
||||||
|
# reading input
|
||||||
|
msg_in2 = tn.read_all().dec_msg()
|
||||||
|
tn.read_until(b'psifer text: ')
|
||||||
|
|
||||||
|
# writing outputs
|
||||||
|
tn.write(msg.encode() + b'\n')
|
@ -0,0 +1,46 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def test_doctest():
|
||||||
|
'''
|
||||||
|
>>> 1 == 1
|
||||||
|
False
|
||||||
|
'''
|
||||||
|
pass
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
doctest.testmod()
|
||||||
|
|
||||||
|
#####
|
||||||
|
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
class BasicsTestCase(unittest.TestCase):
|
||||||
|
|
||||||
|
def test_find_name(self):
|
||||||
|
self.assertTrue(1 == 1)
|
||||||
|
self.assertFalse(1 == 2)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#####
|
||||||
|
|
||||||
|
# content of test_example.py, run with $ py.test
|
||||||
|
#
|
||||||
|
# run tests over the directory
|
||||||
|
# $ nosetest
|
||||||
|
|
||||||
|
|
||||||
|
def func(x):
|
||||||
|
return x + 1
|
||||||
|
|
||||||
|
def test_answer():
|
||||||
|
assert func(3) == 4
|
||||||
|
|
@ -0,0 +1,16 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
import threading
|
||||||
|
|
||||||
|
def worker(num):
|
||||||
|
"""thread worker function"""
|
||||||
|
print 'Worker: %s' % num
|
||||||
|
return
|
||||||
|
|
||||||
|
threads = []
|
||||||
|
for i in range(5):
|
||||||
|
t = threading.Thread(target=worker, args=(i,))
|
||||||
|
threads.append(t)
|
||||||
|
t.start()
|
24
First_edition_2014/ebook_src/python_examples/example_time.py
Normal file
24
First_edition_2014/ebook_src/python_examples/example_time.py
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
#!/usr/bin/python
|
||||||
|
|
||||||
|
__author__ = "bt3"
|
||||||
|
|
||||||
|
''' a simple example of how to time a function '''
|
||||||
|
|
||||||
|
import time
|
||||||
|
|
||||||
|
def sumOfN2(n):
|
||||||
|
start = time.time()
|
||||||
|
theSum = 0
|
||||||
|
for i in range(1,n+1):
|
||||||
|
theSum = theSum + i
|
||||||
|
end = time.time()
|
||||||
|
return theSum,end-start
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
n = 5
|
||||||
|
print("Sum is %d and required %10.7f seconds"%sumOfN2(n))
|
||||||
|
n = 200
|
||||||
|
print("Sum is %d and required %10.7f seconds"%sumOfN2(n))
|
||||||
|
|
@ -0,0 +1,281 @@
|
|||||||
|
|
||||||
|
## Python General Questions & Answers
|
||||||
|
|
||||||
|
Python is a programming language with objects, modules, threads, exceptions and automatic memory management. The benefits of pythons are that it is simple and easy, portable, extensible, build-in data structure and it is an open source.
|
||||||
|
|
||||||
|
|
||||||
|
#### What is PEP 8?
|
||||||
|
|
||||||
|
PEP 8 is a coding convention, a set of recommendation, about how to write your Python code more readable.
|
||||||
|
|
||||||
|
|
||||||
|
#### What is pickling and unpickling?
|
||||||
|
|
||||||
|
Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using a dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.
|
||||||
|
|
||||||
|
|
||||||
|
#### How Python is interpreted?
|
||||||
|
|
||||||
|
Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.
|
||||||
|
|
||||||
|
|
||||||
|
#### How memory is managed in Python?
|
||||||
|
|
||||||
|
Python memory is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have access to this private heap and interpreter takes care of this Python private heap.
|
||||||
|
The allocation of Python heap space for Python objects is done by Python memory manager. The core API gives access to some tools for the programmer to code.
|
||||||
|
Python also has an inbuilt garbage collector, which recycle all the unused memory and frees the memory and makes it available to the heap space.
|
||||||
|
|
||||||
|
|
||||||
|
#### What are the tools that help to find bugs or perform static analysis?
|
||||||
|
|
||||||
|
PyChecker is a static analysis tool that detects the bugs in Python source code and warns about the style and complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard.
|
||||||
|
|
||||||
|
|
||||||
|
#### What are Python decorators?
|
||||||
|
|
||||||
|
A Python decorator is a specific change that we make in Python syntax to alter functions easily.
|
||||||
|
|
||||||
|
#### What is the difference between list and tuple?
|
||||||
|
|
||||||
|
The difference between list and tuple is that list is mutable while tuple is not. Tuple can be hashed for e.g as a key for dictionaries.
|
||||||
|
|
||||||
|
|
||||||
|
#### How are arguments passed by value or by reference?
|
||||||
|
|
||||||
|
Everything in Python is an object and all variables hold references to the objects. The references values are according to the functions; as a result, you cannot change the value of the references. However, you can change the objects if it is mutable.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#### What are the built-in type does python provides?
|
||||||
|
|
||||||
|
There are mutable and Immutable types of Pythons built-in types Mutable built-in types
|
||||||
|
|
||||||
|
List
|
||||||
|
Sets
|
||||||
|
Dictionaries
|
||||||
|
Immutable built-in types
|
||||||
|
Strings
|
||||||
|
Tuples
|
||||||
|
Numbers
|
||||||
|
|
||||||
|
|
||||||
|
#### What is namespace in Python?
|
||||||
|
|
||||||
|
In Python, every name introduced has a place where it lives and can be hooked for. This is known as namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched, to get the corresponding object.
|
||||||
|
|
||||||
|
|
||||||
|
#### What is lambda in Python?
|
||||||
|
|
||||||
|
It is a single expression anonymous function often used as an inline function.
|
||||||
|
|
||||||
|
|
||||||
|
#### Why lambda forms in python do not have statements?
|
||||||
|
|
||||||
|
A lambda form in python does not have statements as it is used to make new function object and then return them at runtime.
|
||||||
|
|
||||||
|
|
||||||
|
#### What is pass in Python?
|
||||||
|
|
||||||
|
Pass means, no-operation Python statement, or in other words, it is a place holder in a compound statement, where there should be a blank left and nothing has to be written there.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#### In Python what are iterators?
|
||||||
|
|
||||||
|
In Python, iterators are used to iterate a group of elements, containers like list.
|
||||||
|
|
||||||
|
|
||||||
|
#### What is unittest in Python?
|
||||||
|
|
||||||
|
A unit testing framework in Python is known as unittest. It supports sharing of setups, automation testing, shutdown code for tests, aggregation of tests into collections, etc.
|
||||||
|
|
||||||
|
|
||||||
|
#### In Python what is slicing?
|
||||||
|
|
||||||
|
A mechanism to select a range of items from sequence types like list, tuple, strings, etc. is known as slicing.
|
||||||
|
|
||||||
|
|
||||||
|
#### What are generators in Python?
|
||||||
|
|
||||||
|
The way of implementing iterators are known as generators. It is a normal function except that it yields expression in the function.
|
||||||
|
|
||||||
|
|
||||||
|
#### What is docstring in Python?
|
||||||
|
|
||||||
|
A Python documentation string is known as docstring, it is a way of documenting Python functions, modules and classes.
|
||||||
|
|
||||||
|
|
||||||
|
#### How can you copy an object in Python?
|
||||||
|
|
||||||
|
To copy an object in Python, you can try copy.copy () or copy.deepcopy() for the general case. You cannot copy all objects but most of them.
|
||||||
|
|
||||||
|
#### What is the difference between deep and shallow copy?
|
||||||
|
|
||||||
|
Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Whereas, a deep copy is used to store the values that are already copied.
|
||||||
|
|
||||||
|
#### What is a negative index in Python?
|
||||||
|
|
||||||
|
Python sequences can be index in positive and negative numbers. For positive index, 0 is the first index, 1 is the second index and so forth. For negative index, (-1) is the last index and (-2) is the second last index and so forth.
|
||||||
|
|
||||||
|
|
||||||
|
#### How you can convert a number to a string?
|
||||||
|
|
||||||
|
In order to convert a number into a string, use the inbuilt function str(). If you want a octal or hexadecimal representation, use the inbuilt function oct() or hex().
|
||||||
|
|
||||||
|
|
||||||
|
#### What is the difference between Xrange and range?
|
||||||
|
|
||||||
|
Xrange returns the xrange object while range returns the list, and uses the same memory no matter what the range size is.
|
||||||
|
|
||||||
|
|
||||||
|
#### What is module and package in Python?
|
||||||
|
|
||||||
|
In Python, a module is the way to structure program. Each Python program file is a module, which imports other modules like objects and attributes.
|
||||||
|
The folder of Python program is a package of modules. A package can have modules or subfolders.
|
||||||
|
|
||||||
|
|
||||||
|
#### What are the rules for local and global variables in Python?
|
||||||
|
|
||||||
|
Local variables: If a variable is assigned a new value anywhere within the function's body, it's assumed to be local.
|
||||||
|
|
||||||
|
Global variables: Those variables that are only referenced inside a function are implicitly global.
|
||||||
|
|
||||||
|
|
||||||
|
#### How can you share global variables across modules?
|
||||||
|
|
||||||
|
To share global variables across modules within a single program, create a special module. Import the config module in all modules of your application. The module will be available as a global variable across modules.
|
||||||
|
|
||||||
|
|
||||||
|
#### Explain how can you make a Python Script executable on Unix?
|
||||||
|
|
||||||
|
To make a Python Script executable on Unix, you need to do two things,
|
||||||
|
|
||||||
|
Script file's mode must be executable and
|
||||||
|
the first line must begin with # (`#!/usr/local/bin/python`).
|
||||||
|
|
||||||
|
|
||||||
|
#### Explain how to delete a file in Python?
|
||||||
|
|
||||||
|
By using a command `os.remove (filename)` or `os.unlink(filename)`.
|
||||||
|
|
||||||
|
|
||||||
|
#### Explain how can you generate random numbers in Python?
|
||||||
|
|
||||||
|
To generate random numbers in Python, you need to import command as
|
||||||
|
|
||||||
|
```
|
||||||
|
import random
|
||||||
|
random.random()
|
||||||
|
```
|
||||||
|
|
||||||
|
This returns a random floating point number in the range [0,1)
|
||||||
|
|
||||||
|
|
||||||
|
#### Explain how can you access a module written in Python from C?
|
||||||
|
|
||||||
|
You can access a module written in Python from C by following method,
|
||||||
|
|
||||||
|
```
|
||||||
|
Module = =PyImport_ImportModule("<modulename>");
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
#### Mention the use of // operator in Python?
|
||||||
|
|
||||||
|
It is a Floor Division operator, which is used for dividing two operands with the result as quotient showing only digits before the decimal point. For instance, `10//5 = 2 and 10.0//5.0 = 2.0`.
|
||||||
|
|
||||||
|
|
||||||
|
#### Explain what is Flask & its benefits?
|
||||||
|
|
||||||
|
Flask is a web microframework for Python based on "Werkzeug, Jinja 2 and good intentions" BSD licensed. Werkzeug and jingja are two of its dependencies.
|
||||||
|
|
||||||
|
Flask is part of the micro-framework. Which means it will have little to no dependencies on external libraries. It makes the framework light while there is a little dependency to update and fewer security bugs.
|
||||||
|
|
||||||
|
|
||||||
|
#### What is the difference between Django, Pyramid, and Flask?
|
||||||
|
|
||||||
|
Flask is a "microframework" primarily build for a small application with simpler requirements. In Flask, you have to use external libraries. Flask is ready to use.
|
||||||
|
|
||||||
|
Pyramid is built for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable.
|
||||||
|
|
||||||
|
Like Pyramid, Django can also be used for larger applications. It includes an ORM.
|
||||||
|
|
||||||
|
|
||||||
|
#### Explain how you can access sessions in Flask?
|
||||||
|
|
||||||
|
A session basically allows you to remember information from one request to another. In a flask, it uses a signed cookie so the user can look at the session contents and modify. The user can modify the session if only it has the secret key Flask.secret_key.
|
||||||
|
|
||||||
|
|
||||||
|
#### Is Flask an MVC model and if yes give an example showing MVC pattern for your application?
|
||||||
|
|
||||||
|
Basically, Flask is a minimalistic framework which behaves the same as MVC framework. So MVC is a perfect fit for Flask, and the pattern for MVC we will consider for the following example:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from flask import Flask
|
||||||
|
|
||||||
|
app = Flask(_name_)
|
||||||
|
|
||||||
|
@app.route("/")
|
||||||
|
|
||||||
|
Def hello():
|
||||||
|
|
||||||
|
return "Hello World"
|
||||||
|
|
||||||
|
app.run(debug = True)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Explain database connection in Python Flask?
|
||||||
|
|
||||||
|
Flask supports database powered application (RDBS). Such a system requires creating a schema, which requires piping the shema.sql file into a sqlite3 command. So you need to install sqlite3 command in order to create or initiate the database in Flask.
|
||||||
|
|
||||||
|
Flask allows requesting database in three ways
|
||||||
|
|
||||||
|
* before_request() : They are called before a request and pass no arguments.
|
||||||
|
* after_request() : They are called after a request and pass the response that will be sent to the client.
|
||||||
|
* teardown_request(): They are called in a situation when an exception is raised, and response is not guaranteed. They are called after the response been constructed. They are not allowed to modify the request, and their values are ignored.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#### You are having multiple Memcache servers running Python, in which one of the Memcache server fails, and it has your data, will it ever try to get key data from that one failed server?
|
||||||
|
|
||||||
|
The data in the failed server won't get removed, but there is a provision for auto-failure, which you can configure for multiple nodes. Fail-over can be triggered during any kind of socket or Memcached server level errors and not during normal client errors like adding an existing key, etc.
|
||||||
|
|
||||||
|
|
||||||
|
#### Explain how you can minimize the Memcached server outages in your Python Development?
|
||||||
|
|
||||||
|
When one instance fails, several of them goes down, this will put a larger load on the database server when lost data is reloaded as the client make a request. To avoid this, if your code has been written to minimize cache stampedes then it will leave a minimal impact.
|
||||||
|
|
||||||
|
Another way is to bring up an instance of Memcached on a new machine using the lost machines IP address.
|
||||||
|
|
||||||
|
|
||||||
|
#### Explain how Memcached should not be used in your Python project?
|
||||||
|
|
||||||
|
Memcached common misuse is to use it as a data store, and not as a cache. Never use Memcached as the only source of the information you need to run your application. Data should always be available through another source as well. Memcached is just a key or value store and cannot perform query over the data or iterate over the contents to extract information. Memcached does not offer any form of security either in encryption or authentication.
|
||||||
|
|
||||||
|
#### What's a metaclass in Python?
|
||||||
|
|
||||||
|
This type of class holds the instructions about the behind-the-scenes code generation that you want to take place when another piece of code is being executed. With a metaclass, we can define properties that should be added to new classes that are defined in our code.
|
||||||
|
|
||||||
|
#### Why isn't all memory freed when Python exits?
|
||||||
|
Objects referenced from the global namespaces of Python modules are not always deallocated when Python exits. This may happen if there are circular references. There are also certain bits of memory that are allocated by the C library that are impossible to free/ Python is, however, aggressive about cleaning up memory on exit and does try to destroy every single object.
|
||||||
|
|
||||||
|
If you want to force Python to delete certain things on deallocation, you can use the atexit module to register one or more exit functions to handle those deletions.
|
||||||
|
|
||||||
|
#### Usage of `__slots__`?
|
||||||
|
|
||||||
|
The special attribute `__slots__` allows you to explicitly state which instance attributes you expect your object instances to have, with the expected results:
|
||||||
|
|
||||||
|
* faster attribute access.
|
||||||
|
* space savings in memory.
|
||||||
|
|
||||||
|
#### What id() function in Python is for?
|
||||||
|
|
||||||
|
`id()` function accepts a single parameter and is used to return the identity of an object. This identity has to be unique and constant for this object during the lifetime. Two objects with non-overlapping lifetimes may have the same `id()` value.
|
||||||
|
|
||||||
|
#### Is Python call-by-value or call-by-reference?
|
||||||
|
|
||||||
|
Neither. In Python, (almost) everything is an object. What we commonly refer to as "variables" in Python are more properly called names. Likewise, "assignment" is really the binding of a name to an object. Each binding has a scope that defines its visibility, usually the block in which the name originates.
|
||||||
|
|
||||||
|
In Python a variable is not an alias for a location in memory. Rather, it is simply binding to a Python object.ext post.
|
||||||
|
|
||||||
|
----
|
44
First_edition_2014/ebook_src/real_interview_problems/other_resources/Project-Euler/.gitignore
vendored
Normal file
44
First_edition_2014/ebook_src/real_interview_problems/other_resources/Project-Euler/.gitignore
vendored
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
# Byte-compiled / optimized / DLL files
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
|
||||||
|
# C extensions
|
||||||
|
*.so
|
||||||
|
|
||||||
|
# Distribution / packaging
|
||||||
|
.Python
|
||||||
|
env/
|
||||||
|
build/
|
||||||
|
develop-eggs/
|
||||||
|
dist/
|
||||||
|
eggs/
|
||||||
|
lib/
|
||||||
|
lib64/
|
||||||
|
parts/
|
||||||
|
sdist/
|
||||||
|
var/
|
||||||
|
*.egg-info/
|
||||||
|
.installed.cfg
|
||||||
|
*.egg
|
||||||
|
|
||||||
|
# Installer logs
|
||||||
|
pip-log.txt
|
||||||
|
pip-delete-this-directory.txt
|
||||||
|
|
||||||
|
# Unit test / coverage reports
|
||||||
|
htmlcov/
|
||||||
|
.tox/
|
||||||
|
.coverage
|
||||||
|
.cache
|
||||||
|
nosetests.xml
|
||||||
|
coverage.xml
|
||||||
|
|
||||||
|
# Translations
|
||||||
|
*.mo
|
||||||
|
*.pot
|
||||||
|
|
||||||
|
# Django stuff:
|
||||||
|
*.log
|
||||||
|
|
||||||
|
# Sphinx documentation
|
||||||
|
docs/_build/
|
@ -0,0 +1,22 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
|
||||||
|
def mul3and5(n):
|
||||||
|
result = 0
|
||||||
|
for num in range(1, n):
|
||||||
|
if num%3 == 0 or num%5 == 0:
|
||||||
|
result += num
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def test_():
|
||||||
|
assert(mul3and5(10) == 23)
|
||||||
|
print(mul3and5(1000))
|
||||||
|
print('Tests Passed!')
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
test_()
|
||||||
|
|
@ -0,0 +1,18 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
|
||||||
|
def even_fib_num(limit):
|
||||||
|
a, b = 0, 1
|
||||||
|
while a < limit:
|
||||||
|
yield a
|
||||||
|
a, b = b, a + b
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print(sum(n for n in even_fib_num(4e6) if not (n & 1)))
|
||||||
|
print('Tests Passed!')
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,41 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
#!/usr/bin/python3
|
||||||
|
|
||||||
|
def is_prime(n):
|
||||||
|
if n < 4 : return True
|
||||||
|
for i in range(2, int(n**0.5 + 1)):
|
||||||
|
if not n%i: return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def largest_prime_factor(n):
|
||||||
|
i = int(n**0.5 +1)
|
||||||
|
while i > 1 :
|
||||||
|
if not n%i and i&1:
|
||||||
|
if is_prime(i): return i
|
||||||
|
i -= 1
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def largest_prime_factor_optimized(n):
|
||||||
|
factor = 2
|
||||||
|
lastfactor = 1
|
||||||
|
while n > 1:
|
||||||
|
if not n%factor:
|
||||||
|
lastfactor = factor
|
||||||
|
n = n//factor
|
||||||
|
while n%factor == 0:
|
||||||
|
n = n//factor
|
||||||
|
factor += 1
|
||||||
|
return lastfactor
|
||||||
|
|
||||||
|
|
||||||
|
def test_largest_prime_factor():
|
||||||
|
assert(largest_prime_factor(13195)== 29)
|
||||||
|
print(largest_prime_factor(600851475143))
|
||||||
|
assert(largest_prime_factor_optimized(13195) == 29)
|
||||||
|
print(largest_prime_factor_optimized(600851475143))
|
||||||
|
print('Tests Passed!')
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
test_largest_prime_factor()
|
@ -0,0 +1,47 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def is_palindrome(s):
|
||||||
|
return s == reverse(s)
|
||||||
|
|
||||||
|
def reverse(s):
|
||||||
|
rev = 0
|
||||||
|
while s > 0:
|
||||||
|
rev = 10*rev + s%10
|
||||||
|
s = s//10
|
||||||
|
return rev
|
||||||
|
|
||||||
|
|
||||||
|
def is_palindrome_2(s):
|
||||||
|
# to use it you need to cast str() first
|
||||||
|
while s:
|
||||||
|
if s[0] != s[-1]: return False
|
||||||
|
else:
|
||||||
|
s = s[1:-1]
|
||||||
|
is_palindrome(s)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def larg_palind_product(n):
|
||||||
|
nmax, largpal = 9, 0
|
||||||
|
for i in range(1, n):
|
||||||
|
nmax += 9*10**i
|
||||||
|
for i in range(nmax, nmax//2, -1):
|
||||||
|
for j in range(i -1, (i -1)//2, -1):
|
||||||
|
candidate = i*j
|
||||||
|
if is_palindrome(candidate) and candidate > largpal:
|
||||||
|
largpal = candidate
|
||||||
|
return largpal
|
||||||
|
|
||||||
|
|
||||||
|
def test_larg_palind_product():
|
||||||
|
assert(larg_palind_product(2)== 9009)
|
||||||
|
print(larg_palind_product(3))
|
||||||
|
print('Tests Passed!')
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
test_larg_palind_product()
|
||||||
|
|
@ -0,0 +1,32 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
|
||||||
|
def smallest_multiple(n):
|
||||||
|
set1 = set([x for x in range(1, n+1)])
|
||||||
|
set2 = set()
|
||||||
|
for i in range(len(set1), 0, -1):
|
||||||
|
for j in range(1, i):
|
||||||
|
if i%j == 0:
|
||||||
|
set2.add(j)
|
||||||
|
set1 = set1 - set2
|
||||||
|
res_num = n*n
|
||||||
|
while True:
|
||||||
|
for i in set1:
|
||||||
|
missing_div = False
|
||||||
|
if res_num%i:
|
||||||
|
missing_div = True
|
||||||
|
shift = res_num%i
|
||||||
|
break
|
||||||
|
if not missing_div: return res_num
|
||||||
|
res_num += 1 or shift
|
||||||
|
shift = 0
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def test_():
|
||||||
|
assert(smallest_multiple(10) == 2520)
|
||||||
|
print(smallest_multiple(20))
|
||||||
|
print('Tests Passed!')
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
test_()
|
@ -0,0 +1,21 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
|
||||||
|
def sum_square_diff(n):
|
||||||
|
sq_sum, sum_sq = 0, 0
|
||||||
|
for i in range(1, n+1):
|
||||||
|
sum_sq += i**2
|
||||||
|
sq_sum += i
|
||||||
|
sq_sum = sq_sum **2
|
||||||
|
return sq_sum - sum_sq
|
||||||
|
|
||||||
|
def main():
|
||||||
|
assert(sum_square_diff(10) == 2640)
|
||||||
|
print(sum_square_diff(100))
|
||||||
|
print('Tests Passed!')
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,32 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
import math
|
||||||
|
|
||||||
|
def is_prime(number, prime_set):
|
||||||
|
if number in prime_set: return True
|
||||||
|
for i in range(2, int(math.sqrt(number)) + 1):
|
||||||
|
if not number%i: return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def findstprime(n):
|
||||||
|
count = 0
|
||||||
|
candidate = 1
|
||||||
|
prime_set = set()
|
||||||
|
while count < n:
|
||||||
|
candidate +=1
|
||||||
|
if is_prime(candidate, prime_set):
|
||||||
|
prime_set.add(candidate)
|
||||||
|
count += 1
|
||||||
|
return candidate
|
||||||
|
|
||||||
|
def main():
|
||||||
|
assert(findstprime(6 == 13))
|
||||||
|
print(findstprime(10001))
|
||||||
|
print('Tests Passed!')
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,28 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def largest_prod_seq(n):
|
||||||
|
result = 0
|
||||||
|
for i in range(0, len(n)-4):
|
||||||
|
first = int(n[i])
|
||||||
|
second = int(n[i+1])
|
||||||
|
third = int(n[i+2])
|
||||||
|
fourth = int(n[i+3])
|
||||||
|
fifth = int(n[i+4])
|
||||||
|
result_here = first*second*third*fourth*fifth
|
||||||
|
if result < result_here:
|
||||||
|
result = result_here
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
n = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450'
|
||||||
|
print(largest_prod_seq(n))
|
||||||
|
print('Tests Passed!')
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,26 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def special_pyt(n):
|
||||||
|
for i in range(3, n):
|
||||||
|
for j in range(i+1, n):
|
||||||
|
c = calc_c(i,j)
|
||||||
|
if i + j + c == n:
|
||||||
|
return i*j*c
|
||||||
|
|
||||||
|
def calc_c(a, b):
|
||||||
|
return (a**2 + b**2)**0.5
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
assert(special_pyt(3+4+5) == (3*4*5))
|
||||||
|
print(special_pyt(1000))
|
||||||
|
print('Tests Passed!')
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,24 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
from findstprime import is_prime
|
||||||
|
|
||||||
|
def summation_primes(n):
|
||||||
|
candidate = 2
|
||||||
|
prime_set = set()
|
||||||
|
while candidate < n:
|
||||||
|
if is_prime(candidate, prime_set):
|
||||||
|
prime_set.add(candidate)
|
||||||
|
candidate +=1
|
||||||
|
return sum(prime_set)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
assert(summation_primes(10) == 17)
|
||||||
|
print(summation_primes(2000000))
|
||||||
|
print('Tests Passed!')
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,66 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
import string
|
||||||
|
|
||||||
|
def get_grid(filename):
|
||||||
|
grid = [ [ 0 for i in range(20) ] for j in range(20) ]
|
||||||
|
with open(filename) as file:
|
||||||
|
for row, line in enumerate(file):
|
||||||
|
line.strip('\n')
|
||||||
|
for collumn, number in enumerate(line.split(' ')):
|
||||||
|
grid[row][collumn] = int(number)
|
||||||
|
return grid
|
||||||
|
|
||||||
|
|
||||||
|
def larg_prod_grid(grid):
|
||||||
|
row, col, larg_prod = 0, 0, 0
|
||||||
|
up, down, left, right, diag1, diag2, diag3, diag4 = 0, 0, 0, 0, 0, 0, 0, 0
|
||||||
|
while row < len(grid):
|
||||||
|
while col < len(grid[0]):
|
||||||
|
if col > 2:
|
||||||
|
up = grid[row][col] * grid[row][col-1] * grid[row][col-2] * grid[row][col-3]
|
||||||
|
if col < len(grid[0]) - 3:
|
||||||
|
down = grid[row][col] * grid[row][col+1] * grid[row][col+2] * grid[row][col+3]
|
||||||
|
if row > 2:
|
||||||
|
left = grid[row][col] * grid[row-1][col] * grid[row-2][col] * grid[row-3][col]
|
||||||
|
if row < len(grid) - 3:
|
||||||
|
right = grid[row][col] * grid[row+1][col] * grid[row+2][col] * grid[row+3][col]
|
||||||
|
|
||||||
|
if col > 2 and row > 2:
|
||||||
|
diag1 = grid[row][col] * grid[row-1][col-1] * grid[row-2][col-2] * grid[row-3][col-3]
|
||||||
|
if col > 2 and row < len(grid) - 3:
|
||||||
|
diag2 = grid[row][col] * grid[row+1][col-1] * grid[row+2][col-2] * grid[row+3][col-3]
|
||||||
|
|
||||||
|
if col < len(grid[0]) - 3 and row > 2:
|
||||||
|
diag3 = grid[row][col] * grid[row-1][col+1] * grid[row-2][col+2] * grid[row-3][col+3]
|
||||||
|
if col < len(grid[0]) -3 and row < len(grid) - 3:
|
||||||
|
down = grid[row][col] * grid[row+1][col+1] * grid[row+1][col+2] * grid[row+1][col+3]
|
||||||
|
|
||||||
|
l1 = [up, down, left, right, diag1, diag2, diag3, diag4]
|
||||||
|
largest_prod_here = max(l1)
|
||||||
|
if largest_prod_here > larg_prod:
|
||||||
|
larg_prod = largest_prod_here
|
||||||
|
col += 1
|
||||||
|
col = 0
|
||||||
|
row += 1
|
||||||
|
|
||||||
|
return larg_prod
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
import time
|
||||||
|
start = time.time()
|
||||||
|
|
||||||
|
filename = 'larg_prod_grid.dat'
|
||||||
|
grid = get_grid(filename)
|
||||||
|
assert((grid[6][8], grid[7][9], grid[8][10], grid[9][11]) == (26, 63, 78, 14))
|
||||||
|
print(larg_prod_grid(grid))
|
||||||
|
|
||||||
|
elapsed = (time.time() - start)
|
||||||
|
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,43 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
import math
|
||||||
|
|
||||||
|
def find_div(n):
|
||||||
|
''' find the divisor of a given n'''
|
||||||
|
set_div = {1, n}
|
||||||
|
for i in range(2, int(math.sqrt(n))+ 1):
|
||||||
|
if not n % i:
|
||||||
|
set_div.add(i)
|
||||||
|
set_div.add(n//i)
|
||||||
|
l1 = list(set_div)
|
||||||
|
return len(l1)
|
||||||
|
|
||||||
|
|
||||||
|
def find_trian(l):
|
||||||
|
''' find the lth trian number'''
|
||||||
|
return sum(range(1, l+1))
|
||||||
|
|
||||||
|
|
||||||
|
def highly_divisible_trian_num(d):
|
||||||
|
thtriangle, n_div, count = 1, 0, 1
|
||||||
|
while n_div < d:
|
||||||
|
count += 1
|
||||||
|
thtriangle += count
|
||||||
|
n_div = find_div(thtriangle)
|
||||||
|
return (thtriangle, count)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
import time
|
||||||
|
start = time.time()
|
||||||
|
assert(highly_divisible_trian_num(6) == (28, 7))
|
||||||
|
print(highly_divisible_trian_num(500))
|
||||||
|
|
||||||
|
elapsed = (time.time() - start)
|
||||||
|
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,25 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
def large_sum(filename):
|
||||||
|
sum_total, lines, numbers = 0, 0, 0
|
||||||
|
with open(filename) as file:
|
||||||
|
for line in file:
|
||||||
|
sum_total += int(line.strip('\n'))
|
||||||
|
return str(sum_total)[0:10]
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
import time
|
||||||
|
start = time.time()
|
||||||
|
|
||||||
|
filename = 'large_sum.dat'
|
||||||
|
print(large_sum(filename))
|
||||||
|
|
||||||
|
elapsed = (time.time() - start)
|
||||||
|
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,43 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
def find_coll_seq(n):
|
||||||
|
count = 1
|
||||||
|
while n > 1:
|
||||||
|
if n%2 == 0:
|
||||||
|
n = n//2
|
||||||
|
else:
|
||||||
|
n = 3*n +1
|
||||||
|
count += 1
|
||||||
|
return count
|
||||||
|
|
||||||
|
|
||||||
|
def find_longest_chain(limit):
|
||||||
|
longest, number = 0, 0
|
||||||
|
start = 0
|
||||||
|
while start <= limit:
|
||||||
|
size_chain = find_coll_seq(start)
|
||||||
|
if size_chain > longest:
|
||||||
|
longest = size_chain
|
||||||
|
number = start
|
||||||
|
start += 1
|
||||||
|
|
||||||
|
return (longest, number)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
import time
|
||||||
|
start = time.time()
|
||||||
|
|
||||||
|
#print(find_longest_chain(13))
|
||||||
|
print(find_longest_chain(10**6))
|
||||||
|
|
||||||
|
elapsed = (time.time() - start)
|
||||||
|
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,42 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
def lattice_paths(squares):
|
||||||
|
gridsize = squares+1
|
||||||
|
grid = [[0 for i in range(gridsize)] for j in range(gridsize)]
|
||||||
|
row, col = 0, 0
|
||||||
|
|
||||||
|
while col < gridsize:
|
||||||
|
while row < gridsize:
|
||||||
|
|
||||||
|
if row == 0 and col == 0:
|
||||||
|
grid[row][col] = 1
|
||||||
|
|
||||||
|
else:
|
||||||
|
if row == 0 and col != 0:
|
||||||
|
grid[row][col] += grid[row][col-1]
|
||||||
|
elif row != 0 and col == 0:
|
||||||
|
grid[row][col] += grid[row-1][col]
|
||||||
|
else:
|
||||||
|
grid[row][col] += grid[row][col-1] + grid[row-1][col]
|
||||||
|
|
||||||
|
row += 1
|
||||||
|
row = 0
|
||||||
|
col += 1
|
||||||
|
return grid[gridsize-1][gridsize-1]
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
import time
|
||||||
|
start = time.time()
|
||||||
|
|
||||||
|
assert(lattice_paths(2) == 6)
|
||||||
|
print(lattice_paths(20))
|
||||||
|
|
||||||
|
elapsed = (time.time() - start)
|
||||||
|
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,22 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
|
||||||
|
def power_digit_sum(n):
|
||||||
|
number = str(2**n)
|
||||||
|
sum_res = 0
|
||||||
|
for i in number:
|
||||||
|
sum_res += int(i)
|
||||||
|
return sum_res
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def test_():
|
||||||
|
assert(power_digit_sum(15) == 26)
|
||||||
|
print(power_digit_sum(1000))
|
||||||
|
print('Tests Passed!')
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
test_()
|
||||||
|
|
@ -0,0 +1,63 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def number_letter_counts(n):
|
||||||
|
dict_lett = build_dict(n)
|
||||||
|
sum_letter = 0
|
||||||
|
for item in dict_lett:
|
||||||
|
sum_letter += dict_lett[item]
|
||||||
|
return sum_letter
|
||||||
|
|
||||||
|
|
||||||
|
def build_dict(n):
|
||||||
|
lett_dict = {}
|
||||||
|
numbers = (x for x in range(1, n+1))
|
||||||
|
dec = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
|
||||||
|
ties = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
|
||||||
|
|
||||||
|
for number in numbers:
|
||||||
|
if 1 <= number < 20:
|
||||||
|
lett_dict[number] = len(dec[number-1])
|
||||||
|
elif 20 <= number < 100:
|
||||||
|
index_dec = number//10
|
||||||
|
index_num = number%10
|
||||||
|
if index_num == 0:
|
||||||
|
lett_dict[number] = len(ties[index_dec-2])
|
||||||
|
else:
|
||||||
|
lett_dict[number] = len(ties[index_dec-2]) + len(dec[index_num-1])
|
||||||
|
elif 100 <= number < 1000:
|
||||||
|
index_hun = number//100
|
||||||
|
index_dec = number%100
|
||||||
|
if index_dec == 0:
|
||||||
|
lett_dict[number] = len(dec[index_hun-1]) + len('hundred')
|
||||||
|
else:
|
||||||
|
if 1 <= index_dec < 20:
|
||||||
|
lett_dict[number] = len(dec[index_hun-1]) + len('hundred') + len('and') + len(dec[index_dec-1])
|
||||||
|
elif 20 <= index_dec < 100:
|
||||||
|
index_dec2 = index_dec//10
|
||||||
|
index_num = index_dec%10
|
||||||
|
if index_num == 0:
|
||||||
|
lett_dict[number] = len(dec[index_hun-1]) + len('hundred') + len('and') + len(ties[index_dec2-2])
|
||||||
|
else:
|
||||||
|
lett_dict[number] = len(dec[index_hun-1]) + len('hundred') + len('and') + len(ties[index_dec2-2]) + len(dec[index_num-1])
|
||||||
|
elif number == 1000:
|
||||||
|
lett_dict[number] = len('onethousand')
|
||||||
|
|
||||||
|
return lett_dict
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
import time
|
||||||
|
start = time.time()
|
||||||
|
|
||||||
|
assert(number_letter_counts(5) == 19)
|
||||||
|
print(number_letter_counts(1000))
|
||||||
|
elapsed = (time.time() - start)
|
||||||
|
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,55 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
def max_path_sum(t):
|
||||||
|
root = t[0][0]
|
||||||
|
height, width, index, large_num = 1, 0, 0, 0
|
||||||
|
max_sum = root
|
||||||
|
heights = len(t[:])
|
||||||
|
|
||||||
|
while height < heights:
|
||||||
|
values_here = t[height][index:index+2]
|
||||||
|
if values_here[0] > values_here[1]:
|
||||||
|
large_num = values_here[0]
|
||||||
|
else:
|
||||||
|
large_num = values_here[1]
|
||||||
|
index += 1
|
||||||
|
max_sum += large_num
|
||||||
|
pivot = large_num
|
||||||
|
width, large_num = 0, 0
|
||||||
|
height += 1
|
||||||
|
|
||||||
|
return max_sum
|
||||||
|
|
||||||
|
def edit_input(filename):
|
||||||
|
output = []
|
||||||
|
with open(filename) as file:
|
||||||
|
for line in file:
|
||||||
|
line = line.rstrip('\n')
|
||||||
|
output.append(line.split(' '))
|
||||||
|
for i, l1 in enumerate(output):
|
||||||
|
for j, c in enumerate(output[i]):
|
||||||
|
output[i][j] = int(c)
|
||||||
|
return(output)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
import time
|
||||||
|
start = time.time()
|
||||||
|
|
||||||
|
filename = 'max_path_sum0.dat'
|
||||||
|
t1 = edit_input(filename)
|
||||||
|
print('Little pir: ',max_path_sum(t1))
|
||||||
|
|
||||||
|
filename = 'max_path_sum.dat'
|
||||||
|
t2 = edit_input(filename)
|
||||||
|
print('Big pir: ', max_path_sum(t2))
|
||||||
|
|
||||||
|
elapsed = (time.time() - start)
|
||||||
|
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,65 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
'''
|
||||||
|
1 Jan 1900 was a Monday.
|
||||||
|
Thirty days has September,
|
||||||
|
April, June and November.
|
||||||
|
All the rest have thirty-one,
|
||||||
|
Saving February alone,
|
||||||
|
Which has twenty-eight, rain or shine.
|
||||||
|
And on leap years, twenty-nine.
|
||||||
|
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
|
||||||
|
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def find_if_leap_year(y):
|
||||||
|
if (y%4 == 0 and y%100 != 0) or (y%400 == 0):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def counting_sundays():
|
||||||
|
''' define variables '''
|
||||||
|
days_year = 7*31 + 4*30 + 28
|
||||||
|
count_sundays = 0
|
||||||
|
days_week = 7
|
||||||
|
dict_week = {0: 'mon', 1:'tue', 2:'wed', 3:'thu', 4:'fri', 5:'sat', 6:'sun'}
|
||||||
|
|
||||||
|
|
||||||
|
''' with info from 1900 find first day for 1901 '''
|
||||||
|
first_day = days_year%days_week # not a leap year
|
||||||
|
|
||||||
|
for y in range (1901, 2001):
|
||||||
|
leap_year = find_if_leap_year(y)
|
||||||
|
days_count = first_day
|
||||||
|
|
||||||
|
for m in range(1, 13):
|
||||||
|
if days_count%7 == 6:
|
||||||
|
count_sundays += 1
|
||||||
|
if m == 2:
|
||||||
|
if leap_year:
|
||||||
|
days_count += 29
|
||||||
|
else:
|
||||||
|
days_count += 28
|
||||||
|
elif m == 4 or m == 6 or m == 9 or m == 11:
|
||||||
|
days_count += 30
|
||||||
|
else:
|
||||||
|
days_count += 31
|
||||||
|
|
||||||
|
if leap_year: first_day = (first_day +2)%days_week
|
||||||
|
else: first_day = (first_day +1)%days_week
|
||||||
|
|
||||||
|
return count_sundays
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print(counting_sundays())
|
||||||
|
print('Tests Passed!')
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,32 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
def factorial(n):
|
||||||
|
prod = 1
|
||||||
|
for i in range(1,n):
|
||||||
|
prod *= i
|
||||||
|
return prod
|
||||||
|
|
||||||
|
def find_sum(n):
|
||||||
|
sum_ = 0
|
||||||
|
fact = factorial(n)
|
||||||
|
number = str(fact)
|
||||||
|
for i in number:
|
||||||
|
sum_ += int(i)
|
||||||
|
return sum_
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
import time
|
||||||
|
start = time.time()
|
||||||
|
|
||||||
|
assert(find_sum(10) == 27)
|
||||||
|
print(find_sum(100))
|
||||||
|
|
||||||
|
elapsed = (time.time() - start)
|
||||||
|
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,44 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
'''
|
||||||
|
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
|
||||||
|
If d(a) = b and d(b) = a, where a b, then a and b are an amicable pair and each of a and b are called amicable numbers.
|
||||||
|
|
||||||
|
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
|
||||||
|
|
||||||
|
Evaluate the sum of all the amicable numbers under 10000.
|
||||||
|
'''
|
||||||
|
|
||||||
|
def find_sum_proper_divisors(n):
|
||||||
|
sum_proper_div = 0
|
||||||
|
for i in range(1, n):
|
||||||
|
if n%i == 0:
|
||||||
|
sum_proper_div += i
|
||||||
|
return sum_proper_div
|
||||||
|
|
||||||
|
|
||||||
|
def amicable_numbers(N):
|
||||||
|
sum_div_list = [find_sum_proper_divisors(i) for i in range(1, N+1)]
|
||||||
|
sum_amicable_numbers = 0
|
||||||
|
set_div = set()
|
||||||
|
for a in range(1, N):
|
||||||
|
da = sum_div_list[a-1]
|
||||||
|
if da < N:
|
||||||
|
b = da
|
||||||
|
db = sum_div_list[b-1]
|
||||||
|
if a != b and db == a and a not in set_div and b not in set_div:
|
||||||
|
sum_amicable_numbers += a + b
|
||||||
|
set_div.add(a)
|
||||||
|
set_div.add(b)
|
||||||
|
return sum_amicable_numbers
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print(amicable_numbers(10000))
|
||||||
|
print('Tests Passed!')
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,33 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
|
||||||
|
def calculate_score(name, dict_letters):
|
||||||
|
sum_letters = 0
|
||||||
|
for letter in name:
|
||||||
|
sum_letters += dict_letters[letter]
|
||||||
|
return sum_letters
|
||||||
|
|
||||||
|
def names_score(filename):
|
||||||
|
dict_letters ={'A':1,'B':2,'C':3,'D':4,'E':5,'F':6,'G':7,'H':8,'I':9,'J':10,'K':11,'L':12,'M':13,'N':14,'O':15,'P':16,'Q':17,'R':18,'S':19, 'T':20,'U':21,'V':22,'W':23,'X':24,'Y':25,'Z':26}
|
||||||
|
total_score = 0
|
||||||
|
with open(filename) as file:
|
||||||
|
for line in file:
|
||||||
|
names = [name.strip('"') for name in line.split(',')]
|
||||||
|
names.sort()
|
||||||
|
for i, name in enumerate(names):
|
||||||
|
total_score += (i+1)* calculate_score(name, dict_letters)
|
||||||
|
|
||||||
|
return total_score
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
filename = 'names.txt'
|
||||||
|
print(names_score(filename))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,44 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
def find_sum_proper_div(n):
|
||||||
|
sum_proper_div = 0
|
||||||
|
for i in range(1, n):
|
||||||
|
if n%i == 0:
|
||||||
|
sum_proper_div += i
|
||||||
|
return sum_proper_div
|
||||||
|
|
||||||
|
|
||||||
|
def find_all_abund(n):
|
||||||
|
sum_div_list = [find_sum_proper_div(i) for i in range(n)]
|
||||||
|
abu = set()
|
||||||
|
for i in range(n):
|
||||||
|
if i < sum_div_list[i]:
|
||||||
|
abu.add(i)
|
||||||
|
return abu
|
||||||
|
|
||||||
|
|
||||||
|
def non_abund_sums(n):
|
||||||
|
abu = find_all_abund(n)
|
||||||
|
sum_nom_abu = 0
|
||||||
|
|
||||||
|
for i in range(n):
|
||||||
|
if not any( (i-a in abu) for a in abu):
|
||||||
|
sum_nom_abu += i
|
||||||
|
|
||||||
|
return sum_nom_abu
|
||||||
|
|
||||||
|
|
||||||
|
def test_():
|
||||||
|
r = set([i for i in range(25)])
|
||||||
|
r_abu = {24}
|
||||||
|
r = r - r_abu
|
||||||
|
assert(non_abund_sums(25) == sum(r))
|
||||||
|
print(non_abund_sums(28123))
|
||||||
|
print('Tests Passed!')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
test_()
|
||||||
|
|
@ -0,0 +1,33 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
def perm_item(elements):
|
||||||
|
if len(elements) <= 1:
|
||||||
|
yield elements
|
||||||
|
else:
|
||||||
|
for (index, elmt) in enumerate(elements):
|
||||||
|
other_elmts = elements[:index]+elements[index+1:]
|
||||||
|
for permutation in perm_item(other_elmts):
|
||||||
|
yield [elmt] + permutation
|
||||||
|
|
||||||
|
|
||||||
|
def lex_perm(l1, n):
|
||||||
|
perm_list = list(perm_item(l1))
|
||||||
|
return sorted(perm_list)[n-1]
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
import time
|
||||||
|
start = time.time()
|
||||||
|
|
||||||
|
l1 = [0,1,2,3,4,5,6,7,8,9]
|
||||||
|
n = 10**6
|
||||||
|
print(lex_perm(l1, n))
|
||||||
|
|
||||||
|
elapsed = (time.time() - start)
|
||||||
|
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,63 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari wahl @2014
|
||||||
|
# marina.w4hl at gmail
|
||||||
|
#
|
||||||
|
|
||||||
|
'''
|
||||||
|
The Fibonacci sequence is defined by the recurrence relation:
|
||||||
|
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
|
||||||
|
Hence the first 12 terms will be:
|
||||||
|
|
||||||
|
F1 = 1
|
||||||
|
F2 = 1
|
||||||
|
F3 = 2
|
||||||
|
F4 = 3
|
||||||
|
F5 = 5
|
||||||
|
F6 = 8
|
||||||
|
F7 = 13
|
||||||
|
F8 = 21
|
||||||
|
F9 = 34
|
||||||
|
F10 = 55
|
||||||
|
F11 = 89
|
||||||
|
F12 = 144
|
||||||
|
The 12th term, F12, is the first term to contain three digits.
|
||||||
|
|
||||||
|
What is the first term in the Fibonacci sequence to contain 1000 digits?
|
||||||
|
Answer: 4782
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def fib(num=1, num_before=1):
|
||||||
|
found = False
|
||||||
|
|
||||||
|
num_before, num = num, num + num_before
|
||||||
|
|
||||||
|
if count_digits(num) == 1000: found = True
|
||||||
|
|
||||||
|
return num, num_before, found
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def count_digits(num):
|
||||||
|
num_str = str(num)
|
||||||
|
return len(num_str)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
found = False
|
||||||
|
num = 1
|
||||||
|
num_before = 1
|
||||||
|
count = 2
|
||||||
|
|
||||||
|
while not found:
|
||||||
|
num, num_before, found = fib(num, num_before)
|
||||||
|
count +=1
|
||||||
|
|
||||||
|
print(count)
|
||||||
|
print('Done!')
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
||||||
|
|
@ -0,0 +1,40 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari wahl @2014
|
||||||
|
# marina.w4hl at gmail
|
||||||
|
|
||||||
|
|
||||||
|
'''
|
||||||
|
A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
|
||||||
|
|
||||||
|
1/2 = 0.5
|
||||||
|
1/3 = 0.(3)
|
||||||
|
1/4 = 0.25
|
||||||
|
1/5 = 0.2
|
||||||
|
1/6 = 0.1(6)
|
||||||
|
1/7 = 0.(142857)
|
||||||
|
1/8 = 0.125
|
||||||
|
1/9 = 0.(1)
|
||||||
|
1/10 = 0.1
|
||||||
|
Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.
|
||||||
|
|
||||||
|
Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.
|
||||||
|
|
||||||
|
Answer: 983
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def recurring_cycle(n, d):
|
||||||
|
for dd in range(1, d):
|
||||||
|
if 1 == 10**dd % d:
|
||||||
|
return dd
|
||||||
|
return 0
|
||||||
|
|
||||||
|
def main():
|
||||||
|
n = 1
|
||||||
|
limit = 1000
|
||||||
|
longest = max(recurring_cycle(n, i) for i in range(2, limit+1))
|
||||||
|
print [i for i in range(2, limit+1) if recurring_cycle(n, i) == longest][0]
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,50 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
def quad_form(n, a, b):
|
||||||
|
return n**2 + a*n + b
|
||||||
|
|
||||||
|
def isPrime(n):
|
||||||
|
n = abs(int(n))
|
||||||
|
if n < 2:
|
||||||
|
return False
|
||||||
|
if n == 2:
|
||||||
|
return True
|
||||||
|
if not n & 1:
|
||||||
|
return False
|
||||||
|
for x in range(3, int(n**0.5)+1, 2):
|
||||||
|
if n % x == 0:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
def quad_primes(a, b):
|
||||||
|
count_max = 0
|
||||||
|
coef = ()
|
||||||
|
for aa in range(-a, a):
|
||||||
|
for bb in range(-b, b):
|
||||||
|
n = 0
|
||||||
|
while True:
|
||||||
|
number = quad_form(n, aa, bb)
|
||||||
|
if isPrime(number):
|
||||||
|
n += 1
|
||||||
|
else:
|
||||||
|
if n > count_max:
|
||||||
|
count_max = n
|
||||||
|
coef = (aa, bb)
|
||||||
|
break
|
||||||
|
return coef(0)*coef(1), coef
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
import time
|
||||||
|
start = time.time()
|
||||||
|
|
||||||
|
print(quad_primes(1000, 1000))
|
||||||
|
|
||||||
|
elapsed = (time.time() - start)
|
||||||
|
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,39 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
def number_spiral(spiral):
|
||||||
|
|
||||||
|
|
||||||
|
return rows, mid
|
||||||
|
|
||||||
|
def make_spiral(n):
|
||||||
|
spiral = []
|
||||||
|
row = rows//2
|
||||||
|
col = col//2
|
||||||
|
count = 1
|
||||||
|
while row < n:
|
||||||
|
while col < n:
|
||||||
|
spiral[col][row] = count
|
||||||
|
count += 1
|
||||||
|
if count%2 == 0:
|
||||||
|
col += 1
|
||||||
|
else:
|
||||||
|
row += 1
|
||||||
|
|
||||||
|
return spiral
|
||||||
|
|
||||||
|
def main():
|
||||||
|
import time
|
||||||
|
start = time.time()
|
||||||
|
|
||||||
|
n = 5
|
||||||
|
spiral = make_spiral(n)
|
||||||
|
print(number_spiral(spiral))# 101
|
||||||
|
|
||||||
|
elapsed = (time.time() - start)
|
||||||
|
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,27 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
def dist_pow(a1, a2, b1, b2):
|
||||||
|
set1 = set()
|
||||||
|
for a in range(a1, a2 + 1):
|
||||||
|
for b in range(b1, b2 + 1):
|
||||||
|
set1.add(a**b)
|
||||||
|
return len(set1)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
import time
|
||||||
|
start = time.time()
|
||||||
|
|
||||||
|
print(dist_pow(2, 5, 2, 5))
|
||||||
|
print(dist_pow(2, 100, 2, 100))
|
||||||
|
|
||||||
|
elapsed = (time.time() - start)
|
||||||
|
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,30 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
def digit_fifth_pow(n):
|
||||||
|
lnum = []
|
||||||
|
for num in range(10**(2), 10**(n+2)):
|
||||||
|
sum_here = 0
|
||||||
|
num_str = str(num)
|
||||||
|
for i in num_str:
|
||||||
|
num_int = int(i)
|
||||||
|
num_int_pow = num_int**n
|
||||||
|
sum_here += num_int_pow
|
||||||
|
if sum_here == num:
|
||||||
|
lnum.append(num)
|
||||||
|
return lnum, sum(lnum)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
import time
|
||||||
|
start = time.time()
|
||||||
|
|
||||||
|
print(digit_fifth_pow(5))
|
||||||
|
|
||||||
|
elapsed = (time.time() - start)
|
||||||
|
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,28 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari wahl @2014
|
||||||
|
# marina.w4hl at gmail
|
||||||
|
'''
|
||||||
|
In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation:
|
||||||
|
|
||||||
|
1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).
|
||||||
|
It is possible to make £2 in the following way:
|
||||||
|
|
||||||
|
1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
|
||||||
|
How many different ways can £2 be made using any number of coins?
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
import time
|
||||||
|
start = time.time()
|
||||||
|
|
||||||
|
print(digit_fifth_pow(5))
|
||||||
|
|
||||||
|
elapsed = (time.time() - start)
|
||||||
|
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,51 @@
|
|||||||
|
#!/usr/bin/python
|
||||||
|
|
||||||
|
|
||||||
|
__author__ = "Mari Wahl"
|
||||||
|
__email__ = "marina.w4hl@gmail.com"
|
||||||
|
|
||||||
|
'''
|
||||||
|
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.
|
||||||
|
The product 7254 is unusual, as the identity, 39 x 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.
|
||||||
|
Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def isPandigitalString(string):
|
||||||
|
""" Check if string contains a pandigital number. """
|
||||||
|
digits = len(string)
|
||||||
|
|
||||||
|
if digits >= 10:
|
||||||
|
return False
|
||||||
|
|
||||||
|
for i in range(1,digits+1):
|
||||||
|
if str(i) not in string:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def gives9PandigitalProduct(a, b):
|
||||||
|
numbers = str(a) + str(b) + str(a*b)
|
||||||
|
if len(numbers) != 9:
|
||||||
|
return False
|
||||||
|
return isPandigitalString(numbers)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
products = []
|
||||||
|
|
||||||
|
for a in range(0, 100000):
|
||||||
|
for b in range(a, 100000):
|
||||||
|
if len(str(a*b) + str(a) + str(b)) > 9:
|
||||||
|
break
|
||||||
|
if gives9PandigitalProduct(a, b):
|
||||||
|
products.append(a*b)
|
||||||
|
print("%i x %i = %i" % (a, b, a*b))
|
||||||
|
|
||||||
|
print(sum(set(products)))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
@ -0,0 +1,91 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
def isPrime(n):
|
||||||
|
n = abs(int(n))
|
||||||
|
if n < 2:
|
||||||
|
return False
|
||||||
|
if n == 2:
|
||||||
|
return True
|
||||||
|
for x in range(2, int(n**0.5)+1):
|
||||||
|
if n%x == 0:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def findPermutations(s):
|
||||||
|
res = []
|
||||||
|
if len(s) == 1:
|
||||||
|
res.append(s)
|
||||||
|
else:
|
||||||
|
for i, c in enumerate(s):
|
||||||
|
for perm in findPermutations(s[:i] + s[i+1:]):
|
||||||
|
res.append(c + perm)
|
||||||
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def isCircular(n):
|
||||||
|
n_str = str(n)
|
||||||
|
permutations = findPermutations(n_str)
|
||||||
|
for perm in permutations:
|
||||||
|
if not isPrime(perm):
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def generatePrimes(n):
|
||||||
|
if n == 2: return [2]
|
||||||
|
elif n < 2: return []
|
||||||
|
s = [i for i in range(3, n+1, 2)]
|
||||||
|
mroot = n ** 0.5
|
||||||
|
half = (n+1)//2 - 1
|
||||||
|
i, m = 0, 3
|
||||||
|
while m <= mroot:
|
||||||
|
if s[i]:
|
||||||
|
j = (m*m-3)//2
|
||||||
|
s[j] = 0
|
||||||
|
while j < half:
|
||||||
|
s[j] = 0
|
||||||
|
j += m
|
||||||
|
i = i+1
|
||||||
|
m = 2*i+3
|
||||||
|
return [2]+[x for x in s if x]
|
||||||
|
|
||||||
|
|
||||||
|
def generate_n_Primes(n):
|
||||||
|
primes = []
|
||||||
|
chkthis = 2
|
||||||
|
while len(primes) < n:
|
||||||
|
ptest = [chkthis for i in primes if chkthis%i == 0]
|
||||||
|
primes += [] if ptest else [chkthis]
|
||||||
|
chkthis += 1
|
||||||
|
return primes
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def circular_primes(n):
|
||||||
|
primes = generatePrimes(n)
|
||||||
|
count = 0
|
||||||
|
for prime in primes:
|
||||||
|
if isCircular(prime):
|
||||||
|
count += 1
|
||||||
|
return count
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
import time
|
||||||
|
start = time.time()
|
||||||
|
|
||||||
|
print(circular_primes(1000000))
|
||||||
|
|
||||||
|
elapsed = (time.time() - start)
|
||||||
|
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,64 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
def isPrime(n):
|
||||||
|
n = abs(int(n))
|
||||||
|
if n < 2:
|
||||||
|
return False
|
||||||
|
if n == 2:
|
||||||
|
return True
|
||||||
|
if not n & 1:
|
||||||
|
return False
|
||||||
|
for x in range(3, int(n**0.5)+1, 2):
|
||||||
|
if n % x == 0:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def generetePrimes(n):
|
||||||
|
if n == 2: return [2]
|
||||||
|
elif n < 2: return []
|
||||||
|
s = [i for i in range(3, n+1,2)]
|
||||||
|
mroot = n ** 0.5
|
||||||
|
half = (n+1)//2-1
|
||||||
|
i = 0
|
||||||
|
m = 3
|
||||||
|
while m <= mroot:
|
||||||
|
if s[i]:
|
||||||
|
j = (m*m - 3)//2
|
||||||
|
s[j] = 0
|
||||||
|
while j < half:
|
||||||
|
s[j] = 0
|
||||||
|
j += m
|
||||||
|
i = i+1
|
||||||
|
m = 2*i+3
|
||||||
|
return [2]+[x for x in s if x]
|
||||||
|
|
||||||
|
|
||||||
|
def gold_other(n):
|
||||||
|
primes_for_n = generetePrimes(n)
|
||||||
|
numbers = {prime + 2*x**2 for prime in primes_for_n for x in range(1, int(n**0.5))}
|
||||||
|
conj = {x for x in range(3, n, 2) if not isPrime(x)}
|
||||||
|
|
||||||
|
while True:
|
||||||
|
candidates = conj - numbers
|
||||||
|
if not candidates:
|
||||||
|
gold_other(2*n)
|
||||||
|
else:
|
||||||
|
return min(candidates)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
import time
|
||||||
|
start = time.time()
|
||||||
|
|
||||||
|
print(gold_other(10000))
|
||||||
|
|
||||||
|
elapsed = (time.time() - start)
|
||||||
|
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,29 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
def self_powers(power, digits):
|
||||||
|
sum_total = 0
|
||||||
|
for pow in range(1, power+1):
|
||||||
|
sum_total += pow**pow
|
||||||
|
sum_total_str = str(sum_total)
|
||||||
|
last_digits = ''
|
||||||
|
for i, c in enumerate(sum_total_str[-digits:]):
|
||||||
|
last_digits += c
|
||||||
|
return int(last_digits)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
import time
|
||||||
|
start = time.time()
|
||||||
|
|
||||||
|
|
||||||
|
assert(self_powers(10, len('10405071317')) == 10405071317)
|
||||||
|
print(self_powers(1000, 10))
|
||||||
|
|
||||||
|
elapsed = (time.time() - start)
|
||||||
|
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,43 @@
|
|||||||
|
#!/usr/bin/python
|
||||||
|
|
||||||
|
__author__ = "Mari Wahl"
|
||||||
|
__email__ = "marina.w4hl@gmail.com"
|
||||||
|
|
||||||
|
'''
|
||||||
|
e = [2; 1,2,1, 1,4,1, 1,6,1 , ... , 1,2k,1, ...].
|
||||||
|
|
||||||
|
The first ten terms in the sequence of convergents for e are:
|
||||||
|
|
||||||
|
2, 3, 8/3, 11/4, 19/7, 87/32, 106/39, 193/71, 1264/465, 1457/536, ...
|
||||||
|
The sum of digits in the numerator of the 10th convergent is 1+4+5+7=17.
|
||||||
|
|
||||||
|
Find the sum of digits in the numerator of the 100th convergent of the continued fraction for e.
|
||||||
|
'''
|
||||||
|
|
||||||
|
from itertools import islice
|
||||||
|
|
||||||
|
def take(iterable, n):
|
||||||
|
#Make an iterator that returns selected elements from the iterable.
|
||||||
|
return list(islice(iterable, n))
|
||||||
|
|
||||||
|
def e():
|
||||||
|
yield 2
|
||||||
|
k = 1
|
||||||
|
while True:
|
||||||
|
yield 1
|
||||||
|
yield 2*k
|
||||||
|
yield 1
|
||||||
|
k += 1
|
||||||
|
|
||||||
|
def rationalize(frac):
|
||||||
|
if len(frac) == 0:
|
||||||
|
return (1, 0)
|
||||||
|
elif len(frac) == 1:
|
||||||
|
return (frac[0], 1)
|
||||||
|
else:
|
||||||
|
remainder = frac[1:len(frac)]
|
||||||
|
(num, denom) = rationalize(remainder)
|
||||||
|
return (frac[0] * num + denom, num)
|
||||||
|
|
||||||
|
numerator = rationalize(take(e(), 100))[0]
|
||||||
|
print sum(int(d) for d in str(numerator))
|
@ -0,0 +1,52 @@
|
|||||||
|
#!/usr/bin/python
|
||||||
|
|
||||||
|
__author__ = "Mari Wahl"
|
||||||
|
__email__ = "marina.w4hl@gmail.com"
|
||||||
|
|
||||||
|
'''
|
||||||
|
The rules for writing Roman numerals allow for many ways of writing each number (see About Roman Numerals...). However, there is always a "best" way of writing a particular number.
|
||||||
|
|
||||||
|
For example, the following represent all of the legitimate ways of writing the number sixteen:
|
||||||
|
|
||||||
|
IIIIIIIIIIIIIIII
|
||||||
|
VIIIIIIIIIII
|
||||||
|
VVIIIIII
|
||||||
|
XIIIIII
|
||||||
|
VVVI
|
||||||
|
XVI
|
||||||
|
|
||||||
|
The last example being considered the most efficient, as it uses the least number of numerals.
|
||||||
|
|
||||||
|
The 11K text file, roman.txt (right click and 'Save Link/Target As...'), contains one thousand numbers written in valid, but not necessarily minimal, Roman numerals; that is, they are arranged in descending units and obey the subtractive pair rule (see About Roman Numerals... for the definitive rules for this problem).
|
||||||
|
|
||||||
|
Find the number of characters saved by writing each of these in their minimal form.
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
def subtractive(roman):
|
||||||
|
result = roman
|
||||||
|
replacements = [
|
||||||
|
("VIIII", "IX"),
|
||||||
|
("IIII", "IV"),
|
||||||
|
("LXXXX", "XC"),
|
||||||
|
("XXXX", "XL"),
|
||||||
|
("DCCCC", "CM"),
|
||||||
|
("CCCC", "CD"),
|
||||||
|
]
|
||||||
|
for old, new in replacements:
|
||||||
|
result = result.replace(old, new)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
|
||||||
|
current = 0
|
||||||
|
improved = 0
|
||||||
|
for line in open(os.path.join(os.path.dirname(__file__), 'roman.txt')):
|
||||||
|
roman = line.strip()
|
||||||
|
current += len(roman)
|
||||||
|
improved += len(subtractive(roman))
|
||||||
|
print current - improved
|
@ -0,0 +1,38 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
# mari von steinkirch @2013
|
||||||
|
# steinkirch at gmail
|
||||||
|
|
||||||
|
def calculate_chain(n):
|
||||||
|
n_str = str(n)
|
||||||
|
while n_str != 1 or n_str != 89:
|
||||||
|
n_str = str(n_str)
|
||||||
|
sum_here = 0
|
||||||
|
for d in n_str:
|
||||||
|
sum_here += int(d)**2
|
||||||
|
n_str = sum_here
|
||||||
|
if n_str == 89:
|
||||||
|
return 1
|
||||||
|
if n_str == 1:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def square_dig_chains(n):
|
||||||
|
count = 0
|
||||||
|
for i in range(1, n+1):
|
||||||
|
count += calculate_chain(i)
|
||||||
|
return count
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
import time
|
||||||
|
start = time.time()
|
||||||
|
|
||||||
|
print(square_dig_chains(10**7))
|
||||||
|
|
||||||
|
elapsed = (time.time() - start)
|
||||||
|
print('Tests Passed!\n It took %s seconds to run them.' % (elapsed))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,21 @@
|
|||||||
|
The MIT License (MIT)
|
||||||
|
|
||||||
|
Copyright (c) 2014 Mari Wahl
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
@ -0,0 +1,23 @@
|
|||||||
|
# 🍟 Project Euler Solutions 🍟
|
||||||
|
|
||||||
|
Several of my solutions for the Euler project. For fun or profit :)
|
||||||
|
|
||||||
|
Most of the exercises are written in Python, but I have some Java and Clojure too.
|
||||||
|
|
||||||
|
Enjoy!
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
----
|
||||||
|
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
When making a reference to my work, please use my [website](http://bt3gl.github.io/index.html).
|
||||||
|
|
||||||
|
<a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by-sa/4.0/88x31.png" /></a><br />
|
||||||
|
|
||||||
|
This work is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](http://creativecommons.org/licenses/by-sa/4.0/).
|
@ -0,0 +1,20 @@
|
|||||||
|
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
|
||||||
|
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
|
||||||
|
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
|
||||||
|
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
|
||||||
|
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
|
||||||
|
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
|
||||||
|
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
|
||||||
|
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
|
||||||
|
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
|
||||||
|
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
|
||||||
|
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
|
||||||
|
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
|
||||||
|
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
|
||||||
|
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
|
||||||
|
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
|
||||||
|
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
|
||||||
|
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
|
||||||
|
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
|
||||||
|
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
|
||||||
|
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
|
@ -0,0 +1,100 @@
|
|||||||
|
37107287533902102798797998220837590246510135740250
|
||||||
|
46376937677490009712648124896970078050417018260538
|
||||||
|
74324986199524741059474233309513058123726617309629
|
||||||
|
91942213363574161572522430563301811072406154908250
|
||||||
|
23067588207539346171171980310421047513778063246676
|
||||||
|
89261670696623633820136378418383684178734361726757
|
||||||
|
28112879812849979408065481931592621691275889832738
|
||||||
|
44274228917432520321923589422876796487670272189318
|
||||||
|
47451445736001306439091167216856844588711603153276
|
||||||
|
70386486105843025439939619828917593665686757934951
|
||||||
|
62176457141856560629502157223196586755079324193331
|
||||||
|
64906352462741904929101432445813822663347944758178
|
||||||
|
92575867718337217661963751590579239728245598838407
|
||||||
|
58203565325359399008402633568948830189458628227828
|
||||||
|
80181199384826282014278194139940567587151170094390
|
||||||
|
35398664372827112653829987240784473053190104293586
|
||||||
|
86515506006295864861532075273371959191420517255829
|
||||||
|
71693888707715466499115593487603532921714970056938
|
||||||
|
54370070576826684624621495650076471787294438377604
|
||||||
|
53282654108756828443191190634694037855217779295145
|
||||||
|
36123272525000296071075082563815656710885258350721
|
||||||
|
45876576172410976447339110607218265236877223636045
|
||||||
|
17423706905851860660448207621209813287860733969412
|
||||||
|
81142660418086830619328460811191061556940512689692
|
||||||
|
51934325451728388641918047049293215058642563049483
|
||||||
|
62467221648435076201727918039944693004732956340691
|
||||||
|
15732444386908125794514089057706229429197107928209
|
||||||
|
55037687525678773091862540744969844508330393682126
|
||||||
|
18336384825330154686196124348767681297534375946515
|
||||||
|
80386287592878490201521685554828717201219257766954
|
||||||
|
78182833757993103614740356856449095527097864797581
|
||||||
|
16726320100436897842553539920931837441497806860984
|
||||||
|
48403098129077791799088218795327364475675590848030
|
||||||
|
87086987551392711854517078544161852424320693150332
|
||||||
|
59959406895756536782107074926966537676326235447210
|
||||||
|
69793950679652694742597709739166693763042633987085
|
||||||
|
41052684708299085211399427365734116182760315001271
|
||||||
|
65378607361501080857009149939512557028198746004375
|
||||||
|
35829035317434717326932123578154982629742552737307
|
||||||
|
94953759765105305946966067683156574377167401875275
|
||||||
|
88902802571733229619176668713819931811048770190271
|
||||||
|
25267680276078003013678680992525463401061632866526
|
||||||
|
36270218540497705585629946580636237993140746255962
|
||||||
|
24074486908231174977792365466257246923322810917141
|
||||||
|
91430288197103288597806669760892938638285025333403
|
||||||
|
34413065578016127815921815005561868836468420090470
|
||||||
|
23053081172816430487623791969842487255036638784583
|
||||||
|
11487696932154902810424020138335124462181441773470
|
||||||
|
63783299490636259666498587618221225225512486764533
|
||||||
|
67720186971698544312419572409913959008952310058822
|
||||||
|
95548255300263520781532296796249481641953868218774
|
||||||
|
76085327132285723110424803456124867697064507995236
|
||||||
|
37774242535411291684276865538926205024910326572967
|
||||||
|
23701913275725675285653248258265463092207058596522
|
||||||
|
29798860272258331913126375147341994889534765745501
|
||||||
|
18495701454879288984856827726077713721403798879715
|
||||||
|
38298203783031473527721580348144513491373226651381
|
||||||
|
34829543829199918180278916522431027392251122869539
|
||||||
|
40957953066405232632538044100059654939159879593635
|
||||||
|
29746152185502371307642255121183693803580388584903
|
||||||
|
41698116222072977186158236678424689157993532961922
|
||||||
|
62467957194401269043877107275048102390895523597457
|
||||||
|
23189706772547915061505504953922979530901129967519
|
||||||
|
86188088225875314529584099251203829009407770775672
|
||||||
|
11306739708304724483816533873502340845647058077308
|
||||||
|
82959174767140363198008187129011875491310547126581
|
||||||
|
97623331044818386269515456334926366572897563400500
|
||||||
|
42846280183517070527831839425882145521227251250327
|
||||||
|
55121603546981200581762165212827652751691296897789
|
||||||
|
32238195734329339946437501907836945765883352399886
|
||||||
|
75506164965184775180738168837861091527357929701337
|
||||||
|
62177842752192623401942399639168044983993173312731
|
||||||
|
32924185707147349566916674687634660915035914677504
|
||||||
|
99518671430235219628894890102423325116913619626622
|
||||||
|
73267460800591547471830798392868535206946944540724
|
||||||
|
76841822524674417161514036427982273348055556214818
|
||||||
|
97142617910342598647204516893989422179826088076852
|
||||||
|
87783646182799346313767754307809363333018982642090
|
||||||
|
10848802521674670883215120185883543223812876952786
|
||||||
|
71329612474782464538636993009049310363619763878039
|
||||||
|
62184073572399794223406235393808339651327408011116
|
||||||
|
66627891981488087797941876876144230030984490851411
|
||||||
|
60661826293682836764744779239180335110989069790714
|
||||||
|
85786944089552990653640447425576083659976645795096
|
||||||
|
66024396409905389607120198219976047599490197230297
|
||||||
|
64913982680032973156037120041377903785566085089252
|
||||||
|
16730939319872750275468906903707539413042652315011
|
||||||
|
94809377245048795150954100921645863754710598436791
|
||||||
|
78639167021187492431995700641917969777599028300699
|
||||||
|
15368713711936614952811305876380278410754449733078
|
||||||
|
40789923115535562561142322423255033685442488917353
|
||||||
|
44889911501440648020369068063960672322193204149535
|
||||||
|
41503128880339536053299340368006977710650566631954
|
||||||
|
81234880673210146739058568557934581403627822703280
|
||||||
|
82616570773948327592232845941706525094512325230608
|
||||||
|
22918802058777319719839450180888072429661980811197
|
||||||
|
77158542502016545090413245809786882778948721859617
|
||||||
|
72107838435069186155435662884062257473692284509516
|
||||||
|
20849603980134001723930671666823555245252804609722
|
||||||
|
53503534226472524250874054075591789781264330331690
|
@ -0,0 +1,15 @@
|
|||||||
|
75
|
||||||
|
95 64
|
||||||
|
17 47 82
|
||||||
|
18 35 87 10
|
||||||
|
20 04 82 47 65
|
||||||
|
19 01 23 75 03 34
|
||||||
|
88 02 77 73 07 63 67
|
||||||
|
99 65 04 28 06 16 70 92
|
||||||
|
41 41 26 56 83 40 80 70 33
|
||||||
|
41 48 72 33 47 32 37 16 94 29
|
||||||
|
53 71 44 65 25 43 91 52 97 51 14
|
||||||
|
70 11 33 28 77 73 17 78 39 68 17 57
|
||||||
|
91 71 52 38 17 14 91 43 58 50 27 29 48
|
||||||
|
63 66 04 68 89 53 67 30 73 16 69 87 40 31
|
||||||
|
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
|
@ -0,0 +1,4 @@
|
|||||||
|
3
|
||||||
|
7 4
|
||||||
|
2 4 6
|
||||||
|
8 5 9 3
|
File diff suppressed because one or more lines are too long
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user