Created
March 12, 2014 16:16
-
-
Save jvrsgsty/9510298 to your computer and use it in GitHub Desktop.
Ejemplos Python 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import optparse | |
import time | |
def fibo(n): | |
if n<= 1: | |
return n | |
return fibo(n-1)+fibo(n-2) | |
def fiboTD(n, tabla): | |
if n<=1: | |
return n | |
if tabla[n-1] == -1: | |
tabla[n-1] = fiboTD(n-1, tabla) | |
if tabla[n-2] == -1: | |
tabla[n-2] = fiboTD(n-2, tabla) | |
tabla[n] = tabla[n-1] + tabla[n-2] | |
return tabla[n] | |
def fiboBU(n): | |
if n<= 1: | |
return n | |
table = np.zeros(n+1) | |
table[0] = 0 | |
table[1] = 1 | |
for i in range(n-1): | |
table[i+2] = table[i+1] + table[i] | |
return table[n] | |
if __name__ == '__main__': | |
n = 30 | |
table = -np.ones(n+1) | |
t1 = time.time() | |
fibo = fibo(n) | |
t2 = time.time() | |
fiboTD = fiboTD(n,table) | |
t3 = time.time() | |
fiboBU = fiboBU(n) | |
t4 = time.time() | |
print 'Time to compute using fibo: ' + str(t2-t1) | |
print 'Time to compute using fiboTD: ' + str(t3-t2) | |
print 'Time to compute using fiboBU: ' + str(t4-t3) | |
print 'The ' + str(n) + 'th term of the fibonacci sequence is: ' + str(fibo) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import networkx as nx | |
from openopt import * | |
import optparse | |
def solve(file, n, s): | |
if s: | |
data = np.genfromtxt(file) | |
else: | |
data = np.genfromtxt(file, delimiter=',') | |
G = nx.convert.from_numpy_matrix(data) | |
p = TSP(G, objective='weight', iprint=-1) | |
res = p.solve('sa') | |
minF = res.ff | |
for i in range(n-1): | |
r = p.solve('sa') | |
if r.ff < minF: | |
res = r | |
minF = res.ff | |
return res | |
if __name__ == '__main__': | |
parser = optparse.OptionParser() | |
parser.add_option('-n', '--n', dest='n', default=5, type='int', | |
help='The number of TSP runs') | |
parser.add_option('-f', '--file', dest='file', default='', | |
help='The csv file contianing the node-node matrix ox the graph') | |
parser.add_option('-s', '--spaces', dest='spaces', default=False, action='store_true', | |
help='The file is separated by spaces') | |
(options, _)=parser.parse_args() | |
n = options.n | |
f = options.file | |
s = options.spaces | |
print 'Solving...' | |
r = solve(f,n,s) | |
print 'Solution: ' | |
print '==========' | |
print 'Path length: ' + str(r.ff) | |
for e in r.Edges: | |
print e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment