mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-05-31 12:28:22 +00:00
Simplify code by dropping support for legacy Python (#1143)
* Simplify code by dropping support for legacy Python * sort() --> sorted()
This commit is contained in:
parent
32aa7ff081
commit
47a9ea2b0b
@ -56,7 +56,7 @@ We want your work to be readable by others; therefore, we encourage you to note
|
|||||||
|
|
||||||
```python
|
```python
|
||||||
"""
|
"""
|
||||||
This function sums a and b
|
This function sums a and b
|
||||||
"""
|
"""
|
||||||
def sum(a, b):
|
def sum(a, b):
|
||||||
return a + b
|
return a + b
|
||||||
@ -82,13 +82,13 @@ We want your work to be readable by others; therefore, we encourage you to note
|
|||||||
The following "testing" approaches are **not** encouraged:
|
The following "testing" approaches are **not** encouraged:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
input('Enter your input:')
|
input('Enter your input:')
|
||||||
# Or even worse...
|
# Or even worse...
|
||||||
input = eval(raw_input("Enter your input: "))
|
input = eval(input("Enter your input: "))
|
||||||
```
|
```
|
||||||
|
|
||||||
However, if your code uses __input()__ then we encourage you to gracefully deal with leading and trailing whitespace in user input by adding __.strip()__ to the end as in:
|
However, if your code uses __input()__ then we encourage you to gracefully deal with leading and trailing whitespace in user input by adding __.strip()__ to the end as in:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
starting_value = int(input("Please enter a starting value: ").strip())
|
starting_value = int(input("Please enter a starting value: ").strip())
|
||||||
```
|
```
|
||||||
@ -99,13 +99,13 @@ We want your work to be readable by others; therefore, we encourage you to note
|
|||||||
def sumab(a, b):
|
def sumab(a, b):
|
||||||
return a + b
|
return a + b
|
||||||
# Write tests this way:
|
# Write tests this way:
|
||||||
print(sumab(1,2)) # 1+2 = 3
|
print(sumab(1, 2)) # 1+2 = 3
|
||||||
print(sumab(6,4)) # 6+4 = 10
|
print(sumab(6, 4)) # 6+4 = 10
|
||||||
# Or this way:
|
# Or this way:
|
||||||
print("1 + 2 = ", sumab(1,2)) # 1+2 = 3
|
print("1 + 2 = ", sumab(1, 2)) # 1+2 = 3
|
||||||
print("6 + 4 = ", sumab(6,4)) # 6+4 = 10
|
print("6 + 4 = ", sumab(6, 4)) # 6+4 = 10
|
||||||
```
|
```
|
||||||
|
|
||||||
Better yet, if you know how to write [__doctests__](https://docs.python.org/3/library/doctest.html), please consider adding them.
|
Better yet, if you know how to write [__doctests__](https://docs.python.org/3/library/doctest.html), please consider adding them.
|
||||||
|
|
||||||
- Avoid importing external libraries for basic algorithms. Only use those libraries for complicated algorithms.
|
- Avoid importing external libraries for basic algorithms. Only use those libraries for complicated algorithms.
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
import sys, random, cryptomath_module as cryptoMath
|
import sys, random, cryptomath_module as cryptoMath
|
||||||
|
|
||||||
SYMBOLS = r""" !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""
|
SYMBOLS = r""" !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""
|
||||||
|
@ -1,23 +1,15 @@
|
|||||||
try: # Python 2
|
def atbash():
|
||||||
raw_input
|
|
||||||
unichr
|
|
||||||
except NameError: # Python 3
|
|
||||||
raw_input = input
|
|
||||||
unichr = chr
|
|
||||||
|
|
||||||
|
|
||||||
def Atbash():
|
|
||||||
output=""
|
output=""
|
||||||
for i in raw_input("Enter the sentence to be encrypted ").strip():
|
for i in input("Enter the sentence to be encrypted ").strip():
|
||||||
extract = ord(i)
|
extract = ord(i)
|
||||||
if 65 <= extract <= 90:
|
if 65 <= extract <= 90:
|
||||||
output += unichr(155-extract)
|
output += chr(155-extract)
|
||||||
elif 97 <= extract <= 122:
|
elif 97 <= extract <= 122:
|
||||||
output += unichr(219-extract)
|
output += chr(219-extract)
|
||||||
else:
|
else:
|
||||||
output+=i
|
output += i
|
||||||
print(output)
|
print(output)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
Atbash()
|
atbash()
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
def decrypt(message):
|
def decrypt(message):
|
||||||
"""
|
"""
|
||||||
>>> decrypt('TMDETUX PMDVU')
|
>>> decrypt('TMDETUX PMDVU')
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
import random
|
import random
|
||||||
|
|
||||||
|
|
||||||
@ -15,7 +13,7 @@ class Onepad:
|
|||||||
cipher.append(c)
|
cipher.append(c)
|
||||||
key.append(k)
|
key.append(k)
|
||||||
return cipher, key
|
return cipher, key
|
||||||
|
|
||||||
def decrypt(self, cipher, key):
|
def decrypt(self, cipher, key):
|
||||||
'''Function to decrypt text using psedo-random numbers.'''
|
'''Function to decrypt text using psedo-random numbers.'''
|
||||||
plain = []
|
plain = []
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
# Primality Testing with the Rabin-Miller Algorithm
|
# Primality Testing with the Rabin-Miller Algorithm
|
||||||
|
|
||||||
import random
|
import random
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
def dencrypt(s, n):
|
def dencrypt(s, n):
|
||||||
out = ''
|
out = ''
|
||||||
for c in s:
|
for c in s:
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
import sys, rsa_key_generator as rkg, os
|
import sys, rsa_key_generator as rkg, os
|
||||||
|
|
||||||
DEFAULT_BLOCK_SIZE = 128
|
DEFAULT_BLOCK_SIZE = 128
|
||||||
@ -16,7 +15,7 @@ def main():
|
|||||||
if mode == 'encrypt':
|
if mode == 'encrypt':
|
||||||
if not os.path.exists('rsa_pubkey.txt'):
|
if not os.path.exists('rsa_pubkey.txt'):
|
||||||
rkg.makeKeyFiles('rsa', 1024)
|
rkg.makeKeyFiles('rsa', 1024)
|
||||||
|
|
||||||
message = input('\nEnter message: ')
|
message = input('\nEnter message: ')
|
||||||
pubKeyFilename = 'rsa_pubkey.txt'
|
pubKeyFilename = 'rsa_pubkey.txt'
|
||||||
print('Encrypting and writing to %s...' % (filename))
|
print('Encrypting and writing to %s...' % (filename))
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
import random, sys, os
|
import random, sys, os
|
||||||
import rabin_miller as rabinMiller, cryptomath_module as cryptoMath
|
import rabin_miller as rabinMiller, cryptomath_module as cryptoMath
|
||||||
|
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
import sys, random
|
import sys, random
|
||||||
|
|
||||||
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
||||||
@ -18,7 +17,7 @@ def main():
|
|||||||
translated = decryptMessage(key, message)
|
translated = decryptMessage(key, message)
|
||||||
|
|
||||||
print('\n%sion: \n%s' % (mode.title(), translated))
|
print('\n%sion: \n%s' % (mode.title(), translated))
|
||||||
|
|
||||||
def checkValidKey(key):
|
def checkValidKey(key):
|
||||||
keyList = list(key)
|
keyList = list(key)
|
||||||
lettersList = list(LETTERS)
|
lettersList = list(LETTERS)
|
||||||
@ -49,7 +48,7 @@ def translateMessage(key, message, mode):
|
|||||||
|
|
||||||
if mode == 'decrypt':
|
if mode == 'decrypt':
|
||||||
charsA, charsB = charsB, charsA
|
charsA, charsB = charsB, charsA
|
||||||
|
|
||||||
for symbol in message:
|
for symbol in message:
|
||||||
if symbol.upper() in charsA:
|
if symbol.upper() in charsA:
|
||||||
symIndex = charsA.find(symbol.upper())
|
symIndex = charsA.find(symbol.upper())
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
import math
|
import math
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
import time, os, sys
|
import time, os, sys
|
||||||
import transposition_cipher as transCipher
|
import transposition_cipher as transCipher
|
||||||
|
|
||||||
@ -16,7 +15,7 @@ def main():
|
|||||||
response = input('> ')
|
response = input('> ')
|
||||||
if not response.lower().startswith('y'):
|
if not response.lower().startswith('y'):
|
||||||
sys.exit()
|
sys.exit()
|
||||||
|
|
||||||
startTime = time.time()
|
startTime = time.time()
|
||||||
if mode.lower().startswith('e'):
|
if mode.lower().startswith('e'):
|
||||||
with open(inputFile) as f:
|
with open(inputFile) as f:
|
||||||
@ -29,9 +28,9 @@ def main():
|
|||||||
|
|
||||||
with open(outputFile, 'w') as outputObj:
|
with open(outputFile, 'w') as outputObj:
|
||||||
outputObj.write(translated)
|
outputObj.write(translated)
|
||||||
|
|
||||||
totalTime = round(time.time() - startTime, 2)
|
totalTime = round(time.time() - startTime, 2)
|
||||||
print(('Done (', totalTime, 'seconds )'))
|
print(('Done (', totalTime, 'seconds )'))
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
main()
|
main()
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
'''
|
'''
|
||||||
A binary search Tree
|
A binary search Tree
|
||||||
'''
|
'''
|
||||||
from __future__ import print_function
|
|
||||||
class Node:
|
class Node:
|
||||||
|
|
||||||
def __init__(self, label, parent):
|
def __init__(self, label, parent):
|
||||||
@ -66,8 +65,8 @@ class BinarySearchTree:
|
|||||||
else:
|
else:
|
||||||
parent_node.setRight(new_node)
|
parent_node.setRight(new_node)
|
||||||
#Set parent to the new node
|
#Set parent to the new node
|
||||||
new_node.setParent(parent_node)
|
new_node.setParent(parent_node)
|
||||||
|
|
||||||
def delete(self, label):
|
def delete(self, label):
|
||||||
if (not self.empty()):
|
if (not self.empty()):
|
||||||
#Look for the node with that label
|
#Look for the node with that label
|
||||||
@ -92,7 +91,7 @@ class BinarySearchTree:
|
|||||||
self.delete(tmpNode.getLabel())
|
self.delete(tmpNode.getLabel())
|
||||||
#Assigns the value to the node to delete and keesp tree structure
|
#Assigns the value to the node to delete and keesp tree structure
|
||||||
node.setLabel(tmpNode.getLabel())
|
node.setLabel(tmpNode.getLabel())
|
||||||
|
|
||||||
def getNode(self, label):
|
def getNode(self, label):
|
||||||
curr_node = None
|
curr_node = None
|
||||||
#If the tree is not empty
|
#If the tree is not empty
|
||||||
@ -177,7 +176,7 @@ class BinarySearchTree:
|
|||||||
#Returns a list of nodes in the order that the users wants to
|
#Returns a list of nodes in the order that the users wants to
|
||||||
return traversalFunction(self.root)
|
return traversalFunction(self.root)
|
||||||
|
|
||||||
#Returns an string of all the nodes labels in the list
|
#Returns an string of all the nodes labels in the list
|
||||||
#In Order Traversal
|
#In Order Traversal
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
list = self.__InOrderTraversal(self.root)
|
list = self.__InOrderTraversal(self.root)
|
||||||
@ -203,7 +202,7 @@ def testBinarySearchTree():
|
|||||||
/ \ \
|
/ \ \
|
||||||
1 6 14
|
1 6 14
|
||||||
/ \ /
|
/ \ /
|
||||||
4 7 13
|
4 7 13
|
||||||
'''
|
'''
|
||||||
|
|
||||||
r'''
|
r'''
|
||||||
@ -236,11 +235,11 @@ def testBinarySearchTree():
|
|||||||
print("The label -1 exists")
|
print("The label -1 exists")
|
||||||
else:
|
else:
|
||||||
print("The label -1 doesn't exist")
|
print("The label -1 doesn't exist")
|
||||||
|
|
||||||
if(not t.empty()):
|
if(not t.empty()):
|
||||||
print(("Max Value: ", t.getMax().getLabel()))
|
print(("Max Value: ", t.getMax().getLabel()))
|
||||||
print(("Min Value: ", t.getMin().getLabel()))
|
print(("Min Value: ", t.getMin().getLabel()))
|
||||||
|
|
||||||
t.delete(13)
|
t.delete(13)
|
||||||
t.delete(10)
|
t.delete(10)
|
||||||
t.delete(8)
|
t.delete(8)
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
class FenwickTree:
|
class FenwickTree:
|
||||||
|
|
||||||
def __init__(self, SIZE): # create fenwick tree with size SIZE
|
def __init__(self, SIZE): # create fenwick tree with size SIZE
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
import math
|
import math
|
||||||
|
|
||||||
class SegmentTree:
|
class SegmentTree:
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
import math
|
import math
|
||||||
|
|
||||||
class SegmentTree:
|
class SegmentTree:
|
||||||
|
@ -1,15 +1,8 @@
|
|||||||
#!/usr/bin/python
|
#!/usr/bin/python
|
||||||
|
|
||||||
from __future__ import print_function, division
|
# This heap class start from here.
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
#This heap class start from here.
|
|
||||||
class Heap:
|
class Heap:
|
||||||
def __init__(self): #Default constructor of heap class.
|
def __init__(self): # Default constructor of heap class.
|
||||||
self.h = []
|
self.h = []
|
||||||
self.currsize = 0
|
self.currsize = 0
|
||||||
|
|
||||||
@ -79,7 +72,7 @@ class Heap:
|
|||||||
print(self.h)
|
print(self.h)
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
l = list(map(int, raw_input().split()))
|
l = list(map(int, input().split()))
|
||||||
h = Heap()
|
h = Heap()
|
||||||
h.buildHeap(l)
|
h.buildHeap(l)
|
||||||
h.heapSort()
|
h.heapSort()
|
||||||
|
@ -4,14 +4,13 @@
|
|||||||
- Each link references the next link and the previous one.
|
- Each link references the next link and the previous one.
|
||||||
- A Doubly Linked List (DLL) contains an extra pointer, typically called previous pointer, together with next pointer and data which are there in singly linked list.
|
- A Doubly Linked List (DLL) contains an extra pointer, typically called previous pointer, together with next pointer and data which are there in singly linked list.
|
||||||
- Advantages over SLL - IT can be traversed in both forward and backward direction.,Delete operation is more efficent'''
|
- Advantages over SLL - IT can be traversed in both forward and backward direction.,Delete operation is more efficent'''
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
|
|
||||||
class LinkedList: #making main class named linked list
|
class LinkedList: #making main class named linked list
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.head = None
|
self.head = None
|
||||||
self.tail = None
|
self.tail = None
|
||||||
|
|
||||||
def insertHead(self, x):
|
def insertHead(self, x):
|
||||||
newLink = Link(x) #Create a new link with a value attached to it
|
newLink = Link(x) #Create a new link with a value attached to it
|
||||||
if(self.isEmpty() == True): #Set the first element added to be the tail
|
if(self.isEmpty() == True): #Set the first element added to be the tail
|
||||||
@ -20,52 +19,52 @@ class LinkedList: #making main class named linked list
|
|||||||
self.head.previous = newLink # newLink <-- currenthead(head)
|
self.head.previous = newLink # newLink <-- currenthead(head)
|
||||||
newLink.next = self.head # newLink <--> currenthead(head)
|
newLink.next = self.head # newLink <--> currenthead(head)
|
||||||
self.head = newLink # newLink(head) <--> oldhead
|
self.head = newLink # newLink(head) <--> oldhead
|
||||||
|
|
||||||
def deleteHead(self):
|
def deleteHead(self):
|
||||||
temp = self.head
|
temp = self.head
|
||||||
self.head = self.head.next # oldHead <--> 2ndElement(head)
|
self.head = self.head.next # oldHead <--> 2ndElement(head)
|
||||||
self.head.previous = None # oldHead --> 2ndElement(head) nothing pointing at it so the old head will be removed
|
self.head.previous = None # oldHead --> 2ndElement(head) nothing pointing at it so the old head will be removed
|
||||||
if(self.head is None):
|
if(self.head is None):
|
||||||
self.tail = None #if empty linked list
|
self.tail = None #if empty linked list
|
||||||
return temp
|
return temp
|
||||||
|
|
||||||
def insertTail(self, x):
|
def insertTail(self, x):
|
||||||
newLink = Link(x)
|
newLink = Link(x)
|
||||||
newLink.next = None # currentTail(tail) newLink -->
|
newLink.next = None # currentTail(tail) newLink -->
|
||||||
self.tail.next = newLink # currentTail(tail) --> newLink -->
|
self.tail.next = newLink # currentTail(tail) --> newLink -->
|
||||||
newLink.previous = self.tail #currentTail(tail) <--> newLink -->
|
newLink.previous = self.tail #currentTail(tail) <--> newLink -->
|
||||||
self.tail = newLink # oldTail <--> newLink(tail) -->
|
self.tail = newLink # oldTail <--> newLink(tail) -->
|
||||||
|
|
||||||
def deleteTail(self):
|
def deleteTail(self):
|
||||||
temp = self.tail
|
temp = self.tail
|
||||||
self.tail = self.tail.previous # 2ndLast(tail) <--> oldTail --> None
|
self.tail = self.tail.previous # 2ndLast(tail) <--> oldTail --> None
|
||||||
self.tail.next = None # 2ndlast(tail) --> None
|
self.tail.next = None # 2ndlast(tail) --> None
|
||||||
return temp
|
return temp
|
||||||
|
|
||||||
def delete(self, x):
|
def delete(self, x):
|
||||||
current = self.head
|
current = self.head
|
||||||
|
|
||||||
while(current.value != x): # Find the position to delete
|
while(current.value != x): # Find the position to delete
|
||||||
current = current.next
|
current = current.next
|
||||||
|
|
||||||
if(current == self.head):
|
if(current == self.head):
|
||||||
self.deleteHead()
|
self.deleteHead()
|
||||||
|
|
||||||
elif(current == self.tail):
|
elif(current == self.tail):
|
||||||
self.deleteTail()
|
self.deleteTail()
|
||||||
|
|
||||||
else: #Before: 1 <--> 2(current) <--> 3
|
else: #Before: 1 <--> 2(current) <--> 3
|
||||||
current.previous.next = current.next # 1 --> 3
|
current.previous.next = current.next # 1 --> 3
|
||||||
current.next.previous = current.previous # 1 <--> 3
|
current.next.previous = current.previous # 1 <--> 3
|
||||||
|
|
||||||
def isEmpty(self): #Will return True if the list is empty
|
def isEmpty(self): #Will return True if the list is empty
|
||||||
return(self.head is None)
|
return(self.head is None)
|
||||||
|
|
||||||
def display(self): #Prints contents of the list
|
def display(self): #Prints contents of the list
|
||||||
current = self.head
|
current = self.head
|
||||||
while(current != None):
|
while(current != None):
|
||||||
current.displayLink()
|
current.displayLink()
|
||||||
current = current.next
|
current = current.next
|
||||||
print()
|
print()
|
||||||
|
|
||||||
class Link:
|
class Link:
|
||||||
|
@ -1,6 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
|
|
||||||
class Node: # create a Node
|
class Node: # create a Node
|
||||||
def __init__(self, data):
|
def __init__(self, data):
|
||||||
self.data = data # given data
|
self.data = data # given data
|
||||||
@ -10,7 +7,7 @@ class Node: # create a Node
|
|||||||
class Linked_List:
|
class Linked_List:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.Head = None # Initialize Head to None
|
self.Head = None # Initialize Head to None
|
||||||
|
|
||||||
def insert_tail(self, data):
|
def insert_tail(self, data):
|
||||||
if(self.Head is None): self.insert_head(data) #If this is first node, call insert_head
|
if(self.Head is None): self.insert_head(data) #If this is first node, call insert_head
|
||||||
else:
|
else:
|
||||||
@ -37,7 +34,7 @@ class Linked_List:
|
|||||||
self.Head = self.Head.next
|
self.Head = self.Head.next
|
||||||
temp.next = None
|
temp.next = None
|
||||||
return temp
|
return temp
|
||||||
|
|
||||||
def delete_tail(self): # delete from tail
|
def delete_tail(self): # delete from tail
|
||||||
tamp = self.Head
|
tamp = self.Head
|
||||||
if self.Head != None:
|
if self.Head != None:
|
||||||
@ -46,7 +43,7 @@ class Linked_List:
|
|||||||
else:
|
else:
|
||||||
while tamp.next.next is not None: # find the 2nd last element
|
while tamp.next.next is not None: # find the 2nd last element
|
||||||
tamp = tamp.next
|
tamp = tamp.next
|
||||||
tamp.next, tamp = None, tamp.next #(2nd last element).next = None and tamp = last element
|
tamp.next, tamp = None, tamp.next #(2nd last element).next = None and tamp = last element
|
||||||
return tamp
|
return tamp
|
||||||
|
|
||||||
def isEmpty(self):
|
def isEmpty(self):
|
||||||
@ -79,7 +76,7 @@ def main():
|
|||||||
print("\nPrint List : ")
|
print("\nPrint List : ")
|
||||||
A.printList()
|
A.printList()
|
||||||
print("\nInserting 1st at Tail")
|
print("\nInserting 1st at Tail")
|
||||||
a3=input()
|
a3=input()
|
||||||
A.insert_tail(a3)
|
A.insert_tail(a3)
|
||||||
print("Inserting 2nd at Tail")
|
print("Inserting 2nd at Tail")
|
||||||
a4=input()
|
a4=input()
|
||||||
@ -96,6 +93,6 @@ def main():
|
|||||||
A.reverse()
|
A.reverse()
|
||||||
print("\nPrint List : ")
|
print("\nPrint List : ")
|
||||||
A.printList()
|
A.printList()
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
main()
|
main()
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
# Python code to demonstrate working of
|
# Python code to demonstrate working of
|
||||||
# extend(), extendleft(), rotate(), reverse()
|
# extend(), extendleft(), rotate(), reverse()
|
||||||
|
|
||||||
|
@ -1,6 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
from __future__ import absolute_import
|
|
||||||
|
|
||||||
from .stack import Stack
|
from .stack import Stack
|
||||||
|
|
||||||
__author__ = 'Omkar Pathak'
|
__author__ = 'Omkar Pathak'
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
from __future__ import absolute_import
|
|
||||||
import string
|
import string
|
||||||
|
|
||||||
from .stack import Stack
|
from .stack import Stack
|
||||||
|
@ -1,17 +1,16 @@
|
|||||||
from __future__ import print_function
|
|
||||||
# Function to print element and NGE pair for all elements of list
|
# Function to print element and NGE pair for all elements of list
|
||||||
def printNGE(arr):
|
def printNGE(arr):
|
||||||
|
|
||||||
for i in range(0, len(arr), 1):
|
for i in range(0, len(arr), 1):
|
||||||
|
|
||||||
next = -1
|
next = -1
|
||||||
for j in range(i+1, len(arr), 1):
|
for j in range(i+1, len(arr), 1):
|
||||||
if arr[i] < arr[j]:
|
if arr[i] < arr[j]:
|
||||||
next = arr[j]
|
next = arr[j]
|
||||||
break
|
break
|
||||||
|
|
||||||
print(str(arr[i]) + " -- " + str(next))
|
print(str(arr[i]) + " -- " + str(next))
|
||||||
|
|
||||||
# Driver program to test above function
|
# Driver program to test above function
|
||||||
arr = [11,13,21,3]
|
arr = [11,13,21,3]
|
||||||
printNGE(arr)
|
printNGE(arr)
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
__author__ = 'Omkar Pathak'
|
__author__ = 'Omkar Pathak'
|
||||||
|
|
||||||
|
|
||||||
|
@ -6,7 +6,6 @@ The span Si of the stock's price on a given day i is defined as the maximum
|
|||||||
number of consecutive days just before the given day, for which the price of the stock
|
number of consecutive days just before the given day, for which the price of the stock
|
||||||
on the current day is less than or equal to its price on the given day.
|
on the current day is less than or equal to its price on the given day.
|
||||||
'''
|
'''
|
||||||
from __future__ import print_function
|
|
||||||
def calculateSpan(price, S):
|
def calculateSpan(price, S):
|
||||||
|
|
||||||
n = len(price)
|
n = len(price)
|
||||||
|
@ -1,18 +1,16 @@
|
|||||||
from __future__ import print_function, absolute_import, division
|
|
||||||
|
|
||||||
from numbers import Number
|
from numbers import Number
|
||||||
"""
|
"""
|
||||||
The convex hull problem is problem of finding all the vertices of convex polygon, P of
|
The convex hull problem is problem of finding all the vertices of convex polygon, P of
|
||||||
a set of points in a plane such that all the points are either on the vertices of P or
|
a set of points in a plane such that all the points are either on the vertices of P or
|
||||||
inside P. TH convex hull problem has several applications in geometrical problems,
|
inside P. TH convex hull problem has several applications in geometrical problems,
|
||||||
computer graphics and game development.
|
computer graphics and game development.
|
||||||
|
|
||||||
Two algorithms have been implemented for the convex hull problem here.
|
Two algorithms have been implemented for the convex hull problem here.
|
||||||
1. A brute-force algorithm which runs in O(n^3)
|
1. A brute-force algorithm which runs in O(n^3)
|
||||||
2. A divide-and-conquer algorithm which runs in O(n^3)
|
2. A divide-and-conquer algorithm which runs in O(n^3)
|
||||||
|
|
||||||
There are other several other algorithms for the convex hull problem
|
There are other several other algorithms for the convex hull problem
|
||||||
which have not been implemented here, yet.
|
which have not been implemented here, yet.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
@ -1,15 +1,13 @@
|
|||||||
from __future__ import print_function, absolute_import, division
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
Given an array-like data structure A[1..n], how many pairs
|
Given an array-like data structure A[1..n], how many pairs
|
||||||
(i, j) for all 1 <= i < j <= n such that A[i] > A[j]? These pairs are
|
(i, j) for all 1 <= i < j <= n such that A[i] > A[j]? These pairs are
|
||||||
called inversions. Counting the number of such inversions in an array-like
|
called inversions. Counting the number of such inversions in an array-like
|
||||||
object is the important. Among other things, counting inversions can help
|
object is the important. Among other things, counting inversions can help
|
||||||
us determine how close a given array is to being sorted
|
us determine how close a given array is to being sorted
|
||||||
|
|
||||||
In this implementation, I provide two algorithms, a divide-and-conquer
|
In this implementation, I provide two algorithms, a divide-and-conquer
|
||||||
algorithm which runs in nlogn and the brute-force n^2 algorithm.
|
algorithm which runs in nlogn and the brute-force n^2 algorithm.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
@ -9,27 +9,26 @@ Find the total no of ways in which the tasks can be distributed.
|
|||||||
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
|
|
||||||
|
|
||||||
class AssignmentUsingBitmask:
|
class AssignmentUsingBitmask:
|
||||||
def __init__(self,task_performed,total):
|
def __init__(self,task_performed,total):
|
||||||
|
|
||||||
self.total_tasks = total #total no of tasks (N)
|
self.total_tasks = total #total no of tasks (N)
|
||||||
|
|
||||||
# DP table will have a dimension of (2^M)*N
|
# DP table will have a dimension of (2^M)*N
|
||||||
# initially all values are set to -1
|
# initially all values are set to -1
|
||||||
self.dp = [[-1 for i in range(total+1)] for j in range(2**len(task_performed))]
|
self.dp = [[-1 for i in range(total+1)] for j in range(2**len(task_performed))]
|
||||||
|
|
||||||
self.task = defaultdict(list) #stores the list of persons for each task
|
self.task = defaultdict(list) #stores the list of persons for each task
|
||||||
|
|
||||||
#finalmask is used to check if all persons are included by setting all bits to 1
|
#finalmask is used to check if all persons are included by setting all bits to 1
|
||||||
self.finalmask = (1<<len(task_performed)) - 1
|
self.finalmask = (1<<len(task_performed)) - 1
|
||||||
|
|
||||||
|
|
||||||
def CountWaysUtil(self,mask,taskno):
|
def CountWaysUtil(self,mask,taskno):
|
||||||
|
|
||||||
# if mask == self.finalmask all persons are distributed tasks, return 1
|
# if mask == self.finalmask all persons are distributed tasks, return 1
|
||||||
if mask == self.finalmask:
|
if mask == self.finalmask:
|
||||||
return 1
|
return 1
|
||||||
@ -48,18 +47,18 @@ class AssignmentUsingBitmask:
|
|||||||
# now assign the tasks one by one to all possible persons and recursively assign for the remaining tasks.
|
# now assign the tasks one by one to all possible persons and recursively assign for the remaining tasks.
|
||||||
if taskno in self.task:
|
if taskno in self.task:
|
||||||
for p in self.task[taskno]:
|
for p in self.task[taskno]:
|
||||||
|
|
||||||
# if p is already given a task
|
# if p is already given a task
|
||||||
if mask & (1<<p):
|
if mask & (1<<p):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# assign this task to p and change the mask value. And recursively assign tasks with the new mask value.
|
# assign this task to p and change the mask value. And recursively assign tasks with the new mask value.
|
||||||
total_ways_util+=self.CountWaysUtil(mask|(1<<p),taskno+1)
|
total_ways_util+=self.CountWaysUtil(mask|(1<<p),taskno+1)
|
||||||
|
|
||||||
# save the value.
|
# save the value.
|
||||||
self.dp[mask][taskno] = total_ways_util
|
self.dp[mask][taskno] = total_ways_util
|
||||||
|
|
||||||
return self.dp[mask][taskno]
|
return self.dp[mask][taskno]
|
||||||
|
|
||||||
def countNoOfWays(self,task_performed):
|
def countNoOfWays(self,task_performed):
|
||||||
|
|
||||||
@ -67,17 +66,17 @@ class AssignmentUsingBitmask:
|
|||||||
for i in range(len(task_performed)):
|
for i in range(len(task_performed)):
|
||||||
for j in task_performed[i]:
|
for j in task_performed[i]:
|
||||||
self.task[j].append(i)
|
self.task[j].append(i)
|
||||||
|
|
||||||
# call the function to fill the DP table, final answer is stored in dp[0][1]
|
# call the function to fill the DP table, final answer is stored in dp[0][1]
|
||||||
return self.CountWaysUtil(0,1)
|
return self.CountWaysUtil(0,1)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|
||||||
total_tasks = 5 #total no of tasks (the value of N)
|
total_tasks = 5 #total no of tasks (the value of N)
|
||||||
|
|
||||||
#the list of tasks that can be done by M persons.
|
#the list of tasks that can be done by M persons.
|
||||||
task_performed = [
|
task_performed = [
|
||||||
[ 1 , 3 , 4 ],
|
[ 1 , 3 , 4 ],
|
||||||
[ 1 , 2 , 5 ],
|
[ 1 , 2 , 5 ],
|
||||||
[ 3 , 4 ]
|
[ 3 , 4 ]
|
||||||
|
@ -5,9 +5,6 @@ Can you determine number of ways of making change for n units using
|
|||||||
the given types of coins?
|
the given types of coins?
|
||||||
https://www.hackerrank.com/challenges/coin-change/problem
|
https://www.hackerrank.com/challenges/coin-change/problem
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
|
|
||||||
def dp_count(S, m, n):
|
def dp_count(S, m, n):
|
||||||
|
|
||||||
# table[i] represents the number of ways to get to amount i
|
# table[i] represents the number of ways to get to amount i
|
||||||
|
@ -7,7 +7,6 @@ This is a pure Python implementation of Dynamic Programming solution to the edit
|
|||||||
The problem is :
|
The problem is :
|
||||||
Given two strings A and B. Find the minimum number of operations to string B such that A = B. The permitted operations are removal, insertion, and substitution.
|
Given two strings A and B. Find the minimum number of operations to string B such that A = B. The permitted operations are removal, insertion, and substitution.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
|
|
||||||
class EditDistance:
|
class EditDistance:
|
||||||
@ -67,14 +66,14 @@ def min_distance_bottom_up(word1: str, word2: str) -> int:
|
|||||||
dp = [[0 for _ in range(n+1) ] for _ in range(m+1)]
|
dp = [[0 for _ in range(n+1) ] for _ in range(m+1)]
|
||||||
for i in range(m+1):
|
for i in range(m+1):
|
||||||
for j in range(n+1):
|
for j in range(n+1):
|
||||||
|
|
||||||
if i == 0: #first string is empty
|
if i == 0: #first string is empty
|
||||||
dp[i][j] = j
|
dp[i][j] = j
|
||||||
elif j == 0: #second string is empty
|
elif j == 0: #second string is empty
|
||||||
dp[i][j] = i
|
dp[i][j] = i
|
||||||
elif word1[i-1] == word2[j-1]: #last character of both substing is equal
|
elif word1[i-1] == word2[j-1]: #last character of both substing is equal
|
||||||
dp[i][j] = dp[i-1][j-1]
|
dp[i][j] = dp[i-1][j-1]
|
||||||
else:
|
else:
|
||||||
insert = dp[i][j-1]
|
insert = dp[i][j-1]
|
||||||
delete = dp[i-1][j]
|
delete = dp[i-1][j]
|
||||||
replace = dp[i-1][j-1]
|
replace = dp[i-1][j-1]
|
||||||
@ -82,21 +81,13 @@ def min_distance_bottom_up(word1: str, word2: str) -> int:
|
|||||||
return dp[m][n]
|
return dp[m][n]
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
solver = EditDistance()
|
solver = EditDistance()
|
||||||
|
|
||||||
print("****************** Testing Edit Distance DP Algorithm ******************")
|
print("****************** Testing Edit Distance DP Algorithm ******************")
|
||||||
print()
|
print()
|
||||||
|
|
||||||
print("Enter the first string: ", end="")
|
S1 = input("Enter the first string: ").strip()
|
||||||
S1 = raw_input().strip()
|
S2 = input("Enter the second string: ").strip()
|
||||||
|
|
||||||
print("Enter the second string: ", end="")
|
|
||||||
S2 = raw_input().strip()
|
|
||||||
|
|
||||||
print()
|
print()
|
||||||
print("The minimum Edit Distance is: %d" % (solver.solve(S1, S2)))
|
print("The minimum Edit Distance is: %d" % (solver.solve(S1, S2)))
|
||||||
@ -106,4 +97,4 @@ if __name__ == '__main__':
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -5,7 +5,6 @@
|
|||||||
This program calculates the nth Fibonacci number in O(log(n)).
|
This program calculates the nth Fibonacci number in O(log(n)).
|
||||||
It's possible to calculate F(1000000) in less than a second.
|
It's possible to calculate F(1000000) in less than a second.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
"""
|
"""
|
||||||
This is a pure Python implementation of Dynamic Programming solution to the fibonacci sequence problem.
|
This is a pure Python implementation of Dynamic Programming solution to the fibonacci sequence problem.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
|
|
||||||
class Fibonacci:
|
class Fibonacci:
|
||||||
@ -29,21 +28,16 @@ class Fibonacci:
|
|||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
print("\n********* Fibonacci Series Using Dynamic Programming ************\n")
|
print("\n********* Fibonacci Series Using Dynamic Programming ************\n")
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
print("\n Enter the upper limit for the fibonacci sequence: ", end="")
|
print("\n Enter the upper limit for the fibonacci sequence: ", end="")
|
||||||
try:
|
try:
|
||||||
N = eval(raw_input().strip())
|
N = int(input().strip())
|
||||||
fib = Fibonacci(N)
|
fib = Fibonacci(N)
|
||||||
print(
|
print(
|
||||||
"\n********* Enter different values to get the corresponding fibonacci sequence, enter any negative number to exit. ************\n")
|
"\n********* Enter different values to get the corresponding fibonacci "
|
||||||
|
"sequence, enter any negative number to exit. ************\n")
|
||||||
while True:
|
while True:
|
||||||
print("Enter value: ", end=" ")
|
|
||||||
try:
|
try:
|
||||||
i = eval(raw_input().strip())
|
i = int(input("Enter value: ").strip())
|
||||||
if i < 0:
|
if i < 0:
|
||||||
print("\n********* Good Bye!! ************\n")
|
print("\n********* Good Bye!! ************\n")
|
||||||
break
|
break
|
||||||
|
@ -1,27 +1,15 @@
|
|||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
try:
|
|
||||||
xrange #Python 2
|
|
||||||
except NameError:
|
|
||||||
xrange = range #Python 3
|
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input #Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input #Python 3
|
|
||||||
|
|
||||||
'''
|
'''
|
||||||
The number of partitions of a number n into at least k parts equals the number of partitions into exactly k parts
|
The number of partitions of a number n into at least k parts equals the number of partitions into exactly k parts
|
||||||
plus the number of partitions into at least k-1 parts. Subtracting 1 from each part of a partition of n into k parts
|
plus the number of partitions into at least k-1 parts. Subtracting 1 from each part of a partition of n into k parts
|
||||||
gives a partition of n-k into k parts. These two facts together are used for this algorithm.
|
gives a partition of n-k into k parts. These two facts together are used for this algorithm.
|
||||||
'''
|
'''
|
||||||
def partition(m):
|
def partition(m):
|
||||||
memo = [[0 for _ in xrange(m)] for _ in xrange(m+1)]
|
memo = [[0 for _ in range(m)] for _ in range(m+1)]
|
||||||
for i in xrange(m+1):
|
for i in range(m+1):
|
||||||
memo[i][0] = 1
|
memo[i][0] = 1
|
||||||
|
|
||||||
for n in xrange(m+1):
|
for n in range(m+1):
|
||||||
for k in xrange(1, m):
|
for k in range(1, m):
|
||||||
memo[n][k] += memo[n][k-1]
|
memo[n][k] += memo[n][k-1]
|
||||||
if n-k > 0:
|
if n-k > 0:
|
||||||
memo[n][k] += memo[n-k-1][k]
|
memo[n][k] += memo[n-k-1][k]
|
||||||
@ -33,7 +21,7 @@ if __name__ == '__main__':
|
|||||||
|
|
||||||
if len(sys.argv) == 1:
|
if len(sys.argv) == 1:
|
||||||
try:
|
try:
|
||||||
n = int(raw_input('Enter a number: '))
|
n = int(input('Enter a number: ').strip())
|
||||||
print(partition(n))
|
print(partition(n))
|
||||||
except ValueError:
|
except ValueError:
|
||||||
print('Please enter a number.')
|
print('Please enter a number.')
|
||||||
|
@ -3,7 +3,6 @@ LCS Problem Statement: Given two sequences, find the length of longest subsequen
|
|||||||
A subsequence is a sequence that appears in the same relative order, but not necessarily continuous.
|
A subsequence is a sequence that appears in the same relative order, but not necessarily continuous.
|
||||||
Example:"abc", "abg" are subsequences of "abcdefgh".
|
Example:"abc", "abg" are subsequences of "abcdefgh".
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
|
|
||||||
def longest_common_subsequence(x: str, y: str):
|
def longest_common_subsequence(x: str, y: str):
|
||||||
@ -80,4 +79,3 @@ if __name__ == '__main__':
|
|||||||
assert expected_ln == ln
|
assert expected_ln == ln
|
||||||
assert expected_subseq == subseq
|
assert expected_subseq == subseq
|
||||||
print("len =", ln, ", sub-sequence =", subseq)
|
print("len =", ln, ", sub-sequence =", subseq)
|
||||||
|
|
||||||
|
@ -7,10 +7,8 @@ The problem is :
|
|||||||
Given an ARRAY, to find the longest and increasing sub ARRAY in that given ARRAY and return it.
|
Given an ARRAY, to find the longest and increasing sub ARRAY in that given ARRAY and return it.
|
||||||
Example: [10, 22, 9, 33, 21, 50, 41, 60, 80] as input will return [10, 22, 33, 41, 60, 80] as output
|
Example: [10, 22, 9, 33, 21, 50, 41, 60, 80] as input will return [10, 22, 33, 41, 60, 80] as output
|
||||||
'''
|
'''
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
def longestSub(ARRAY): #This function is recursive
|
def longestSub(ARRAY): #This function is recursive
|
||||||
|
|
||||||
ARRAY_LENGTH = len(ARRAY)
|
ARRAY_LENGTH = len(ARRAY)
|
||||||
if(ARRAY_LENGTH <= 1): #If the array contains only one element, we return it (it's the stop condition of recursion)
|
if(ARRAY_LENGTH <= 1): #If the array contains only one element, we return it (it's the stop condition of recursion)
|
||||||
return ARRAY
|
return ARRAY
|
||||||
|
@ -1,9 +1,8 @@
|
|||||||
from __future__ import print_function
|
|
||||||
#############################
|
#############################
|
||||||
# Author: Aravind Kashyap
|
# Author: Aravind Kashyap
|
||||||
# File: lis.py
|
# File: lis.py
|
||||||
# comments: This programme outputs the Longest Strictly Increasing Subsequence in O(NLogN)
|
# comments: This programme outputs the Longest Strictly Increasing Subsequence in O(NLogN)
|
||||||
# Where N is the Number of elements in the list
|
# Where N is the Number of elements in the list
|
||||||
#############################
|
#############################
|
||||||
def CeilIndex(v,l,r,key):
|
def CeilIndex(v,l,r,key):
|
||||||
while r-l > 1:
|
while r-l > 1:
|
||||||
@ -12,30 +11,30 @@ def CeilIndex(v,l,r,key):
|
|||||||
r = m
|
r = m
|
||||||
else:
|
else:
|
||||||
l = m
|
l = m
|
||||||
|
|
||||||
return r
|
return r
|
||||||
|
|
||||||
|
|
||||||
def LongestIncreasingSubsequenceLength(v):
|
def LongestIncreasingSubsequenceLength(v):
|
||||||
if(len(v) == 0):
|
if(len(v) == 0):
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
tail = [0]*len(v)
|
tail = [0]*len(v)
|
||||||
length = 1
|
length = 1
|
||||||
|
|
||||||
tail[0] = v[0]
|
tail[0] = v[0]
|
||||||
|
|
||||||
for i in range(1,len(v)):
|
for i in range(1,len(v)):
|
||||||
if v[i] < tail[0]:
|
if v[i] < tail[0]:
|
||||||
tail[0] = v[i]
|
tail[0] = v[i]
|
||||||
elif v[i] > tail[length-1]:
|
elif v[i] > tail[length-1]:
|
||||||
tail[length] = v[i]
|
tail[length] = v[i]
|
||||||
length += 1
|
length += 1
|
||||||
else:
|
else:
|
||||||
tail[CeilIndex(tail,-1,length-1,v[i])] = v[i]
|
tail[CeilIndex(tail,-1,length-1,v[i])] = v[i]
|
||||||
|
|
||||||
return length
|
return length
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
v = [2, 5, 3, 7, 11, 8, 10, 13, 6]
|
v = [2, 5, 3, 7, 11, 8, 10, 13, 6]
|
||||||
|
@ -6,7 +6,6 @@ This is a pure Python implementation of Dynamic Programming solution to the long
|
|||||||
The problem is :
|
The problem is :
|
||||||
Given an array, to find the longest and continuous sub array and get the max sum of the sub array in the given array.
|
Given an array, to find the longest and continuous sub array and get the max sum of the sub array in the given array.
|
||||||
'''
|
'''
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
|
|
||||||
class SubArray:
|
class SubArray:
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
import sys
|
import sys
|
||||||
'''
|
'''
|
||||||
Dynamic Programming
|
Dynamic Programming
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
"""
|
"""
|
||||||
author : Mayank Kumar Jha (mk9440)
|
author : Mayank Kumar Jha (mk9440)
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
from typing import List
|
from typing import List
|
||||||
import time
|
import time
|
||||||
import matplotlib.pyplot as plt
|
import matplotlib.pyplot as plt
|
||||||
@ -10,7 +9,7 @@ def find_max_sub_array(A,low,high):
|
|||||||
if low==high:
|
if low==high:
|
||||||
return low,high,A[low]
|
return low,high,A[low]
|
||||||
else :
|
else :
|
||||||
mid=(low+high)//2
|
mid=(low+high)//2
|
||||||
left_low,left_high,left_sum=find_max_sub_array(A,low,mid)
|
left_low,left_high,left_sum=find_max_sub_array(A,low,mid)
|
||||||
right_low,right_high,right_sum=find_max_sub_array(A,mid+1,high)
|
right_low,right_high,right_sum=find_max_sub_array(A,mid+1,high)
|
||||||
cross_left,cross_right,cross_sum=find_max_cross_sum(A,low,mid,high)
|
cross_left,cross_right,cross_sum=find_max_cross_sum(A,low,mid,high)
|
||||||
@ -30,7 +29,7 @@ def find_max_cross_sum(A,low,mid,high):
|
|||||||
if summ > left_sum:
|
if summ > left_sum:
|
||||||
left_sum=summ
|
left_sum=summ
|
||||||
max_left=i
|
max_left=i
|
||||||
summ=0
|
summ=0
|
||||||
for i in range(mid+1,high+1):
|
for i in range(mid+1,high+1):
|
||||||
summ+=A[i]
|
summ+=A[i]
|
||||||
if summ > right_sum:
|
if summ > right_sum:
|
||||||
@ -40,7 +39,7 @@ def find_max_cross_sum(A,low,mid,high):
|
|||||||
|
|
||||||
def max_sub_array(nums: List[int]) -> int:
|
def max_sub_array(nums: List[int]) -> int:
|
||||||
"""
|
"""
|
||||||
Finds the contiguous subarray (can be empty array)
|
Finds the contiguous subarray (can be empty array)
|
||||||
which has the largest sum and return its sum.
|
which has the largest sum and return its sum.
|
||||||
|
|
||||||
>>> max_sub_array([-2,1,-3,4,-1,2,1,-5,4])
|
>>> max_sub_array([-2,1,-3,4,-1,2,1,-5,4])
|
||||||
@ -50,14 +49,14 @@ def max_sub_array(nums: List[int]) -> int:
|
|||||||
>>> max_sub_array([-1,-2,-3])
|
>>> max_sub_array([-1,-2,-3])
|
||||||
0
|
0
|
||||||
"""
|
"""
|
||||||
best = 0
|
best = 0
|
||||||
current = 0
|
current = 0
|
||||||
for i in nums:
|
for i in nums:
|
||||||
current += i
|
current += i
|
||||||
if current < 0:
|
if current < 0:
|
||||||
current = 0
|
current = 0
|
||||||
best = max(best, current)
|
best = max(best, current)
|
||||||
return best
|
return best
|
||||||
|
|
||||||
if __name__=='__main__':
|
if __name__=='__main__':
|
||||||
inputs=[10,100,1000,10000,50000,100000,200000,300000,400000,500000]
|
inputs=[10,100,1000,10000,50000,100000,200000,300000,400000,500000]
|
||||||
@ -68,8 +67,8 @@ if __name__=='__main__':
|
|||||||
(find_max_sub_array(li,0,len(li)-1))
|
(find_max_sub_array(li,0,len(li)-1))
|
||||||
end=time.time()
|
end=time.time()
|
||||||
tim.append(end-strt)
|
tim.append(end-strt)
|
||||||
print("No of Inputs Time Taken")
|
print("No of Inputs Time Taken")
|
||||||
for i in range(len(inputs)):
|
for i in range(len(inputs)):
|
||||||
print(inputs[i],'\t\t',tim[i])
|
print(inputs[i],'\t\t',tim[i])
|
||||||
plt.plot(inputs,tim)
|
plt.plot(inputs,tim)
|
||||||
plt.xlabel("Number of Inputs");plt.ylabel("Time taken in seconds ")
|
plt.xlabel("Number of Inputs");plt.ylabel("Time taken in seconds ")
|
||||||
@ -77,4 +76,4 @@ if __name__=='__main__':
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
grid = [[0, 1, 0, 0, 0, 0],
|
grid = [[0, 1, 0, 0, 0, 0],
|
||||||
[0, 1, 0, 0, 0, 0],#0 are free path whereas 1's are obstacles
|
[0, 1, 0, 0, 0, 0],#0 are free path whereas 1's are obstacles
|
||||||
[0, 1, 0, 0, 0, 0],
|
[0, 1, 0, 0, 0, 0],
|
||||||
@ -14,13 +12,13 @@ heuristic = [[9, 8, 7, 6, 5, 4],
|
|||||||
[5, 4, 3, 2, 1, 0]]'''
|
[5, 4, 3, 2, 1, 0]]'''
|
||||||
|
|
||||||
init = [0, 0]
|
init = [0, 0]
|
||||||
goal = [len(grid)-1, len(grid[0])-1] #all coordinates are given in format [y,x]
|
goal = [len(grid)-1, len(grid[0])-1] #all coordinates are given in format [y,x]
|
||||||
cost = 1
|
cost = 1
|
||||||
|
|
||||||
#the cost map which pushes the path closer to the goal
|
#the cost map which pushes the path closer to the goal
|
||||||
heuristic = [[0 for row in range(len(grid[0]))] for col in range(len(grid))]
|
heuristic = [[0 for row in range(len(grid[0]))] for col in range(len(grid))]
|
||||||
for i in range(len(grid)):
|
for i in range(len(grid)):
|
||||||
for j in range(len(grid[0])):
|
for j in range(len(grid[0])):
|
||||||
heuristic[i][j] = abs(i - goal[0]) + abs(j - goal[1])
|
heuristic[i][j] = abs(i - goal[0]) + abs(j - goal[1])
|
||||||
if grid[i][j] == 1:
|
if grid[i][j] == 1:
|
||||||
heuristic[i][j] = 99 #added extra penalty in the heuristic map
|
heuristic[i][j] = 99 #added extra penalty in the heuristic map
|
||||||
@ -62,7 +60,7 @@ def search(grid,init,goal,cost,heuristic):
|
|||||||
g = next[1]
|
g = next[1]
|
||||||
f = next[0]
|
f = next[0]
|
||||||
|
|
||||||
|
|
||||||
if x == goal[0] and y == goal[1]:
|
if x == goal[0] and y == goal[1]:
|
||||||
found = True
|
found = True
|
||||||
else:
|
else:
|
||||||
@ -93,10 +91,10 @@ def search(grid,init,goal,cost,heuristic):
|
|||||||
print("ACTION MAP")
|
print("ACTION MAP")
|
||||||
for i in range(len(action)):
|
for i in range(len(action)):
|
||||||
print(action[i])
|
print(action[i])
|
||||||
|
|
||||||
return path
|
return path
|
||||||
|
|
||||||
a = search(grid,init,goal,cost,heuristic)
|
a = search(grid,init,goal,cost,heuristic)
|
||||||
for i in range(len(a)):
|
for i in range(len(a)):
|
||||||
print(a[i])
|
print(a[i])
|
||||||
|
|
||||||
|
@ -1,23 +1,10 @@
|
|||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
try:
|
|
||||||
xrange # Python 2
|
|
||||||
except NameError:
|
|
||||||
xrange = range # Python 3
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# Accept No. of Nodes and edges
|
# Accept No. of Nodes and edges
|
||||||
n, m = map(int, raw_input().split(" "))
|
n, m = map(int, input().split(" "))
|
||||||
|
|
||||||
# Initialising Dictionary of edges
|
# Initialising Dictionary of edges
|
||||||
g = {}
|
g = {}
|
||||||
for i in xrange(n):
|
for i in range(n):
|
||||||
g[i + 1] = []
|
g[i + 1] = []
|
||||||
|
|
||||||
"""
|
"""
|
||||||
@ -25,8 +12,8 @@ if __name__ == "__main__":
|
|||||||
Accepting edges of Unweighted Directed Graphs
|
Accepting edges of Unweighted Directed Graphs
|
||||||
----------------------------------------------------------------------------
|
----------------------------------------------------------------------------
|
||||||
"""
|
"""
|
||||||
for _ in xrange(m):
|
for _ in range(m):
|
||||||
x, y = map(int, raw_input().strip().split(" "))
|
x, y = map(int, input().strip().split(" "))
|
||||||
g[x].append(y)
|
g[x].append(y)
|
||||||
|
|
||||||
"""
|
"""
|
||||||
@ -34,8 +21,8 @@ if __name__ == "__main__":
|
|||||||
Accepting edges of Unweighted Undirected Graphs
|
Accepting edges of Unweighted Undirected Graphs
|
||||||
----------------------------------------------------------------------------
|
----------------------------------------------------------------------------
|
||||||
"""
|
"""
|
||||||
for _ in xrange(m):
|
for _ in range(m):
|
||||||
x, y = map(int, raw_input().strip().split(" "))
|
x, y = map(int, input().strip().split(" "))
|
||||||
g[x].append(y)
|
g[x].append(y)
|
||||||
g[y].append(x)
|
g[y].append(x)
|
||||||
|
|
||||||
@ -44,8 +31,8 @@ if __name__ == "__main__":
|
|||||||
Accepting edges of Weighted Undirected Graphs
|
Accepting edges of Weighted Undirected Graphs
|
||||||
----------------------------------------------------------------------------
|
----------------------------------------------------------------------------
|
||||||
"""
|
"""
|
||||||
for _ in xrange(m):
|
for _ in range(m):
|
||||||
x, y, r = map(int, raw_input().strip().split(" "))
|
x, y, r = map(int, input().strip().split(" "))
|
||||||
g[x].append([y, r])
|
g[x].append([y, r])
|
||||||
g[y].append([x, r])
|
g[y].append([x, r])
|
||||||
|
|
||||||
@ -170,10 +157,10 @@ def topo(G, ind=None, Q=[1]):
|
|||||||
|
|
||||||
|
|
||||||
def adjm():
|
def adjm():
|
||||||
n = raw_input().strip()
|
n = input().strip()
|
||||||
a = []
|
a = []
|
||||||
for i in xrange(n):
|
for i in range(n):
|
||||||
a.append(map(int, raw_input().strip().split()))
|
a.append(map(int, input().strip().split()))
|
||||||
return a, n
|
return a, n
|
||||||
|
|
||||||
|
|
||||||
@ -193,10 +180,10 @@ def adjm():
|
|||||||
def floy(A_and_n):
|
def floy(A_and_n):
|
||||||
(A, n) = A_and_n
|
(A, n) = A_and_n
|
||||||
dist = list(A)
|
dist = list(A)
|
||||||
path = [[0] * n for i in xrange(n)]
|
path = [[0] * n for i in range(n)]
|
||||||
for k in xrange(n):
|
for k in range(n):
|
||||||
for i in xrange(n):
|
for i in range(n):
|
||||||
for j in xrange(n):
|
for j in range(n):
|
||||||
if dist[i][j] > dist[i][k] + dist[k][j]:
|
if dist[i][j] > dist[i][k] + dist[k][j]:
|
||||||
dist[i][j] = dist[i][k] + dist[k][j]
|
dist[i][j] = dist[i][k] + dist[k][j]
|
||||||
path[i][k] = k
|
path[i][k] = k
|
||||||
@ -245,10 +232,10 @@ def prim(G, s):
|
|||||||
|
|
||||||
|
|
||||||
def edglist():
|
def edglist():
|
||||||
n, m = map(int, raw_input().split(" "))
|
n, m = map(int, input().split(" "))
|
||||||
l = []
|
l = []
|
||||||
for i in xrange(m):
|
for i in range(m):
|
||||||
l.append(map(int, raw_input().split(' ')))
|
l.append(map(int, input().split(' ')))
|
||||||
return l, n
|
return l, n
|
||||||
|
|
||||||
|
|
||||||
@ -272,10 +259,10 @@ def krusk(E_and_n):
|
|||||||
break
|
break
|
||||||
print(s)
|
print(s)
|
||||||
x = E.pop()
|
x = E.pop()
|
||||||
for i in xrange(len(s)):
|
for i in range(len(s)):
|
||||||
if x[0] in s[i]:
|
if x[0] in s[i]:
|
||||||
break
|
break
|
||||||
for j in xrange(len(s)):
|
for j in range(len(s)):
|
||||||
if x[1] in s[j]:
|
if x[1] in s[j]:
|
||||||
if i == j:
|
if i == j:
|
||||||
break
|
break
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
def printDist(dist, V):
|
def printDist(dist, V):
|
||||||
print("\nVertex Distance")
|
print("\nVertex Distance")
|
||||||
for i in range(V):
|
for i in range(V):
|
||||||
|
@ -3,8 +3,6 @@
|
|||||||
|
|
||||||
""" Author: OMKAR PATHAK """
|
""" Author: OMKAR PATHAK """
|
||||||
|
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
|
|
||||||
class Graph():
|
class Graph():
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
|
@ -2,7 +2,6 @@
|
|||||||
# encoding=utf8
|
# encoding=utf8
|
||||||
|
|
||||||
""" Author: OMKAR PATHAK """
|
""" Author: OMKAR PATHAK """
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
|
|
||||||
class Graph():
|
class Graph():
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
def printDist(dist, V):
|
def printDist(dist, V):
|
||||||
print("\nVertex Distance")
|
print("\nVertex Distance")
|
||||||
for i in range(V):
|
for i in range(V):
|
||||||
|
@ -2,7 +2,6 @@
|
|||||||
# Author: Shubham Malik
|
# Author: Shubham Malik
|
||||||
# References: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
|
# References: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
|
||||||
|
|
||||||
from __future__ import print_function
|
|
||||||
import math
|
import math
|
||||||
import sys
|
import sys
|
||||||
# For storing the vertex set to retreive node with the lowest distance
|
# For storing the vertex set to retreive node with the lowest distance
|
||||||
|
@ -12,7 +12,6 @@ Constraints
|
|||||||
Note: The tree input will be such that it can always be decomposed into
|
Note: The tree input will be such that it can always be decomposed into
|
||||||
components containing an even number of nodes.
|
components containing an even number of nodes.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
# pylint: disable=invalid-name
|
# pylint: disable=invalid-name
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
|
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
#!/usr/bin/python
|
#!/usr/bin/python
|
||||||
# encoding=utf8
|
# encoding=utf8
|
||||||
|
|
||||||
from __future__ import print_function
|
|
||||||
# Author: OMKAR PATHAK
|
# Author: OMKAR PATHAK
|
||||||
|
|
||||||
# We can use Python's dictionary for constructing the graph.
|
# We can use Python's dictionary for constructing the graph.
|
||||||
|
@ -1,6 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
|
|
||||||
class Graph:
|
class Graph:
|
||||||
|
|
||||||
def __init__(self, vertex):
|
def __init__(self, vertex):
|
||||||
|
@ -4,8 +4,6 @@
|
|||||||
have negative edge weights.
|
have negative edge weights.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
|
|
||||||
def _print_dist(dist, v):
|
def _print_dist(dist, v):
|
||||||
print("\nThe shortest path matrix using Floyd Warshall algorithm\n")
|
print("\nThe shortest path matrix using Floyd Warshall algorithm\n")
|
||||||
@ -34,9 +32,9 @@ def floyd_warshall(graph, v):
|
|||||||
4. The above is repeated for each vertex k in the graph.
|
4. The above is repeated for each vertex k in the graph.
|
||||||
5. Whenever distance[i][j] is given a new minimum value, next vertex[i][j] is updated to the next vertex[i][k].
|
5. Whenever distance[i][j] is given a new minimum value, next vertex[i][j] is updated to the next vertex[i][k].
|
||||||
"""
|
"""
|
||||||
|
|
||||||
dist=[[float('inf') for _ in range(v)] for _ in range(v)]
|
dist=[[float('inf') for _ in range(v)] for _ in range(v)]
|
||||||
|
|
||||||
for i in range(v):
|
for i in range(v):
|
||||||
for j in range(v):
|
for j in range(v):
|
||||||
dist[i][j] = graph[i][j]
|
dist[i][j] = graph[i][j]
|
||||||
@ -53,7 +51,7 @@ def floyd_warshall(graph, v):
|
|||||||
_print_dist(dist, v)
|
_print_dist(dist, v)
|
||||||
return dist, v
|
return dist, v
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if __name__== '__main__':
|
if __name__== '__main__':
|
||||||
v = int(input("Enter number of vertices: "))
|
v = int(input("Enter number of vertices: "))
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
num_nodes, num_edges = list(map(int, input().strip().split()))
|
num_nodes, num_edges = list(map(int, input().strip().split()))
|
||||||
|
|
||||||
|
@ -1,12 +1,6 @@
|
|||||||
from __future__ import print_function
|
|
||||||
import heapq
|
import heapq
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
try:
|
|
||||||
xrange # Python 2
|
|
||||||
except NameError:
|
|
||||||
xrange = range # Python 3
|
|
||||||
|
|
||||||
|
|
||||||
class PriorityQueue:
|
class PriorityQueue:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
@ -96,7 +90,7 @@ def do_something(back_pointer, goal, start):
|
|||||||
grid[(n-1)][0] = "-"
|
grid[(n-1)][0] = "-"
|
||||||
|
|
||||||
|
|
||||||
for i in xrange(n):
|
for i in range(n):
|
||||||
for j in range(n):
|
for j in range(n):
|
||||||
if (i, j) == (0, n-1):
|
if (i, j) == (0, n-1):
|
||||||
print(grid[i][j], end=' ')
|
print(grid[i][j], end=' ')
|
||||||
|
@ -1,6 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
|
|
||||||
def dfs(u):
|
def dfs(u):
|
||||||
global g, r, scc, component, visit, stack
|
global g, r, scc, component, visit, stack
|
||||||
if visit[u]: return
|
if visit[u]: return
|
||||||
|
@ -1,10 +1,4 @@
|
|||||||
"""example of simple chaos machine"""
|
"""example of simple chaos machine"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
try:
|
|
||||||
input = raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
pass # Python 3
|
|
||||||
|
|
||||||
# Chaos Machine (K, t, m)
|
# Chaos Machine (K, t, m)
|
||||||
K = [0.33, 0.44, 0.55, 0.44, 0.33]; t = 3; m = 5
|
K = [0.33, 0.44, 0.55, 0.44, 0.33]; t = 3; m = 5
|
||||||
@ -96,7 +90,7 @@ message = random.sample(range(0xFFFFFFFF), 100)
|
|||||||
for chunk in message:
|
for chunk in message:
|
||||||
push(chunk)
|
push(chunk)
|
||||||
|
|
||||||
# for controlling
|
# for controlling
|
||||||
inp = ""
|
inp = ""
|
||||||
|
|
||||||
# Pulling Data (Output)
|
# Pulling Data (Output)
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
alphabets = [chr(i) for i in range(32, 126)]
|
alphabets = [chr(i) for i in range(32, 126)]
|
||||||
gear_one = [i for i in range(len(alphabets))]
|
gear_one = [i for i in range(len(alphabets))]
|
||||||
gear_two = [i for i in range(len(alphabets))]
|
gear_two = [i for i in range(len(alphabets))]
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
import math
|
import math
|
||||||
|
|
||||||
|
|
||||||
@ -66,7 +65,7 @@ def getBlock(bitString):
|
|||||||
"""[summary]
|
"""[summary]
|
||||||
Iterator:
|
Iterator:
|
||||||
Returns by each call a list of length 16 with the 32 bit
|
Returns by each call a list of length 16 with the 32 bit
|
||||||
integer blocks.
|
integer blocks.
|
||||||
|
|
||||||
Arguments:
|
Arguments:
|
||||||
bitString {[string]} -- [binary string >= 512]
|
bitString {[string]} -- [binary string >= 512]
|
||||||
@ -95,7 +94,7 @@ def not32(i):
|
|||||||
|
|
||||||
def sum32(a, b):
|
def sum32(a, b):
|
||||||
'''
|
'''
|
||||||
|
|
||||||
'''
|
'''
|
||||||
return (a + b) % 2**32
|
return (a + b) % 2**32
|
||||||
|
|
||||||
|
@ -1,10 +1,8 @@
|
|||||||
"""
|
"""
|
||||||
Implementation of a basic regression decision tree.
|
Implementation of a basic regression decision tree.
|
||||||
Input data set: The input data set must be 1-dimensional with continuous labels.
|
Input data set: The input data set must be 1-dimensional with continuous labels.
|
||||||
Output: The decision tree maps a real number input to a real number output.
|
Output: The decision tree maps a real number input to a real number output.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
class Decision_Tree:
|
class Decision_Tree:
|
||||||
@ -19,7 +17,7 @@ class Decision_Tree:
|
|||||||
def mean_squared_error(self, labels, prediction):
|
def mean_squared_error(self, labels, prediction):
|
||||||
"""
|
"""
|
||||||
mean_squared_error:
|
mean_squared_error:
|
||||||
@param labels: a one dimensional numpy array
|
@param labels: a one dimensional numpy array
|
||||||
@param prediction: a floating point value
|
@param prediction: a floating point value
|
||||||
return value: mean_squared_error calculates the error if prediction is used to estimate the labels
|
return value: mean_squared_error calculates the error if prediction is used to estimate the labels
|
||||||
"""
|
"""
|
||||||
@ -32,7 +30,7 @@ class Decision_Tree:
|
|||||||
"""
|
"""
|
||||||
train:
|
train:
|
||||||
@param X: a one dimensional numpy array
|
@param X: a one dimensional numpy array
|
||||||
@param y: a one dimensional numpy array.
|
@param y: a one dimensional numpy array.
|
||||||
The contents of y are the labels for the corresponding X values
|
The contents of y are the labels for the corresponding X values
|
||||||
|
|
||||||
train does not have a return value
|
train does not have a return value
|
||||||
@ -135,6 +133,6 @@ def main():
|
|||||||
print("Predictions: " + str(predictions))
|
print("Predictions: " + str(predictions))
|
||||||
print("Average error: " + str(avg_error))
|
print("Average error: " + str(avg_error))
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
main()
|
main()
|
@ -1,7 +1,6 @@
|
|||||||
"""
|
"""
|
||||||
Implementation of gradient descent algorithm for minimizing cost of a linear hypothesis function.
|
Implementation of gradient descent algorithm for minimizing cost of a linear hypothesis function.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function, division
|
|
||||||
import numpy
|
import numpy
|
||||||
|
|
||||||
# List of input, output pairs
|
# List of input, output pairs
|
||||||
|
@ -17,36 +17,35 @@ Inputs:
|
|||||||
|
|
||||||
Usage:
|
Usage:
|
||||||
1. define 'k' value, 'X' features array and 'hetrogeneity' empty list
|
1. define 'k' value, 'X' features array and 'hetrogeneity' empty list
|
||||||
|
|
||||||
2. create initial_centroids,
|
2. create initial_centroids,
|
||||||
initial_centroids = get_initial_centroids(
|
initial_centroids = get_initial_centroids(
|
||||||
X,
|
X,
|
||||||
k,
|
k,
|
||||||
seed=0 # seed value for initial centroid generation, None for randomness(default=None)
|
seed=0 # seed value for initial centroid generation, None for randomness(default=None)
|
||||||
)
|
)
|
||||||
|
|
||||||
3. find centroids and clusters using kmeans function.
|
3. find centroids and clusters using kmeans function.
|
||||||
|
|
||||||
centroids, cluster_assignment = kmeans(
|
centroids, cluster_assignment = kmeans(
|
||||||
X,
|
X,
|
||||||
k,
|
k,
|
||||||
initial_centroids,
|
initial_centroids,
|
||||||
maxiter=400,
|
maxiter=400,
|
||||||
record_heterogeneity=heterogeneity,
|
record_heterogeneity=heterogeneity,
|
||||||
verbose=True # whether to print logs in console or not.(default=False)
|
verbose=True # whether to print logs in console or not.(default=False)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
4. Plot the loss function, hetrogeneity values for every iteration saved in hetrogeneity list.
|
4. Plot the loss function, hetrogeneity values for every iteration saved in hetrogeneity list.
|
||||||
plot_heterogeneity(
|
plot_heterogeneity(
|
||||||
heterogeneity,
|
heterogeneity,
|
||||||
k
|
k
|
||||||
)
|
)
|
||||||
|
|
||||||
5. Have fun..
|
5. Have fun..
|
||||||
|
|
||||||
'''
|
'''
|
||||||
from __future__ import print_function
|
|
||||||
from sklearn.metrics import pairwise_distances
|
from sklearn.metrics import pairwise_distances
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
@ -57,30 +56,30 @@ def get_initial_centroids(data, k, seed=None):
|
|||||||
if seed is not None: # useful for obtaining consistent results
|
if seed is not None: # useful for obtaining consistent results
|
||||||
np.random.seed(seed)
|
np.random.seed(seed)
|
||||||
n = data.shape[0] # number of data points
|
n = data.shape[0] # number of data points
|
||||||
|
|
||||||
# Pick K indices from range [0, N).
|
# Pick K indices from range [0, N).
|
||||||
rand_indices = np.random.randint(0, n, k)
|
rand_indices = np.random.randint(0, n, k)
|
||||||
|
|
||||||
# Keep centroids as dense format, as many entries will be nonzero due to averaging.
|
# Keep centroids as dense format, as many entries will be nonzero due to averaging.
|
||||||
# As long as at least one document in a cluster contains a word,
|
# As long as at least one document in a cluster contains a word,
|
||||||
# it will carry a nonzero weight in the TF-IDF vector of the centroid.
|
# it will carry a nonzero weight in the TF-IDF vector of the centroid.
|
||||||
centroids = data[rand_indices,:]
|
centroids = data[rand_indices,:]
|
||||||
|
|
||||||
return centroids
|
return centroids
|
||||||
|
|
||||||
def centroid_pairwise_dist(X,centroids):
|
def centroid_pairwise_dist(X,centroids):
|
||||||
return pairwise_distances(X,centroids,metric='euclidean')
|
return pairwise_distances(X,centroids,metric='euclidean')
|
||||||
|
|
||||||
def assign_clusters(data, centroids):
|
def assign_clusters(data, centroids):
|
||||||
|
|
||||||
# Compute distances between each data point and the set of centroids:
|
# Compute distances between each data point and the set of centroids:
|
||||||
# Fill in the blank (RHS only)
|
# Fill in the blank (RHS only)
|
||||||
distances_from_centroids = centroid_pairwise_dist(data,centroids)
|
distances_from_centroids = centroid_pairwise_dist(data,centroids)
|
||||||
|
|
||||||
# Compute cluster assignments for each data point:
|
# Compute cluster assignments for each data point:
|
||||||
# Fill in the blank (RHS only)
|
# Fill in the blank (RHS only)
|
||||||
cluster_assignment = np.argmin(distances_from_centroids,axis=1)
|
cluster_assignment = np.argmin(distances_from_centroids,axis=1)
|
||||||
|
|
||||||
return cluster_assignment
|
return cluster_assignment
|
||||||
|
|
||||||
def revise_centroids(data, k, cluster_assignment):
|
def revise_centroids(data, k, cluster_assignment):
|
||||||
@ -92,23 +91,23 @@ def revise_centroids(data, k, cluster_assignment):
|
|||||||
centroid = member_data_points.mean(axis=0)
|
centroid = member_data_points.mean(axis=0)
|
||||||
new_centroids.append(centroid)
|
new_centroids.append(centroid)
|
||||||
new_centroids = np.array(new_centroids)
|
new_centroids = np.array(new_centroids)
|
||||||
|
|
||||||
return new_centroids
|
return new_centroids
|
||||||
|
|
||||||
def compute_heterogeneity(data, k, centroids, cluster_assignment):
|
def compute_heterogeneity(data, k, centroids, cluster_assignment):
|
||||||
|
|
||||||
heterogeneity = 0.0
|
heterogeneity = 0.0
|
||||||
for i in range(k):
|
for i in range(k):
|
||||||
|
|
||||||
# Select all data points that belong to cluster i. Fill in the blank (RHS only)
|
# Select all data points that belong to cluster i. Fill in the blank (RHS only)
|
||||||
member_data_points = data[cluster_assignment==i, :]
|
member_data_points = data[cluster_assignment==i, :]
|
||||||
|
|
||||||
if member_data_points.shape[0] > 0: # check if i-th cluster is non-empty
|
if member_data_points.shape[0] > 0: # check if i-th cluster is non-empty
|
||||||
# Compute distances from centroid to data points (RHS only)
|
# Compute distances from centroid to data points (RHS only)
|
||||||
distances = pairwise_distances(member_data_points, [centroids[i]], metric='euclidean')
|
distances = pairwise_distances(member_data_points, [centroids[i]], metric='euclidean')
|
||||||
squared_distances = distances**2
|
squared_distances = distances**2
|
||||||
heterogeneity += np.sum(squared_distances)
|
heterogeneity += np.sum(squared_distances)
|
||||||
|
|
||||||
return heterogeneity
|
return heterogeneity
|
||||||
|
|
||||||
from matplotlib import pyplot as plt
|
from matplotlib import pyplot as plt
|
||||||
@ -129,36 +128,36 @@ def kmeans(data, k, initial_centroids, maxiter=500, record_heterogeneity=None, v
|
|||||||
verbose: if True, print how many data points changed their cluster labels in each iteration'''
|
verbose: if True, print how many data points changed their cluster labels in each iteration'''
|
||||||
centroids = initial_centroids[:]
|
centroids = initial_centroids[:]
|
||||||
prev_cluster_assignment = None
|
prev_cluster_assignment = None
|
||||||
|
|
||||||
for itr in range(maxiter):
|
for itr in range(maxiter):
|
||||||
if verbose:
|
if verbose:
|
||||||
print(itr, end='')
|
print(itr, end='')
|
||||||
|
|
||||||
# 1. Make cluster assignments using nearest centroids
|
# 1. Make cluster assignments using nearest centroids
|
||||||
cluster_assignment = assign_clusters(data,centroids)
|
cluster_assignment = assign_clusters(data,centroids)
|
||||||
|
|
||||||
# 2. Compute a new centroid for each of the k clusters, averaging all data points assigned to that cluster.
|
# 2. Compute a new centroid for each of the k clusters, averaging all data points assigned to that cluster.
|
||||||
centroids = revise_centroids(data,k, cluster_assignment)
|
centroids = revise_centroids(data,k, cluster_assignment)
|
||||||
|
|
||||||
# Check for convergence: if none of the assignments changed, stop
|
# Check for convergence: if none of the assignments changed, stop
|
||||||
if prev_cluster_assignment is not None and \
|
if prev_cluster_assignment is not None and \
|
||||||
(prev_cluster_assignment==cluster_assignment).all():
|
(prev_cluster_assignment==cluster_assignment).all():
|
||||||
break
|
break
|
||||||
|
|
||||||
# Print number of new assignments
|
# Print number of new assignments
|
||||||
if prev_cluster_assignment is not None:
|
if prev_cluster_assignment is not None:
|
||||||
num_changed = np.sum(prev_cluster_assignment!=cluster_assignment)
|
num_changed = np.sum(prev_cluster_assignment!=cluster_assignment)
|
||||||
if verbose:
|
if verbose:
|
||||||
print(' {0:5d} elements changed their cluster assignment.'.format(num_changed))
|
print(' {0:5d} elements changed their cluster assignment.'.format(num_changed))
|
||||||
|
|
||||||
# Record heterogeneity convergence metric
|
# Record heterogeneity convergence metric
|
||||||
if record_heterogeneity is not None:
|
if record_heterogeneity is not None:
|
||||||
# YOUR CODE HERE
|
# YOUR CODE HERE
|
||||||
score = compute_heterogeneity(data,k,centroids,cluster_assignment)
|
score = compute_heterogeneity(data,k,centroids,cluster_assignment)
|
||||||
record_heterogeneity.append(score)
|
record_heterogeneity.append(score)
|
||||||
|
|
||||||
prev_cluster_assignment = cluster_assignment[:]
|
prev_cluster_assignment = cluster_assignment[:]
|
||||||
|
|
||||||
return centroids, cluster_assignment
|
return centroids, cluster_assignment
|
||||||
|
|
||||||
# Mock test below
|
# Mock test below
|
||||||
|
@ -7,8 +7,6 @@ We try to set these Feature weights, over many iterations, so that they best
|
|||||||
fits our dataset. In this particular code, i had used a CSGO dataset (ADR vs
|
fits our dataset. In this particular code, i had used a CSGO dataset (ADR vs
|
||||||
Rating). We try to best fit a line through dataset and estimate the parameters.
|
Rating). We try to best fit a line through dataset and estimate the parameters.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
|
@ -8,9 +8,6 @@ method 2:
|
|||||||
"Simpson Rule"
|
"Simpson Rule"
|
||||||
|
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
|
|
||||||
def method_2(boundary, steps):
|
def method_2(boundary, steps):
|
||||||
# "Simpson Rule"
|
# "Simpson Rule"
|
||||||
# int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn)
|
# int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn)
|
||||||
|
@ -7,8 +7,6 @@ method 1:
|
|||||||
"extended trapezoidal rule"
|
"extended trapezoidal rule"
|
||||||
|
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
def method_1(boundary, steps):
|
def method_1(boundary, steps):
|
||||||
# "extended trapezoidal rule"
|
# "extended trapezoidal rule"
|
||||||
# int(f) = dx/2 * (f1 + 2f2 + ... + fn)
|
# int(f) = dx/2 * (f1 + 2f2 + ... + fn)
|
||||||
@ -19,7 +17,7 @@ def method_1(boundary, steps):
|
|||||||
y = 0.0
|
y = 0.0
|
||||||
y += (h/2.0)*f(a)
|
y += (h/2.0)*f(a)
|
||||||
for i in x_i:
|
for i in x_i:
|
||||||
#print(i)
|
#print(i)
|
||||||
y += h*f(i)
|
y += h*f(i)
|
||||||
y += (h/2.0)*f(b)
|
y += (h/2.0)*f(b)
|
||||||
return y
|
return y
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
from __future__ import annotations
|
|
||||||
import datetime
|
import datetime
|
||||||
import argparse
|
import argparse
|
||||||
|
|
||||||
@ -7,7 +6,7 @@ def zeller(date_input: str) -> str:
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
Zellers Congruence Algorithm
|
Zellers Congruence Algorithm
|
||||||
Find the day of the week for nearly any Gregorian or Julian calendar date
|
Find the day of the week for nearly any Gregorian or Julian calendar date
|
||||||
|
|
||||||
>>> zeller('01-31-2010')
|
>>> zeller('01-31-2010')
|
||||||
'Your date 01-31-2010, is a Sunday!'
|
'Your date 01-31-2010, is a Sunday!'
|
||||||
@ -108,7 +107,7 @@ def zeller(date_input: str) -> str:
|
|||||||
# Validate
|
# Validate
|
||||||
if not 0 < d < 32:
|
if not 0 < d < 32:
|
||||||
raise ValueError("Date must be between 1 - 31")
|
raise ValueError("Date must be between 1 - 31")
|
||||||
|
|
||||||
# Get second seperator
|
# Get second seperator
|
||||||
sep_2: str = date_input[5]
|
sep_2: str = date_input[5]
|
||||||
# Validate
|
# Validate
|
||||||
|
@ -13,9 +13,6 @@ Converting to matrix,
|
|||||||
So we just need the n times multiplication of the matrix [1,1],[1,0]].
|
So we just need the n times multiplication of the matrix [1,1],[1,0]].
|
||||||
We can decrease the n times multiplication by following the divide and conquer approach.
|
We can decrease the n times multiplication by following the divide and conquer approach.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
|
|
||||||
def multiply(matrix_a, matrix_b):
|
def multiply(matrix_a, matrix_b):
|
||||||
matrix_c = []
|
matrix_c = []
|
||||||
n = len(matrix_a)
|
n = len(matrix_a)
|
||||||
|
@ -15,8 +15,6 @@
|
|||||||
Date: 2017.9.20
|
Date: 2017.9.20
|
||||||
- - - - - -- - - - - - - - - - - - - - - - - - - - - - -
|
- - - - - -- - - - - - - - - - - - - - - - - - - - - - -
|
||||||
'''
|
'''
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
import pickle
|
import pickle
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import matplotlib.pyplot as plt
|
import matplotlib.pyplot as plt
|
||||||
|
@ -9,8 +9,6 @@
|
|||||||
p2 = 1
|
p2 = 1
|
||||||
|
|
||||||
'''
|
'''
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
import random
|
import random
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
import collections, pprint, time, os
|
import collections, pprint, time, os
|
||||||
|
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
# https://en.wikipedia.org/wiki/Euclidean_algorithm
|
# https://en.wikipedia.org/wiki/Euclidean_algorithm
|
||||||
|
|
||||||
def euclidean_gcd(a, b):
|
def euclidean_gcd(a, b):
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
__author__ = "Tobias Carryer"
|
__author__ = "Tobias Carryer"
|
||||||
|
|
||||||
from time import time
|
from time import time
|
||||||
@ -7,11 +6,11 @@ class LinearCongruentialGenerator(object):
|
|||||||
"""
|
"""
|
||||||
A pseudorandom number generator.
|
A pseudorandom number generator.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__( self, multiplier, increment, modulo, seed=int(time()) ):
|
def __init__( self, multiplier, increment, modulo, seed=int(time()) ):
|
||||||
"""
|
"""
|
||||||
These parameters are saved and used when nextNumber() is called.
|
These parameters are saved and used when nextNumber() is called.
|
||||||
|
|
||||||
modulo is the largest number that can be generated (exclusive). The most
|
modulo is the largest number that can be generated (exclusive). The most
|
||||||
efficent values are powers of 2. 2^32 is a common value.
|
efficent values are powers of 2. 2^32 is a common value.
|
||||||
"""
|
"""
|
||||||
@ -19,7 +18,7 @@ class LinearCongruentialGenerator(object):
|
|||||||
self.increment = increment
|
self.increment = increment
|
||||||
self.modulo = modulo
|
self.modulo = modulo
|
||||||
self.seed = seed
|
self.seed = seed
|
||||||
|
|
||||||
def next_number( self ):
|
def next_number( self ):
|
||||||
"""
|
"""
|
||||||
The smallest number that can be generated is zero.
|
The smallest number that can be generated is zero.
|
||||||
|
@ -13,9 +13,6 @@ The function called is_balanced takes as input a string S which is a sequence of
|
|||||||
returns true if S is nested and false otherwise.
|
returns true if S is nested and false otherwise.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
|
|
||||||
def is_balanced(S):
|
def is_balanced(S):
|
||||||
|
|
||||||
stack = []
|
stack = []
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
"""Password generator allows you to generate a random password of length N."""
|
"""Password generator allows you to generate a random password of length N."""
|
||||||
from __future__ import print_function
|
|
||||||
from random import choice
|
from random import choice
|
||||||
from string import ascii_letters, digits, punctuation
|
from string import ascii_letters, digits, punctuation
|
||||||
|
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
from __future__ import print_function
|
def moveTower(height, fromPole, toPole, withPole):
|
||||||
def moveTower(height, fromPole, toPole, withPole):
|
|
||||||
'''
|
'''
|
||||||
>>> moveTower(3, 'A', 'B', 'C')
|
>>> moveTower(3, 'A', 'B', 'C')
|
||||||
moving disk from A to B
|
moving disk from A to B
|
||||||
|
@ -9,8 +9,6 @@ Given nums = [2, 7, 11, 15], target = 9,
|
|||||||
Because nums[0] + nums[1] = 2 + 7 = 9,
|
Because nums[0] + nums[1] = 2 + 7 = 9,
|
||||||
return [0, 1].
|
return [0, 1].
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
def twoSum(nums, target):
|
def twoSum(nums, target):
|
||||||
"""
|
"""
|
||||||
:type nums: List[int]
|
:type nums: List[int]
|
||||||
@ -20,7 +18,7 @@ def twoSum(nums, target):
|
|||||||
chk_map = {}
|
chk_map = {}
|
||||||
for index, val in enumerate(nums):
|
for index, val in enumerate(nums):
|
||||||
compl = target - val
|
compl = target - val
|
||||||
if compl in chk_map:
|
if compl in chk_map:
|
||||||
indices = [chk_map[compl], index]
|
indices = [chk_map[compl], index]
|
||||||
print(indices)
|
print(indices)
|
||||||
return [indices]
|
return [indices]
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
from __future__ import print_function
|
|
||||||
import pprint, time
|
import pprint, time
|
||||||
|
|
||||||
def getWordPattern(word):
|
def getWordPattern(word):
|
||||||
|
@ -4,17 +4,9 @@ If we list all the natural numbers below 10 that are multiples of 3 or 5,
|
|||||||
we get 3,5,6 and 9. The sum of these multiples is 23.
|
we get 3,5,6 and 9. The sum of these multiples is 23.
|
||||||
Find the sum of all the multiples of 3 or 5 below N.
|
Find the sum of all the multiples of 3 or 5 below N.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
|
|
||||||
def solution(n):
|
def solution(n):
|
||||||
"""Returns the sum of all the multiples of 3 or 5 below n.
|
"""Returns the sum of all the multiples of 3 or 5 below n.
|
||||||
|
|
||||||
>>> solution(3)
|
>>> solution(3)
|
||||||
0
|
0
|
||||||
>>> solution(4)
|
>>> solution(4)
|
||||||
@ -31,4 +23,4 @@ def solution(n):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(solution(int(raw_input().strip())))
|
print(solution(int(input().strip())))
|
||||||
|
@ -4,17 +4,11 @@ If we list all the natural numbers below 10 that are multiples of 3 or 5,
|
|||||||
we get 3,5,6 and 9. The sum of these multiples is 23.
|
we get 3,5,6 and 9. The sum of these multiples is 23.
|
||||||
Find the sum of all the multiples of 3 or 5 below N.
|
Find the sum of all the multiples of 3 or 5 below N.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
|
|
||||||
def solution(n):
|
def solution(n):
|
||||||
"""Returns the sum of all the multiples of 3 or 5 below n.
|
"""Returns the sum of all the multiples of 3 or 5 below n.
|
||||||
|
|
||||||
>>> solution(3)
|
>>> solution(3)
|
||||||
0
|
0
|
||||||
>>> solution(4)
|
>>> solution(4)
|
||||||
@ -36,4 +30,4 @@ def solution(n):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(solution(int(raw_input().strip())))
|
print(solution(int(input().strip())))
|
||||||
|
@ -4,20 +4,12 @@ If we list all the natural numbers below 10 that are multiples of 3 or 5,
|
|||||||
we get 3,5,6 and 9. The sum of these multiples is 23.
|
we get 3,5,6 and 9. The sum of these multiples is 23.
|
||||||
Find the sum of all the multiples of 3 or 5 below N.
|
Find the sum of all the multiples of 3 or 5 below N.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
|
|
||||||
def solution(n):
|
def solution(n):
|
||||||
"""
|
"""
|
||||||
This solution is based on the pattern that the successive numbers in the
|
This solution is based on the pattern that the successive numbers in the
|
||||||
series follow: 0+3,+2,+1,+3,+1,+2,+3.
|
series follow: 0+3,+2,+1,+3,+1,+2,+3.
|
||||||
Returns the sum of all the multiples of 3 or 5 below n.
|
Returns the sum of all the multiples of 3 or 5 below n.
|
||||||
|
|
||||||
>>> solution(3)
|
>>> solution(3)
|
||||||
0
|
0
|
||||||
>>> solution(4)
|
>>> solution(4)
|
||||||
@ -63,4 +55,4 @@ def solution(n):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(solution(int(raw_input().strip())))
|
print(solution(int(input().strip())))
|
||||||
|
@ -4,17 +4,9 @@ If we list all the natural numbers below 10 that are multiples of 3 or 5,
|
|||||||
we get 3,5,6 and 9. The sum of these multiples is 23.
|
we get 3,5,6 and 9. The sum of these multiples is 23.
|
||||||
Find the sum of all the multiples of 3 or 5 below N.
|
Find the sum of all the multiples of 3 or 5 below N.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
|
|
||||||
def solution(n):
|
def solution(n):
|
||||||
"""Returns the sum of all the multiples of 3 or 5 below n.
|
"""Returns the sum of all the multiples of 3 or 5 below n.
|
||||||
|
|
||||||
>>> solution(3)
|
>>> solution(3)
|
||||||
0
|
0
|
||||||
>>> solution(4)
|
>>> solution(4)
|
||||||
@ -50,4 +42,4 @@ def solution(n):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(solution(int(raw_input().strip())))
|
print(solution(int(input().strip())))
|
||||||
|
@ -4,19 +4,13 @@ If we list all the natural numbers below 10 that are multiples of 3 or 5,
|
|||||||
we get 3,5,6 and 9. The sum of these multiples is 23.
|
we get 3,5,6 and 9. The sum of these multiples is 23.
|
||||||
Find the sum of all the multiples of 3 or 5 below N.
|
Find the sum of all the multiples of 3 or 5 below N.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
"""A straightforward pythonic solution using list comprehension"""
|
"""A straightforward pythonic solution using list comprehension"""
|
||||||
|
|
||||||
|
|
||||||
def solution(n):
|
def solution(n):
|
||||||
"""Returns the sum of all the multiples of 3 or 5 below n.
|
"""Returns the sum of all the multiples of 3 or 5 below n.
|
||||||
|
|
||||||
>>> solution(3)
|
>>> solution(3)
|
||||||
0
|
0
|
||||||
>>> solution(4)
|
>>> solution(4)
|
||||||
@ -31,4 +25,4 @@ def solution(n):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(solution(int(raw_input().strip())))
|
print(solution(int(input().strip())))
|
||||||
|
@ -4,17 +4,9 @@ If we list all the natural numbers below 10 that are multiples of 3 or 5,
|
|||||||
we get 3,5,6 and 9. The sum of these multiples is 23.
|
we get 3,5,6 and 9. The sum of these multiples is 23.
|
||||||
Find the sum of all the multiples of 3 or 5 below N.
|
Find the sum of all the multiples of 3 or 5 below N.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
|
|
||||||
def solution(n):
|
def solution(n):
|
||||||
"""Returns the sum of all the multiples of 3 or 5 below n.
|
"""Returns the sum of all the multiples of 3 or 5 below n.
|
||||||
|
|
||||||
>>> solution(3)
|
>>> solution(3)
|
||||||
0
|
0
|
||||||
>>> solution(4)
|
>>> solution(4)
|
||||||
@ -37,4 +29,4 @@ def solution(n):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(solution(int(raw_input().strip())))
|
print(solution(int(input().strip())))
|
||||||
|
@ -9,18 +9,10 @@ By considering the terms in the Fibonacci sequence whose values do not exceed
|
|||||||
n, find the sum of the even-valued terms. e.g. for n=10, we have {2,8}, sum is
|
n, find the sum of the even-valued terms. e.g. for n=10, we have {2,8}, sum is
|
||||||
10.
|
10.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
|
|
||||||
def solution(n):
|
def solution(n):
|
||||||
"""Returns the sum of all fibonacci sequence even elements that are lower
|
"""Returns the sum of all fibonacci sequence even elements that are lower
|
||||||
or equals to n.
|
or equals to n.
|
||||||
|
|
||||||
>>> solution(10)
|
>>> solution(10)
|
||||||
10
|
10
|
||||||
>>> solution(15)
|
>>> solution(15)
|
||||||
@ -44,4 +36,4 @@ def solution(n):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(solution(int(raw_input().strip())))
|
print(solution(int(input().strip())))
|
||||||
|
@ -9,18 +9,10 @@ By considering the terms in the Fibonacci sequence whose values do not exceed
|
|||||||
n, find the sum of the even-valued terms. e.g. for n=10, we have {2,8}, sum is
|
n, find the sum of the even-valued terms. e.g. for n=10, we have {2,8}, sum is
|
||||||
10.
|
10.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
|
|
||||||
def solution(n):
|
def solution(n):
|
||||||
"""Returns the sum of all fibonacci sequence even elements that are lower
|
"""Returns the sum of all fibonacci sequence even elements that are lower
|
||||||
or equals to n.
|
or equals to n.
|
||||||
|
|
||||||
>>> solution(10)
|
>>> solution(10)
|
||||||
[2, 8]
|
[2, 8]
|
||||||
>>> solution(15)
|
>>> solution(15)
|
||||||
@ -42,4 +34,4 @@ def solution(n):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(solution(int(raw_input().strip())))
|
print(solution(int(input().strip())))
|
||||||
|
@ -9,18 +9,10 @@ By considering the terms in the Fibonacci sequence whose values do not exceed
|
|||||||
n, find the sum of the even-valued terms. e.g. for n=10, we have {2,8}, sum is
|
n, find the sum of the even-valued terms. e.g. for n=10, we have {2,8}, sum is
|
||||||
10.
|
10.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
|
|
||||||
def solution(n):
|
def solution(n):
|
||||||
"""Returns the sum of all fibonacci sequence even elements that are lower
|
"""Returns the sum of all fibonacci sequence even elements that are lower
|
||||||
or equals to n.
|
or equals to n.
|
||||||
|
|
||||||
>>> solution(10)
|
>>> solution(10)
|
||||||
10
|
10
|
||||||
>>> solution(15)
|
>>> solution(15)
|
||||||
@ -44,4 +36,4 @@ def solution(n):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(solution(int(raw_input().strip())))
|
print(solution(int(input().strip())))
|
||||||
|
@ -9,20 +9,14 @@ By considering the terms in the Fibonacci sequence whose values do not exceed
|
|||||||
n, find the sum of the even-valued terms. e.g. for n=10, we have {2,8}, sum is
|
n, find the sum of the even-valued terms. e.g. for n=10, we have {2,8}, sum is
|
||||||
10.
|
10.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
import math
|
import math
|
||||||
from decimal import Decimal, getcontext
|
from decimal import Decimal, getcontext
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
|
|
||||||
def solution(n):
|
def solution(n):
|
||||||
"""Returns the sum of all fibonacci sequence even elements that are lower
|
"""Returns the sum of all fibonacci sequence even elements that are lower
|
||||||
or equals to n.
|
or equals to n.
|
||||||
|
|
||||||
>>> solution(10)
|
>>> solution(10)
|
||||||
10
|
10
|
||||||
>>> solution(15)
|
>>> solution(15)
|
||||||
@ -68,4 +62,4 @@ def solution(n):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(solution(int(raw_input().strip())))
|
print(solution(int(input().strip())))
|
||||||
|
@ -5,14 +5,8 @@ of a given number N?
|
|||||||
|
|
||||||
e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17.
|
e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function, division
|
|
||||||
import math
|
import math
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
|
|
||||||
def isprime(no):
|
def isprime(no):
|
||||||
if no == 2:
|
if no == 2:
|
||||||
@ -81,4 +75,4 @@ def solution(n):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(solution(int(raw_input().strip())))
|
print(solution(int(input().strip())))
|
||||||
|
@ -5,12 +5,6 @@ of a given number N?
|
|||||||
|
|
||||||
e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17.
|
e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function, division
|
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
|
|
||||||
def solution(n):
|
def solution(n):
|
||||||
@ -60,4 +54,4 @@ def solution(n):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(solution(int(raw_input().strip())))
|
print(solution(int(input().strip())))
|
||||||
|
@ -6,18 +6,10 @@ the product of two 2-digit numbers is 9009 = 91 x 99.
|
|||||||
Find the largest palindrome made from the product of two 3-digit numbers which
|
Find the largest palindrome made from the product of two 3-digit numbers which
|
||||||
is less than N.
|
is less than N.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
|
|
||||||
def solution(n):
|
def solution(n):
|
||||||
"""Returns the largest palindrome made from the product of two 3-digit
|
"""Returns the largest palindrome made from the product of two 3-digit
|
||||||
numbers which is less than n.
|
numbers which is less than n.
|
||||||
|
|
||||||
>>> solution(20000)
|
>>> solution(20000)
|
||||||
19591
|
19591
|
||||||
>>> solution(30000)
|
>>> solution(30000)
|
||||||
@ -47,4 +39,4 @@ def solution(n):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(solution(int(raw_input().strip())))
|
print(solution(int(input().strip())))
|
||||||
|
@ -6,18 +6,10 @@ the product of two 2-digit numbers is 9009 = 91 x 99.
|
|||||||
Find the largest palindrome made from the product of two 3-digit numbers which
|
Find the largest palindrome made from the product of two 3-digit numbers which
|
||||||
is less than N.
|
is less than N.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
|
|
||||||
def solution(n):
|
def solution(n):
|
||||||
"""Returns the largest palindrome made from the product of two 3-digit
|
"""Returns the largest palindrome made from the product of two 3-digit
|
||||||
numbers which is less than n.
|
numbers which is less than n.
|
||||||
|
|
||||||
>>> solution(20000)
|
>>> solution(20000)
|
||||||
19591
|
19591
|
||||||
>>> solution(30000)
|
>>> solution(30000)
|
||||||
@ -35,4 +27,4 @@ def solution(n):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(solution(int(raw_input().strip())))
|
print(solution(int(input().strip())))
|
||||||
|
@ -6,14 +6,6 @@ to 10 without any remainder.
|
|||||||
What is the smallest positive number that is evenly divisible(divisible with no
|
What is the smallest positive number that is evenly divisible(divisible with no
|
||||||
remainder) by all of the numbers from 1 to N?
|
remainder) by all of the numbers from 1 to N?
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
|
|
||||||
def solution(n):
|
def solution(n):
|
||||||
"""Returns the smallest positive number that is evenly divisible(divisible
|
"""Returns the smallest positive number that is evenly divisible(divisible
|
||||||
with no remainder) by all of the numbers from 1 to n.
|
with no remainder) by all of the numbers from 1 to n.
|
||||||
@ -66,4 +58,4 @@ def solution(n):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(solution(int(raw_input().strip())))
|
print(solution(int(input().strip())))
|
||||||
|
@ -6,13 +6,6 @@ to 10 without any remainder.
|
|||||||
What is the smallest positive number that is evenly divisible(divisible with no
|
What is the smallest positive number that is evenly divisible(divisible with no
|
||||||
remainder) by all of the numbers from 1 to N?
|
remainder) by all of the numbers from 1 to N?
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
""" Euclidean GCD Algorithm """
|
""" Euclidean GCD Algorithm """
|
||||||
|
|
||||||
|
|
||||||
@ -30,7 +23,7 @@ def lcm(x, y):
|
|||||||
def solution(n):
|
def solution(n):
|
||||||
"""Returns the smallest positive number that is evenly divisible(divisible
|
"""Returns the smallest positive number that is evenly divisible(divisible
|
||||||
with no remainder) by all of the numbers from 1 to n.
|
with no remainder) by all of the numbers from 1 to n.
|
||||||
|
|
||||||
>>> solution(10)
|
>>> solution(10)
|
||||||
2520
|
2520
|
||||||
>>> solution(15)
|
>>> solution(15)
|
||||||
@ -47,4 +40,4 @@ def solution(n):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(solution(int(raw_input().strip())))
|
print(solution(int(input().strip())))
|
||||||
|
@ -14,18 +14,10 @@ numbers and the square of the sum is 3025 − 385 = 2640.
|
|||||||
Find the difference between the sum of the squares of the first N natural
|
Find the difference between the sum of the squares of the first N natural
|
||||||
numbers and the square of the sum.
|
numbers and the square of the sum.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
|
|
||||||
def solution(n):
|
def solution(n):
|
||||||
"""Returns the difference between the sum of the squares of the first n
|
"""Returns the difference between the sum of the squares of the first n
|
||||||
natural numbers and the square of the sum.
|
natural numbers and the square of the sum.
|
||||||
|
|
||||||
>>> solution(10)
|
>>> solution(10)
|
||||||
2640
|
2640
|
||||||
>>> solution(15)
|
>>> solution(15)
|
||||||
@ -45,4 +37,4 @@ def solution(n):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(solution(int(raw_input().strip())))
|
print(solution(int(input().strip())))
|
||||||
|
@ -14,18 +14,10 @@ numbers and the square of the sum is 3025 − 385 = 2640.
|
|||||||
Find the difference between the sum of the squares of the first N natural
|
Find the difference between the sum of the squares of the first N natural
|
||||||
numbers and the square of the sum.
|
numbers and the square of the sum.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
|
|
||||||
def solution(n):
|
def solution(n):
|
||||||
"""Returns the difference between the sum of the squares of the first n
|
"""Returns the difference between the sum of the squares of the first n
|
||||||
natural numbers and the square of the sum.
|
natural numbers and the square of the sum.
|
||||||
|
|
||||||
>>> solution(10)
|
>>> solution(10)
|
||||||
2640
|
2640
|
||||||
>>> solution(15)
|
>>> solution(15)
|
||||||
@ -42,4 +34,4 @@ def solution(n):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(solution(int(raw_input().strip())))
|
print(solution(int(input().strip())))
|
||||||
|
@ -14,19 +14,13 @@ numbers and the square of the sum is 3025 − 385 = 2640.
|
|||||||
Find the difference between the sum of the squares of the first N natural
|
Find the difference between the sum of the squares of the first N natural
|
||||||
numbers and the square of the sum.
|
numbers and the square of the sum.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
import math
|
import math
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
|
|
||||||
def solution(n):
|
def solution(n):
|
||||||
"""Returns the difference between the sum of the squares of the first n
|
"""Returns the difference between the sum of the squares of the first n
|
||||||
natural numbers and the square of the sum.
|
natural numbers and the square of the sum.
|
||||||
|
|
||||||
>>> solution(10)
|
>>> solution(10)
|
||||||
2640
|
2640
|
||||||
>>> solution(15)
|
>>> solution(15)
|
||||||
@ -42,4 +36,4 @@ def solution(n):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(solution(int(raw_input().strip())))
|
print(solution(int(input().strip())))
|
||||||
|
@ -6,14 +6,8 @@ By listing the first six prime numbers:
|
|||||||
|
|
||||||
We can see that the 6th prime is 13. What is the Nth prime number?
|
We can see that the 6th prime is 13. What is the Nth prime number?
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
from math import sqrt
|
from math import sqrt
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
|
|
||||||
def isprime(n):
|
def isprime(n):
|
||||||
if n == 2:
|
if n == 2:
|
||||||
@ -30,7 +24,7 @@ def isprime(n):
|
|||||||
|
|
||||||
def solution(n):
|
def solution(n):
|
||||||
"""Returns the n-th prime number.
|
"""Returns the n-th prime number.
|
||||||
|
|
||||||
>>> solution(6)
|
>>> solution(6)
|
||||||
13
|
13
|
||||||
>>> solution(1)
|
>>> solution(1)
|
||||||
@ -58,4 +52,4 @@ def solution(n):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(solution(int(raw_input().strip())))
|
print(solution(int(input().strip())))
|
||||||
|
@ -6,14 +6,6 @@ By listing the first six prime numbers:
|
|||||||
|
|
||||||
We can see that the 6th prime is 13. What is the Nth prime number?
|
We can see that the 6th prime is 13. What is the Nth prime number?
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
|
|
||||||
def isprime(number):
|
def isprime(number):
|
||||||
for i in range(2, int(number ** 0.5) + 1):
|
for i in range(2, int(number ** 0.5) + 1):
|
||||||
if number % i == 0:
|
if number % i == 0:
|
||||||
@ -23,7 +15,7 @@ def isprime(number):
|
|||||||
|
|
||||||
def solution(n):
|
def solution(n):
|
||||||
"""Returns the n-th prime number.
|
"""Returns the n-th prime number.
|
||||||
|
|
||||||
>>> solution(6)
|
>>> solution(6)
|
||||||
13
|
13
|
||||||
>>> solution(1)
|
>>> solution(1)
|
||||||
@ -73,4 +65,4 @@ def solution(n):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(solution(int(raw_input().strip())))
|
print(solution(int(input().strip())))
|
||||||
|
@ -6,15 +6,9 @@ By listing the first six prime numbers:
|
|||||||
|
|
||||||
We can see that the 6th prime is 13. What is the Nth prime number?
|
We can see that the 6th prime is 13. What is the Nth prime number?
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
import math
|
import math
|
||||||
import itertools
|
import itertools
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
|
|
||||||
def primeCheck(number):
|
def primeCheck(number):
|
||||||
if number % 2 == 0 and number > 2:
|
if number % 2 == 0 and number > 2:
|
||||||
@ -32,7 +26,7 @@ def prime_generator():
|
|||||||
|
|
||||||
def solution(n):
|
def solution(n):
|
||||||
"""Returns the n-th prime number.
|
"""Returns the n-th prime number.
|
||||||
|
|
||||||
>>> solution(6)
|
>>> solution(6)
|
||||||
13
|
13
|
||||||
>>> solution(1)
|
>>> solution(1)
|
||||||
@ -50,4 +44,4 @@ def solution(n):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(solution(int(raw_input().strip())))
|
print(solution(int(input().strip())))
|
||||||
|
@ -7,7 +7,6 @@ For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
|
|||||||
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
|
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
|
||||||
Find the product abc.
|
Find the product abc.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
|
|
||||||
def solution():
|
def solution():
|
||||||
@ -17,7 +16,7 @@ def solution():
|
|||||||
1. a < b < c
|
1. a < b < c
|
||||||
2. a**2 + b**2 = c**2
|
2. a**2 + b**2 = c**2
|
||||||
3. a + b + c = 1000
|
3. a + b + c = 1000
|
||||||
|
|
||||||
# The code below has been commented due to slow execution affecting Travis.
|
# The code below has been commented due to slow execution affecting Travis.
|
||||||
# >>> solution()
|
# >>> solution()
|
||||||
# 31875000
|
# 31875000
|
||||||
|
@ -7,14 +7,6 @@ For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
|
|||||||
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
|
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
|
||||||
Find the product abc.
|
Find the product abc.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
try:
|
|
||||||
raw_input # Python 2
|
|
||||||
except NameError:
|
|
||||||
raw_input = input # Python 3
|
|
||||||
|
|
||||||
|
|
||||||
def solution(n):
|
def solution(n):
|
||||||
"""
|
"""
|
||||||
Return the product of a,b,c which are Pythagorean Triplet that satisfies
|
Return the product of a,b,c which are Pythagorean Triplet that satisfies
|
||||||
@ -22,7 +14,7 @@ def solution(n):
|
|||||||
1. a < b < c
|
1. a < b < c
|
||||||
2. a**2 + b**2 = c**2
|
2. a**2 + b**2 = c**2
|
||||||
3. a + b + c = 1000
|
3. a + b + c = 1000
|
||||||
|
|
||||||
>>> solution(1000)
|
>>> solution(1000)
|
||||||
31875000
|
31875000
|
||||||
"""
|
"""
|
||||||
@ -41,4 +33,4 @@ def solution(n):
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(solution(int(raw_input().strip())))
|
print(solution(int(input().strip())))
|
||||||
|
@ -10,9 +10,6 @@ For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
|
|||||||
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
|
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
|
||||||
Find the product abc.
|
Find the product abc.
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
|
|
||||||
def solution():
|
def solution():
|
||||||
"""
|
"""
|
||||||
Returns the product of a,b,c which are Pythagorean Triplet that satisfies
|
Returns the product of a,b,c which are Pythagorean Triplet that satisfies
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user