text
stringlengths
37
1.41M
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : heap_sort.py @Time : 2020/03/25 18:19:01 @Author : cogito0823 @Contact : 754032908@qq.com @Desc : None ''' def heapify(array,index,heap_size): largest = index lchild = index * 2 + 1 rchild = index * 2 + 2 if lchild < heap_size and array[lchild] < array[largest]: largest = lchild if rchild < heap_size and array[rchild] < array[largest]: largest = rchild if largest != index: array[largest], array[index] = array[index], array[largest] heapify(array,largest,heap_size) def heap_sort(array): """堆排序 Examples: >>> heap_sort([7, 6, 5, 4, 3, 2, 1, 0]) [7, 6, 5, 4, 3, 2, 1, 0] >>> heap_sort([0, 1, 2, 3, 4, 5, 6, 7]) [7, 6, 5, 4, 3, 2, 1, 0] >>> heap_sort([1, 2, 3, 4, 5, 6, 7]) [7, 6, 5, 4, 3, 2, 1] >>> heap_sort([]) [] >>> heap_sort(None) """ if array: length = len(array) for index in range((length - 1) // 2, -1, -1): heapify(array,index,length) for i in range(length - 1, 0, -1): array[i], array[0] = array[0], array[i] heapify(array, 0, i) return array if __name__ == "__main__": import doctest doctest.testmod()
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- ''' @File : stack_binary_tree.py @Time : 2020/03/16 23:15:26 @Author : cogito0823 @Contact : 754032908@qq.com @Desc : 用栈遍历二叉树 ''' class Node(): """节点类""" def __init__(self,data): self.data = data self.left_child = None self.right_child = None """重构__wq__方法""" def __eq__(self,other): return (self.__class__ == other.__class__ and self.data == other.data and ((not self.left_child and not other.left_child) or self.left_child.data == other.left_child.data) and ((not self.right_child and not other.right_child) or self.right_child.data == other.right_child.data)) def create_binary_tree(tree_list): """通过一个数组创建二叉树""" if tree_list: data = tree_list.pop(0) if data: node = Node(data) node.left_child = create_binary_tree(tree_list) node.right_child = create_binary_tree(tree_list) return node return None def pre_order_traversal(node): """先序遍历""" result = [] tree_stack = [] while node or tree_stack: while node: result.append(node.data) tree_stack.append(node) node = node.left_child if tree_stack: node = tree_stack.pop() node = node.right_child return result def in_order_traversal(node): """中序遍历""" result = [] tree_stack = [] while node or tree_stack: while node: tree_stack.append(node) node = node.left_child if tree_stack: node = tree_stack.pop() if node: result.append(node.data) node = node.right_child return result # def post_order_traversal(node): # """后序遍历""" # # result = [] # tree_stack = [node] # while tree_stack: # while node: # while node.left_child: # tree_stack.append(node.left_child) # node = node.left_child # node = tree_stack[-1] # if node.right_child: # node = node.right_child # else: # print(node.data) # node = tree_stack.pop() # node = tree_stack[-1].right_child # tree_stack.append(node) if __name__ == "__main__": pre_order_traversal(create_binary_tree([1,2,3,4,None,None,5,None,None,6,None,None,None]))
class MyQueue: def __init__(self, capacity): self.capacity = capacity self.item = [None] * capacity self.head = None self.tail = None self.size = 0 def is_full(self): if self.head is None: return False if (self.tail + 1) % self.capacity == self.head: return True def enqueue(self, value): if self.is_full(): raise Exception("队列已满") if self.size == 0: self.head = 0 self.tail = 0 self.item[self.tail] = value else: self.tail = (self.tail + 1) % self.capacity self.item[self.tail] = value self.size += 1 def dequeue(self): if self.size == 0: raise Exception("队列为空") # 队列只有一个元素 if self.head == self.tail: self.head = None self.tail = None else: self.head = (self.head + 1) % self.capacity self.size -= 1
import requests import os yn = 'y' while yn == 'y': os.system('cls') print("Welcome to IsItDown.py!") print("Please write a URL or URLs you want to check. (separated by comma)") urls = input().split() for l in urls: l = l.strip(',') if '.' not in l: print(l, "is not valid url") else: if "https://" not in l: l = "https://"+l try: result = requests.get(l) print(l, "is up!") except: print(l, "is down!") while True: print("Do you want to start over? y/n ", end='') yn = input() if yn != 'y' and yn != 'n': print("That's not valid answer.") else: break print("k.bye")
size = 10 i = 0 userValue = [] print("List of Integers: ") while i < size: userValue.append(int(input("Enter an integer: "))) i = i + 1 print("Now the reverse") i = 9 while i >= 0: print(userValue[i]) i = i - 1
valor1 = int(input("Digite um número: ")) valor2 = int(input("Digite outro número: ")) soma = valor1 + valor2 print("A soma entre {} e {} é = {}".format(valor1, valor2, soma))
import numpy as np class LinearClassifier(object): """Implementation of linear classifier with svm and softmax loss functions""" def __init__(self): self.W = None def predict(self, X: np.array) -> np.array: """ predict labels for given data :param X: np.array of shape (num_data_points, num_dim) :return: prediction in np.array of shape (num_data_points) """ f = self.W.dot(X) return np.argmax(f, axis=1) def train(self, X: np.array, y: np.array, lr: float = 1e-3, epochs: int = 100, loss_function: str = 'svm', batch_size: int = 64): """ train the classifier using gradient descent with softmax of svm loss :param X: train data of shape (num_data_points, num_dim) :param y: labels of shape (num_data_points) :param lr: learning rate :param epochs: num of epochs :param batch_size: batch size :param loss_function: which loss function to use """ num_train, dimension = X.shape num_classes = np.max(y) + 1 self.W = np.random.rand(dimension, num_classes) for _ in range(epochs): batch_inds = np.random.choice(num_train, batch_size) X_batch = X[batch_inds] y_batch = y[batch_inds] if loss_function == 'svm': loss, gradients = self.svm_loss(X_batch, y_batch) elif loss_function == 'softmax': loss, gradients = self.softmax_loss(X_batch, y_batch) else: raise RuntimeError("unknown loss function") self.W -= gradients * lr def svm_loss(self, X: np.array, y: np.array, delta: float = 1.0, reg: float = 1e-2): """ Computes svm loss and gradients on weights :param X: train data of shape (batch_size, num_dim) :param y: labels of shape (batch_size) :param delta: delta for svm loss :param reg: regularization :return: loss and gradients for weights """ f = X.dot(self.W) # L = sum_j(max(0 ,y_j - y_i + delta)) # y_i correct class # y_j all other classes # dL/dy_i = -sum_j( 1(y_j - y_i + delta > 0)) # dL/dy_j = 1(y_j - y_i + delta > 0) diffs = f - f[np.arange(len(f)), y].reshape(-1, 1) diffs[diffs < delta] = 0 diffs[np.arange(len(f)), y] = 0 loss = np.mean(np.sum(diffs, axis=1)) loss += reg * 0.5 * np.sum(self.W**2) diffs[diffs > 0] = 1 row_sum = np.sum(diffs, axis=1) diffs[np.arange(len(diffs)), y] -= row_sum.T grads = X.T.dot(diffs) grads += reg*self.W return loss, grads def softmax_loss(self, X: np.array, y: np.array, reg: float = 1e-2): """ Computes cross entropy loss and gradients on weights :param X: train data of shape (batch_size, num_dim) :param y: labels of shape (batch_size) :param reg: regularization :return: loss and gradients for weights """ f = X.dot(self.W) # L = -log(e^y_i / sum(e^y_j)) # x_i correct label exp = np.exp(f - np.max(f, axis=1).reshape(-1, 1)) soft_scores = exp / np.sum(exp, axis=1) losses = soft_scores[np.arange(len(soft_scores)), y] loss = np.mean(-np.log(losses)) loss += reg * 0.5 * np.sum(self.W**2) soft_scores[np.arange(len(soft_scores)), y] -= 1 grads = X.T.dot(soft_scores) grads /= len(grads) grads += reg * self.W return loss, grads
# can you use varname for prompt? fname = 'First Name' lname = 'Last Name' #fname = raw_input(prompt) % 'First Name' def getvars(vars): prompt = '%s > ' % vars var = raw_input(prompt) return var fname = getvars(fname) lname = getvars(lname) print '%s %s' % (fname,lname)
# Ejercicio de Calculadora try: number1 = int(input('Valor 1: ')) except: print('Solo Numeros') exit() try: number2 = int(input('Valor 2: ')) except: print('Solo Numeros') exit() operation = input('que operacion quiere realizar +-*/') if operation == '+': print(number1+number2) elif operation == '-': print(number1-number2) elif operation == '*': print(number1*number2) elif operation == '/': print(number1/number2) else: print('No se encontro la operacion')
#!/usr/bin//python3 def ler_arquivo(nome): with open (nome,'r') as arquivo: conteudo = arquivo.read() return conteudo def escrever_arquivo (nome): with open (nome,'a') as arquivo: conteudo = input('digite uma fruta:') arquivo.write(conteudo +'\n') return True def sobrescrever_arquivo(nome): with open (nome, 'w') as arquivo: conteudo = input ('digite uma fruta: ') arquivo.white(conteudo +'\n') return True escrever_arquivo('frutas.txt') print(ler_arquivo('frutas.txt'))
#!/usr/bin//python3 qtd = int(input ('digite um inteiro')) for z in range (qtd): if z ==100: print("encontrei") break else: print('nao encontrei')
soma=0 for x in range (4): nota = float(input('Digite a nota {}: '.format(x+1))) soma +=nota print ('A média é igual há {:.2f}'.format(soma/4))
lower = 10 upper = 100 LowNumber = input("Enter a number ({}-­‐{}): ".format(str(lower), str(upper))) LowNumber = LowNumber.strip() HighNumber = input("Enter a number ({}-­‐{}): ".format(str(LowNumber), str(upper))) HighNumber = HighNumber.strip() for i in range(int(LowNumber), int(HighNumber)): print("{} {}".format(i, chr(i)))
import pandas as pd import numpy as np def get_betas(X, Y): """Get betas (according to OLS formula)""" betas = (np.transpose(X) * X)^(-1) * (np.transpose(X) * Y) # transpose is a numpy function print("Working!") return betas def get_residuals(betas, X, Y): """Get residuals (according to OLS formula)""" y_hat = betas * X residuals = Y - y_hat print("Working!") return residuals def get_n(X, Y): """Get N, check independent vs dependent variables""" n_X = length(X) n_Y = length(Y) if n_X == n_Y: n = n_X else: print("Error!") print("Working!") return n def get_ses(residuals, X, Y): """Get SEs (according to OLS formula)""" residuals2 = residuals^2 XX = (np.transpose(X) * X)^(-1) # transpose is not a real function N = get_n(X, Y) ses = (residuals2 / (N-1)) * XX print("Working!") return ses def get_r2(Y, X, betas): """Get R^2""" y_hat = X * betas y_bar = mean(y) SSR = sum((y_hat - y_bar)^2) SST = sum((y - y_bar)^2) r2 = SSR / SST print("Working!") return r2 def get_sse(Y, X, betas): """Get sum of squared errors""" y_hat = X * beta sse = (Y - y_hat) ** 2 print("Working!") return sse def get_loss_function(SSE, lamb, betas): """Get loss function""" betas_no_intercept = betas[1:len(betas)] loss_function = SSE + lamb * np.sum(np.abs(betas_no_intercept)) print("Working!") return loss_function def get_coeffs_given_lambda(X, Y, lamb): Z = # STANDARDIZED X Y_c = # CENTERED Y coefficients = np.linalg.inv(Z.transpose().dot(Z).values() + lamb * np.identity(X.shape[1])).dot(Z.transpose().dot(Y_c)) return(coefficients) def pick_lowest_lambda(X, Y): """Pick lowest lambda""" lambs = range(0, 1, 100) losses = list() for l in lambs: coeffs = get_coeffs_given_lambda(X, Y, l) SSE = get_sse(Y, X, coeffs) loss = loss_function(SSE, l, coeffs) losses.append(loss) min_loss = min(losses) lowest_lambda = loss(min_loss_position_in_list) print("Working!") return(lowest_lamb) def main(): """Performs OLS, prints output to table""" print("Working!") import pandas as pd import numpy as np def get_betas(X, Y): ''' Get betas (according to OLS formula) ''' betas = (np.transpose(X) * X)^(-1) * (np.transpose(X) * Y) # transpose is a numpy function print("Working!") return betas def get_residuals(betas, X, Y): ''' Get residuals (according to OLS formula) ''' y_hat = betas * X residuals = Y - y_hat print("Working!") return residuals def get_n(X, Y): ''' Get N, check independent vs dependent variables ''' n_X = length(X) n_Y = length(Y) if n_X == n_Y: n = n_X else: print("Error!") print("Working!") return n def get_ses(residuals, X, Y): ''' Get SEs (according to OLS formula) ''' residuals2 = residuals^2 XX = (np.transpose(X) * X)^(-1) # transpose is not a real function N = get_n(X, Y) ses = (residuals2 / (N-1)) * XX print("Working!") return ses def get_r2(Y, X, betas): ''' Get R^2 ''' y_hat = X * betas y_bar = mean(y) SSR = sum((y_hat - y_bar)^2) SST = sum((y - y_bar)^2) r2 = SSR / SST print("Working!") return r2 def get_sse(Y, X, betas): ''' Get sum of squared errors''' y_hat = X * betas sse = (Y - y_hat) ** 2 print("Working!") return sse def get_loss_function(SSE, lamb, betas): ''' Get loss function ''' betas_without_intercept = betas[1:length(betas)] loss_function = SSE + lamb * sum(abs(betas_without_intercept)) print("Working!") return loss_function def get_coefficients_given_lambda(lamb): ''' Get coefficients ''' return(coefficients) def pick_lowest_lamda(): ''' Pick lowest lambda ''' lambs = [0.001, 0.01, 0.1, 0.5, 1, 2, 10] l_num = length(lam) pred_num = X.shape[1] losses = list(length(lamb)) # prepare data for enumerate coeff_a = np.zeros((l_num, pred_num)) for ind, i in enumerate(lambs): loss = loss_function(lamb) list.append(loss) min_loss = min(losses) lowest_lamb = loss(min_loss_position_in_list) print("Working!") return(lowest_lamb) def main(): ''' Performs LASSO, prints output to table ''' print("Working!")
# -*- coding: utf-8 -*- """ Created on Thu Dec 26 18:01:04 2019 @author: soodr """ import tkinter from tkinter import Button from tkinter import Label from tkinter import StringVar from tkinter import Entry from tkinter import messagebox import time def myGame(): window = tkinter.Tk() window.title("Tic Tac Toe Mania") window.geometry("500x380") lbl = Label(window,text="Tic-tac-toe Game",font=('Helvetica','15'), padx = 10, pady = 10) lbl.grid(row=1,column=1) ply1 = StringVar() ply2 = StringVar() pl1_name = StringVar() pl2_name = StringVar() lb1 = Label(window, text="Player 1 Name: ") lb1.grid(row=2,column=2) pl1_entry = Entry(window, textvariable=pl1_name) pl1_entry.grid(row=2,column=3, columnspan = 3) lbl1 = Label(window, text="Player 1 Choice: ") lbl1.grid(row=2,column=0) ply1_entry = Entry(window, textvariable=ply1) ply1_entry.grid(row=2,column=1, columnspan = 3) lb2 = Label(window, text="Player 2 Name: ") lb2.grid(row=3,column=2) pl2_entry = Entry(window, textvariable=pl2_name) pl2_entry.grid(row=3,column=3, columnspan = 3) lbl2 = Label(window, text="Player 2 Choice: ") lbl2.grid(row=3,column=0) ply2_entry = Entry(window, textvariable=ply2) ply2_entry.grid(row=3,column=1, columnspan = 3) turn = 1; def clicked1(): global turn p1 = ply1.get() p2 = ply2.get() if p1 == "" or p2 == "": error = Label(window, text="Invalid Field Entry/Entries!!") error.grid(row=10,column=1) time.sleep(3) window.destroy() if btn1["text"]==" ": if turn==1: turn=2; btn1["text"]=p1 elif turn==2: turn=1; btn1["text"]=p2 check(); def clicked2(): global turn p1 = ply1.get() p2 = ply2.get() if p1 == "" or p2 == "": error = Label(window, text="Invalid Field Entry/Entries!!") error.grid(row=10,column=1) time.sleep(3) window.destroy() if btn2["text"]==" ": if turn==1: turn=2; btn2["text"]=p1 elif turn==2: turn=1; btn2["text"]=p2 check(); def clicked3(): global turn p1 = ply1.get() p2 = ply2.get() if p1 == "" or p2 == "": error = Label(window, text="Invalid Field Entry/Entries!!") error.grid(row=10,column=1) time.sleep(3) window.destroy() if btn3["text"]==" ": if turn==1: turn=2; btn3["text"]=p1 elif turn==2: turn=1; btn3["text"]=p2 check(); def clicked4(): global turn p1 = ply1.get() p2 = ply2.get() if p1 == "" or p2 == "": error = Label(window, text="Invalid Field Entry/Entries!!") error.grid(row=10,column=1) time.sleep(3) window.destroy() if btn4["text"]==" ": if turn==1: turn=2; btn4["text"]=p1 elif turn==2: turn=1; btn4["text"]=p2 check(); def clicked5(): global turn p1 = ply1.get() p2 = ply2.get() if p1 == "" or p2 == "": error = Label(window, text="Invalid Field Entry/Entries!!") error.grid(row=10,column=1) time.sleep(3) window.destroy() if btn5["text"]==" ": if turn==1: turn=2; btn5["text"]=p1 elif turn==2: turn=1; btn5["text"]=p2 check(); def clicked6(): global turn p1 = ply1.get() p2 = ply2.get() if p1 == "" or p2 == "": error = Label(window, text="Invalid Field Entry/Entries!!") error.grid(row=10,column=1) time.sleep(3) window.destroy() if btn6["text"]==" ": if turn==1: turn=2; btn6["text"]=p1 elif turn==2: turn=1; btn6["text"]=p2 check(); def clicked7(): global turn p1 = ply1.get() p2 = ply2.get() if p1 == "" or p2 == "": error = Label(window, text="Invalid Field Entry/Entries!!") error.grid(row=10,column=1) time.sleep(3) window.destroy() if btn7["text"]==" ": if turn==1: turn=2; btn7["text"]=p1 elif turn==2: turn=1; btn7["text"]=p2 check(); def clicked8(): global turn p1 = ply1.get() p2 = ply2.get() if p1 == "" or p2 == "": error = Label(window, text="Invalid Field Entry/Entries!!") error.grid(row=10,column=1) time.sleep(3) window.destroy() if btn8["text"]==" ": if turn==1: turn=2; btn8["text"]=p1 elif turn==2: turn=1; btn8["text"]=p2 check(); def clicked9(): global turn p1 = ply1.get() p2 = ply2.get() if p1 == "" or p2 == "": error = Label(window, text="Invalid Field Entry/Entries!!") error.grid(row=10,column=1) time.sleep(3) window.destroy() if btn9["text"]==" ": if turn==1: turn=2; btn9["text"]=p1 elif turn==2: turn=1; btn9["text"]=p2 check(); flag=1; def check(): global flag; b1 = btn1["text"]; b2 = btn2["text"]; b3 = btn3["text"]; b4 = btn4["text"]; b5 = btn5["text"]; b6 = btn6["text"]; b7 = btn7["text"]; b8 = btn8["text"]; b9 = btn9["text"]; flag=flag+1; if b1==b2 and b1==b3 and b1==ply1.get() or b1==b2 and b1==b3 and b1==ply2.get(): win(btn1["text"]) if b4==b5 and b4==b6 and b4==ply1.get() or b4==b5 and b4==b6 and b4==ply2.get(): win(btn4["text"]); if b7==b8 and b7==b9 and b7==ply1.get() or b7==b8 and b7==b9 and b7==ply2.get(): win(btn7["text"]); if b1==b4 and b1==b7 and b1==ply1.get() or b1==b4 and b1==b7 and b1==ply2.get(): win(btn1["text"]); if b2==b5 and b2==b8 and b2==ply1.get() or b2==b5 and b2==b8 and b2==ply2.get(): win(btn2["text"]); if b3==b6 and b3==b9 and b3==ply1.get() or b3==b6 and b3==b9 and b3==ply2.get(): win(btn3["text"]); if b1==b5 and b1==b9 and b1==ply1.get() or b1==b5 and b1==b9 and b1==ply2.get(): win(btn1["text"]); if b7==b5 and b7==b3 and b7==ply1.get() or b7==b5 and b7==b3 and b7==ply2.get(): win(btn7["text"]); if flag ==10: messagebox.showinfo("Tie", "Match Tied!!! Try again :)") window.destroy() def newGame(): newGame = messagebox.askquestion("New Game", "Do you wish to start a new game?") if newGame == 'yes': window.destroy() myGame() else: window.destroy() def win(player): if player == ply1.get(): player = pl1_name.get() if player == ply2.get(): player = pl2_name.get() ans = "Game complete " +player + " wins "; messagebox.showinfo("Congratulations", ans) newGame() k = 50 btn1 = Button(window, text=" ",bg="Black", fg="White",width=3,height=1,font=('Helvetica','20'),command=clicked1) btn1.place(x=50+k, y=120) btn2 = Button(window, text=" ",bg="Black", fg="White",width=3,height=1,font=('Helvetica','20'),command=clicked2) btn2.place(x=110+k, y=120) btn3 = Button(window, text=" ",bg="Black", fg="White",width=3,height=1,font=('Helvetica','20'),command=clicked3) btn3.place(x=170+k, y=120) btn4 = Button(window, text=" ",bg="Black", fg="White",width=3,height=1,font=('Helvetica','20'),command=clicked4) btn4.place(x=50+k, y=180) btn5 = Button(window, text=" ",bg="Black", fg="White",width=3,height=1,font=('Helvetica','20'),command=clicked5) btn5.place(x=110+k, y=180) btn6 = Button(window, text=" ",bg="Black", fg="White",width=3,height=1,font=('Helvetica','20'),command=clicked6) btn6.place(x=170+k, y=180) btn7 = Button(window, text=" ",bg="Black", fg="White",width=3,height=1,font=('Helvetica','20'),command=clicked7) btn7.place(x=50+k, y=240) btn8 = Button(window, text=" ",bg="Black", fg="White",width=3,height=1,font=('Helvetica','20'),command=clicked8) btn8.place(x=110+k, y=240) btn9 = Button(window, text=" ",bg="Black", fg="White",width=3,height=1,font=('Helvetica','20'),command=clicked9) btn9.place(x=170+k, y=240) new_btn = Button(window, text=" ",bg="Green", fg="White",font=('Helvetica','10'),command=newGame) new_btn["text"] = "New Game" new_btn.place(x = 160, y = 320) window.mainloop() myGame()
idade = contM = contH = cont = 0 while True: print('-' * 30) print('CADASTRE UMA PESSOA') print('-' * 30) idade = int(input('Quantos anos você tem?')) sexo = ' ' while sexo not in 'MF': sexo = str(input('Qual é o seu sexo? [M/F]')).strip().upper()[0] if idade >= 18: cont +=1 if sexo == 'M': contH += 1 if sexo == 'F' and idade < 20: contM += 1 resp = ' ' while resp not in 'SN': resp = str(input('Deseja continuar? [S/N]')).strip().upper()[0] if resp == 'N': break print('====== FIM DO PROGRAMA ======') print(f'Total de pessoas com mais de 18 anos: {cont}') print(f'Ao todo temos {contH} homens cadastrados') print(f'E temos {contM} mulheres com menos de 20 anos')
print ('='*40) print(' 10 TERMOS DE UMA PA ') termo = int(input('Primeiro termo: ')) razao = int(input('Razão: ')) pa = 0 pa = termo + (10 - 1) * razao for count in range(termo, pa + razao, razao): print('{} '.format(count), end=' ->')
menorP = 0 maiorP = 0 for count in range(1, 6): peso = float(input('Peso da {}ª pessoa: '.format(count))) if count == 1: maiorP = peso menorP = peso else: if peso > maiorP: maiorP = peso if peso < menorP: menorP = peso print('O maior peso lido foi de {}kg'.format(maiorP)) print('O menor peso lido foi de {}kg'.format(menorP))
peso = float(input('Digite seu peso: ')) altura = float(input('Digite sua altura: ')) imc = peso / (altura ** 2) print('Com peso de {}kg e altura de {}m'.format(peso,altura)) if imc <= 18.5: print('Seu IMC está em {}. Você está abaixo do peso'.format(imc)) elif imc <= 25: print('Seu IMC está em {}. Você está no seu peso ideal'.format(imc)) elif imc <= 30: print('Seu IMC está em {}. Você está com Sobrepeso'.format(imc)) elif imc <= 40: print('Seu IMC está em {}. Você está com Obesidade'.format(imc)) else: print('Seu IMC está em {}. Você está com Obesidade Mórbida'.format(imc))
##Python 3.7.3 Implementation import math ################### #- Collect input -# ################### def get_input(): ## Get inputs, and store them in an array num_boxes_students = input() boxes, students = num_boxes_students.split() rawArray = [] boxContents = input() return boxes, students, boxContents ################### #- Print Results -# ################### def print_results(array): ## Print out the entire array for i in range(0,len(array)): print(array[i]) #################################### #- Quick Sort: Partition and sort -# #################################### def quick_sort(array, start, end): ## Recusive loop break check - ## Make sure the indexes for starting point and end are consistent if start < end: ## Find the partition point, and sort out the middle. part = partition(array, start, end) ## Recursivley sort the function again. ## Sort the right side of the partition. quick_sort(array, part + 1, end) ## Sort the left side of the partition quick_sort(array, start, part - 1) return array ################ #- Partition -# ############### def partition(array, start, end): ## Set pivot point at the beginning of the array pivotPoint = array[end] index = start - 1 loopIndex = start while loopIndex in range(start, end): if array[loopIndex] < pivotPoint: index = index + 1 #Swap the two values of the array at loopIndex and index array[index], array[loopIndex] = array[loopIndex], array[index] loopIndex = loopIndex + 1 nextPointer = index + 1 ## Swap the index for the item at the end of the array array[nextPointer], array[end] = array[end],array[nextPointer] ## Increment the pointer by one and return return nextPointer ############################ #- Search for max candies -# ############################ def max_candy(array, boxes, students, middle): sum = 0 i = boxes - 1 while i in range(0, boxes): sum = math.floor(sum + (int(array[i])/int(array[middle]))) i = i - 1 if sum == students: return array[middle] return 0 ################################################################## #- Binary Search: Returns the index of the item we searched for -# ################################################################## def binary_search(array, start, end, boxes, students, absoluteMaxCandy=0): ## Make sure that the start index is less than the end index if start <= end: ## Find the middle of the start and the end indicies middle =int((start + end)/2) maxCandy = max_candy(array, boxes, students, middle) if int(maxCandy) > absoluteMaxCandy: absoluteMaxCandy = maxCandy print(absoluteMaxCandy) ## Else see if the element is smaller than the midpoint absoluteMaxCandy = binary_search(array, start, middle - 1, boxes, students, absoluteMaxCandy) absoluteMaxCandy = binary_search(array, middle + 1, end, boxes, students, absoluteMaxCandy) return absoluteMaxCandy ################### #- Find Answer -# ################### def find_answer(boxes, students, boxContents): contentsArray = boxContents.split() quick_sort(contentsArray, 0, len(contentsArray) - 1) return binary_search(contentsArray, 0, len(contentsArray) - 1, boxes, students, 0) ########## #- Main -# ########## def main(): # numTestCases = input() numTestCases = 1 sorted = [] for i in range(0,int(numTestCases)): ## Get Input returns the inputs boxes, students, boxContents = get_input() sorted.append(find_answer(int(boxes), int(students), boxContents)) print_results(sorted) main()
words = [] fileObj = open("ignore_words.txt", "r") # opens the file in read mode words += fileObj.read().splitlines() # puts the file into an array fileObj.close() fileObj = open("common_ignore.txt", "r") # opens the file in read mode words += fileObj.read().splitlines() # puts the file into an array fileObj.close() words = set(words) words = list(words) words = sorted(words, key=str.lower) words = "\n".join(words) fileObj = open("my_full_ignore.txt", "w") # opens the file in read mode fileObj.write(words) # puts the file into an array fileObj.close()
# -*- coding: utf-8 -*- """ Created on Tue Sep 13 20:38:56 2022 @author: Henry """ a=0; z=10; dato=0; for z in range(0,25): z=z+3; print("El valor de z es: ", z);
#Funcion para Crear la matriz def matrizKreator(n,m): A=[] for i in range(n): A.append([]) for j in range(m): A[i].append(int(input("Ingrese la duracion de llamada en segundos: "))) return(A); #Funcion para calcular el promedio de la matriz def prom(A): Agente=0 suma=0 for i in A: for j in i: suma+=j Agente+=1 return suma/Agente #Definir tamaño del vector n = int(input("Ingrese el numero de agentes: ")); m = int(input("Ingrese el numero de llamadas por agente: ")) #Mostrar la matriz creada Matrix=matrizKreator(n,m) print("La matriz creada es la siguiente: ", Matrix, end= " ") #Calcular el promedio Promedio=prom(Matrix) print("El promedio de la matriz creada es el siguiente: ", Promedio, end= " ")
def primo(n): for i in range(2,int(n/2)): if(n%i==0): return False; return True Arr=[13,12,27,31,56,11,10] for i in Arr: if(primo(i)): print("El numero ", i," es primo") else: print("El numero ", i," NO es primo")
#NAND or NOR로 모든 가능한 논리 회로를 구성할 수 있습니다. #실제로 상업적 용도의 flash memory 를 nand/nor 회로로만 구성합니다. #NOR 에 비해 적은 회로로도 구성할 수 있어서 몇 가지 단점에도 불구하고 nand flash memory가 주류 import numpy as np #nand 회로 def NAND(x1, x2): x = np.array([x1, x2]) weight = np.array([-0.5, -0.5]) bias = 0.7 tmp = np.sum(x*weight) + bias if tmp <= 0: return 0 else: return 1 #NAND로 or 회로 구성 def OR_NAND(x1, x2): s1 = NAND(x1, x1) s2 = NAND(x2, x2) y = NAND(s1, s2) return y print("NAND to OR") print(OR_NAND(0, 0)) print(OR_NAND(0, 1)) print(OR_NAND(1, 0)) print(OR_NAND(1, 1)) #nand로 and 회로 구성 def AND_NAND(x1, x2): s1 = NAND(x1, x2) y = NAND(s1, s1) return y print("NAND to AND") print(AND_NAND(0, 0)) print(AND_NAND(0, 1)) print(AND_NAND(1, 0)) print(AND_NAND(1, 1)) #nand로 not 회로 구성 def NOT_NAND(x): return NAND(x, x) print("NAND to NOT") print(NOT_NAND(0)) print(NOT_NAND(1))
# Pro/g/ramming challenges # 69: RPN Calculator # by ahmad89098 def operation(num1, num2): if operator == "+": answer = num1 + num2 elif operator == "-": answer = num1 - num2 elif operator == "*": answer = num1 * num2 elif operator == "/": answer = num1/num2 return answer i = 0 number1 = int(input()) # this was to setup an infinite loop so that the calculator runs forever until it is exited manually while i == 0: number2 = int(input()) operator = input() result = operation(number1, number2) print(result) number1 = result
def count_vals(val_string, count=1): if len(val_string) == 0: return [] elif len(val_string) == 1: return [(val_string, count)] else: if val_string[0] == val_string[1]: return count_vals(val_string[1:], count+1) else: inner = count_vals(val_string[1:]) if count == 0: count = count+1 inner.insert(0, (val_string[0], count)) return inner def create_string(val_count_pair): return str(val_count_pair[1]) + val_count_pair[0] def look_and_say_single(val): val_counts = count_vals(val) strs = list(map(create_string, val_counts)) return ''.join(strs) def look_and_say(data='1', maxlen=5): #TODO populate result list with the look and say numbers ''' data: starting number set maxlen: max sequence length ''' this_result = look_and_say_single(data) if maxlen < 1: return [] else: inner = look_and_say(this_result, maxlen - 1) inner.insert(0, this_result) return inner def main(): data = '1' maxlen = 10 # result = look_and_say_single(data) result = look_and_say(data, maxlen) # result = count_vals("1") print(result) main()
# -*- coding: utf-8 -*- ''' File name: code\polar_polygons\sol_465.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #465 :: Polar polygons # # For more information see: # https://projecteuler.net/problem=465 # Problem Statement ''' The kernel of a polygon is defined by the set of points from which the entire polygon's boundary is visible. We define a polar polygon as a polygon for which the origin is strictly contained inside its kernel. For this problem, a polygon can have collinear consecutive vertices. However, a polygon still cannot have self-intersection and cannot have zero area. For example, only the first of the following is a polar polygon (the kernels of the second, third, and fourth do not strictly contain the origin, and the fifth does not have a kernel at all): Notice that the first polygon has three consecutive collinear vertices. Let P(n) be the number of polar polygons such that the vertices (x, y) have integer coordinates whose absolute values are not greater than n. Note that polygons should be counted as different if they have different set of edges, even if they enclose the same area. For example, the polygon with vertices [(0,0),(0,3),(1,1),(3,0)] is distinct from the polygon with vertices [(0,0),(0,3),(1,1),(3,0),(1,0)]. For example, P(1) = 131, P(2) = 1648531, P(3) = 1099461296175 and P(343) mod 1 000 000 007 = 937293740. Find P(713) mod 1 000 000 007. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\exploring_pascals_pyramid\sol_154.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #154 :: Exploring Pascal's pyramid # # For more information see: # https://projecteuler.net/problem=154 # Problem Statement ''' A triangular pyramid is constructed using spherical balls so that each ball rests on exactly three balls of the next lower level. Then, we calculate the number of paths leading from the apex to each position: A path starts at the apex and progresses downwards to any of the three spheres directly below the current position. Consequently, the number of paths to reach a certain position is the sum of the numbers immediately above it (depending on the position, there are up to three numbers above it). The result is Pascal's pyramid and the numbers at each level n are the coefficients of the trinomial expansion (x + y + z)n. How many coefficients in the expansion of (x + y + z)200000 are multiples of 1012? ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\inscribed_circles_of_triangles_with_one_angle_of_60_degrees\sol_195.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #195 :: Inscribed circles of triangles with one angle of 60 degrees # # For more information see: # https://projecteuler.net/problem=195 # Problem Statement ''' Let's call an integer sided triangle with exactly one angle of 60 degrees a 60-degree triangle. Let r be the radius of the inscribed circle of such a 60-degree triangle. There are 1234 60-degree triangles for which r ≤ 100. Let T(n) be the number of 60-degree triangles for which r ≤ n, so T(100) = 1234,  T(1000) = 22767, and  T(10000) = 359912. Find T(1053779). ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\harshad_numbers\sol_387.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #387 :: Harshad Numbers # # For more information see: # https://projecteuler.net/problem=387 # Problem Statement ''' A Harshad or Niven number is a number that is divisible by the sum of its digits. 201 is a Harshad number because it is divisible by 3 (the sum of its digits.) When we truncate the last digit from 201, we get 20, which is a Harshad number. When we truncate the last digit from 20, we get 2, which is also a Harshad number. Let's call a Harshad number that, while recursively truncating the last digit, always results in a Harshad number a right truncatable Harshad number. Also: 201/3=67 which is prime. Let's call a Harshad number that, when divided by the sum of its digits, results in a prime a strong Harshad number. Now take the number 2011 which is prime. When we truncate the last digit from it we get 201, a strong Harshad number that is also right truncatable. Let's call such primes strong, right truncatable Harshad primes. You are given that the sum of the strong, right truncatable Harshad primes less than 10000 is 90619. Find the sum of the strong, right truncatable Harshad primes less than 1014. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\integers_with_decreasing_prime_powers\sol_578.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #578 :: Integers with decreasing prime powers # # For more information see: # https://projecteuler.net/problem=578 # Problem Statement ''' Any positive integer can be written as a product of prime powers: p1a1 × p2a2 × ... × pkak, where pi are distinct prime integers, ai > 0 and pi < pj if i < j. A decreasing prime power positive integer is one for which ai ≥ aj if i < j. For example, 1, 2, 15=3×5, 360=23×32×5 and 1000=23×53 are decreasing prime power integers. Let C(n) be the count of decreasing prime power positive integers not exceeding n. C(100) = 94 since all positive integers not exceeding 100 have decreasing prime powers except 18, 50, 54, 75, 90 and 98. You are given C(106) = 922052. Find C(1013). ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\four_representations_using_squares\sol_229.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #229 :: Four Representations using Squares # # For more information see: # https://projecteuler.net/problem=229 # Problem Statement ''' Consider the number 3600. It is very special, because 3600 = 482 +     362 3600 = 202 + 2×402 3600 = 302 + 3×302 3600 = 452 + 7×152 Similarly, we find that 88201 = 992 + 2802 = 2872 + 2×542 = 2832 + 3×522 = 1972 + 7×842. In 1747, Euler proved which numbers are representable as a sum of two squares. We are interested in the numbers n which admit representations of all of the following four types: n = a12 +   b12n = a22 + 2 b22n = a32 + 3 b32n = a72 + 7 b72, where the ak and bk are positive integers. There are 75373 such numbers that do not exceed 107. How many such numbers are there that do not exceed 2×109? ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\permuted_multiples\sol_52.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #52 :: Permuted multiples # # For more information see: # https://projecteuler.net/problem=52 # Problem Statement ''' It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\robot_walks\sol_208.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #208 :: Robot Walks # # For more information see: # https://projecteuler.net/problem=208 # Problem Statement ''' A robot moves in a series of one-fifth circular arcs (72°), with a free choice of a clockwise or an anticlockwise arc for each step, but no turning on the spot. One of 70932 possible closed paths of 25 arcs starting northward is Given that the robot starts facing North, how many journeys of 70 arcs in length can it take that return it, after the final arc, to its starting position? (Any arc may be traversed multiple times.) ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\incenter_and_circumcenter_of_triangle\sol_496.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #496 :: Incenter and circumcenter of triangle # # For more information see: # https://projecteuler.net/problem=496 # Problem Statement ''' Given an integer sided triangle ABC: Let I be the incenter of ABC. Let D be the intersection between the line AI and the circumcircle of ABC (A ≠ D). We define F(L) as the sum of BC for the triangles ABC that satisfy AC = DI and BC ≤ L. For example, F(15) = 45 because the triangles ABC with (BC,AC,AB) = (6,4,5), (12,8,10), (12,9,7), (15,9,16) satisfy the conditions. Find F(109). ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\1000digit_fibonacci_number\sol_25.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #25 :: 1000-digit Fibonacci number # # For more information see: # https://projecteuler.net/problem=25 # Problem Statement ''' 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? ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\the_prime_factorisation_of_binomial_coefficients\sol_231.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #231 :: The prime factorisation of binomial coefficients # # For more information see: # https://projecteuler.net/problem=231 # Problem Statement ''' The binomial coefficient 10C3 = 120. 120 = 23 × 3 × 5 = 2 × 2 × 2 × 3 × 5, and 2 + 2 + 2 + 3 + 5 = 14. So the sum of the terms in the prime factorisation of 10C3 is 14. Find the sum of the terms in the prime factorisation of 20000000C15000000. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\möbius_function_and_intervals\sol_464.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #464 :: Möbius function and intervals # # For more information see: # https://projecteuler.net/problem=464 # Problem Statement ''' The Möbius function, denoted μ(n), is defined as: μ(n) = (-1)ω(n) if n is squarefree (where ω(n) is the number of distinct prime factors of n) μ(n) = 0 if n is not squarefree. Let P(a,b) be the number of integers n in the interval [a,b] such that μ(n) = 1. Let N(a,b) be the number of integers n in the interval [a,b] such that μ(n) = -1. For example, P(2,10) = 2 and N(2,10) = 4. Let C(n) be the number of integer pairs (a,b) such that: 1 ≤ a ≤ b ≤ n, 99·N(a,b) ≤ 100·P(a,b), and 99·P(a,b) ≤ 100·N(a,b). For example, C(10) = 13, C(500) = 16676 and C(10 000) = 20155319. Find C(20 000 000). ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\ordered_fractions\sol_71.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #71 :: Ordered fractions # # For more information see: # https://projecteuler.net/problem=71 # Problem Statement ''' Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 It can be seen that 2/5 is the fraction immediately to the left of 3/7. By listing the set of reduced proper fractions for d ≤ 1,000,000 in ascending order of size, find the numerator of the fraction immediately to the left of 3/7. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\modular_cubes_part_2\sol_272.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #272 :: Modular Cubes, part 2 # # For more information see: # https://projecteuler.net/problem=272 # Problem Statement ''' For a positive number n, define C(n) as the number of the integers x, for which 1<x<n andx3≡1 mod n. When n=91, there are 8 possible values for x, namely : 9, 16, 22, 29, 53, 74, 79, 81. Thus, C(91)=8. Find the sum of the positive numbers n≤1011 for which C(n)=242. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\first_sort_i\sol_523.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #523 :: First Sort I # # For more information see: # https://projecteuler.net/problem=523 # Problem Statement ''' Consider the following algorithm for sorting a list: 1. Starting from the beginning of the list, check each pair of adjacent elements in turn. 2. If the elements are out of order: a. Move the smallest element of the pair at the beginning of the list. b. Restart the process from step 1. 3. If all pairs are in order, stop.For example, the list { 4 1 3 2 } is sorted as follows: 4 1 3 2 (4 and 1 are out of order so move 1 to the front of the list) 1 4 3 2 (4 and 3 are out of order so move 3 to the front of the list) 3 1 4 2 (3 and 1 are out of order so move 1 to the front of the list) 1 3 4 2 (4 and 2 are out of order so move 2 to the front of the list) 2 1 3 4 (2 and 1 are out of order so move 1 to the front of the list) 1 2 3 4 (The list is now sorted)Let F(L) be the number of times step 2a is executed to sort list L. For example, F({ 4 1 3 2 }) = 5. Let E(n) be the expected value of F(P) over all permutations P of the integers {1, 2, ..., n}. You are given E(4) = 3.25 and E(10) = 115.725. Find E(30). Give your answer rounded to two digits after the decimal point. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\maximum_path_sum_ii\sol_67.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #67 :: Maximum path sum II # # For more information see: # https://projecteuler.net/problem=67 # Problem Statement ''' By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 37 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom in triangle.txt (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred rows. NOTE: This is a much more difficult version of Problem 18. It is not possible to try every route to solve this problem, as there are 299 altogether! If you could check one trillion (1012) routes every second it would take over twenty billion years to check them all. There is an efficient algorithm to solve it. ;o) ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\clock_sequence\sol_506.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #506 :: Clock sequence # # For more information see: # https://projecteuler.net/problem=506 # Problem Statement ''' Consider the infinite repeating sequence of digits: 1234321234321234321... Amazingly, you can break this sequence of digits into a sequence of integers such that the sum of the digits in the n'th value is n. The sequence goes as follows: 1, 2, 3, 4, 32, 123, 43, 2123, 432, 1234, 32123, ... Let vn be the n'th value in this sequence. For example, v2 = 2, v5 = 32 and v11 = 32123. Let S(n) be v1 + v2 + ... + vn. For example, S(11) = 36120, and S(1000) mod 123454321 = 18232686. Find S(1014) mod 123454321. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\primitive_triangles\sol_276.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #276 :: Primitive Triangles # # For more information see: # https://projecteuler.net/problem=276 # Problem Statement ''' Consider the triangles with integer sides a, b and c with a ≤ b ≤ c. An integer sided triangle (a,b,c) is called primitive if gcd(a,b,c)=1. How many primitive integer sided triangles exist with a perimeter not exceeding 10 000 000? ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\angular_bisectors\sol_257.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #257 :: Angular Bisectors # # For more information see: # https://projecteuler.net/problem=257 # Problem Statement ''' Given is an integer sided triangle ABC with sides a ≤ b ≤ c. (AB = c, BC = a and AC = b). The angular bisectors of the triangle intersect the sides at points E, F and G (see picture below). The segments EF, EG and FG partition the triangle ABC into four smaller triangles: AEG, BFE, CGF and EFG. It can be proven that for each of these four triangles the ratio area(ABC)/area(subtriangle) is rational. However, there exist triangles for which some or all of these ratios are integral. How many triangles ABC with perimeter≤100,000,000 exist so that the ratio area(ABC)/area(AEG) is integral? ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\integer_angled_quadrilaterals\sol_177.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #177 :: Integer angled Quadrilaterals # # For more information see: # https://projecteuler.net/problem=177 # Problem Statement ''' Let ABCD be a convex quadrilateral, with diagonals AC and BD. At each vertex the diagonal makes an angle with each of the two sides, creating eight corner angles. For example, at vertex A, the two angles are CAD, CAB. We call such a quadrilateral for which all eight corner angles have integer values when measured in degrees an "integer angled quadrilateral". An example of an integer angled quadrilateral is a square, where all eight corner angles are 45°. Another example is given by DAC = 20°, BAC = 60°, ABD = 50°, CBD = 30°, BCA = 40°, DCA = 30°, CDB = 80°, ADB = 50°. What is the total number of non-similar integer angled quadrilaterals? Note: In your calculations you may assume that a calculated angle is integral if it is within a tolerance of 10-9 of an integer value. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\fibonacci_primitive_roots\sol_437.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #437 :: Fibonacci primitive roots # # For more information see: # https://projecteuler.net/problem=437 # Problem Statement ''' When we calculate 8n modulo 11 for n=0 to 9 we get: 1, 8, 9, 6, 4, 10, 3, 2, 5, 7. As we see all possible values from 1 to 10 occur. So 8 is a primitive root of 11. But there is more: If we take a closer look we see: 1+8=9 8+9=17≡6 mod 11 9+6=15≡4 mod 11 6+4=10 4+10=14≡3 mod 11 10+3=13≡2 mod 11 3+2=5 2+5=7 5+7=12≡1 mod 11. So the powers of 8 mod 11 are cyclic with period 10, and 8n + 8n+1 ≡ 8n+2 (mod 11). 8 is called a Fibonacci primitive root of 11. Not every prime has a Fibonacci primitive root. There are 323 primes less than 10000 with one or more Fibonacci primitive roots and the sum of these primes is 1480491. Find the sum of the primes less than 100,000,000 with at least one Fibonacci primitive root. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\prime_pair_sets\sol_60.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #60 :: Prime pair sets # # For more information see: # https://projecteuler.net/problem=60 # Problem Statement ''' The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property. Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\step_numbers\sol_178.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #178 :: Step Numbers # # For more information see: # https://projecteuler.net/problem=178 # Problem Statement ''' Consider the number 45656. It can be seen that each pair of consecutive digits of 45656 has a difference of one. A number for which every pair of consecutive digits has a difference of one is called a step number. A pandigital number contains every decimal digit from 0 to 9 at least once. How many pandigital step numbers less than 1040 are there? ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\gozinta_chains_ii\sol_606.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #606 :: Gozinta Chains II # # For more information see: # https://projecteuler.net/problem=606 # Problem Statement ''' A gozinta chain for n is a sequence {1,a,b,...,n} where each element properly divides the next. For example, there are eight distinct gozinta chains for 12: {1,12}, {1,2,12}, {1,2,4,12}, {1,2,6,12}, {1,3,12}, {1,3,6,12}, {1,4,12} and {1,6,12}. Let S(n) be the sum of all numbers, k, not exceeding n, which have 252 distinct gozinta chains. You are given S(106)=8462952 and S(1012)=623291998881978. Find S(1036), giving the last nine digits of your answer. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\optimum_polynomial\sol_101.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #101 :: Optimum polynomial # # For more information see: # https://projecteuler.net/problem=101 # Problem Statement ''' If we are presented with the first k terms of a sequence it is impossible to say with certainty the value of the next term, as there are infinitely many polynomial functions that can model the sequence. As an example, let us consider the sequence of cube numbers. This is defined by the generating function, un = n3: 1, 8, 27, 64, 125, 216, ... Suppose we were only given the first two terms of this sequence. Working on the principle that "simple is best" we should assume a linear relationship and predict the next term to be 15 (common difference 7). Even if we were presented with the first three terms, by the same principle of simplicity, a quadratic relationship should be assumed. We shall define OP(k, n) to be the nth term of the optimum polynomial generating function for the first k terms of a sequence. It should be clear that OP(k, n) will accurately generate the terms of the sequence for n ≤ k, and potentially the first incorrect term (FIT) will be OP(k, k+1); in which case we shall call it a bad OP (BOP). As a basis, if we were only given the first term of sequence, it would be most sensible to assume constancy; that is, for n ≥ 2, OP(1, n) = u1. Hence we obtain the following OPs for the cubic sequence: OP(1, n) = 1 1, 1, 1, 1, ... OP(2, n) = 7n−6 1, 8, 15, ... OP(3, n) = 6n2−11n+6      1, 8, 27, 58, ... OP(4, n) = n3 1, 8, 27, 64, 125, ... Clearly no BOPs exist for k ≥ 4. By considering the sum of FITs generated by the BOPs (indicated in red above), we obtain 1 + 15 + 58 = 74. Consider the following tenth degree polynomial generating function: un = 1 − n + n2 − n3 + n4 − n5 + n6 − n7 + n8 − n9 + n10 Find the sum of FITs for the BOPs. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\a_rectangular_tiling\sol_405.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #405 :: A rectangular tiling # # For more information see: # https://projecteuler.net/problem=405 # Problem Statement ''' We wish to tile a rectangle whose length is twice its width. Let T(0) be the tiling consisting of a single rectangle. For n > 0, let T(n) be obtained from T(n-1) by replacing all tiles in the following manner: The following animation demonstrates the tilings T(n) for n from 0 to 5: Let f(n) be the number of points where four tiles meet in T(n). For example, f(1) = 0, f(4) = 82 and f(109) mod 177 = 126897180. Find f(10k) for k = 1018, give your answer modulo 177. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\triangular_pentagonal_and_hexagonal\sol_45.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #45 :: Triangular, pentagonal, and hexagonal # # For more information see: # https://projecteuler.net/problem=45 # Problem Statement ''' Triangle, pentagonal, and hexagonal numbers are generated by the following formulae: Triangle   Tn=n(n+1)/2   1, 3, 6, 10, 15, ... Pentagonal   Pn=n(3n−1)/2   1, 5, 12, 22, 35, ... Hexagonal   Hn=n(2n−1)   1, 6, 15, 28, 45, ... It can be verified that T285 = P165 = H143 = 40755. Find the next triangle number that is also pentagonal and hexagonal. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\biclinic_integral_quadrilaterals\sol_311.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #311 :: Biclinic Integral Quadrilaterals # # For more information see: # https://projecteuler.net/problem=311 # Problem Statement ''' ABCD is a convex, integer sided quadrilateral with 1 ≤ AB < BC < CD < AD. BD has integer length. O is the midpoint of BD. AO has integer length. We'll call ABCD a biclinic integral quadrilateral if AO = CO ≤ BO = DO. For example, the following quadrilateral is a biclinic integral quadrilateral: AB = 19, BC = 29, CD = 37, AD = 43, BD = 48 and AO = CO = 23. Let B(N) be the number of distinct biclinic integral quadrilaterals ABCD that satisfy AB2+BC2+CD2+AD2 ≤ N. We can verify that B(10 000) = 49 and B(1 000 000) = 38239. Find B(10 000 000 000). ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\gozinta_chains\sol_548.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #548 :: Gozinta Chains # # For more information see: # https://projecteuler.net/problem=548 # Problem Statement ''' A gozinta chain for n is a sequence {1,a,b,...,n} where each element properly divides the next. There are eight gozinta chains for 12: {1,12} ,{1,2,12}, {1,2,4,12}, {1,2,6,12}, {1,3,12}, {1,3,6,12}, {1,4,12} and {1,6,12}. Let g(n) be the number of gozinta chains for n, so g(12)=8. g(48)=48 and g(120)=132. Find the sum of the numbers n not exceeding 1016 for which g(n)=n. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\counting_rectangles\sol_85.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #85 :: Counting rectangles # # For more information see: # https://projecteuler.net/problem=85 # Problem Statement ''' By counting carefully it can be seen that a rectangular grid measuring 3 by 2 contains eighteen rectangles: Although there exists no rectangular grid that contains exactly two million rectangles, find the area of the grid with the nearest solution. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\nim_square\sol_310.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #310 :: Nim Square # # For more information see: # https://projecteuler.net/problem=310 # Problem Statement ''' Alice and Bob play the game Nim Square. Nim Square is just like ordinary three-heap normal play Nim, but the players may only remove a square number of stones from a heap. The number of stones in the three heaps is represented by the ordered triple (a,b,c). If 0≤a≤b≤c≤29 then the number of losing positions for the next player is 1160. Find the number of losing positions for the next player if 0≤a≤b≤c≤100 000. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\mirror_power_sequence\sol_617.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #617 :: Mirror Power Sequence # # For more information see: # https://projecteuler.net/problem=617 # Problem Statement ''' For two integers $n,e > 1$, we define a $(n,e)$-MPS (Mirror Power Sequence) to be an infinite sequence of integers $(a_i)_{i\ge 0}$ such that for all $i\ge 0$, $a_{i+1} = min(a_i^e,n-a_i^e)$ and $a_i > 1$. Examples of such sequences are the two $(18,2)$-MPS sequences made of alternating $2$ and $4$. Note that even though such a sequence is uniquely determined by $n,e$ and $a_0$, for most values such a sequence does not exist. For example, no $(n,e)$-MPS exists for $n < 6$. Define $C(n)$ to be the number of $(n,e)$-MPS for some $e$, and $\displaystyle D(N) = \sum_{n=2}^N {C(n)}$. You are given that $D(10) = 2$, $D(100) = 21$, $D(1000) = 69$, $D(10^6) = 1303$ and $D(10^{12}) = 1014800$. Find $D(10^{18})$. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\unfair_race\sol_573.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #573 :: Unfair race # # For more information see: # https://projecteuler.net/problem=573 # Problem Statement ''' $n$ runners in very different training states want to compete in a race. Each one of them is given a different starting number $k$ $(1\leq k \leq n)$ according to his (constant) individual racing speed being $v_k=\frac{k}{n}$. In order to give the slower runners a chance to win the race, $n$ different starting positions are chosen randomly (with uniform distribution) and independently from each other within the racing track of length $1$. After this, the starting position nearest to the goal is assigned to runner $1$, the next nearest starting position to runner $2$ and so on, until finally the starting position furthest away from the goal is assigned to runner $n$. The winner of the race is the runner who reaches the goal first. Interestingly, the expected running time for the winner is $\frac{1}{2}$, independently of the number of runners. Moreover, while it can be shown that all runners will have the same expected running time of $\frac{n}{n+1}$, the race is still unfair, since the winning chances may differ significantly for different starting numbers: Let $P_{n,k}$ be the probability for runner $k$ to win a race with $n$ runners and $E_n = \sum_{k=1}^n k P_{n,k}$ be the expected starting number of the winner in that race. It can be shown that, for example, $P_{3,1}=\frac{4}{9}$, $P_{3,2}=\frac{2}{9}$, $P_{3,3}=\frac{1}{3}$ and $E_3=\frac{17}{9}$ for a race with $3$ runners. You are given that $E_4=2.21875$, $E_5=2.5104$ and $E_{10}=3.66021568$. Find $E_{1000000}$ rounded to 4 digits after the decimal point. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\pivotal_square_sums\sol_261.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #261 :: Pivotal Square Sums # # For more information see: # https://projecteuler.net/problem=261 # Problem Statement ''' Let us call a positive integer k a square-pivot, if there is a pair of integers m > 0 and n ≥ k, such that the sum of the (m+1) consecutive squares up to k equals the sum of the m consecutive squares from (n+1) on: (k-m)2 + ... + k2 = (n+1)2 + ... + (n+m)2. Some small square-pivots are 4: 32 + 42 = 52 21: 202 + 212 = 292 24: 212 + 222 + 232 + 242 = 252 + 262 + 272 110: 1082 + 1092 + 1102 = 1332 + 1342Find the sum of all distinct square-pivots ≤ 1010. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\stone_game_ii\sol_325.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #325 :: Stone Game II # # For more information see: # https://projecteuler.net/problem=325 # Problem Statement ''' A game is played with two piles of stones and two players. At her turn, a player removes a number of stones from the larger pile. The number of stones she removes must be a positive multiple of the number of stones in the smaller pile. E.g., let the ordered pair(6,14) describe a configuration with 6 stones in the smaller pile and 14 stones in the larger pile, then the first player can remove 6 or 12 stones from the larger pile. The player taking all the stones from a pile wins the game. A winning configuration is one where the first player can force a win. For example, (1,5), (2,6) and (3,12) are winning configurations because the first player can immediately remove all stones in the second pile. A losing configuration is one where the second player can force a win, no matter what the first player does. For example, (2,3) and (3,4) are losing configurations: any legal move leaves a winning configuration for the second player. Define S(N) as the sum of (xi+yi) for all losing configurations (xi,yi), 0 < xi < yi ≤ N. We can verify that S(10) = 211 and S(104) = 230312207313. Find S(1016) mod 710. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\counting_binary_matrices\sol_626.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #626 :: Counting Binary Matrices # # For more information see: # https://projecteuler.net/problem=626 # Problem Statement ''' A binary matrix is a matrix consisting entirely of 0s and 1s. Consider the following transformations that can be performed on a binary matrix: Swap any two rows Swap any two columns Flip all elements in a single row (1s become 0s, 0s become 1s) Flip all elements in a single column Two binary matrices $A$ and $B$ will be considered equivalent if there is a sequence of such transformations that when applied to $A$ yields $B$. For example, the following two matrices are equivalent: $A=\begin{pmatrix} 1 & 0 & 1 \\ 0 & 0 & 1 \\ 0 & 0 & 0 \\ \end{pmatrix} \quad B=\begin{pmatrix} 0 & 0 & 0 \\ 1 & 0 & 0 \\ 0 & 0 & 1 \\ \end{pmatrix}$ via the sequence of two transformations "Flip all elements in column 3" followed by "Swap rows 1 and 2". Define $c(n)$ to be the maximum number of $n\times n$ binary matrices that can be found such that no two are equivalent. For example, $c(3)=3$. You are also given that $c(5)=39$ and $c(8)=656108$. Find $c(20)$, and give your answer modulo $1\,001\,001\,011$. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\rational_zeros_of_a_function_of_three_variables\sol_180.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #180 :: Rational zeros of a function of three variables # # For more information see: # https://projecteuler.net/problem=180 # Problem Statement ''' For any integer n, consider the three functions f1,n(x,y,z) = xn+1 + yn+1 − zn+1f2,n(x,y,z) = (xy + yz + zx)*(xn-1 + yn-1 − zn-1)f3,n(x,y,z) = xyz*(xn-2 + yn-2 − zn-2) and their combination fn(x,y,z) = f1,n(x,y,z) + f2,n(x,y,z) − f3,n(x,y,z) We call (x,y,z) a golden triple of order k if x, y, and z are all rational numbers of the form a / b with 0 < a < b ≤ k and there is (at least) one integer n, so that fn(x,y,z) = 0. Let s(x,y,z) = x + y + z. Let t = u / v be the sum of all distinct s(x,y,z) for all golden triples (x,y,z) of order 35. All the s(x,y,z) and t must be in reduced form. Find u + v. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\steps_in_euclids_algorithm\sol_433.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #433 :: Steps in Euclid's algorithm # # For more information see: # https://projecteuler.net/problem=433 # Problem Statement ''' Let E(x0, y0) be the number of steps it takes to determine the greatest common divisor of x0 and y0 with Euclid's algorithm. More formally:x1 = y0, y1 = x0 mod y0xn = yn-1, yn = xn-1 mod yn-1 E(x0, y0) is the smallest n such that yn = 0. We have E(1,1) = 1, E(10,6) = 3 and E(6,10) = 4. Define S(N) as the sum of E(x,y) for 1 ≤ x,y ≤ N. We have S(1) = 1, S(10) = 221 and S(100) = 39826. Find S(5·106). ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\a_weird_recurrence_relation\sol_463.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #463 :: A weird recurrence relation # # For more information see: # https://projecteuler.net/problem=463 # Problem Statement ''' The function $f$ is defined for all positive integers as follows: $f(1)=1$ $f(3)=3$ $f(2n)=f(n)$ $f(4n + 1)=2f(2n + 1) - f(n)$ $f(4n + 3)=3f(2n + 1) - 2f(n)$ The function $S(n)$ is defined as $\sum_{i=1}^{n}f(i)$. $S(8)=22$ and $S(100)=3604$. Find $S(3^{37})$. Give the last 9 digits of your answer. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\goldbachs_other_conjecture\sol_46.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #46 :: Goldbach's other conjecture # # For more information see: # https://projecteuler.net/problem=46 # Problem Statement ''' It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2×12 15 = 7 + 2×22 21 = 3 + 2×32 25 = 7 + 2×32 27 = 19 + 2×22 33 = 31 + 2×12 It turns out that the conjecture was false. What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\sum_of_a_square_and_a_cube\sol_348.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #348 :: Sum of a square and a cube # # For more information see: # https://projecteuler.net/problem=348 # Problem Statement ''' Many numbers can be expressed as the sum of a square and a cube. Some of them in more than one way. Consider the palindromic numbers that can be expressed as the sum of a square and a cube, both greater than 1, in exactly 4 different ways. For example, 5229225 is a palindromic number and it can be expressed in exactly 4 different ways: 22852 + 203 22232 + 663 18102 + 1253 11972 + 1563 Find the sum of the five smallest such palindromic numbers. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\pandigital_multiples\sol_38.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #38 :: Pandigital multiples # # For more information see: # https://projecteuler.net/problem=38 # Problem Statement ''' Take the number 192 and multiply it by each of 1, 2, and 3: 192 × 1 = 192 192 × 2 = 384 192 × 3 = 576 By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5). What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1? ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\triangle_on_parabola\sol_397.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #397 :: Triangle on parabola # # For more information see: # https://projecteuler.net/problem=397 # Problem Statement ''' On the parabola y = x2/k, three points A(a, a2/k), B(b, b2/k) and C(c, c2/k) are chosen. Let F(K, X) be the number of the integer quadruplets (k, a, b, c) such that at least one angle of the triangle ABC is 45-degree, with 1 ≤ k ≤ K and -X ≤ a < b < c ≤ X. For example, F(1, 10) = 41 and F(10, 100) = 12492. Find F(106, 109). ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\number_sequence_game\sol_477.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #477 :: Number Sequence Game # # For more information see: # https://projecteuler.net/problem=477 # Problem Statement ''' The number sequence game starts with a sequence S of N numbers written on a line. Two players alternate turns. At his turn, a player must select and remove either the first or the last number remaining in the sequence. The player score is the sum of all the numbers he has taken. Each player attempts to maximize his own sum. If N = 4 and S = {1, 2, 10, 3}, then each player maximizes his score as follows: Player 1: removes the first number (1) Player 2: removes the last number from the remaining sequence (3) Player 1: removes the last number from the remaining sequence (10) Player 2: removes the remaining number (2) Player 1 score is 1 + 10 = 11. Let F(N) be the score of player 1 if both players follow the optimal strategy for the sequence S = {s1, s2, ..., sN} defined as: s1 = 0 si+1 = (si2 + 45) modulo 1 000 000 007 The sequence begins with S = {0, 45, 2070, 4284945, 753524550, 478107844, 894218625, ...}. You are given F(2) = 45, F(4) = 4284990, F(100) = 26365463243, F(104) = 2495838522951. Find F(108). ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\π_sequences\sol_609.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #609 :: π sequences # # For more information see: # https://projecteuler.net/problem=609 # Problem Statement ''' For every $n \ge 1$ the prime-counting function $\pi(n)$ is equal to the number of primes not exceeding $n$. E.g. $\pi(6)=3$ and $\pi(100)=25$. We say that a sequence of integers $u = (u_0,\cdots,u_m)$ is a $\pi$ sequence if $u_n \ge 1$ for every $n$ $u_{n+1}= \pi(u_n)$ $u$ has two or more elements For $u_0=10$ there are three distinct $\pi$ sequences: (10,4), (10,4,2) and (10,4,2,1). Let $c(u)$ be the number of elements of $u$ that are not prime. Let $p(n,k)$ be the number of $\pi$ sequences $u$ for which $u_0\le n$ and $c(u)=k$. Let $P(n)$ be the product of all $p(n,k)$ that are larger than 0. You are given: P(10)=3×8×9×3=648 and P(100)=31038676032. Find $P(10^8)$. Give your answer modulo 1000000007. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\diophantine_reciprocals_i\sol_108.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #108 :: Diophantine reciprocals I # # For more information see: # https://projecteuler.net/problem=108 # Problem Statement ''' In the following equation x, y, and n are positive integers. 1x + 1y = 1n For n = 4 there are exactly three distinct solutions: 15 + 120 = 14 16 + 112 = 14 18 + 18 = 14 What is the least value of n for which the number of distinct solutions exceeds one-thousand? NOTE: This problem is an easier version of Problem 110; it is strongly advised that you solve this one first. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\divisibility_comparison_between_factorials\sol_383.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #383 :: Divisibility comparison between factorials # # For more information see: # https://projecteuler.net/problem=383 # Problem Statement ''' Let f5(n) be the largest integer x for which 5x divides n. For example, f5(625000) = 7. Let T5(n) be the number of integers i which satisfy f5((2·i-1)!) < 2·f5(i!) and 1 ≤ i ≤ n. It can be verified that T5(103) = 68 and T5(109) = 2408210. Find T5(1018). ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\migrating_ants\sol_393.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #393 :: Migrating ants # # For more information see: # https://projecteuler.net/problem=393 # Problem Statement ''' An n×n grid of squares contains n2 ants, one ant per square. All ants decide to move simultaneously to an adjacent square (usually 4 possibilities, except for ants on the edge of the grid or at the corners). We define f(n) to be the number of ways this can happen without any ants ending on the same square and without any two ants crossing the same edge between two squares. You are given that f(4) = 88. Find f(10). ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- ''' File name: code\squarefree_fibonacci_numbers\sol_399.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #399 :: Squarefree Fibonacci Numbers # # For more information see: # https://projecteuler.net/problem=399 # Problem Statement ''' The first 15 fibonacci numbers are: 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610. It can be seen that 8 and 144 are not squarefree: 8 is divisible by 4 and 144 is divisible by 4 and by 9. So the first 13 squarefree fibonacci numbers are: 1,1,2,3,5,13,21,34,55,89,233,377 and 610. The 200th squarefree fibonacci number is: 971183874599339129547649988289594072811608739584170445. The last sixteen digits of this number are: 1608739584170445 and in scientific notation this number can be written as 9.7e53. Find the 100 000 000th squarefree fibonacci number. Give as your answer its last sixteen digits followed by a comma followed by the number in scientific notation (rounded to one digit after the decimal point). For the 200th squarefree number the answer would have been: 1608739584170445,9.7e53 Note: For this problem, assume that for every prime p, the first fibonacci number divisible by p is not divisible by p2 (this is part of Wall's conjecture). This has been verified for primes ≤ 3·1015, but has not been proven in general. If it happens that the conjecture is false, then the accepted answer to this problem isn't guaranteed to be the 100 000 000th squarefree fibonacci number, rather it represents only a lower bound for that number. ''' # Solution # Solution Approach ''' '''
# -*- coding: utf-8 -*- """ Created on Sun Aug 30 00:20:04 2020 @author: frmendes If n=1, the sequence is composed of a single integer: 1 If n is even, the sequence is composed of n followed by sequence h(n/2) If n is odd, the sequence is composed of n followed by sequence h(3⋅n+1) global sum """ import sys n = [] text = [] for linenum,i in enumerate(sys.stdin): text.append(i) x = int(text[0].split(' ')[0]) def hailstone(s,n): if n==1: s = s+1 return(s) elif n%2==0: s = n + hailstone(s,n/2) return(s) elif n%2 !=0: s = n + hailstone(s,3*n + 1) return(s) print(int(hailstone(0,x)))
###### Function : get_gravitational_force ###### Paremters: 3 floating point numbers, 2 corresponding to two different masses, 1 corresponding to the distance between them ###### Preconditions: all three parameters must be in manipulatable floating point form ###### Postconditions: None. def get_gravitational_force(mass1, mass2, dist): numerator = (.000000006673)*(mass1)*(mass2); denominator = dist; force = numerator/denominator; return force; ###### Function: main ###### Description: Prompts user for two masses and a distance, converts them to floating point (if possible. if not, repeats main) and prints out the resulting function call to get_gravitational_force. Then, asks the user if they want to repeat the program. def main(): try: mass1 = float(input("Please enter mass 1.")); except: print("Error: Try again."); main(); try: mass2 = float(input("Please enter mass 2.")); except: print("Error: try again"); main(); try: distance = float(input("Please enter the distance.")); except: print("Error, try again"); main(); print("The gravitational force is ", get_gravitational_force(mass1, mass2, distance)); try: repeat = int(input("Would you like to do it again? 1 for yes and 0 for no.")); except: exit(1); if (repeat == 1): main(); elif (repeat == 0): exit(1); main();
# ENME 489Y: Remote Sensing # Grayscale algorithm & comparison with OpenCV # Import packages import numpy as np import cv2 import imutils print "All packages imported properly!" # Load & show original image image = cv2.imread("testudo.jpg") true = image.copy() cv2.imshow("Original Image", image) print "height: %d" % (image.shape[0]) print "width: %d" % (image.shape[1]) x_lim = image.shape[0] y_lim = image.shape[1] for x in range (0,x_lim - 1): for y in range (0,y_lim - 1): (b, g, r) = image[x, y] # image[x, y] = (0.33 * b + 0.33 * g + 0.33 * r) image[x, y] = (0.11 * b + 0.59 * g + 0.3 * r) cv2.imshow("Grayscale Image: Algorithm", image) # Grayscale image using cv2.COLOR_BGR2GRAY image = cv2.cvtColor(true, cv2.COLOR_BGR2GRAY) cv2.imshow("Grayscale: OpenCV", image) cv2.waitKey(0)
# ENME489Y: Remote Sensing # import the necessary packages import numpy as np import time import cv2 import imutils import os # allow the camera to setup time.sleep(1) # Enter the initial IMU angle from user d = raw_input("Please enter IMU angle: ") print "Confirming the IMU angle you entered is: " print d # The following line should be used if interestsed in # the -ss ("shutter speed") command for long exposure #command = 'raspistill -w 1280 -h 720 -ss 1000000 -o blank.jpg' command = 'raspistill -w 1280 -h 720 -o blank.jpg' os.system(command) image = cv2.imread('blank.jpg') image = cv2.flip(image,-1) # plot crosshairs for alignment cv2.line(image, (640,0), (640,720), (0,150,150), 1) cv2.line(image, (600,360), (1280,360), (0,150,150), 1) # display IMU angle, for reference font = cv2.FONT_HERSHEY_COMPLEX_SMALL red = (0, 0, 255) cv2.putText(image, d, (800, 200), font, 10, red, 10) # write image to file d = int(d) filename = "%d.jpg" %d cv2.imwrite(filename, image) command = 'mv ' + filename + ' /home/pi/alignment_images/' os.system(command) print "All done!"
import time def countdown(seconds): i = 0 while i < seconds: print seconds seconds -=1 time.sleep(1) print "End countdown" countdown(int(raw_input("Please enter the number of seconds")))
import sys def check_row(row,value): if value in board[row]: return False return True def check_column(column,value): for i in range(9): if value == board[i][column] : return False return True def check_box(row,column,value): idx = [row // 3 * 3, column // 3 * 3] for i in range(3): for j in range(3): if value == board[idx[0] + i][idx[1] + j]: return False return True def dfs(x): if x == len(zero): for i in range(9): for j in range(9): print(board[i][j],end=' ') print() sys.exit(0) else: for j in range(1,10): if check_row(zero[x][0],j) and check_column(zero[x][1],j) and check_box(zero[x][0],zero[x][1],j): board[zero[x][0]][zero[x][1]] = j dfs(x+1) board[zero[x][0]][zero[x][1]] = 0 board = [list(map(int, sys.stdin.readline().split())) for _ in range(9)] zero = [(i, j) for i in range(9) for j in range(9) if board[i][j] == 0] dfs(0)
import fractions n = int(input()) t = list(map(int,input().split())) first,t = t[0],t[1:] for i in t: tmp = fractions.Fraction(i,first) print(str(tmp.denominator)+'/'+str(tmp.numerator))
def check_sosu(end): for i in range(2, end+1): if is_sosu[i]: try: for j in range(2, end+1): is_sosu[i*j] = False except: continue start, end = map(int, input().split()) is_sosu = [True for _ in range(end+1)] is_sosu[0], is_sosu[1] = False, False check_sosu(end) for i in range(start, end+1): if is_sosu[i]: print(i)
menu = [int(input()) for i in range(5)] print(min(menu[:3])+min(menu[3:])-50)
import requests from typing import List from lib.types import Stop from lib.utils import validate_number_choice def fetch_stops(route_id: str, direction_index: int) -> List[Stop]: """ Fetches a list of stops for a given route and direction from the MBTA API. """ try: response = requests.get( "https://api-v3.mbta.com/stops?filter%5Bdirection_id%5D={direction_id}&filter%5Broute%5D={route_id}".format( direction_id=direction_index, route_id=route_id ) ) stops = response.json()["data"] except Exception: return None formatted_stops = [ {"id": stop["id"], "name": stop["attributes"]["name"]} for stop in stops ] return formatted_stops def print_stops_list(stops: List[Stop]): """ Prints out a list of stops. """ for stop_index, stop in enumerate(stops): print("{}) {}".format(stop_index + 1, stop["name"])) def get_stop_choice(stops: List[Stop]) -> Stop: """ Prompts user to select a stop from a list of Stops. """ maximum_choice = len(stops) stop_choice = input("Enter a number between 1 and {}: ".format(maximum_choice)) stop_choice_number = validate_number_choice(maximum_choice, stop_choice) if stop_choice_number is None: return get_stop_choice(stops) return stops[stop_choice_number - 1]
import numpy as np # as se hum kisi bhi moduleko chota ker ke use ka name change ker sakete he a=np.array([1,2,3,4,5,6,7,8,9,0]) b=np.array([1,2,3,4,5,6,7,8,9,0]) print(a) print(b) print(a+b) print(a+2) print(a*2) print(a**2) print(a/2)
#Question 1 #Create an Array in python using the list and perform delete from any position operation l=list(map(int,input().split())) k=int(input("enter the position to be deleted")) l.pop(k-1) print("Numbers of list after removal ") print(*l)
primes = [2, 3, 5, 7] planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'] hands = [ ['J', 'Q', 'K'], ['2', '2', '2'], ['6', 'A', 'K'], # (Comma after the last element is optional) ] hands = [['J', 'Q', 'K'], ['2', '2', '2'], ['6', 'A', 'K']] # A list can contain a mix of different types of variables my_favourite_things = [32, 'raindrops on roses', help] # Elements at the end of the list can be accessed with negative numbers, starting from -1: print(planets[-1]) print(planets[-2]) print(planets[0:3])
class Node: def __init__(self , data): self.data = data self.next = None self.prev = None class doubly_linkedlist: def __init__(self): self.head = None def append(self,data): if self.head == None: # no element is there new_node = Node(data) new_node.prev = None self.head = new_node else: new_node = Node(data) cur = self.head while cur.next != None: cur = cur.next cur.next = new_node new_node.prev = cur new_node.next = None def prepend(self,data): if self.head == None: new_node = Node(data) new_node.prev = None self.head = new_node else: new_node = Node(data) self.head.prev = new_node new_node.next = self.head self.head = new_node new_node.prev = None def add_after_node(self,key , data): cur = self.head while cur != None: if cur.next == None and cur.data == key: #last ele self.append(data) return elif cur.data == key: new_node = Node(data) nxt = cur.next cur.next = new_node new_node.next = nxt new_node.prev = cur nxt.prev = new_node cur = cur.next # to increase value of cur in while loop def add_before_node(self,key,data): cur = self.head while cur!= None: if cur.prev == None and cur.data == key: self.prepend(data) return elif cur.data == key: new_node = Node(data) prev = cur.prev prev.next = new_node cur.prev = new_node new_node.next = cur new_node.prev = prev cur = cur.next def delete_node(self,key): cur = self.head while cur!=None: if cur.data == key and cur == self.head: #case 1 when only head is there if cur.next != None: cur = None self.head = None return #case 2 when you want to remove head but there are other ele also else: nxt = cur.next cur.next = None nxt.prev = None cur = None self.head = nxt return #case 3 delete node at specific pos elif cur.data == key: if cur.next !=None: nxt = cur.next prev = cur.prev prev.next = nxt nxt.prev = prev cur.next = None cur.prev = None cur = None return #case 4 deleting last node else: prev = cur.prev prev.next = None cur.prev = None cur = None return cur = cur.next def print_list(self): if self.head == None: print("List is Empty") else: cur = self.head c = 0 while cur != None: c += 1 print(cur.data ) cur = cur.next obj = doubly_linkedlist() obj.print_list() #list is empty print() obj.append(1) #adding ele after list obj.append(2) obj.append(3) obj.append(4) obj.print_list() #prints the list print() obj.prepend(0) # adding ele b4 list obj.print_list() #print list with prepend print() obj.add_after_node(1 , 11) obj.print_list() print() obj.add_before_node(4 , 33) obj.print_list() print() obj.delete_node(1) #delete first node obj.delete_node(3) obj.print_list() print()
from functools import partial from typing import Callable, List, Type, Union, Iterable from ....excepts import LookupyError def iff(precond: Callable, val: Union[int, str], f: Callable) -> bool: """If and only if the precond is True Shortcut function for precond(val) and f(val). It is mainly used to create partial functions for commonly required preconditions :param precond : (function) represents the precondition :param val: (mixed) value to which the functions are applied :param f: (function) the actual function :return: whether or not the cond is satisfied """ return False if not precond(val) else f(val) iff_not_none = partial(iff, lambda x: x is not None) def guard_type(classinfo: Union[Type[str], Type[Iterable]], val: Union[str, List[int]]) -> Union[str, List[int]]: if not isinstance(val, classinfo): raise LookupyError(f'Value not a {classinfo}') return val guard_str = partial(guard_type, str) guard_iter = partial(guard_type, Iterable) guard_int = partial(guard_type, int)
# def solution(arr, divisor): # answer = [] # for i in arr: # if i % divisor == 0: # answer.append(i) # answer.sort() # if len(answer) == 0: # answer = [-1] # # return answer #list comprehension def solution(arr, divisor): array = [x for x in arr if x % divisor == 0] array.sort() return array if len(array) else [-1]
#Making a digital clock with Python import time import tkinter as tk from tkinter import * def tick(time1=''): #Get the current local time from the PC time2 = time.strftime('%I:%M:%S') #if the time string has changes, update it if time2 != time1: time1 = time2 clock_frame.config(text=time2) #calls itself every 200 milliseconds to update clock_frame.after(200, tick) root = tk.Tk() root.title('Robin digital clock') clock_frame = tk.Label(root, font=('comic sans ms', 80 ,'bold'), bg='silver', fg='gold') clock_frame.pack(fill='both', expand=1) root.geometry('700x500') tick() root.mainloop()
# variables var1 = 10 # int var2 = 4.5 # float var3 = "bonjour" # string var4 = True # boolean var5 = ["bonjour", 5 , 3.5] # list print("total est egal a :") total = var1 + var2 print(total) # conditions if var1 > var2: print("c'est plus grand") elif var1 < var2: print("c'est plus petit") else: print("c'est egal") # boucles while var1 > var2: print(var1) var1 = var1 - 1 for element in var5: print(element) print("-------------------") # fonctions def add(a, b,): resultat = a + b return resultat def soust(a, b): return a-b # fonction div, multip, soust total = soust(var2, var1) print(total)
import unittest '''The merge sort starts by slicing the array into smaller pieces by half till the array has onle 1 element then we start sorting and merging from there in the helper method, I need to make sure that I am accounting for the cases where the left is done before the right and continoue the missing one''' def mergeSort(array): #before that I need to check for the length of one or empty, this will also break the recursion if len(array) <= 1: return array #I need a middle index here then divide the array by that middleIdx = int(len(array) / 2) #rounding down becuase we need an integer as an index value not a float, we can round up by adding 1 to len(array) then dividing by 2, Do not add 1 after division rightSide = array[: middleIdx] leftSide = array[middleIdx :] rightSideDivision = mergeSort(rightSide) #keeps on dividing the array to smaller ones leftSideDivision = mergeSort(leftSide) #keeps on dividing the array to smaller ones return mergeHelper(rightSideDivision, leftSideDivision) #calling for a helper method to help merge sort def mergeHelper(rightSide, leftSide): """This helper will sort the array for us""" fullySortedArray = [0] * (len(rightSide)+ len(leftSide)) #creating zero array i,j,k = 0,0,0 #starting with zero because the first element of any array in python is zero, this should be incremented according to logic implementation below #logic starts here, i and j should not exceed the len of arrays, the smaller comes first and start incrementing while i < len(rightSide) and j < len(leftSide): #first logic check, keeps on checking till one of the indecies is over if rightSide[i] < leftSide[j]: fullySortedArray[k] = rightSide[i] i+=1 else: fullySortedArray[k] = leftSide[j] j+=1 k +=1 #this while loop ends here and others will start after #second logic check, takes care of what was missing, above we needed both i and j to be less than length of thier arrays, so if one of them was not true, the while loop will break or stop working #below, we continoue to solve for that while i < len(rightSide): fullySortedArray[k] = rightSide[i] i+=1 k+=1 while j < len(leftSide): fullySortedArray[k] = leftSide[j] j+=1 k+=1 #when all are done, now our array is sorted and we can return it return fullySortedArray """Feel free to add more test cases below, I added 5, to have the best outcome, make sure to have uniquly named methods so change the methods names while coping and pasting""" class TestProgram(unittest.TestCase): def test_1(self): self.assertEqual(mergeSort([8, 5, 2, 9, 5, 6, 3]), [2, 3, 5, 5, 6, 8, 9]) def test_2(self): self.assertEqual(mergeSort([1,2,10,56,20,15,36]), [1,2,10,15,20,36,56]) def test_3(self): self.assertEqual(mergeSort([5, 10, -5, -10, 100, -100, 20, -200]), [-200, -100, -10, -5, 5, 10, 20, 100]) def test_4(self): self.assertEqual(mergeSort([]), []) def test_5(self): self.assertEqual(mergeSort([1]), [1]) #DO NOT CHANGE THAT, if __name__ == '__main__': unittest.main()
temp = list(range(1,6)) N = len(temp) for i in range(N): for j in range(N - 1): print(temp) a = temp[j] b = temp[j + 1] temp[j] = b temp[j + 1] = a
from itertools import permutations def solution(card, n): answer = -1 idx = 0 ans = [] n = tuple(map(int, str(n))) for i in permutations(card): print(i) ans.append(i) ans = sorted(set(ans)) for i in ans: if n == i: return idx + 1 idx += 1 return -1 card1 = [1, 2, 1, 3] n1 = 1312 ret1 = solution(card1, n1) print("solution 함수의 반환 값은", ret1, "입니다.") card2 = [1, 1, 1, 2] n2 = 1122 ret2 = solution(card2, n2) print("solution 함수의 반환 값은", ret2, "입니다.")
# 2947 def printList(L): for i in range(len(L)): print(L[i], end=" ") print() inputList = list(map(int, input().split())) sortedList = sorted(inputList) while inputList != sortedList: for i in range(len(inputList) - 1): if inputList[i] > inputList[i + 1]: temp = inputList[i + 1] inputList[i + 1] = inputList[i] inputList[i] = temp printList(inputList)
from collections import Counter sentence = input("Enter the string: ") res = Counter(sentence) max_key = max(res, key = res.get) print(max_key, res[max_key])
def construct_trie(): root = dict() with open("scrabble-dictionary.txt", "r") as f: words = f.read().splitlines() for word in words: current_dict = root for letter in word: current_dict = current_dict.setdefault(letter.lower(), {}) current_dict["end"] = word.lower() return root print("NYT Spelling Bee Solver (11/21/2020) -- Rob Walker") print("Please wait. Initializing dictionary...", end='', flush=True) trie = construct_trie() print(" done!") mandatory_letter = input("Mandatory letter: ").lower() print("You entered the mandatory letter: " + mandatory_letter.lower()) print("Please enter the other letters.") letters = [] i = 1 while i < 7: x = input("Letter " + str(i) + ": ") if x in letters: print("You've already entered this letter!") elif not x.isalpha(): print("Please enter a letter.") else: letters.append(x.lower()) i += 1 print("You entered the non-mandatory letters: " + ", ".join(letters)) print("Finding words... ", end='', flush=True) letters.append(mandatory_letter) letters = sorted(letters) found_words = [] def find_words(current_dict): if "end" in current_dict.keys() and mandatory_letter in current_dict["end"]: found_words.append(current_dict["end"]) for letter in letters: if letter in current_dict.keys(): find_words(current_dict[letter]) find_words(trie) print("done!") print("Found the following words:") for word in found_words: print(word)