mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-01-19 00:37:02 +00:00
Merge pull request #220 from cclauss/modernize-python2-code
Modernize Python 2 code to get ready for Python 3
This commit is contained in:
commit
09cc769660
|
@ -1,4 +1,4 @@
|
||||||
"""
|
"""
|
||||||
File transfer protocol used to send and receive files using FTP server.
|
File transfer protocol used to send and receive files using FTP server.
|
||||||
Use credentials to provide access to the FTP client
|
Use credentials to provide access to the FTP client
|
||||||
|
|
||||||
|
@ -6,29 +6,29 @@
|
||||||
Create a seperate user and provide access to a home directory of the user
|
Create a seperate user and provide access to a home directory of the user
|
||||||
Use login id and password of the user created
|
Use login id and password of the user created
|
||||||
cwd here stands for current working directory
|
cwd here stands for current working directory
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from ftplib import FTP
|
from ftplib import FTP
|
||||||
ftp = FTP('xxx.xxx.x.x') """ Enter the ip address or the domain name here """
|
ftp = FTP('xxx.xxx.x.x') # Enter the ip address or the domain name here
|
||||||
ftp.login(user='username', passwd='password')
|
ftp.login(user='username', passwd='password')
|
||||||
ftp.cwd('/Enter the directory here/')
|
ftp.cwd('/Enter the directory here/')
|
||||||
|
|
||||||
"""
|
"""
|
||||||
The file which will be received via the FTP server
|
The file which will be received via the FTP server
|
||||||
Enter the location of the file where the file is received
|
Enter the location of the file where the file is received
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def ReceiveFile():
|
def ReceiveFile():
|
||||||
FileName = 'example.txt' """ Enter the location of the file """
|
FileName = 'example.txt' """ Enter the location of the file """
|
||||||
LocalFile = open(FileName, 'wb')
|
LocalFile = open(FileName, 'wb')
|
||||||
ftp.retrbinary('RETR ' + filename, LocalFile.write, 1024)
|
ftp.retrbinary('RETR ' + FileName, LocalFile.write, 1024)
|
||||||
ftp.quit()
|
ftp.quit()
|
||||||
LocalFile.close()
|
LocalFile.close()
|
||||||
|
|
||||||
"""
|
"""
|
||||||
The file which will be sent via the FTP server
|
The file which will be sent via the FTP server
|
||||||
The file send will be send to the current working directory
|
The file send will be send to the current working directory
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def SendFile():
|
def SendFile():
|
||||||
FileName = 'example.txt' """ Enter the name of the file """
|
FileName = 'example.txt' """ Enter the name of the file """
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
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
|
||||||
|
@ -89,13 +90,13 @@ def search(grid,init,goal,cost,heuristic):
|
||||||
path = []
|
path = []
|
||||||
for i in range(len(invpath)):
|
for i in range(len(invpath)):
|
||||||
path.append(invpath[len(invpath) - 1 - i])
|
path.append(invpath[len(invpath) - 1 - i])
|
||||||
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,3 +1,15 @@
|
||||||
|
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
|
||||||
|
|
||||||
# Accept No. of Nodes and edges
|
# Accept No. of Nodes and edges
|
||||||
n, m = map(int, raw_input().split(" "))
|
n, m = map(int, raw_input().split(" "))
|
||||||
|
|
||||||
|
@ -48,7 +60,7 @@ for _ in xrange(m):
|
||||||
|
|
||||||
def dfs(G, s):
|
def dfs(G, s):
|
||||||
vis, S = set([s]), [s]
|
vis, S = set([s]), [s]
|
||||||
print s
|
print(s)
|
||||||
while S:
|
while S:
|
||||||
flag = 0
|
flag = 0
|
||||||
for i in G[S[-1]]:
|
for i in G[S[-1]]:
|
||||||
|
@ -56,7 +68,7 @@ def dfs(G, s):
|
||||||
S.append(i)
|
S.append(i)
|
||||||
vis.add(i)
|
vis.add(i)
|
||||||
flag = 1
|
flag = 1
|
||||||
print i
|
print(i)
|
||||||
break
|
break
|
||||||
if not flag:
|
if not flag:
|
||||||
S.pop()
|
S.pop()
|
||||||
|
@ -76,14 +88,14 @@ from collections import deque
|
||||||
|
|
||||||
def bfs(G, s):
|
def bfs(G, s):
|
||||||
vis, Q = set([s]), deque([s])
|
vis, Q = set([s]), deque([s])
|
||||||
print s
|
print(s)
|
||||||
while Q:
|
while Q:
|
||||||
u = Q.popleft()
|
u = Q.popleft()
|
||||||
for v in G[u]:
|
for v in G[u]:
|
||||||
if v not in vis:
|
if v not in vis:
|
||||||
vis.add(v)
|
vis.add(v)
|
||||||
Q.append(v)
|
Q.append(v)
|
||||||
print v
|
print(v)
|
||||||
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
@ -116,7 +128,7 @@ def dijk(G, s):
|
||||||
path[v[0]] = u
|
path[v[0]] = u
|
||||||
for i in dist:
|
for i in dist:
|
||||||
if i != s:
|
if i != s:
|
||||||
print dist[i]
|
print(dist[i])
|
||||||
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
@ -140,7 +152,7 @@ def topo(G, ind=None, Q=[1]):
|
||||||
if len(Q) == 0:
|
if len(Q) == 0:
|
||||||
return
|
return
|
||||||
v = Q.popleft()
|
v = Q.popleft()
|
||||||
print v
|
print(v)
|
||||||
for w in G[v]:
|
for w in G[v]:
|
||||||
ind[w] -= 1
|
ind[w] -= 1
|
||||||
if ind[w] == 0:
|
if ind[w] == 0:
|
||||||
|
@ -175,7 +187,8 @@ def adjm():
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
def floy((A, n)):
|
def floy(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 xrange(n)]
|
||||||
for k in xrange(n):
|
for k in xrange(n):
|
||||||
|
@ -184,7 +197,7 @@ def floy((A, 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
|
||||||
print dist
|
print(dist)
|
||||||
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
@ -246,14 +259,15 @@ def edglist():
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
def krusk((E, n)):
|
def krusk(E_and_n):
|
||||||
# Sort edges on the basis of distance
|
# Sort edges on the basis of distance
|
||||||
|
(E, n) = E_and_n
|
||||||
E.sort(reverse=True, key=lambda x: x[2])
|
E.sort(reverse=True, key=lambda x: x[2])
|
||||||
s = [set([i]) for i in range(1, n + 1)]
|
s = [set([i]) for i in range(1, n + 1)]
|
||||||
while True:
|
while True:
|
||||||
if len(s) == 1:
|
if len(s) == 1:
|
||||||
break
|
break
|
||||||
print s
|
print(s)
|
||||||
x = E.pop()
|
x = E.pop()
|
||||||
for i in xrange(len(s)):
|
for i in xrange(len(s)):
|
||||||
if x[0] in s[i]:
|
if x[0] in s[i]:
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
num_nodes, num_edges = list(map(int,input().split()))
|
num_nodes, num_edges = list(map(int,input().split()))
|
||||||
|
|
||||||
edges = []
|
edges = []
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
# n - no of nodes, m - no of edges
|
# n - no of nodes, m - no of edges
|
||||||
n, m = list(map(int,input().split()))
|
n, m = list(map(int,input().split()))
|
||||||
|
|
||||||
|
|
|
@ -1,8 +1,14 @@
|
||||||
|
from __future__ import print_function
|
||||||
import heapq
|
import heapq
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import math
|
import math
|
||||||
import copy
|
import copy
|
||||||
|
|
||||||
|
try:
|
||||||
|
xrange # Python 2
|
||||||
|
except NameError:
|
||||||
|
xrange = range # Python 3
|
||||||
|
|
||||||
|
|
||||||
class PriorityQueue:
|
class PriorityQueue:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
|
@ -95,22 +101,22 @@ def do_something(back_pointer, goal, start):
|
||||||
for i in xrange(n):
|
for i in xrange(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],
|
print(grid[i][j], end=' ')
|
||||||
print "<-- End position",
|
print("<-- End position", end=' ')
|
||||||
else:
|
else:
|
||||||
print grid[i][j],
|
print(grid[i][j], end=' ')
|
||||||
print
|
print()
|
||||||
print("^")
|
print("^")
|
||||||
print("Start position")
|
print("Start position")
|
||||||
print
|
print()
|
||||||
print("# is an obstacle")
|
print("# is an obstacle")
|
||||||
print("- is the path taken by algorithm")
|
print("- is the path taken by algorithm")
|
||||||
print("PATH TAKEN BY THE ALGORITHM IS:-")
|
print("PATH TAKEN BY THE ALGORITHM IS:-")
|
||||||
x = back_pointer[goal]
|
x = back_pointer[goal]
|
||||||
while x != start:
|
while x != start:
|
||||||
print x,
|
print(x, end=' ')
|
||||||
x = back_pointer[x]
|
x = back_pointer[x]
|
||||||
print x
|
print(x)
|
||||||
quit()
|
quit()
|
||||||
|
|
||||||
def valid(p):
|
def valid(p):
|
||||||
|
@ -239,24 +245,24 @@ def multi_a_star(start, goal, n_hueristic):
|
||||||
expand_state(get_s, 0, visited, g_function, close_list_anchor, close_list_inad, open_list, back_pointer)
|
expand_state(get_s, 0, visited, g_function, close_list_anchor, close_list_inad, open_list, back_pointer)
|
||||||
close_list_anchor.append(get_s)
|
close_list_anchor.append(get_s)
|
||||||
print("No path found to goal")
|
print("No path found to goal")
|
||||||
print
|
print()
|
||||||
for i in range(n-1,-1, -1):
|
for i in range(n-1,-1, -1):
|
||||||
for j in range(n):
|
for j in range(n):
|
||||||
if (j, i) in blocks:
|
if (j, i) in blocks:
|
||||||
print '#',
|
print('#', end=' ')
|
||||||
elif (j, i) in back_pointer:
|
elif (j, i) in back_pointer:
|
||||||
if (j, i) == (n-1, n-1):
|
if (j, i) == (n-1, n-1):
|
||||||
print '*',
|
print('*', end=' ')
|
||||||
else:
|
else:
|
||||||
print '-',
|
print('-', end=' ')
|
||||||
else:
|
else:
|
||||||
print '*',
|
print('*', end=' ')
|
||||||
if (j, i) == (n-1, n-1):
|
if (j, i) == (n-1, n-1):
|
||||||
print '<-- End position',
|
print('<-- End position', end=' ')
|
||||||
print
|
print()
|
||||||
print("^")
|
print("^")
|
||||||
print("Start position")
|
print("Start position")
|
||||||
print
|
print()
|
||||||
print("# is an obstacle")
|
print("# is an obstacle")
|
||||||
print("- is the path taken by algorithm")
|
print("- is the path taken by algorithm")
|
||||||
multi_a_star(start, goal, n_hueristic)
|
multi_a_star(start, goal, n_hueristic)
|
|
@ -15,6 +15,7 @@
|
||||||
Date: 2017.9.20
|
Date: 2017.9.20
|
||||||
- - - - - -- - - - - - - - - - - - - - - - - - - - - - -
|
- - - - - -- - - - - - - - - - - - - - - - - - - - - - -
|
||||||
'''
|
'''
|
||||||
|
from __future__ import print_function
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import matplotlib.pyplot as plt
|
import matplotlib.pyplot as plt
|
||||||
|
@ -192,8 +193,8 @@ class CNN():
|
||||||
def trian(self,patterns,datas_train, datas_teach, n_repeat, error_accuracy,draw_e = bool):
|
def trian(self,patterns,datas_train, datas_teach, n_repeat, error_accuracy,draw_e = bool):
|
||||||
#model traning
|
#model traning
|
||||||
print('----------------------Start Training-------------------------')
|
print('----------------------Start Training-------------------------')
|
||||||
print(' - - Shape: Train_Data ',np.shape(datas_train))
|
print((' - - Shape: Train_Data ',np.shape(datas_train)))
|
||||||
print(' - - Shape: Teach_Data ',np.shape(datas_teach))
|
print((' - - Shape: Teach_Data ',np.shape(datas_teach)))
|
||||||
rp = 0
|
rp = 0
|
||||||
all_mse = []
|
all_mse = []
|
||||||
mse = 10000
|
mse = 10000
|
||||||
|
@ -262,7 +263,7 @@ class CNN():
|
||||||
plt.grid(True, alpha=0.5)
|
plt.grid(True, alpha=0.5)
|
||||||
plt.show()
|
plt.show()
|
||||||
print('------------------Training Complished---------------------')
|
print('------------------Training Complished---------------------')
|
||||||
print(' - - Training epoch: ', rp, ' - - Mse: %.6f' % mse)
|
print((' - - Training epoch: ', rp, ' - - Mse: %.6f' % mse))
|
||||||
if draw_e:
|
if draw_e:
|
||||||
draw_error()
|
draw_error()
|
||||||
return mse
|
return mse
|
||||||
|
@ -271,7 +272,7 @@ class CNN():
|
||||||
#model predict
|
#model predict
|
||||||
produce_out = []
|
produce_out = []
|
||||||
print('-------------------Start Testing-------------------------')
|
print('-------------------Start Testing-------------------------')
|
||||||
print(' - - Shape: Test_Data ',np.shape(datas_test))
|
print((' - - Shape: Test_Data ',np.shape(datas_test)))
|
||||||
for p in range(len(datas_test)):
|
for p in range(len(datas_test)):
|
||||||
data_test = np.asmatrix(datas_test[p])
|
data_test = np.asmatrix(datas_test[p])
|
||||||
data_focus1, data_conved1 = self.convolute(data_test, self.conv1, self.w_conv1,
|
data_focus1, data_conved1 = self.convolute(data_test, self.conv1, self.w_conv1,
|
||||||
|
|
|
@ -9,6 +9,7 @@
|
||||||
p2 = 1
|
p2 = 1
|
||||||
|
|
||||||
'''
|
'''
|
||||||
|
from __future__ import print_function
|
||||||
|
|
||||||
import random
|
import random
|
||||||
|
|
||||||
|
@ -52,7 +53,7 @@ class Perceptron:
|
||||||
epoch_count = epoch_count + 1
|
epoch_count = epoch_count + 1
|
||||||
# if you want controle the epoch or just by erro
|
# if you want controle the epoch or just by erro
|
||||||
if erro == False:
|
if erro == False:
|
||||||
print('\nEpoch:\n',epoch_count)
|
print(('\nEpoch:\n',epoch_count))
|
||||||
print('------------------------\n')
|
print('------------------------\n')
|
||||||
#if epoch_count > self.epoch_number or not erro:
|
#if epoch_count > self.epoch_number or not erro:
|
||||||
break
|
break
|
||||||
|
@ -66,10 +67,10 @@ class Perceptron:
|
||||||
y = self.sign(u)
|
y = self.sign(u)
|
||||||
|
|
||||||
if y == -1:
|
if y == -1:
|
||||||
print('Sample: ', sample)
|
print(('Sample: ', sample))
|
||||||
print('classification: P1')
|
print('classification: P1')
|
||||||
else:
|
else:
|
||||||
print('Sample: ', sample)
|
print(('Sample: ', sample))
|
||||||
print('classification: P2')
|
print('classification: P2')
|
||||||
|
|
||||||
def sign(self, u):
|
def sign(self, u):
|
||||||
|
|
|
@ -4,9 +4,14 @@ 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
|
||||||
n = int(raw_input().strip())
|
n = int(raw_input().strip())
|
||||||
sum=0
|
sum=0
|
||||||
for a in range(3,n):
|
for a in range(3,n):
|
||||||
if(a%3==0 or a%5==0):
|
if(a%3==0 or a%5==0):
|
||||||
sum+=a
|
sum+=a
|
||||||
print sum
|
print(sum)
|
||||||
|
|
|
@ -4,6 +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
|
||||||
n = int(raw_input().strip())
|
n = int(raw_input().strip())
|
||||||
sum = 0
|
sum = 0
|
||||||
terms = (n-1)/3
|
terms = (n-1)/3
|
||||||
|
@ -12,4 +17,4 @@ terms = (n-1)/5
|
||||||
sum+= ((terms)*(10+(terms-1)*5))/2
|
sum+= ((terms)*(10+(terms-1)*5))/2
|
||||||
terms = (n-1)/15
|
terms = (n-1)/15
|
||||||
sum-= ((terms)*(30+(terms-1)*15))/2
|
sum-= ((terms)*(30+(terms-1)*15))/2
|
||||||
print sum
|
print(sum)
|
||||||
|
|
|
@ -7,6 +7,11 @@ Find the sum of all the multiples of 3 or 5 below N.
|
||||||
'''
|
'''
|
||||||
This solution is based on the pattern that the successive numbers in the series follow: 0+3,+2,+1,+3,+1,+2,+3.
|
This solution is based on the pattern that the successive numbers in the series follow: 0+3,+2,+1,+3,+1,+2,+3.
|
||||||
'''
|
'''
|
||||||
|
from __future__ import print_function
|
||||||
|
try:
|
||||||
|
raw_input # Python 2
|
||||||
|
except NameError:
|
||||||
|
raw_input = input # Python 3
|
||||||
n = int(raw_input().strip())
|
n = int(raw_input().strip())
|
||||||
sum=0
|
sum=0
|
||||||
num=0
|
num=0
|
||||||
|
@ -39,4 +44,5 @@ while(1):
|
||||||
if(num>=n):
|
if(num>=n):
|
||||||
break
|
break
|
||||||
sum+=num
|
sum+=num
|
||||||
print sum
|
|
||||||
|
print(sum);
|
||||||
|
|
|
@ -6,6 +6,12 @@ the first 10 terms will be:
|
||||||
By considering the terms in the Fibonacci sequence whose values do not exceed n, find the sum of the even-valued terms.
|
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.
|
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
|
||||||
|
|
||||||
n = int(raw_input().strip())
|
n = int(raw_input().strip())
|
||||||
i=1
|
i=1
|
||||||
|
@ -17,4 +23,4 @@ while(j<=n):
|
||||||
temp=i
|
temp=i
|
||||||
i=j
|
i=j
|
||||||
j=temp+i
|
j=temp+i
|
||||||
print sum
|
print(sum)
|
||||||
|
|
|
@ -3,6 +3,7 @@ Problem:
|
||||||
The prime factors of 13195 are 5,7,13 and 29. What is the largest prime factor of a given number N?
|
The prime factors of 13195 are 5,7,13 and 29. What is the largest prime factor 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
|
||||||
|
|
||||||
import math
|
import math
|
||||||
|
|
||||||
|
@ -20,12 +21,12 @@ def isprime(no):
|
||||||
maxNumber = 0
|
maxNumber = 0
|
||||||
n=int(input())
|
n=int(input())
|
||||||
if(isprime(n)):
|
if(isprime(n)):
|
||||||
print n
|
print(n)
|
||||||
else:
|
else:
|
||||||
while (n%2==0):
|
while (n%2==0):
|
||||||
n=n/2
|
n=n/2
|
||||||
if(isprime(n)):
|
if(isprime(n)):
|
||||||
print n
|
print(n)
|
||||||
else:
|
else:
|
||||||
n1 = int(math.sqrt(n))+1
|
n1 = int(math.sqrt(n))+1
|
||||||
for i in range(3,n1,2):
|
for i in range(3,n1,2):
|
||||||
|
@ -35,4 +36,4 @@ else:
|
||||||
break
|
break
|
||||||
elif(isprime(i)):
|
elif(isprime(i)):
|
||||||
maxNumber = i
|
maxNumber = i
|
||||||
print maxNumber
|
print(maxNumber)
|
||||||
|
|
|
@ -3,6 +3,7 @@ Problem:
|
||||||
The prime factors of 13195 are 5,7,13 and 29. What is the largest prime factor of a given number N?
|
The prime factors of 13195 are 5,7,13 and 29. What is the largest prime factor 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
|
||||||
n=int(input())
|
n=int(input())
|
||||||
prime=1
|
prime=1
|
||||||
i=2
|
i=2
|
||||||
|
@ -13,4 +14,4 @@ while(i*i<=n):
|
||||||
i+=1
|
i+=1
|
||||||
if(n>1):
|
if(n>1):
|
||||||
prime=n
|
prime=n
|
||||||
print prime
|
print(prime)
|
||||||
|
|
|
@ -3,6 +3,7 @@ Problem:
|
||||||
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99.
|
A palindromic number reads the same both ways. The largest palindrome made from 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.
|
Find the largest palindrome made from the product of two 3-digit numbers which is less than N.
|
||||||
'''
|
'''
|
||||||
|
from __future__ import print_function
|
||||||
limit = int(input("limit? "))
|
limit = int(input("limit? "))
|
||||||
|
|
||||||
# fetchs the next number
|
# fetchs the next number
|
||||||
|
@ -22,7 +23,7 @@ for number in range(limit-1,10000,-1):
|
||||||
|
|
||||||
if((number % divisor == 0) and (len(str(number / divisor)) == 3)):
|
if((number % divisor == 0) and (len(str(number / divisor)) == 3)):
|
||||||
|
|
||||||
print number
|
print(number)
|
||||||
exit(0)
|
exit(0)
|
||||||
|
|
||||||
divisor -=1
|
divisor -=1
|
|
@ -3,6 +3,7 @@ Problem:
|
||||||
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99.
|
A palindromic number reads the same both ways. The largest palindrome made from 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.
|
Find the largest palindrome made from the product of two 3-digit numbers which is less than N.
|
||||||
'''
|
'''
|
||||||
|
from __future__ import print_function
|
||||||
arr = []
|
arr = []
|
||||||
for i in range(999,100,-1):
|
for i in range(999,100,-1):
|
||||||
for j in range(999,100,-1):
|
for j in range(999,100,-1):
|
||||||
|
@ -14,5 +15,5 @@ arr.sort()
|
||||||
n=int(input())
|
n=int(input())
|
||||||
for i in arr[::-1]:
|
for i in arr[::-1]:
|
||||||
if(i<n):
|
if(i<n):
|
||||||
print i
|
print(i)
|
||||||
exit(0)
|
exit(0)
|
|
@ -3,6 +3,7 @@ Problem:
|
||||||
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
|
2520 is the smallest number that can be divided by each of the numbers from 1 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?
|
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
|
||||||
|
|
||||||
n = int(input())
|
n = int(input())
|
||||||
i = 0
|
i = 0
|
||||||
|
@ -16,5 +17,5 @@ while 1:
|
||||||
if(nfound==0):
|
if(nfound==0):
|
||||||
if(i==0):
|
if(i==0):
|
||||||
i=1
|
i=1
|
||||||
print i
|
print(i)
|
||||||
break
|
break
|
|
@ -8,6 +8,7 @@ The square of the sum of the first ten natural numbers is,
|
||||||
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
|
Hence the difference between the sum of the squares of the first ten natural 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.
|
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
|
||||||
|
|
||||||
suma = 0
|
suma = 0
|
||||||
sumb = 0
|
sumb = 0
|
||||||
|
@ -16,4 +17,4 @@ for i in range(1,n+1):
|
||||||
suma += i**2
|
suma += i**2
|
||||||
sumb += i
|
sumb += i
|
||||||
sum = sumb**2 - suma
|
sum = sumb**2 - suma
|
||||||
print sum
|
print(sum)
|
|
@ -8,8 +8,9 @@ The square of the sum of the first ten natural numbers is,
|
||||||
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
|
Hence the difference between the sum of the squares of the first ten natural 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.
|
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
|
||||||
n = int(input())
|
n = int(input())
|
||||||
suma = n*(n+1)/2
|
suma = n*(n+1)/2
|
||||||
suma **= 2
|
suma **= 2
|
||||||
sumb = n*(n+1)*(2*n+1)/6
|
sumb = n*(n+1)*(2*n+1)/6
|
||||||
print suma-sumb
|
print(suma-sumb)
|
|
@ -3,6 +3,7 @@ By listing the first six prime numbers:
|
||||||
2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
|
2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
|
||||||
What is the Nth prime number?
|
What is the Nth prime number?
|
||||||
'''
|
'''
|
||||||
|
from __future__ import print_function
|
||||||
from math import sqrt
|
from math import sqrt
|
||||||
def isprime(n):
|
def isprime(n):
|
||||||
if (n==2):
|
if (n==2):
|
||||||
|
@ -26,4 +27,4 @@ while(i!=n):
|
||||||
j+=2
|
j+=2
|
||||||
if(isprime(j)):
|
if(isprime(j)):
|
||||||
i+=1
|
i+=1
|
||||||
print j
|
print(j)
|
|
@ -2,6 +2,7 @@
|
||||||
Problem Statement:
|
Problem Statement:
|
||||||
Work out the first ten digits of the sum of the N 50-digit numbers.
|
Work out the first ten digits of the sum of the N 50-digit numbers.
|
||||||
'''
|
'''
|
||||||
|
from __future__ import print_function
|
||||||
|
|
||||||
n = int(input().strip())
|
n = int(input().strip())
|
||||||
|
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
largest_number = 0
|
largest_number = 0
|
||||||
pre_counter = 0
|
pre_counter = 0
|
||||||
|
|
||||||
|
@ -17,4 +18,4 @@ for input1 in range(750000,1000000):
|
||||||
largest_number = input1
|
largest_number = input1
|
||||||
pre_counter = counter
|
pre_counter = counter
|
||||||
|
|
||||||
print('Largest Number:',largest_number,'->',pre_counter,'digits')
|
print(('Largest Number:',largest_number,'->',pre_counter,'digits'))
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
# Program to find the product of a,b,c which are Pythagorean Triplet that satisfice the following:
|
# Program to find the product of a,b,c which are Pythagorean Triplet that satisfice the following:
|
||||||
# 1. a < b < c
|
# 1. a < b < c
|
||||||
# 2. a**2 + b**2 = c**2
|
# 2. a**2 + b**2 = c**2
|
||||||
|
@ -10,5 +11,5 @@ for a in range(300):
|
||||||
if(a < b < c):
|
if(a < b < c):
|
||||||
if((a**2) + (b**2) == (c**2)):
|
if((a**2) + (b**2) == (c**2)):
|
||||||
if((a+b+c) == 1000):
|
if((a+b+c) == 1000):
|
||||||
print("Product of",a,"*",b,"*",c,"=",(a*b*c))
|
print(("Product of",a,"*",b,"*",c,"=",(a*b*c)))
|
||||||
break
|
break
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
import sys, random, cryptomath_module as cryptoMath
|
import sys, random, cryptomath_module as cryptoMath
|
||||||
|
|
||||||
SYMBOLS = """ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""
|
SYMBOLS = """ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
def decrypt(message):
|
def decrypt(message):
|
||||||
"""
|
"""
|
||||||
>>> decrypt('TMDETUX PMDVU')
|
>>> decrypt('TMDETUX PMDVU')
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
# The Caesar Cipher Algorithm
|
# The Caesar Cipher Algorithm
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
|
@ -12,9 +13,9 @@ def main():
|
||||||
|
|
||||||
translated = encdec(message, key, mode)
|
translated = encdec(message, key, mode)
|
||||||
if mode == "encrypt":
|
if mode == "encrypt":
|
||||||
print("Encryption:", translated)
|
print(("Encryption:", translated))
|
||||||
elif mode == "decrypt":
|
elif mode == "decrypt":
|
||||||
print("Decryption:", translated)
|
print(("Decryption:", translated))
|
||||||
|
|
||||||
def encdec(message, key, mode):
|
def encdec(message, key, mode):
|
||||||
message = message.upper()
|
message = message.upper()
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
# Primality Testing with the Rabin-Miller Algorithm
|
# Primality Testing with the Rabin-Miller Algorithm
|
||||||
|
|
||||||
import random
|
import random
|
||||||
|
@ -59,5 +60,5 @@ def generateLargePrime(keysize = 1024):
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
num = generateLargePrime()
|
num = generateLargePrime()
|
||||||
print('Prime number:', num)
|
print(('Prime number:', num))
|
||||||
print('isPrime:', isPrime(num))
|
print(('isPrime:', isPrime(num)))
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
def dencrypt(s, n):
|
def dencrypt(s, n):
|
||||||
out = ''
|
out = ''
|
||||||
for c in s:
|
for c in s:
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
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
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
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,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
import sys, random
|
import sys, random
|
||||||
|
|
||||||
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
import math
|
import math
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
import time, os, sys
|
import time, os, sys
|
||||||
import transposition_cipher as transCipher
|
import transposition_cipher as transCipher
|
||||||
|
|
||||||
|
@ -29,7 +30,7 @@ def main():
|
||||||
outputObj.close()
|
outputObj.close()
|
||||||
|
|
||||||
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,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
'''
|
'''
|
||||||
A AVL tree
|
A AVL tree
|
||||||
'''
|
'''
|
||||||
|
from __future__ import print_function
|
||||||
|
|
||||||
|
|
||||||
class Node:
|
class Node:
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
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,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
import math
|
import math
|
||||||
|
|
||||||
class SegmentTree:
|
class SegmentTree:
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
import math
|
import math
|
||||||
|
|
||||||
class SegmentTree:
|
class SegmentTree:
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
'''
|
'''
|
||||||
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):
|
||||||
|
@ -237,8 +238,8 @@ def testBinarySearchTree():
|
||||||
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)
|
||||||
|
|
|
@ -1,3 +1,5 @@
|
||||||
|
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):
|
||||||
|
|
|
@ -1,4 +1,6 @@
|
||||||
# Author: OMKAR PATHAK
|
# Author: OMKAR PATHAK
|
||||||
|
from __future__ import print_function
|
||||||
|
|
||||||
|
|
||||||
class Graph():
|
class Graph():
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
|
|
|
@ -1,4 +1,6 @@
|
||||||
# Author: OMKAR PATHAK
|
# Author: OMKAR PATHAK
|
||||||
|
from __future__ import print_function
|
||||||
|
|
||||||
|
|
||||||
class Graph():
|
class Graph():
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
|
|
||||||
def printDist(dist, V):
|
def printDist(dist, V):
|
||||||
print("\nVertex Distance")
|
print("\nVertex Distance")
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
|
|
||||||
def printDist(dist, V):
|
def printDist(dist, V):
|
||||||
print("\nThe shortest path matrix using Floyd Warshall algorithm\n")
|
print("\nThe shortest path matrix using Floyd Warshall algorithm\n")
|
||||||
|
@ -7,7 +8,7 @@ def printDist(dist, V):
|
||||||
print(int(dist[i][j]),end = "\t")
|
print(int(dist[i][j]),end = "\t")
|
||||||
else:
|
else:
|
||||||
print("INF",end="\t")
|
print("INF",end="\t")
|
||||||
print();
|
print()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -29,19 +30,19 @@ def FloydWarshall(graph, V):
|
||||||
|
|
||||||
|
|
||||||
#MAIN
|
#MAIN
|
||||||
V = int(input("Enter number of vertices: "));
|
V = int(input("Enter number of vertices: "))
|
||||||
E = int(input("Enter number of edges: "));
|
E = int(input("Enter number of edges: "))
|
||||||
|
|
||||||
graph = [[float('inf') for i in range(V)] for j in range(V)]
|
graph = [[float('inf') for i in range(V)] for j in range(V)]
|
||||||
|
|
||||||
for i in range(V):
|
for i in range(V):
|
||||||
graph[i][i] = 0.0;
|
graph[i][i] = 0.0
|
||||||
|
|
||||||
for i in range(E):
|
for i in range(E):
|
||||||
print("\nEdge ",i+1)
|
print("\nEdge ",i+1)
|
||||||
src = int(input("Enter source:"))
|
src = int(input("Enter source:"))
|
||||||
dst = int(input("Enter destination:"))
|
dst = int(input("Enter destination:"))
|
||||||
weight = float(input("Enter weight:"))
|
weight = float(input("Enter weight:"))
|
||||||
graph[src][dst] = weight;
|
graph[src][dst] = weight
|
||||||
|
|
||||||
FloydWarshall(graph, V)
|
FloydWarshall(graph, V)
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
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
|
||||||
|
@ -15,7 +16,7 @@ class AdjacencyList(object):
|
||||||
|
|
||||||
def printList(self):
|
def printList(self):
|
||||||
for i in self.List:
|
for i in self.List:
|
||||||
print(i,'->',' -> '.join([str(j) for j in self.List[i]]))
|
print((i,'->',' -> '.join([str(j) for j in self.List[i]])))
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
al = AdjacencyList()
|
al = AdjacencyList()
|
||||||
|
|
|
@ -1,3 +1,6 @@
|
||||||
|
from __future__ import print_function
|
||||||
|
|
||||||
|
|
||||||
class Graph:
|
class Graph:
|
||||||
def __init__(self, vertex):
|
def __init__(self, vertex):
|
||||||
self.vertex = vertex
|
self.vertex = vertex
|
||||||
|
|
|
@ -1,3 +1,6 @@
|
||||||
|
from __future__ import print_function
|
||||||
|
|
||||||
|
|
||||||
class Graph:
|
class Graph:
|
||||||
|
|
||||||
def __init__(self, vertex):
|
def __init__(self, vertex):
|
||||||
|
|
|
@ -2,6 +2,7 @@
|
||||||
# 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,6 +12,7 @@ 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
|
||||||
|
|
||||||
|
@ -66,4 +67,4 @@ if __name__ == '__main__':
|
||||||
tree[u].append(v)
|
tree[u].append(v)
|
||||||
tree[v].append(u)
|
tree[v].append(u)
|
||||||
even_tree()
|
even_tree()
|
||||||
print len(cuts) - 1
|
print(len(cuts) - 1)
|
||||||
|
|
|
@ -1,5 +1,12 @@
|
||||||
#!/usr/bin/python
|
#!/usr/bin/python
|
||||||
|
|
||||||
|
from __future__ import print_function
|
||||||
|
|
||||||
|
try:
|
||||||
|
raw_input # Python 2
|
||||||
|
except NameError:
|
||||||
|
raw_input = input # Python 3
|
||||||
|
|
||||||
class Heap:
|
class Heap:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.h = []
|
self.h = []
|
||||||
|
@ -68,10 +75,10 @@ class Heap:
|
||||||
curr = curr/2
|
curr = curr/2
|
||||||
|
|
||||||
def display(self):
|
def display(self):
|
||||||
print (self.h)
|
print(self.h)
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
l = list(map(int,raw_input().split()))
|
l = list(map(int, raw_input().split()))
|
||||||
h = Heap()
|
h = Heap()
|
||||||
h.buildHeap(l)
|
h.buildHeap(l)
|
||||||
h.heapSort()
|
h.heapSort()
|
||||||
|
|
|
@ -3,6 +3,9 @@
|
||||||
- This is an example of a double ended, doubly linked list.
|
- This is an example of a double ended, doubly linked list.
|
||||||
- Each link references the next link and the previous one.
|
- Each link references the next link and the previous one.
|
||||||
'''
|
'''
|
||||||
|
from __future__ import print_function
|
||||||
|
|
||||||
|
|
||||||
class LinkedList:
|
class LinkedList:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.head = None
|
self.head = None
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
class Node:#create a Node
|
class Node:#create a Node
|
||||||
def __int__(self,data):
|
def __int__(self,data):
|
||||||
self.data=data#given data
|
self.data=data#given data
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
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,4 +1,6 @@
|
||||||
from Stack import Stack
|
from __future__ import print_function
|
||||||
|
from __future__ import absolute_import
|
||||||
|
from .Stack import Stack
|
||||||
|
|
||||||
__author__ = 'Omkar Pathak'
|
__author__ = 'Omkar Pathak'
|
||||||
|
|
||||||
|
|
|
@ -1,6 +1,8 @@
|
||||||
|
from __future__ import print_function
|
||||||
|
from __future__ import absolute_import
|
||||||
import string
|
import string
|
||||||
|
|
||||||
from Stack import Stack
|
from .Stack import Stack
|
||||||
|
|
||||||
__author__ = 'Omkar Pathak'
|
__author__ = 'Omkar Pathak'
|
||||||
|
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
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):
|
||||||
|
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
__author__ = 'Omkar Pathak'
|
__author__ = 'Omkar Pathak'
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -1,4 +1,5 @@
|
||||||
from union_find import UnionFind
|
from __future__ import absolute_import
|
||||||
|
from .union_find import UnionFind
|
||||||
import unittest
|
import unittest
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -5,6 +5,7 @@ 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 = [0] * (n + 1)
|
table = [0] * (n + 1)
|
||||||
|
|
||||||
|
@ -21,5 +22,5 @@ def dp_count(S, m, n):
|
||||||
return table[n]
|
return table[n]
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
print dp_count([1, 2, 3], 3, 4) # answer 4
|
print(dp_count([1, 2, 3], 3, 4)) # answer 4
|
||||||
print dp_count([2, 5, 3, 6], 4, 10) # answer 5
|
print(dp_count([2, 5, 3, 6], 4, 10)) # answer 5
|
||||||
|
|
|
@ -7,6 +7,8 @@ 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:
|
||||||
"""
|
"""
|
||||||
|
@ -51,11 +53,10 @@ class EditDistance:
|
||||||
return self.__solveDP(len(A)-1, len(B)-1)
|
return self.__solveDP(len(A)-1, len(B)-1)
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
import sys
|
try:
|
||||||
if sys.version_info.major < 3:
|
raw_input # Python 2
|
||||||
input_function = raw_input
|
except NameError:
|
||||||
else:
|
raw_input = input # Python 3
|
||||||
input_function = input
|
|
||||||
|
|
||||||
solver = EditDistance()
|
solver = EditDistance()
|
||||||
|
|
||||||
|
@ -63,10 +64,10 @@ if __name__ == '__main__':
|
||||||
print()
|
print()
|
||||||
|
|
||||||
print("Enter the first string: ", end="")
|
print("Enter the first string: ", end="")
|
||||||
S1 = input_function()
|
S1 = raw_input().strip()
|
||||||
|
|
||||||
print("Enter the second string: ", end="")
|
print("Enter the second string: ", end="")
|
||||||
S2 = input_function()
|
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)))
|
||||||
|
|
|
@ -2,6 +2,7 @@
|
||||||
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,6 +1,7 @@
|
||||||
"""
|
"""
|
||||||
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:
|
||||||
|
@ -27,26 +28,22 @@ class Fibonacci:
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
import sys
|
|
||||||
|
|
||||||
print("\n********* Fibonacci Series Using Dynamic Programming ************\n")
|
print("\n********* Fibonacci Series Using Dynamic Programming ************\n")
|
||||||
# For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
|
try:
|
||||||
# otherwise 2.x's input builtin function is too "smart"
|
raw_input # Python 2
|
||||||
if sys.version_info.major < 3:
|
except NameError:
|
||||||
input_function = raw_input
|
raw_input = input # Python 3
|
||||||
else:
|
|
||||||
input_function = input
|
|
||||||
|
|
||||||
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(input())
|
N = eval(raw_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=" ")
|
print("Enter value: ", end=" ")
|
||||||
try:
|
try:
|
||||||
i = eval(input())
|
i = eval(raw_input().strip())
|
||||||
if i < 0:
|
if i < 0:
|
||||||
print("\n********* Good Bye!! ************\n")
|
print("\n********* Good Bye!! ************\n")
|
||||||
break
|
break
|
||||||
|
|
|
@ -3,6 +3,13 @@ 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 continious.
|
A subsequence is a sequence that appears in the same relative order, but not necessarily continious.
|
||||||
Example:"abc", "abg" are subsequences of "abcdefgh".
|
Example:"abc", "abg" are subsequences of "abcdefgh".
|
||||||
"""
|
"""
|
||||||
|
from __future__ import print_function
|
||||||
|
|
||||||
|
try:
|
||||||
|
xrange # Python 2
|
||||||
|
except NameError:
|
||||||
|
xrange = range # Python 3
|
||||||
|
|
||||||
def lcs_dp(x, y):
|
def lcs_dp(x, y):
|
||||||
# find the length of strings
|
# find the length of strings
|
||||||
m = len(x)
|
m = len(x)
|
||||||
|
@ -27,4 +34,4 @@ def lcs_dp(x, y):
|
||||||
if __name__=='__main__':
|
if __name__=='__main__':
|
||||||
x = 'AGGTAB'
|
x = 'AGGTAB'
|
||||||
y = 'GXTXAYB'
|
y = 'GXTXAYB'
|
||||||
print lcs_dp(x, y)
|
print(lcs_dp(x, y))
|
||||||
|
|
|
@ -7,6 +7,7 @@ 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
|
||||||
|
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
#############################
|
#############################
|
||||||
# Author: Aravind Kashyap
|
# Author: Aravind Kashyap
|
||||||
# File: lis.py
|
# File: lis.py
|
||||||
|
@ -37,4 +38,4 @@ def LongestIncreasingSubsequenceLength(v):
|
||||||
|
|
||||||
|
|
||||||
v = [2, 5, 3, 7, 11, 8, 10, 13, 6]
|
v = [2, 5, 3, 7, 11, 8, 10, 13, 6]
|
||||||
print LongestIncreasingSubsequenceLength(v)
|
print(LongestIncreasingSubsequenceLength(v))
|
||||||
|
|
|
@ -6,6 +6,7 @@ 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:
|
||||||
|
@ -13,7 +14,7 @@ class SubArray:
|
||||||
def __init__(self, arr):
|
def __init__(self, arr):
|
||||||
# we need a list not a string, so do something to change the type
|
# we need a list not a string, so do something to change the type
|
||||||
self.array = arr.split(',')
|
self.array = arr.split(',')
|
||||||
print("the input array is:", self.array)
|
print(("the input array is:", self.array))
|
||||||
|
|
||||||
def solve_sub_array(self):
|
def solve_sub_array(self):
|
||||||
rear = [int(self.array[0])]*len(self.array)
|
rear = [int(self.array[0])]*len(self.array)
|
||||||
|
@ -28,5 +29,5 @@ if __name__ == '__main__':
|
||||||
whole_array = input("please input some numbers:")
|
whole_array = input("please input some numbers:")
|
||||||
array = SubArray(whole_array)
|
array = SubArray(whole_array)
|
||||||
re = array.solve_sub_array()
|
re = array.solve_sub_array()
|
||||||
print("the results is:", re)
|
print(("the results is:", re))
|
||||||
|
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
"""
|
"""
|
||||||
author : Mayank Kumar Jha (mk9440)
|
author : Mayank Kumar Jha (mk9440)
|
||||||
"""
|
"""
|
||||||
|
from __future__ import print_function
|
||||||
|
|
||||||
import time
|
import time
|
||||||
import matplotlib.pyplot as plt
|
import matplotlib.pyplot as plt
|
||||||
|
@ -49,7 +50,7 @@ if __name__=='__main__':
|
||||||
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 ")
|
||||||
plt.show()
|
plt.show()
|
||||||
|
|
|
@ -1,4 +1,5 @@
|
||||||
"""example of simple chaos machine"""
|
"""example of simple chaos machine"""
|
||||||
|
from __future__ import print_function
|
||||||
|
|
||||||
# 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
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
import math
|
import math
|
||||||
|
|
||||||
def rearrange(bitString32):
|
def rearrange(bitString32):
|
||||||
|
|
|
@ -3,6 +3,7 @@ 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
|
||||||
|
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
"""
|
"""
|
||||||
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
|
||||||
import numpy
|
import numpy
|
||||||
|
|
||||||
# List of input, output pairs
|
# List of input, output pairs
|
||||||
|
@ -106,13 +107,13 @@ def run_gradient_descent():
|
||||||
atol=absolute_error_limit, rtol=relative_error_limit):
|
atol=absolute_error_limit, rtol=relative_error_limit):
|
||||||
break
|
break
|
||||||
parameter_vector = temp_parameter_vector
|
parameter_vector = temp_parameter_vector
|
||||||
print("Number of iterations:", j)
|
print(("Number of iterations:", j))
|
||||||
|
|
||||||
|
|
||||||
def test_gradient_descent():
|
def test_gradient_descent():
|
||||||
for i in range(len(test_data)):
|
for i in range(len(test_data)):
|
||||||
print("Actual output value:", output(i, 'test'))
|
print(("Actual output value:", output(i, 'test')))
|
||||||
print("Hypothesis output:", calculate_hypothesis_value(i, 'test'))
|
print(("Hypothesis output:", calculate_hypothesis_value(i, 'test')))
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|
|
@ -46,6 +46,7 @@ Usage:
|
||||||
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
|
||||||
|
|
||||||
|
|
|
@ -7,6 +7,7 @@ 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
|
||||||
|
|
|
@ -9,6 +9,7 @@
|
||||||
p2 = 1
|
p2 = 1
|
||||||
|
|
||||||
'''
|
'''
|
||||||
|
from __future__ import print_function
|
||||||
|
|
||||||
import random
|
import random
|
||||||
|
|
||||||
|
@ -52,7 +53,7 @@ class Perceptron:
|
||||||
epoch_count = epoch_count + 1
|
epoch_count = epoch_count + 1
|
||||||
# if you want controle the epoch or just by erro
|
# if you want controle the epoch or just by erro
|
||||||
if erro == False:
|
if erro == False:
|
||||||
print('\nEpoch:\n',epoch_count)
|
print(('\nEpoch:\n',epoch_count))
|
||||||
print('------------------------\n')
|
print('------------------------\n')
|
||||||
#if epoch_count > self.epoch_number or not erro:
|
#if epoch_count > self.epoch_number or not erro:
|
||||||
break
|
break
|
||||||
|
@ -66,10 +67,10 @@ class Perceptron:
|
||||||
y = self.sign(u)
|
y = self.sign(u)
|
||||||
|
|
||||||
if y == -1:
|
if y == -1:
|
||||||
print('Sample: ', sample)
|
print(('Sample: ', sample))
|
||||||
print('classification: P1')
|
print('classification: P1')
|
||||||
else:
|
else:
|
||||||
print('Sample: ', sample)
|
print(('Sample: ', sample))
|
||||||
print('classification: P2')
|
print('classification: P2')
|
||||||
|
|
||||||
def sign(self, u):
|
def sign(self, u):
|
||||||
|
|
|
@ -2,6 +2,9 @@
|
||||||
-The sieve of Eratosthenes is an algorithm used to find prime numbers, less than or equal to a given value.
|
-The sieve of Eratosthenes is an algorithm used to find prime numbers, less than or equal to a given value.
|
||||||
-Illustration: https://upload.wikimedia.org/wikipedia/commons/b/b9/Sieve_of_Eratosthenes_animation.gif
|
-Illustration: https://upload.wikimedia.org/wikipedia/commons/b/b9/Sieve_of_Eratosthenes_animation.gif
|
||||||
'''
|
'''
|
||||||
|
from __future__ import print_function
|
||||||
|
|
||||||
|
|
||||||
from math import sqrt
|
from math import sqrt
|
||||||
def SOE(n):
|
def SOE(n):
|
||||||
check = round(sqrt(n)) #Need not check for multiples past the square root of n
|
check = round(sqrt(n)) #Need not check for multiples past the square root of n
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
__author__ = "Tobias Carryer"
|
__author__ = "Tobias Carryer"
|
||||||
|
|
||||||
from time import time
|
from time import time
|
||||||
|
@ -31,4 +32,4 @@ if __name__ == "__main__":
|
||||||
# Show the LCG in action.
|
# Show the LCG in action.
|
||||||
lcg = LinearCongruentialGenerator(1664525, 1013904223, 2<<31)
|
lcg = LinearCongruentialGenerator(1664525, 1013904223, 2<<31)
|
||||||
while True :
|
while True :
|
||||||
print lcg.next_number()
|
print(lcg.next_number())
|
|
@ -1,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
import collections, pprint, time, os
|
import collections, pprint, time, os
|
||||||
|
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
|
@ -25,4 +26,4 @@ with open('anagrams.txt', 'w') as file:
|
||||||
file.write(pprint.pformat(all_anagrams))
|
file.write(pprint.pformat(all_anagrams))
|
||||||
|
|
||||||
total_time = round(time.time() - start_time, 2)
|
total_time = round(time.time() - start_time, 2)
|
||||||
print('Done [', total_time, 'seconds ]')
|
print(('Done [', total_time, 'seconds ]'))
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
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):
|
||||||
|
|
|
@ -13,6 +13,7 @@ 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):
|
||||||
|
@ -39,10 +40,10 @@ def main():
|
||||||
S = input("Enter sequence of brackets: ")
|
S = input("Enter sequence of brackets: ")
|
||||||
|
|
||||||
if is_balanced(S):
|
if is_balanced(S):
|
||||||
print(S, "is balanced")
|
print((S, "is balanced"))
|
||||||
|
|
||||||
else:
|
else:
|
||||||
print(S, "is not balanced")
|
print((S, "is not balanced"))
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
import string
|
import string
|
||||||
import random
|
import random
|
||||||
|
|
||||||
|
|
|
@ -1,3 +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')
|
||||||
|
@ -15,7 +16,7 @@ def moveTower(height, fromPole, toPole, withPole):
|
||||||
moveTower(height-1, withPole, toPole, fromPole)
|
moveTower(height-1, withPole, toPole, fromPole)
|
||||||
|
|
||||||
def moveDisk(fp,tp):
|
def moveDisk(fp,tp):
|
||||||
print('moving disk from', fp, 'to', tp)
|
print(('moving disk from', fp, 'to', tp))
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
height = int(input('Height of hanoi: '))
|
height = int(input('Height of hanoi: '))
|
||||||
|
|
|
@ -9,6 +9,7 @@ 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):
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
import pprint, time
|
import pprint, time
|
||||||
|
|
||||||
def getWordPattern(word):
|
def getWordPattern(word):
|
||||||
|
@ -32,7 +33,7 @@ def main():
|
||||||
fo.write(pprint.pformat(allPatterns))
|
fo.write(pprint.pformat(allPatterns))
|
||||||
|
|
||||||
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()
|
||||||
|
|
|
@ -12,6 +12,11 @@ python binary_search.py
|
||||||
from __future__ import print_function
|
from __future__ import print_function
|
||||||
import bisect
|
import bisect
|
||||||
|
|
||||||
|
try:
|
||||||
|
raw_input # Python 2
|
||||||
|
except NameError:
|
||||||
|
raw_input = input # Python 3
|
||||||
|
|
||||||
|
|
||||||
def binary_search(sorted_collection, item):
|
def binary_search(sorted_collection, item):
|
||||||
"""Pure implementation of binary search algorithm in Python
|
"""Pure implementation of binary search algorithm in Python
|
||||||
|
@ -137,23 +142,14 @@ def __assert_sorted(collection):
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
import sys
|
import sys
|
||||||
# For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
|
user_input = raw_input('Enter numbers separated by comma:\n').strip()
|
||||||
# otherwise 2.x's input builtin function is too "smart"
|
|
||||||
if sys.version_info.major < 3:
|
|
||||||
input_function = raw_input
|
|
||||||
else:
|
|
||||||
input_function = input
|
|
||||||
|
|
||||||
user_input = input_function('Enter numbers separated by comma:\n')
|
|
||||||
collection = [int(item) for item in user_input.split(',')]
|
collection = [int(item) for item in user_input.split(',')]
|
||||||
try:
|
try:
|
||||||
__assert_sorted(collection)
|
__assert_sorted(collection)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
sys.exit('Sequence must be sorted to apply binary search')
|
sys.exit('Sequence must be sorted to apply binary search')
|
||||||
|
|
||||||
target_input = input_function(
|
target_input = raw_input('Enter a single number to be found in the list:\n')
|
||||||
'Enter a single number to be found in the list:\n'
|
|
||||||
)
|
|
||||||
target = int(target_input)
|
target = int(target_input)
|
||||||
result = binary_search(collection, target)
|
result = binary_search(collection, target)
|
||||||
if result is not None:
|
if result is not None:
|
||||||
|
|
|
@ -4,6 +4,11 @@ This is pure python implementation of interpolation search algorithm
|
||||||
from __future__ import print_function
|
from __future__ import print_function
|
||||||
import bisect
|
import bisect
|
||||||
|
|
||||||
|
try:
|
||||||
|
raw_input # Python 2
|
||||||
|
except NameError:
|
||||||
|
raw_input = input # Python 3
|
||||||
|
|
||||||
|
|
||||||
def interpolation_search(sorted_collection, item):
|
def interpolation_search(sorted_collection, item):
|
||||||
"""Pure implementation of interpolation search algorithm in Python
|
"""Pure implementation of interpolation search algorithm in Python
|
||||||
|
@ -77,23 +82,15 @@ def __assert_sorted(collection):
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
import sys
|
import sys
|
||||||
# For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
|
|
||||||
# otherwise 2.x's input builtin function is too "smart"
|
|
||||||
if sys.version_info.major < 3:
|
|
||||||
input_function = raw_input
|
|
||||||
else:
|
|
||||||
input_function = input
|
|
||||||
|
|
||||||
user_input = input_function('Enter numbers separated by comma:\n')
|
user_input = raw_input('Enter numbers separated by comma:\n').strip()
|
||||||
collection = [int(item) for item in user_input.split(',')]
|
collection = [int(item) for item in user_input.split(',')]
|
||||||
try:
|
try:
|
||||||
__assert_sorted(collection)
|
__assert_sorted(collection)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
sys.exit('Sequence must be sorted to apply interpolation search')
|
sys.exit('Sequence must be sorted to apply interpolation search')
|
||||||
|
|
||||||
target_input = input_function(
|
target_input = raw_input('Enter a single number to be found in the list:\n')
|
||||||
'Enter a single number to be found in the list:\n'
|
|
||||||
)
|
|
||||||
target = int(target_input)
|
target = int(target_input)
|
||||||
result = interpolation_search(collection, target)
|
result = interpolation_search(collection, target)
|
||||||
if result is not None:
|
if result is not None:
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
import math
|
import math
|
||||||
def jump_search(arr, x):
|
def jump_search(arr, x):
|
||||||
n = len(arr)
|
n = len(arr)
|
||||||
|
|
|
@ -11,6 +11,10 @@ python linear_search.py
|
||||||
"""
|
"""
|
||||||
from __future__ import print_function
|
from __future__ import print_function
|
||||||
|
|
||||||
|
try:
|
||||||
|
raw_input # Python 2
|
||||||
|
except NameError:
|
||||||
|
raw_input = input # Python 3
|
||||||
|
|
||||||
def linear_search(sequence, target):
|
def linear_search(sequence, target):
|
||||||
"""Pure implementation of linear search algorithm in Python
|
"""Pure implementation of linear search algorithm in Python
|
||||||
|
@ -39,21 +43,10 @@ def linear_search(sequence, target):
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
import sys
|
user_input = raw_input('Enter numbers separated by coma:\n').strip()
|
||||||
|
|
||||||
# For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
|
|
||||||
# otherwise 2.x's input builtin function is too "smart"
|
|
||||||
if sys.version_info.major < 3:
|
|
||||||
input_function = raw_input
|
|
||||||
else:
|
|
||||||
input_function = input
|
|
||||||
|
|
||||||
user_input = input_function('Enter numbers separated by coma:\n')
|
|
||||||
sequence = [int(item) for item in user_input.split(',')]
|
sequence = [int(item) for item in user_input.split(',')]
|
||||||
|
|
||||||
target_input = input_function(
|
target_input = raw_input('Enter a single number to be found in the list:\n')
|
||||||
'Enter a single number to be found in the list:\n'
|
|
||||||
)
|
|
||||||
target = int(target_input)
|
target = int(target_input)
|
||||||
result = linear_search(sequence, target)
|
result = linear_search(sequence, target)
|
||||||
if result is not None:
|
if result is not None:
|
||||||
|
|
|
@ -6,9 +6,15 @@ This is a type of divide and conquer algorithm which divides the search space in
|
||||||
Time Complexity : O(log3 N)
|
Time Complexity : O(log3 N)
|
||||||
Space Complexity : O(1)
|
Space Complexity : O(1)
|
||||||
'''
|
'''
|
||||||
|
from __future__ import print_function
|
||||||
|
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
|
try:
|
||||||
|
raw_input # Python 2
|
||||||
|
except NameError:
|
||||||
|
raw_input = input # Python 3
|
||||||
|
|
||||||
# This is the precision for this function which can be altered.
|
# This is the precision for this function which can be altered.
|
||||||
# It is recommended for users to keep this number greater than or equal to 10.
|
# It is recommended for users to keep this number greater than or equal to 10.
|
||||||
precision = 10
|
precision = 10
|
||||||
|
@ -81,16 +87,7 @@ def __assert_sorted(collection):
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
user_input = raw_input('Enter numbers separated by coma:\n').strip()
|
||||||
# For python 2.x and 3.x compatibility: 3.x has not raw_input builtin
|
|
||||||
# otherwise 2.x's input builtin function is too "smart"
|
|
||||||
|
|
||||||
if sys.version_info.major < 3:
|
|
||||||
input_function = raw_input
|
|
||||||
else:
|
|
||||||
input_function = input
|
|
||||||
|
|
||||||
user_input = input_function('Enter numbers separated by coma:\n')
|
|
||||||
collection = [int(item) for item in user_input.split(',')]
|
collection = [int(item) for item in user_input.split(',')]
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
@ -98,9 +95,7 @@ if __name__ == '__main__':
|
||||||
except ValueError:
|
except ValueError:
|
||||||
sys.exit('Sequence must be sorted to apply the ternary search')
|
sys.exit('Sequence must be sorted to apply the ternary search')
|
||||||
|
|
||||||
target_input = input_function(
|
target_input = raw_input('Enter a single number to be found in the list:\n')
|
||||||
'Enter a single number to be found in the list:\n'
|
|
||||||
)
|
|
||||||
target = int(target_input)
|
target = int(target_input)
|
||||||
result1 = ite_ternary_search(collection, target)
|
result1 = ite_ternary_search(collection, target)
|
||||||
result2 = rec_ternary_search(0, len(collection)-1, collection, target)
|
result2 = rec_ternary_search(0, len(collection)-1, collection, target)
|
||||||
|
|
|
@ -39,15 +39,11 @@ def bogosort(collection):
|
||||||
return collection
|
return collection
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
import sys
|
try:
|
||||||
|
raw_input # Python 2
|
||||||
|
except NameError:
|
||||||
|
raw_input = input # Python 3
|
||||||
|
|
||||||
# For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
|
user_input = raw_input('Enter numbers separated by a comma:\n').stript()
|
||||||
# otherwise 2.x's input builtin function is too "smart"
|
|
||||||
if sys.version_info.major < 3:
|
|
||||||
input_function = raw_input
|
|
||||||
else:
|
|
||||||
input_function = input
|
|
||||||
|
|
||||||
user_input = input_function('Enter numbers separated by a comma:\n')
|
|
||||||
unsorted = [int(item) for item in user_input.split(',')]
|
unsorted = [int(item) for item in user_input.split(',')]
|
||||||
print(bogosort(unsorted))
|
print(bogosort(unsorted))
|
||||||
|
|
|
@ -40,14 +40,11 @@ def bubble_sort(collection):
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
import sys
|
try:
|
||||||
# For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
|
raw_input # Python 2
|
||||||
# otherwise 2.x's input builtin function is too "smart"
|
except NameError:
|
||||||
if sys.version_info.major < 3:
|
raw_input = input # Python 3
|
||||||
input_function = raw_input
|
|
||||||
else:
|
|
||||||
input_function = input
|
|
||||||
|
|
||||||
user_input = input_function('Enter numbers separated by a comma:\n')
|
user_input = raw_input('Enter numbers separated by a comma:\n').strip()
|
||||||
unsorted = [int(item) for item in user_input.split(',')]
|
unsorted = [int(item) for item in user_input.split(',')]
|
||||||
print(bubble_sort(unsorted))
|
print(bubble_sort(unsorted))
|
||||||
|
|
|
@ -13,6 +13,7 @@
|
||||||
# Time Complexity of Solution:
|
# Time Complexity of Solution:
|
||||||
# Best Case O(n); Average Case O(n); Worst Case O(n)
|
# Best Case O(n); Average Case O(n); Worst Case O(n)
|
||||||
|
|
||||||
|
from __future__ import print_function
|
||||||
from P26_InsertionSort import insertionSort
|
from P26_InsertionSort import insertionSort
|
||||||
import math
|
import math
|
||||||
|
|
||||||
|
|
|
@ -21,16 +21,12 @@ def cocktail_shaker_sort(unsorted):
|
||||||
return unsorted
|
return unsorted
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
import sys
|
try:
|
||||||
|
raw_input # Python 2
|
||||||
|
except NameError:
|
||||||
|
raw_input = input # Python 3
|
||||||
|
|
||||||
# For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
|
user_input = raw_input('Enter numbers separated by a comma:\n').strip()
|
||||||
# otherwise 2.x's input builtin function is too "smart"
|
|
||||||
if sys.version_info.major < 3:
|
|
||||||
input_function = raw_input
|
|
||||||
else:
|
|
||||||
input_function = input
|
|
||||||
|
|
||||||
user_input = input_function('Enter numbers separated by a comma:\n')
|
|
||||||
unsorted = [int(item) for item in user_input.split(',')]
|
unsorted = [int(item) for item in user_input.split(',')]
|
||||||
cocktail_shaker_sort(unsorted)
|
cocktail_shaker_sort(unsorted)
|
||||||
print(unsorted)
|
print(unsorted)
|
|
@ -59,14 +59,11 @@ def counting_sort(collection):
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
import sys
|
try:
|
||||||
# For python 2.x and 3.x compatibility: 3.x has not raw_input builtin
|
raw_input # Python 2
|
||||||
# otherwise 2.x's input builtin function is too "smart"
|
except NameError:
|
||||||
if sys.version_info.major < 3:
|
raw_input = input # Python 3
|
||||||
input_function = raw_input
|
|
||||||
else:
|
|
||||||
input_function = input
|
|
||||||
|
|
||||||
user_input = input_function('Enter numbers separated by a comma:\n')
|
user_input = raw_input('Enter numbers separated by a comma:\n').strip()
|
||||||
unsorted = [int(item) for item in user_input.split(',')]
|
unsorted = [int(item) for item in user_input.split(',')]
|
||||||
print(counting_sort(unsorted))
|
print(counting_sort(unsorted))
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
from __future__ import print_function
|
||||||
# Python program for counting sort
|
# Python program for counting sort
|
||||||
|
|
||||||
# This is the main function that sort the given string arr[] in
|
# This is the main function that sort the given string arr[] in
|
||||||
|
|
|
@ -1,4 +1,7 @@
|
||||||
# Code contributed by Honey Sharma
|
# Code contributed by Honey Sharma
|
||||||
|
from __future__ import print_function
|
||||||
|
|
||||||
|
|
||||||
def cycle_sort(array):
|
def cycle_sort(array):
|
||||||
ans = 0
|
ans = 0
|
||||||
|
|
||||||
|
|
|
@ -158,4 +158,4 @@ def main():
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
main()
|
main()
|
||||||
|
|
|
@ -19,16 +19,12 @@ def gnome_sort(unsorted):
|
||||||
i = 1
|
i = 1
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
import sys
|
try:
|
||||||
|
raw_input # Python 2
|
||||||
|
except NameError:
|
||||||
|
raw_input = input # Python 3
|
||||||
|
|
||||||
# For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
|
user_input = raw_input('Enter numbers separated by a comma:\n').strip()
|
||||||
# otherwise 2.x's input builtin function is too "smart"
|
|
||||||
if sys.version_info.major < 3:
|
|
||||||
input_function = raw_input
|
|
||||||
else:
|
|
||||||
input_function = input
|
|
||||||
|
|
||||||
user_input = input_function('Enter numbers separated by a comma:\n')
|
|
||||||
unsorted = [int(item) for item in user_input.split(',')]
|
unsorted = [int(item) for item in user_input.split(',')]
|
||||||
gnome_sort(unsorted)
|
gnome_sort(unsorted)
|
||||||
print(unsorted)
|
print(unsorted)
|
|
@ -54,12 +54,11 @@ def heap_sort(unsorted):
|
||||||
return unsorted
|
return unsorted
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
import sys
|
try:
|
||||||
if sys.version_info.major < 3:
|
raw_input # Python 2
|
||||||
input_function = raw_input
|
except NameError:
|
||||||
else:
|
raw_input = input # Python 3
|
||||||
input_function = input
|
|
||||||
|
|
||||||
user_input = input_function('Enter numbers separated by a comma:\n')
|
user_input = raw_input('Enter numbers separated by a comma:\n').strip()
|
||||||
unsorted = [int(item) for item in user_input.split(',')]
|
unsorted = [int(item) for item in user_input.split(',')]
|
||||||
print(heap_sort(unsorted))
|
print(heap_sort(unsorted))
|
||||||
|
|
|
@ -39,15 +39,11 @@ def insertion_sort(collection):
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
import sys
|
try:
|
||||||
|
raw_input # Python 2
|
||||||
|
except NameError:
|
||||||
|
raw_input = input # Python 3
|
||||||
|
|
||||||
# For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
|
user_input = raw_input('Enter numbers separated by a comma:\n').strip()
|
||||||
# otherwise 2.x's input builtin function is too "smart"
|
|
||||||
if sys.version_info.major < 3:
|
|
||||||
input_function = raw_input
|
|
||||||
else:
|
|
||||||
input_function = input
|
|
||||||
|
|
||||||
user_input = input_function('Enter numbers separated by a comma:\n')
|
|
||||||
unsorted = [int(item) for item in user_input.split(',')]
|
unsorted = [int(item) for item in user_input.split(',')]
|
||||||
print(insertion_sort(unsorted))
|
print(insertion_sort(unsorted))
|
||||||
|
|
|
@ -62,15 +62,11 @@ def merge_sort(collection):
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
import sys
|
try:
|
||||||
|
raw_input # Python 2
|
||||||
|
except NameError:
|
||||||
|
raw_input = input # Python 3
|
||||||
|
|
||||||
# For python 2.x and 3.x compatibility: 3.x has no raw_input builtin
|
user_input = raw_input('Enter numbers separated by a comma:\n').strip()
|
||||||
# otherwise 2.x's input builtin function is too "smart"
|
|
||||||
if sys.version_info.major < 3:
|
|
||||||
input_function = raw_input
|
|
||||||
else:
|
|
||||||
input_function = input
|
|
||||||
|
|
||||||
user_input = input_function('Enter numbers separated by a comma:\n')
|
|
||||||
unsorted = [int(item) for item in user_input.split(',')]
|
unsorted = [int(item) for item in user_input.split(',')]
|
||||||
print(merge_sort(unsorted))
|
print(merge_sort(unsorted))
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user