mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-02 06:46:18 -04:00
🏣 Clean up for arxiv
This commit is contained in:
parent
1b969e7db3
commit
41756cb10c
280 changed files with 2 additions and 11 deletions
41
book/ebook_src/real_interview_problems/2n_packets.py
Normal file
41
book/ebook_src/real_interview_problems/2n_packets.py
Normal file
|
@ -0,0 +1,41 @@
|
|||
#!/bin/python
|
||||
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
|
||||
# Complete the 'largestRepackaged' function below.
|
||||
#
|
||||
# The function is expected to return a LONG_INTEGER.
|
||||
# The function accepts INTEGER_ARRAY arrivingPackets as parameter.
|
||||
#
|
||||
|
||||
def largestRepackaged(arrivingPackets):
|
||||
|
||||
packet_size = arrivingPackets[0]
|
||||
packets = arrivingPackets[1:]
|
||||
largest_packet = 0
|
||||
remaining = 0
|
||||
|
||||
for packet in packets:
|
||||
print packet
|
||||
if remaining:
|
||||
packet += remaining
|
||||
remaining = 0
|
||||
|
||||
if packet % 2 != 0:
|
||||
remaining = packet % 2
|
||||
packet -= remaining
|
||||
|
||||
if packet > largest_packet:
|
||||
largest_packet = packet
|
||||
|
||||
return largest_packet
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
arrivingPackets= [5, 1, 2, 4, 7, 5]
|
||||
|
||||
print(largestRepackaged(arrivingPackets))
|
22
book/ebook_src/real_interview_problems/balanced.py
Normal file
22
book/ebook_src/real_interview_problems/balanced.py
Normal file
|
@ -0,0 +1,22 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
def balance_par_str_with_stack(str1):
|
||||
i, stack = 0, []
|
||||
|
||||
while i < len(str1):
|
||||
symbol = str1[i]
|
||||
if symbol == "(":
|
||||
stack.append(symbol)
|
||||
elif symbol == ")":
|
||||
stack.pop()
|
||||
i += 1
|
||||
return not stack
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print(balance_par_str_with_stack('((()))'))
|
||||
print(balance_par_str_with_stack('(()'))
|
50
book/ebook_src/real_interview_problems/binary_search.py
Normal file
50
book/ebook_src/real_interview_problems/binary_search.py
Normal file
|
@ -0,0 +1,50 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
def binary_search(array, value):
|
||||
last, first = len(array), 0
|
||||
|
||||
while first < last:
|
||||
mid = (last - first)//2
|
||||
item = array[mid]
|
||||
|
||||
if item == value:
|
||||
return True
|
||||
|
||||
elif item < value:
|
||||
last = mid
|
||||
|
||||
else:
|
||||
first = mid
|
||||
|
||||
return False
|
||||
|
||||
def binary_search_rec(array, value, first=0, last=None):
|
||||
last = last or len(array)
|
||||
if len(array[first:last]) < 1:
|
||||
return False
|
||||
|
||||
mid = (last - first)//2
|
||||
if array[mid] == value:
|
||||
return True
|
||||
elif array[mid] < value:
|
||||
return binary_search_rec(array, value, first=first, last=mid)
|
||||
else:
|
||||
return binary_search_rec(array, value, first=mid, last=last)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
array = [3, 4, 6, 7, 10, 11, 34, 67, 84]
|
||||
value = 6
|
||||
assert(binary_search(array, value) == True)
|
||||
assert(binary_search_rec(array, value) == True)
|
||||
value = 8
|
||||
assert(binary_search(array, value) == False)
|
||||
assert(binary_search_rec(array, value) == False)
|
||||
array = [8]
|
||||
assert(binary_search(array, value) == True)
|
||||
assert(binary_search_rec(array, value) == True)
|
||||
array = []
|
||||
assert(binary_search(array, value) == False)
|
||||
assert(binary_search_rec(array, value) == False)
|
165
book/ebook_src/real_interview_problems/bst.py
Normal file
165
book/ebook_src/real_interview_problems/bst.py
Normal file
|
@ -0,0 +1,165 @@
|
|||
#!/usr/bin/python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
from collections import deque
|
||||
|
||||
class Node(object):
|
||||
|
||||
def __init__(self, item=None):
|
||||
|
||||
self.item = item
|
||||
self.left = None
|
||||
self.right = None
|
||||
|
||||
|
||||
def _add(self, value):
|
||||
new_node = Node(value)
|
||||
if not self.item:
|
||||
self.item = new_node
|
||||
else:
|
||||
if value > self.item:
|
||||
self.right = self.right and self.right._add(value) or new_node
|
||||
elif value < self.item:
|
||||
self.left = self.left and self.left._add(value) or new_node
|
||||
else:
|
||||
print("BSTs do not support repeated items.")
|
||||
return self
|
||||
|
||||
|
||||
def _search(self, value):
|
||||
if self.item == value:
|
||||
return True
|
||||
elif self.left and value < self.item:
|
||||
return self.left._search(value)
|
||||
elif self.right and value > self.item:
|
||||
return self.right._search(value)
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
def _isLeaf(self):
|
||||
return not self.right and not self.left
|
||||
|
||||
|
||||
def _printPreorder(self):
|
||||
print self.item
|
||||
|
||||
if self.left:
|
||||
self.left._printPreorder()
|
||||
|
||||
if self.right:
|
||||
self.right._printPreorder()
|
||||
|
||||
|
||||
def _preorder_array(self):
|
||||
nodes = []
|
||||
if self.item:
|
||||
nodes.append(self.item)
|
||||
if self.left:
|
||||
nodes.extend(self.left._preorder_array())
|
||||
if self.right:
|
||||
nodes.extend(self.right._preorder_array())
|
||||
return nodes
|
||||
|
||||
|
||||
|
||||
class BST(object):
|
||||
|
||||
def __init__(self):
|
||||
self.root = None
|
||||
|
||||
def add(self, value):
|
||||
if not self.root:
|
||||
self.root = Node(value)
|
||||
else:
|
||||
self.root._add(value)
|
||||
|
||||
def printPreorder(self):
|
||||
if self.root:
|
||||
self.root._printPreorder()
|
||||
|
||||
def search(self, value):
|
||||
if self.root:
|
||||
return self.root._search(value)
|
||||
|
||||
def preorder_array(self):
|
||||
if self.root:
|
||||
return self.root._preorder_array()
|
||||
else:
|
||||
return 'Tree is empty.'
|
||||
|
||||
|
||||
|
||||
|
||||
def BFT(tree):
|
||||
current = tree.root
|
||||
nodes = []
|
||||
queue = deque()
|
||||
queue.append(current)
|
||||
|
||||
while queue:
|
||||
current = queue.popleft()
|
||||
nodes.append(current.item)
|
||||
if current.left:
|
||||
queue.append(current.left)
|
||||
if current.right:
|
||||
queue.append(current.right)
|
||||
|
||||
return nodes
|
||||
|
||||
|
||||
def preorder(tree, nodes=None):
|
||||
nodes = nodes or []
|
||||
if tree:
|
||||
nodes.append(tree.item)
|
||||
if tree.left:
|
||||
preorder(tree.left, nodes)
|
||||
if tree.right:
|
||||
preorder(tree.right, nodes)
|
||||
return nodes
|
||||
|
||||
|
||||
def postorder(tree, nodes=None):
|
||||
nodes = nodes or []
|
||||
if tree:
|
||||
if tree.left:
|
||||
nodes = postorder(tree.left, nodes)
|
||||
if tree.right:
|
||||
nodes = postorder(tree.right, nodes)
|
||||
nodes.append(tree.item)
|
||||
|
||||
return nodes
|
||||
|
||||
|
||||
def inorder(tree, nodes=None):
|
||||
nodes = nodes or []
|
||||
if tree:
|
||||
if tree.left:
|
||||
nodes = inorder(tree.left, nodes)
|
||||
nodes.append(tree.item)
|
||||
if tree.right:
|
||||
nodes = inorder(tree.right, nodes)
|
||||
return nodes
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
bst = BST()
|
||||
l = [10, 5, 6, 3, 8, 2, 1, 11, 9, 4]
|
||||
for i in l:
|
||||
bst.add(i)
|
||||
|
||||
print
|
||||
print "Searching for nodes 16 and 6:"
|
||||
print bst.search(16)
|
||||
print bst.search(6)
|
||||
|
||||
print
|
||||
print 'Traversals:'
|
||||
print 'Original: ', l
|
||||
print 'Preorder: ', preorder(bst.root)
|
||||
print 'Postorder: ', postorder(bst.root)
|
||||
print 'Inorder: ', inorder(bst.root)
|
||||
print 'BSF: ', BFT(bst)
|
38
book/ebook_src/real_interview_problems/check_anagram.py
Normal file
38
book/ebook_src/real_interview_problems/check_anagram.py
Normal file
|
@ -0,0 +1,38 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
from collections import Counter
|
||||
|
||||
def check_if_anagram(word1, word2):
|
||||
counter = Counter()
|
||||
|
||||
for c in word1:
|
||||
counter[c] += 1
|
||||
|
||||
for c in word2:
|
||||
counter[c] -= 1
|
||||
|
||||
for values in counter.values():
|
||||
if values != 0:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
word1 = 'abc'
|
||||
word2 = 'bca'
|
||||
assert(check_if_anagram(word1, word2) == True)
|
||||
|
||||
word2 = 'bcd'
|
||||
assert(check_if_anagram(word1, word2) == False)
|
||||
|
||||
word1 = ''
|
||||
word2 = ''
|
||||
assert(check_if_anagram(word1, word2) == True)
|
||||
|
||||
word1 = 'a'
|
||||
word2 = 'a'
|
||||
assert(check_if_anagram(word1, word2) == True)
|
32
book/ebook_src/real_interview_problems/combination.py
Normal file
32
book/ebook_src/real_interview_problems/combination.py
Normal file
|
@ -0,0 +1,32 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
def combination(array):
|
||||
if len(array) < 2:
|
||||
return set(array)
|
||||
|
||||
result = set()
|
||||
for index, item in enumerate(array):
|
||||
new_array = array[:index] + array[index+1:]
|
||||
result.add(item)
|
||||
for perm in combination(new_array):
|
||||
new_item = ''.join(sorted(item + perm))
|
||||
result.add(new_item)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
array = ['a', 'b', 'c']
|
||||
result = set(['a', 'ac', 'ab', 'abc', 'bc', 'c', 'b'])
|
||||
assert(combination(array) == result)
|
||||
|
||||
array = ['']
|
||||
result = set([''])
|
||||
assert(combination(array) == result)
|
||||
|
||||
array = ['a']
|
||||
result = set(['a'])
|
||||
assert(combination(array) == result)
|
45
book/ebook_src/real_interview_problems/hash_table.py
Normal file
45
book/ebook_src/real_interview_problems/hash_table.py
Normal file
|
@ -0,0 +1,45 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
class HashTable(object):
|
||||
def __init__(self, slots=10):
|
||||
self.slots = slots
|
||||
self.table = []
|
||||
self.create_table()
|
||||
|
||||
# Get the slot
|
||||
def hash_key(self, value):
|
||||
return hash(value)%self.slots
|
||||
|
||||
# When creating the table, add list struct
|
||||
# to each slot
|
||||
def create_table(self):
|
||||
for i in range(self.slots):
|
||||
self.table.append([])
|
||||
|
||||
# Method to add a item in the right slot
|
||||
def add_item(self, value):
|
||||
key = self.hash_key(value)
|
||||
self.table[key].append(value)
|
||||
|
||||
# Aux: print table
|
||||
def print_table(self):
|
||||
for key in range(self.slots):
|
||||
print "Key is {0}, value is {1}.".format(key, self.table[key])
|
||||
|
||||
# Aux: find item
|
||||
def find_item(self, item):
|
||||
item_hash = self.hash_key(item)
|
||||
return item in self.table[item_hash]
|
||||
|
||||
|
||||
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)
|
60
book/ebook_src/real_interview_problems/linked_list.py
Normal file
60
book/ebook_src/real_interview_problems/linked_list.py
Normal file
|
@ -0,0 +1,60 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
class Node(object):
|
||||
def __init__(self, value, next=None):
|
||||
self.value = value
|
||||
self.next = next
|
||||
|
||||
|
||||
class LinkedList(object):
|
||||
def __init__(self):
|
||||
self.head = None
|
||||
|
||||
def _add(self, value):
|
||||
self.head = Node(value, self.head)
|
||||
|
||||
def _printList(self):
|
||||
node = self.head
|
||||
while node:
|
||||
print node.value
|
||||
node = node.next
|
||||
|
||||
def _find(self, index):
|
||||
prev = None
|
||||
node = self.head
|
||||
i = 0
|
||||
while node and i < index:
|
||||
prev = node
|
||||
node = node.next
|
||||
i += 1
|
||||
return node, prev, i
|
||||
|
||||
def _delete(self, prev, node):
|
||||
if not prev:
|
||||
self.head = node.next
|
||||
else:
|
||||
prev.next = node.next
|
||||
|
||||
def deleteNode(self, index):
|
||||
node, prev, i = self._find(index)
|
||||
if index == i:
|
||||
self._delete(prev, node)
|
||||
else:
|
||||
print('Node with index {} not found'.format(index))
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
ll = LinkedList()
|
||||
for i in range(1, 5):
|
||||
ll._add(i)
|
||||
|
||||
print('The list is:')
|
||||
ll._printList()
|
||||
|
||||
print('The list after deleting node with index 2:')
|
||||
ll.deleteNode(2)
|
||||
ll._printList()
|
|
@ -0,0 +1,32 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
def longest_common_substring(s1, s2):
|
||||
p1 = 0
|
||||
aux, lcp = '', ''
|
||||
string1 = max(s1, s2)
|
||||
string2 = min(s1, s2)
|
||||
|
||||
while p1 < len(string1):
|
||||
p2 = 0
|
||||
while p2 < len(string2) and p1+p2 < len(string1):
|
||||
if string1[p1+p2] == string2[p2]:
|
||||
aux += string1[p1+p2]
|
||||
else:
|
||||
if len(lcp) < len(aux):
|
||||
lcp = aux
|
||||
aux = ''
|
||||
p2 += 1
|
||||
p1 += 1
|
||||
|
||||
return lcp
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
str1 = 'hasfgeaae'
|
||||
str2 = 'bafgekk'
|
||||
result = 'fge'
|
||||
assert(longest_common_substring(str1, str2) == result)
|
|
@ -0,0 +1,31 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
def longest_increasing_subsequence(seq):
|
||||
result, aux = [], []
|
||||
seq.append(-float('infinity'))
|
||||
|
||||
for i, value in enumerate(seq[:-1]):
|
||||
aux.append(value)
|
||||
if value > seq[i+1]:
|
||||
if len(result) < len(aux):
|
||||
result = aux[:]
|
||||
aux = []
|
||||
return result
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
seq = [10, -12, 2, 3, -3, 5, -1, 2, -10]
|
||||
result = [-12, 2, 3]
|
||||
assert(longest_increasing_subsequence(seq) == result)
|
||||
|
||||
seq = [2]
|
||||
result = [2]
|
||||
assert(longest_increasing_subsequence(seq) == result)
|
||||
|
||||
seq = []
|
||||
result = []
|
||||
assert(longest_increasing_subsequence(seq) == result)
|
47
book/ebook_src/real_interview_problems/merge_sort.py
Normal file
47
book/ebook_src/real_interview_problems/merge_sort.py
Normal file
|
@ -0,0 +1,47 @@
|
|||
#!/usr/bin/env python
|
||||
# AKA: do you believe in magic?
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
def merge_sort(array):
|
||||
if len(array) < 2:
|
||||
return array
|
||||
|
||||
# divide
|
||||
mid = len(array)//2
|
||||
left = merge_sort(array[:mid])
|
||||
right = merge_sort(array[mid:])
|
||||
|
||||
# merge
|
||||
result = []
|
||||
i, j = 0, 0
|
||||
|
||||
while i < len(left) and j < len(right):
|
||||
if left[i] < right[j]:
|
||||
result.append(left[i])
|
||||
i += 1
|
||||
else:
|
||||
result.append(right[j])
|
||||
j+= 1
|
||||
|
||||
# make sure nothing is left behind
|
||||
if left[i:]:
|
||||
result.extend(left[i:])
|
||||
if right[j:]:
|
||||
result.extend(right[j:])
|
||||
|
||||
return result
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
array = [3, 1, 6, 0, 7, 19, 7, 2, 22]
|
||||
sorted = [0, 1, 2, 3, 6, 7, 7, 19, 22]
|
||||
assert(merge_sort(array) == sorted)
|
||||
|
||||
array = []
|
||||
assert(merge_sort(array) == array)
|
||||
|
||||
array = [1]
|
||||
assert(merge_sort(array) == array)
|
281
book/ebook_src/real_interview_problems/other_resources/PYTHON.md
Normal file
281
book/ebook_src/real_interview_problems/other_resources/PYTHON.md
Normal file
|
@ -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
book/ebook_src/real_interview_problems/other_resources/Project-Euler/.gitignore
vendored
Normal file
44
book/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
File diff suppressed because it is too large
Load diff
54
book/ebook_src/real_interview_problems/other_resources/Top-Coder/.gitignore
vendored
Normal file
54
book/ebook_src/real_interview_problems/other_resources/Top-Coder/.gitignore
vendored
Normal file
|
@ -0,0 +1,54 @@
|
|||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
env/
|
||||
bin/
|
||||
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
|
||||
|
||||
# Mr Developer
|
||||
.mr.developer.cfg
|
||||
.project
|
||||
.pydevproject
|
||||
|
||||
# Rope
|
||||
.ropeproject
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
*.pot
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
|
@ -0,0 +1,70 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
|
||||
|
||||
def findToneDiff(tones):
|
||||
tonesDiff = []
|
||||
n = len(tones)
|
||||
for i, tone in enumerate(tones):
|
||||
for j in range(i+1, len(tones)):
|
||||
sum_here = abs(tone - tones[j])
|
||||
tonesDiff.append([sum_here, i, j])
|
||||
return sorted(tonesDiff)
|
||||
|
||||
def findAllPossible(duration, tones, T):
|
||||
tonesDiff = findToneDiff(tones)
|
||||
sumsTone1 = [(song, i) for i, song in enumerate(duration) if song <= T]
|
||||
sumsTone2 = []
|
||||
for song in tonesDiff:
|
||||
sum_here = song[0] + duration[song[1]] + duration[song[2]]
|
||||
if sum_here <= T:
|
||||
sumsTone2.append((sum_here, song[1], song[2], 2))
|
||||
return sumsTone1, sumsTone2
|
||||
|
||||
|
||||
def findAllPossibleNext(sumsTone, T, n_music):
|
||||
sumsTone2 = []
|
||||
for i, song1 in enumerate(sumsTone):
|
||||
index1 = song1[1]
|
||||
for j in range(i+1, len(sumsTone)):
|
||||
song2 = sumsTone[j]
|
||||
index2 = song2[1]
|
||||
if index1 == index2:
|
||||
sum_here = song1[0] + song2[0]
|
||||
if sum_here < T:
|
||||
sumsTone2.append((sum_here, song2[1], song2[2], n_music))
|
||||
|
||||
|
||||
return sumsTone2
|
||||
|
||||
|
||||
def maxSongs(duration, tones, T):
|
||||
|
||||
if min(duration) >= T:
|
||||
return 0
|
||||
|
||||
sumsTone1, sumsTone = findAllPossible(duration, tones, T)
|
||||
if not sumsTone:
|
||||
return 1
|
||||
|
||||
while sumsTone:
|
||||
n_music = sumsTone[0][3]+1
|
||||
sumsTone = findAllPossibleNext(sumsTone, T, n_music)
|
||||
if not sumsTone:
|
||||
return n_music
|
||||
|
||||
|
||||
|
||||
def tests_250():
|
||||
print(maxSongs([3, 5, 4, 11], [2, 1, 3, 1], 17)) #3
|
||||
print(maxSongs([9, 11, 13, 17], [2, 1, 3, 4], 20)) #1
|
||||
print(maxSongs([100, 200, 300], [1,2,3], 99)) #0
|
||||
print(maxSongs([87,21,20,73,97,57,12,80,86,97,98,85,41,12,89,15,41,17,68,37,21,1,9,65,4,67,38,91,46,82,7,98,21,70,99,41,21,65,11,1,8,12,77,62,52,69,56,33,98,97], [88,27,89,2,96,32,4,93,89,50,58,70,15,48,31,2,27,20,31,3,23,86,69,12,59,61,85,67,77,34,29,3,75,42,50,37,56,45,51,68,89,17,4,47,9,14,29,59,43,3], 212))
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
tests_250()
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
### 🍬 [Top Coder](Solutions) for Fun or Profit
|
||||
|
||||
|
||||
----
|
||||
|
||||
|
||||
## 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/).
|
30
book/ebook_src/real_interview_problems/other_resources/eudyptula-challenge-solutions/.gitignore
vendored
Normal file
30
book/ebook_src/real_interview_problems/other_resources/eudyptula-challenge-solutions/.gitignore
vendored
Normal file
|
@ -0,0 +1,30 @@
|
|||
# Compiled Object files
|
||||
*.slo
|
||||
*.lo
|
||||
*.o
|
||||
*.ko
|
||||
*.obj
|
||||
|
||||
# Precompiled Headers
|
||||
*.gch
|
||||
*.pch
|
||||
|
||||
# Compiled Dynamic libraries
|
||||
*.so
|
||||
*.dylib
|
||||
*.dll
|
||||
|
||||
# Fortran module files
|
||||
*.mod
|
||||
*.smod
|
||||
|
||||
# Compiled Static libraries
|
||||
*.lai
|
||||
*.la
|
||||
*.a
|
||||
*.lib
|
||||
|
||||
# Executables
|
||||
*.exe
|
||||
*.out
|
||||
*.app
|
|
@ -0,0 +1,674 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
{one line to give the program's name and a brief idea of what it does.}
|
||||
Copyright (C) {year} {name of author}
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
{project} Copyright (C) {year} {fullname}
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
BIN
book/ebook_src/real_interview_problems/other_resources/eudyptula-challenge-solutions/bt3/.DS_Store
vendored
Normal file
BIN
book/ebook_src/real_interview_problems/other_resources/eudyptula-challenge-solutions/bt3/.DS_Store
vendored
Normal file
Binary file not shown.
|
@ -0,0 +1,9 @@
|
|||
obj-m += eudyptula_1.o
|
||||
KERNEL_VER ?= $(shell uname -r)
|
||||
KERNEL_PATH ?= /lib/modules/$(KERNEL_VER)/build
|
||||
|
||||
all:
|
||||
make -C $(KERNEL_PATH) M=$(PWD) modules
|
||||
|
||||
clean:
|
||||
make -C $(KERNEL_PATH) M=$(PWD) clean
|
|
@ -0,0 +1,22 @@
|
|||
/*
|
||||
* Eudyptula #1
|
||||
*/
|
||||
|
||||
#include <linux/module.h>
|
||||
#include <linux/kernel.h>
|
||||
#include <linux/init.h>
|
||||
|
||||
int init_module(void)
|
||||
{
|
||||
printk(KERN_DEBUG "Ola Mundo!\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
void cleanup_module(void)
|
||||
{
|
||||
printk(KERN_DEBUG "Unloading exer 1! Goodbye!!!\n");
|
||||
}
|
||||
|
||||
|
||||
MODULE_LICENSE("GLP");
|
||||
MODULE_AUTHOR("7e1cf379bd3d");
|
|
@ -0,0 +1,5 @@
|
|||
make
|
||||
sudo insmod ./eudyptula_1.ko
|
||||
cat /proc/modules | grep eudyptula
|
||||
lsmod | grep eudyptula
|
||||
sudo rmmod eudyptula_1
|
Binary file not shown.
After Width: | Height: | Size: 15 KiB |
File diff suppressed because it is too large
Load diff
|
@ -0,0 +1,42 @@
|
|||
1. Clone Linus’ repo and read Installing the kernel source:
|
||||
```
|
||||
$ git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
|
||||
```
|
||||
|
||||
2. Generate .config and add CONFIG_LOCALVERSION_AUTO=y
|
||||
```
|
||||
$ make localmodconfig
|
||||
```
|
||||
|
||||
3. Get an openssl header error, install lots of dev libraries
|
||||
```
|
||||
$ sudo apt-get install python-pip python-dev libffi-dev libssl-dev libxml2-dev libxslt1-dev libjpeg8-dev zlib1g-dev
|
||||
```
|
||||
|
||||
4. Make! (It takes ~ 30 min)
|
||||
```
|
||||
$ make
|
||||
```
|
||||
|
||||
5. Make module, install, add to grub
|
||||
```
|
||||
$ make modules
|
||||
$ sudo make modules_install
|
||||
$ sudo make install
|
||||
$ update-grub
|
||||
```
|
||||
|
||||
6. Reboot machine. For ubuntu: press shift to get grub menu
|
||||
|
||||
Profit!
|
||||
|
||||
Some tips:
|
||||
* List of kernel addresses sorted in ascending order, from which it is simple to find the function that contains the offending address:
|
||||
```
|
||||
$ nm vmlinux | sort | less
|
||||
```
|
||||
|
||||
Send
|
||||
```
|
||||
make && make modules && make modules_install && make install
|
||||
```
|
|
@ -0,0 +1,34 @@
|
|||
This is Task 02 of the Eudyptula Challenge
|
||||
------------------------------------------
|
||||
|
||||
Now that you have written your first kernel module, it's time to take
|
||||
off the training wheels and move on to building a custom kernel. No
|
||||
more distro kernels for you. For this task you must run your own
|
||||
kernel. And use git! Exciting, isn't it? No? Oh, ok...
|
||||
|
||||
The tasks for this round are:
|
||||
- Download Linus's latest git tree from git.kernel.org (you have to
|
||||
figure out which one is his. It's not that hard, just remember what
|
||||
his last name is and you should be fine.)
|
||||
- Build it, install it, and boot it. You can use whatever kernel
|
||||
configuration options you wish to use, but you must enable
|
||||
CONFIG_LOCALVERSION_AUTO=y.
|
||||
- Show proof of booting this kernel. Bonus points if you do it on a
|
||||
"real" machine, and not a virtual machine (virtual machines are
|
||||
acceptable, but come on, real kernel developers don't mess around
|
||||
with virtual machines, they are too slow. Oh yeah, we aren't real
|
||||
kernel developers just yet. Well, I'm not anyway, I'm just a
|
||||
script...) Again, proof of running this kernel is up to you, I'm
|
||||
sure you can do well.
|
||||
|
||||
Hint, you should look into the 'make localmodconfig' option, and base
|
||||
your kernel configuration on a working distro kernel configuration.
|
||||
Don't sit there and answer all 1625 different kernel configuration
|
||||
options by hand, even I, a foolish script, know better than to do that!
|
||||
|
||||
After doing this, don't throw away that kernel, git tree, and
|
||||
configuration file. You'll be using it for later tasks. A working
|
||||
kernel configuration file is a precious thing, all kernel developers
|
||||
have one they have grown and tended to over the years. This is the
|
||||
start of a long journey with yours. Don't discard it like was a broken
|
||||
umbrella, it deserves better than that.
|
|
@ -0,0 +1,8 @@
|
|||
KERNEL_SRC ?= /lib/modules/$(shell uname -r)/build
|
||||
obj-m += task-01.o
|
||||
|
||||
all:
|
||||
make -C $(KERNEL_SRC) M=$(PWD) modules
|
||||
|
||||
clean:
|
||||
make -C $(KERNEL_SRC) M=$(PWD) clean
|
|
@ -0,0 +1,15 @@
|
|||
#include <linux/module.h>
|
||||
#include <linux/kernel.h>
|
||||
#include <linux/init.h>
|
||||
|
||||
static int __init setup(void) {
|
||||
printk(KERN_DEBUG "Hello World!");
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void __exit teardown(void) {
|
||||
}
|
||||
|
||||
module_init(setup);
|
||||
module_exit(teardown);
|
File diff suppressed because it is too large
Load diff
|
@ -0,0 +1,6 @@
|
|||
Steps
|
||||
=====
|
||||
|
||||
- `make`
|
||||
- `make modules_install`
|
||||
- `make install`
|
File diff suppressed because it is too large
Load diff
|
@ -0,0 +1,4 @@
|
|||
Steps
|
||||
=====
|
||||
|
||||
- `git format-patch -o /tmp/ HEAD~`
|
|
@ -0,0 +1 @@
|
|||
mutt -s [7e1cf379bd3d] Task 01 of the Eudyptula Challenge little@eudyptula-challenge.org -a ~/Projects/eudyptula-challenge/task_01/eudyptula_1.c
|
|
@ -0,0 +1,35 @@
|
|||
#!/usr/bin/python
|
||||
|
||||
''' 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'
|
|
@ -0,0 +1,37 @@
|
|||
#!/usr/bin/python
|
||||
|
||||
''' 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
|
|
@ -0,0 +1,20 @@
|
|||
#!/usr/bin/python
|
||||
''' 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'
|
|
@ -0,0 +1,19 @@
|
|||
#!/usr/bin/python
|
||||
|
||||
''' 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'
|
|
@ -0,0 +1,37 @@
|
|||
#!/bin/python
|
||||
|
||||
"""
|
||||
Each round, players receive a score between 0 and 100, which you use to rank them from highest to lowest. So far you're using an algorithm that sorts in O(n\lg{n})O(nlgn) time, but players are complaining that their rankings aren't updated fast enough. You need a faster sorting algorithm.
|
||||
|
||||
Write a function that takes:
|
||||
|
||||
a list of unsorted_scores
|
||||
the highest_possible_score in the game
|
||||
and returns a sorted list of scores in less than O(n\lg{n})O(nlgn) time.
|
||||
"""
|
||||
|
||||
def sort_scores(unsorted_scores, highest_score):
|
||||
|
||||
score_counts = [0] * (highest_score+1)
|
||||
|
||||
for score in unsorted_scores:
|
||||
score_counts[score] += 1
|
||||
|
||||
sorted_scores = []
|
||||
|
||||
for score in range(len(score_counts)-1, -1, -1):
|
||||
count = score_counts[score]
|
||||
|
||||
for i in range(count):
|
||||
sorted_scores.append(score)
|
||||
|
||||
return sorted_scores
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
unsorted_scores = [37, 89, 41, 65, 91, 53]
|
||||
HIGHEST_POSSIBLE_SCORE = 100
|
||||
|
||||
print sort_scores(unsorted_scores, HIGHEST_POSSIBLE_SCORE)
|
|
@ -0,0 +1,76 @@
|
|||
#!/bin/python
|
||||
|
||||
"""
|
||||
Write a function that returns a list of all the duplicate files.
|
||||
|
||||
the first item is the duplicate file
|
||||
the second item is the original file
|
||||
For example:
|
||||
|
||||
[('/tmp/parker_is_dumb.mpg', '/home/parker/secret_puppy_dance.mpg'),
|
||||
('/home/trololol.mov', '/etc/apache2/httpd.conf')]
|
||||
You can assume each file was only duplicated once.
|
||||
"""
|
||||
|
||||
import os
|
||||
import hashlib
|
||||
|
||||
def find_duplicate_files(starting_directory):
|
||||
files_seen_already = {}
|
||||
stack = [starting_directory]
|
||||
|
||||
duplicates = []
|
||||
|
||||
while len(stack):
|
||||
current_path = stack.pop()
|
||||
|
||||
if os.path.isdir(current_path):
|
||||
for path in os.listdir(current_path):
|
||||
full_path = os.path.join(current_path, path)
|
||||
stack.append(full_path)
|
||||
|
||||
else:
|
||||
file_hash = sample_hash_file(current_path)
|
||||
|
||||
current_last_edited_time = os.path.getmtime(current_path)
|
||||
|
||||
if file_hash in files_seen_already:
|
||||
existing_last_edited_time, existing_path = files_seen_already[file_hash]
|
||||
if current_last_edited_time > existing_last_edited_time:
|
||||
|
||||
duplicates.append((current_path, existing_path))
|
||||
else:
|
||||
|
||||
duplicates.append((existing_path, current_path))
|
||||
files_seen_already[file_hash] = (current_last_edited_time, current_path)
|
||||
|
||||
else:
|
||||
files_seen_already[file_hash] = (current_last_edited_time, current_path)
|
||||
|
||||
return duplicates
|
||||
|
||||
|
||||
def sample_hash_file(path):
|
||||
num_bytes_to_read_per_sample = 4000
|
||||
total_bytes = os.path.getsize(path)
|
||||
hasher = hashlib.sha512()
|
||||
|
||||
with open(path, 'rb') as file:
|
||||
|
||||
if total_bytes < num_bytes_to_read_per_sample * 3:
|
||||
hasher.update(file.read())
|
||||
else:
|
||||
num_bytes_between_samples = (
|
||||
(total_bytes - num_bytes_to_read_per_sample * 3) / 2
|
||||
)
|
||||
|
||||
for offset_multiplier in range(3):
|
||||
start_of_sample = (
|
||||
offset_multiplier
|
||||
* (num_bytes_to_read_per_sample + num_bytes_between_samples)
|
||||
)
|
||||
file.seek(start_of_sample)
|
||||
sample = file.read(num_bytes_to_read_per_sample)
|
||||
hasher.update(sample)
|
||||
|
||||
return hasher.hexdigest()
|
|
@ -0,0 +1,42 @@
|
|||
#!/bin/python
|
||||
|
||||
"""
|
||||
Users on longer flights like to start a second movie right when their first one ends,
|
||||
but they complain that the plane usually lands before they can see the ending.
|
||||
So you're building a feature for choosing two movies whose total runtimes will equal the exact flight length.
|
||||
|
||||
Write a function that takes an integer flight_length (in minutes) and a
|
||||
list of integers movie_lengths (in minutes) and returns a boolean indicating
|
||||
whether there are two numbers in movie_lengths whose sum equals flight_length.
|
||||
|
||||
When building your function:
|
||||
|
||||
Assume your users will watch exactly two movies
|
||||
Don't make your users watch the same movie twice
|
||||
Optimize for runtime over memory
|
||||
"""
|
||||
|
||||
def is_there_two_movies(flight_length, movie_lengths):
|
||||
movie_lengths_seen = set()
|
||||
|
||||
for first_movie_length in movie_lengths:
|
||||
matching_second_movie_length = flight_length - first_movie_length
|
||||
if matching_second_movie_length in movie_lengths_seen:
|
||||
return True
|
||||
movie_lengths_seen.add(first_movie_length)
|
||||
|
||||
return False
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
flight_length = 10
|
||||
|
||||
movie_lengths = [2, 4, 7]
|
||||
print(is_there_two_movies(flight_length, movie_lengths))
|
||||
print("Should be True")
|
||||
|
||||
movie_lengths = [5, 6, 7, 8]
|
||||
print(is_there_two_movies(flight_length, movie_lengths))
|
||||
print("Should be False")
|
|
@ -0,0 +1,27 @@
|
|||
#!/bin/python
|
||||
|
||||
"""
|
||||
Grab Apple's stock prices and put them in a list called stock_prices, where:
|
||||
|
||||
The indices are the time (in minutes) past trade opening time, which was 9:30am local time.
|
||||
The values are the price (in US dollars) of one share of Apple stock at that time.
|
||||
So if the stock cost $500 at 10:30am, that means stock_prices[60] = 500.
|
||||
|
||||
Write an efficient function that takes stock_prices and returns the best profit I could have made from one purchase and one sale of one share.
|
||||
"""
|
||||
|
||||
def apple_stock_profit(stock_prices):
|
||||
|
||||
min_s, max_s = max(stock_prices), 0
|
||||
|
||||
while stock_prices:
|
||||
stock = stock_prices.pop()
|
||||
min_s = min(min_s, stock)
|
||||
max_s = max(max_s, stock)
|
||||
|
||||
return max_s - min_s
|
||||
|
||||
|
||||
stock_prices = [10, 7, 5, 8, 11, 9]
|
||||
print apple_stock_profit(stock_prices)
|
||||
print("Should return 6 (buying for $5 and selling for $11)")
|
|
@ -0,0 +1,36 @@
|
|||
#!/bin/python
|
||||
|
||||
"""
|
||||
Write a function fib() that takes an integer nn and returns the nnth Fibonacci number.
|
||||
"""
|
||||
|
||||
# this is O(2^n)
|
||||
def fib(n):
|
||||
if n in [1, 0]:
|
||||
return n
|
||||
return fib(n - 1) + fib(n - 2)
|
||||
|
||||
|
||||
print fib(10)
|
||||
|
||||
|
||||
# this is O(n)
|
||||
def fib(n):
|
||||
if n < 0:
|
||||
raise ValueError('Index was negative. No such thing as a '
|
||||
'negative index in a series.')
|
||||
elif n in [0, 1]:
|
||||
return n
|
||||
|
||||
prev_prev = 0 # 0th fibonacci
|
||||
prev = 1 # 1st fibonacci
|
||||
|
||||
for _ in range(n - 1):
|
||||
current = prev + prev_prev
|
||||
prev_prev = prev
|
||||
prev = current
|
||||
|
||||
return current
|
||||
|
||||
|
||||
print fib(10)
|
|
@ -0,0 +1,38 @@
|
|||
#!/bin/python
|
||||
|
||||
"""
|
||||
Find a duplicate
|
||||
We have a list of integers, where:
|
||||
The integers are in the range 1..n1..n
|
||||
The list has a length of n+1n+1
|
||||
It follows that our list has at least one integer which appears at least twice. But it may have several duplicates, and each duplicate may appear more than twice.
|
||||
|
||||
Write a function which finds an integer that appears more than once in our list. (If there are multiple duplicates, you only need to find one of them.)
|
||||
"""
|
||||
|
||||
def find_dups(num_list):
|
||||
num_dict = {}
|
||||
for n in num_list:
|
||||
if n in num_dict.keys():
|
||||
num_dict[n] += 1
|
||||
else:
|
||||
num_dict[n] = 1
|
||||
|
||||
for k,v in num_dict.items():
|
||||
if v > 1:
|
||||
print "dup is {}".format(k)
|
||||
|
||||
def find_dups_set(num_list):
|
||||
|
||||
num_set = set()
|
||||
|
||||
for n in num_list:
|
||||
if n in num_set:
|
||||
print n
|
||||
else:
|
||||
num_set.add(n)
|
||||
|
||||
|
||||
num_list = [6,1,3,7,6,4,5,2,8,5,6,6,7]
|
||||
find_dups(num_list)
|
||||
find_dups_set(num_list)
|
|
@ -0,0 +1,26 @@
|
|||
#!/usr/bin/python
|
||||
|
||||
''' 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):
|
||||
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__':
|
||||
print get_float_rep(0.72) #('Error 2', '.1011100001010001111010111000010')
|
||||
print get_float_rep(0.1) # ('Error 2', '.0001100110011001100110011001100')
|
||||
print get_float_rep(0.5) #'.1'
|
|
@ -0,0 +1,54 @@
|
|||
#!/bin/python
|
||||
|
||||
"""
|
||||
Given a list of integers, find the highest product you can get from three of the integers.
|
||||
|
||||
The input list_of_ints will always have at least three integers.
|
||||
"""
|
||||
|
||||
def highest_num(list_of_ints):
|
||||
|
||||
if len(list_of_ints) == 3:
|
||||
return list_of_ints[0]*list_of_ints[1]*list_of_ints[2]
|
||||
|
||||
sorted_list = sorted(list_of_ints)
|
||||
|
||||
return sorted_list[-3]*sorted_list[-2]*sorted_list[-1]
|
||||
|
||||
|
||||
def highest_product_of_3_On(list_of_ints):
|
||||
|
||||
highest = max(list_of_ints[0], list_of_ints[1])
|
||||
lowest = min(list_of_ints[0], list_of_ints[1])
|
||||
highest_product_of_2 = list_of_ints[0] * list_of_ints[1]
|
||||
lowest_product_of_2 = list_of_ints[0] * list_of_ints[1]
|
||||
|
||||
highest_product_of_3 = list_of_ints[0] * list_of_ints[1] * list_of_ints[2]
|
||||
|
||||
for i in range(2, len(list_of_ints)):
|
||||
current = list_of_ints[i]
|
||||
|
||||
highest_product_of_3 = max(highest_product_of_3,
|
||||
current * highest_product_of_2,
|
||||
current * lowest_product_of_2)
|
||||
|
||||
highest_product_of_2 = max(highest_product_of_2,
|
||||
current * highest,
|
||||
current * lowest)
|
||||
|
||||
lowest_product_of_2 = min(lowest_product_of_2,
|
||||
current * highest,
|
||||
current * lowest)
|
||||
|
||||
highest = max(highest, current)
|
||||
|
||||
lowest = min(lowest, current)
|
||||
|
||||
return highest_product_of_3
|
||||
|
||||
list_of_ints = [4, 2, 5, 6]
|
||||
print highest_num(list_of_ints)
|
||||
print "Should be 120"
|
||||
|
||||
print highest_product_of_3_On(list_of_ints)
|
||||
print "Should be 120"
|
|
@ -0,0 +1,33 @@
|
|||
#!/bin/python
|
||||
|
||||
"""
|
||||
Write a function for doing an in-place shuffle of a list.
|
||||
|
||||
The shuffle must be "uniform," meaning each item in the original list must have the same probability of ending up in each spot in the final list.
|
||||
|
||||
Assume that you have a function get_random(floor, ceiling) for getting a random integer that is >= floor and <= ceiling.
|
||||
"""
|
||||
|
||||
import random
|
||||
|
||||
def get_random(floor, ceiling):
|
||||
return random.randrange(floor, ceiling + 1)
|
||||
|
||||
def shuffle(the_list):
|
||||
|
||||
if len(the_list) <= 1:
|
||||
return the_list
|
||||
|
||||
last_index_in_the_list = len(the_list) - 1
|
||||
|
||||
for i in range(len(the_list) - 1):
|
||||
random_choice_index = get_random(i,
|
||||
last_index_in_the_list)
|
||||
if random_choice_index != i:
|
||||
the_list[i], the_list[random_choice_index] = \
|
||||
the_list[random_choice_index], the_list[i]
|
||||
|
||||
|
||||
seed_list = [5, 2, 6, 2, 6]
|
||||
shuffle(seed_list)
|
||||
print seed_list
|
|
@ -0,0 +1,38 @@
|
|||
#!/bin/python
|
||||
|
||||
"""
|
||||
You have a list of integers, and for each index you want to find the product of every integer except the integer at that index.
|
||||
|
||||
Write a function get_products_of_all_ints_except_at_index() that takes a list of integers and returns a list of the products.
|
||||
|
||||
For example, given:
|
||||
|
||||
[1, 7, 3, 4]
|
||||
|
||||
your function would return:
|
||||
|
||||
[84, 12, 28, 21]
|
||||
|
||||
by calculating:
|
||||
|
||||
[7 * 3 * 4, 1 * 3 * 4, 1 * 7 * 4, 1 * 7 * 3]
|
||||
|
||||
Here's the catch: You can't use division in your solution!
|
||||
"""
|
||||
|
||||
def get_products_of_all_ints_except_at_index(array):
|
||||
prod_array = []
|
||||
|
||||
for i, num in enumerate(array):
|
||||
prod = 1
|
||||
for other_num in array[:i] + array[i+1:]:
|
||||
prod *= other_num
|
||||
|
||||
prod_array.append(prod)
|
||||
|
||||
return prod_array
|
||||
|
||||
|
||||
array = [1, 7, 3, 4]
|
||||
print get_products_of_all_ints_except_at_index(array)
|
||||
print "Should be [84, 12, 28, 21]"
|
|
@ -0,0 +1,32 @@
|
|||
#!/bin/python
|
||||
|
||||
"""
|
||||
Write a recursive function for generating all permutations of an input string. Return them as a set.
|
||||
"""
|
||||
|
||||
def get_permutations(string):
|
||||
|
||||
if len(string) < 2:
|
||||
return set([string])
|
||||
|
||||
all_chars_except_last = string[:-1]
|
||||
last_char = string[-1]
|
||||
|
||||
permutations_of_all_chars_except_last = get_permutations(all_chars_except_last)
|
||||
|
||||
permutations = set()
|
||||
for permutation_of_all_chars_except_last in permutations_of_all_chars_except_last:
|
||||
for position in range(len(all_chars_except_last) + 1):
|
||||
permutation = (
|
||||
permutation_of_all_chars_except_last[:position]
|
||||
+ last_char
|
||||
+ permutation_of_all_chars_except_last[position:]
|
||||
)
|
||||
permutations.add(permutation)
|
||||
|
||||
|
||||
return permutations
|
||||
|
||||
|
||||
str = "abcd"
|
||||
print get_permutations(str)
|
|
@ -0,0 +1,70 @@
|
|||
#!/bin/python
|
||||
|
||||
"""
|
||||
I want to learn some big words so people think I'm smart.
|
||||
|
||||
I opened up a dictionary to a page in the middle and started flipping through, looking for words I didn't know. I put each word I didn't know at increasing indices in a huge list I created in memory. When I reached the end of the dictionary, I started from the beginning and did the same thing until I reached the page I started at.
|
||||
|
||||
Now I have a list of words that are mostly alphabetical, except they start somewhere in the middle of the alphabet, reach the end, and then start from the beginning of the alphabet. In other words, this is an alphabetically ordered list that has been "rotated." For example:
|
||||
|
||||
words = [
|
||||
'ptolemaic',
|
||||
'retrograde',
|
||||
'supplant',
|
||||
'undulate',
|
||||
'xenoepist',
|
||||
'asymptote', # <-- rotates here!
|
||||
'babka',
|
||||
'banoffee',
|
||||
'engender',
|
||||
'karpatka',
|
||||
'othellolagkage',
|
||||
]
|
||||
|
||||
Write a function for finding the index of the "rotation point," which is where I started working from the beginning of the dictionary. This list is huge (there are lots of words I don't know) so we want to be efficient here.
|
||||
"""
|
||||
|
||||
def find_index(words):
|
||||
|
||||
for i, word in enumerate(words):
|
||||
if word[0] > words[i+1][0]:
|
||||
return i+1, words[i+1]
|
||||
|
||||
return "Not found"
|
||||
|
||||
|
||||
|
||||
def find_index_bs(words):
|
||||
first_word = words[0]
|
||||
floor_index = 0
|
||||
ceiling_index = len(words) - 1
|
||||
|
||||
while floor_index < ceiling_index:
|
||||
guess_index = floor_index + ((ceiling_index - floor_index) / 2)
|
||||
|
||||
if words[guess_index] >= first_word:
|
||||
floor_index = guess_index
|
||||
else:
|
||||
ceiling_index = guess_index
|
||||
|
||||
if floor_index + 1 == ceiling_index:
|
||||
return ceiling_index
|
||||
|
||||
|
||||
words = [
|
||||
'ptolemaic',
|
||||
'retrograde',
|
||||
'supplant',
|
||||
'undulate',
|
||||
'xenoepist',
|
||||
'asymptote',
|
||||
'babka',
|
||||
'banoffee',
|
||||
'engender',
|
||||
'karpatka',
|
||||
'othellolagkage',
|
||||
]
|
||||
|
||||
print find_index(words)
|
||||
print
|
||||
print find_index_bs(words)
|
|
@ -0,0 +1,48 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
|
||||
def binary_search(array, value):
|
||||
last, first = len(array), 0
|
||||
|
||||
while first < last:
|
||||
mid = (last - first)//2
|
||||
item = array[mid]
|
||||
|
||||
if item == value:
|
||||
return True
|
||||
|
||||
elif item < value:
|
||||
last = mid
|
||||
|
||||
else:
|
||||
first = mid
|
||||
|
||||
return False
|
||||
|
||||
def binary_search_rec(array, value, first=0, last=None):
|
||||
last = last or len(array)
|
||||
if len(array[first:last]) < 1:
|
||||
return False
|
||||
|
||||
mid = (last - first)//2
|
||||
if array[mid] == value:
|
||||
return True
|
||||
elif array[mid] < value:
|
||||
return binary_search_rec(array, value, first=first, last=mid)
|
||||
else:
|
||||
return binary_search_rec(array, value, first=mid, last=last)
|
||||
|
||||
|
||||
array = [3, 4, 6, 7, 10, 11, 34, 67, 84]
|
||||
value = 6
|
||||
assert(binary_search(array, value) == True)
|
||||
assert(binary_search_rec(array, value) == True)
|
||||
value = 8
|
||||
assert(binary_search(array, value) == False)
|
||||
assert(binary_search_rec(array, value) == False)
|
||||
array = [8]
|
||||
assert(binary_search(array, value) == True)
|
||||
assert(binary_search_rec(array, value) == True)
|
||||
array = []
|
||||
assert(binary_search(array, value) == False)
|
||||
assert(binary_search_rec(array, value) == False)
|
|
@ -0,0 +1,37 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
def merge_sort(list_to_sort):
|
||||
# Base case: lists with fewer than 2 elements are sorted
|
||||
if len(list_to_sort) < 2:
|
||||
return list_to_sort
|
||||
|
||||
# Step 1: divide the list in half
|
||||
mid_index = len(list_to_sort) / 2
|
||||
left = list_to_sort[:mid_index]
|
||||
right = list_to_sort[mid_index:]
|
||||
|
||||
# Step 2: sort each half
|
||||
sorted_left = merge_sort(left)
|
||||
sorted_right = merge_sort(right)
|
||||
|
||||
# Step 3: merge the sorted halves
|
||||
sorted_list = []
|
||||
current_index_left = 0
|
||||
current_index_right = 0
|
||||
|
||||
while len(sorted_list) < len(left) + len(right):
|
||||
if ((current_index_left < len(left)) and
|
||||
(current_index_right == len(right) or
|
||||
sorted_left[current_index_left] < sorted_right[current_index_right])):
|
||||
sorted_list.append(sorted_left[current_index_left])
|
||||
current_index_left += 1
|
||||
else:
|
||||
sorted_list.append(sorted_right[current_index_right])
|
||||
current_index_right += 1
|
||||
return sorted_list
|
||||
|
||||
|
||||
|
||||
list_to_sort = [5, 3, 7, 12, 1, 0, 10]
|
||||
|
||||
print merge_sort(list_to_sort)
|
|
@ -0,0 +1,52 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
"""
|
||||
In order to win the prize for most cookies sold, my friend Alice and
|
||||
# I are going to merge our Girl Scout Cookies orders and enter as one unit.
|
||||
# Each order is represented by an "order id" (an integer).
|
||||
We have our lists of orders sorted numerically already, in lists.
|
||||
Write a function to merge our lists of orders into one sorted list.
|
||||
"""
|
||||
|
||||
def merge_lists(my_list, alices_list):
|
||||
|
||||
result = []
|
||||
index_alice_list = 0
|
||||
index_my_list = 0
|
||||
|
||||
while index_alice_list < len(alices_list) and index_my_list < len(my_list):
|
||||
if alices_list[index_alice_list] < my_list[index_my_list]:
|
||||
result.append(alices_list[index_alice_list])
|
||||
index_alice_list += 1
|
||||
elif alices_list[index_alice_list] > my_list[index_my_list]:
|
||||
result.append(my_list[index_my_list])
|
||||
index_my_list += 1
|
||||
else:
|
||||
result.append(my_list[index_my_list])
|
||||
result.append(alices_list[index_alice_list])
|
||||
index_my_list += 1
|
||||
index_alice_list += 1
|
||||
|
||||
if index_alice_list < len(alices_list):
|
||||
result.extend(alices_list[index_alice_list:])
|
||||
|
||||
if index_my_list < len(my_list):
|
||||
result.extend(my_list[index_my_list:])
|
||||
|
||||
return result
|
||||
|
||||
|
||||
my_list = [3, 4, 6, 10, 11, 15]
|
||||
alices_list = [1, 5, 8, 12, 14, 19]
|
||||
|
||||
|
||||
print merge_lists(my_list, alices_list)
|
||||
print "Must be [1, 3, 4, 5, 6, 8, 10, 11, 12, 14, 15, 19]"
|
||||
|
||||
|
||||
# Or just using Timsort
|
||||
def merge_sorted_lists(arr1, arr2):
|
||||
return sorted(arr1 + arr2)
|
||||
|
||||
print merge_sorted_lists(my_list, alices_list)
|
||||
print "Must be [1, 3, 4, 5, 6, 8, 10, 11, 12, 14, 15, 19]"
|
|
@ -0,0 +1,51 @@
|
|||
#!/bin/python
|
||||
|
||||
"""
|
||||
Build a calendar.
|
||||
|
||||
A meeting is stored as a tuple of integers (start_time, end_time).
|
||||
These integers represent the number of 30-minute blocks past 9:00am.
|
||||
|
||||
For example:
|
||||
|
||||
(2, 3)# Meeting from 10:00-10:30 am
|
||||
(6, 9)# Meeting from 12:00-1:30 pm
|
||||
|
||||
Write a function merge_ranges() that takes a list of multiple meeting time ranges and returns a list of condensed ranges.
|
||||
|
||||
For example, given:
|
||||
|
||||
[(0, 1), (3, 5), (4, 8), (10, 12), (9, 10)]
|
||||
|
||||
your function would return:
|
||||
|
||||
[(0, 1), (3, 8), (9, 12)]
|
||||
|
||||
Do not assume the meetings are in order. The meeting times are coming from multiple teams.
|
||||
|
||||
Write a solution that's efficient even when we can't put a nice upper bound on the numbers representing our time ranges.
|
||||
Here we've simplified our times down to the number of 30-minute slots past 9:00 am.
|
||||
But we want the function to work even for very large numbers, like Unix timestamps.
|
||||
In any case, the spirit of the challenge is to merge meetings where start_time and end_time don't have an upper bound.
|
||||
"""
|
||||
|
||||
def merge_ranges(meetings):
|
||||
|
||||
sorted_meetings = sorted(meetings)
|
||||
merged_meetings = [sorted_meetings[0]]
|
||||
|
||||
for current_meeting_start, current_meeting_ending in sorted_meetings[1:]:
|
||||
last_merged_meeting_start, last_merged_meeting_end = merged_meetings[-1]
|
||||
|
||||
if (current_meeting_start <= last_merged_meeting_end):
|
||||
merged_meetings[-1] = (last_merged_meeting_start, max(last_merged_meeting_end, current_meeting_ending))
|
||||
else:
|
||||
merged_meetings.append((current_meeting_start, current_meeting_ending))
|
||||
|
||||
return merged_meetings
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
meetings = [(0, 1), (3, 5), (4, 8), (10, 12), (9, 10)]
|
||||
print(merge_ranges(meetings))
|
||||
print("Should return {}".format([(0, 1), (3, 8), (9, 12)]))
|
|
@ -0,0 +1,28 @@
|
|||
#!/bin/python
|
||||
|
||||
"""
|
||||
Write a function to tell us if a full deck of cards shuffled_deck is a single riffle of two other halves half1 and half2.
|
||||
|
||||
We'll represent a stack of cards as a list of integers in the range 1..521..52 (since there are 5252 distinct cards in a deck).
|
||||
Why do I care? A single riffle is not a completely random shuffle. If I'm right, I can make more informed bets and get rich and finally prove to my ex that I am not a "loser with an unhealthy cake obsession" (even though it's too late now because she let me go and she's never getting me back).
|
||||
"""
|
||||
|
||||
def is_single_riffle(half1, half2, shuffled_deck,
|
||||
shuffled_deck_index=0, half1_index=0, half2_index=0):
|
||||
if shuffled_deck_index == len(shuffled_deck):
|
||||
return True
|
||||
|
||||
if ((half1_index < len(half1)) and
|
||||
half1[half1_index] == shuffled_deck[shuffled_deck_index]):
|
||||
half1_index += 1
|
||||
|
||||
elif ((half2_index < len(half2)) and
|
||||
half2[half2_index] == shuffled_deck[shuffled_deck_index]):
|
||||
half2_index += 1
|
||||
else:
|
||||
return False
|
||||
|
||||
shuffled_deck_index += 1
|
||||
return is_single_riffle(
|
||||
half1, half2, shuffled_deck, shuffled_deck_index,
|
||||
half1_index, half2_index)
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue