mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-27 15:01:08 +00:00
Modernize Python 2 code to get ready for Python 3
This commit is contained in:
parent
a03b2eafc0
commit
4e06949072
|
@ -1,34 +1,34 @@
|
|||
"""
|
||||
File transfer protocol used to send and receive files using FTP server.
|
||||
Use credentials to provide access to the FTP client
|
||||
"""
|
||||
File transfer protocol used to send and receive files using FTP server.
|
||||
Use credentials to provide access to the FTP client
|
||||
|
||||
Note: Do not use root username & password for security reasons
|
||||
Create a seperate user and provide access to a home directory of the user
|
||||
Use login id and password of the user created
|
||||
cwd here stands for current working directory
|
||||
"""
|
||||
Note: Do not use root username & password for security reasons
|
||||
Create a seperate user and provide access to a home directory of the user
|
||||
Use login id and password of the user created
|
||||
cwd here stands for current working directory
|
||||
"""
|
||||
|
||||
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.cwd('/Enter the directory here/')
|
||||
|
||||
"""
|
||||
The file which will be received via the FTP server
|
||||
Enter the location of the file where the file is received
|
||||
"""
|
||||
"""
|
||||
The file which will be received via the FTP server
|
||||
Enter the location of the file where the file is received
|
||||
"""
|
||||
|
||||
def ReceiveFile():
|
||||
FileName = 'example.txt' """ Enter the location of the file """
|
||||
LocalFile = open(FileName, 'wb')
|
||||
ftp.retrbinary('RETR ' + filename, LocalFile.write, 1024)
|
||||
ftp.retrbinary('RETR ' + FileName, LocalFile.write, 1024)
|
||||
ftp.quit()
|
||||
LocalFile.close()
|
||||
|
||||
"""
|
||||
The file which will be sent via the FTP server
|
||||
The file send will be send to the current working directory
|
||||
"""
|
||||
"""
|
||||
The file which will be sent via the FTP server
|
||||
The file send will be send to the current working directory
|
||||
"""
|
||||
|
||||
def SendFile():
|
||||
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],
|
||||
[0, 1, 0, 0, 0, 0],#0 are free path whereas 1's are obstacles
|
||||
|
@ -80,7 +81,7 @@ def search(grid,init,goal,cost,heuristic):
|
|||
y = goal[1]
|
||||
invpath.append([x, y])#we get the reverse path from here
|
||||
while x != init[0] or y != init[1]:
|
||||
x2 = x - delta[action[x][y]][0]
|
||||
x2 = x - delta[action[x][y]][0]
|
||||
y2 = y - delta[action[x][y]][1]
|
||||
x = x2
|
||||
y = y2
|
||||
|
@ -89,13 +90,13 @@ def search(grid,init,goal,cost,heuristic):
|
|||
path = []
|
||||
for i in range(len(invpath)):
|
||||
path.append(invpath[len(invpath) - 1 - i])
|
||||
print "ACTION MAP"
|
||||
print("ACTION MAP")
|
||||
for i in range(len(action)):
|
||||
print action[i]
|
||||
print(action[i])
|
||||
|
||||
return path
|
||||
|
||||
a = search(grid,init,goal,cost,heuristic)
|
||||
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
|
||||
n, m = map(int, raw_input().split(" "))
|
||||
|
||||
|
@ -48,7 +60,7 @@ for _ in xrange(m):
|
|||
|
||||
def dfs(G, s):
|
||||
vis, S = set([s]), [s]
|
||||
print s
|
||||
print(s)
|
||||
while S:
|
||||
flag = 0
|
||||
for i in G[S[-1]]:
|
||||
|
@ -56,7 +68,7 @@ def dfs(G, s):
|
|||
S.append(i)
|
||||
vis.add(i)
|
||||
flag = 1
|
||||
print i
|
||||
print(i)
|
||||
break
|
||||
if not flag:
|
||||
S.pop()
|
||||
|
@ -76,14 +88,14 @@ from collections import deque
|
|||
|
||||
def bfs(G, s):
|
||||
vis, Q = set([s]), deque([s])
|
||||
print s
|
||||
print(s)
|
||||
while Q:
|
||||
u = Q.popleft()
|
||||
for v in G[u]:
|
||||
if v not in vis:
|
||||
vis.add(v)
|
||||
Q.append(v)
|
||||
print v
|
||||
print(v)
|
||||
|
||||
|
||||
"""
|
||||
|
@ -116,7 +128,7 @@ def dijk(G, s):
|
|||
path[v[0]] = u
|
||||
for i in dist:
|
||||
if i != s:
|
||||
print dist[i]
|
||||
print(dist[i])
|
||||
|
||||
|
||||
"""
|
||||
|
@ -140,7 +152,7 @@ def topo(G, ind=None, Q=[1]):
|
|||
if len(Q) == 0:
|
||||
return
|
||||
v = Q.popleft()
|
||||
print v
|
||||
print(v)
|
||||
for w in G[v]:
|
||||
ind[w] -= 1
|
||||
if ind[w] == 0:
|
||||
|
@ -175,7 +187,8 @@ def adjm():
|
|||
"""
|
||||
|
||||
|
||||
def floy((A, n)):
|
||||
def floy(xxx_todo_changeme):
|
||||
(A, n) = xxx_todo_changeme
|
||||
dist = list(A)
|
||||
path = [[0] * n for i 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]:
|
||||
dist[i][j] = dist[i][k] + dist[k][j]
|
||||
path[i][k] = k
|
||||
print dist
|
||||
print(dist)
|
||||
|
||||
|
||||
"""
|
||||
|
@ -246,14 +259,15 @@ def edglist():
|
|||
"""
|
||||
|
||||
|
||||
def krusk((E, n)):
|
||||
def krusk(xxx_todo_changeme1):
|
||||
# Sort edges on the basis of distance
|
||||
(E, n) = xxx_todo_changeme1
|
||||
E.sort(reverse=True, key=lambda x: x[2])
|
||||
s = [set([i]) for i in range(1, n + 1)]
|
||||
while True:
|
||||
if len(s) == 1:
|
||||
break
|
||||
print s
|
||||
print(s)
|
||||
x = E.pop()
|
||||
for i in xrange(len(s)):
|
||||
if x[0] in s[i]:
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
num_nodes, num_edges = list(map(int,input().split()))
|
||||
|
||||
edges = []
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
# n - no of nodes, m - no of edges
|
||||
n, m = list(map(int,input().split()))
|
||||
|
||||
|
|
|
@ -1,8 +1,14 @@
|
|||
from __future__ import print_function
|
||||
import heapq
|
||||
import numpy as np
|
||||
import math
|
||||
import copy
|
||||
|
||||
try:
|
||||
xrange # Python 2
|
||||
except NameError:
|
||||
xrange = range # Python 3
|
||||
|
||||
|
||||
class PriorityQueue:
|
||||
def __init__(self):
|
||||
|
@ -95,22 +101,22 @@ def do_something(back_pointer, goal, start):
|
|||
for i in xrange(n):
|
||||
for j in range(n):
|
||||
if (i, j) == (0, n-1):
|
||||
print grid[i][j],
|
||||
print "<-- End position",
|
||||
print(grid[i][j], end=' ')
|
||||
print("<-- End position", end=' ')
|
||||
else:
|
||||
print grid[i][j],
|
||||
print
|
||||
print(grid[i][j], end=' ')
|
||||
print()
|
||||
print("^")
|
||||
print("Start position")
|
||||
print
|
||||
print()
|
||||
print("# is an obstacle")
|
||||
print("- is the path taken by algorithm")
|
||||
print("PATH TAKEN BY THE ALGORITHM IS:-")
|
||||
x = back_pointer[goal]
|
||||
while x != start:
|
||||
print x,
|
||||
print(x, end=' ')
|
||||
x = back_pointer[x]
|
||||
print x
|
||||
print(x)
|
||||
quit()
|
||||
|
||||
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)
|
||||
close_list_anchor.append(get_s)
|
||||
print("No path found to goal")
|
||||
print
|
||||
print()
|
||||
for i in range(n-1,-1, -1):
|
||||
for j in range(n):
|
||||
if (j, i) in blocks:
|
||||
print '#',
|
||||
print('#', end=' ')
|
||||
elif (j, i) in back_pointer:
|
||||
if (j, i) == (n-1, n-1):
|
||||
print '*',
|
||||
print('*', end=' ')
|
||||
else:
|
||||
print '-',
|
||||
print('-', end=' ')
|
||||
else:
|
||||
print '*',
|
||||
print('*', end=' ')
|
||||
if (j, i) == (n-1, n-1):
|
||||
print '<-- End position',
|
||||
print
|
||||
print('<-- End position', end=' ')
|
||||
print()
|
||||
print("^")
|
||||
print("Start position")
|
||||
print
|
||||
print()
|
||||
print("# is an obstacle")
|
||||
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
|
||||
- - - - - -- - - - - - - - - - - - - - - - - - - - - - -
|
||||
'''
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
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):
|
||||
#model traning
|
||||
print('----------------------Start Training-------------------------')
|
||||
print(' - - Shape: Train_Data ',np.shape(datas_train))
|
||||
print(' - - Shape: Teach_Data ',np.shape(datas_teach))
|
||||
print((' - - Shape: Train_Data ',np.shape(datas_train)))
|
||||
print((' - - Shape: Teach_Data ',np.shape(datas_teach)))
|
||||
rp = 0
|
||||
all_mse = []
|
||||
mse = 10000
|
||||
|
@ -262,7 +263,7 @@ class CNN():
|
|||
plt.grid(True, alpha=0.5)
|
||||
plt.show()
|
||||
print('------------------Training Complished---------------------')
|
||||
print(' - - Training epoch: ', rp, ' - - Mse: %.6f' % mse)
|
||||
print((' - - Training epoch: ', rp, ' - - Mse: %.6f' % mse))
|
||||
if draw_e:
|
||||
draw_error()
|
||||
return mse
|
||||
|
@ -271,7 +272,7 @@ class CNN():
|
|||
#model predict
|
||||
produce_out = []
|
||||
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)):
|
||||
data_test = np.asmatrix(datas_test[p])
|
||||
data_focus1, data_conved1 = self.convolute(data_test, self.conv1, self.w_conv1,
|
||||
|
|
|
@ -9,6 +9,7 @@
|
|||
p2 = 1
|
||||
|
||||
'''
|
||||
from __future__ import print_function
|
||||
|
||||
import random
|
||||
|
||||
|
@ -52,7 +53,7 @@ class Perceptron:
|
|||
epoch_count = epoch_count + 1
|
||||
# if you want controle the epoch or just by erro
|
||||
if erro == False:
|
||||
print('\nEpoch:\n',epoch_count)
|
||||
print(('\nEpoch:\n',epoch_count))
|
||||
print('------------------------\n')
|
||||
#if epoch_count > self.epoch_number or not erro:
|
||||
break
|
||||
|
@ -66,10 +67,10 @@ class Perceptron:
|
|||
y = self.sign(u)
|
||||
|
||||
if y == -1:
|
||||
print('Sample: ', sample)
|
||||
print(('Sample: ', sample))
|
||||
print('classification: P1')
|
||||
else:
|
||||
print('Sample: ', sample)
|
||||
print(('Sample: ', sample))
|
||||
print('classification: P2')
|
||||
|
||||
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.
|
||||
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())
|
||||
sum=0;
|
||||
sum=0
|
||||
for a in range(3,n):
|
||||
if(a%3==0 or a%5==0):
|
||||
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.
|
||||
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())
|
||||
sum = 0
|
||||
terms = (n-1)/3
|
||||
|
@ -12,4 +17,4 @@ terms = (n-1)/5
|
|||
sum+= ((terms)*(10+(terms-1)*5))/2
|
||||
terms = (n-1)/15
|
||||
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.
|
||||
'''
|
||||
from __future__ import print_function
|
||||
try:
|
||||
raw_input # Python 2
|
||||
except NameError:
|
||||
raw_input = input # Python 3
|
||||
n = int(raw_input().strip())
|
||||
sum=0;
|
||||
num=0;
|
||||
|
@ -39,4 +44,4 @@ while(1):
|
|||
if(num>=n):
|
||||
break
|
||||
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.
|
||||
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())
|
||||
i=1; j=2; sum=0
|
||||
|
@ -15,4 +21,4 @@ while(j<=n):
|
|||
temp=i
|
||||
i=j
|
||||
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?
|
||||
e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17.
|
||||
'''
|
||||
from __future__ import print_function
|
||||
|
||||
import math
|
||||
|
||||
|
@ -20,12 +21,12 @@ def isprime(no):
|
|||
max=0
|
||||
n=int(input())
|
||||
if(isprime(n)):
|
||||
print n
|
||||
print(n)
|
||||
else:
|
||||
while (n%2==0):
|
||||
n=n/2
|
||||
if(isprime(n)):
|
||||
print n
|
||||
print(n)
|
||||
else:
|
||||
n1 = int(math.sqrt(n))+1
|
||||
for i in range(3,n1,2):
|
||||
|
@ -35,4 +36,4 @@ else:
|
|||
break
|
||||
elif(isprime(i)):
|
||||
max=i
|
||||
print max
|
||||
print(max)
|
||||
|
|
|
@ -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?
|
||||
e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17.
|
||||
'''
|
||||
from __future__ import print_function
|
||||
n=int(input())
|
||||
prime=1
|
||||
i=2
|
||||
|
@ -13,4 +14,4 @@ while(i*i<=n):
|
|||
i+=1
|
||||
if(n>1):
|
||||
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.
|
||||
Find the largest palindrome made from the product of two 3-digit numbers which is less than N.
|
||||
'''
|
||||
from __future__ import print_function
|
||||
n=int(input())
|
||||
for i in range(n-1,10000,-1):
|
||||
temp=str(i)
|
||||
|
@ -10,6 +11,6 @@ for i in range(n-1,10000,-1):
|
|||
j=999
|
||||
while(j!=99):
|
||||
if((i%j==0) and (len(str(i/j))==3)):
|
||||
print i
|
||||
print(i)
|
||||
exit(0)
|
||||
j-=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.
|
||||
Find the largest palindrome made from the product of two 3-digit numbers which is less than N.
|
||||
'''
|
||||
from __future__ import print_function
|
||||
arr = []
|
||||
for i in range(999,100,-1):
|
||||
for j in range(999,100,-1):
|
||||
|
@ -14,5 +15,5 @@ arr.sort()
|
|||
n=int(input())
|
||||
for i in arr[::-1]:
|
||||
if(i<n):
|
||||
print i
|
||||
print(i)
|
||||
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.
|
||||
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())
|
||||
i = 0
|
||||
|
@ -16,5 +17,5 @@ while 1:
|
|||
if(nfound==0):
|
||||
if(i==0):
|
||||
i=1
|
||||
print i
|
||||
print(i)
|
||||
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.
|
||||
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
|
||||
sumb = 0
|
||||
|
@ -16,4 +17,4 @@ for i in range(1,n+1):
|
|||
suma += i**2
|
||||
sumb += i
|
||||
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.
|
||||
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())
|
||||
suma = n*(n+1)/2
|
||||
suma **= 2
|
||||
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.
|
||||
What is the Nth prime number?
|
||||
'''
|
||||
from __future__ import print_function
|
||||
from math import sqrt
|
||||
def isprime(n):
|
||||
if (n==2):
|
||||
|
@ -26,4 +27,4 @@ while(i!=n):
|
|||
j+=2
|
||||
if(isprime(j)):
|
||||
i+=1
|
||||
print j
|
||||
print(j)
|
|
@ -2,6 +2,7 @@
|
|||
Problem Statement:
|
||||
Work out the first ten digits of the sum of the N 50-digit numbers.
|
||||
'''
|
||||
from __future__ import print_function
|
||||
|
||||
n = int(input().strip())
|
||||
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
largest_number = 0
|
||||
pre_counter = 0
|
||||
|
||||
|
@ -17,4 +18,4 @@ for input1 in range(750000,1000000):
|
|||
largest_number = input1
|
||||
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:
|
||||
# 1. a < b < c
|
||||
# 2. a**2 + b**2 = c**2
|
||||
|
@ -10,5 +11,5 @@ for a in range(300):
|
|||
if(a < b < c):
|
||||
if((a**2) + (b**2) == (c**2)):
|
||||
if((a+b+c) == 1000):
|
||||
print("Product of",a,"*",b,"*",c,"=",(a*b*c))
|
||||
print(("Product of",a,"*",b,"*",c,"=",(a*b*c)))
|
||||
break
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
import sys, random, cryptomath_module as cryptoMath
|
||||
|
||||
SYMBOLS = """ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
def decrypt(message):
|
||||
"""
|
||||
>>> decrypt('TMDETUX PMDVU')
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
# The Caesar Cipher Algorithm
|
||||
|
||||
def main():
|
||||
|
@ -12,9 +13,9 @@ def main():
|
|||
|
||||
translated = encdec(message, key, mode)
|
||||
if mode == "encrypt":
|
||||
print("Encryption:", translated)
|
||||
print(("Encryption:", translated))
|
||||
elif mode == "decrypt":
|
||||
print("Decryption:", translated)
|
||||
print(("Decryption:", translated))
|
||||
|
||||
def encdec(message, key, mode):
|
||||
message = message.upper()
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
# Primality Testing with the Rabin-Miller Algorithm
|
||||
|
||||
import random
|
||||
|
@ -59,5 +60,5 @@ def generateLargePrime(keysize = 1024):
|
|||
|
||||
if __name__ == '__main__':
|
||||
num = generateLargePrime()
|
||||
print('Prime number:', num)
|
||||
print('isPrime:', isPrime(num))
|
||||
print(('Prime number:', num))
|
||||
print(('isPrime:', isPrime(num)))
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
def dencrypt(s, n):
|
||||
out = ''
|
||||
for c in s:
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
import sys, rsa_key_generator as rkg, os
|
||||
|
||||
DEFAULT_BLOCK_SIZE = 128
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
import random, sys, os
|
||||
import rabin_miller as rabinMiller, cryptomath_module as cryptoMath
|
||||
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
import sys, random
|
||||
|
||||
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
import math
|
||||
|
||||
def main():
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
import time, os, sys
|
||||
import transposition_cipher as transCipher
|
||||
|
||||
|
@ -29,7 +30,7 @@ def main():
|
|||
outputObj.close()
|
||||
|
||||
totalTime = round(time.time() - startTime, 2)
|
||||
print('Done (', totalTime, 'seconds )')
|
||||
print(('Done (', totalTime, 'seconds )'))
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
||||
|
||||
def main():
|
||||
|
|
|
@ -1,28 +1,29 @@
|
|||
class FenwickTree:
|
||||
|
||||
def __init__(self, SIZE): # create fenwick tree with size SIZE
|
||||
self.Size = SIZE
|
||||
self.ft = [0 for i in range (0,SIZE)]
|
||||
|
||||
def update(self, i, val): # update data (adding) in index i in O(lg N)
|
||||
while (i < self.Size):
|
||||
self.ft[i] += val
|
||||
i += i & (-i)
|
||||
|
||||
def query(self, i): # query cumulative data from index 0 to i in O(lg N)
|
||||
ret = 0
|
||||
while (i > 0):
|
||||
ret += self.ft[i]
|
||||
i -= i & (-i)
|
||||
return ret
|
||||
|
||||
if __name__ == '__main__':
|
||||
f = FenwickTree(100)
|
||||
f.update(1,20)
|
||||
f.update(4,4)
|
||||
print (f.query(1))
|
||||
print (f.query(3))
|
||||
print (f.query(4))
|
||||
f.update(2,-5)
|
||||
print (f.query(1))
|
||||
print (f.query(3))
|
||||
from __future__ import print_function
|
||||
class FenwickTree:
|
||||
|
||||
def __init__(self, SIZE): # create fenwick tree with size SIZE
|
||||
self.Size = SIZE
|
||||
self.ft = [0 for i in range (0,SIZE)]
|
||||
|
||||
def update(self, i, val): # update data (adding) in index i in O(lg N)
|
||||
while (i < self.Size):
|
||||
self.ft[i] += val
|
||||
i += i & (-i)
|
||||
|
||||
def query(self, i): # query cumulative data from index 0 to i in O(lg N)
|
||||
ret = 0
|
||||
while (i > 0):
|
||||
ret += self.ft[i]
|
||||
i -= i & (-i)
|
||||
return ret
|
||||
|
||||
if __name__ == '__main__':
|
||||
f = FenwickTree(100)
|
||||
f.update(1,20)
|
||||
f.update(4,4)
|
||||
print (f.query(1))
|
||||
print (f.query(3))
|
||||
print (f.query(4))
|
||||
f.update(2,-5)
|
||||
print (f.query(1))
|
||||
print (f.query(3))
|
||||
|
|
|
@ -1,90 +1,91 @@
|
|||
import math
|
||||
|
||||
class SegmentTree:
|
||||
|
||||
def __init__(self, N):
|
||||
self.N = N
|
||||
self.st = [0 for i in range(0,4*N)] # approximate the overall size of segment tree with array N
|
||||
self.lazy = [0 for i in range(0,4*N)] # create array to store lazy update
|
||||
self.flag = [0 for i in range(0,4*N)] # flag for lazy update
|
||||
|
||||
def left(self, idx):
|
||||
return idx*2
|
||||
|
||||
def right(self, idx):
|
||||
return idx*2 + 1
|
||||
|
||||
def build(self, idx, l, r, A):
|
||||
if l==r:
|
||||
self.st[idx] = A[l-1]
|
||||
else :
|
||||
mid = (l+r)//2
|
||||
self.build(self.left(idx),l,mid, A)
|
||||
self.build(self.right(idx),mid+1,r, A)
|
||||
self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
|
||||
|
||||
# update with O(lg N) (Normal segment tree without lazy update will take O(Nlg N) for each update)
|
||||
def update(self, idx, l, r, a, b, val): # update(1, 1, N, a, b, v) for update val v to [a,b]
|
||||
if self.flag[idx] == True:
|
||||
self.st[idx] = self.lazy[idx]
|
||||
self.flag[idx] = False
|
||||
if l!=r:
|
||||
self.lazy[self.left(idx)] = self.lazy[idx]
|
||||
self.lazy[self.right(idx)] = self.lazy[idx]
|
||||
self.flag[self.left(idx)] = True
|
||||
self.flag[self.right(idx)] = True
|
||||
|
||||
if r < a or l > b:
|
||||
return True
|
||||
if l >= a and r <= b :
|
||||
self.st[idx] = val
|
||||
if l!=r:
|
||||
self.lazy[self.left(idx)] = val
|
||||
self.lazy[self.right(idx)] = val
|
||||
self.flag[self.left(idx)] = True
|
||||
self.flag[self.right(idx)] = True
|
||||
return True
|
||||
mid = (l+r)//2
|
||||
self.update(self.left(idx),l,mid,a,b,val)
|
||||
self.update(self.right(idx),mid+1,r,a,b,val)
|
||||
self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
|
||||
return True
|
||||
|
||||
# query with O(lg N)
|
||||
def query(self, idx, l, r, a, b): #query(1, 1, N, a, b) for query max of [a,b]
|
||||
if self.flag[idx] == True:
|
||||
self.st[idx] = self.lazy[idx]
|
||||
self.flag[idx] = False
|
||||
if l != r:
|
||||
self.lazy[self.left(idx)] = self.lazy[idx]
|
||||
self.lazy[self.right(idx)] = self.lazy[idx]
|
||||
self.flag[self.left(idx)] = True
|
||||
self.flag[self.right(idx)] = True
|
||||
if r < a or l > b:
|
||||
return -math.inf
|
||||
if l >= a and r <= b:
|
||||
return self.st[idx]
|
||||
mid = (l+r)//2
|
||||
q1 = self.query(self.left(idx),l,mid,a,b)
|
||||
q2 = self.query(self.right(idx),mid+1,r,a,b)
|
||||
return max(q1,q2)
|
||||
|
||||
def showData(self):
|
||||
showList = []
|
||||
for i in range(1,N+1):
|
||||
showList += [self.query(1, 1, self.N, i, i)]
|
||||
print (showList)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
A = [1,2,-4,7,3,-5,6,11,-20,9,14,15,5,2,-8]
|
||||
N = 15
|
||||
segt = SegmentTree(N)
|
||||
segt.build(1,1,N,A)
|
||||
print (segt.query(1,1,N,4,6))
|
||||
print (segt.query(1,1,N,7,11))
|
||||
print (segt.query(1,1,N,7,12))
|
||||
segt.update(1,1,N,1,3,111)
|
||||
print (segt.query(1,1,N,1,15))
|
||||
segt.update(1,1,N,7,8,235)
|
||||
segt.showData()
|
||||
from __future__ import print_function
|
||||
import math
|
||||
|
||||
class SegmentTree:
|
||||
|
||||
def __init__(self, N):
|
||||
self.N = N
|
||||
self.st = [0 for i in range(0,4*N)] # approximate the overall size of segment tree with array N
|
||||
self.lazy = [0 for i in range(0,4*N)] # create array to store lazy update
|
||||
self.flag = [0 for i in range(0,4*N)] # flag for lazy update
|
||||
|
||||
def left(self, idx):
|
||||
return idx*2
|
||||
|
||||
def right(self, idx):
|
||||
return idx*2 + 1
|
||||
|
||||
def build(self, idx, l, r, A):
|
||||
if l==r:
|
||||
self.st[idx] = A[l-1]
|
||||
else :
|
||||
mid = (l+r)//2
|
||||
self.build(self.left(idx),l,mid, A)
|
||||
self.build(self.right(idx),mid+1,r, A)
|
||||
self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
|
||||
|
||||
# update with O(lg N) (Normal segment tree without lazy update will take O(Nlg N) for each update)
|
||||
def update(self, idx, l, r, a, b, val): # update(1, 1, N, a, b, v) for update val v to [a,b]
|
||||
if self.flag[idx] == True:
|
||||
self.st[idx] = self.lazy[idx]
|
||||
self.flag[idx] = False
|
||||
if l!=r:
|
||||
self.lazy[self.left(idx)] = self.lazy[idx]
|
||||
self.lazy[self.right(idx)] = self.lazy[idx]
|
||||
self.flag[self.left(idx)] = True
|
||||
self.flag[self.right(idx)] = True
|
||||
|
||||
if r < a or l > b:
|
||||
return True
|
||||
if l >= a and r <= b :
|
||||
self.st[idx] = val
|
||||
if l!=r:
|
||||
self.lazy[self.left(idx)] = val
|
||||
self.lazy[self.right(idx)] = val
|
||||
self.flag[self.left(idx)] = True
|
||||
self.flag[self.right(idx)] = True
|
||||
return True
|
||||
mid = (l+r)//2
|
||||
self.update(self.left(idx),l,mid,a,b,val)
|
||||
self.update(self.right(idx),mid+1,r,a,b,val)
|
||||
self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
|
||||
return True
|
||||
|
||||
# query with O(lg N)
|
||||
def query(self, idx, l, r, a, b): #query(1, 1, N, a, b) for query max of [a,b]
|
||||
if self.flag[idx] == True:
|
||||
self.st[idx] = self.lazy[idx]
|
||||
self.flag[idx] = False
|
||||
if l != r:
|
||||
self.lazy[self.left(idx)] = self.lazy[idx]
|
||||
self.lazy[self.right(idx)] = self.lazy[idx]
|
||||
self.flag[self.left(idx)] = True
|
||||
self.flag[self.right(idx)] = True
|
||||
if r < a or l > b:
|
||||
return -math.inf
|
||||
if l >= a and r <= b:
|
||||
return self.st[idx]
|
||||
mid = (l+r)//2
|
||||
q1 = self.query(self.left(idx),l,mid,a,b)
|
||||
q2 = self.query(self.right(idx),mid+1,r,a,b)
|
||||
return max(q1,q2)
|
||||
|
||||
def showData(self):
|
||||
showList = []
|
||||
for i in range(1,N+1):
|
||||
showList += [self.query(1, 1, self.N, i, i)]
|
||||
print (showList)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
A = [1,2,-4,7,3,-5,6,11,-20,9,14,15,5,2,-8]
|
||||
N = 15
|
||||
segt = SegmentTree(N)
|
||||
segt.build(1,1,N,A)
|
||||
print (segt.query(1,1,N,4,6))
|
||||
print (segt.query(1,1,N,7,11))
|
||||
print (segt.query(1,1,N,7,12))
|
||||
segt.update(1,1,N,1,3,111)
|
||||
print (segt.query(1,1,N,1,15))
|
||||
segt.update(1,1,N,7,8,235)
|
||||
segt.showData()
|
||||
|
|
|
@ -1,64 +1,65 @@
|
|||
import math
|
||||
|
||||
class SegmentTree:
|
||||
|
||||
def __init__(self, N):
|
||||
self.N = N
|
||||
self.st = [0 for i in range(0,4*N)] # approximate the overall size of segment tree with array N
|
||||
|
||||
def left(self, idx):
|
||||
return idx*2
|
||||
|
||||
def right(self, idx):
|
||||
return idx*2 + 1
|
||||
|
||||
def build(self, idx, l, r, A):
|
||||
if l==r:
|
||||
self.st[idx] = A[l-1]
|
||||
else :
|
||||
mid = (l+r)//2
|
||||
self.build(self.left(idx),l,mid, A)
|
||||
self.build(self.right(idx),mid+1,r, A)
|
||||
self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
|
||||
|
||||
def update(self, idx, l, r, a, b, val): # update(1, 1, N, a, b, v) for update val v to [a,b]
|
||||
if r < a or l > b:
|
||||
return True
|
||||
if l == r :
|
||||
self.st[idx] = val
|
||||
return True
|
||||
mid = (l+r)//2
|
||||
self.update(self.left(idx),l,mid,a,b,val)
|
||||
self.update(self.right(idx),mid+1,r,a,b,val)
|
||||
self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
|
||||
return True
|
||||
|
||||
def query(self, idx, l, r, a, b): #query(1, 1, N, a, b) for query max of [a,b]
|
||||
if r < a or l > b:
|
||||
return -math.inf
|
||||
if l >= a and r <= b:
|
||||
return self.st[idx]
|
||||
mid = (l+r)//2
|
||||
q1 = self.query(self.left(idx),l,mid,a,b)
|
||||
q2 = self.query(self.right(idx),mid+1,r,a,b)
|
||||
return max(q1,q2)
|
||||
|
||||
def showData(self):
|
||||
showList = []
|
||||
for i in range(1,N+1):
|
||||
showList += [self.query(1, 1, self.N, i, i)]
|
||||
print (showList)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
A = [1,2,-4,7,3,-5,6,11,-20,9,14,15,5,2,-8]
|
||||
N = 15
|
||||
segt = SegmentTree(N)
|
||||
segt.build(1,1,N,A)
|
||||
print (segt.query(1,1,N,4,6))
|
||||
print (segt.query(1,1,N,7,11))
|
||||
print (segt.query(1,1,N,7,12))
|
||||
segt.update(1,1,N,1,3,111)
|
||||
print (segt.query(1,1,N,1,15))
|
||||
segt.update(1,1,N,7,8,235)
|
||||
segt.showData()
|
||||
from __future__ import print_function
|
||||
import math
|
||||
|
||||
class SegmentTree:
|
||||
|
||||
def __init__(self, N):
|
||||
self.N = N
|
||||
self.st = [0 for i in range(0,4*N)] # approximate the overall size of segment tree with array N
|
||||
|
||||
def left(self, idx):
|
||||
return idx*2
|
||||
|
||||
def right(self, idx):
|
||||
return idx*2 + 1
|
||||
|
||||
def build(self, idx, l, r, A):
|
||||
if l==r:
|
||||
self.st[idx] = A[l-1]
|
||||
else :
|
||||
mid = (l+r)//2
|
||||
self.build(self.left(idx),l,mid, A)
|
||||
self.build(self.right(idx),mid+1,r, A)
|
||||
self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
|
||||
|
||||
def update(self, idx, l, r, a, b, val): # update(1, 1, N, a, b, v) for update val v to [a,b]
|
||||
if r < a or l > b:
|
||||
return True
|
||||
if l == r :
|
||||
self.st[idx] = val
|
||||
return True
|
||||
mid = (l+r)//2
|
||||
self.update(self.left(idx),l,mid,a,b,val)
|
||||
self.update(self.right(idx),mid+1,r,a,b,val)
|
||||
self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
|
||||
return True
|
||||
|
||||
def query(self, idx, l, r, a, b): #query(1, 1, N, a, b) for query max of [a,b]
|
||||
if r < a or l > b:
|
||||
return -math.inf
|
||||
if l >= a and r <= b:
|
||||
return self.st[idx]
|
||||
mid = (l+r)//2
|
||||
q1 = self.query(self.left(idx),l,mid,a,b)
|
||||
q2 = self.query(self.right(idx),mid+1,r,a,b)
|
||||
return max(q1,q2)
|
||||
|
||||
def showData(self):
|
||||
showList = []
|
||||
for i in range(1,N+1):
|
||||
showList += [self.query(1, 1, self.N, i, i)]
|
||||
print (showList)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
A = [1,2,-4,7,3,-5,6,11,-20,9,14,15,5,2,-8]
|
||||
N = 15
|
||||
segt = SegmentTree(N)
|
||||
segt.build(1,1,N,A)
|
||||
print (segt.query(1,1,N,4,6))
|
||||
print (segt.query(1,1,N,7,11))
|
||||
print (segt.query(1,1,N,7,12))
|
||||
segt.update(1,1,N,1,3,111)
|
||||
print (segt.query(1,1,N,1,15))
|
||||
segt.update(1,1,N,7,8,235)
|
||||
segt.showData()
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
'''
|
||||
A binary search Tree
|
||||
'''
|
||||
from __future__ import print_function
|
||||
class Node:
|
||||
|
||||
def __init__(self, label, parent):
|
||||
|
@ -237,8 +238,8 @@ def testBinarySearchTree():
|
|||
print("The label -1 doesn't exist")
|
||||
|
||||
if(not t.empty()):
|
||||
print("Max Value: ", t.getMax().getLabel())
|
||||
print("Min Value: ", t.getMin().getLabel())
|
||||
print(("Max Value: ", t.getMax().getLabel()))
|
||||
print(("Min Value: ", t.getMin().getLabel()))
|
||||
|
||||
t.delete(13)
|
||||
t.delete(10)
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
# Author: OMKAR PATHAK
|
||||
|
||||
# We can use Python's dictionary for constructing the graph
|
||||
|
@ -15,7 +16,7 @@ class AdjacencyList(object):
|
|||
|
||||
def printList(self):
|
||||
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__':
|
||||
al = AdjacencyList()
|
||||
|
|
|
@ -12,6 +12,7 @@ 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
|
||||
|
||||
|
@ -66,4 +67,4 @@ if __name__ == '__main__':
|
|||
tree[u].append(v)
|
||||
tree[v].append(u)
|
||||
even_tree()
|
||||
print len(cuts) - 1
|
||||
print(len(cuts) - 1)
|
||||
|
|
|
@ -1,5 +1,12 @@
|
|||
#!/usr/bin/python
|
||||
|
||||
from __future__ import print_function
|
||||
|
||||
try:
|
||||
raw_input # Python 2
|
||||
except NameError:
|
||||
raw_input = input # Python 3
|
||||
|
||||
class Heap:
|
||||
def __init__(self):
|
||||
self.h = []
|
||||
|
@ -68,10 +75,10 @@ class Heap:
|
|||
curr = curr/2
|
||||
|
||||
def display(self):
|
||||
print (self.h)
|
||||
print(self.h)
|
||||
|
||||
def main():
|
||||
l = list(map(int,raw_input().split()))
|
||||
l = list(map(int, raw_input().split()))
|
||||
h = Heap()
|
||||
h.buildHeap(l)
|
||||
h.heapSort()
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
class Node:#create a Node
|
||||
def __int__(self,data):
|
||||
self.data=data#given data
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
# Python code to demonstrate working of
|
||||
# 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'
|
||||
|
||||
|
|
|
@ -1,6 +1,8 @@
|
|||
from __future__ import print_function
|
||||
from __future__ import absolute_import
|
||||
import string
|
||||
|
||||
from Stack import Stack
|
||||
from .Stack import Stack
|
||||
|
||||
__author__ = 'Omkar Pathak'
|
||||
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
# Function to print element and NGE pair for all elements of list
|
||||
def printNGE(arr):
|
||||
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
__author__ = 'Omkar Pathak'
|
||||
|
||||
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
from union_find import UnionFind
|
||||
from __future__ import absolute_import
|
||||
from .union_find import UnionFind
|
||||
import unittest
|
||||
|
||||
|
||||
|
|
|
@ -5,6 +5,7 @@ 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 = [0] * (n + 1)
|
||||
|
||||
|
@ -21,5 +22,5 @@ def dp_count(S, m, n):
|
|||
return table[n]
|
||||
|
||||
if __name__ == '__main__':
|
||||
print dp_count([1, 2, 3], 3, 4) # answer 4
|
||||
print dp_count([2, 5, 3, 6], 4, 10) # answer 5
|
||||
print(dp_count([1, 2, 3], 3, 4)) # answer 4
|
||||
print(dp_count([2, 5, 3, 6], 4, 10)) # answer 5
|
||||
|
|
|
@ -51,11 +51,10 @@ class EditDistance:
|
|||
return self.__solveDP(len(A)-1, len(B)-1)
|
||||
|
||||
if __name__ == '__main__':
|
||||
import sys
|
||||
if sys.version_info.major < 3:
|
||||
input_function = raw_input
|
||||
else:
|
||||
input_function = input
|
||||
try:
|
||||
raw_input # Python 2
|
||||
except NameError:
|
||||
raw_input = input # Python 3
|
||||
|
||||
solver = EditDistance()
|
||||
|
||||
|
@ -63,10 +62,10 @@ if __name__ == '__main__':
|
|||
print()
|
||||
|
||||
print("Enter the first string: ", end="")
|
||||
S1 = input_function()
|
||||
S1 = raw_input().strip()
|
||||
|
||||
print("Enter the second string: ", end="")
|
||||
S2 = input_function()
|
||||
S2 = raw_input().strip()
|
||||
|
||||
print()
|
||||
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)).
|
||||
It's possible to calculate F(1000000) in less than a second.
|
||||
"""
|
||||
from __future__ import print_function
|
||||
import sys
|
||||
|
||||
|
||||
|
|
|
@ -27,26 +27,22 @@ class Fibonacci:
|
|||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import sys
|
||||
|
||||
print("\n********* Fibonacci Series Using Dynamic Programming ************\n")
|
||||
# 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
|
||||
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(input())
|
||||
N = eval(raw_input().strip())
|
||||
fib = Fibonacci(N)
|
||||
print(
|
||||
"\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(input())
|
||||
i = eval(raw_input().strip())
|
||||
if i < 0:
|
||||
print("\n********* Good Bye!! ************\n")
|
||||
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.
|
||||
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):
|
||||
# find the length of strings
|
||||
m = len(x)
|
||||
|
@ -27,4 +34,4 @@ def lcs_dp(x, y):
|
|||
if __name__=='__main__':
|
||||
x = 'AGGTAB'
|
||||
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.
|
||||
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
|
||||
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
#############################
|
||||
# Author: Aravind Kashyap
|
||||
# File: lis.py
|
||||
|
@ -37,4 +38,4 @@ def LongestIncreasingSubsequenceLength(v):
|
|||
|
||||
|
||||
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 :
|
||||
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:
|
||||
|
@ -13,7 +14,7 @@ class SubArray:
|
|||
def __init__(self, arr):
|
||||
# we need a list not a string, so do something to change the type
|
||||
self.array = arr.split(',')
|
||||
print("the input array is:", self.array)
|
||||
print(("the input array is:", self.array))
|
||||
|
||||
def solve_sub_array(self):
|
||||
rear = [int(self.array[0])]*len(self.array)
|
||||
|
@ -28,5 +29,5 @@ if __name__ == '__main__':
|
|||
whole_array = input("please input some numbers:")
|
||||
array = SubArray(whole_array)
|
||||
re = array.solve_sub_array()
|
||||
print("the results is:", re)
|
||||
print(("the results is:", re))
|
||||
|
||||
|
|
|
@ -1,59 +1,60 @@
|
|||
"""
|
||||
author : Mayank Kumar Jha (mk9440)
|
||||
"""
|
||||
|
||||
import time
|
||||
import matplotlib.pyplot as plt
|
||||
from random import randint
|
||||
def find_max_sub_array(A,low,high):
|
||||
if low==high:
|
||||
return low,high,A[low]
|
||||
else :
|
||||
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)
|
||||
if left_sum>=right_sum and left_sum>=cross_sum:
|
||||
return left_low,left_high,left_sum
|
||||
elif right_sum>=left_sum and right_sum>=cross_sum :
|
||||
return right_low,right_high,right_sum
|
||||
else:
|
||||
return cross_left,cross_right,cross_sum
|
||||
|
||||
def find_max_cross_sum(A,low,mid,high):
|
||||
left_sum,max_left=-999999999,-1
|
||||
right_sum,max_right=-999999999,-1
|
||||
summ=0
|
||||
for i in range(mid,low-1,-1):
|
||||
summ+=A[i]
|
||||
if summ > left_sum:
|
||||
left_sum=summ
|
||||
max_left=i
|
||||
summ=0
|
||||
for i in range(mid+1,high+1):
|
||||
summ+=A[i]
|
||||
if summ > right_sum:
|
||||
right_sum=summ
|
||||
max_right=i
|
||||
return max_left,max_right,(left_sum+right_sum)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
inputs=[10,100,1000,10000,50000,100000,200000,300000,400000,500000]
|
||||
tim=[]
|
||||
for i in inputs:
|
||||
li=[randint(1,i) for j in range(i)]
|
||||
strt=time.time()
|
||||
(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(inputs[i],'\t\t',tim[i])
|
||||
plt.plot(inputs,tim)
|
||||
plt.xlabel("Number of Inputs");plt.ylabel("Time taken in seconds ")
|
||||
plt.show()
|
||||
|
||||
|
||||
|
||||
|
||||
"""
|
||||
author : Mayank Kumar Jha (mk9440)
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
import time
|
||||
import matplotlib.pyplot as plt
|
||||
from random import randint
|
||||
def find_max_sub_array(A,low,high):
|
||||
if low==high:
|
||||
return low,high,A[low]
|
||||
else :
|
||||
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)
|
||||
if left_sum>=right_sum and left_sum>=cross_sum:
|
||||
return left_low,left_high,left_sum
|
||||
elif right_sum>=left_sum and right_sum>=cross_sum :
|
||||
return right_low,right_high,right_sum
|
||||
else:
|
||||
return cross_left,cross_right,cross_sum
|
||||
|
||||
def find_max_cross_sum(A,low,mid,high):
|
||||
left_sum,max_left=-999999999,-1
|
||||
right_sum,max_right=-999999999,-1
|
||||
summ=0
|
||||
for i in range(mid,low-1,-1):
|
||||
summ+=A[i]
|
||||
if summ > left_sum:
|
||||
left_sum=summ
|
||||
max_left=i
|
||||
summ=0
|
||||
for i in range(mid+1,high+1):
|
||||
summ+=A[i]
|
||||
if summ > right_sum:
|
||||
right_sum=summ
|
||||
max_right=i
|
||||
return max_left,max_right,(left_sum+right_sum)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
inputs=[10,100,1000,10000,50000,100000,200000,300000,400000,500000]
|
||||
tim=[]
|
||||
for i in inputs:
|
||||
li=[randint(1,i) for j in range(i)]
|
||||
strt=time.time()
|
||||
(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((inputs[i],'\t\t',tim[i]))
|
||||
plt.plot(inputs,tim)
|
||||
plt.xlabel("Number of Inputs");plt.ylabel("Time taken in seconds ")
|
||||
plt.show()
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
"""example of simple chaos machine"""
|
||||
from __future__ import print_function
|
||||
|
||||
# Chaos Machine (K, t, m)
|
||||
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
|
||||
|
||||
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.
|
||||
Output: The decision tree maps a real number input to a real number output.
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
"""
|
||||
Implementation of gradient descent algorithm for minimizing cost of a linear hypothesis function.
|
||||
"""
|
||||
from __future__ import print_function
|
||||
import numpy
|
||||
|
||||
# List of input, output pairs
|
||||
|
@ -106,13 +107,13 @@ def run_gradient_descent():
|
|||
atol=absolute_error_limit, rtol=relative_error_limit):
|
||||
break
|
||||
parameter_vector = temp_parameter_vector
|
||||
print("Number of iterations:", j)
|
||||
print(("Number of iterations:", j))
|
||||
|
||||
|
||||
def test_gradient_descent():
|
||||
for i in range(len(test_data)):
|
||||
print("Actual output value:", output(i, 'test'))
|
||||
print("Hypothesis output:", calculate_hypothesis_value(i, 'test'))
|
||||
print(("Actual output value:", output(i, 'test')))
|
||||
print(("Hypothesis output:", calculate_hypothesis_value(i, 'test')))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
|
|
@ -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
|
||||
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
|
||||
|
|
|
@ -9,6 +9,7 @@
|
|||
p2 = 1
|
||||
|
||||
'''
|
||||
from __future__ import print_function
|
||||
|
||||
import random
|
||||
|
||||
|
@ -52,7 +53,7 @@ class Perceptron:
|
|||
epoch_count = epoch_count + 1
|
||||
# if you want controle the epoch or just by erro
|
||||
if erro == False:
|
||||
print('\nEpoch:\n',epoch_count)
|
||||
print(('\nEpoch:\n',epoch_count))
|
||||
print('------------------------\n')
|
||||
#if epoch_count > self.epoch_number or not erro:
|
||||
break
|
||||
|
@ -66,10 +67,10 @@ class Perceptron:
|
|||
y = self.sign(u)
|
||||
|
||||
if y == -1:
|
||||
print('Sample: ', sample)
|
||||
print(('Sample: ', sample))
|
||||
print('classification: P1')
|
||||
else:
|
||||
print('Sample: ', sample)
|
||||
print(('Sample: ', sample))
|
||||
print('classification: P2')
|
||||
|
||||
def sign(self, u):
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
import numpy
|
||||
import numpy as np
|
||||
|
||||
""" Here I implemented the scoring functions.
|
||||
MAE, MSE, RMSE, RMSLE are included.
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
__author__ = "Tobias Carryer"
|
||||
|
||||
from time import time
|
||||
|
@ -31,4 +32,4 @@ if __name__ == "__main__":
|
|||
# Show the LCG in action.
|
||||
lcg = LinearCongruentialGenerator(1664525, 1013904223, 2<<31)
|
||||
while True :
|
||||
print lcg.next_number()
|
||||
print(lcg.next_number())
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
import collections, pprint, time, os
|
||||
|
||||
start_time = time.time()
|
||||
|
@ -25,4 +26,4 @@ with open('anagrams.txt', 'w') as file:
|
|||
file.write(pprint.pformat(all_anagrams))
|
||||
|
||||
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
|
||||
|
||||
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.
|
||||
|
||||
'''
|
||||
from __future__ import print_function
|
||||
|
||||
|
||||
def is_balanced(S):
|
||||
|
@ -39,10 +40,10 @@ def main():
|
|||
S = input("Enter sequence of brackets: ")
|
||||
|
||||
if is_balanced(S):
|
||||
print(S, "is balanced")
|
||||
print((S, "is balanced"))
|
||||
|
||||
else:
|
||||
print(S, "is not balanced")
|
||||
print((S, "is not balanced"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
import string
|
||||
import random
|
||||
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
def moveTower(height, fromPole, toPole, withPole):
|
||||
'''
|
||||
>>> moveTower(3, 'A', 'B', 'C')
|
||||
|
@ -15,7 +16,7 @@ def moveTower(height, fromPole, toPole, withPole):
|
|||
moveTower(height-1, withPole, toPole, fromPole)
|
||||
|
||||
def moveDisk(fp,tp):
|
||||
print('moving disk from', fp, 'to', tp)
|
||||
print(('moving disk from', fp, 'to', tp))
|
||||
|
||||
def main():
|
||||
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,
|
||||
return [0, 1].
|
||||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
def twoSum(nums, target):
|
||||
"""
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
import pprint, time
|
||||
|
||||
def getWordPattern(word):
|
||||
|
@ -32,7 +33,7 @@ def main():
|
|||
fo.write(pprint.pformat(allPatterns))
|
||||
|
||||
totalTime = round(time.time() - startTime, 2)
|
||||
print('Done! [', totalTime, 'seconds ]')
|
||||
print(('Done! [', totalTime, 'seconds ]'))
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
|
|
@ -12,6 +12,11 @@ python binary_search.py
|
|||
from __future__ import print_function
|
||||
import bisect
|
||||
|
||||
try:
|
||||
raw_input # Python 2
|
||||
except NameError:
|
||||
raw_input = input # Python 3
|
||||
|
||||
|
||||
def binary_search(sorted_collection, item):
|
||||
"""Pure implementation of binary search algorithm in Python
|
||||
|
@ -137,23 +142,14 @@ def __assert_sorted(collection):
|
|||
|
||||
if __name__ == '__main__':
|
||||
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(',')]
|
||||
try:
|
||||
__assert_sorted(collection)
|
||||
except ValueError:
|
||||
sys.exit('Sequence must be sorted to apply binary search')
|
||||
|
||||
target_input = input_function(
|
||||
'Enter a single number to be found in the list:\n'
|
||||
)
|
||||
target_input = raw_input('Enter a single number to be found in the list:\n')
|
||||
target = int(target_input)
|
||||
result = binary_search(collection, target)
|
||||
if result is not None:
|
||||
|
|
|
@ -4,6 +4,11 @@ This is pure python implementation of interpolation search algorithm
|
|||
from __future__ import print_function
|
||||
import bisect
|
||||
|
||||
try:
|
||||
raw_input # Python 2
|
||||
except NameError:
|
||||
raw_input = input # Python 3
|
||||
|
||||
|
||||
def interpolation_search(sorted_collection, item):
|
||||
"""Pure implementation of interpolation search algorithm in Python
|
||||
|
@ -77,26 +82,18 @@ def __assert_sorted(collection):
|
|||
|
||||
if __name__ == '__main__':
|
||||
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(',')]
|
||||
try:
|
||||
__assert_sorted(collection)
|
||||
except ValueError:
|
||||
sys.exit('Sequence must be sorted to apply interpolation search')
|
||||
|
||||
target_input = input_function(
|
||||
'Enter a single number to be found in the list:\n'
|
||||
)
|
||||
target_input = raw_input('Enter a single number to be found in the list:\n')
|
||||
target = int(target_input)
|
||||
result = interpolation_search(collection, target)
|
||||
if result is not None:
|
||||
print('{} found at positions: {}'.format(target, result))
|
||||
else:
|
||||
print('Not found')
|
||||
print('Not found')
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
import math
|
||||
def jump_search(arr, x):
|
||||
n = len(arr)
|
||||
|
|
|
@ -11,6 +11,10 @@ python linear_search.py
|
|||
"""
|
||||
from __future__ import print_function
|
||||
|
||||
try:
|
||||
raw_input # Python 2
|
||||
except NameError:
|
||||
raw_input = input # Python 3
|
||||
|
||||
def linear_search(sequence, target):
|
||||
"""Pure implementation of linear search algorithm in Python
|
||||
|
@ -39,21 +43,10 @@ def linear_search(sequence, target):
|
|||
|
||||
|
||||
if __name__ == '__main__':
|
||||
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 coma:\n')
|
||||
user_input = raw_input('Enter numbers separated by coma:\n').strip()
|
||||
sequence = [int(item) for item in user_input.split(',')]
|
||||
|
||||
target_input = input_function(
|
||||
'Enter a single number to be found in the list:\n'
|
||||
)
|
||||
target_input = raw_input('Enter a single number to be found in the list:\n')
|
||||
target = int(target_input)
|
||||
result = linear_search(sequence, target)
|
||||
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)
|
||||
Space Complexity : O(1)
|
||||
'''
|
||||
from __future__ import print_function
|
||||
|
||||
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.
|
||||
# It is recommended for users to keep this number greater than or equal to 10.
|
||||
precision = 10
|
||||
|
@ -81,16 +87,7 @@ def __assert_sorted(collection):
|
|||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
# 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')
|
||||
user_input = raw_input('Enter numbers separated by coma:\n').strip()
|
||||
collection = [int(item) for item in user_input.split(',')]
|
||||
|
||||
try:
|
||||
|
@ -98,9 +95,7 @@ if __name__ == '__main__':
|
|||
except ValueError:
|
||||
sys.exit('Sequence must be sorted to apply the ternary search')
|
||||
|
||||
target_input = input_function(
|
||||
'Enter a single number to be found in the list:\n'
|
||||
)
|
||||
target_input = raw_input('Enter a single number to be found in the list:\n')
|
||||
target = int(target_input)
|
||||
result1 = ite_ternary_search(collection, target)
|
||||
result2 = rec_ternary_search(0, len(collection)-1, collection, target)
|
||||
|
|
|
@ -39,15 +39,11 @@ def bogosort(collection):
|
|||
return collection
|
||||
|
||||
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
|
||||
# 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')
|
||||
user_input = raw_input('Enter numbers separated by a comma:\n').stript()
|
||||
unsorted = [int(item) for item in user_input.split(',')]
|
||||
print(bogosort(unsorted))
|
||||
|
|
|
@ -40,14 +40,11 @@ def bubble_sort(collection):
|
|||
|
||||
|
||||
if __name__ == '__main__':
|
||||
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
|
||||
try:
|
||||
raw_input # Python 2
|
||||
except NameError:
|
||||
raw_input = input # Python 3
|
||||
|
||||
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(',')]
|
||||
print(bubble_sort(unsorted))
|
||||
|
|
|
@ -13,6 +13,7 @@
|
|||
# Time Complexity of Solution:
|
||||
# Best Case O(n); Average Case O(n); Worst Case O(n)
|
||||
|
||||
from __future__ import print_function
|
||||
from P26_InsertionSort import insertionSort
|
||||
import math
|
||||
|
||||
|
|
|
@ -21,16 +21,12 @@ def cocktail_shaker_sort(unsorted):
|
|||
return unsorted
|
||||
|
||||
if __name__ == '__main__':
|
||||
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
|
||||
try:
|
||||
raw_input # Python 2
|
||||
except NameError:
|
||||
raw_input = input # Python 3
|
||||
|
||||
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(',')]
|
||||
cocktail_shaker_sort(unsorted)
|
||||
print(unsorted)
|
||||
print(unsorted)
|
||||
|
|
|
@ -59,14 +59,11 @@ def counting_sort(collection):
|
|||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import sys
|
||||
# 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
|
||||
try:
|
||||
raw_input # Python 2
|
||||
except NameError:
|
||||
raw_input = input # Python 3
|
||||
|
||||
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(',')]
|
||||
print(counting_sort(unsorted))
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
# Python program for counting sort
|
||||
|
||||
# This is the main function that sort the given string arr[] in
|
||||
|
|
|
@ -158,4 +158,4 @@ def main():
|
|||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
main()
|
||||
|
|
|
@ -19,16 +19,12 @@ def gnome_sort(unsorted):
|
|||
i = 1
|
||||
|
||||
if __name__ == '__main__':
|
||||
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
|
||||
try:
|
||||
raw_input # Python 2
|
||||
except NameError:
|
||||
raw_input = input # Python 3
|
||||
|
||||
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(',')]
|
||||
gnome_sort(unsorted)
|
||||
print(unsorted)
|
||||
print(unsorted)
|
||||
|
|
|
@ -54,12 +54,11 @@ def heap_sort(unsorted):
|
|||
return unsorted
|
||||
|
||||
if __name__ == '__main__':
|
||||
import sys
|
||||
if sys.version_info.major < 3:
|
||||
input_function = raw_input
|
||||
else:
|
||||
input_function = input
|
||||
try:
|
||||
raw_input # Python 2
|
||||
except NameError:
|
||||
raw_input = input # Python 3
|
||||
|
||||
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(',')]
|
||||
print(heap_sort(unsorted))
|
||||
|
|
|
@ -39,15 +39,11 @@ def insertion_sort(collection):
|
|||
|
||||
|
||||
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
|
||||
# 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')
|
||||
user_input = raw_input('Enter numbers separated by a comma:\n').strip()
|
||||
unsorted = [int(item) for item in user_input.split(',')]
|
||||
print(insertion_sort(unsorted))
|
||||
|
|
|
@ -62,15 +62,11 @@ def merge_sort(collection):
|
|||
|
||||
|
||||
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
|
||||
# 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')
|
||||
user_input = raw_input('Enter numbers separated by a comma:\n').strip()
|
||||
unsorted = [int(item) for item in user_input.split(',')]
|
||||
print(merge_sort(unsorted))
|
||||
|
|
|
@ -40,15 +40,11 @@ def quick_sort(ARRAY):
|
|||
|
||||
|
||||
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
|
||||
# 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')
|
||||
user_input = raw_input('Enter numbers separated by a comma:\n').strip()
|
||||
unsorted = [ int(item) for item in user_input.split(',') ]
|
||||
print( quick_sort(unsorted) )
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
from random import randint
|
||||
from tempfile import TemporaryFile
|
||||
import numpy as np
|
||||
|
|
|
@ -43,14 +43,11 @@ def selection_sort(collection):
|
|||
|
||||
|
||||
if __name__ == '__main__':
|
||||
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
|
||||
try:
|
||||
raw_input # Python 2
|
||||
except NameError:
|
||||
raw_input = input # Python 3
|
||||
|
||||
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(',')]
|
||||
print(selection_sort(unsorted))
|
||||
|
|
|
@ -44,14 +44,11 @@ def shell_sort(collection):
|
|||
return collection
|
||||
|
||||
if __name__ == '__main__':
|
||||
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
|
||||
try:
|
||||
raw_input # Python 2
|
||||
except NameError:
|
||||
raw_input = input # Python 3
|
||||
|
||||
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(',')]
|
||||
print(shell_sort(unsorted))
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
def binary_search(lst, item, start, end):
|
||||
if start == end:
|
||||
if lst[start] > item:
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
from __future__ import print_function
|
||||
# a
|
||||
# / \
|
||||
# b c
|
||||
|
|
|
@ -4,6 +4,11 @@ This is pure python implementation of tree traversal algorithms
|
|||
from __future__ import print_function
|
||||
import queue
|
||||
|
||||
try:
|
||||
raw_input # Python 2
|
||||
except NameError:
|
||||
raw_input = input # Python 3
|
||||
|
||||
|
||||
class TreeNode:
|
||||
def __init__(self, data):
|
||||
|
@ -15,26 +20,26 @@ class TreeNode:
|
|||
def build_tree():
|
||||
print("\n********Press N to stop entering at any point of time********\n")
|
||||
print("Enter the value of the root node: ", end="")
|
||||
check=input()
|
||||
if check=='N' or check=='n':
|
||||
check = raw_input().strip().lower()
|
||||
if check == 'n':
|
||||
return None
|
||||
data=int(check)
|
||||
data = int(check)
|
||||
q = queue.Queue()
|
||||
tree_node = TreeNode(data)
|
||||
q.put(tree_node)
|
||||
while not q.empty():
|
||||
node_found = q.get()
|
||||
print("Enter the left node of %s: " % node_found.data, end="")
|
||||
check=input()
|
||||
if check=='N' or check =='n':
|
||||
check = raw_input().strip().lower()
|
||||
if check == 'n':
|
||||
return tree_node
|
||||
left_data = int(check)
|
||||
left_node = TreeNode(left_data)
|
||||
node_found.left = left_node
|
||||
q.put(left_node)
|
||||
print("Enter the right node of %s: " % node_found.data, end="")
|
||||
check = input()
|
||||
if check == 'N' or check == 'n':
|
||||
check = raw_input().strip().lower()
|
||||
if check == 'n':
|
||||
return tree_node
|
||||
right_data = int(check)
|
||||
right_node = TreeNode(right_data)
|
||||
|
@ -81,15 +86,7 @@ def level_order(node):
|
|||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import sys
|
||||
|
||||
print("\n********* Binary Tree Traversals ************\n")
|
||||
# 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
|
||||
|
||||
node = build_tree()
|
||||
print("\n********* Pre Order Traversal ************")
|
||||
|
|
Loading…
Reference in New Issue
Block a user