def main(): f = open_data_file("pb83matrix.txt") matrix = [ [int(x) for x in line.split(",")] for line in f ] size = len(matrix) distances = [ [float("inf")]*size for i in range(size) ] heap = [] heappush(heap, (matrix[0][0], 0, 0)) # distance, row, col # Dijkstra's algorithm, simplified while heap: distance, row, col = heappop(heap) neighbors = [] if row > 0: neighbors.append((distance+matrix[row-1][col], row-1, col)), # up if col < size-1: neighbors.append((distance+matrix[row][col+1], row, col+1)), # right if row < size-1: neighbors.append((distance+matrix[row+1][col], row+1, col)), # down if col > 0: neighbors.append((distance+matrix[row][col-1], row, col-1)), # left for node in neighbors: if node[0] < distances[node[1]][node[2]]: heappush(heap, node) distances[node[1]][node[2]] = node[0] if row == col == size-1: return distance
def main(): triangle_numbers = [triangle(n) for n in range(1, 100)] words = [word.strip('"') for word in open_data_file(os.path.join(os.path.dirname(__file__), 'words.txt')).read().split(',')] total = 0 for word in words: if word_value(word) in triangle_numbers: total += 1 print total
def main(): cipher = [int(c) for c in open_data_file('pb59cipher.txt').read().strip().split(',')] candidates = ascii_lowercase passwords = product(candidates, candidates, candidates) for p in passwords: password = [ord(c) for c in p] plaintext = ''.join(list(decipher(cipher, password))) if is_english(plaintext): print sum(ord(c) for c in plaintext) return
def main(): triangle_numbers = [triangle(n) for n in range(1, 100)] words = [ word.strip('"') for word in open_data_file( os.path.join(os.path.dirname(__file__), 'words.txt')).read().split( ',') ] total = 0 for word in words: if word_value(word) in triangle_numbers: total += 1 print total
def answer(): with open_data_file('pb98words.txt') as f: pair = {} tmp = {} words = f.read().replace('\"', '').split(',') for w in words: t = tuple(sorted(set(w))) if t in tmp: tmp[t] += [w] else: tmp[t] = [w] for i in tmp: l = len(tmp[i]) if l > 1: for j in range(l - 1): for m in range(j + 1, l): w1 = tmp[i][j] w2 = tmp[i][m] if sorted(w1) == sorted(w2): pair[w1, w2] = len(w1) pair = sorted(pair.items(), lambda x, y: cmp(y[1], x[1])) for (w1, w2), l in pair: m = 0 s = set(w1) k = len(s) for i in itertools.combinations('9876543210', k): for j in itertools.permutations(i, k): w4 = w1 for p in range(k): w4 = w4.replace(list(s)[p], j[p]) if w4[0] != '0': n1 = int(''.join(w4)) if check(n1): w3 = w2 for p in range(k): w3 = w3.replace(list(s)[p], j[p]) if w3[0] != '0': n2 = int(''.join(w3)) if check(n2): print n1, n2, w1, w2 return
def answer(): with open_data_file('pb98words.txt') as f: pair={} tmp={} words=f.read().replace('\"','').split(',') for w in words: t=tuple(sorted(set(w))) if t in tmp: tmp[t]+=[w] else: tmp[t]=[w] for i in tmp: l=len(tmp[i]) if l>1: for j in range(l-1): for m in range(j+1,l): w1=tmp[i][j] w2=tmp[i][m] if sorted(w1)==sorted(w2): pair[w1,w2]=len(w1) pair=sorted(pair.items(),lambda x,y:cmp(y[1],x[1])) for (w1,w2),l in pair: m=0 s=set(w1) k=len(s) for i in itertools.combinations('9876543210',k): for j in itertools.permutations(i,k): w4=w1 for p in range(k): w4=w4.replace(list(s)[p],j[p]) if w4[0]!='0': n1=int(''.join(w4)) if check(n1): w3=w2 for p in range(k): w3=w3.replace(list(s)[p],j[p]) if w3[0]!='0': n2=int(''.join(w3)) if check(n2): print n1,n2,w1,w2 return
def main(): f = open_data_file("pb82matrix.txt") matrix = [[int(x) for x in line.split(",")] for line in f] size = len(matrix) best = [row[0] for row in matrix] # first column for col in range(1, size): column = [matrix[row][col] + best[row] for row in range(size)] for row in range(1, size): if column[row - 1] + matrix[row][col] < column[row]: column[row] = column[row - 1] + matrix[row][col] for row in range(size - 2, -1, -1): if column[row + 1] + matrix[row][col] < column[row]: column[row] = column[row + 1] + matrix[row][col] best = column return min(best)
def main(): f = open_data_file("pb82matrix.txt") matrix = [ [int(x) for x in line.split(",")] for line in f ] size = len(matrix) best = [row[0] for row in matrix] # first column for col in range(1, size): column = [ matrix[row][col] + best[row] for row in range(size) ] for row in range(1, size): if column[row-1] + matrix[row][col] < column[row]: column[row] = column[row-1] + matrix[row][col] for row in range(size-2, -1, -1): if column[row+1] + matrix[row][col] < column[row]: column[row] = column[row+1] + matrix[row][col] best = column return min(best)
def main(): """Main Program""" player1 = 0 f = open_data_file('poker.txt') for line in f: x = line.split(' ') y = ''.join(x) player_one = y[0:10] player_two = y[10:20] j = examine_cards(player_one) t = examine_cards(player_two) if j == t: print "player_one = ", player_one print "player_two = ", player_two print "EQUAL" elif j < t: continue elif j > t: player1 += 1 else: pass f.close() print "Answer = ", player1
def main(): f = open_data_file("pb83matrix.txt") matrix = [[int(x) for x in line.split(",")] for line in f] size = len(matrix) distances = [[float("inf")] * size for i in range(size)] heap = [] heappush(heap, (matrix[0][0], 0, 0)) # distance, row, col # Dijkstra's algorithm, simplified while heap: distance, row, col = heappop(heap) neighbors = [] if row > 0: neighbors.append( (distance + matrix[row - 1][col], row - 1, col)), # up if col < size - 1: neighbors.append( (distance + matrix[row][col + 1], row, col + 1)), # right if row < size - 1: neighbors.append( (distance + matrix[row + 1][col], row + 1, col)), # down if col > 0: neighbors.append( (distance + matrix[row][col - 1], row, col - 1)), # left for node in neighbors: if node[0] < distances[node[1]][node[2]]: heappush(heap, node) distances[node[1]][node[2]] = node[0] if row == col == size - 1: return distance
triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred lines. NOTE: This is a much more difficult version of Problem 18. It is not possible to try every route to solve this problem, as there are 299 altogether! If you could check one trillion (1012) routes every second it would take over twenty billion years to check them all. There is an efficient algorithm to solve it. ;o) """ from projecteuler import open_data_file sumlist = [0] * 200 f = open_data_file('triangle.txt') for line in f: i = 0 cells = line.split() sumlist_prev = sumlist[:] for cell in cells: #first number if i == 0: sumlist[i] = sumlist_prev[i] + int(cell) #last number elif i == len(cells) - 1: sumlist[i] = sumlist_prev[i - 1] + int(cell) else: sumlist[i] = max(sumlist_prev[i] + int(cell), sumlist_prev[i - 1] + int(cell))
triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred lines. NOTE: This is a much more difficult version of Problem 18. It is not possible to try every route to solve this problem, as there are 299 altogether! If you could check one trillion (1012) routes every second it would take over twenty billion years to check them all. There is an efficient algorithm to solve it. ;o) """ from projecteuler import open_data_file sumlist = [0]*200 f = open_data_file('triangle.txt') for line in f: i = 0 cells = line.split() sumlist_prev = sumlist[:] for cell in cells: #first number if i == 0: sumlist[i] = sumlist_prev[i] + int(cell) #last number elif i == len(cells)-1: sumlist[i] = sumlist_prev[i-1] + int(cell) else: sumlist[i] = max(sumlist_prev[i] + int(cell), sumlist_prev[i-1] + int(cell)) i += 1
#!/usr/bin/env python from projecteuler import open_data_file import time # define a recursive function to create partial sums by row def recSumAtRow(rowData, rowNum): # iterate over the given row for i in range(len(rowData[rowNum])): # add the largest of the values below-left or below-right rowData[rowNum][i] += max([rowData[rowNum+1][i],rowData[rowNum+1][i+1]]) # base case if len(rowData[rowNum])==1: return rowData[rowNum][0] # recursive case else: return recSumAtRow(rowData, rowNum-1) # read in the data rows = [] with open_data_file("problem-18-data") as f: for line in f: rows.append([int(i) for i in line.rstrip('\n').split(" ")]) start = time.time() result = recSumAtRow(rows, len(rows)-2) # start at second to last row elapsed = time.time() - start print "%s found in %s seconds" % (result ,elapsed)
import time # define a recursive function to create partial sums by row def recSumAtRow(rowData, rowNum): # iterate over the given row for i in range(len(rowData[rowNum])): # add the largest of the values below-left or below-right rowData[rowNum][i] += max( [rowData[rowNum + 1][i], rowData[rowNum + 1][i + 1]]) # base case if len(rowData[rowNum]) == 1: return rowData[rowNum][0] # recursive case else: return recSumAtRow(rowData, rowNum - 1) # read in the data rows = [] with open_data_file("problem-18-data") as f: for line in f: rows.append([int(i) for i in line.rstrip('\n').split(" ")]) start = time.time() result = recSumAtRow(rows, len(rows) - 2) # start at second to last row elapsed = time.time() - start print "%s found in %s seconds" % (result, elapsed)
from projecteuler import open_data_file # This function takes a name / password and returns its text value def name_score ( name ): score = 0 #Lecture one by one letter from the word for i in name : #The ord function takes a character parameter and returns its ascii code ascii #The of A being 65, we subtract 64 to ascii code # a letter to get its position in the alphabet score += ord ( i ) - 64 return score file = open_data_file("022_names.txt") #Lecture names the file and generate a list of names names = list ( eval ( file . read ())) file . close () names.sort() result = 0 for i, name in enumerate(names): result += name_score(name)*(i+1) print ( result )
from projecteuler import open_data_file # This function takes a name / password and returns its text value def name_score(name): score = 0 #Lecture one by one letter from the word for i in name: #The ord function takes a character parameter and returns its ascii code ascii #The of A being 65, we subtract 64 to ascii code # a letter to get its position in the alphabet score += ord(i) - 64 return score file = open_data_file("022_names.txt") #Lecture names the file and generate a list of names names = list(eval(file.read())) file.close() names.sort() result = 0 for i, name in enumerate(names): result += name_score(name) * (i + 1) print(result)
#http://blog.singhanuvrat.com/problems/project-euler-greatest-exponent-value ''' Created on Oct 23, 2012 @author: anuvrat ''' from projecteuler import open_data_file import numpy max_digits = max_line = line_idx = 0 for line in ( line.rstrip( '\n' ) for line in open_data_file( 'pb99baseexp.txt' ) ): base, exponent = map( int, line.split( ',' ) ) digits = exponent * numpy.log10( base ) if digits > max_digits : max_digits = digits max_line = line_idx line_idx += 1 print max_line + 1
bold red and is equal to 2427. 131 673 234 103 18 201 96 342 965 150 630 803 746 422 111 537 699 497 121 956 805 732 524 37 331 Find the minimal path sum, in matrix.txt (right click and 'Save Link/Target As...'), a 31K text file containing a 80 by 80 matrix, from the top left to the bottom right by only moving right and down. """ from projecteuler import open_data_file f = open_data_file("pb82matrix.txt") matrix = [] for line in f: numbers = [int(n) for n in line.split(',')] matrix.append(numbers) num = len(matrix) - 1 for i in range(num+1): for j in range(num+1): if (i == 0 and j == 0): continue if (j == 0): minx = matrix[i-1][j] elif (i == 0): minx = matrix[i][j-1] else: minx = min(matrix[i-1][j], matrix[i][j-1]) matrix[i][j] += minx print matrix[num][num]