Datasets:

zip
stringlengths
19
109
filename
stringlengths
4
185
contents
stringlengths
0
30.1M
type_annotations
sequencelengths
0
1.97k
type_annotation_starts
sequencelengths
0
1.97k
type_annotation_ends
sequencelengths
0
1.97k
archives/1098994933_python.zip
matrix/tests/test_matrix_operation.py
""" Testing here assumes that numpy and linalg is ALWAYS correct!!!! If running from PyCharm you can place the following line in "Additional Arguments" for the pytest run configuration -vv -m mat_ops -p no:cacheprovider """ # standard libraries import sys import numpy as np import pytest import logging # Custom/local libraries from matrix import matrix_operation as matop mat_a = [[12, 10], [3, 9]] mat_b = [[3, 4], [7, 4]] mat_c = [[3, 0, 2], [2, 0, -2], [0, 1, 1]] mat_d = [[3, 0, -2], [2, 0, 2], [0, 1, 1]] mat_e = [[3, 0, 2], [2, 0, -2], [0, 1, 1], [2, 0, -2]] mat_f = [1] mat_h = [2] logger = logging.getLogger() logger.level = logging.DEBUG stream_handler = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) @pytest.mark.mat_ops @pytest.mark.parametrize(('mat1', 'mat2'), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)]) def test_addition(mat1, mat2): if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2): with pytest.raises(TypeError): logger.info(f"\n\t{test_addition.__name__} returned integer") matop.add(mat1, mat2) elif (np.array(mat1)).shape == (np.array(mat2)).shape: logger.info(f"\n\t{test_addition.__name__} with same matrix dims") act = (np.array(mat1) + np.array(mat2)).tolist() theo = matop.add(mat1, mat2) assert theo == act else: with pytest.raises(ValueError): logger.info(f"\n\t{test_addition.__name__} with different matrix dims") matop.add(mat1, mat2) @pytest.mark.mat_ops @pytest.mark.parametrize(('mat1', 'mat2'), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)]) def test_subtraction(mat1, mat2): if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2): with pytest.raises(TypeError): logger.info(f"\n\t{test_subtraction.__name__} returned integer") matop.subtract(mat1, mat2) elif (np.array(mat1)).shape == (np.array(mat2)).shape: logger.info(f"\n\t{test_subtraction.__name__} with same matrix dims") act = (np.array(mat1) - np.array(mat2)).tolist() theo = matop.subtract(mat1, mat2) assert theo == act else: with pytest.raises(ValueError): logger.info(f"\n\t{test_subtraction.__name__} with different matrix dims") assert matop.subtract(mat1, mat2) @pytest.mark.mat_ops @pytest.mark.parametrize(('mat1', 'mat2'), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)]) def test_multiplication(mat1, mat2): if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2): logger.info(f"\n\t{test_multiplication.__name__} returned integer") with pytest.raises(TypeError): matop.add(mat1, mat2) elif (np.array(mat1)).shape == (np.array(mat2)).shape: logger.info(f"\n\t{test_multiplication.__name__} meets dim requirements") act = (np.matmul(mat1, mat2)).tolist() theo = matop.multiply(mat1, mat2) assert theo == act else: with pytest.raises(ValueError): logger.info(f"\n\t{test_multiplication.__name__} does not meet dim requirements") assert matop.subtract(mat1, mat2) @pytest.mark.mat_ops def test_scalar_multiply(): act = (3.5 * np.array(mat_a)).tolist() theo = matop.scalar_multiply(mat_a, 3.5) assert theo == act @pytest.mark.mat_ops def test_identity(): act = (np.identity(5)).tolist() theo = matop.identity(5) assert theo == act @pytest.mark.mat_ops @pytest.mark.parametrize('mat', [mat_a, mat_b, mat_c, mat_d, mat_e, mat_f]) def test_transpose(mat): if (np.array(mat)).shape < (2, 2): with pytest.raises(TypeError): logger.info(f"\n\t{test_transpose.__name__} returned integer") matop.transpose(mat) else: act = (np.transpose(mat)).tolist() theo = matop.transpose(mat, return_map=False) assert theo == act
[]
[]
[]
archives/1098994933_python.zip
networking_flow/ford_fulkerson.py
# Ford-Fulkerson Algorithm for Maximum Flow Problem """ Description: (1) Start with initial flow as 0; (2) Choose augmenting path from source to sink and add path to flow; """ def BFS(graph, s, t, parent): # Return True if there is node that has not iterated. visited = [False]*len(graph) queue=[] queue.append(s) visited[s] = True while queue: u = queue.pop(0) for ind in range(len(graph[u])): if visited[ind] == False and graph[u][ind] > 0: queue.append(ind) visited[ind] = True parent[ind] = u return True if visited[t] else False def FordFulkerson(graph, source, sink): # This array is filled by BFS and to store path parent = [-1]*(len(graph)) max_flow = 0 while BFS(graph, source, sink, parent) : path_flow = float("Inf") s = sink while(s != source): # Find the minimum value in select path path_flow = min (path_flow, graph[parent[s]][s]) s = parent[s] max_flow += path_flow v = sink while(v != source): u = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow v = parent[v] return max_flow graph = [[0, 16, 13, 0, 0, 0], [0, 0, 10 ,12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0]] source, sink = 0, 5 print(FordFulkerson(graph, source, sink))
[]
[]
[]
archives/1098994933_python.zip
networking_flow/minimum_cut.py
# Minimum cut on Ford_Fulkerson algorithm. test_graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def BFS(graph, s, t, parent): # Return True if there is node that has not iterated. visited = [False] * len(graph) queue = [s] visited[s] = True while queue: u = queue.pop(0) for ind in range(len(graph[u])): if visited[ind] == False and graph[u][ind] > 0: queue.append(ind) visited[ind] = True parent[ind] = u return True if visited[t] else False def mincut(graph, source, sink): """This array is filled by BFS and to store path >>> mincut(test_graph, source=0, sink=5) [(1, 3), (4, 3), (4, 5)] """ parent = [-1] * (len(graph)) max_flow = 0 res = [] temp = [i[:] for i in graph] # Record orignial cut, copy. while BFS(graph, source, sink, parent): path_flow = float("Inf") s = sink while s != source: # Find the minimum value in select path path_flow = min(path_flow, graph[parent[s]][s]) s = parent[s] max_flow += path_flow v = sink while v != source: u = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow v = parent[v] for i in range(len(graph)): for j in range(len(graph[0])): if graph[i][j] == 0 and temp[i][j] > 0: res.append((i, j)) return res if __name__ == "__main__": print(mincut(test_graph, source=0, sink=5))
[]
[]
[]
archives/1098994933_python.zip
neural_network/back_propagation_neural_network.py
#!/usr/bin/python # encoding=utf8 ''' A Framework of Back Propagation Neural Network(BP) model Easy to use: * add many layers as you want !!! * clearly see how the loss decreasing Easy to expand: * more activation functions * more loss functions * more optimization method Author: Stephen Lee Github : https://github.com/RiptideBo Date: 2017.11.23 ''' import numpy as np import matplotlib.pyplot as plt def sigmoid(x): return 1 / (1 + np.exp(-1 * x)) class DenseLayer(): ''' Layers of BP neural network ''' def __init__(self,units,activation=None,learning_rate=None,is_input_layer=False): ''' common connected layer of bp network :param units: numbers of neural units :param activation: activation function :param learning_rate: learning rate for paras :param is_input_layer: whether it is input layer or not ''' self.units = units self.weight = None self.bias = None self.activation = activation if learning_rate is None: learning_rate = 0.3 self.learn_rate = learning_rate self.is_input_layer = is_input_layer def initializer(self,back_units): self.weight = np.asmatrix(np.random.normal(0,0.5,(self.units,back_units))) self.bias = np.asmatrix(np.random.normal(0,0.5,self.units)).T if self.activation is None: self.activation = sigmoid def cal_gradient(self): if self.activation == sigmoid: gradient_mat = np.dot(self.output ,(1- self.output).T) gradient_activation = np.diag(np.diag(gradient_mat)) else: gradient_activation = 1 return gradient_activation def forward_propagation(self,xdata): self.xdata = xdata if self.is_input_layer: # input layer self.wx_plus_b = xdata self.output = xdata return xdata else: self.wx_plus_b = np.dot(self.weight,self.xdata) - self.bias self.output = self.activation(self.wx_plus_b) return self.output def back_propagation(self,gradient): gradient_activation = self.cal_gradient() # i * i 维 gradient = np.asmatrix(np.dot(gradient.T,gradient_activation)) self._gradient_weight = np.asmatrix(self.xdata) self._gradient_bias = -1 self._gradient_x = self.weight self.gradient_weight = np.dot(gradient.T,self._gradient_weight.T) self.gradient_bias = gradient * self._gradient_bias self.gradient = np.dot(gradient,self._gradient_x).T # ----------------------upgrade # -----------the Negative gradient direction -------- self.weight = self.weight - self.learn_rate * self.gradient_weight self.bias = self.bias - self.learn_rate * self.gradient_bias.T return self.gradient class BPNN(): ''' Back Propagation Neural Network model ''' def __init__(self): self.layers = [] self.train_mse = [] self.fig_loss = plt.figure() self.ax_loss = self.fig_loss.add_subplot(1,1,1) def add_layer(self,layer): self.layers.append(layer) def build(self): for i,layer in enumerate(self.layers[:]): if i < 1: layer.is_input_layer = True else: layer.initializer(self.layers[i-1].units) def summary(self): for i,layer in enumerate(self.layers[:]): print('------- layer %d -------'%i) print('weight.shape ',np.shape(layer.weight)) print('bias.shape ',np.shape(layer.bias)) def train(self,xdata,ydata,train_round,accuracy): self.train_round = train_round self.accuracy = accuracy self.ax_loss.hlines(self.accuracy, 0, self.train_round * 1.1) x_shape = np.shape(xdata) for round_i in range(train_round): all_loss = 0 for row in range(x_shape[0]): _xdata = np.asmatrix(xdata[row,:]).T _ydata = np.asmatrix(ydata[row,:]).T # forward propagation for layer in self.layers: _xdata = layer.forward_propagation(_xdata) loss, gradient = self.cal_loss(_ydata, _xdata) all_loss = all_loss + loss # back propagation # the input_layer does not upgrade for layer in self.layers[:0:-1]: gradient = layer.back_propagation(gradient) mse = all_loss/x_shape[0] self.train_mse.append(mse) self.plot_loss() if mse < self.accuracy: print('----达到精度----') return mse def cal_loss(self,ydata,ydata_): self.loss = np.sum(np.power((ydata - ydata_),2)) self.loss_gradient = 2 * (ydata_ - ydata) # vector (shape is the same as _ydata.shape) return self.loss,self.loss_gradient def plot_loss(self): if self.ax_loss.lines: self.ax_loss.lines.remove(self.ax_loss.lines[0]) self.ax_loss.plot(self.train_mse, 'r-') plt.ion() plt.xlabel('step') plt.ylabel('loss') plt.show() plt.pause(0.1) def example(): x = np.random.randn(10,10) y = np.asarray([[0.8,0.4],[0.4,0.3],[0.34,0.45],[0.67,0.32], [0.88,0.67],[0.78,0.77],[0.55,0.66],[0.55,0.43],[0.54,0.1], [0.1,0.5]]) model = BPNN() model.add_layer(DenseLayer(10)) model.add_layer(DenseLayer(20)) model.add_layer(DenseLayer(30)) model.add_layer(DenseLayer(2)) model.build() model.summary() model.train(xdata=x,ydata=y,train_round=100,accuracy=0.01) if __name__ == '__main__': example()
[]
[]
[]
archives/1098994933_python.zip
neural_network/convolution_neural_network.py
#-*- coding: utf-8 -*- ''' - - - - - -- - - - - - - - - - - - - - - - - - - - - - - Name - - CNN - Convolution Neural Network For Photo Recognizing Goal - - Recognize Handing Writting Word Photo Detail:Total 5 layers neural network * Convolution layer * Pooling layer * Input layer layer of BP * Hiden layer of BP * Output layer of BP Author: Stephen Lee Github: 245885195@qq.com Date: 2017.9.20 - - - - - -- - - - - - - - - - - - - - - - - - - - - - - ''' import pickle import numpy as np import matplotlib.pyplot as plt class CNN(): def __init__(self, conv1_get, size_p1, bp_num1, bp_num2, bp_num3, rate_w=0.2, rate_t=0.2): ''' :param conv1_get: [a,c,d],size, number, step of convolution kernel :param size_p1: pooling size :param bp_num1: units number of flatten layer :param bp_num2: units number of hidden layer :param bp_num3: units number of output layer :param rate_w: rate of weight learning :param rate_t: rate of threshold learning ''' self.num_bp1 = bp_num1 self.num_bp2 = bp_num2 self.num_bp3 = bp_num3 self.conv1 = conv1_get[:2] self.step_conv1 = conv1_get[2] self.size_pooling1 = size_p1 self.rate_weight = rate_w self.rate_thre = rate_t self.w_conv1 = [np.mat(-1*np.random.rand(self.conv1[0],self.conv1[0])+0.5) for i in range(self.conv1[1])] self.wkj = np.mat(-1 * np.random.rand(self.num_bp3, self.num_bp2) + 0.5) self.vji = np.mat(-1*np.random.rand(self.num_bp2, self.num_bp1)+0.5) self.thre_conv1 = -2*np.random.rand(self.conv1[1])+1 self.thre_bp2 = -2*np.random.rand(self.num_bp2)+1 self.thre_bp3 = -2*np.random.rand(self.num_bp3)+1 def save_model(self, save_path): #save model dict with pickle model_dic = {'num_bp1':self.num_bp1, 'num_bp2':self.num_bp2, 'num_bp3':self.num_bp3, 'conv1':self.conv1, 'step_conv1':self.step_conv1, 'size_pooling1':self.size_pooling1, 'rate_weight':self.rate_weight, 'rate_thre':self.rate_thre, 'w_conv1':self.w_conv1, 'wkj':self.wkj, 'vji':self.vji, 'thre_conv1':self.thre_conv1, 'thre_bp2':self.thre_bp2, 'thre_bp3':self.thre_bp3} with open(save_path, 'wb') as f: pickle.dump(model_dic, f) print('Model saved: %s'% save_path) @classmethod def ReadModel(cls, model_path): #read saved model with open(model_path, 'rb') as f: model_dic = pickle.load(f) conv_get= model_dic.get('conv1') conv_get.append(model_dic.get('step_conv1')) size_p1 = model_dic.get('size_pooling1') bp1 = model_dic.get('num_bp1') bp2 = model_dic.get('num_bp2') bp3 = model_dic.get('num_bp3') r_w = model_dic.get('rate_weight') r_t = model_dic.get('rate_thre') #create model instance conv_ins = CNN(conv_get,size_p1,bp1,bp2,bp3,r_w,r_t) #modify model parameter conv_ins.w_conv1 = model_dic.get('w_conv1') conv_ins.wkj = model_dic.get('wkj') conv_ins.vji = model_dic.get('vji') conv_ins.thre_conv1 = model_dic.get('thre_conv1') conv_ins.thre_bp2 = model_dic.get('thre_bp2') conv_ins.thre_bp3 = model_dic.get('thre_bp3') return conv_ins def sig(self, x): return 1 / (1 + np.exp(-1*x)) def do_round(self, x): return round(x, 3) def convolute(self, data, convs, w_convs, thre_convs, conv_step): #convolution process size_conv = convs[0] num_conv =convs[1] size_data = np.shape(data)[0] #get the data slice of original image data, data_focus data_focus = [] for i_focus in range(0, size_data - size_conv + 1, conv_step): for j_focus in range(0, size_data - size_conv + 1, conv_step): focus = data[i_focus:i_focus + size_conv, j_focus:j_focus + size_conv] data_focus.append(focus) #caculate the feature map of every single kernel, and saved as list of matrix data_featuremap = [] Size_FeatureMap = int((size_data - size_conv) / conv_step + 1) for i_map in range(num_conv): featuremap = [] for i_focus in range(len(data_focus)): net_focus = np.sum(np.multiply(data_focus[i_focus], w_convs[i_map])) - thre_convs[i_map] featuremap.append(self.sig(net_focus)) featuremap = np.asmatrix(featuremap).reshape(Size_FeatureMap, Size_FeatureMap) data_featuremap.append(featuremap) #expanding the data slice to One dimenssion focus1_list = [] for each_focus in data_focus: focus1_list.extend(self.Expand_Mat(each_focus)) focus_list = np.asarray(focus1_list) return focus_list,data_featuremap def pooling(self, featuremaps, size_pooling, type='average_pool'): #pooling process size_map = len(featuremaps[0]) size_pooled = int(size_map/size_pooling) featuremap_pooled = [] for i_map in range(len(featuremaps)): map = featuremaps[i_map] map_pooled = [] for i_focus in range(0,size_map,size_pooling): for j_focus in range(0, size_map, size_pooling): focus = map[i_focus:i_focus + size_pooling, j_focus:j_focus + size_pooling] if type == 'average_pool': #average pooling map_pooled.append(np.average(focus)) elif type == 'max_pooling': #max pooling map_pooled.append(np.max(focus)) map_pooled = np.asmatrix(map_pooled).reshape(size_pooled,size_pooled) featuremap_pooled.append(map_pooled) return featuremap_pooled def _expand(self, datas): #expanding three dimension data to one dimension list data_expanded = [] for i in range(len(datas)): shapes = np.shape(datas[i]) data_listed = datas[i].reshape(1,shapes[0]*shapes[1]) data_listed = data_listed.getA().tolist()[0] data_expanded.extend(data_listed) data_expanded = np.asarray(data_expanded) return data_expanded def _expand_mat(self, data_mat): #expanding matrix to one dimension list data_mat = np.asarray(data_mat) shapes = np.shape(data_mat) data_expanded = data_mat.reshape(1,shapes[0]*shapes[1]) return data_expanded def _calculate_gradient_from_pool(self, out_map, pd_pool,num_map, size_map, size_pooling): ''' calcluate the gradient from the data slice of pool layer pd_pool: list of matrix out_map: the shape of data slice(size_map*size_map) return: pd_all: list of matrix, [num, size_map, size_map] ''' pd_all = [] i_pool = 0 for i_map in range(num_map): pd_conv1 = np.ones((size_map, size_map)) for i in range(0, size_map, size_pooling): for j in range(0, size_map, size_pooling): pd_conv1[i:i + size_pooling, j:j + size_pooling] = pd_pool[i_pool] i_pool = i_pool + 1 pd_conv2 = np.multiply(pd_conv1,np.multiply(out_map[i_map],(1-out_map[i_map]))) pd_all.append(pd_conv2) return pd_all def train(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))) rp = 0 all_mse = [] mse = 10000 while rp < n_repeat and mse >= error_accuracy: alle = 0 print('-------------Learning Time %d--------------'%rp) for p in range(len(datas_train)): #print('------------Learning Image: %d--------------'%p) data_train = np.asmatrix(datas_train[p]) data_teach = np.asarray(datas_teach[p]) data_focus1,data_conved1 = self.convolute(data_train,self.conv1,self.w_conv1, self.thre_conv1,conv_step=self.step_conv1) data_pooled1 = self.pooling(data_conved1,self.size_pooling1) shape_featuremap1 = np.shape(data_conved1) ''' print(' -----original shape ', np.shape(data_train)) print(' ---- after convolution ',np.shape(data_conv1)) print(' -----after pooling ',np.shape(data_pooled1)) ''' data_bp_input = self._expand(data_pooled1) bp_out1 = data_bp_input bp_net_j = np.dot(bp_out1,self.vji.T) - self.thre_bp2 bp_out2 = self.sig(bp_net_j) bp_net_k = np.dot(bp_out2 ,self.wkj.T) - self.thre_bp3 bp_out3 = self.sig(bp_net_k) #--------------Model Leaning ------------------------ # calcluate error and gradient--------------- pd_k_all = np.multiply((data_teach - bp_out3), np.multiply(bp_out3, (1 - bp_out3))) pd_j_all = np.multiply(np.dot(pd_k_all,self.wkj), np.multiply(bp_out2, (1 - bp_out2))) pd_i_all = np.dot(pd_j_all,self.vji) pd_conv1_pooled = pd_i_all / (self.size_pooling1*self.size_pooling1) pd_conv1_pooled = pd_conv1_pooled.T.getA().tolist() pd_conv1_all = self._calculate_gradient_from_pool(data_conved1,pd_conv1_pooled,shape_featuremap1[0], shape_featuremap1[1],self.size_pooling1) #weight and threshold learning process--------- #convolution layer for k_conv in range(self.conv1[1]): pd_conv_list = self._expand_mat(pd_conv1_all[k_conv]) delta_w = self.rate_weight * np.dot(pd_conv_list,data_focus1) self.w_conv1[k_conv] = self.w_conv1[k_conv] + delta_w.reshape((self.conv1[0],self.conv1[0])) self.thre_conv1[k_conv] = self.thre_conv1[k_conv] - np.sum(pd_conv1_all[k_conv]) * self.rate_thre #all connected layer self.wkj = self.wkj + pd_k_all.T * bp_out2 * self.rate_weight self.vji = self.vji + pd_j_all.T * bp_out1 * self.rate_weight self.thre_bp3 = self.thre_bp3 - pd_k_all * self.rate_thre self.thre_bp2 = self.thre_bp2 - pd_j_all * self.rate_thre # calculate the sum error of all single image errors = np.sum(abs((data_teach - bp_out3))) alle = alle + errors #print(' ----Teach ',data_teach) #print(' ----BP_output ',bp_out3) rp = rp + 1 mse = alle/patterns all_mse.append(mse) def draw_error(): yplot = [error_accuracy for i in range(int(n_repeat * 1.2))] plt.plot(all_mse, '+-') plt.plot(yplot, 'r--') plt.xlabel('Learning Times') plt.ylabel('All_mse') plt.grid(True, alpha=0.5) plt.show() print('------------------Training Complished---------------------') print((' - - Training epoch: ', rp, ' - - Mse: %.6f' % mse)) if draw_e: draw_error() return mse def predict(self, datas_test): #model predict produce_out = [] print('-------------------Start Testing-------------------------') 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, self.thre_conv1, conv_step=self.step_conv1) data_pooled1 = self.pooling(data_conved1, self.size_pooling1) data_bp_input = self._expand(data_pooled1) bp_out1 = data_bp_input bp_net_j = bp_out1 * self.vji.T - self.thre_bp2 bp_out2 = self.sig(bp_net_j) bp_net_k = bp_out2 * self.wkj.T - self.thre_bp3 bp_out3 = self.sig(bp_net_k) produce_out.extend(bp_out3.getA().tolist()) res = [list(map(self.do_round,each)) for each in produce_out] return np.asarray(res) def convolution(self, data): #return the data of image after convoluting process so we can check it out data_test = np.asmatrix(data) data_focus1, data_conved1 = self.convolute(data_test, self.conv1, self.w_conv1, self.thre_conv1, conv_step=self.step_conv1) data_pooled1 = self.pooling(data_conved1, self.size_pooling1) return data_conved1,data_pooled1 if __name__ == '__main__': pass ''' I will put the example on other file '''
[]
[]
[]
archives/1098994933_python.zip
neural_network/perceptron.py
''' Perceptron w = w + N * (d(k) - y) * x(k) Using perceptron network for oil analysis, with Measuring of 3 parameters that represent chemical characteristics we can classify the oil, in p1 or p2 p1 = -1 p2 = 1 ''' import random class Perceptron: def __init__(self, sample, exit, learn_rate=0.01, epoch_number=1000, bias=-1): self.sample = sample self.exit = exit self.learn_rate = learn_rate self.epoch_number = epoch_number self.bias = bias self.number_sample = len(sample) self.col_sample = len(sample[0]) self.weight = [] def training(self): for sample in self.sample: sample.insert(0, self.bias) for i in range(self.col_sample): self.weight.append(random.random()) self.weight.insert(0, self.bias) epoch_count = 0 while True: erro = False for i in range(self.number_sample): u = 0 for j in range(self.col_sample + 1): u = u + self.weight[j] * self.sample[i][j] y = self.sign(u) if y != self.exit[i]: for j in range(self.col_sample + 1): self.weight[j] = self.weight[j] + self.learn_rate * (self.exit[i] - y) * self.sample[i][j] erro = True #print('Epoch: \n',epoch_count) epoch_count = epoch_count + 1 # if you want controle the epoch or just by erro if erro == False: print(('\nEpoch:\n',epoch_count)) print('------------------------\n') #if epoch_count > self.epoch_number or not erro: break def sort(self, sample): sample.insert(0, self.bias) u = 0 for i in range(self.col_sample + 1): u = u + self.weight[i] * sample[i] y = self.sign(u) if y == -1: print(('Sample: ', sample)) print('classification: P1') else: print(('Sample: ', sample)) print('classification: P2') def sign(self, u): return 1 if u >= 0 else -1 samples = [ [-0.6508, 0.1097, 4.0009], [-1.4492, 0.8896, 4.4005], [2.0850, 0.6876, 12.0710], [0.2626, 1.1476, 7.7985], [0.6418, 1.0234, 7.0427], [0.2569, 0.6730, 8.3265], [1.1155, 0.6043, 7.4446], [0.0914, 0.3399, 7.0677], [0.0121, 0.5256, 4.6316], [-0.0429, 0.4660, 5.4323], [0.4340, 0.6870, 8.2287], [0.2735, 1.0287, 7.1934], [0.4839, 0.4851, 7.4850], [0.4089, -0.1267, 5.5019], [1.4391, 0.1614, 8.5843], [-0.9115, -0.1973, 2.1962], [0.3654, 1.0475, 7.4858], [0.2144, 0.7515, 7.1699], [0.2013, 1.0014, 6.5489], [0.6483, 0.2183, 5.8991], [-0.1147, 0.2242, 7.2435], [-0.7970, 0.8795, 3.8762], [-1.0625, 0.6366, 2.4707], [0.5307, 0.1285, 5.6883], [-1.2200, 0.7777, 1.7252], [0.3957, 0.1076, 5.6623], [-0.1013, 0.5989, 7.1812], [2.4482, 0.9455, 11.2095], [2.0149, 0.6192, 10.9263], [0.2012, 0.2611, 5.4631] ] exit = [-1, -1, -1, 1, 1, -1, 1, -1, 1, 1, -1, 1, -1, -1, -1, -1, 1, 1, 1, 1, -1, 1, 1, 1, 1, -1, -1, 1, -1, 1] network = Perceptron(sample=samples, exit = exit, learn_rate=0.01, epoch_number=1000, bias=-1) network.training() if __name__ == '__main__': while True: sample = [] for i in range(3): sample.insert(i, float(input('value: '))) network.sort(sample)
[]
[]
[]
archives/1098994933_python.zip
other/anagrams.py
import collections, pprint, time, os start_time = time.time() print('creating word list...') path = os.path.split(os.path.realpath(__file__)) with open(path[0] + '/words') as f: word_list = sorted(list(set([word.strip().lower() for word in f]))) def signature(word): return ''.join(sorted(word)) word_bysig = collections.defaultdict(list) for word in word_list: word_bysig[signature(word)].append(word) def anagram(myword): return word_bysig[signature(myword)] print('finding anagrams...') all_anagrams = {word: anagram(word) for word in word_list if len(anagram(word)) > 1} print('writing anagrams to file...') with open('anagrams.txt', 'w') as file: file.write('all_anagrams = ') file.write(pprint.pformat(all_anagrams)) total_time = round(time.time() - start_time, 2) print(('Done [', total_time, 'seconds ]'))
[]
[]
[]
archives/1098994933_python.zip
other/binary_exponentiation.py
""" * Binary Exponentiation for Powers * This is a method to find a^b in a time complexity of O(log b) * This is one of the most commonly used methods of finding powers. * Also useful in cases where solution to (a^b)%c is required, * where a,b,c can be numbers over the computers calculation limits. * Done using iteration, can also be done using recursion * @author chinmoy159 * @version 1.0 dated 10/08/2017 """ def b_expo(a, b): res = 1 while b > 0: if b&1: res *= a a *= a b >>= 1 return res def b_expo_mod(a, b, c): res = 1 while b > 0: if b&1: res = ((res%c) * (a%c)) % c a *= a b >>= 1 return res """ * Wondering how this method works ! * It's pretty simple. * Let's say you need to calculate a ^ b * RULE 1 : a ^ b = (a*a) ^ (b/2) ---- example : 4 ^ 4 = (4*4) ^ (4/2) = 16 ^ 2 * RULE 2 : IF b is ODD, then ---- a ^ b = a * (a ^ (b - 1)) :: where (b - 1) is even. * Once b is even, repeat the process to get a ^ b * Repeat the process till b = 1 OR b = 0, because a^1 = a AND a^0 = 1 * * As far as the modulo is concerned, * the fact : (a*b) % c = ((a%c) * (b%c)) % c * Now apply RULE 1 OR 2 whichever is required. """
[]
[]
[]
archives/1098994933_python.zip
other/binary_exponentiation_2.py
""" * Binary Exponentiation with Multiplication * This is a method to find a*b in a time complexity of O(log b) * This is one of the most commonly used methods of finding result of multiplication. * Also useful in cases where solution to (a*b)%c is required, * where a,b,c can be numbers over the computers calculation limits. * Done using iteration, can also be done using recursion * @author chinmoy159 * @version 1.0 dated 10/08/2017 """ def b_expo(a, b): res = 0 while b > 0: if b&1: res += a a += a b >>= 1 return res def b_expo_mod(a, b, c): res = 0 while b > 0: if b&1: res = ((res%c) + (a%c)) % c a += a b >>= 1 return res """ * Wondering how this method works ! * It's pretty simple. * Let's say you need to calculate a ^ b * RULE 1 : a * b = (a+a) * (b/2) ---- example : 4 * 4 = (4+4) * (4/2) = 8 * 2 * RULE 2 : IF b is ODD, then ---- a * b = a + (a * (b - 1)) :: where (b - 1) is even. * Once b is even, repeat the process to get a * b * Repeat the process till b = 1 OR b = 0, because a*1 = a AND a*0 = 0 * * As far as the modulo is concerned, * the fact : (a+b) % c = ((a%c) + (b%c)) % c * Now apply RULE 1 OR 2, whichever is required. """
[]
[]
[]
archives/1098994933_python.zip
other/detecting_english_programmatically.py
import os UPPERLETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' LETTERS_AND_SPACE = UPPERLETTERS + UPPERLETTERS.lower() + ' \t\n' def loadDictionary(): path = os.path.split(os.path.realpath(__file__)) englishWords = {} with open(path[0] + '/dictionary.txt') as dictionaryFile: for word in dictionaryFile.read().split('\n'): englishWords[word] = None return englishWords ENGLISH_WORDS = loadDictionary() def getEnglishCount(message): message = message.upper() message = removeNonLetters(message) possibleWords = message.split() if possibleWords == []: return 0.0 matches = 0 for word in possibleWords: if word in ENGLISH_WORDS: matches += 1 return float(matches) / len(possibleWords) def removeNonLetters(message): lettersOnly = [] for symbol in message: if symbol in LETTERS_AND_SPACE: lettersOnly.append(symbol) return ''.join(lettersOnly) def isEnglish(message, wordPercentage = 20, letterPercentage = 85): """ >>> isEnglish('Hello World') True >>> isEnglish('llold HorWd') False """ wordsMatch = getEnglishCount(message) * 100 >= wordPercentage numLetters = len(removeNonLetters(message)) messageLettersPercentage = (float(numLetters) / len(message)) * 100 lettersMatch = messageLettersPercentage >= letterPercentage return wordsMatch and lettersMatch import doctest doctest.testmod()
[]
[]
[]
archives/1098994933_python.zip
other/euclidean_gcd.py
# https://en.wikipedia.org/wiki/Euclidean_algorithm def euclidean_gcd(a, b): while b: t = b b = a % b a = t return a def main(): print("GCD(3, 5) = " + str(euclidean_gcd(3, 5))) print("GCD(5, 3) = " + str(euclidean_gcd(5, 3))) print("GCD(1, 3) = " + str(euclidean_gcd(1, 3))) print("GCD(3, 6) = " + str(euclidean_gcd(3, 6))) print("GCD(6, 3) = " + str(euclidean_gcd(6, 3))) if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
other/fischer_yates_shuffle.py
#!/usr/bin/python # encoding=utf8 """ The Fisher–Yates shuffle is an algorithm for generating a random permutation of a finite sequence. For more details visit wikipedia/Fischer-Yates-Shuffle. """ import random def FYshuffle(LIST): for i in range(len(LIST)): a = random.randint(0, len(LIST)-1) b = random.randint(0, len(LIST)-1) LIST[a], LIST[b] = LIST[b], LIST[a] return LIST if __name__ == '__main__': integers = [0,1,2,3,4,5,6,7] strings = ['python', 'says', 'hello', '!'] print('Fisher-Yates Shuffle:') print('List',integers, strings) print('FY Shuffle',FYshuffle(integers), FYshuffle(strings))
[]
[]
[]
archives/1098994933_python.zip
other/frequency_finder.py
# Frequency Finder # frequency taken from http://en.wikipedia.org/wiki/Letter_frequency englishLetterFreq = {'E': 12.70, 'T': 9.06, 'A': 8.17, 'O': 7.51, 'I': 6.97, 'N': 6.75, 'S': 6.33, 'H': 6.09, 'R': 5.99, 'D': 4.25, 'L': 4.03, 'C': 2.78, 'U': 2.76, 'M': 2.41, 'W': 2.36, 'F': 2.23, 'G': 2.02, 'Y': 1.97, 'P': 1.93, 'B': 1.29, 'V': 0.98, 'K': 0.77, 'J': 0.15, 'X': 0.15, 'Q': 0.10, 'Z': 0.07} ETAOIN = 'ETAOINSHRDLCUMWFGYPBVKJXQZ' LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def getLetterCount(message): letterCount = {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'J': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'O': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'U': 0, 'V': 0, 'W': 0, 'X': 0, 'Y': 0, 'Z': 0} for letter in message.upper(): if letter in LETTERS: letterCount[letter] += 1 return letterCount def getItemAtIndexZero(x): return x[0] def getFrequencyOrder(message): letterToFreq = getLetterCount(message) freqToLetter = {} for letter in LETTERS: if letterToFreq[letter] not in freqToLetter: freqToLetter[letterToFreq[letter]] = [letter] else: freqToLetter[letterToFreq[letter]].append(letter) for freq in freqToLetter: freqToLetter[freq].sort(key = ETAOIN.find, reverse = True) freqToLetter[freq] = ''.join(freqToLetter[freq]) freqPairs = list(freqToLetter.items()) freqPairs.sort(key = getItemAtIndexZero, reverse = True) freqOrder = [] for freqPair in freqPairs: freqOrder.append(freqPair[1]) return ''.join(freqOrder) def englishFreqMatchScore(message): ''' >>> englishFreqMatchScore('Hello World') 1 ''' freqOrder = getFrequencyOrder(message) matchScore = 0 for commonLetter in ETAOIN[:6]: if commonLetter in freqOrder[:6]: matchScore += 1 for uncommonLetter in ETAOIN[-6:]: if uncommonLetter in freqOrder[-6:]: matchScore += 1 return matchScore if __name__ == '__main__': import doctest doctest.testmod()
[]
[]
[]
archives/1098994933_python.zip
other/game_of_life.py
'''Conway's Game Of Life, Author Anurag Kumar(mailto:anuragkumarak95@gmail.com) Requirements: - numpy - random - time - matplotlib Python: - 3.5 Usage: - $python3 game_o_life <canvas_size:int> Game-Of-Life Rules: 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population. 2. Any live cell with two or three live neighbours lives on to the next generation. 3. Any live cell with more than three live neighbours dies, as if by over-population. 4. Any dead cell with exactly three live neighbours be- comes a live cell, as if by reproduction. ''' import numpy as np import random, sys from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap usage_doc='Usage of script: script_nama <size_of_canvas:int>' choice = [0]*100 + [1]*10 random.shuffle(choice) def create_canvas(size): canvas = [ [False for i in range(size)] for j in range(size)] return canvas def seed(canvas): for i,row in enumerate(canvas): for j,_ in enumerate(row): canvas[i][j]=bool(random.getrandbits(1)) def run(canvas): ''' This function runs the rules of game through all points, and changes their status accordingly.(in the same canvas) @Args: -- canvas : canvas of population to run the rules on. @returns: -- None ''' canvas = np.array(canvas) next_gen_canvas = np.array(create_canvas(canvas.shape[0])) for r, row in enumerate(canvas): for c, pt in enumerate(row): # print(r-1,r+2,c-1,c+2) next_gen_canvas[r][c] = __judge_point(pt,canvas[r-1:r+2,c-1:c+2]) canvas = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. return canvas.tolist() def __judge_point(pt,neighbours): dead = 0 alive = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive+=1 else: dead+=1 # handling duplicate entry for focus pt. if pt : alive-=1 else : dead-=1 # running the rules of game here. state = pt if pt: if alive<2: state=False elif alive==2 or alive==3: state=True elif alive>3: state=False else: if alive==3: state=True return state if __name__=='__main__': if len(sys.argv) != 2: raise Exception(usage_doc) canvas_size = int(sys.argv[1]) # main working structure of this module. c=create_canvas(canvas_size) seed(c) fig, ax = plt.subplots() fig.show() cmap = ListedColormap(['w','k']) try: while True: c = run(c) ax.matshow(c,cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
[]
[]
[]
archives/1098994933_python.zip
other/linear_congruential_generator.py
__author__ = "Tobias Carryer" from time import time class LinearCongruentialGenerator(object): """ A pseudorandom number generator. """ def __init__( self, multiplier, increment, modulo, seed=int(time()) ): """ These parameters are saved and used when nextNumber() is called. modulo is the largest number that can be generated (exclusive). The most efficent values are powers of 2. 2^32 is a common value. """ self.multiplier = multiplier self.increment = increment self.modulo = modulo self.seed = seed def next_number( self ): """ The smallest number that can be generated is zero. The largest number that can be generated is modulo-1. modulo is set in the constructor. """ self.seed = (self.multiplier * self.seed + self.increment) % self.modulo return self.seed if __name__ == "__main__": # Show the LCG in action. lcg = LinearCongruentialGenerator(1664525, 1013904223, 2<<31) while True : print(lcg.next_number())
[]
[]
[]
archives/1098994933_python.zip
other/nested_brackets.py
''' The nested brackets problem is a problem that determines if a sequence of brackets are properly nested. A sequence of brackets s is considered properly nested if any of the following conditions are true: - s is empty - s has the form (U) or [U] or {U} where U is a properly nested string - s has the form VW where V and W are properly nested strings For example, the string "()()[()]" is properly nested but "[(()]" is not. The function called is_balanced takes as input a string S which is a sequence of brackets and returns true if S is nested and false otherwise. ''' def is_balanced(S): stack = [] open_brackets = set({'(', '[', '{'}) closed_brackets = set({')', ']', '}'}) open_to_closed = dict({'{':'}', '[':']', '(':')'}) for i in range(len(S)): if S[i] in open_brackets: stack.append(S[i]) elif S[i] in closed_brackets: if len(stack) == 0 or (len(stack) > 0 and open_to_closed[stack.pop()] != S[i]): return False return len(stack) == 0 def main(): S = input("Enter sequence of brackets: ") if is_balanced(S): print((S, "is balanced")) else: print((S, "is not balanced")) if __name__ == "__main__": main()
[]
[]
[]
archives/1098994933_python.zip
other/palindrome.py
# Program to find whether given string is palindrome or not def is_palindrome(str): start_i = 0 end_i = len(str) - 1 while start_i < end_i: if str[start_i] == str[end_i]: start_i += 1 end_i -= 1 else: return False return True # Recursive method def recursive_palindrome(str): if len(str) <= 1: return True if str[0] == str[len(str) - 1]: return recursive_palindrome(str[1:-1]) else: return False def main(): str = 'ama' print(recursive_palindrome(str.lower())) print(is_palindrome(str.lower())) if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
other/password_generator.py
"""Password generator allows you to generate a random password of length N.""" from random import choice from string import ascii_letters, digits, punctuation def password_generator(length=8): """ >>> len(password_generator()) 8 >>> len(password_generator(length=16)) 16 >>> len(password_generator(257)) 257 >>> len(password_generator(length=0)) 0 >>> len(password_generator(-1)) 0 """ chars = tuple(ascii_letters) + tuple(digits) + tuple(punctuation) return ''.join(choice(chars) for x in range(length)) # ALTERNATIVE METHODS # ctbi= characters that must be in password # i= how many letters or characters the password length will be def alternative_password_generator(ctbi, i): # Password generator = full boot with random_number, random_letters, and # random_character FUNCTIONS pass # Put your code here... def random_number(ctbi, i): pass # Put your code here... def random_letters(ctbi, i): pass # Put your code here... def random_characters(ctbi, i): pass # Put your code here... def main(): length = int( input('Please indicate the max length of your password: ').strip()) print('Password generated:', password_generator(length)) print('[If you are thinking of using this passsword, You better save it.]') if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
other/primelib.py
# -*- coding: utf-8 -*- """ Created on Thu Oct 5 16:44:23 2017 @author: Christian Bender This python library contains some useful functions to deal with prime numbers and whole numbers. Overview: isPrime(number) sieveEr(N) getPrimeNumbers(N) primeFactorization(number) greatestPrimeFactor(number) smallestPrimeFactor(number) getPrime(n) getPrimesBetween(pNumber1, pNumber2) ---- isEven(number) isOdd(number) gcd(number1, number2) // greatest common divisor kgV(number1, number2) // least common multiple getDivisors(number) // all divisors of 'number' inclusive 1, number isPerfectNumber(number) NEW-FUNCTIONS simplifyFraction(numerator, denominator) factorial (n) // n! fib (n) // calculate the n-th fibonacci term. ----- goldbach(number) // Goldbach's assumption """ from math import sqrt def isPrime(number): """ input: positive integer 'number' returns true if 'number' is prime otherwise false. """ # precondition assert isinstance(number,int) and (number >= 0) , \ "'number' must been an int and positive" status = True # 0 and 1 are none primes. if number <= 1: status = False for divisor in range(2,int(round(sqrt(number)))+1): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: status = False break # precondition assert isinstance(status,bool), "'status' must been from type bool" return status # ------------------------------------------ def sieveEr(N): """ input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N. This function implements the algorithm called sieve of erathostenes. """ # precondition assert isinstance(N,int) and (N > 2), "'N' must been an int and > 2" # beginList: conatins all natural numbers from 2 upt to N beginList = [x for x in range(2,N+1)] ans = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(beginList)): for j in range(i+1,len(beginList)): if (beginList[i] != 0) and \ (beginList[j] % beginList[i] == 0): beginList[j] = 0 # filters actual prime numbers. ans = [x for x in beginList if x != 0] # precondition assert isinstance(ans,list), "'ans' must been from type list" return ans # -------------------------------- def getPrimeNumbers(N): """ input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N (inclusive) This function is more efficient as function 'sieveEr(...)' """ # precondition assert isinstance(N,int) and (N > 2), "'N' must been an int and > 2" ans = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2,N+1): if isPrime(number): ans.append(number) # precondition assert isinstance(ans,list), "'ans' must been from type list" return ans # ----------------------------------------- def primeFactorization(number): """ input: positive integer 'number' returns a list of the prime number factors of 'number' """ # precondition assert isinstance(number,int) and number >= 0, \ "'number' must been an int and >= 0" ans = [] # this list will be returns of the function. # potential prime number factors. factor = 2 quotient = number if number == 0 or number == 1: ans.append(number) # if 'number' not prime then builds the prime factorization of 'number' elif not isPrime(number): while (quotient != 1): if isPrime(factor) and (quotient % factor == 0): ans.append(factor) quotient /= factor else: factor += 1 else: ans.append(number) # precondition assert isinstance(ans,list), "'ans' must been from type list" return ans # ----------------------------------------- def greatestPrimeFactor(number): """ input: positive integer 'number' >= 0 returns the greatest prime number factor of 'number' """ # precondition assert isinstance(number,int) and (number >= 0), \ "'number' bust been an int and >= 0" ans = 0 # prime factorization of 'number' primeFactors = primeFactorization(number) ans = max(primeFactors) # precondition assert isinstance(ans,int), "'ans' must been from type int" return ans # ---------------------------------------------- def smallestPrimeFactor(number): """ input: integer 'number' >= 0 returns the smallest prime number factor of 'number' """ # precondition assert isinstance(number,int) and (number >= 0), \ "'number' bust been an int and >= 0" ans = 0 # prime factorization of 'number' primeFactors = primeFactorization(number) ans = min(primeFactors) # precondition assert isinstance(ans,int), "'ans' must been from type int" return ans # ---------------------- def isEven(number): """ input: integer 'number' returns true if 'number' is even, otherwise false. """ # precondition assert isinstance(number, int), "'number' must been an int" assert isinstance(number % 2 == 0, bool), "compare bust been from type bool" return number % 2 == 0 # ------------------------ def isOdd(number): """ input: integer 'number' returns true if 'number' is odd, otherwise false. """ # precondition assert isinstance(number, int), "'number' must been an int" assert isinstance(number % 2 != 0, bool), "compare bust been from type bool" return number % 2 != 0 # ------------------------ def goldbach(number): """ Goldbach's assumption input: a even positive integer 'number' > 2 returns a list of two prime numbers whose sum is equal to 'number' """ # precondition assert isinstance(number,int) and (number > 2) and isEven(number), \ "'number' must been an int, even and > 2" ans = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' primeNumbers = getPrimeNumbers(number) lenPN = len(primeNumbers) # run variable for while-loops. i = 0 j = None # exit variable. for break up the loops loop = True while (i < lenPN and loop): j = i+1 while (j < lenPN and loop): if primeNumbers[i] + primeNumbers[j] == number: loop = False ans.append(primeNumbers[i]) ans.append(primeNumbers[j]) j += 1 i += 1 # precondition assert isinstance(ans,list) and (len(ans) == 2) and \ (ans[0] + ans[1] == number) and isPrime(ans[0]) and isPrime(ans[1]), \ "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans # ---------------------------------------------- def gcd(number1,number2): """ Greatest common divisor input: two positive integer 'number1' and 'number2' returns the greatest common divisor of 'number1' and 'number2' """ # precondition assert isinstance(number1,int) and isinstance(number2,int) \ and (number1 >= 0) and (number2 >= 0), \ "'number1' and 'number2' must been positive integer." rest = 0 while number2 != 0: rest = number1 % number2 number1 = number2 number2 = rest # precondition assert isinstance(number1,int) and (number1 >= 0), \ "'number' must been from type int and positive" return number1 # ---------------------------------------------------- def kgV(number1, number2): """ Least common multiple input: two positive integer 'number1' and 'number2' returns the least common multiple of 'number1' and 'number2' """ # precondition assert isinstance(number1,int) and isinstance(number2,int) \ and (number1 >= 1) and (number2 >= 1), \ "'number1' and 'number2' must been positive integer." ans = 1 # actual answer that will be return. # for kgV (x,1) if number1 > 1 and number2 > 1: # builds the prime factorization of 'number1' and 'number2' primeFac1 = primeFactorization(number1) primeFac2 = primeFactorization(number2) elif number1 == 1 or number2 == 1: primeFac1 = [] primeFac2 = [] ans = max(number1,number2) count1 = 0 count2 = 0 done = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in primeFac1: if n not in done: if n in primeFac2: count1 = primeFac1.count(n) count2 = primeFac2.count(n) for i in range(max(count1,count2)): ans *= n else: count1 = primeFac1.count(n) for i in range(count1): ans *= n done.append(n) # iterates through primeFac2 for n in primeFac2: if n not in done: count2 = primeFac2.count(n) for i in range(count2): ans *= n done.append(n) # precondition assert isinstance(ans,int) and (ans >= 0), \ "'ans' must been from type int and positive" return ans # ---------------------------------- def getPrime(n): """ Gets the n-th prime number. input: positive integer 'n' >= 0 returns the n-th prime number, beginning at index 0 """ # precondition assert isinstance(n,int) and (n >= 0), "'number' must been a positive int" index = 0 ans = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not isPrime(ans): ans += 1 # precondition assert isinstance(ans,int) and isPrime(ans), \ "'ans' must been a prime number and from type int" return ans # --------------------------------------------------- def getPrimesBetween(pNumber1, pNumber2): """ input: prime numbers 'pNumber1' and 'pNumber2' pNumber1 < pNumber2 returns a list of all prime numbers between 'pNumber1' (exclusiv) and 'pNumber2' (exclusiv) """ # precondition assert isPrime(pNumber1) and isPrime(pNumber2) and (pNumber1 < pNumber2), \ "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" number = pNumber1 + 1 # jump to the next number ans = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not isPrime(number): number += 1 while number < pNumber2: ans.append(number) number += 1 # fetch the next prime number. while not isPrime(number): number += 1 # precondition assert isinstance(ans,list) and ans[0] != pNumber1 \ and ans[len(ans)-1] != pNumber2, \ "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans # ---------------------------------------------------- def getDivisors(n): """ input: positive integer 'n' >= 1 returns all divisors of n (inclusive 1 and 'n') """ # precondition assert isinstance(n,int) and (n >= 1), "'n' must been int and >= 1" ans = [] # will be returned. for divisor in range(1,n+1): if n % divisor == 0: ans.append(divisor) #precondition assert ans[0] == 1 and ans[len(ans)-1] == n, \ "Error in function getDivisiors(...)" return ans # ---------------------------------------------------- def isPerfectNumber(number): """ input: positive integer 'number' > 1 returns true if 'number' is a perfect number otherwise false. """ # precondition assert isinstance(number,int) and (number > 1), \ "'number' must been an int and >= 1" divisors = getDivisors(number) # precondition assert isinstance(divisors,list) and(divisors[0] == 1) and \ (divisors[len(divisors)-1] == number), \ "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1]) == number # ------------------------------------------------------------ def simplifyFraction(numerator, denominator): """ input: two integer 'numerator' and 'denominator' assumes: 'denominator' != 0 returns: a tuple with simplify numerator and denominator. """ # precondition assert isinstance(numerator, int) and isinstance(denominator,int) \ and (denominator != 0), \ "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. gcdOfFraction = gcd(abs(numerator), abs(denominator)) # precondition assert isinstance(gcdOfFraction, int) and (numerator % gcdOfFraction == 0) \ and (denominator % gcdOfFraction == 0), \ "Error in function gcd(...,...)" return (numerator // gcdOfFraction, denominator // gcdOfFraction) # ----------------------------------------------------------------- def factorial(n): """ input: positive integer 'n' returns the factorial of 'n' (n!) """ # precondition assert isinstance(n,int) and (n >= 0), "'n' must been a int and >= 0" ans = 1 # this will be return. for factor in range(1,n+1): ans *= factor return ans # ------------------------------------------------------------------- def fib(n): """ input: positive integer 'n' returns the n-th fibonacci term , indexing by 0 """ # precondition assert isinstance(n, int) and (n >= 0), "'n' must been an int and >= 0" tmp = 0 fib1 = 1 ans = 1 # this will be return for i in range(n-1): tmp = ans ans += fib1 fib1 = tmp return ans
[]
[]
[]
archives/1098994933_python.zip
other/sierpinski_triangle.py
#!/usr/bin/python # encoding=utf8 '''Author Anurag Kumar | anuragkumarak95@gmail.com | git/anuragkumarak95 Simple example of Fractal generation using recursive function. What is Sierpinski Triangle? >>The Sierpinski triangle (also with the original orthography Sierpinski), also called the Sierpinski gasket or the Sierpinski Sieve, is a fractal and attractive fixed set with the overall shape of an equilateral triangle, subdivided recursively into smaller equilateral triangles. Originally constructed as a curve, this is one of the basic examples of self-similar sets, i.e., it is a mathematically generated pattern that can be reproducible at any magnification or reduction. It is named after the Polish mathematician Wacław Sierpinski, but appeared as a decorative pattern many centuries prior to the work of Sierpinski. Requirements(pip): - turtle Python: - 2.6 Usage: - $python sierpinski_triangle.py <int:depth_for_fractal> Credits: This code was written by editing the code from http://www.riannetrujillo.com/blog/python-fractal/ ''' import turtle import sys PROGNAME = 'Sierpinski Triangle' points = [[-175,-125],[0,175],[175,-125]] #size of triangle def getMid(p1,p2): return ( (p1[0]+p2[0]) / 2, (p1[1] + p2[1]) / 2) #find midpoint def triangle(points,depth): myPen.up() myPen.goto(points[0][0],points[0][1]) myPen.down() myPen.goto(points[1][0],points[1][1]) myPen.goto(points[2][0],points[2][1]) myPen.goto(points[0][0],points[0][1]) if depth>0: triangle([points[0], getMid(points[0], points[1]), getMid(points[0], points[2])], depth-1) triangle([points[1], getMid(points[0], points[1]), getMid(points[1], points[2])], depth-1) triangle([points[2], getMid(points[2], points[1]), getMid(points[0], points[2])], depth-1) if __name__ == '__main__': if len(sys.argv) !=2: raise ValueError('right format for using this script: ' '$python fractals.py <int:depth_for_fractal>') myPen = turtle.Turtle() myPen.ht() myPen.speed(5) myPen.pencolor('red') triangle(points,int(sys.argv[1]))
[]
[]
[]
archives/1098994933_python.zip
other/tower_of_hanoi.py
def moveTower(height, fromPole, toPole, withPole): ''' >>> moveTower(3, 'A', 'B', 'C') moving disk from A to B moving disk from A to C moving disk from B to C moving disk from A to B moving disk from C to A moving disk from C to B moving disk from A to B ''' if height >= 1: moveTower(height-1, fromPole, withPole, toPole) moveDisk(fromPole, toPole) moveTower(height-1, withPole, toPole, fromPole) def moveDisk(fp,tp): print('moving disk from', fp, 'to', tp) def main(): height = int(input('Height of hanoi: ').strip()) moveTower(height, 'A', 'B', 'C') if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
other/two_sum.py
""" Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. """ def twoSum(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ chk_map = {} for index, val in enumerate(nums): compl = target - val if compl in chk_map: indices = [chk_map[compl], index] print(indices) return [indices] else: chk_map[val] = index return False
[]
[]
[]
archives/1098994933_python.zip
other/word_patterns.py
import pprint, time def getWordPattern(word): word = word.upper() nextNum = 0 letterNums = {} wordPattern = [] for letter in word: if letter not in letterNums: letterNums[letter] = str(nextNum) nextNum += 1 wordPattern.append(letterNums[letter]) return '.'.join(wordPattern) def main(): startTime = time.time() allPatterns = {} with open('Dictionary.txt') as fo: wordList = fo.read().split('\n') for word in wordList: pattern = getWordPattern(word) if pattern not in allPatterns: allPatterns[pattern] = [word] else: allPatterns[pattern].append(word) with open('Word Patterns.txt', 'w') as fo: fo.write(pprint.pformat(allPatterns)) totalTime = round(time.time() - startTime, 2) print(('Done! [', totalTime, 'seconds ]')) if __name__ == '__main__': main()
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_01/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_01/sol1.py
""" Problem Statement: 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. """ def solution(n): """Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 >>> solution(-7) 0 """ return sum([e for e in range(3, n) if e % 3 == 0 or e % 5 == 0]) if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_01/sol2.py
""" Problem Statement: 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. """ def solution(n): """Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ sum = 0 terms = (n - 1) // 3 sum += ((terms) * (6 + (terms - 1) * 3)) // 2 # sum of an A.P. terms = (n - 1) // 5 sum += ((terms) * (10 + (terms - 1) * 5)) // 2 terms = (n - 1) // 15 sum -= ((terms) * (30 + (terms - 1) * 15)) // 2 return sum if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_01/sol3.py
""" Problem Statement: 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. """ def solution(n): """ This solution is based on the pattern that the successive numbers in the series follow: 0+3,+2,+1,+3,+1,+2,+3. Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ sum = 0 num = 0 while 1: num += 3 if num >= n: break sum += num num += 2 if num >= n: break sum += num num += 1 if num >= n: break sum += num num += 3 if num >= n: break sum += num num += 1 if num >= n: break sum += num num += 2 if num >= n: break sum += num num += 3 if num >= n: break sum += num return sum if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_01/sol4.py
""" Problem Statement: 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. """ def solution(n): """Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ xmulti = [] zmulti = [] z = 3 x = 5 temp = 1 while True: result = z * temp if result < n: zmulti.append(result) temp += 1 else: temp = 1 break while True: result = x * temp if result < n: xmulti.append(result) temp += 1 else: break collection = list(set(xmulti + zmulti)) return sum(collection) if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_01/sol5.py
""" Problem Statement: 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. """ """A straightforward pythonic solution using list comprehension""" def solution(n): """Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ return sum([i for i in range(n) if i % 3 == 0 or i % 5 == 0]) if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_01/sol6.py
""" Problem Statement: 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. """ def solution(n): """Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ a = 3 result = 0 while a < n: if a % 3 == 0 or a % 5 == 0: result += a elif a % 15 == 0: result -= a a += 1 return result if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_02/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_02/sol1.py
""" Problem: Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1,2,3,5,8,13,21,34,55,89,.. 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. """ def solution(n): """Returns the sum of all fibonacci sequence even elements that are lower or equals to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 """ i = 1 j = 2 sum = 0 while j <= n: if j % 2 == 0: sum += j i, j = j, i + j return sum if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_02/sol2.py
""" Problem: Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1,2,3,5,8,13,21,34,55,89,.. 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. """ def solution(n): """Returns the sum of all fibonacci sequence even elements that are lower or equals to n. >>> solution(10) [2, 8] >>> solution(15) [2, 8] >>> solution(2) [2] >>> solution(1) [] >>> solution(34) [2, 8, 34] """ ls = [] a, b = 0, 1 while b <= n: if b % 2 == 0: ls.append(b) a, b = b, a + b return ls if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_02/sol3.py
""" Problem: Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1,2,3,5,8,13,21,34,55,89,.. 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. """ def solution(n): """Returns the sum of all fibonacci sequence even elements that are lower or equals to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 """ if n <= 1: return 0 a = 0 b = 2 count = 0 while 4 * b + a <= n: a, b = b, 4 * b + a count += a return count + b if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_02/sol4.py
""" Problem: Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1,2,3,5,8,13,21,34,55,89,.. 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. """ import math from decimal import Decimal, getcontext def solution(n): """Returns the sum of all fibonacci sequence even elements that are lower or equals to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 >>> solution(3.4) 2 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or passive of cast to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or passive of cast to int. """ try: n = int(n) except (TypeError, ValueError) as e: raise TypeError("Parameter n must be int or passive of cast to int.") if n <= 0: raise ValueError("Parameter n must be greater or equal to one.") getcontext().prec = 100 phi = (Decimal(5) ** Decimal(0.5) + 1) / Decimal(2) index = (math.floor(math.log(n * (phi + 2), phi) - 1) // 3) * 3 + 2 num = Decimal(round(phi ** Decimal(index + 1))) / (phi + 2) sum = num // 2 return int(sum) if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_03/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_03/sol1.py
""" 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. """ import math def isprime(no): if no == 2: return True elif no % 2 == 0: return False sq = int(math.sqrt(no)) + 1 for i in range(3, sq, 2): if no % i == 0: return False return True def solution(n): """Returns the largest prime factor of a given number n. >>> solution(13195) 29 >>> solution(10) 5 >>> solution(17) 17 >>> solution(3.4) 3 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or passive of cast to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or passive of cast to int. """ try: n = int(n) except (TypeError, ValueError) as e: raise TypeError("Parameter n must be int or passive of cast to int.") if n <= 0: raise ValueError("Parameter n must be greater or equal to one.") maxNumber = 0 if isprime(n): return n else: while n % 2 == 0: n = n / 2 if isprime(n): return int(n) else: n1 = int(math.sqrt(n)) + 1 for i in range(3, n1, 2): if n % i == 0: if isprime(n / i): maxNumber = n / i break elif isprime(i): maxNumber = i return maxNumber if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_03/sol2.py
""" 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. """ def solution(n): """Returns the largest prime factor of a given number n. >>> solution(13195) 29 >>> solution(10) 5 >>> solution(17) 17 >>> solution(3.4) 3 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or passive of cast to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or passive of cast to int. """ try: n = int(n) except (TypeError, ValueError) as e: raise TypeError("Parameter n must be int or passive of cast to int.") if n <= 0: raise ValueError("Parameter n must be greater or equal to one.") prime = 1 i = 2 while i * i <= n: while n % i == 0: prime = i n //= i i += 1 if n > 1: prime = n return int(prime) if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_04/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_04/sol1.py
""" 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. """ def solution(n): """Returns the largest palindrome made from the product of two 3-digit numbers which is less than n. >>> solution(20000) 19591 >>> solution(30000) 29992 >>> solution(40000) 39893 """ # fetchs the next number for number in range(n - 1, 10000, -1): # converts number into string. strNumber = str(number) # checks whether 'strNumber' is a palindrome. if strNumber == strNumber[::-1]: divisor = 999 # if 'number' is a product of two 3-digit numbers # then number is the answer otherwise fetch next number. while divisor != 99: if (number % divisor == 0) and ( len(str(int(number / divisor))) == 3 ): return number divisor -= 1 if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_04/sol2.py
""" 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. """ def solution(n): """Returns the largest palindrome made from the product of two 3-digit numbers which is less than n. >>> solution(20000) 19591 >>> solution(30000) 29992 >>> solution(40000) 39893 """ answer = 0 for i in range(999, 99, -1): # 3 digit nimbers range from 999 down to 100 for j in range(999, 99, -1): t = str(i * j) if t == t[::-1] and i * j < n: answer = max(answer, i * j) return answer if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_05/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_05/sol1.py
""" 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? """ def solution(n): """Returns the smallest positive number that is evenly divisible(divisible with no remainder) by all of the numbers from 1 to n. >>> solution(10) 2520 >>> solution(15) 360360 >>> solution(20) 232792560 >>> solution(22) 232792560 >>> solution(3.4) 6 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or passive of cast to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or passive of cast to int. """ try: n = int(n) except (TypeError, ValueError) as e: raise TypeError("Parameter n must be int or passive of cast to int.") if n <= 0: raise ValueError("Parameter n must be greater or equal to one.") i = 0 while 1: i += n * (n - 1) nfound = 0 for j in range(2, n): if i % j != 0: nfound = 1 break if nfound == 0: if i == 0: i = 1 return i if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_05/sol2.py
""" 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? """ """ Euclidean GCD Algorithm """ def gcd(x, y): return x if y == 0 else gcd(y, x % y) """ Using the property lcm*gcd of two numbers = product of them """ def lcm(x, y): return (x * y) // gcd(x, y) def solution(n): """Returns the smallest positive number that is evenly divisible(divisible with no remainder) by all of the numbers from 1 to n. >>> solution(10) 2520 >>> solution(15) 360360 >>> solution(20) 232792560 >>> solution(22) 232792560 """ g = 1 for i in range(1, n + 1): g = lcm(g, i) return g if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_06/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_06/sol1.py
# -*- coding: utf-8 -*- """ Problem: The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 552 = 3025 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. """ def solution(n): """Returns the difference between the sum of the squares of the first n natural numbers and the square of the sum. >>> solution(10) 2640 >>> solution(15) 13160 >>> solution(20) 41230 >>> solution(50) 1582700 """ suma = 0 sumb = 0 for i in range(1, n + 1): suma += i ** 2 sumb += i sum = sumb ** 2 - suma return sum if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_06/sol2.py
# -*- coding: utf-8 -*- """ Problem: The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 552 = 3025 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. """ def solution(n): """Returns the difference between the sum of the squares of the first n natural numbers and the square of the sum. >>> solution(10) 2640 >>> solution(15) 13160 >>> solution(20) 41230 >>> solution(50) 1582700 """ suma = n * (n + 1) / 2 suma **= 2 sumb = n * (n + 1) * (2 * n + 1) / 6 return int(suma - sumb) if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_06/sol3.py
# -*- coding: utf-8 -*- """ Problem: The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 552 = 3025 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. """ import math def solution(n): """Returns the difference between the sum of the squares of the first n natural numbers and the square of the sum. >>> solution(10) 2640 >>> solution(15) 13160 >>> solution(20) 41230 >>> solution(50) 1582700 """ sum_of_squares = sum([i * i for i in range(1, n + 1)]) square_of_sum = int(math.pow(sum(range(1, n + 1)), 2)) return square_of_sum - sum_of_squares if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_07/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_07/sol1.py
# -*- coding: utf-8 -*- """ 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 math import sqrt def isprime(n): if n == 2: return True elif n % 2 == 0: return False else: sq = int(sqrt(n)) + 1 for i in range(3, sq, 2): if n % i == 0: return False return True def solution(n): """Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 """ i = 0 j = 1 while i != n and j < 3: j += 1 if isprime(j): i += 1 while i != n: j += 2 if isprime(j): i += 1 return j if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_07/sol2.py
# -*- coding: utf-8 -*- """ 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? """ def isprime(number): for i in range(2, int(number ** 0.5) + 1): if number % i == 0: return False return True def solution(n): """Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 >>> solution(3.4) 5 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or passive of cast to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or passive of cast to int. """ try: n = int(n) except (TypeError, ValueError) as e: raise TypeError("Parameter n must be int or passive of cast to int.") if n <= 0: raise ValueError("Parameter n must be greater or equal to one.") primes = [] num = 2 while len(primes) < n: if isprime(num): primes.append(num) num += 1 else: num += 1 return primes[len(primes) - 1] if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_07/sol3.py
# -*- coding: utf-8 -*- """ 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? """ import math import itertools def primeCheck(number): if number % 2 == 0 and number > 2: return False return all(number % i for i in range(3, int(math.sqrt(number)) + 1, 2)) def prime_generator(): num = 2 while True: if primeCheck(num): yield num num += 1 def solution(n): """Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 """ return next(itertools.islice(prime_generator(), n - 1, n)) if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_08/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_08/sol1.py
# -*- coding: utf-8 -*- """ The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? """ import sys N = """73167176531330624919225119674426574742355349194934\ 96983520312774506326239578318016984801869478851843\ 85861560789112949495459501737958331952853208805511\ 12540698747158523863050715693290963295227443043557\ 66896648950445244523161731856403098711121722383113\ 62229893423380308135336276614282806444486645238749\ 30358907296290491560440772390713810515859307960866\ 70172427121883998797908792274921901699720888093776\ 65727333001053367881220235421809751254540594752243\ 52584907711670556013604839586446706324415722155397\ 53697817977846174064955149290862569321978468622482\ 83972241375657056057490261407972968652414535100474\ 82166370484403199890008895243450658541227588666881\ 16427171479924442928230863465674813919123162824586\ 17866458359124566529476545682848912883142607690042\ 24219022671055626321111109370544217506941658960408\ 07198403850962455444362981230987879927244284909188\ 84580156166097919133875499200524063689912560717606\ 05886116467109405077541002256983155200055935729725\ 71636269561882670428252483600823257530420752963450""" def solution(n): """Find the thirteen adjacent digits in the 1000-digit number n that have the greatest product and returns it. >>> solution(N) 23514624000 """ LargestProduct = -sys.maxsize - 1 for i in range(len(n) - 12): product = 1 for j in range(13): product *= int(n[i + j]) if product > LargestProduct: LargestProduct = product return LargestProduct if __name__ == "__main__": print(solution(N))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_08/sol2.py
# -*- coding: utf-8 -*- """ The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? """ from functools import reduce N = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def solution(n): """Find the thirteen adjacent digits in the 1000-digit number n that have the greatest product and returns it. >>> solution(N) 23514624000 """ return max( [ reduce(lambda x, y: int(x) * int(y), n[i : i + 13]) for i in range(len(n) - 12) ] ) if __name__ == "__main__": print(solution(str(N)))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_09/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_09/sol1.py
""" Problem Statement: A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ def solution(): """ Returns the product of a,b,c which are Pythagorean Triplet that satisfies the following: 1. a < b < c 2. a**2 + b**2 = c**2 3. a + b + c = 1000 # The code below has been commented due to slow execution affecting Travis. # >>> solution() # 31875000 """ for a in range(300): for b in range(400): for c in range(500): if a < b < c: if (a ** 2) + (b ** 2) == (c ** 2): if (a + b + c) == 1000: return a * b * c if __name__ == "__main__": print("Please Wait...") print(solution())
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_09/sol2.py
""" Problem Statement: A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ def solution(n): """ Return the product of a,b,c which are Pythagorean Triplet that satisfies the following: 1. a < b < c 2. a**2 + b**2 = c**2 3. a + b + c = 1000 >>> solution(1000) 31875000 """ product = -1 d = 0 for a in range(1, n // 3): """Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c """ b = (n * n - 2 * a * n) // (2 * n - 2 * a) c = n - a - b if c * c == (a * a + b * b): d = a * b * c if d >= product: product = d return product if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_09/sol3.py
""" Problem Statement: A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ def solution(): """ Returns the product of a,b,c which are Pythagorean Triplet that satisfies the following: 1. a**2 + b**2 = c**2 2. a + b + c = 1000 # The code below has been commented due to slow execution affecting Travis. # >>> solution() # 31875000 """ return [ a * b * c for a in range(1, 999) for b in range(a, 999) for c in range(b, 999) if (a * a + b * b == c * c) and (a + b + c == 1000) ][0] if __name__ == "__main__": print(solution())
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_10/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_10/sol1.py
""" Problem Statement: The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. """ from math import sqrt def is_prime(n): for i in range(2, int(sqrt(n)) + 1): if n % i == 0: return False return True def sum_of_primes(n): if n > 2: sumOfPrimes = 2 else: return 0 for i in range(3, n, 2): if is_prime(i): sumOfPrimes += i return sumOfPrimes def solution(n): """Returns the sum of all the primes below n. # The code below has been commented due to slow execution affecting Travis. # >>> solution(2000000) # 142913828922 >>> solution(1000) 76127 >>> solution(5000) 1548136 >>> solution(10000) 5736396 >>> solution(7) 10 """ return sum_of_primes(n) if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_10/sol2.py
""" Problem Statement: The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. """ import math from itertools import takewhile def primeCheck(number): if number % 2 == 0 and number > 2: return False return all(number % i for i in range(3, int(math.sqrt(number)) + 1, 2)) def prime_generator(): num = 2 while True: if primeCheck(num): yield num num += 1 def solution(n): """Returns the sum of all the primes below n. # The code below has been commented due to slow execution affecting Travis. # >>> solution(2000000) # 142913828922 >>> solution(1000) 76127 >>> solution(5000) 1548136 >>> solution(10000) 5736396 >>> solution(7) 10 """ return sum(takewhile(lambda x: x < n, prime_generator())) if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_10/sol3.py
""" https://projecteuler.net/problem=10 Problem Statement: The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million using Sieve_of_Eratosthenes: The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is smaller than 10 million. Only for positive numbers. """ def prime_sum(n: int) -> int: """ Returns the sum of all the primes below n. >>> prime_sum(2_000_000) 142913828922 >>> prime_sum(1_000) 76127 >>> prime_sum(5_000) 1548136 >>> prime_sum(10_000) 5736396 >>> prime_sum(7) 10 >>> prime_sum(7.1) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> prime_sum(-7) # doctest: +ELLIPSIS Traceback (most recent call last): ... IndexError: list assignment index out of range >>> prime_sum("seven") # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: can only concatenate str (not "int") to str """ list_ = [0 for i in range(n + 1)] list_[0] = 1 list_[1] = 1 for i in range(2, int(n ** 0.5) + 1): if list_[i] == 0: for j in range(i * i, n + 1, i): list_[j] = 1 s = 0 for i in range(n): if list_[i] == 0: s += i return s if __name__ == "__main__": # import doctest # doctest.testmod() print(prime_sum(int(input().strip())))
[ "int" ]
[ 374 ]
[ 377 ]
archives/1098994933_python.zip
project_euler/problem_11/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_11/sol1.py
""" What is the greatest product of four adjacent numbers (horizontally, vertically, or diagonally) in this 20x20 array? 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 """ import os def largest_product(grid): nColumns = len(grid[0]) nRows = len(grid) largest = 0 lrDiagProduct = 0 rlDiagProduct = 0 # Check vertically, horizontally, diagonally at the same time (only works # for nxn grid) for i in range(nColumns): for j in range(nRows - 3): vertProduct = ( grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i] ) horzProduct = ( grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3] ) # Left-to-right diagonal (\) product if i < nColumns - 3: lrDiagProduct = ( grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3] ) # Right-to-left diagonal(/) product if i > 2: rlDiagProduct = ( grid[i][j] * grid[i - 1][j + 1] * grid[i - 2][j + 2] * grid[i - 3][j + 3] ) maxProduct = max( vertProduct, horzProduct, lrDiagProduct, rlDiagProduct ) if maxProduct > largest: largest = maxProduct return largest def solution(): """Returns the sum of all the multiples of 3 or 5 below n. >>> solution() 70600674 """ grid = [] with open(os.path.dirname(__file__) + "/grid.txt") as file: for line in file: grid.append(line.strip("\n").split(" ")) grid = [[int(i) for i in grid[j]] for j in range(len(grid))] return largest_product(grid) if __name__ == "__main__": print(solution())
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_11/sol2.py
""" What is the greatest product of four adjacent numbers (horizontally, vertically, or diagonally) in this 20x20 array? 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 """ import os def solution(): """Returns the sum of all the multiples of 3 or 5 below n. >>> solution() 70600674 """ with open(os.path.dirname(__file__) + "/grid.txt") as f: l = [] for i in range(20): l.append([int(x) for x in f.readline().split()]) maximum = 0 # right for i in range(20): for j in range(17): temp = l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3] if temp > maximum: maximum = temp # down for i in range(17): for j in range(20): temp = l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j] if temp > maximum: maximum = temp # diagonal 1 for i in range(17): for j in range(17): temp = ( l[i][j] * l[i + 1][j + 1] * l[i + 2][j + 2] * l[i + 3][j + 3] ) if temp > maximum: maximum = temp # diagonal 2 for i in range(17): for j in range(3, 20): temp = ( l[i][j] * l[i + 1][j - 1] * l[i + 2][j - 2] * l[i + 3][j - 3] ) if temp > maximum: maximum = temp return maximum if __name__ == "__main__": print(solution())
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_12/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_12/sol1.py
""" Highly divisible triangular numbers Problem 12 The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: 1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28 We can see that 28 is the first triangle number to have over five divisors. What is the value of the first triangle number to have over five hundred divisors? """ from math import sqrt def count_divisors(n): nDivisors = 0 for i in range(1, int(sqrt(n)) + 1): if n % i == 0: nDivisors += 2 # check if n is perfect square if n ** 0.5 == int(n ** 0.5): nDivisors -= 1 return nDivisors def solution(): """Returns the value of the first triangle number to have over five hundred divisors. # The code below has been commented due to slow execution affecting Travis. # >>> solution() # 76576500 """ tNum = 1 i = 1 while True: i += 1 tNum += i if count_divisors(tNum) > 500: break return tNum if __name__ == "__main__": print(solution())
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_12/sol2.py
""" Highly divisible triangular numbers Problem 12 The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: 1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28 We can see that 28 is the first triangle number to have over five divisors. What is the value of the first triangle number to have over five hundred divisors? """ def triangle_number_generator(): for n in range(1, 1000000): yield n * (n + 1) // 2 def count_divisors(n): return sum( [2 for i in range(1, int(n ** 0.5) + 1) if n % i == 0 and i * i != n] ) def solution(): """Returns the value of the first triangle number to have over five hundred divisors. # The code below has been commented due to slow execution affecting Travis. # >>> solution() # 76576500 """ return next( i for i in triangle_number_generator() if count_divisors(i) > 500 ) if __name__ == "__main__": print(solution())
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_13/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_13/sol1.py
""" Problem Statement: Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. """ def solution(array): """Returns the first ten digits of the sum of the array elements. >>> import os >>> sum = 0 >>> array = [] >>> with open(os.path.dirname(__file__) + "/num.txt","r") as f: ... for line in f: ... array.append(int(line)) ... >>> solution(array) '5537376230' """ return str(sum(array))[:10] if __name__ == "__main__": n = int(input().strip()) array = [] for i in range(n): array.append(int(input().strip())) print(solution(array))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_14/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_14/sol1.py
# -*- coding: utf-8 -*- """ Problem Statement: The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? """ def solution(n): """Returns the number under n that generates the longest sequence using the formula: n → n/2 (n is even) n → 3n + 1 (n is odd) # The code below has been commented due to slow execution affecting Travis. # >>> solution(1000000) # {'counter': 525, 'largest_number': 837799} >>> solution(200) {'counter': 125, 'largest_number': 171} >>> solution(5000) {'counter': 238, 'largest_number': 3711} >>> solution(15000) {'counter': 276, 'largest_number': 13255} """ largest_number = 0 pre_counter = 0 for input1 in range(n): counter = 1 number = input1 while number > 1: if number % 2 == 0: number /= 2 counter += 1 else: number = (3 * number) + 1 counter += 1 if counter > pre_counter: largest_number = input1 pre_counter = counter return {"counter": pre_counter, "largest_number": largest_number} if __name__ == "__main__": result = solution(int(input().strip())) print( ( "Largest Number:", result["largest_number"], "->", result["counter"], "digits", ) )
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_14/sol2.py
# -*- coding: utf-8 -*- """ Collatz conjecture: start with any positive integer n. Next term obtained from the previous term as follows: If the previous term is even, the next term is one half the previous term. If the previous term is odd, the next term is 3 times the previous term plus 1. The conjecture states the sequence will always reach 1 regardless of starting n. Problem Statement: The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? """ def collatz_sequence(n): """Returns the Collatz sequence for n.""" sequence = [n] while n != 1: if n % 2 == 0: n //= 2 else: n = 3 * n + 1 sequence.append(n) return sequence def solution(n): """Returns the number under n that generates the longest Collatz sequence. # The code below has been commented due to slow execution affecting Travis. # >>> solution(1000000) # {'counter': 525, 'largest_number': 837799} >>> solution(200) {'counter': 125, 'largest_number': 171} >>> solution(5000) {'counter': 238, 'largest_number': 3711} >>> solution(15000) {'counter': 276, 'largest_number': 13255} """ result = max([(len(collatz_sequence(i)), i) for i in range(1, n)]) return {"counter": result[0], "largest_number": result[1]} if __name__ == "__main__": result = solution(int(input().strip())) print( "Longest Collatz sequence under one million is %d with length %d" % (result["largest_number"], result["counter"]) )
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_15/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_15/sol1.py
""" Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. How many such routes are there through a 20×20 grid? """ from math import factorial def lattice_paths(n): """ Returns the number of paths possible in a n x n grid starting at top left corner going to bottom right corner and being able to move right and down only. bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 50 1.008913445455642e+29 bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 25 126410606437752.0 bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 23 8233430727600.0 bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 15 155117520.0 bruno@bruno-laptop:~/git/Python/project_euler/problem_15$ python3 sol1.py 1 2.0 >>> lattice_paths(25) 126410606437752 >>> lattice_paths(23) 8233430727600 >>> lattice_paths(20) 137846528820 >>> lattice_paths(15) 155117520 >>> lattice_paths(1) 2 """ n = ( 2 * n ) # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... k = n / 2 return int(factorial(n) / (factorial(k) * factorial(n - k))) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(lattice_paths(20)) else: try: n = int(sys.argv[1]) print(lattice_paths(n)) except ValueError: print("Invalid entry - please enter a number.")
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_16/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_16/sol1.py
""" 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? """ def solution(power): """Returns the sum of the digits of the number 2^power. >>> solution(1000) 1366 >>> solution(50) 76 >>> solution(20) 31 >>> solution(15) 26 """ num = 2 ** power string_num = str(num) list_num = list(string_num) sum_of_num = 0 for i in list_num: sum_of_num += int(i) return sum_of_num if __name__ == "__main__": power = int(input("Enter the power of 2: ").strip()) print("2 ^ ", power, " = ", 2 ** power) result = solution(power) print("Sum of the digits is: ", result)
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_16/sol2.py
""" 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? """ def solution(power): """Returns the sum of the digits of the number 2^power. >>> solution(1000) 1366 >>> solution(50) 76 >>> solution(20) 31 >>> solution(15) 26 """ n = 2 ** power r = 0 while n: r, n = r + n % 10, n // 10 return r if __name__ == "__main__": print(solution(int(str(input()).strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_17/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_17/sol1.py
""" Number letter counts Problem 17 If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance withBritish usage. """ def solution(n): """Returns the number of letters used to write all numbers from 1 to n. where n is lower or equals to 1000. >>> solution(1000) 21124 >>> solution(5) 19 """ # number of letters in zero, one, two, ..., nineteen (0 for zero since it's # never said aloud) ones_counts = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8] # number of letters in twenty, thirty, ..., ninety (0 for numbers less than # 20 due to inconsistency in teens) tens_counts = [0, 0, 6, 6, 5, 5, 5, 7, 6, 6] count = 0 for i in range(1, n + 1): if i < 1000: if i >= 100: # add number of letters for "n hundred" count += ones_counts[i // 100] + 7 if i % 100 != 0: # add number of letters for "and" if number is not multiple # of 100 count += 3 if 0 < i % 100 < 20: # add number of letters for one, two, three, ..., nineteen # (could be combined with below if not for inconsistency in # teens) count += ones_counts[i % 100] else: # add number of letters for twenty, twenty one, ..., ninety # nine count += ones_counts[i % 10] count += tens_counts[(i % 100 - i % 10) // 10] else: count += ones_counts[i // 1000] + 8 return count if __name__ == "__main__": print(solution(int(input().strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_19/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_19/sol1.py
""" Counting Sundays Problem 19 You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? """ def solution(): """Returns the number of mondays that fall on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? >>> solution() 171 """ days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] day = 6 month = 1 year = 1901 sundays = 0 while year < 2001: day += 7 if (year % 4 == 0 and not year % 100 == 0) or (year % 400 == 0): if day > days_per_month[month - 1] and month != 2: month += 1 day = day - days_per_month[month - 2] elif day > 29 and month == 2: month += 1 day = day - 29 else: if day > days_per_month[month - 1]: month += 1 day = day - days_per_month[month - 2] if month > 12: year += 1 month = 1 if year < 2001 and day == 1: sundays += 1 return sundays if __name__ == "__main__": print(solution())
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_20/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_20/sol1.py
""" n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! """ def factorial(n): fact = 1 for i in range(1, n + 1): fact *= i return fact def split_and_add(number): """Split number digits and add them.""" sum_of_digits = 0 while number > 0: last_digit = number % 10 sum_of_digits += last_digit number = number // 10 # Removing the last_digit from the given number return sum_of_digits def solution(n): """Returns the sum of the digits in the number 100! >>> solution(100) 648 >>> solution(50) 216 >>> solution(10) 27 >>> solution(5) 3 >>> solution(3) 6 >>> solution(2) 2 >>> solution(1) 1 """ f = factorial(n) result = split_and_add(f) return result if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_20/sol2.py
""" n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! """ from math import factorial def solution(n): """Returns the sum of the digits in the number 100! >>> solution(100) 648 >>> solution(50) 216 >>> solution(10) 27 >>> solution(5) 3 >>> solution(3) 6 >>> solution(2) 2 >>> solution(1) 1 """ return sum([int(x) for x in str(factorial(n))]) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_21/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_21/sol1.py
# -.- coding: latin-1 -.- from math import sqrt """ Amicable Numbers Problem 21 Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. Evaluate the sum of all the amicable numbers under 10000. """ def sum_of_divisors(n): total = 0 for i in range(1, int(sqrt(n) + 1)): if n % i == 0 and i != sqrt(n): total += i + n // i elif i == sqrt(n): total += i return total - n def solution(n): """Returns the sum of all the amicable numbers under n. >>> solution(10000) 31626 >>> solution(5000) 8442 >>> solution(1000) 504 >>> solution(100) 0 >>> solution(50) 0 """ total = sum( [ i for i in range(1, n) if sum_of_divisors(sum_of_divisors(i)) == i and sum_of_divisors(i) != i ] ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_22/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_22/sol1.py
# -*- coding: latin-1 -*- """ Name scores Problem 22 Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714. What is the total of all the name scores in the file? """ import os def solution(): """Returns the total of all the name scores in the file. >>> solution() 871198282 """ with open(os.path.dirname(__file__) + "/p022_names.txt") as file: names = str(file.readlines()[0]) names = names.replace('"', "").split(",") names.sort() name_score = 0 total_score = 0 for i, name in enumerate(names): for letter in name: name_score += ord(letter) - 64 total_score += (i + 1) * name_score name_score = 0 return total_score if __name__ == "__main__": print(solution())
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_22/sol2.py
# -*- coding: latin-1 -*- """ Name scores Problem 22 Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714. What is the total of all the name scores in the file? """ import os def solution(): """Returns the total of all the name scores in the file. >>> solution() 871198282 """ total_sum = 0 temp_sum = 0 with open(os.path.dirname(__file__) + "/p022_names.txt") as file: name = str(file.readlines()[0]) name = name.replace('"', "").split(",") name.sort() for i in range(len(name)): for j in name[i]: temp_sum += ord(j) - ord("A") + 1 total_sum += (i + 1) * temp_sum temp_sum = 0 return total_sum if __name__ == "__main__": print(solution())
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_234/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_234/sol1.py
""" https://projecteuler.net/problem=234 For an integer n ≥ 4, we define the lower prime square root of n, denoted by lps(n), as the largest prime ≤ √n and the upper prime square root of n, ups(n), as the smallest prime ≥ √n. So, for example, lps(4) = 2 = ups(4), lps(1000) = 31, ups(1000) = 37. Let us call an integer n ≥ 4 semidivisible, if one of lps(n) and ups(n) divides n, but not both. The sum of the semidivisible numbers not exceeding 15 is 30, the numbers are 8, 10 and 12. 15 is not semidivisible because it is a multiple of both lps(15) = 3 and ups(15) = 5. As a further example, the sum of the 92 semidivisible numbers up to 1000 is 34825. What is the sum of all semidivisible numbers not exceeding 999966663333 ? """ def fib(a, b, n): if n==1: return a elif n==2: return b elif n==3: return str(a)+str(b) temp = 0 for x in range(2,n): c=str(a) + str(b) temp = b b = c a = temp return c def solution(n): """Returns the sum of all semidivisible numbers not exceeding n.""" semidivisible = [] for x in range(n): l=[i for i in input().split()] c2=1 while(1): if len(fib(l[0],l[1],c2))<int(l[2]): c2+=1 else: break semidivisible.append(fib(l[0],l[1],c2+1)[int(l[2])-1]) return semidivisible if __name__ == "__main__": for i in solution(int(str(input()).strip())): print(i)
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_24/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_24/sol1.py
""" A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are: 012 021 102 120 201 210 What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? """ from itertools import permutations def solution(): """Returns the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. >>> solution() '2783915460' """ result = list(map("".join, permutations("0123456789"))) return result[999999] if __name__ == "__main__": print(solution())
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_25/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_25/sol1.py
# -*- coding: utf-8 -*- """ The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the index of the first term in the Fibonacci sequence to contain 1000 digits? """ def fibonacci(n): if n == 1 or type(n) is not int: return 0 elif n == 2: return 1 else: sequence = [0, 1] for i in range(2, n + 1): sequence.append(sequence[i - 1] + sequence[i - 2]) return sequence[n] def fibonacci_digits_index(n): digits = 0 index = 2 while digits < n: index += 1 digits = len(str(fibonacci(index))) return index def solution(n): """Returns the index of the first term in the Fibonacci sequence to contain n digits. >>> solution(1000) 4782 >>> solution(100) 476 >>> solution(50) 237 >>> solution(3) 12 """ return fibonacci_digits_index(n) if __name__ == "__main__": print(solution(int(str(input()).strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_25/sol2.py
# -*- coding: utf-8 -*- """ The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the index of the first term in the Fibonacci sequence to contain 1000 digits? """ def fibonacci_generator(): a, b = 0, 1 while True: a, b = b, a + b yield b def solution(n): """Returns the index of the first term in the Fibonacci sequence to contain n digits. >>> solution(1000) 4782 >>> solution(100) 476 >>> solution(50) 237 >>> solution(3) 12 """ answer = 1 gen = fibonacci_generator() while len(str(next(gen))) < n: answer += 1 return answer + 1 if __name__ == "__main__": print(solution(int(str(input()).strip())))
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_28/__init__.py
[]
[]
[]
archives/1098994933_python.zip
project_euler/problem_28/sol1.py
""" Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13 It can be verified that the sum of the numbers on the diagonals is 101. What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way? """ from math import ceil def diagonal_sum(n): """Returns the sum of the numbers on the diagonals in a n by n spiral formed in the same way. >>> diagonal_sum(1001) 669171001 >>> diagonal_sum(500) 82959497 >>> diagonal_sum(100) 651897 >>> diagonal_sum(50) 79697 >>> diagonal_sum(10) 537 """ total = 1 for i in range(1, int(ceil(n / 2.0))): odd = 2 * i + 1 even = 2 * i total = total + 4 * odd ** 2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(diagonal_sum(1001)) else: try: n = int(sys.argv[1]) print(diagonal_sum(n)) except ValueError: print("Invalid entry - please enter a number")
[]
[]
[]