Skip to content

Commit

Permalink
Modernize Python 2 code to get ready for Python 3
Browse files Browse the repository at this point in the history
  • Loading branch information
cclauss committed Nov 25, 2017
1 parent a03b2ea commit 4e06949
Show file tree
Hide file tree
Showing 95 changed files with 583 additions and 524 deletions.
36 changes: 18 additions & 18 deletions File_Transfer_Protocol/ftp_send_receive.py
Original file line number Diff line number Diff line change
@@ -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 """
Expand Down
9 changes: 5 additions & 4 deletions Graphs/a_star.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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])

34 changes: 24 additions & 10 deletions Graphs/basic-graphs.py
Original file line number Diff line number Diff line change
@@ -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(" "))

Expand Down Expand Up @@ -48,15 +60,15 @@

def dfs(G, s):
vis, S = set([s]), [s]
print s
print(s)
while S:
flag = 0
for i in G[S[-1]]:
if i not in vis:
S.append(i)
vis.add(i)
flag = 1
print i
print(i)
break
if not flag:
S.pop()
Expand All @@ -76,14 +88,14 @@ def dfs(G, s):

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)


"""
Expand Down Expand Up @@ -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])


"""
Expand All @@ -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:
Expand Down Expand Up @@ -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):
Expand All @@ -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)


"""
Expand Down Expand Up @@ -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]:
Expand Down
1 change: 1 addition & 0 deletions Graphs/minimum_spanning_tree_kruskal.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
num_nodes, num_edges = list(map(int,input().split()))

edges = []
Expand Down
1 change: 1 addition & 0 deletions Graphs/scc_kosaraju.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
# n - no of nodes, m - no of edges
n, m = list(map(int,input().split()))

Expand Down
38 changes: 22 additions & 16 deletions Multi_Hueristic_Astar.py
Original file line number Diff line number Diff line change
@@ -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):
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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)
9 changes: 5 additions & 4 deletions Neural_Network/convolution_neural_network.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
Date: 2017.9.20
- - - - - -- - - - - - - - - - - - - - - - - - - - - - -
'''
from __future__ import print_function

import numpy as np
import matplotlib.pyplot as plt
Expand Down Expand Up @@ -192,8 +193,8 @@ def _calculate_gradient_from_pool(self,out_map,pd_pool,num_map,size_map,size_poo
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
Expand Down Expand Up @@ -262,7 +263,7 @@ def draw_error():
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
Expand All @@ -271,7 +272,7 @@ def predict(self,datas_test):
#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,
Expand Down
7 changes: 4 additions & 3 deletions Neural_Network/perceptron.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
p2 = 1
'''
from __future__ import print_function

import random

Expand Down Expand Up @@ -52,7 +53,7 @@ def trannig(self):
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
Expand All @@ -66,10 +67,10 @@ def sort(self, sample):
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):
Expand Down
9 changes: 7 additions & 2 deletions Project Euler/Problem 01/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,14 @@
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)
7 changes: 6 additions & 1 deletion Project Euler/Problem 01/sol2.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
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
Expand All @@ -12,4 +17,4 @@
sum+= ((terms)*(10+(terms-1)*5))/2
terms = (n-1)/15
sum-= ((terms)*(30+(terms-1)*15))/2
print sum
print(sum)
Loading

0 comments on commit 4e06949

Please sign in to comment.