Simplify code by dropping support for legacy Python (#1143)

* Simplify code by dropping support for legacy Python

* sort() --> sorted()
This commit is contained in:
Christian Clauss 2019-08-19 15:37:49 +02:00 committed by GitHub
parent 32aa7ff081
commit 47a9ea2b0b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
145 changed files with 367 additions and 976 deletions

View File

@ -56,7 +56,7 @@ We want your work to be readable by others; therefore, we encourage you to note
```python
"""
This function sums a and b
This function sums a and b
"""
def sum(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:
```python
input('Enter your input:')
input('Enter your input:')
# 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:
```python
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):
return a + b
# Write tests this way:
print(sumab(1,2)) # 1+2 = 3
print(sumab(6,4)) # 6+4 = 10
print(sumab(1, 2)) # 1+2 = 3
print(sumab(6, 4)) # 6+4 = 10
# Or this way:
print("1 + 2 = ", sumab(1,2)) # 1+2 = 3
print("6 + 4 = ", sumab(6,4)) # 6+4 = 10
print("1 + 2 = ", sumab(1, 2)) # 1+2 = 3
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.
- Avoid importing external libraries for basic algorithms. Only use those libraries for complicated algorithms.

View File

@ -1,4 +1,3 @@
from __future__ import print_function
import sys, random, cryptomath_module as cryptoMath
SYMBOLS = r""" !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""

View File

@ -1,23 +1,15 @@
try: # Python 2
raw_input
unichr
except NameError: # Python 3
raw_input = input
unichr = chr
def Atbash():
def atbash():
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)
if 65 <= extract <= 90:
output += unichr(155-extract)
output += chr(155-extract)
elif 97 <= extract <= 122:
output += unichr(219-extract)
output += chr(219-extract)
else:
output+=i
output += i
print(output)
if __name__ == '__main__':
Atbash()
atbash()

View File

@ -1,4 +1,3 @@
from __future__ import print_function
def decrypt(message):
"""
>>> decrypt('TMDETUX PMDVU')

View File

@ -1,5 +1,3 @@
from __future__ import print_function
import random
@ -15,7 +13,7 @@ class Onepad:
cipher.append(c)
key.append(k)
return cipher, key
def decrypt(self, cipher, key):
'''Function to decrypt text using psedo-random numbers.'''
plain = []

View File

@ -1,4 +1,3 @@
from __future__ import print_function
# Primality Testing with the Rabin-Miller Algorithm
import random

View File

@ -1,4 +1,3 @@
from __future__ import print_function
def dencrypt(s, n):
out = ''
for c in s:

View File

@ -1,4 +1,3 @@
from __future__ import print_function
import sys, rsa_key_generator as rkg, os
DEFAULT_BLOCK_SIZE = 128
@ -16,7 +15,7 @@ def main():
if mode == 'encrypt':
if not os.path.exists('rsa_pubkey.txt'):
rkg.makeKeyFiles('rsa', 1024)
message = input('\nEnter message: ')
pubKeyFilename = 'rsa_pubkey.txt'
print('Encrypting and writing to %s...' % (filename))

View File

@ -1,4 +1,3 @@
from __future__ import print_function
import random, sys, os
import rabin_miller as rabinMiller, cryptomath_module as cryptoMath

View File

@ -1,4 +1,3 @@
from __future__ import print_function
import sys, random
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
@ -18,7 +17,7 @@ def main():
translated = decryptMessage(key, message)
print('\n%sion: \n%s' % (mode.title(), translated))
def checkValidKey(key):
keyList = list(key)
lettersList = list(LETTERS)
@ -49,7 +48,7 @@ def translateMessage(key, message, mode):
if mode == 'decrypt':
charsA, charsB = charsB, charsA
for symbol in message:
if symbol.upper() in charsA:
symIndex = charsA.find(symbol.upper())

View File

@ -1,4 +1,3 @@
from __future__ import print_function
import math
def main():

View File

@ -1,4 +1,3 @@
from __future__ import print_function
import time, os, sys
import transposition_cipher as transCipher
@ -16,7 +15,7 @@ def main():
response = input('> ')
if not response.lower().startswith('y'):
sys.exit()
startTime = time.time()
if mode.lower().startswith('e'):
with open(inputFile) as f:
@ -29,9 +28,9 @@ def main():
with open(outputFile, 'w') as outputObj:
outputObj.write(translated)
totalTime = round(time.time() - startTime, 2)
print(('Done (', totalTime, 'seconds )'))
if __name__ == '__main__':
main()

View File

@ -1,4 +1,3 @@
from __future__ import print_function
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():

View File

@ -1,7 +1,6 @@
'''
A binary search Tree
'''
from __future__ import print_function
class Node:
def __init__(self, label, parent):
@ -66,8 +65,8 @@ class BinarySearchTree:
else:
parent_node.setRight(new_node)
#Set parent to the new node
new_node.setParent(parent_node)
new_node.setParent(parent_node)
def delete(self, label):
if (not self.empty()):
#Look for the node with that label
@ -92,7 +91,7 @@ class BinarySearchTree:
self.delete(tmpNode.getLabel())
#Assigns the value to the node to delete and keesp tree structure
node.setLabel(tmpNode.getLabel())
def getNode(self, label):
curr_node = None
#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
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
def __str__(self):
list = self.__InOrderTraversal(self.root)
@ -203,7 +202,7 @@ def testBinarySearchTree():
/ \ \
1 6 14
/ \ /
4 7 13
4 7 13
'''
r'''
@ -236,11 +235,11 @@ def testBinarySearchTree():
print("The label -1 exists")
else:
print("The label -1 doesn't exist")
if(not t.empty()):
print(("Max Value: ", t.getMax().getLabel()))
print(("Min Value: ", t.getMin().getLabel()))
t.delete(13)
t.delete(10)
t.delete(8)

View File

@ -1,4 +1,3 @@
from __future__ import print_function
class FenwickTree:
def __init__(self, SIZE): # create fenwick tree with size SIZE

View File

@ -1,4 +1,3 @@
from __future__ import print_function
import math
class SegmentTree:

View File

@ -1,4 +1,3 @@
from __future__ import print_function
import math
class SegmentTree:

View File

@ -1,15 +1,8 @@
#!/usr/bin/python
from __future__ import print_function, division
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
#This heap class start from here.
# This heap class start from here.
class Heap:
def __init__(self): #Default constructor of heap class.
def __init__(self): # Default constructor of heap class.
self.h = []
self.currsize = 0
@ -79,7 +72,7 @@ class Heap:
print(self.h)
def main():
l = list(map(int, raw_input().split()))
l = list(map(int, input().split()))
h = Heap()
h.buildHeap(l)
h.heapSort()

View File

@ -4,14 +4,13 @@
- 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.
- 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
def __init__(self):
self.head = None
self.tail = None
def insertHead(self, x):
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
@ -20,52 +19,52 @@ class LinkedList: #making main class named linked list
self.head.previous = newLink # newLink <-- currenthead(head)
newLink.next = self.head # newLink <--> currenthead(head)
self.head = newLink # newLink(head) <--> oldhead
def deleteHead(self):
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
if(self.head is None):
self.tail = None #if empty linked list
return temp
def insertTail(self, x):
newLink = Link(x)
newLink.next = None # currentTail(tail) newLink -->
self.tail.next = newLink # currentTail(tail) --> newLink -->
newLink.previous = self.tail #currentTail(tail) <--> newLink -->
self.tail = newLink # oldTail <--> newLink(tail) -->
def deleteTail(self):
temp = self.tail
self.tail = self.tail.previous # 2ndLast(tail) <--> oldTail --> None
self.tail.next = None # 2ndlast(tail) --> None
return temp
def delete(self, x):
current = self.head
while(current.value != x): # Find the position to delete
current = current.next
if(current == self.head):
self.deleteHead()
elif(current == self.tail):
self.deleteTail()
else: #Before: 1 <--> 2(current) <--> 3
current.previous.next = current.next # 1 --> 3
current.next.previous = current.previous # 1 <--> 3
def isEmpty(self): #Will return True if the list is empty
return(self.head is None)
def display(self): #Prints contents of the list
current = self.head
while(current != None):
current.displayLink()
current = current.next
current = current.next
print()
class Link:

View File

@ -1,6 +1,3 @@
from __future__ import print_function
class Node: # create a Node
def __init__(self, data):
self.data = data # given data
@ -10,7 +7,7 @@ class Node: # create a Node
class Linked_List:
def __init__(self):
self.Head = None # Initialize Head to None
def insert_tail(self, data):
if(self.Head is None): self.insert_head(data) #If this is first node, call insert_head
else:
@ -37,7 +34,7 @@ class Linked_List:
self.Head = self.Head.next
temp.next = None
return temp
def delete_tail(self): # delete from tail
tamp = self.Head
if self.Head != None:
@ -46,7 +43,7 @@ class Linked_List:
else:
while tamp.next.next is not None: # find the 2nd last element
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
def isEmpty(self):
@ -79,7 +76,7 @@ def main():
print("\nPrint List : ")
A.printList()
print("\nInserting 1st at Tail")
a3=input()
a3=input()
A.insert_tail(a3)
print("Inserting 2nd at Tail")
a4=input()
@ -96,6 +93,6 @@ def main():
A.reverse()
print("\nPrint List : ")
A.printList()
if __name__ == '__main__':
main()

View File

@ -1,4 +1,3 @@
from __future__ import print_function
# Python code to demonstrate working of
# extend(), extendleft(), rotate(), reverse()

View File

@ -1,6 +1,3 @@
from __future__ import print_function
from __future__ import absolute_import
from .stack import Stack
__author__ = 'Omkar Pathak'

View File

@ -1,5 +1,3 @@
from __future__ import print_function
from __future__ import absolute_import
import string
from .stack import Stack

View File

@ -1,17 +1,16 @@
from __future__ import print_function
# Function to print element and NGE pair for all elements of list
def printNGE(arr):
for i in range(0, len(arr), 1):
next = -1
for j in range(i+1, len(arr), 1):
if arr[i] < arr[j]:
next = arr[j]
break
print(str(arr[i]) + " -- " + str(next))
# Driver program to test above function
arr = [11,13,21,3]
printNGE(arr)

View File

@ -1,4 +1,3 @@
from __future__ import print_function
__author__ = 'Omkar Pathak'

View File

@ -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
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):
n = len(price)

View File

@ -1,18 +1,16 @@
from __future__ import print_function, absolute_import, division
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
inside P. TH convex hull problem has several applications in geometrical problems,
computer graphics and game development.
inside P. TH convex hull problem has several applications in geometrical problems,
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)
2. A divide-and-conquer algorithm which runs in O(n^3)
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.
"""

View File

@ -1,15 +1,13 @@
from __future__ import print_function, absolute_import, division
"""
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
called inversions. Counting the number of such inversions in an array-like
object is the important. Among other things, counting inversions can help
(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
object is the important. Among other things, counting inversions can help
us determine how close a given array is to being sorted
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.
"""

View File

@ -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
class AssignmentUsingBitmask:
def __init__(self,task_performed,total):
self.total_tasks = total #total no of tasks (N)
# DP table will have a dimension of (2^M)*N
# 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.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
self.finalmask = (1<<len(task_performed)) - 1
def CountWaysUtil(self,mask,taskno):
# if mask == self.finalmask all persons are distributed tasks, return 1
if mask == self.finalmask:
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.
if taskno in self.task:
for p in self.task[taskno]:
# if p is already given a task
if mask & (1<<p):
continue
# 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)
# save the value.
self.dp[mask][taskno] = total_ways_util
return self.dp[mask][taskno]
return self.dp[mask][taskno]
def countNoOfWays(self,task_performed):
@ -67,17 +66,17 @@ class AssignmentUsingBitmask:
for i in range(len(task_performed)):
for j in task_performed[i]:
self.task[j].append(i)
# call the function to fill the DP table, final answer is stored in dp[0][1]
return self.CountWaysUtil(0,1)
if __name__ == '__main__':
total_tasks = 5 #total no of tasks (the value of N)
#the list of tasks that can be done by M persons.
task_performed = [
task_performed = [
[ 1 , 3 , 4 ],
[ 1 , 2 , 5 ],
[ 3 , 4 ]

View File

@ -5,9 +5,6 @@ Can you determine number of ways of making change for n units using
the given types of coins?
https://www.hackerrank.com/challenges/coin-change/problem
"""
from __future__ import print_function
def dp_count(S, m, n):
# table[i] represents the number of ways to get to amount i

View File

@ -7,7 +7,6 @@ This is a pure Python implementation of Dynamic Programming solution to the edit
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.
"""
from __future__ import print_function
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)]
for i in range(m+1):
for j in range(n+1):
if i == 0: #first string is empty
dp[i][j] = j
elif j == 0: #second string is empty
dp[i][j] = i
elif j == 0: #second string is empty
dp[i][j] = i
elif word1[i-1] == word2[j-1]: #last character of both substing is equal
dp[i][j] = dp[i-1][j-1]
else:
else:
insert = dp[i][j-1]
delete = dp[i-1][j]
replace = dp[i-1][j-1]
@ -82,21 +81,13 @@ def min_distance_bottom_up(word1: str, word2: str) -> int:
return dp[m][n]
if __name__ == '__main__':
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
solver = EditDistance()
print("****************** Testing Edit Distance DP Algorithm ******************")
print()
print("Enter the first string: ", end="")
S1 = raw_input().strip()
print("Enter the second string: ", end="")
S2 = raw_input().strip()
S1 = input("Enter the first string: ").strip()
S2 = input("Enter the second string: ").strip()
print()
print("The minimum Edit Distance is: %d" % (solver.solve(S1, S2)))
@ -106,4 +97,4 @@ if __name__ == '__main__':

View File

@ -5,7 +5,6 @@
This program calculates the nth Fibonacci number in O(log(n)).
It's possible to calculate F(1000000) in less than a second.
"""
from __future__ import print_function
import sys

View File

@ -1,7 +1,6 @@
"""
This is a pure Python implementation of Dynamic Programming solution to the fibonacci sequence problem.
"""
from __future__ import print_function
class Fibonacci:
@ -29,21 +28,16 @@ class Fibonacci:
if __name__ == '__main__':
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="")
try:
N = eval(raw_input().strip())
N = int(input().strip())
fib = Fibonacci(N)
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:
print("Enter value: ", end=" ")
try:
i = eval(raw_input().strip())
i = int(input("Enter value: ").strip())
if i < 0:
print("\n********* Good Bye!! ************\n")
break

View File

@ -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
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.
'''
def partition(m):
memo = [[0 for _ in xrange(m)] for _ in xrange(m+1)]
for i in xrange(m+1):
memo = [[0 for _ in range(m)] for _ in range(m+1)]
for i in range(m+1):
memo[i][0] = 1
for n in xrange(m+1):
for k in xrange(1, m):
for n in range(m+1):
for k in range(1, m):
memo[n][k] += memo[n][k-1]
if n-k > 0:
memo[n][k] += memo[n-k-1][k]
@ -33,7 +21,7 @@ if __name__ == '__main__':
if len(sys.argv) == 1:
try:
n = int(raw_input('Enter a number: '))
n = int(input('Enter a number: ').strip())
print(partition(n))
except ValueError:
print('Please enter a number.')

View File

@ -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.
Example:"abc", "abg" are subsequences of "abcdefgh".
"""
from __future__ import print_function
def longest_common_subsequence(x: str, y: str):
@ -80,4 +79,3 @@ if __name__ == '__main__':
assert expected_ln == ln
assert expected_subseq == subseq
print("len =", ln, ", sub-sequence =", subseq)

View File

@ -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.
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
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)
return ARRAY

View File

@ -1,9 +1,8 @@
from __future__ import print_function
#############################
# Author: Aravind Kashyap
# File: lis.py
# 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):
while r-l > 1:
@ -12,30 +11,30 @@ def CeilIndex(v,l,r,key):
r = m
else:
l = m
return r
def LongestIncreasingSubsequenceLength(v):
if(len(v) == 0):
return 0
return 0
tail = [0]*len(v)
length = 1
tail[0] = v[0]
for i in range(1,len(v)):
if v[i] < tail[0]:
tail[0] = v[i]
elif v[i] > tail[length-1]:
tail[length] = v[i]
length += 1
length += 1
else:
tail[CeilIndex(tail,-1,length-1,v[i])] = v[i]
return length
if __name__ == "__main__":
v = [2, 5, 3, 7, 11, 8, 10, 13, 6]

View File

@ -6,7 +6,6 @@ This is a pure Python implementation of Dynamic Programming solution to the long
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.
'''
from __future__ import print_function
class SubArray:

View File

@ -1,5 +1,3 @@
from __future__ import print_function
import sys
'''
Dynamic Programming

View File

@ -1,7 +1,6 @@
"""
author : Mayank Kumar Jha (mk9440)
"""
from __future__ import print_function
from typing import List
import time
import matplotlib.pyplot as plt
@ -10,7 +9,7 @@ def find_max_sub_array(A,low,high):
if low==high:
return low,high,A[low]
else :
mid=(low+high)//2
mid=(low+high)//2
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)
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:
left_sum=summ
max_left=i
summ=0
summ=0
for i in range(mid+1,high+1):
summ+=A[i]
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:
"""
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.
>>> 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])
0
"""
best = 0
current = 0
for i in nums:
current += i
best = 0
current = 0
for i in nums:
current += i
if current < 0:
current = 0
best = max(best, current)
return best
return best
if __name__=='__main__':
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))
end=time.time()
tim.append(end-strt)
print("No of Inputs Time Taken")
for i in range(len(inputs)):
print("No of Inputs Time Taken")
for i in range(len(inputs)):
print(inputs[i],'\t\t',tim[i])
plt.plot(inputs,tim)
plt.xlabel("Number of Inputs");plt.ylabel("Time taken in seconds ")
@ -77,4 +76,4 @@ if __name__=='__main__':

View File

@ -1,5 +1,3 @@
from __future__ import print_function
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],
@ -14,13 +12,13 @@ heuristic = [[9, 8, 7, 6, 5, 4],
[5, 4, 3, 2, 1, 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
#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))]
for i in range(len(grid)):
for j in range(len(grid[0])):
for i in range(len(grid)):
for j in range(len(grid[0])):
heuristic[i][j] = abs(i - goal[0]) + abs(j - goal[1])
if grid[i][j] == 1:
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]
f = next[0]
if x == goal[0] and y == goal[1]:
found = True
else:
@ -93,10 +91,10 @@ def search(grid,init,goal,cost,heuristic):
print("ACTION MAP")
for i in range(len(action)):
print(action[i])
return path
a = search(grid,init,goal,cost,heuristic)
for i in range(len(a)):
print(a[i])
print(a[i])

View File

@ -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__":
# Accept No. of Nodes and edges
n, m = map(int, raw_input().split(" "))
n, m = map(int, input().split(" "))
# Initialising Dictionary of edges
g = {}
for i in xrange(n):
for i in range(n):
g[i + 1] = []
"""
@ -25,8 +12,8 @@ if __name__ == "__main__":
Accepting edges of Unweighted Directed Graphs
----------------------------------------------------------------------------
"""
for _ in xrange(m):
x, y = map(int, raw_input().strip().split(" "))
for _ in range(m):
x, y = map(int, input().strip().split(" "))
g[x].append(y)
"""
@ -34,8 +21,8 @@ if __name__ == "__main__":
Accepting edges of Unweighted Undirected Graphs
----------------------------------------------------------------------------
"""
for _ in xrange(m):
x, y = map(int, raw_input().strip().split(" "))
for _ in range(m):
x, y = map(int, input().strip().split(" "))
g[x].append(y)
g[y].append(x)
@ -44,8 +31,8 @@ if __name__ == "__main__":
Accepting edges of Weighted Undirected Graphs
----------------------------------------------------------------------------
"""
for _ in xrange(m):
x, y, r = map(int, raw_input().strip().split(" "))
for _ in range(m):
x, y, r = map(int, input().strip().split(" "))
g[x].append([y, r])
g[y].append([x, r])
@ -170,10 +157,10 @@ def topo(G, ind=None, Q=[1]):
def adjm():
n = raw_input().strip()
n = input().strip()
a = []
for i in xrange(n):
a.append(map(int, raw_input().strip().split()))
for i in range(n):
a.append(map(int, input().strip().split()))
return a, n
@ -193,10 +180,10 @@ def adjm():
def floy(A_and_n):
(A, n) = A_and_n
dist = list(A)
path = [[0] * n for i in xrange(n)]
for k in xrange(n):
for i in xrange(n):
for j in xrange(n):
path = [[0] * n for i in range(n)]
for k in range(n):
for i in range(n):
for j in range(n):
if dist[i][j] > dist[i][k] + dist[k][j]:
dist[i][j] = dist[i][k] + dist[k][j]
path[i][k] = k
@ -245,10 +232,10 @@ def prim(G, s):
def edglist():
n, m = map(int, raw_input().split(" "))
n, m = map(int, input().split(" "))
l = []
for i in xrange(m):
l.append(map(int, raw_input().split(' ')))
for i in range(m):
l.append(map(int, input().split(' ')))
return l, n
@ -272,10 +259,10 @@ def krusk(E_and_n):
break
print(s)
x = E.pop()
for i in xrange(len(s)):
for i in range(len(s)):
if x[0] in s[i]:
break
for j in xrange(len(s)):
for j in range(len(s)):
if x[1] in s[j]:
if i == j:
break

View File

@ -1,5 +1,3 @@
from __future__ import print_function
def printDist(dist, V):
print("\nVertex Distance")
for i in range(V):

View File

@ -3,8 +3,6 @@
""" Author: OMKAR PATHAK """
from __future__ import print_function
class Graph():
def __init__(self):

View File

@ -2,7 +2,6 @@
# encoding=utf8
""" Author: OMKAR PATHAK """
from __future__ import print_function
class Graph():

View File

@ -1,5 +1,3 @@
from __future__ import print_function
def printDist(dist, V):
print("\nVertex Distance")
for i in range(V):

View File

@ -2,7 +2,6 @@
# Author: Shubham Malik
# References: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
from __future__ import print_function
import math
import sys
# For storing the vertex set to retreive node with the lowest distance

View File

@ -12,7 +12,6 @@ Constraints
Note: The tree input will be such that it can always be decomposed into
components containing an even number of nodes.
"""
from __future__ import print_function
# pylint: disable=invalid-name
from collections import defaultdict

View File

@ -1,7 +1,6 @@
#!/usr/bin/python
# encoding=utf8
from __future__ import print_function
# Author: OMKAR PATHAK
# We can use Python's dictionary for constructing the graph.

View File

@ -1,6 +1,3 @@
from __future__ import print_function
class Graph:
def __init__(self, vertex):

View File

@ -4,8 +4,6 @@
have negative edge weights.
"""
from __future__ import print_function
def _print_dist(dist, v):
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.
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)]
for i in range(v):
for j in range(v):
dist[i][j] = graph[i][j]
@ -53,7 +51,7 @@ def floyd_warshall(graph, v):
_print_dist(dist, v)
return dist, v
if __name__== '__main__':
v = int(input("Enter number of vertices: "))

View File

@ -1,5 +1,3 @@
from __future__ import print_function
if __name__ == "__main__":
num_nodes, num_edges = list(map(int, input().strip().split()))

View File

@ -1,12 +1,6 @@
from __future__ import print_function
import heapq
import numpy as np
try:
xrange # Python 2
except NameError:
xrange = range # Python 3
class PriorityQueue:
def __init__(self):
@ -96,7 +90,7 @@ def do_something(back_pointer, goal, start):
grid[(n-1)][0] = "-"
for i in xrange(n):
for i in range(n):
for j in range(n):
if (i, j) == (0, n-1):
print(grid[i][j], end=' ')

View File

@ -1,6 +1,3 @@
from __future__ import print_function
def dfs(u):
global g, r, scc, component, visit, stack
if visit[u]: return

View File

@ -1,10 +1,4 @@
"""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)
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:
push(chunk)
# for controlling
# for controlling
inp = ""
# Pulling Data (Output)

View File

@ -1,5 +1,3 @@
from __future__ import print_function
alphabets = [chr(i) for i in range(32, 126)]
gear_one = [i for i in range(len(alphabets))]
gear_two = [i for i in range(len(alphabets))]

View File

@ -1,4 +1,3 @@
from __future__ import print_function
import math
@ -66,7 +65,7 @@ def getBlock(bitString):
"""[summary]
Iterator:
Returns by each call a list of length 16 with the 32 bit
integer blocks.
integer blocks.
Arguments:
bitString {[string]} -- [binary string >= 512]
@ -95,7 +94,7 @@ def not32(i):
def sum32(a, b):
'''
'''
return (a + b) % 2**32

View File

@ -1,10 +1,8 @@
"""
Implementation of a basic regression decision tree.
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
class Decision_Tree:
@ -19,7 +17,7 @@ class Decision_Tree:
def mean_squared_error(self, labels, prediction):
"""
mean_squared_error:
@param labels: a one dimensional numpy array
@param labels: a one dimensional numpy array
@param prediction: a floating point value
return value: mean_squared_error calculates the error if prediction is used to estimate the labels
"""
@ -32,7 +30,7 @@ class Decision_Tree:
"""
train:
@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
train does not have a return value
@ -135,6 +133,6 @@ def main():
print("Predictions: " + str(predictions))
print("Average error: " + str(avg_error))
if __name__ == '__main__':
main()

View File

@ -1,7 +1,6 @@
"""
Implementation of gradient descent algorithm for minimizing cost of a linear hypothesis function.
"""
from __future__ import print_function, division
import numpy
# List of input, output pairs

View File

@ -17,36 +17,35 @@ Inputs:
Usage:
1. define 'k' value, 'X' features array and 'hetrogeneity' empty list
2. create initial_centroids,
initial_centroids = get_initial_centroids(
X,
k,
X,
k,
seed=0 # seed value for initial centroid generation, None for randomness(default=None)
)
3. find centroids and clusters using kmeans function.
centroids, cluster_assignment = kmeans(
X,
k,
initial_centroids,
X,
k,
initial_centroids,
maxiter=400,
record_heterogeneity=heterogeneity,
record_heterogeneity=heterogeneity,
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.
plot_heterogeneity(
heterogeneity,
heterogeneity,
k
)
5. Have fun..
'''
from __future__ import print_function
from sklearn.metrics import pairwise_distances
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
np.random.seed(seed)
n = data.shape[0] # number of data points
# Pick K indices from range [0, N).
rand_indices = np.random.randint(0, n, k)
# 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,
# it will carry a nonzero weight in the TF-IDF vector of the centroid.
centroids = data[rand_indices,:]
return centroids
def centroid_pairwise_dist(X,centroids):
return pairwise_distances(X,centroids,metric='euclidean')
def assign_clusters(data, centroids):
# Compute distances between each data point and the set of centroids:
# Fill in the blank (RHS only)
distances_from_centroids = centroid_pairwise_dist(data,centroids)
# Compute cluster assignments for each data point:
# Fill in the blank (RHS only)
cluster_assignment = np.argmin(distances_from_centroids,axis=1)
return 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)
new_centroids.append(centroid)
new_centroids = np.array(new_centroids)
return new_centroids
def compute_heterogeneity(data, k, centroids, cluster_assignment):
heterogeneity = 0.0
for i in range(k):
# Select all data points that belong to cluster i. Fill in the blank (RHS only)
member_data_points = data[cluster_assignment==i, :]
if member_data_points.shape[0] > 0: # check if i-th cluster is non-empty
# Compute distances from centroid to data points (RHS only)
distances = pairwise_distances(member_data_points, [centroids[i]], metric='euclidean')
squared_distances = distances**2
heterogeneity += np.sum(squared_distances)
return heterogeneity
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'''
centroids = initial_centroids[:]
prev_cluster_assignment = None
for itr in range(maxiter):
for itr in range(maxiter):
if verbose:
print(itr, end='')
# 1. Make cluster assignments using nearest 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.
centroids = revise_centroids(data,k, cluster_assignment)
# Check for convergence: if none of the assignments changed, stop
if prev_cluster_assignment is not None and \
(prev_cluster_assignment==cluster_assignment).all():
break
# Print number of new assignments
# Print number of new assignments
if prev_cluster_assignment is not None:
num_changed = np.sum(prev_cluster_assignment!=cluster_assignment)
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
if record_heterogeneity is not None:
# YOUR CODE HERE
score = compute_heterogeneity(data,k,centroids,cluster_assignment)
record_heterogeneity.append(score)
prev_cluster_assignment = cluster_assignment[:]
return centroids, cluster_assignment
# Mock test below

View File

@ -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
Rating). We try to best fit a line through dataset and estimate the parameters.
"""
from __future__ import print_function
import requests
import numpy as np

View File

@ -8,9 +8,6 @@ method 2:
"Simpson Rule"
"""
from __future__ import print_function
def method_2(boundary, steps):
# "Simpson Rule"
# int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn)

View File

@ -7,8 +7,6 @@ method 1:
"extended trapezoidal rule"
"""
from __future__ import print_function
def method_1(boundary, steps):
# "extended trapezoidal rule"
# int(f) = dx/2 * (f1 + 2f2 + ... + fn)
@ -19,7 +17,7 @@ def method_1(boundary, steps):
y = 0.0
y += (h/2.0)*f(a)
for i in x_i:
#print(i)
#print(i)
y += h*f(i)
y += (h/2.0)*f(b)
return y

View File

@ -1,4 +1,3 @@
from __future__ import annotations
import datetime
import argparse
@ -7,7 +6,7 @@ def zeller(date_input: str) -> str:
"""
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')
'Your date 01-31-2010, is a Sunday!'
@ -108,7 +107,7 @@ def zeller(date_input: str) -> str:
# Validate
if not 0 < d < 32:
raise ValueError("Date must be between 1 - 31")
# Get second seperator
sep_2: str = date_input[5]
# Validate

View File

@ -13,9 +13,6 @@ Converting to matrix,
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.
"""
from __future__ import print_function
def multiply(matrix_a, matrix_b):
matrix_c = []
n = len(matrix_a)

View File

@ -15,8 +15,6 @@
Date: 2017.9.20
- - - - - -- - - - - - - - - - - - - - - - - - - - - - -
'''
from __future__ import print_function
import pickle
import numpy as np
import matplotlib.pyplot as plt

View File

@ -9,8 +9,6 @@
p2 = 1
'''
from __future__ import print_function
import random

View File

@ -1,4 +1,3 @@
from __future__ import print_function
import collections, pprint, time, os
start_time = time.time()

View File

@ -1,4 +1,3 @@
from __future__ import print_function
# https://en.wikipedia.org/wiki/Euclidean_algorithm
def euclidean_gcd(a, b):

View File

@ -1,4 +1,3 @@
from __future__ import print_function
__author__ = "Tobias Carryer"
from time import time
@ -7,11 +6,11 @@ class LinearCongruentialGenerator(object):
"""
A pseudorandom number generator.
"""
def __init__( self, multiplier, increment, modulo, seed=int(time()) ):
"""
These parameters are saved and used when nextNumber() is called.
modulo is the largest number that can be generated (exclusive). The most
efficent values are powers of 2. 2^32 is a common value.
"""
@ -19,7 +18,7 @@ class LinearCongruentialGenerator(object):
self.increment = increment
self.modulo = modulo
self.seed = seed
def next_number( self ):
"""
The smallest number that can be generated is zero.

View File

@ -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.
'''
from __future__ import print_function
def is_balanced(S):
stack = []

View File

@ -1,5 +1,4 @@
"""Password generator allows you to generate a random password of length N."""
from __future__ import print_function
from random import choice
from string import ascii_letters, digits, punctuation

View File

@ -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')
moving disk from A to B

View File

@ -9,8 +9,6 @@ Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
"""
from __future__ import print_function
def twoSum(nums, target):
"""
:type nums: List[int]
@ -20,7 +18,7 @@ def twoSum(nums, target):
chk_map = {}
for index, val in enumerate(nums):
compl = target - val
if compl in chk_map:
if compl in chk_map:
indices = [chk_map[compl], index]
print(indices)
return [indices]

View File

@ -1,4 +1,3 @@
from __future__ import print_function
import pprint, time
def getWordPattern(word):

View File

@ -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.
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):
"""Returns the sum of all the multiples of 3 or 5 below n.
>>> solution(3)
0
>>> solution(4)
@ -31,4 +23,4 @@ def solution(n):
if __name__ == "__main__":
print(solution(int(raw_input().strip())))
print(solution(int(input().strip())))

View File

@ -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.
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):
"""Returns the sum of all the multiples of 3 or 5 below n.
>>> solution(3)
0
>>> solution(4)
@ -36,4 +30,4 @@ def solution(n):
if __name__ == "__main__":
print(solution(int(raw_input().strip())))
print(solution(int(input().strip())))

View File

@ -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.
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):
"""
This solution is based on the pattern that the successive numbers in the
series follow: 0+3,+2,+1,+3,+1,+2,+3.
Returns the sum of all the multiples of 3 or 5 below n.
>>> solution(3)
0
>>> solution(4)
@ -63,4 +55,4 @@ def solution(n):
if __name__ == "__main__":
print(solution(int(raw_input().strip())))
print(solution(int(input().strip())))

View File

@ -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.
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):
"""Returns the sum of all the multiples of 3 or 5 below n.
>>> solution(3)
0
>>> solution(4)
@ -50,4 +42,4 @@ def solution(n):
if __name__ == "__main__":
print(solution(int(raw_input().strip())))
print(solution(int(input().strip())))

View File

@ -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.
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"""
def solution(n):
"""Returns the sum of all the multiples of 3 or 5 below n.
>>> solution(3)
0
>>> solution(4)
@ -31,4 +25,4 @@ def solution(n):
if __name__ == "__main__":
print(solution(int(raw_input().strip())))
print(solution(int(input().strip())))

View File

@ -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.
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):
"""Returns the sum of all the multiples of 3 or 5 below n.
>>> solution(3)
0
>>> solution(4)
@ -37,4 +29,4 @@ def solution(n):
if __name__ == "__main__":
print(solution(int(raw_input().strip())))
print(solution(int(input().strip())))

View File

@ -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
10.
"""
from __future__ import print_function
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
def solution(n):
"""Returns the sum of all fibonacci sequence even elements that are lower
or equals to n.
>>> solution(10)
10
>>> solution(15)
@ -44,4 +36,4 @@ def solution(n):
if __name__ == "__main__":
print(solution(int(raw_input().strip())))
print(solution(int(input().strip())))

View File

@ -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
10.
"""
from __future__ import print_function
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
def solution(n):
"""Returns the sum of all fibonacci sequence even elements that are lower
or equals to n.
>>> solution(10)
[2, 8]
>>> solution(15)
@ -42,4 +34,4 @@ def solution(n):
if __name__ == "__main__":
print(solution(int(raw_input().strip())))
print(solution(int(input().strip())))

View File

@ -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
10.
"""
from __future__ import print_function
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
def solution(n):
"""Returns the sum of all fibonacci sequence even elements that are lower
or equals to n.
>>> solution(10)
10
>>> solution(15)
@ -44,4 +36,4 @@ def solution(n):
if __name__ == "__main__":
print(solution(int(raw_input().strip())))
print(solution(int(input().strip())))

View File

@ -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
10.
"""
from __future__ import print_function
import math
from decimal import Decimal, getcontext
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
def solution(n):
"""Returns the sum of all fibonacci sequence even elements that are lower
or equals to n.
>>> solution(10)
10
>>> solution(15)
@ -68,4 +62,4 @@ def solution(n):
if __name__ == "__main__":
print(solution(int(raw_input().strip())))
print(solution(int(input().strip())))

View File

@ -5,14 +5,8 @@ of a given number N?
e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17.
"""
from __future__ import print_function, division
import math
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
def isprime(no):
if no == 2:
@ -81,4 +75,4 @@ def solution(n):
if __name__ == "__main__":
print(solution(int(raw_input().strip())))
print(solution(int(input().strip())))

View File

@ -5,12 +5,6 @@ of a given number N?
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):
@ -60,4 +54,4 @@ def solution(n):
if __name__ == "__main__":
print(solution(int(raw_input().strip())))
print(solution(int(input().strip())))

View File

@ -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
is less than N.
"""
from __future__ import print_function
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
def solution(n):
"""Returns the largest palindrome made from the product of two 3-digit
numbers which is less than n.
>>> solution(20000)
19591
>>> solution(30000)
@ -47,4 +39,4 @@ def solution(n):
if __name__ == "__main__":
print(solution(int(raw_input().strip())))
print(solution(int(input().strip())))

View File

@ -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
is less than N.
"""
from __future__ import print_function
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
def solution(n):
"""Returns the largest palindrome made from the product of two 3-digit
numbers which is less than n.
>>> solution(20000)
19591
>>> solution(30000)
@ -35,4 +27,4 @@ def solution(n):
if __name__ == "__main__":
print(solution(int(raw_input().strip())))
print(solution(int(input().strip())))

View File

@ -6,14 +6,6 @@ to 10 without any remainder.
What is the smallest positive number that is evenly divisible(divisible with no
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):
"""Returns the smallest positive number that is evenly divisible(divisible
with no remainder) by all of the numbers from 1 to n.
@ -66,4 +58,4 @@ def solution(n):
if __name__ == "__main__":
print(solution(int(raw_input().strip())))
print(solution(int(input().strip())))

View File

@ -6,13 +6,6 @@ to 10 without any remainder.
What is the smallest positive number that is evenly divisible(divisible with no
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 """
@ -30,7 +23,7 @@ def lcm(x, y):
def solution(n):
"""Returns the smallest positive number that is evenly divisible(divisible
with no remainder) by all of the numbers from 1 to n.
>>> solution(10)
2520
>>> solution(15)
@ -47,4 +40,4 @@ def solution(n):
if __name__ == "__main__":
print(solution(int(raw_input().strip())))
print(solution(int(input().strip())))

View File

@ -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
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):
"""Returns the difference between the sum of the squares of the first n
natural numbers and the square of the sum.
>>> solution(10)
2640
>>> solution(15)
@ -45,4 +37,4 @@ def solution(n):
if __name__ == "__main__":
print(solution(int(raw_input().strip())))
print(solution(int(input().strip())))

View File

@ -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
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):
"""Returns the difference between the sum of the squares of the first n
natural numbers and the square of the sum.
>>> solution(10)
2640
>>> solution(15)
@ -42,4 +34,4 @@ def solution(n):
if __name__ == "__main__":
print(solution(int(raw_input().strip())))
print(solution(int(input().strip())))

View File

@ -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
numbers and the square of the sum.
"""
from __future__ import print_function
import math
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
def solution(n):
"""Returns the difference between the sum of the squares of the first n
natural numbers and the square of the sum.
>>> solution(10)
2640
>>> solution(15)
@ -42,4 +36,4 @@ def solution(n):
if __name__ == "__main__":
print(solution(int(raw_input().strip())))
print(solution(int(input().strip())))

View File

@ -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?
"""
from __future__ import print_function
from math import sqrt
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
def isprime(n):
if n == 2:
@ -30,7 +24,7 @@ def isprime(n):
def solution(n):
"""Returns the n-th prime number.
>>> solution(6)
13
>>> solution(1)
@ -58,4 +52,4 @@ def solution(n):
if __name__ == "__main__":
print(solution(int(raw_input().strip())))
print(solution(int(input().strip())))

View File

@ -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?
"""
from __future__ import print_function
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
def isprime(number):
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
@ -23,7 +15,7 @@ def isprime(number):
def solution(n):
"""Returns the n-th prime number.
>>> solution(6)
13
>>> solution(1)
@ -73,4 +65,4 @@ def solution(n):
if __name__ == "__main__":
print(solution(int(raw_input().strip())))
print(solution(int(input().strip())))

View File

@ -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?
"""
from __future__ import print_function
import math
import itertools
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
def primeCheck(number):
if number % 2 == 0 and number > 2:
@ -32,7 +26,7 @@ def prime_generator():
def solution(n):
"""Returns the n-th prime number.
>>> solution(6)
13
>>> solution(1)
@ -50,4 +44,4 @@ def solution(n):
if __name__ == "__main__":
print(solution(int(raw_input().strip())))
print(solution(int(input().strip())))

View File

@ -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.
Find the product abc.
"""
from __future__ import print_function
def solution():
@ -17,7 +16,7 @@ def solution():
1. a < b < c
2. a**2 + b**2 = c**2
3. a + b + c = 1000
# The code below has been commented due to slow execution affecting Travis.
# >>> solution()
# 31875000

View File

@ -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.
Find the product abc.
"""
from __future__ import print_function
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
def solution(n):
"""
Return the product of a,b,c which are Pythagorean Triplet that satisfies
@ -22,7 +14,7 @@ def solution(n):
1. a < b < c
2. a**2 + b**2 = c**2
3. a + b + c = 1000
>>> solution(1000)
31875000
"""
@ -41,4 +33,4 @@ def solution(n):
if __name__ == "__main__":
print(solution(int(raw_input().strip())))
print(solution(int(input().strip())))

View File

@ -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.
Find the product abc.
"""
from __future__ import print_function
def solution():
"""
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