text
stringlengths
37
1.41M
""" # Definition for a Node. class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.right = right self.next = next """ class Solution: def connect(self, root: 'Node') -> 'Node': q = deque() if root: q.append(root) while q: l = len(q) for i in range(l): n = q.popleft() if i < l - 1 and q: n.next = q[0] if n.left: q.append(n.left) if n.right: q.append(n.right) return root
class Solution: def fib(self, N: int) -> int: memo = {0: 0, 1: 1} return self.fib_helper(N, memo) def fib_helper(self, N, memo): if N in memo: return memo[N] else: memo[N] = self.fib_helper(N - 1, memo) + \ self.fib_helper(N - 2, memo) return memo[N]
# run with python3 turtle_draw.py from turtle import * import math # describe the arm and its joints inner_radius = 180 # the blue (inner) arm outer_radius = 160 # the red (outer) arm extent = 160 # the arc covered by each of the two joints joint_angle = 90 # the centre of the outer arm relative to the blue arm steps = 5 # number of degrees to step between drawing arcs draw_arms_every = 10 # the number of degrees between drawing the arms class T(Turtle): def draw_inner_arm(self, angle): self.up() self.home() self.width(2) # only draw the inner arm every draw_arms_every degrees if (angle/draw_arms_every).is_integer() or angle==extent: self.down() self.color("blue") self.left(angle) self.fd(inner_radius) self.dot(5, "black") else: self.left(angle) self.fd(inner_radius) def draw_outer_arm(self): self.rt(joint_angle) self.color("red") # go back to the start of the arm before drawing the arc self.fd(outer_radius) self.fd(-outer_radius) def draw_arc(self): # get the turtle into the correct position for drawing the arc self.up() self.rt(180) self.fd(outer_radius) self.rt(-90) # cover the undrawn part of the arc first self.circle(outer_radius, (360-extent)/2) # and then the part we want to draw self.color("gray") self.down() self.width(3) self.circle(outer_radius, extent) def visualise(): # set up the environment s = Screen() s.setup(width=800, height=800) mode("logo") t = T() t.speed(0) t.hideturtle() for angle in range (0, extent+1, steps): t.draw_inner_arm(angle) t.draw_outer_arm() t.draw_arc() s.exitonclick() # mainloop()
#!/usr/bin/env python # -*- coding: utf-8 -*- from datetime import date from random import randint class Intervalo: def __init__(self): self.t_i = "" self.t_f = "" self.listaDePontosTemporaisAleatorios = [] self.listaDePontosTemporais = [] self.listaDeIntervalos = [] self.hj = date.today() self.arrayIntervalosOrdenados = [] self.atributoTag = "" def incluiPonto(self,ponto): if(self.t_i > ponto): self.t_i = ponto elif(self.t_f < ponto): self.t_f = ponto self.listaDePontosTemporais.append(ponto) def get_inicio(self): return self.t_i def get_Fim(self): return self.t_f def get_ListadePontosTemporais(self): return self.listaDePontosTemporais # a partir de aqui é preciso verificar se não se trata do mesmo intervalo (muitos equals) e tb conferir qual a relação da AIA presente def imprimeIntervalos(self): print("\n Intervalo: ", self.t_i, self.t_f) print('Tamanho do intervalo'+ str(len(self.listaDePontosTemporais))) for i in range(len(self.listaDePontosTemporais)): print(self.listaDePontosTemporais[i]) def constroiIntervalos(self,janelaParaIntervalo): for ponto in self.listaDePontosTemporaisAleatorios: if (len(self.listaDeIntervalos) == 0): inter = Intervalo() inter.t_f = inter.t_i = ponto inter.listaDePontosTemporais.append(ponto) self.listaDeIntervalos.append(inter) else: inseriu = False for intervalo in self.listaDeIntervalos: # para cada intervalo de interesse no array de intervalos do atributo if (intervalo.t_i <= ponto and ponto <= intervalo.t_f): intervalo.listaDePontosTemporais.append(ponto) else: diferenca = abs(intervalo.t_i - ponto) if ( diferenca.days < janelaParaIntervalo and intervalo.t_i > ponto): # temos um novo ponto de inicio intervalo.t_i = ponto intervalo.listaDePontosTemporais.append(ponto) inseriu = True break else: diferenca = abs(intervalo.t_f - ponto) if ( diferenca.days < janelaParaIntervalo and intervalo.t_f < ponto): # temos um novo ponto de termino intervalo.t_f = ponto intervalo.listaDePontosTemporais.append(ponto) inseriu = True break if (inseriu): inseriu = False else: inter = Intervalo() inter.t_f = inter.t_i = ponto inter.listaDePontosTemporais.append(ponto) self.listaDeIntervalos.append(inter) def geraUmaDataAleatoria(self): hj = date.today() novaData = date.fromordinal(hj.toordinal() + randint(-900, 900)) # hoje + 45 dias</pre> return novaData
""" We'll start with this tree:: 4 2 7 1 3 5 8 like this:: >>> t = Node(4, ... Node(2, Node(1), Node(3)), ... Node(7, Node(5), Node(8)) ... ) >>> t.sum_dfs() 30 >>> t.sum_bfs() 30 """ class Node(object): """Binary search tree node.""" def __init__(self, data, left=None, right=None): """Create node, with data and optional left/right.""" self.left = left self.right = right self.data = data def __repr__(self): if self.left is None and self.right is None: return "<Node %s>" % self.data else: return "<Node %s l=%s r=%s>" % (self.data, self.left, self.right) def sum_dfs(self): node_sum = 0 if self.left: node_sum += self.left.sum_dfs() if self.right: node_sum += self.right.sum_dfs() node_sum += self.data return node_sum # The disadvantage of using queue is extra storage space def sum_bfs(self): queue = [self] node_sum = 0 while len(queue) > 0: n = queue.pop() # if using collections, use queue.deque , but that will have O(n^2) run time node_sum += n.data if n.left: queue.append(n.left) if n.right: queue.append(n.right) return node_sum if __name__ == "__main__": import doctest if doctest.testmod().failed == 0: print "\n*** ALL TESTS PASSED. NODES ADDED SUCCESSFULLY!\n"
import random def compare(): list1 = list([random.randint(0, 50) for i in range(1, 10)]) print(list1) list2 = list([random.randint(0, 50) for j in range(1, 15)]) print(list2) list3 = list() for i in list1: for j in list2: if i == j: list3.append(i) print(list3) compare()
# Leitura dos Arquivos fileReadState = open('entrada.txt.txt' , 'r') fileReadAlphabet = open('automato.txt.txt', 'r') #Cria arquivo para escrita fileWrite = open('saida.txt.txt' , 'w') # Leitura das linhas dos arquivos ReadState = fileReadState.read() ReadAlphabet = fileReadAlphabet.read() # Vetores Que guardam as linhas dos txts States = [] StateList = [] InputList = [] #Vetor que guarda encadeamento EncadList = [] # Variaveis inicial e final initial = "i" final = "f" # Colocando as linhas do txt nos vetores ListStateLines = ReadState.splitlines() ListInputLines = ReadAlphabet.splitlines() EstadoAtual = 0 AntEstado = 't' PrxEstado = 't' ValAtual = 't' AntVal = 't' PrxVal = 't' boolean = False ValAntEst = 0 # Separando os dados de cada linha por colunas for line in ListStateLines: StateList.append(line.split()) for line in ListInputLines: InputList.append(line.split()) #Descobrindo o estado inicial e final for line in StateList: count = len(line) - 1 if (line[count] == "i" or line[count] == "I"): initial = line[0] del(line[count]) for line in StateList: count = len(line) - 1 if (line[count] == "f" or line[count] == "F"): final = line[0] del(line[count]) #Guarda os estados States.append(line[0]) #Leitura do alfabeto for lineInput in InputList: if(ValAtual == "Break"): print('teste') fileWrite.close break; for lineI in lineInput: if(ValAtual == "Break"): break; for lineState in range(len(StateList)): if(PrxVal == 'True'): PrxVal = StateList[EstadoAtual][2] if(PrxVal == StateList[EstadoAtual][3]): EstadoAtual = EstadoAtual + 1 break else: EstadoAtual = EstadoAtual + 1 else: PrxVal = StateList[EstadoAtual][1] if(lineI == PrxVal): PrxVal = 'True' boolean = True break else: fileWrite.write(str(InputList[0]) + " -> " + StateList[EstadoAtual][0]+ " -> Rejeitado") EstadoAtual = 8 print('teste2') ValAtual = 'Break' break; if(EstadoAtual == 8): EstadoAtual = 0 break;
diasv=int(input("Insira quantos dias de vida você tem: ")) anos=diasv/365 mes=(diasv%365)/30 dias=((diasv%365)%30) print("Você tem %1.f anos %1.f meses e %1.f dias de vida."%(anos,mes,dias))
base=int(input("Insira a base: ")) altura=int(input("Insira a altura: ")) area=base*altura if base!=altura: print("A area do retangulo é: ",area) else: print("A area do quadrado é: ",area)
def soma(n1,n2,n3): s=n1+n2+n3 print("O resultado da soma dos números anteriormente é : ",a) def maior(n1,n2,n3): if n1>n2 and n1>n3: print("O maior número é o: ",a) elif n2>n1 and n2>n3: print("O maior número é o: ",b) else: print("O maior número é o: ",c) def menor(n1,n2,n3): if n1<n2 and n1<n3: print("O menor número é o: ",a) elif n2<n1 and n2<n3: print("O menor número é o: ",b) else: print("O menor número é o: ",c) def media(n1,n2,n3): med=(n1+n2+n3)/3 print("A média dos números inseridos anteriormente é: %.2f"%(med)) def opcao(o): if o==1: soma(a,b,c) elif o==2: maior(a,b,c) elif o==3: menor(a,b,c) elif o==4: media(a,b,c) a=int(input("Insira o primeira número:")) b=int(input("Insira o segundo número:")) c=int(input("Insira o terceiro número:")) op=int(input("Escolha uma opção. Instruções: 1 - soma dos número, 2 - exibe o maior dos número, 3 - exibe o menor dos números, 4 - média dos números: ")) while op<=0 or op>4: op=int(input("Opção inválida. Escolha uma opção. Instruções: 1 - soma dos número, 2 - exibe o maior dos número, 3 - exibe o menor dos números, 4 - média dos números: ")) opcao(op)
ano=int(input("Insira ano: ")) if ano%4==0 and ano%100!=0 or ano%400==0: print("É bissexto")
import csv inputfile = '\\Users\\guila\\PycharmProjects\\python_poll\\election_data.csv' outputfile = '\\Users\\guila\\PycharmProjects\\python_poll\\election_output.txt' # Create empty list for csv file polls = [] # Create empty dictionary to record only candidate names dict_polls = {} # Create empty dictionaty to summarize the total number votes per candidate name dict_summary = {} # Open file and assign to csvfile object name with open(inputfile, newline='') as csvfile: # read and split the data on commas assign to pollreader string variable pollreader = csv.reader(csvfile, delimiter=',') # Skip header row next(pollreader) text_file = open(outputfile, "w") # Output to text file text_file.write("Election Results") # Terminal output print("Election Results.....By Serge Guilao") # Output to text file text_file.write("\n-------------------------") # Terminal Output print("-------------------------") # Converting string to list for line in pollreader: polls.append(line) # Output to text file text_file.write("\nTotal Votes: " + str(len(polls))) # Terminal Output print("Total Votes: " + str(len(polls))) # Text file Output text_file.write("\n-------------------------") # Terminal Output print("-------------------------") # Converting to dictionary for counting and grouping candidate names for line in polls: name_key = line[2] if name_key not in dict_polls: # insert name_key into dictionary and initialize to 0 dict_polls[name_key] = 0 # count the name key inside dictionary dict_polls[name_key] += 1 # Dictionary_summary total_polls = len(polls) for name in dict_polls: dict_summary[name] = round((dict_polls[name] / total_polls) * 100) # Output to text file text_file.write("\n" + str(name) + ": " + str(dict_summary[name]) + "% " + "(" + str(dict_polls[name]) + ")") # Output to console print(str(name) + ": " + str(dict_summary[name]) + "% " + "(" + str(dict_polls[name]) + ")") # The highest value highest = 0 # Find larget value of the key/value pair inside dictionary and place the key name inside winner for name in dict_summary: if highest < dict_summary[name]: highest = dict_summary[name] winner = name # Output to text file text_file.write("\n-------------------------") # Output to console print("-------------------------") # Output to text file text_file.write("\nWinner: " + winner) # Output to console print("Winner: " + winner) # Output to text file text_file.write("\n-------------------------") # Output to console print("-------------------------") # Close text file text_file.close()
# -*- coding: utf-8 -*- """ Created on Tue Feb 2 22:03:48 2021 @author: ThinkPad """ class Solution: def solveNQueens(self, n: int) -> List[List[str]]: solutions = list() queens = [-1]*n #初始化皇后的位置 col = set() diag1 = set() diag2 = set() def backtrack(row): if row == n: # 当找到所有皇后的位置(符合条件), 将结果添加到solutions列表中 board = generateboard() solutions.append(board) else: for i in range(n): if i in col or row - i in diag1 or row + i in diag2: #如果该列或该单元格所在两条对角线上已经有皇后,那么继续判断该列的下一格 continue queens[row] = i # 记录第i行皇后的位置(即列号) col.add(i) diag1.add(row - i) diag2.add(row + i) backtrack(row + 1) # 回溯算法, 寻找下一行皇后的位置 col.remove(i) diag1.remove(row - i) diag2.remove(row + i) rows = "."*n def generateboard(): board = [] for i in range(n): line = list(rows) line[queens[i]] = 'Q' #将对应位置的 '.' 换为 'Q' line = ''.join(line) board.append(line) return board backtrack(0) return solutions
# -*- coding: utf-8 -*- """ 实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,x^n)。 """ class Solution: def myPow(self, x: float, n: int) -> float: if n == 0: return 1 if n == 1: return x if n < 0: x = 1/x n = -n temp = self.myPow(x, n//2) if n%2 == 0: return temp*temp return temp*temp*x #对于奇数,需要乘一个额外的x
# -*- coding: utf-8 -*- ''' Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next ''' class Solution: # Normal method def addTwoNumbers(self, l1, l2): result = ListNode(0) re = result carry = 0 while(l1 or l2): x = l1.val if l1 else 0 y = l2.val if l2 else 0 s = carry + x + y carry = s//10 re.next = ListNode(s % 10) re = re.next if l1 != None: l1 = l1.next if l2 != None: l2 = l2.next if carry > 0: re.next = ListNode(1) return result.next class Solution2: # 递归解法 def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: def dfs(l, r, i): if not l and not r and not i: return None s = (l.val if l else 0) + (r.val if r else 0) + i node = ListNode(s % 10) node.next = dfs(l.next if l else None, r.next if r else None, s // 10) return node return dfs(l1, l2, 0)
''' Created on Feb 8, 2016 @author: Carles Poles-Mielgo UCI - Introduction to Python Week 3 Assignment NOTE: My compiler is Python 3.5.0 |Anaconda 2.4.0. ''' # Question 1. for x in range(10): print(x) # Question 2. for x in range(10): if x == 0: print('zero') elif (x % 2) == 0: print('even') else: print('odd') # Question 3. myVar = 2.0 while(myVar <= 100): myVar = myVar * 1.65 print(myVar)
from numpy import * import math import funciones import gauss import os os.system("clear") print("=======================================================================") print("========================== Metodo de Newton ===========================") print("================== Sistema de Ecuaniones no Lineales ==================") print("=======================================================================") it = int(input("De el numero de iteraciones: ")) k = 0 error = pow(10,-5) e = 1 X0 = loadtxt("vecX.dat") print("========================== Vector Inicial ===========================") print(X0) print("iteracion\tX1\tX2\terror") while(k < it and e > error): k+=1 J = array(([funciones.xf1(X0),funciones.yf1(X0)],[funciones.xf2(X0),funciones.yf2(X0)]),dtype = float) B = array(([-funciones.f1(X0)],[-funciones.f2(X0)])) Z = column_stack((J,B)) h = gauss.gauss(Z) X1 = X0 + h print(k,"[",X1[0],",",X1[1],"]",e) e = linalg.norm(X1-X0) X0 = X1
def selection_sort(arr): for i in range(len(arr)): minimum = i for j in range(i+1,len(arr)): if arr[j] < arr[minimum]: minimum = j arr[i],arr[minimum] =arr[minimum],arr[i] return arr a= [3,1,5,2,6,4,9,8,7] b= [5,6,9,8,7,2,4,3,1] c= [9,7,8,4,6,1,3,2,5] print(selection_sort(a)) print(selection_sort(b)) print(selection_sort(c))
# Selection Sort # Complexity of Selection Sort - O(n2) # Number of Swaps - O(n) # It is not a stable sort def selection(iteration_list): length = len(iteration_list) for i in range(length - 1): min_position = i for j in range(i, length): if iteration_list[j] < iteration_list[min_position]: min_position = j iteration_list[i], iteration_list[min_position] = iteration_list[min_position], iteration_list[i] number_list = [5, 3, 8, 6, 5, 2] selection(number_list) print("Sorted List: ", number_list)
# Bubble Sort # Complexity of Bubble Sort - O(n2) # It is a stable sort # Number of Swaps - O(n) def bubble(iterate_list): for i in range(len(iterate_list) - 1, 0, -1): for j in range(i): if iterate_list[j] > iterate_list[j+1]: iterate_list[j], iterate_list[j+1] = iterate_list[j+1], iterate_list[j] print(iterate_list) print(" ") number_list = [5, 3, 8, 6, 7, 5, 2] bubble(number_list) print("Sorted List: ", number_list) print(sorted(number_list)) number_list.sort() print(number_list)
"""Eular Problem 6 - Sum square difference: Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ import timer DESC = 'Sum square difference' SOLUTION = 25164150 def sum_of_squares(limit): """ Returns the sum of all squares in the range 1 up to and including limit. """ return sum([i ** 2 for i in range(limit+1)]) def square_of_sum(limit): """ Returns the square of the sum of all integers in the range 1 up to and including limit. """ return sum([i for i in range(limit + 1)]) ** 2 @timer.timeit def solve(): upto = 100 sum_of_sq = sum_of_squares(upto) sq_of_sum = square_of_sum(upto) return abs(sq_of_sum - sum_of_sq)
"""Eular Problem 8 - What is the 10001st prime number? """ import primes import timer DESC = '10001st prime:' SOLUTION = 104743 @timer.timeit def solve(): targetprime = 10001 result = 0 for i, result in enumerate(primes.primes()): if i == targetprime - 1: break return result
################################ # Title -- The Old Mansion # Author -- Austin Rosenbaum # Started -- July 5, 2018 # Modified -- July 29, 2019 # Finished -- ??/??/???? ################################ # Imports # pygame? import time, random # Custom imports from entity.player import Player from map.spot import Spot # Create map # create a default spot to test default_spot = Spot(0, 0) # Create player object name = input("What is your name? ") player = Player(name, default_spot) print(f"Welcome to The Old Mansion {player.name}!") print(f"You are currently at ({player.location.x}, {player.location.y})") # Create enemies # Create items
print 'hello nancy' a = 1; b = 3; if a<b: print a else: print b count = 0 while (count < 9): print "this count is:", count count= count+1 print "this is the end" a="I am the start" b="I am the end" print a,b
def merge(left_list, right_list): sorted_list = [] left_list_index = right_list_index = 0 left_length, right_length = len(left_list), len(right_list) for _ in range(left_length + right_length): if left_list_index < left_length and right_list_index < right_length: if left_list[left_list_index] <= right_list[right_list_index]: sorted_list.append(left_list[left_list_index]) left_list_index += 1 else: sorted_list.append(right_list[right_list_index]) right_list_index += 1 elif left_list_index == left_length: sorted_list.append(right_list[right_list_index]) right_list_index += 1 elif right_list_index == right_length: sorted_list.append(left_list[left_list_index]) left_list_index += 1 return sorted_list def merge_sort(nums): if len(nums) <= 1: return nums mid = len(nums) // 2 left_list = merge_sort(nums[:mid]) right_list = merge_sort(nums[mid:]) return merge(left_list, right_list) def merge_sort_func(file_name): with open(file_name, "r") as file: S = list(map(int, file.read().split(" "))) merge_sort(S) print("Сортировка слиянием") print(S)
def singleton(class_): """Singleton decorator function Arguments: class_: singleton class """ instance = {} def get_instance(*args, **kwargs): if class_ not in instance: instance[class_] = class_(*args, **kwargs) return instance[class_] return get_instance class Singleton(type): """Singleton class Metaclass to provide Singleton pattern to custom Python class. """ _instance = {} def __call__(cls, *args, **kwargs): if cls not in cls._instance: cls._instance[cls] = super().__call__(*args, **kwargs) return cls._instance[cls] class MyClass(metaclass=Singleton): def __init__(self, o): self.o = o def bark(self): print('gav') def von(self): print(self.o) @singleton class MyClassWithDec: def __init__(self, o): self.o = o def bark(self): print('gav') def von(self): print(self.o)
class VectorError(Exception): def __init__(self, message): self.message = message class Vector: def __init__(self, *components): for arg in components: if not isinstance(arg, int) and not isinstance(arg, float): raise TypeError self.components = components self.dimensions = len(components) def __len__(self): sum = 0 for c in self.components: sum += c * c return pow(sum, 1 / 2) def __getitem__(self, i): if i < self.dimensions: return self.components[i] else: raise IndexError def __repr__(self): return repr(self.components) def __add__(self, vector): if isinstance(vector, Vector): if self.dimensions == vector.dimensions: return Vector(*[a + b for (a, b) in zip(self.components, vector.components)]) else: raise VectorError("Vectors have different dimensions.") else: raise TypeError def __sub__(self, vector): if isinstance(vector, Vector): if self.dimensions == vector.dimensions: return Vector(*[a - b for (a, b) in zip(self.components, vector.components)]) else: raise VectorError("Vectors have different dimensions.") else: raise TypeError def __eq__(self, vector): if isinstance(vector, Vector): if self.dimensions == vector.dimensions: return self.components == vector.components else: return False else: raise TypeError def __mul__(self, obj): if isinstance(obj, Vector): if self.dimensions == obj.dimensions: return sum([a * b for (a, b) in zip(self.components, obj.components)]) else: raise VectorError("Vectors have different dimensions.") if isinstance(obj, int) or isinstance(obj, float): return Vector(*[a * obj for a in self.components]) else: raise TypeError
import re import argparse def generator(range, first = 0, second = 1): while second < range: temp = second second += first first = temp yield first def fibonacci(range): f = generator(range) for num in f: print(num) def merge(left, right): result = [] i = j = 0 while i < len(left) and j < len(right): if left[i] < right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 while i < len(left): result.append(left[i]) i += 1 while j < len(right): result.append(right[j]) j += 1 return result def merge_sort(list): if len(list) < 2: return list else: middle = len(list) // 2 left = merge_sort(list[:middle]) right = merge_sort(list[middle:]) return merge(left, right) def quick_sort(list, first, last): i,j = first, last pivot = list[(first + last) // 2] while i <= j: while list[i] < pivot: i += 1 while list[j] > pivot: j -= 1 if i <= j: list[i], list[j] = list[j], list[i] i += 1 j -= 1 if first < j: quick_sort(list, first, j) if i < last: quick_sort(list, i, last) def text(task, file, length = 0): with open(file, "r") as text: regexp = re.findall(r"\w+", text.read()) words = dict() for word in regexp: word = word.lower() if word in words: words[word] += 1 else: words[word] = 1 if task == "list": return words else: words = sorted(words.items(), key=lambda pair: pair[1], reverse = True) sentence = [] if length > len(words): print("Max length is " + str(len(words)) + ".") length = len(words) elif length <= 0: return "Invalid length." for word in list(words) [:length]: sentence.append(word[0]) sentence[0] = sentence[0].capitalize() sentence[length - 1] += "." return " ".join(sentence) def sort(task, file): with open(file, "r") as nums: numbers = nums.read().split() for i in range(0, len(numbers)): numbers[i] = int(numbers[i]) if task == "quick_sort": quick_sort(numbers, 0, len(numbers) - 1) else: numbers = merge_sort(numbers) print(numbers) def create_parser(): parser = argparse.ArgumentParser() parser.add_argument("-t", "--task", choices=["list", "sentence", "quick_sort", "merge_sort", "fibonacci"], default="fibonacci") parser.add_argument("-f", "--file", choices=["text.txt", "numbers.txt"], default="text.txt") parser.add_argument("-sl", "--sentence_length", default=10, type=int) parser.add_argument("-fr", "--fib_range", default=100, type=int) return parser parser = create_parser() params = parser.parse_args() task = params.task file = params.file sentence_length = params.sentence_length fib_range = params.fib_range if task == "list": for item in text(task, file).items(): print(str(item[1]) + " " + item[0]) elif task == "sentence": print(text(task, file, sentence_length)) elif task == "quick_sort" or task == "merge_sort": sort(task, file) else: fibonacci(fib_range)
# -*- coding: utf-8 -*- def main(): ipt = input().split(' ') N, M = tuple(map(lambda x: int(x), ipt)) route_dict = {} if M != 0: for _ in range(M): ipt = input().split(' ') a, b = tuple(map(lambda x: int(x), ipt)) if not a in route_dict: route_dict[a] = [b] else: route_dict[a].append(b) pointer = 0 route_num = 0 for i in range(N): available = [i+1] pointer = 0 flag=True while flag: if not available[pointer] in route_dict: flag = False else: for n in route_dict[available[pointer]]: if not n in available: available.append(n) else: pass if (pointer+1) == len(available): flag = False else: pointer += 1 route_num += len(available) print(route_num) else: print(N) if __name__ == '__main__': main()
for _ in range(input()): a = raw_input() b = raw_input() l = len(a) answer = "" for i in range(l): if a[i] == b[i]: if a[i] == 'B': answer += 'W' else: answer += 'B' else: answer += 'B' print answer
for _ in range(input()): s = raw_input() l = len(s) for i in range(l): if s[i] == "s" and i > 0 and s[i-1] == "m": s = s[:i-1] + "#." + s[i+1:] elif s[i] == "s" and i < l-1 and s[i+1] == "m": s = s[:i] + ".#" + s[i+2:] answer = 0 for c in s: if c == "s": answer -= 1 elif c == "m" or c == "#": answer += 1 if answer < 0: print "snakes" elif answer == 0: print "tie" else: print "mongooses"
for _ in range(input()): n = input() a = [] if n%2 == 1: for i in range(1,n-3,2): a.append(i+1) a.append(i) a.append(n-1) a.append(n) a.append(n-2) else: for i in range(1,n,2): a.append(i+1) a.append(i) for i in a: print i, print ""
allowed = ["CES", "CE", "CS", "ES", "C", "E", "S"] for i in range(input()): s = raw_input() newS = "" lastC = "" for c in s: if c != lastC: newS += c lastC = c answer = "no" for correct in allowed: if newS == correct: answer = "yes" break print answer
for _ in range(input()): a = raw_input().split() answer = "" for i in range(len(a)-1): answer += a[i][0].upper() + ". " answer += a[-1][0].upper() + a[-1][1:].lower() print answer
# -*- coding: utf-8 -*- """ Created on Thu Nov 28 17:39:36 2019 @author: 33762 """ import blocageTour as bT import blocageFou as bF def place_dispo(pos,echiquier,couleur): """ place_dispo(List[int,int],List[List[String]],String) -> return String Returns if the box whose position is given as a parameter is enemy / ally or empty compared to a color !!! Returns enemy that if it is badly written mdrrr it is weird !!! #WORK mais étrange """ noirs=['Pn','Cn','Fn','Tn','Rn','Dn'] blancs=['Pb','Cb','Fb','Tb','Rb','Db'] if echiquier[pos[1]][pos[0]] in noirs: if couleur == 'Noir': return 'Allier' if echiquier[pos[1]][pos[0]] in blancs: if couleur == 'Blanc': return 'Allier' elif echiquier[pos[1]][pos[0]] == '**': return 'Vide' elif echiquier[pos[1]][pos[0]] != '': return 'Ennemi' def coups_possibles_tour(pos,echiquier,couleur): """ coups_possibles_tour(List[int,int],List[List[String]],List[List[int,int]],string) return -> List[List[int,int]] returns all possible moves for a rook in a specific position and chessboard """ res=[] #move down rook coups_bas=bT.descendre(pos) for coup in coups_bas: if place_dispo(coup,echiquier,couleur) == 'Allier': break elif place_dispo(coup,echiquier,couleur) == 'Ennemi': res.append(coup) break elif place_dispo(coup,echiquier,couleur) == 'Vide': res.append(coup) else: break #move hight rook coups_haut=bT.monter(pos) for coup in coups_haut: if place_dispo(coup,echiquier,couleur) == 'Allier': break elif place_dispo(coup,echiquier,couleur) == 'Ennemi': res.append(coup) break elif place_dispo(coup,echiquier,couleur) == 'Vide': res.append(coup) else: break #move right coups_droite=bT.droite(pos) for coup in coups_droite: if place_dispo(coup,echiquier,couleur) == 'Allier': break elif place_dispo(coup,echiquier,couleur) == 'Ennemi': res.append(coup) break elif place_dispo(coup,echiquier,couleur) == 'Vide': res.append(coup) else: break #move left rook coups_gauche=bT.gauche(pos) for coup in coups_gauche: if place_dispo(coup,echiquier,couleur) == 'Allier': break elif place_dispo(coup,echiquier,couleur) == 'Ennemi': res.append(coup) break elif place_dispo(coup,echiquier,couleur) == 'Vide': res.append(coup) else: break return res def coups_possibles_fou(pos,echiquier,couleur): """ coups_possibles_fou(List[int,int],List[List[String]],List[List[int,int]],string) return -> List[List[int,int]] returns all possible moves for a bishop in a precise position and chessboard #work """ res=[] #move down bishop coups_bas_doite=bF.decendreDroite(pos) for coup in coups_bas_doite: if place_dispo(coup,echiquier,couleur) == 'Allier': break elif place_dispo(coup,echiquier,couleur) == 'Ennemi': res.append(coup) break elif place_dispo(coup,echiquier,couleur) == 'Vide': res.append(coup) else: break #move down bishop coups_bas_gauche=bF.decendreGauche(pos) for coup in coups_bas_gauche: if place_dispo(coup,echiquier,couleur) == 'Allier': break elif place_dispo(coup,echiquier,couleur) == 'Ennemi': res.append(coup) break elif place_dispo(coup,echiquier,couleur) == 'Vide': res.append(coup) else: break #move right bishop coups_haut_droite=bF.monterDroite(pos) for coup in coups_haut_droite: if place_dispo(coup,echiquier,couleur) == 'Allier': break elif place_dispo(coup,echiquier,couleur) == 'Ennemi': res.append(coup) break elif place_dispo(coup,echiquier,couleur) == 'Vide': res.append(coup) else: break #move left bishop coups_haut_gauche=bF.monterGauche(pos) for coup in coups_haut_gauche: if place_dispo(coup,echiquier,couleur) == 'Allier': break elif place_dispo(coup,echiquier,couleur) == 'Ennemi': res.append(coup) break elif place_dispo(coup,echiquier,couleur) == 'Vide': res.append(coup) else: break return res def coups_possibles_dame(pos,echiquier,couleur): """ coups_possibles_dame(List[int,int],List[List[String]],List[List[int,int]],string) return -> List[List[int,int]] returns all possible moves for a queen in a specific position and chessboard We consider that the queen moves like bishop + a rook #work """ return coups_possibles_fou(pos,echiquier,couleur)+coups_possibles_tour(pos,echiquier,couleur) def coups_possibles_cavalier(pos,echiquier,couleur): """ coups_possibles_cavalier(List[int,int],List[List[String]],List[List[int,int]],string) return -> List[List[int,int]] return all possibilities for the knight in a specific position #WORK """ x=pos[0] y=pos[1] coups=[] res=[] for i,j in [[2,1],[2,-1],[1,2],[1,-2],[-1,2],[-1,-2],[-2,1],[-2,-1]]: #for each knight possibilities coordx=x+i coordy=y+j if coordx <= 7 and coordy <= 7 and coordx >= 0 and coordy >= 0: #if the movement does not bring the piece out of the chessboard coups.append([coordx,coordy]) #then we add it to the list of theoretically possible moves for coup in coups: #For each move in the list of theoretically possible moves if place_dispo(coup,echiquier,couleur) != 'Allier': #if there is no ally on the square res.append(coup) #then this move is valid so we add it to the list return res def coups_possibles_roi(pos,echiquier,couleur): """ coups_possibles_cavalier(List[int,int],List[List[String]],List[List[int,int]],string) return -> List[List[int,int]] returns all possible moves for a king in a specific position and chessboard """ x=pos[0] y=pos[1] coups=[] res=[] for i in [-1,0,1]: for j in [-1,0,1]: coordx=x+i coordy=y+j if coordx < 8 and coordy < 8 and coordx >= 0 and coordy >= 0: coups.append([coordx,coordy]) for coup in coups: #For each move in the list of theoretically possible moves if place_dispo(coup,echiquier,couleur) != 'Allier': #if there is no ally on the square res.append(coup) #then this move is valid so we add it to the list return res def coups_possibles_pion(pos,echiquier,couleur): """ coups_possibles_cavalier(List[int,int],List[List[String]],List[List[int,int]],string) return -> List[List[int,int]] returns all possible moves for a king in a specific position and chessboard """ x=pos[0] y=pos[1] coups=[] res=[] if couleur == 'Blanc': coups.append([x,y-1]) if y == 6 and place_dispo([x,y-1],echiquier,couleur) == 'Vide': #If the pawn is in its initial position and it is not blocking then it can advance two spaces coups.append([x,y-2]) for coup in coups: if place_dispo(coup,echiquier,couleur) == 'Vide': #the pawn can only eat diagonally, that's why the box must be empty res.append(coup) #If an enemy is on the nearest diagonal square then he can eat him if x!=7: if place_dispo([x+1,y-1],echiquier,couleur) == 'Ennemi': res.append([x+1,y-1]) if x!=0: if place_dispo([x-1,y-1],echiquier,couleur) == 'Ennemi': res.append([x-1,y-1]) else : #if it is black coups.append([x,y+1]) if y == 1 and place_dispo([x,y+1],echiquier,couleur) == 'Vide': #If the pawn is in its initial position and it is not blocking then it can advance two square coups.append([x,y+2]) for coup in coups: if place_dispo(coup,echiquier,couleur) == 'Vide': #the pawn can only eat diagonally, that's why the box must be empty res.append(coup) #If an enemy is on the nearest diagonal square then he can eat it if x!=7: if place_dispo([x+1,y+1],echiquier,couleur) == 'Ennemi': res.append([x+1,y+1]) if x!=0: if place_dispo([x-1,y+1],echiquier,couleur) == 'Ennemi': res.append([x-1,y+1]) return res
class Foo: def __init__(self, a, b, c): self.a = a self.b = b self.c = c print('call __init__ with args({}, {}, {})'.format( self.a, self.b, self.c)) def __call__(self, a, b): self.a = a self.b = b print('call __call__ with args({}, {})'.format(self.a, self.b)) f = Foo(1, 2, 3) f(1, 2)
# Create of Master User and save Passwords. After Creation of Master User, you # add your username and passwords along with websites on which you have made # your account and want to store the data. import sqlite3 import string import secrets database = sqlite3.connect('master_database.db') cur = database.cursor() def choices(): print("1. Add new Master User") print("2. Login as Master User") print("3. Change Your Master User Password") print("4. Delete your Master User Data") def password_generator(): password = ''.join(secrets.choice(string.ascii_letters+string.digits+string.punctuation) for i in range(10)) return password choices() instruct_choice = int(input("Enter your choice:")) choice = [1, 2, 3, 4] if instruct_choice not in choice: print("Wrong Choice! Please Read your Instructions again..") choices() else: if instruct_choice == 1: cur.execute('''CREATE table IF NOT EXISTS master_user (MasterUserName,Password) Primary Key (MasterUserName)''') master_user_name = input("Enter Master Username without space:") print("Do you want to generate a new password. YES or NO") gen_pass = input("Enter your Choice:") password_list = [] password = '' choice = 0 if gen_pass.upper() == 'YES': for i in range(5): a = password_generator() password_list.append(a) for i in password_list: print(password_list.index(i)+1, " ", i) choice_of_password = int(input("Enter the serial number of Password:")) password = password_list[choice_of_password-1] elif gen_pass.upper() == 'NO': password = input("Enter your master password (should be in range 8-14 characters):") print(password) print("Master Username:{} \nMaster Password:{}".format(master_user_name, password)) save_choice = input("Do you want to save your password? (YES or NO)") if save_choice.upper() == 'YES': cur.execute("INSERT INTO master_user values(?,?)", (master_user_name, password)) database.commit() filename = "master_user_" + master_user_name password_file = open(filename, "w") password_file.write("Password:{}".format(password)) else: exit() elif instruct_choice == 2: print("\n\t\tWelcome to Login Section!\n\n") input_master_username = input("Enter your Master Username:") input_master_password = input("Enter your Master Password:") cur.execute('''SELECT Password FROM master_user where MasterUserName = ?''', (input_master_username,)) password_list = cur.fetchone() password = password_list[0] curr = database.cursor() if password == input_master_password: print("Welcome Master User \"{}\"\n\n".format(input_master_username)) print("How Can I Help You Today?") print("1. Enter New Username, Password, Website") print("2. Change Password") print("3. Delete Username, Password, Website data") print("4. Display All Details of the Master User") second_choice = int(input("Enter your choice:")) curr.execute('''Create Table IF NOT EXISTS username_database ( MasterUserName varchar2 NOT NULL, Username varchar2 NOT NULL, Password varchar2 NOT NULL, Website varchar2) Primary Key (MasterUserName,Username) Foreign Key (MasterUserName)''') # Add MasterUserName as Foreign Key if second_choice == 1: new_username = input("Enter new Username:") password_choice = input("Do you want to generate new password? YES or NO:") new_password = '' if password_choice.upper() == 'YES': new_password = password_generator() elif password_choice.upper() == 'NO': new_password = input("Enter you password:") new_website = input("Enter website link for Credentials Storage(YOU CAN KEEP IT Empty):") print("New Username:{}\nNew Password:{}\nWebsite link provided:{}".format(new_username, new_password, new_website)) curr.execute('''INSERT INTO username_database (MasterUserName, Username, Password, Website) values(?,?,?,?)''', (input_master_username, new_username, new_password, new_website)) database.commit() elif second_choice == 2: username_ = input("Enter your Username to change Password for:") old_password = input("Enter your current password:") curr.execute('''Select password from username_database where MasterUserName=? and Username=?''', ( input_master_username, username_,)) password_l = curr.fetchone() password_ = password_l[0] if old_password == password_: print("Password Matched!") choice_ = input("Do you want to generate Password?(YES or NO)") new_password = '' if choice_.upper() == 'YES': new_password = password_generator() else: new_password = input("Enter your new password:") filename = "master_user_"+input_master_username+"_username_"+username_ password_file = open(filename, "w") password_file.write("Password:{}".format(new_password)) curr.execute('''update username_database set password=? where MasterUserName=? and Username=?''', (new_password, input_master_username, username_)) database.commit() print("Successfully Updated your Password") curr.execute('''Select * from username_database where MasterUserName=? and Username=?''', ( input_master_username, username_,)) details = curr.fetchone() print("MasterUserName:{}\nUsername:{}\nPassword:{}\nWebsite:{}".format( details[0], details[1], details[2], details[3])) elif second_choice == 3: print("Enter your Details to be Deleted:") username = input("Enter your username:") password = input("Enter your password:") curr.execute('''Select * from username_database where MasterUserName=? and Username=? and Password=?''', (input_master_username, username, password)) details = curr.fetchone() print("Your details have been matched!\nUsername:\t{}\nPassword:\t{}\nWebsite:\t{}".format( details[1], details[2], details[3])) curr.execute('''Delete from username_database where MasterUserName=? and Username=? and Password=?''', (input_master_username, username, password)) database.commit() print("\nThe above Displayed Details have been deleted successfully!\n") elif second_choice == 4: curr.execute('''Select Username, Password, Website from username_database where MasterUserName=?''', (input_master_username,)) details = curr.fetchall() for i in details: print("\nUsername:\t{}\nPassword:\t{}\nWebsite:\t{}\n".format(i[0], i[1], i[2])) elif instruct_choice == 3: master_username = input("Enter Your Master Username:") master_password = input("Enter Your Password:") cur.execute('''SELECT Password FROM master_user where MasterUserName = ?''', (master_username,)) password_list = cur.fetchone() password = password_list[0] if password == master_password: print("Password Matched!") choice = input("Do you want to generate a new password? (YES or NO)") new_password = '' if choice.upper() == 'YES': new_password = password_generator() else: new_password = input("Enter your new password:") filename = "master_user_"+master_username password_file = open(filename, "w") password_file.write("Password:{}".format(new_password)) cur.execute('''update master_user set password=? where MasterUserName=?''', (new_password, master_username)) database.commit() print("Successfully Updated your Password") elif instruct_choice == 4: master_username = input("Enter Your Master Username:") master_password = input("Enter Your Password:") cur.execute('''SELECT Password FROM master_user where MasterUserName = ?''', (master_username,)) password_list = cur.fetchone() password = password_list[0] if password == master_password: print("Password Matched!") cur.execute('''Delete from master_user where MasterUserName=? and Password=?''', ( master_username, master_password)) database.commit() print("Master Username and Password Deleted Successfully!") else: print("Invalid Password. Retry!")
import networkx as nx import matplotlib.pyplot as plt import numpy as np from typing import List from find_optimal import find_optimal from find_approx import find_approx from our_cost import our_cost def compare_graph(graph_type: str, num_nodes: int, **kwargs): G = get_graph_by_type(graph_type=graph_type, num_nodes=num_nodes, **kwargs) trees, opt_cost = find_optimal(G, our_cost) print(f"Min Cost Us: {opt_cost}") print(f"Min Trees ({len(trees)})") for tree in trees: tree.show() tree, approx_cost = find_approx(G) print(f"Min Cost Us: {approx_cost}") print(f"Min Tree:") tree.show() labels = {n: n for n in G.nodes()} print(f"Optimal Cost: {opt_cost}") print(f"Algorithm Cost: {approx_cost}") nx.draw(G, labels=labels) plt.show() def compare_graphs(graph_type: str, num_nodes: int, **kwargs): num_graphs = 100 optimal_costs = np.zeros((num_graphs,)) approx_costs = np.zeros((num_graphs,)) for i in range(num_graphs): G = get_graph_by_type(graph_type=graph_type, num_nodes=num_nodes, **kwargs) trees, cost = find_optimal(G, our_cost) print(f"Min Cost Us: {cost}") print(f"Min Trees ({len(trees)})") for tree in trees: tree.show() optimal_costs[i] = cost tree, cost = find_approx(G) print(f"Min Cost Us: {cost}") print(f"Min Tree:") tree.show() approx_costs[i] = cost diffs = approx_costs - optimal_costs mean_diff = np.mean(diffs) print(f"Optimal: {optimal_costs}") print(f"Approx: {approx_costs}") print(f"Difference: {diffs}") print(f"Mean Difference: {mean_diff}") unique, counts = np.unique(diffs, return_counts=True) norm_counts = counts / num_graphs percentile_90 = int(np.percentile(diffs, 90)) max_diff = int(np.max(diffs)) plt.bar(unique, norm_counts, width=0.9) plt.axvline(mean_diff, c="yellow", label=f"Mean ({mean_diff:.2})") plt.axvline(percentile_90, c="orange", label=f"90th Percentile ({percentile_90})") plt.axvline(max_diff, c="red", label=f"Max ({max_diff})") plt.xlabel("Difference from Optimal") plt.ylabel("Probability") plt.xlim(-0.5, np.max(diffs) + 0.5) plt.title(f"Difference from Optimal for {num_nodes}-node {graph_type} Graphs") plt.legend(loc="upper right") plt.show() def compare_graph_means(graph_type: str, node_range: List[int], **kwargs): num_graphs = 100 range_len = len(node_range) optimal_costs = np.zeros((range_len, num_graphs,)) approx_costs = np.zeros((range_len, num_graphs,)) for i, n in enumerate(node_range): for j in range(num_graphs): G = get_graph_by_type(graph_type=graph_type, num_nodes=n, **kwargs) trees, cost = find_optimal(G, our_cost) print(f"Min Cost Us: {cost}") print(f"Min Trees ({len(trees)})") for tree in trees: tree.show() optimal_costs[i, j] = cost tree, cost = find_approx(G) print(f"Min Cost Us: {cost}") print(f"Min Tree:") tree.show() approx_costs[i, j] = cost mean_opts = np.zeros((range_len,)) std_opts = np.zeros((range_len,)) mean_approxs = np.zeros((range_len,)) std_approxs = np.zeros((range_len,)) for i, _ in enumerate(node_range): mean_opt = np.mean(optimal_costs[i,:]) mean_opts[i] = mean_opt std_opt = np.std(optimal_costs[i,:]) std_opts[i] = std_opt mean_approx = np.mean(approx_costs[i,:]) mean_approxs[i] = mean_approx std_approx = np.std(approx_costs[i,:]) std_approxs[i] = std_approx plt.plot(node_range, mean_opts, c="g", label="Optimal") plt.plot(node_range, mean_opts + std_opts, ls="--", c="g", label="Optimal (±1 std.)") plt.plot(node_range, mean_opts - std_opts, ls="--", c="g") plt.plot(node_range, mean_approxs, c="b", label="Algo") plt.plot(node_range, mean_approxs + std_approxs, ls="--", c="b", label="Algo (±1 std.)") plt.plot(node_range, mean_approxs - std_approxs, ls="--", c="b") plt.xlabel("Size of Data (# Nodes)") plt.ylabel("Cost") plt.xlim(np.min(node_range)-0.5, np.max(node_range)+0.5) plt.title(f"Optimal vs. Algo Costs for {graph_type} Graphs") plt.legend(loc="upper left") plt.show() def get_graph_by_type(graph_type: str, num_nodes: int, **kwargs) -> nx.Graph: if graph_type == "E-R": return nx.erdos_renyi_graph(n=num_nodes, **kwargs) elif graph_type == "Random Tree": return nx.random_tree(n=num_nodes, **kwargs) elif graph_type == "r-ary": return nx.full_rary_tree(n=num_nodes, **kwargs) elif graph_type == "Planted Partition": return nx.planted_partition_graph(**kwargs) elif graph_type == "Line": return nx.path_graph(n=num_nodes, **kwargs) elif graph_type == "Barabási–Albert": return nx.barabasi_albert_graph(n=num_nodes, **kwargs)
#1. Create a greeting for your program. #2. Ask the user for the city that they grew up in. #3. Ask the user for the name of a pet. #4. Combine the name of their city and pet and show them their band name. #5. Make sure the input cursor shows on a new line, see the example at: # https://band-name-generator-end.appbrewery.repl.run/ print("Welcome to Band Name Generator") city = input("What's name of the city you grew up in?\n") pet = input("What is the name of your pet?(Let's have a pet's name if not a pet otherwise)\n") print("Seems like "+ pet +" "+ city + " will be a good band name for you")
""" Created on Sun Oct 21 17:04:27 2018 @author: Wuethrich Pierre This is some example code of image classification using a simple CNN, using the MNIST data (hand-written digits) """ import numpy as np import pandas as pd import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data # Getting the MNIST data-set mnist = input_data.read_data_sets("MNIST_data/",one_hot=True) #------------------------------------------------------------------ # Creating functions which will help readability/structure of code # Initializing the weights of the NN-layers def init_weights(shape): init_rand_dist = tf.truncated_normal(shape,stddev=0.1) return tf.Variable(init_rand_dist) # Initializing the bias-terms def init_bias(shape): init_bias_values = tf.constant(0.1,shape=shape) return tf.Variable(init_bias_values) # Defining the two-dimenstional convolution and pooling functions # using tf built-in conv2d and max_pool methods def conv2d(x,W): return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding='SAME') def max_pool_2by2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') # Defining the convolutional layers and normal layers def convolutional_layer(input_x,shape): W = init_weights(shape) b= init_bias([shape[3]]) return tf.nn.relu(conv2d(input_x, W) + b) def normal_full_layer(input_layer, size): input_size = int(input_layer.get_shape()[1]) W = init_weights([input_size, size]) b = init_bias([size]) return tf.matmul(input_layer, W) + b #----------------------------------------------------------------------- # Defining the Placeholders, Layers, Optimizer, Loss-function,etc # Placeholders x = tf.placeholder(tf.float32,shape=[None,784]) y_true = tf.placeholder(tf.float32,shape=[None,10]) # Layers (2 times convolution and 2 x subpooling) x_image = tf.reshape(x,[-1,28,28,1]) convo_1 = convolutional_layer(x_image,shape=[6,6,1,32]) convo_1_pooling = max_pool_2by2(convo_1) convo_2 = convolutional_layer(convo_1_pooling,shape=[6,6,32,64]) convo_2_pooling = max_pool_2by2(convo_2) # Flattening of the output convo_2_flat = tf.reshape(convo_2_pooling,[-1,7*7*64]) full_layer_1 = normal_full_layer(convo_2_flat,1000) # Introducing node drop-out and getting y_pred holding_prob = tf.placeholder(tf.float32) full_one_dropout = tf.nn.dropout(full_layer_1,keep_prob=holding_prob) y_pred = normal_full_layer(full_one_dropout,10) # Defining the loss-function and optimizer cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits( labels=y_true,logits=y_pred)) optimizer = tf.train.AdamOptimizer(learning_rate=0.001) train = optimizer.minimize(cross_entropy) # Initialization of the variables and Session init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) steps = 500 for i in range(steps): batch_x , batch_y = mnist.train.next_batch(50) sess.run(train,feed_dict={x:batch_x,y_true:batch_y,holding_prob:0.5}) # PRINT OUT A MESSAGE EVERY 100 STEPS if i%50 == 0: print('Currently on step {}'.format(i)) print('Accuracy is:') # Test the Train Model matches = tf.equal(tf.argmax(y_pred,1),tf.argmax(y_true,1)) acc = tf.reduce_mean(tf.cast(matches,tf.float32)) print(sess.run(acc,feed_dict={x:mnist.test.images,y_true:mnist.test.labels,holding_prob:1.0})) print('\n')
def longest_subsequence(arr): n = len(arr) lista_crescatoare = [1]*n for i in range (1 , n): for j in range(0 , i): if arr[i] > arr[j] and lista_crescatoare[i]< lista_crescatoare[j] + 1 : lista_crescatoare[i] = lista_crescatoare[j]+1 maximum = 0 for i in range(n): maximum = max(maximum , lista_crescatoare[i]) return maximum arr = [1, 0, 3, 4, 2, 10, 4] print "Length of lista_crescatoare is", longest_subsequence(arr)
# Strip() function is used to remove the white space from the string. x = " hello world! " # print # print(x.lstrip()) # print(x.rstrip()) # print(x.strip()) #The split() method splits the string into substrings if it finds instances of the separator: print(x.split( )) print(x.split("world")) print(x.split("e"))
# Quadratic equation: ax**2 + bx + c # solution is: -b +- under root b square minus 4 ac upon 2a import cmath a = int(input("Enter no1:")) b = int(input("Enter no2:")) c = int(input("Enter no3:")) # calculate discrimination d = (b ** 2) - (4 * a * c) # two solutions solu1 = (-b + cmath.sqrt(d)) / (2 * a) solu2 = (-b - cmath.sqrt(d)) / (2 * a) print("The solutions are {0} and {1}".format(solu1, solu2))
num = int(input("Enter number:")) sum = 0 if num < 0: print("Enter positive number!") else: for i in range (1, num+1): sum = sum + i print("the sum of natural no.", num,":", sum)
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/",one_hot=True) x = tf.placeholder(tf.float32,[None,784]) w = tf.Variable(tf.zeros([784,10]), tf.float32) b = tf.Variable(tf.zeros([10]), tf.float32) y = tf.nn.softmax(tf.matmul(x, w)+ b) y_ = tf.placeholder(tf.float32,[None,10]) cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ *tf.log(y),reduction_indices=[1])) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) sess = tf.InteractiveSession() tf.global_variables_initializer().run() for _ in range(1000): batch_xs,batch_ys = mnist.train.next_batch(100) sess.run(train_step,feed_dict={x:batch_xs,y_:batch_ys}) correct_prediction = tf.equal(tf.argmax(y,1),tf.arg_max(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) print(sess.run(accuracy,feed_dict={x:mnist.test.images,y_:mnist.test.labels}))
import random import os def get_random_digits(): correct_answer = [] while len(correct_answer) < 3: digit = random.randint(0, 9) if digit not in correct_answer: correct_answer.append(digit) return correct_answer def get_user_input(): while True: user_guess = input("Enter number: ") if user_guess.isalpha(): print("Enter only digits") elif len(user_guess) != 3: print("You have to enter exactly 3 digits!") else: return list(user_guess) def compare_user_input_with_answer(user_guess, correct_answer): index = 0 hint_list = [] for a in correct_answer: if str(a) == user_guess[index]: hint_list.insert(0, 'HOT') elif str(a) in user_guess: hint_list.append("WARM") index += 1 if not hint_list: hint_list.append("COLD") return hint_list def check_result(hint_list): if hint_list == ["HOT"] * 3: return True def play_boss_game(): os.system('clear') print("Fight with Great Rydz in Hot Cold Warm game") print("guess three digits number Great Rydz is thinking of") correct_answer = get_random_digits() tries_left = 10 while tries_left > 0: user_guess = get_user_input() result = compare_user_input_with_answer(user_guess, correct_answer) print(result) if check_result(result): return True tries_left -= 1 if tries_left == 0: return False
imagenes=['im1','im2','im3'] dic={} indice=0 for i in imagenes: print("Ingrese la primer coordenada del elemento" " '",imagenes[indice],"'") primer=int(input()) print("Ingrese la segunda coordenada del elemento" " '",imagenes[indice],"'") segundo=int(input()) tupla=(primer, segundo) if not dic: dic[i]=tupla else: if tupla in dic.values(): while tupla in dic.values(): print("La coordenada ya existe, ingrese una nueva") print("Ingrese la primer coordenada del elemento" " '",imagenes[indice],"'") primer=int(input()) print("Ingrese la segunda coordenada del elemento" " '",imagenes[indice],"'") segundo=int(input()) tupla=(primer, segundo) dic[i]=tupla else: dic[i]=tupla print(dic) indice=indice+1
# -*- coding: utf-8 -*- class Classifier: """ This class is the abstract version of a classifier. All classifiers in this project should inherit this class to offer a uniform API. """ def __init__(self, name): """ Constructor. Arg: name the name of the classifier """ self.parameters = dict({"name": name}) def get_underlying_classifier(self): """ Returns the underlying classifier object. """ raise NotImplementedError() def train(self, inputs, targets): """ Trains the model on the given dataset. Arg: inputs the inputs targets the targets """ raise NotImplementedError() def predict(self, dataset): """ Predicts the dataset. Arg: dataset the inputs to predict Returns: the prediction of all inputs """ raise NotImplementedError() def predict_proba(self, dataset): """ Predicts the probabilities of each class for the dataset inputs. Arg: dataset the inputs to predict Returns: the probabilities of all inputs """ raise NotImplementedError() def score(self, inputs, targets): """ Computes the accuracy and loss on the given dataset. Arg: inputs the inputs targets the targets Returns: the accuracy and loss """ raise NotImplementedError()
name = "John Doe" age = 47 occupation = "Spy" print(f"{name}, aged {age} is a {occupation}") number = 5 number= number + 20 print (f"The number is {number}.") number_of_oranges = 3333 number_of_people = 4 print(int(number_of_oranges/number_of_people)) print(int(number_of_oranges%number_of_people)) sentence = "This is a string" print(sentence) print(type(sentence)) age = 34 if age < 12: print('Deny Entry') elif age < 18: print('Ask for parent\'s consent letter') else: print('Let in') age = 11 if age < 12: print('Deny Entry') elif age < 18: print('Ask for parent\'s consent letter') else: print('Let in') age = 11 if age < 18: print('Deny Entry') elif age < 12: print('Ask for parent\'s consent letter') else: print('Let in') age = 14 if age < 12: print('Deny Entry') elif age < 18: print('Ask for parent\'s consent letter') else: print('Let in') age = 12 if age <= 12: print('Deny Entry') elif age < 18: print('Ask for parent\'s consent letter') else: print('Let in') name = input("What is your name?") print(f"Hello {name}")
# Collaborators (including web sites where you got help: (enter none if you didn't need help) # none print("Hello welcome to madlibs! You ready?") input() print("Great lets get started!") adjective = input("type an adjective ") nationality = input("type a nationality ") person = input("type a person ") noun = input ("type a noun ") adjective2 = input("type an adjective ") noun2 = input("type a noun ") adjective3 = input("type an adjective ") adjective4 = input("type an adjective ") plural_noun = input("type a plural noun ") noun3 = input("type a noun ") number = input("type a number ") shapes = input("type a shape ") food = input("type a food ") food2 = input("type a food ") number2 = input("type a number ") print("Pizza was invented by " + adjective + " " + nationality + " chef named " + person + ".") print(" To make a pizza, you need to take a lump of " + noun + ", and make a thin, round " + adjective2 + " " + noun2 + ".") print(" Then you cover it with " + adjective3 + " sauce, " + adjective4 + " cheese, and fresh chopped " + plural_noun + ".") print(" Next you have to bake it in a very hot " + noun3 + ". When it is done, cut it into " + number + " " + shapes) print(" Some kids like " + food + " pizza the best, but my favorite is the " + food2 + " pizza.") print(" If i could, I would eat pizza " + number2 + " times a day!")
import copy class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def sortList(self, head): if not head: return None val_list = [] while head: val_list.append(head.val) head = head.next val_list = sorted(val_list) head = ListNode(val_list[0]) curr = head for i in val_list[1:]: curr.next = ListNode(i) curr = curr.next return head def sortList2(self, head): if not head or not head.next: return head # termination. # cut the LinkedList at the mid index. slow, fast = head, head.next while fast and fast.next: fast, slow = fast.next.next, slow.next mid, slow.next = slow.next, None # save and cut. # recursive for cutting. left, right = self.sortList2(head), self.sortList2(mid) # merge `left` and `right` linked list and return it. h = res = ListNode(0) while left and right: if left.val < right.val: h.next, left = left, left.next else: h.next, right = right, right.next h = h.next h.next = left if left else right return res.next def maxArea(self, height): start, end = 0, len(height) - 1 res = 0 while start < end: res = max(min(height[start], height[end]) * (end-start), res) if height[start] < height[end]: start += 1 else: end -= 1 return res def isPalindrome(self, x): return True if str(x) == ''.join(list(reversed(str(x)))) else False def myAtoi(self, str): str = str + 'p' _range = [-2 ** 31, 2 ** 31 - 1] symbol = ['-', '+'] result = [] for i in range(len(str)): if i == len(str) - 1: break if str[i] != ' ' and not str[i].isdigit() and len(result) == 0 and (str[i] not in symbol or not str[i+1].isdigit()): print(i) break if str[i].isdigit() or (str[i] in symbol and str[i+1].isdigit() and len(result) == 0): result.append(str[i]) if not str[i+1].isdigit(): break if result: result = int(''.join(result)) if result > _range[1]: return _range[1] elif result < _range[0]: return _range[0] else: return result else: return 0 def generateMatrix(self, n): l = [0 for _ in range(n)] self.map = [l.copy() for _ in range(n)] self.value = 1 self.func(0, n-1) return self.map def func(self, start, end): if start > end: return if start == end: self.map[start][end] = self.value return for i in range(start, end): self.map[start][i] = self.value self.value += 1 for i in range(start, end): self.map[i][end] = self.value self.value += 1 for i in range(end, start, -1): self.map[end][i] = self.value self.value += 1 for i in range(end, start, -1): self.map[i][start] = self.value self.value += 1 self.func(start+1, end-1) def longestcommonsubsequence(self, str1, str2): m, n = len(str1), len(str2) dp = [[0] * (n+1) for _ in range(m+1)] s = [[0] * (n+1) for _ in range(m+1)] for i in range(1, m+1): for j in range(1, n+1): if str1[i-1] == str2[j-1]: dp[i][j] = dp[i-1][j-1] + 1 s[i][j] = 1 else: dp[i][j] = max(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]) if dp[i][j] == dp[i][j-1]: s[i][j] = 2 elif dp[i][j] == dp[i-1][j]: s[i][j] = 3 rs = [] i, j = m, n while i >= 1 and j >= 1: if s[i][j] == 1: rs.append(str1[i-1]) i = i-1 j = j-1 elif s[i][j] == 2: j = j-1 elif s[i][j] == 3: i = i-1 else: i = i-1 j = j-1 return ''.join(reversed(rs)) # return dp[-1][-1] def solveNQueens(self, n): map = [['.'] * n for _ in range(n)] rs = [] self.next_queen(map, 0, rs) for item in rs: for row in range(len(item)): item[row] = ''.join(item[row]) return rs def next_queen(self, map, row, rs): n = len(map) if row == n: rs.append(copy.deepcopy(map)) for i in range(n): if self.queeen_valid(map, row, i): map[row][i] = 'Q' self.next_queen(map, row+1, rs) map[row][i] = '.' def queeen_valid(self, map, row, col): for i in range(row): if map[i][col] == 'Q': return False for i in range(row+1): if col - i >= 0 and map[row-i][col-i] == 'Q': return False if col + i <= len(map)-1 and map[row-i][col+i] == 'Q': return False return True def crackSafe(self, n, k): pass if __name__ == '__main__': aa = Solution() print(aa.solveNQueens(4))
""" 回溯模板 result = [] def backtrack(路径, 选择列表): if 满足结束条件: result.add(路径) return for 选择 in 选择列表: 做选择 backtrack(路径, 选择列表) 撤销选择 """ # 全排列 list = [1, 2, 3] ret = [] ret.extend(list) def func(pp, ret): if len(pp) == len(list): print(pp) for i, va in enumerate(ret): pp.append(va) temp = ret[:] temp.pop(i) func(pp[:], temp) pp.pop(-1) func([], ret)
# 最常见的形式,采用左右闭区间(<=, +1 -1都于此有关) def binarySearch(nums, target): left, right = 0, len(nums) - 1 while left <= right: mid = (right+left)//2 if nums[mid] == target: return mid elif nums[mid] < target: left = mid + 1 else: right = mid - 1 return -1 # 找寻左边界 def leftboundSearch(nums, target): left, right = 0, len(nums) - 1 while left <= right: mid = (right+left)//2 if nums[mid] == target: right = mid - 1 elif nums[mid] < target: left = mid + 1 else: right = mid - 1 if left == len(nums) or nums[left] != target: return -1 return left def rightboundSearch(nums, target): left, right = 0, len(nums) - 1 while left <= right: mid = (right+left)//2 if nums[mid] == target: left = mid + 1 elif nums[mid] < target: left = mid + 1 else: right = mid - 1 if nums[right] != target or right == -1: return -1 return right a = [1,2,2,2,3,4,5,5] print(rightboundSearch(a, 5))
def get_numbers_list(number_length, digit): table = [] for i in range(0, 2**number_length): if '{0:0{1}b}'.format(i, number_length)[digit] == '1': table.append(i) return table def is_binary_one(i, table): while True: print "\n\nTable {0}: {1}".format(i, table) answer = raw_input('Is your number in the above table? ') if answer in ('y', 'ye', 'yes'): return True if answer in ('n', 'no', 'nop', 'nope'): return False print """\nAnswer must be 'yes' or 'no'!""" def main(): binary_length = int(raw_input("\nThink of a secret number. Please provide the number of digits of this number in binary: ")) secret_number_list = [1 for i in range(binary_length)] for i in range(1, binary_length + 1): numbers_list = get_numbers_list(binary_length, -i) is_binary = is_binary_one(i, numbers_list) secret_number_list[-i] = '1' if is_binary else '0' print "secret_number_list:", secret_number_list secret_number = ''.join(secret_number_list) print "\nYou have selected number {}".format(int(secret_number, 2)) raw_input("\nPress any key to exit.") if __name__ == '__main__': main()
from collections import defaultdict # Setting up Tuple of Tuples classes = ( ('V', 1), ('VI', 1), ('V', 2), ('VI', 2), ('VI', 3), ('VII', 1), ) # Calling for a defaultdict list rollno = defaultdict(list) # For loop to append name with 'id' numbers for name, id in classes: rollno[name].append(id) # printing List print(rollno) # Output: # defaultdict(<class 'list'>, {'V': [1, 2], 'VI': [1, 2, 3], 'VII': [1]})
from tkinter import * from tkinter import ttk from tkinter import messagebox import random class Application(Frame): def __init__(self, master): super(Application, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): #enter name label r0 c0 [1] Label(self, text="Enter a name:", ).grid(row=0, column=0, sticky="w") #student entry r0 c1 [2] self.student_entry = Entry(self, width=14) self.student_entry.grid(row=0, column=1, sticky="w") #add button r1 c0-2(centered) [3] self.add_button = Button(self, text="Add", command=self.add) self.add_button.grid(row=1, column=0, columnspan = 2) #horizontal separator r0 c0-2 [4] ttk.Separator(self, orient='horizontal' ).grid(row=2, column=0, columnspan=3, sticky="ew", pady=7) #list of students label r3 c0 [5] Label(self, text="List of students:" ).grid(row=3, column=0, sticky="w") #listbox? r4-5 c0-1 [6] #separator r4 c2 [7] self.student_box = Listbox(self) self.scrollbar = Scrollbar(self.student_box, orient=VERTICAL) self.student_box.config(yscrollcommand=self.scrollbar.set) self.scrollbar.config(command=self.student_box.yview) self.student_box.grid(row=4, rowspan=2, column=0, columnspan=2, sticky=N+E+S+W) self.student_box.columnconfigure(0, weight=1) self.scrollbar.grid(row=4, column=2, sticky=N+S) self.student_box.bind("<<ListboxSelect>>", self.sel_student) #student selected label r6 c0 [8] Label(self, text="Student selected:" ).grid(row=6, column=0, sticky="w") #student actually selected r6 c1 [9] self.student_selected = Label(self, text="<no one>") self.student_selected.grid(row=6, column=1, sticky="w") #remove button r7 c0-2(centered) [10] self.remove_button = Button(self, text="Remove", command=self.remove) self.remove_button.grid(row=7, column=0, columnspan=2) #horizontal separator r8 c0-2 [11] ttk.Separator(self, orient='horizontal' ).grid(row=8, column=0, columnspan=3, sticky="ew", pady=7) #random student label r9 c0 [12] Label(self, text="Random student:" ).grid(row=9, column=0, sticky="w") #generated student r9 c1 [13] self.gen_student = Label(self, text="<no one>") self.gen_student.grid(row=9, column=1, sticky="w") #generate button r10 c0-2 [14] self.gen_button = Button(self, text="Generate!", command=self.generate) self.gen_button.grid(row=10, column=0, columnspan=2) #total of 14 widgets. def add(self): contents = self.student_entry.get() if contents.strip(): self.student_box.insert(END, contents) self.student_entry.delete(0, END) else: messagebox.showerror( "Error!", "Cannot enter a blank student." ) return def remove(self): try: selection = self.student_box.curselection() self.student_box.delete(selection[0]) self.student_selected["text"] = "<no one>" except IndexError: if self.student_box.size() == 0: messagebox.showerror( "Error!", "There is nothing else to delete!" ) else: messagebox.showerror( "Error!", "You have not selected anything to delete." ) def generate(self): temp_list = list(self.student_box.get(0, END)) if len(temp_list) not in (0, 1): choice = random.choice(temp_list) self.gen_student["text"] = choice else: if len(temp_list) == 0: messagebox.showerror( "Error!", "There are no students to pick from!" ) elif len(temp_list) == 1: messagebox.showerror( "Error!", "You have only one student to pick from!" ) def sel_student(self, event): try: widget = event.widget selection = widget.curselection() value = widget.get(selection[0]) self.student_selected["text"] = value except: self.student_selected["text"] = "<no one>" root = Tk() w = 192 # width for the Tk root h = 250 # height for the Tk root ws = root.winfo_screenwidth() # width of the screen hs = root.winfo_screenheight() # height of the screen # calculate x and y coordinates for the Tk root window x = (ws/2) - (w/2) y = (hs/2) - (h/2) - 100 root.title("RSG") root.geometry('%dx%d+%d+%d' % (w, h, x, y)) root.resizable(width=False, height=False) app = Application(root) root.mainloop()
''' Created on 20-Mar-2019 @author: sourav nandi ''' def factors(n): l=[] for i in range(1,n+1): if(n%i==0): l.append(i) return l try: n=input() if(int(n)<=1000): l=factors(int(n)) if(l==[1,int(n)]): print("yes") else: print("no") else: print("no") except: print("no")
import random def rand5(): return random.randint(1, 5) def rand7(): # Implement rand7() using rand5() while (True): i = (rand5()-1)*5+rand5() if i<=21: return (i)%7+1 print ('Rolling 7-sided die...') print (rand7())
import unittest def find_rotation_point(lists): n = len(lists)-1 l = 0 while n >= l: y = int (l + (n - l)/2) if lists[y-1] >= lists[n] and lists[y] <= lists[n]: return y elif lists[y] > lists[n]: l = y+1 else: n = y-1 # Tests class Test(unittest.TestCase): def test_syall_list(self): actual = find_rotation_point(['cape', 'cake']) expected = 1 self.assertEqual(actual, expected) def test_yediuy_list(self): actual = find_rotation_point(['grape', 'orange', 'pluy', 'radish', 'apple']) expected = 4 self.assertEqual(actual, expected) def test_large_list(self): actual = find_rotation_point(['ptoleyaic', 'retrograde', 'supplant', 'undulate', 'xenoepist', 'asyyptote', 'babka', 'banoffee', 'engender', 'karpatka', 'othellolagkage']) expected = 5 self.assertEqual(actual, expected) # Are we yissing any edge cases? unittest.yain(verbosity=2)
from abc import ABC, abstractmethod class CaffeineBeverage(ABC): def prepare_recipe(self): self.boil_water() self.brew() self.pour_in_cup() if self.customer_wants_condiments(): self.add_condiments() def boil_water(self): print('Boiling water') def pour_in_cup(self): print('Pouring beverage in cup') @abstractmethod def brew(self): pass @abstractmethod def add_condiments(self): pass def customer_wants_condiments(self): return True class Coffee(CaffeineBeverage): def brew(self): print('Brewing coffee grind') def add_condiments(self): print('Adding milk and sugar') def customer_wants_condiments(self): choice = input('Do you want milk and sugar in your coffee? (reply Y/N)') return choice.lower() == 'y' class Tea(CaffeineBeverage): def brew(self): print('Steeping tea leaves') def add_condiments(self): print('Adding lemon') if __name__ == '__main__': t = Tea() c = Coffee() t.prepare_recipe() c.prepare_recipe()
from abc import abstractmethod # According to ISP # Many specific interfaces are better than one # do it all interface. class Printer: @abstractmethod def print(self, document): pass class Scanner: @abstractmethod def scan(self, document): pass # same for Fax, etc. # Here defining Printer and Scanner Interfaces separately # we can use them separately or together according to the usecase. class MyPrinter(Printer): def print(self, document): print(document) class Photocopier(Printer, Scanner): def print(self, document): print(document) def scan(self, document): pass # something meaningful
import discord # api wrapper for the discord api import os # to work with environment variables import requests # make a http request to api import json # to process data returned from api import random # for bot to choose message randomly from replit import db from keep_alive import keep_alive # import the keep_alive function from the keep_alive.py file # create an instance of the client using methods from the discord.py library # GENERAL STEP = (create a new object) using library func client = discord.Client() my_secret = os.environ['TOKEN'] # grab the token from environment variable # words for bot to look out sad_words = ["sad", "depressed", "unhappy", "anxious", "miserable", "worse", "depressing", "bad", "pissed", "unexceptable"] # encouraging words for bot to reply when detects sad words # its called initial because user will be able to add more encouragements to the bot in discord initial_encouragements = [ "Cheer up!", "Hang in there.", "You got this!" ] # determine if bot will be responding to sad words if "responding" not in db.keys(): db["responding"] = True # helper function def get_quote(): # this function will be called to return an inspirational quote from an api # use the requests module to get the data from the api # this line makes a get request to the api # GENERAL STEP: (create a new object) using library func response = requests.get("https://zenquotes.io/api/random") # convert response to json # GENERAL STEP: (create a new object) using library func json_data = json.loads(response.text) # access the specific quote from json object using specific KEY and save the value to the KEY to a new variable # GENERAL STEP: (create a new variable) quote = json_data[0]['q'] # add author name to the quote # which can be combined with line 28, but separate for learning sake # GENERAL STEP: (modify existing variable) quote += " -" + json_data[0]['a'] return(quote) # before we add another command for the bot, let's add two helpful functions: add_helpful_message and del_helpful_message def add_encouragement(encouraging_message): # check if encouragements key is in database if "encouragements" in db.keys(): encouragements = db["encouragements"] encouragements.append(encouraging_message) db["encouragements"] = encouragements # save the updated list back to db else: db["encouragements"] = encouraging_message # create a new key value pair in db def delete_encouragement(index): encouragements = db["encouragements"] # check if index is valid if len(encouragements) > index: del encouragements[index] db["encouragements"] = encouragements # update db # discord.py is an asynchronous library, so we need to work with callback # callback = a function that is called when something else happens # we are writing callbacks below for the discord.py library to call # these function names are specifically form the discord.py library # the library looks for different specific functions to know what to do when certain event happens # use Client.event decorator to register an event @client.event async def on_ready(): # this event happens (will be called) when the bot is ready to start being used print('We have logged in as {0.user}'.format(client)) @client.event async def on_message(message): # we dont want this event to trigger if the message is from ourselves, the bot if message.author == client.user: return msg = message.content # because we will use message.content many times so we create a variable for that value if msg.startswith('$hello'): # check to see if the message starts with a specific string (our command) # if true, the bot will response 'Hello!' await message.channel.send('Hello!') if msg.startswith('$inspire'): await message.channel.send(get_quote()) options = initial_encouragements # check to see if database has additional user added encouragements if "encouragements" in db.keys(): options = options + list(db["encouragements"]) # concatenating two lists; repl.it stores list as ObservedList, so we need to cast it to list in order to use list concatenation if db["responding"]: # go through every `word` in `sad_words` and check if any of the current `word` is in the `msg` if any(word in msg for word in sad_words): # found a word in the sad_words list in the message await message.channel.send(random.choice(options)) # respond an encouraging message # detects to see if user wants to add a message if msg.startswith('$add'): # parse msg so we don't add the command $new into our db # encouraging_message = msg.split(" ")[1:] encouraging_message = msg.split("$add ",1)[1] # a better approach that above # encouraging_message has a ObservedList type add_encouragement(encouraging_message) # this msg is added to the list of all encouraging message await message.channel.send("New encouraging message added.") # return message so user knows that the message is added # check if user wants to delete a message, ex: $del 0 if msg.startswith('$del'): # user passed in the index of the message it wants to delete encouragements = [] # this list will be returned to the user if "encouragements" in db.keys(): index = int(msg.split("$del",1)[1]) # get index user input; no need include space after command because we convert it to an integer delete_encouragement(index) encouragements = list(db["encouragements"]) # get the updated encouragements list to return to user await message.channel.send(encouragements) # check if user wants to list all encouragements if msg.startswith("$list"): encouragements = [] # because db could contain no encouragement if "encouragements" in db.keys(): encouragements = list(db["encouragements"]) await message.channel.send(encouragements) # check if user wants the bot to respond to sad words or not if msg.startswith("$responding"): # user input: $responding true / $responding false value = msg.split("$responding ",1)[1] if value.lower() == "true": db["responding"] = True await message.channel.send("Responding is on.") else: db["responding"] = False # if user enters anything but true set bot to not responding await message.channel.send("Responding is off.") keep_alive() # now we need to run the bot # within the run method, we need to put our bot's token (password) client.run(my_secret) ''' feature #1 1. anyone should be able to add stuff for the bot to use 2. the stuff that the user gives to the bot will be stored in a DATABASE, so those stuff will save even if you stop and start your bot!!!!! ''' ''' feature #2 working with API 1. import python modules: requests, json 2. add a get quote function 3. the bot will then call the function request module: allows our code to make a http request to get data from an api json module: api returns a json, which this module will allow us to work with the json data returned by an api ''' ''' feature #3 bot will recognize sad words that user typed and then reply with encouragement words 1. create a python list of sad words for the bot to look for 2. create a python list of encouragement words to reply 3. when we receive a message, check the message to see if it contains sad words 4. use a database to store user submitted messages so user will be able to add more encouragement words for bot to display 5. repl uses a key-value store ''' # by default, every project on repl.it is public so everyone will be able to see secrets like password # so we need to hide these secrets using environment variable # 1. create a new file called .env # 2. create a variable like TOKEN and assign the token to the variable # 3. import the .env file into the code file that you want to use isinstance # code: `import os` # 4. access the token # code: `os.getenv('VAR_NAME') # if the repl browser window is closed, the bot will stop running. # so, we have to setup a web server in repl, which will continue running even after the tab is # however, repl.it will only run the web server for an hour before sleeping if it receives no request. # so a workaround is to use another app called UptimeRobot to ping the web server every say 5 minutes so repl will not sleep the web server # 1. create another .py file and add flask code # 2. import the web server.py file into our bot's main.py file # 3. run the function in the web server file to setup the web server # 4. once the web server is running, get the url to the server # 5. ping the url with UptimeRobot
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 8 06:25:58 2018 @author: habhavsar """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None q = queue.Queue() q.put(1) while not q.empty(): print(q.get()) class Solution: #import queue def minDepth(self, root): if root is None: return 0 if root.left == None or root.right == None: return 1 + self.minDepth(root.left) + self.minDepth(root.left) return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
import sys def output_func(arr, threshold, limit): sum_val = 0 for i, element in enumerate(arr): #Subtract the threshold val = max(0, element - threshold) #If we reached the limit, only print zeros if (sum_val == limit): print(0) elif sum_val + val < limit: #If not, and the new value is still less than limit, add it to sum sum_val += val print(val) else: #Else if greater or equals to limit, only print the differece which is the last portion and make sum_val = limit print(limit - sum_val) sum_val = limit print(sum_val) def isfloat(val): try: float(val) return True except ValueError: return False if __name__ == "__main__": arr = [] if isfloat(sys.argv[1]) and isfloat(sys.argv[2]): threshold = float(sys.argv[1]) limit = float(sys.argv[2]) else: exit() #Check threshold and limit within the specified ranges. if not ( 0 <= threshold <= 1000000000.0 and 0 <= limit <= 1000000000.0): exit() #Read form the file line by line for line in iter(sys.stdin.readline, ''): line = line.replace("\n", "") if isfloat(line): line = float(line) if 0 <= line <= 1000000000.0: arr.append(line) else: exit() else: exit() #Make sure that the input does not exceed 100 if len(arr) > 100: exit() output_func(arr, threshold, limit)
__author__ = 'Kalyan' max_marks = 20 problem_notes = ''' Given a sequence [a1, ... ,an], the diff sequence is [|a1- a2|, |a2-a3|, .... |an -a1|] (loop around at the end). (|x| denotes absolute value of x) A sequence of 0s is called a null sequence. If we apply the diff process repeatedly on a given sequence, it may or may not end in a null sequence. For e.g. - [1, 1, 1] becomes [0, 0, 0] in 1 step. - [1, 1, 0] loops and never becomes a null sequence. Write a routine to find out the number of steps it takes for a sequence to end in a null sequence. If it does not end (due to some repetition), then return -1. Notes: 1. Assume nums is a valid list of integers. 2. Refer to the testcase for an example. 3. Write your own tests and edge cases, don't rely only on the examples given. 4. Feel free to write additional helper methods as appropriate. 5. Treat this as a coding problem, don't try to find O(1) maths formulas :) ''' # assume numbers is a valid list of numbers def allone(l): for i in range(0,len(l)): if l[i]!=0: return 0 return 1 def alleq(l): for i in range(0,len(l)-1): if l[i]!=l[i+1]: return 0 return 1 def count_steps(numbers): diff=[] c=0 if type(numbers).__name__!="list": return ValueError raise ValueError if(allone(numbers)): return 0 for i in range(0,len(numbers)): if i==len(numbers)-1: diff.append(numbers[len(numbers)-1]-numbers[0]) else: diff.append(numbers[i]-numbers[i+1]) if allone(diff): return c+1 elif alleq(diff): return c+2 else: return -1 # one basic test given, write more exhaustive tests print(type(count_steps((1,2,3))).__name__)
inputRow = int(input("Masukkan Angka : ")) for x in range(1, inputRow+1): for y in range(1, x + 1): print(x * y, end=" ") print()
from datetime import datetime import getpass import locale import module statusMasuk = True def formatRupiah(angka): locale.setlocale(locale.LC_NUMERIC, 'IND') rupiah = locale.format_string("%.*f", (0, angka), True) return "Rp. " + rupiah while statusMasuk: print("\n1. Login") print("2. Register") inputMenu = int(input("Masukkan Menu = ")) while inputMenu != 1 and inputMenu != 2: print("Menu tidak valid") inputMenu = int(input("Masukkan Menu = ")) authMod = module.module("user") produkMod = module.module("produk") laporanMod = module.module("laporan") while inputMenu == 1 or inputMenu == 2: if inputMenu == 1: print("\nLogin") inputUsername = str(input("Masukkan Username = ")) inputPassword = getpass.getpass(prompt="Masukkan Password = ") statusLogin = False statusLogout = False dataLogin = {} pilihanRegister = 't' for dataUser in authMod.dataRead(): if dataUser['username'] == inputUsername and dataUser['password'] == inputPassword: dataLogin = dataUser statusLogin = True pilihanRegister = 't' if statusLogin == False and statusLogout == False: print("Username atau Password salah") pilihanRegister = str(input("Tidak ada akun, Register? (y/n)")) if pilihanRegister == 'y': inputMenu = 2 daftarBelanjaPembeli = [] while statusLogin: if dataLogin['status'] == 1: print("\nInfo Produk\n") print("{:<6} {:<15} {:<10} {:<15}".format('No', 'Nama', 'Jumlah Beli', 'Jumlah Harga')) for idx, dataProduk in enumerate(produkMod.dataRead()): print("{:<6} {:<15} {:<10} {:<15}".format(idx + 1, dataProduk['nama'], dataProduk['stock'], formatRupiah(dataProduk['harga']))) print("\nSelamat Datang", dataLogin['nama']) print("\n1. Tambah Produk") print("2. Ubah Produk") print("3. Hapus Produk") print("4. Laporan Belanja Pembeli") print("5. Logout") inputMenuData = int(input("Masukkan Menu = ")) while inputMenuData > 5: print("Menu tidak valid") inputMenuData = int(input("Masukkan Menu = ")) if inputMenuData == 1: inputNamaProduk = str(input("Masukkan Nama Produk = ")) inputStockProduk = int(input("Masukkan Stock Produk = ")) inputHargaProduk = int(input("Masukkan Harga Produk = ")) dataProduk = { "nama": inputNamaProduk, "stock": inputStockProduk, "harga": inputHargaProduk } print(produkMod.saveData(dataProduk, 1, 0)) elif inputMenuData == 2: print("Info Produk\n") print("{:<6} {:<15} {:<10} {:<10}".format('No', 'Nama', 'Stock', 'Harga')) for idx, dataProduk in enumerate(produkMod.dataRead()): print("{:<6} {:<15} {:<10} {:<10}".format(idx + 1, dataProduk['nama'], dataProduk['stock'], formatRupiah(dataProduk['harga']))) inputProduk = int(input("\nMasukkan Nomor Produk = ")) while inputProduk > len(produkMod.dataRead()): print("Produk tidak ada!!!") inputProduk = int(input("Masukkan Nomor Produk = ")) inputStockProduk = int(input("Masukkan Stock Produk = ")) inputHargaProduk = int(input("Masukkan Harga Produk = ")) dataProduk = { "stock": inputStockProduk, "harga": inputHargaProduk } print(produkMod.saveData(dataProduk, 2, inputProduk)) elif inputMenuData == 3: print("Info Produk\n") print("{:<6} {:<15} {:<10} {:<10}".format('No', 'Nama', 'Stock', 'Harga')) for idx, dataProduk in enumerate(produkMod.dataRead()): print("{:<6} {:<15} {:<10} {:<10}" .format(idx + 1, dataProduk['nama'], dataProduk['stock'], formatRupiah(dataProduk['harga']))) inputProduk = int(input("\nMasukkan Nomor Produk = ")) while inputProduk > len(produkMod.dataRead()): print("Produk tidak ada!!!") inputProduk = int(input("Masukkan Nomor Produk = ")) print(produkMod.deleteData(inputProduk)) elif inputMenuData == 4: print() print("{:<6} {:<15} {:<15} {:<15}".format('No', 'Tanggal', 'Jam', 'Jumlah Uang')) for idx, data in enumerate(laporanMod.dataRead()): print("{:<6} {:<15} {:<15} {:<15}" .format(idx + 1, data['tanggal'], data['waktu'], formatRupiah(data['tunai']))) print() inputMenuLaporan = int(input("Masukkan Nomor Laporan = ")) while inputMenuLaporan > len(laporanMod.dataRead()): print("Nomor Laporan Tidak Ada!!!") inputMenuLaporan = int(input("Masukkan Nomor Laporan = ")) print() print('-------------------------------------') print('\t INVEST MART') print('=====================================') print("{:<12} {:<15} {:<15}".format('Tgl.', laporanMod.dataRead()[inputMenuLaporan - 1]['tanggal'], laporanMod.dataRead()[inputMenuLaporan - 1]['waktu'])) print('=====================================') jumlahStockBelanja = 0 jumlahHargaBelanja = 0 for idx, itemBelanja in enumerate(laporanMod.dataRead()[inputMenuLaporan - 1]['data']): print("{:<16} {:<11} {:<15}".format(itemBelanja['nama'], itemBelanja['stock'], formatRupiah(itemBelanja['harga']))) jumlahStockBelanja += itemBelanja['stock'] jumlahHargaBelanja += itemBelanja['harga'] print('-------------------------------------') print("{:<16} {:<11} {:<15}".format('Total Item', jumlahStockBelanja, formatRupiah(jumlahHargaBelanja))) print("{:<16} {:<11} {:<15}".format('Tunai', '', formatRupiah( laporanMod.dataRead()[inputMenuLaporan - 1]['tunai']))) print("{:<16} {:<11} {:<15}".format('Kembalian', '', formatRupiah( laporanMod.dataRead()[inputMenuLaporan - 1]['tunai'] - jumlahHargaBelanja))) print('=====================================') print('TERIMA KASIH. SELAMAT BELANJA KEMBALI') print('-------------------------------------') elif inputMenuData == 5: statusLogin = False statusLogout = True inputMenu = 3 else: print("\nInfo Produk\n") print("{:<6} {:<15} {:<10} {:<10}".format('No', 'Nama', 'Stock', 'Harga')) for idx, dataProduk in enumerate(produkMod.dataRead()): print("{:<6} {:<15} {:<10} {:<10}" .format(idx + 1, dataProduk['nama'], dataProduk['stock'], formatRupiah(dataProduk['harga']))) print("\nSelamat Datang", dataLogin['nama']) print("\nBelanja Pembeli\n") print("{:<6} {:<15} {:<10} {:<10}".format('No', 'Nama', 'Stock', 'Harga')) for idx, itemBelanja in enumerate(daftarBelanjaPembeli): print("{:<6} {:<15} {:<10} {:<10}" .format(idx + 1, itemBelanja['nama'], itemBelanja['stock'], formatRupiah(itemBelanja['harga']))) print("\n1. Tambah Produk Belanja") print("2. Hapus Produk Belanja") print("3. Bayar Belanja") print("4. Logout") inputMenuData = int(input("Masukkan Menu = ")) while inputMenuData != 1 and inputMenuData != 2 and inputMenuData != 3 and inputMenuData != 4: print("Menu tidak valid") inputMenuData = int(input("Masukkan Menu = ")) if inputMenuData == 1: mengulangTambahProduk = 'y' while mengulangTambahProduk == 'y': inputProdukBelanja = int(input("Masukkan Nomor Produk = ")) while inputProdukBelanja > len(produkMod.dataRead()): print("Produk Tidak Ada!!!") inputProdukBelanja = int(input("Masukkan Nomor Produk = ")) inputStockBelanja = int(input("Masukkan Jumlah Pembelian Produk = ")) while inputStockBelanja > produkMod.dataRead()[inputProdukBelanja - 1]['stock']: print("Jumlah melebihi stock!!!") print("Stock di produk", produkMod.dataRead()[inputProdukBelanja - 1]['nama'], 'adalah', produkMod.dataRead()[inputProdukBelanja - 1]['stock']) inputStockBelanja = int(input("Masukkan Jumlah Pembelian Produk = ")) jumlahHargaProduk = inputStockBelanja * produkMod.dataRead()[inputProdukBelanja - 1][ 'harga'] for idx, item in enumerate(daftarBelanjaPembeli): if produkMod.dataRead()[inputProdukBelanja - 1]['nama'] == item['nama']: del daftarBelanjaPembeli[idx] dictionaryProdukBelanja = { "id": inputProdukBelanja - 1, "nama": produkMod.dataRead()[inputProdukBelanja - 1]['nama'], "stock": inputStockBelanja, "harga": int(jumlahHargaProduk) } daftarBelanjaPembeli.append(dictionaryProdukBelanja) mengulangTambahProduk = str(input("Ingin menambah produk lagi? (y/n) : ")) elif inputMenuData == 2: inputNomorProduk = int(input("Masukkan Nomor Produk yang mau dihapus = ")) while inputNomorProduk > len(produkMod.dataRead()): print("Produk Tidak Ada!!!") inputNomorProduk = int(input("Masukkan Nomor Produk yang mau dihapus = ")) del daftarBelanjaPembeli[inputNomorProduk - 1] elif inputMenuData == 3: if len(daftarBelanjaPembeli) == 0: print("\nBelanjaan Kosong!!!") else: jumlahHargaBelanja = 0 for item in daftarBelanjaPembeli: jumlahHargaBelanja += item['harga'] inputUangPembeli = int(input("Masukkan Uang Pembeli = ")) while inputUangPembeli < jumlahHargaBelanja: print("Uang kurang!!!") inputUangPembeli = int(input("Masukkan Uang Pembeli = ")) print() print('-------------------------------------') print('\t INVEST MART') print('=====================================') print("{:<12} {:<15} {:<15}".format('Tgl.', datetime.today().strftime('%d-%m-%Y'), datetime.today().strftime('%H:%M:%S'))) print('=====================================') jumlahStockBelanja = 0 for idx, itemBelanja in enumerate(daftarBelanjaPembeli): print("{:<16} {:<11} {:<15}".format(itemBelanja['nama'], itemBelanja['stock'], formatRupiah(itemBelanja['harga']))) jumlahStockBelanja += itemBelanja['stock'] print('-------------------------------------') print("{:<16} {:<11} {:<15}".format('Total Item', jumlahStockBelanja, formatRupiah(jumlahHargaBelanja))) print("{:<16} {:<11} {:<15}".format('Tunai', '', formatRupiah(inputUangPembeli))) print("{:<16} {:<11} {:<15}".format('Kembalian', '', formatRupiah(inputUangPembeli - jumlahHargaBelanja))) print('=====================================') print('TERIMA KASIH. SELAMAT BELANJA KEMBALI') print('-------------------------------------') produkMod.simpanBelanja(daftarBelanjaPembeli, inputUangPembeli, datetime.today().strftime('%d-%m-%Y'), datetime.today().strftime('%H:%M:%S')) daftarBelanjaPembeli = [] elif inputMenuData == 4: statusLogin = False statusLogout = True inputMenu = 3 elif inputMenu == 2: print("\nRegister") inputNama = str(input("Masukkan Nama = ")) inputUsername = str(input("Masukkan Username = ")) inputPassword = str(input("Masukkan Password = ")) dataRegister = { "nama": inputNama, "username": inputUsername, "password": inputPassword, "status": 2 } print(authMod.authSave(dataRegister)) inputMenu = 1
jawab = 'y' def operatorTambah(angka1,angka2): return angka1+angka2 def operatorKurang(angka1,angka2): return angka1 - angka2 def operatorBagi(angka1,angka2): return angka1 / angka2 def operatorKali(angka1,angka2): return angka1 * angka2 while jawab == 'y': angkaPertama = int(input("Masukkan Angka Pertama = ")) angkaKedua = int(input("Masukkan Angka Kedua = ")) print() print("Pilih Operasi") print("1. Tambah") print("2. Kurang") print("3. Bagi") print("4. Kali") inpuMenu = int(input("Masukkan Menu Operasi = ")) while inpuMenu > 4: print("Menu tidak ada") inpuMenu = int(input("Masukkan Menu Operasi = ")) if inpuMenu == 1: print(angkaPertama,'+',angkaKedua,'=',operatorTambah(angkaPertama,angkaKedua)) elif inpuMenu == 2: print(angkaPertama,'-',angkaKedua,'=',operatorKurang(angkaPertama,angkaKedua)) elif inpuMenu == 3: print(angkaPertama,'/',angkaKedua,'=',operatorBagi(angkaPertama,angkaKedua)) elif inpuMenu == 4: print(angkaPertama,'*',angkaKedua,'=',operatorKali(angkaPertama,angkaKedua)) jawab = str(input("Ingin mengulang?(y/n) "))
import time, math # ------------------------------------------------------------------------------------------ # FUNCTIONS # ------------------------------------------------------------------------------------------ def create_sequences(parent_tree_position, parent_value, parent_bit_list): ''' Generates Collatz prefix sequences that take m steps to get to a given power of two. ''' global global_bit_list next_even_number = parent_value * 2 even_child_tree_position = parent_tree_position * 2 even_bit_list = parent_bit_list + [0] if even_child_tree_position >= 2 ** (sequence_length - 1): print(list(reversed(even_bit_list))) global_bit_list.append(list(reversed(even_bit_list))) else: create_sequences(even_child_tree_position, next_even_number, even_bit_list) next_odd_number = (parent_value - 1) / 3 # If the next odd number is going to be a fraction or even, stop going down that path. if next_odd_number % 1 != 0 or next_odd_number % 2 == 0: return odd_child_tree_position = (parent_tree_position * 2) + 1 odd_bit_list = parent_bit_list + [1] if odd_child_tree_position >= 2 ** (sequence_length - 1): print(list(reversed(odd_bit_list))) global_bit_list.append(list(reversed(odd_bit_list))) return else: create_sequences(odd_child_tree_position, int(next_odd_number), odd_bit_list) return # ------------------------------------------------------------------------------------------ # USER INPUT # ------------------------------------------------------------------------------------------ print() user_powers_checked = input('How many powers of two do you want to check? ') if not user_powers_checked.isdigit(): print('The powers checked must be a positive integer.\n') quit() elif float(user_powers_checked) == 0: print('The powers checked must be a positive integer.\n') quit() powers_list = [2**i for i in range(4,4+(2*int(user_powers_checked)),2)] user_sequence_length = input('Enter a sequence length: ') if not user_sequence_length.isdigit(): print('The sequence length must be a positive integer.\n') quit() elif float(user_sequence_length) == 0: print('The sequence length must be a positive integer.\n') quit() sequence_length = int(user_sequence_length) print() # ------------------------------------------------------------------------------------------ # CORE LOGIC # ------------------------------------------------------------------------------------------ start_time = time.time() global_bit_list = [] for starting_power in powers_list: starting_number = (starting_power - 1) // 3 print(starting_power) print('------------------------') create_sequences(1, starting_number, []) global_bit_list = list(set(tuple(sequence) for sequence in global_bit_list)) print() print('unique permutations:') print('------------------------') for sequence in sorted(global_bit_list): print(list(sequence)) print() up_down_permutations = len(global_bit_list) print('%i unique up-down permutations of length %i.' % (up_down_permutations, sequence_length)) print() print('runtime: %s' % (time.time() - start_time)) print()
import math import time # ------------------------------------------------------------------------------------------ # FUNCTIONS # ------------------------------------------------------------------------------------------ global_bit_list = [] def powers_of_two(n): """ Creates and returns a list of powers of two from which we will build our Collatz prefix sequences. """ powers = [] for i in range(4,n+8,2): powers.append(2**i) return(powers) def create_sequences(parent_tree_position, parent_value, parent_bit_list): """ Generates Collatz prefix sequences that take m steps to get to a given power of two. """ next_even_number = parent_value * 2 even_child_tree_position = parent_tree_position * 2 even_bit_list = parent_bit_list + [0] if(even_child_tree_position >= 2 ** (sequence_length - 1)): # print(list(reversed(even_bit_list))) global_bit_list.append(even_bit_list) else: create_sequences(even_child_tree_position, next_even_number, even_bit_list) next_odd_number = (parent_value - 1) / 3 # If the next odd number is going to be a fraction, stop going down that path. if(next_odd_number % 1 != 0 or next_odd_number % 2 == 0): return odd_child_tree_position = (parent_tree_position * 2) + 1 odd_bit_list = parent_bit_list + [1] if(odd_child_tree_position >= 2 ** (sequence_length - 1)): # print(list(reversed(odd_bit_list))) global_bit_list.append(odd_bit_list) return else: create_sequences(odd_child_tree_position, int(next_odd_number), odd_bit_list) return # ------------------------------------------------------------------------------------------ # USER INPUT # ------------------------------------------------------------------------------------------ # print("") # user_starting_power = input("Enter a starting power of two: ") # if(not user_starting_power.isdigit()): # print("The starting power must be a positive integer. \n") # quit() # elif(float(user_starting_power) == 0): # print("The starting power must be a positive integer. \n") # quit() # elif(((2 ** int(user_starting_power)) - 1) % 3 != 0): # print("There are no sequences of any length that reach %i. \n" % (2 ** int(user_starting_power))) # quit() # starting_power = 2 ** int(user_starting_power) # print("We are now looking for sequences that reach %i. \n" % (starting_power)) print("") user_powers_checked = input("How many powers of two do you want to check? ") if(not user_powers_checked.isdigit()): print("The powers checked must be a positive integer. \n") quit() elif(float(user_powers_checked) == 0): print("The starting power must be a positive integer. \n") quit() powers_checked = int(user_powers_checked) powers_list = powers_of_two(powers_checked) user_sequence_length = input("Enter a sequence length: ") if(not user_sequence_length.isdigit()): print("The sequence length must be a positive integer. \n") quit() elif(float(user_sequence_length) == 0): print("The sequence length must be a positive integer. \n") quit() sequence_length = int(user_sequence_length) # ------------------------------------------------------------------------------------------ # CORE LOGIC # ------------------------------------------------------------------------------------------ start_time = time.time() print("") for starting_power in powers_list: starting_number = int((starting_power - 1) / 3) create_sequences(1, starting_number, []) up_down_permutations = len(set(tuple(sequence) for sequence in global_bit_list)) print("%i unique up-down permutations of length %i." % (up_down_permutations, sequence_length)) print("") print("runtime: %s" % (time.time() - start_time)) print("")
import time start_time = time.time() sum_of_fifths = [] for number in range(2, ((9**5)*6)+1): sum_of_digits = 0 for i in range(len(str(number))): sum_of_digits += int(str(number)[i])**5 if sum_of_digits == number: sum_of_fifths.append(number) print() print('solution: '+ str(sum(sum_of_fifths))) print('runtime: %s sec' % (time.time() - start_time)) print()
import time start_time = time.time() a, b = 1, 1 hit = False while hit is False: b += 1 for delta_a in range(b-a): if (((a+delta_a)**2 + b**2)**0.5) + (a+delta_a) + b == 1000: hit = True a += delta_a print() print('a,b,c = '+str(a)+','+str(b)+','+str(int((a**2 + b**2)**0.5))) print('product of side lengths: '+ str(a * b * int(((a**2)+(b**2))**0.5))) print('runtime: '+str(time.time()-start_time)+' sec') print()
import time, matplotlib.pyplot as plt print() threshold = int(input('how many powers of 2 do you want to print? ')) start_time = time.time() sum_of_digits = [0] * (threshold+1) number_of_digits = [0] * (threshold+1) for number in range(threshold+1): power = 2 ** number sum_of_digits[number] = sum([int(digit) for digit in list(str(power))]) number_of_digits[number] = len(str(power)) # print(str(sum_of_digits[number])+', '+str(number_of_digits[number])) fig = plt.figure(figsize=(6,8)) fig.subplots_adjust(left=0.15, right=0.95, top=0.9, hspace=.5) sub1 = fig.add_subplot(2,1,1) sub1.scatter( range(threshold+1), sum_of_digits, color='k', s=1 ) sub1.set_xlabel('Power of 2') sub1.set_ylabel('Sum of Digits') sub1.set_title('Sum of Digits vs. Power of 2') sub2 = fig.add_subplot(2,1,2, sharex=sub1, sharey=sub1) sub2.scatter( range(threshold+1), number_of_digits, color='b', s=1 ) sub2.set_xlabel('Power of 2') sub2.set_ylabel('Number of Digits') sub2.set_title('Number of Digits vs. Power of 2') print('runtime: %s sec' % (time.time() - start_time)) print() plt.show()
import re from typing import Tuple import pandas as pd __all__ = ['sanitize_string', 'sanitize_string_column', 'extract_names'] __ALPHANUMERIC_REGEX = re.compile(r'[^0-9A-Za-z\s]') __SPACING_REGEX = re.compile(r'\s+') def sanitize_string(text: str, upper: bool = False, alphanumeric_only: bool = False, strip: bool = False, whitespace: bool = False) -> str: """ Function for conditionally sanitizing a string. :param text: str, the string to sanitize :param upper: bool, default False whether to convert the series to uppercase :param alphanumeric_only: whether to remove all non alpha-numeric characters :param strip: bool, default False whether to strip whitespace around the series :param whitespace: bool, default False whether to sanitize all whitespace characters to single spaces :return: text: str The sanitized string. """ if alphanumeric_only: text = re.sub(__ALPHANUMERIC_REGEX, ' ', text) if whitespace: text = re.sub(__SPACING_REGEX, ' ', text) if strip: text = text.strip() if upper: text = text.upper() return text def sanitize_string_column(series: pd.Series, upper: bool = False, alphanumeric_only: bool = False, strip: bool = False, whitespace: bool = False) -> pd.Series: """ Function for conditionally sanitizing string series in pandas. :param series: pd.Series, the pandas series containing strings to sanitize :param upper: bool, default False whether to convert the series to uppercase :param alphanumeric_only: whether to remove all non alpha-numeric characters :param strip: bool, default False whether to strip whitespace around the series :param whitespace: bool, default False whether to sanitize all whitespace characters to single spaces :return: series: pd.Series The sanitized Pandas series. """ if alphanumeric_only: series = series.str.replace(__ALPHANUMERIC_REGEX, ' ') if whitespace: series = series.str.replace(__SPACING_REGEX, ' ') if strip: series = series.str.strip() if upper: series = series.str.upper() return series def extract_names(text: str) -> Tuple[str, str, str, str]: """ Function for extracting names from a string. Assumes string spaces have been sanitized. :param text: :return: (first, last, first_last, full) A tuple containing the first name, last name, first name + last name combination, and the full name. """ ''' ''' if text.startswith('LT '): text = text.lstrip('LT ') if text.startswith('MR '): text = text.lstrip('MR ') if text.startswith('MS '): text = text.lstrip('MS ') if text.startswith('MRS '): text = text.lstrip('MRS ') if text.startswith('MISS '): text = text.lstrip('MISS ') first, last, first_last, full = None, None, None, text n_spaces = text.count(' ') if n_spaces == 0: first = text elif n_spaces == 1: first, last = text.split(' ') first_last, full = text, text elif n_spaces > 1: first, middle, last = text.split(' ')[:3] first_last, full = ' '.join([first, last]), ' '.join([first, middle, last]) return first, last, first_last, full
import numpy as np import scipy.special as sp """ The focus of the test is the proportion of zeroes and ones for the entire sequence. The purpose of this test is to determine whether the number of ones and zeros in a sequence are approximately the same as would be expected for a truly random sequence. The test assesses the closeness of the fraction of ones to ½, that is, the number of ones and zeroes in a sequence should be about the same. All subsequent tests depend on the passing of this test. Note that if the P-value were small (< 0.01), then this would be caused by s or being large. Large positive values of s are indicative of too many ones, and large negative values of s are indicative of too many zeros. """ MIN_BITS = 100 class Monobit: def __init__(self, bits, p_threshold = 0.01): self.bits = bits self.p_threshold = p_threshold self.n = len(bits) self.ones = None self.zeroes = None self.diff = None # difference between the number of 0s and 1s self.absdiff = None # absolute value of the difference self.excess = None # which bit is in excess, 0s or 1s self.s = None # s_obs is the test statistic self.p = None # p_value = erfc(s_obs / sqrt(2)) self.success = None self.test_run = False self.check_enough_bits() if self.enough_bits: self.run_test() def check_enough_bits(self): self.enough_bits = MIN_BITS <= self.n def run_test(self): self.ones = sum(self.bits) self.zeroes = len(self.bits) - sum(self.bits) self.diff = self.ones-self.zeroes self.absdiff = abs(self.diff) self.excess = 1 if self.diff == self.absdiff else 0 self.s = self.absdiff/np.sqrt(self.n) self.p = sp.erfc(self.s/np.sqrt(2.0)) self.success = self.p >= self.p_threshold self.test_run = True if __name__ == '__main__': import sys sys.path.append('../') import utils bits = utils.e[:1000000] M = Monobit(bits) print(M.p) # p = 0.953749
import re from app import lista class instrumento(): def __init__(self, tipo): self.tipo = tipo def tipoInstrumento(self): if self.tipo == "viento": return 1 elif self.tipo=="cuerda": return 2 else: return 3 class Guitarra(instrumento): def __init__(self, tipo, cuerdas): super().__init__(tipo) self.__tipo= tipo #privado self.__cuerdas= cuerdas#privado def tocar(self): for x in range(0,self.__cuerdas,1): print("Usted esta tocando", x) def __str__(self): return "Este objeto sirve para poder tener una clase" class fecha(object): #esta es una clase de neuvo estilo que permite usar metodos estaticos, propiedades, descriptores def __init__(self, dia): self.__dia= dia def getDia(self): return self.__dia def setDia(self, dia): if self.__dia<=0: self.__dia = dia dia= property(getDia, setDia) #declaro propiedad if __name__ == "__main__": # print (lista) guitarra=Guitarra("viento", 3) print(guitarra.tipoInstrumento()) guitarra.tocar() print(guitarra.__str__()) try: fech1= fecha(0) print(fech1.getDia()) fech1.dia= "hola" + 9 print(fech1.getDia()) except Exception as e: print("Error", str(e)) finally: print("Adios") print(re.match(".ython", "python"))
#declaracion de variables cadena = r"hola \n f" #raw sirve para expresiones regulares cadenaTripleComilla= """hola sirvo para hacer saltos de linea""" lista= [33,"roberto", "cachanosky", 3.12] #declaro list 1 print(lista[0:3]) #imprimo lista1 lista2= lista[0:2] #declaro e incializo con los datos de list1 a lista 2 print(lista2) lista[0:2]=[] #elimino los elementos de lista1 print(lista) #lista compuesta listaComp =[1,True, [0,4]] print(listaComp[2][1]) #imprimir lista de forma contraria (al reves) print(lista[-1]) #esto imprime el ultimo elemento #Tuplas (son inmutables y de tamaño fijo pero mas ligeras que las listas) tupla= (1,) #tupla de un solo elemento siempre lleva coma tupla2=(3, True, False, "roberto") #tupla normal ''' esto es un comentario multilinea''' print (cadena) print (cadenaTripleComilla)
class phalangeList: phalangelist = [] def refill(self,plist): templist = [] appflag = 1 for i in range(len(plist)): for j in range(len(self.phalangelist)): if plist[i] == self.phalangelist[j].fileID: templist.append(self.phalangelist[j]) for i in range(len(plist)): for j in range(len(templist)): if plist[i] == templist[j].fileID: appflag = 0 break else: appflag = 1 if appflag == 1: templist.append(phalange(plist[i],None)) appflag = 0 temp = set(self.phalangelist) - set(templist) temp1 = list(temp) temp2 = [] del self.phalangelist[:] self.phalangelist = templist for i in range(len(temp1)): temp2.append(temp1[i].scannerID) return temp2 def appendPL(self,fileID,scannerID): if self.returnfileID(scannerID) != -1 and self.returnscannerID(fileID) != -1: print 'entry already exists' return -1 elif self.returnfileID(scannerID) != -1: raise PhalangeError('Enrollment already exists') elif self.returnscannerID(fileID) != -1: raise PhalangeError('file exists under different scannerID') else: self.phalangelist.append(phalange(fileID,scannerID)) #print 'added' + fileID + 'as' + scannerID return 1 def returnscannerID(self,fileID): for i in range(len(self.phalangelist)): if self.phalangelist[i].fileID == fileID: return self.phalangelist[i].scannerID return -1 def returnfileID(self,scannerID): for i in range(len(self.phalangelist)): if self.phalangelist[i].scannerID == scannerID and \ self.phalangelist[i].scannerID != None: return self.phalangelist[i].fileID return -1 def returnfileID_index(self,fileID): for i in range(len(self.phalangelist)): if self.phalangelist[i].fileID == fileID: return i return -1 def returnscannerID_index(self,scannerID): for i in range(len(self.phalangelist)): if self.phalangelist[i].scannerID == scannerID: return i return -1 def delete_fileID(self,fileID): for i in range(len(self.phalangelist)): if self.phalangelist[i].fileID == fileID: del(self.phalangelist[i]) return 1 return -1 def assign_scannerID(self,fileID,scannerID): index = self.returnfileID_index(fileID) if index == -1: return -1 else: self.phalangelist[index].scannerID = scannerID return 1 def printall(self): for i in range(len(self.phalangelist)): print '[' + str(self.phalangelist[i].fileID) + ', ' + \ str(self.phalangelist[i].scannerID) + ']' def printID(self): for i in range(len(self.phalangelist)): print self.phalangelist[i].fileID def printEnrollment(self): for i in range(len(self.phalangelist)): print self.phalangelist[i].scannerID class phalange: def __init__(self, fileID, scannerID): self.fileID = fileID self.scannerID = scannerID class PhalangeError(Exception): def __init__(self,msg): self.msg = msg ''' poo = phalangeList() poo.appendPL(111,1) poo.appendPL(222,2) poo.appendPL(333,3) poo.appendPL(444,4) poo.appendPL(555,5) poo.appendPL(666,6) poo.appendPL(777,7) poo.appendPL(888,8) '''
import csv import os # # stock_pick.py # DD 1318 @ KTH # For P-assignment 2020 # # The program needs two folders in the same file as where the program exists. # One folder named data_files_in and one work_data_files. # - In data_files_in you save csv files from nasdaq just as they are. # - In the work_data_files folder the program will save necessary files. # - Fundamentals file needs to be updated manualy. This will be automated in v2. # # If you se a variable "days" it is for further development. This verision does just handle time periods of 30 days. # Next verisione will give the user the ability to change time period. # # NOTE: Program has been created from a given text with specified methods to go by. Like getting data from files. # To make the program flexible for fufure development I have decided to have more attributes to make it easier to # add calculation functions later. # # Author Tom K. Axberg # Last edit 04.04.20 # Contact: [email protected] # _____________________________________________________________ # classes and methods class Stock: """ Stock is a stock with attributes specified below: Attributes: :param name: Name of the stock
 beta: The Beta value movement: Movement of stock the past 30 days high: Highest price on stock the past 30 days low: Lowest price on stock the past 30 days last: Latest price on stock the past 30 days first: Price on stock 30 days ago solidity: Solidity of stock pe: Price per earnings ps: Price per sales """ stock_list = [] def __init__(self, name): """ Creates instances of stocks. Why just the name is taken as a parameter is because all the other attributes are either calculated or fetched from files. This is because all other attributes, than the name, is going to change if the user whants to uptate the available stiocks data (attributes). :param name: """ self.name = name self.stock_list.append(self) self.beta = 0 self.movement = 0 self.high = 0 self.low = 0 self.last = 0 self.first = 0 self.solidity = 0 self.pe = 0 self.ps = 0 self.no_shares = 0 def __lt__(self, other): """ Used for the exsisting sorting algorithm ( sorted() ). Other is used to compare to. More info in python documentation :return: boolean for sorting algorithm """ return self.beta > other.beta def fundamental_analysis(self): """ Used to print out a fundamental analysis of the stock to the user :return: string of fundamental analysis """ return "\nTechnical analysis - " + str(self.name) + "\n" \ "\nThe solidity of the company is " + str(self.solidity) + " %" \ "\nThe p/e value of the company is " + str(self.pe) + \ "\nThe p/s value of the company is " + str(self.ps) def technical_analysis(self, days): """ Used to print out a technical analysis of the stock to the user :return: string of technical analtsis """ return "\nTechnical analysis - " + str(self.name) + "\n" \ "\nMovement of the stock is " + str(self.movement) + "%" \ "\nLowest price the past " + str(days) + " days is " + str(self.low) + \ "\nHighest price the past " + str(days) + " days is " + str(self.high) # Functions def get_int_input(prompt_string): """ Used to get an positive integer input from the user, asks again if input is not convertible to an integer or if it's negative. :param prompt_string: Message for the user :return: The inputed positive integer """ done = False while not done: try: res = int(input(prompt_string)) # Result of input if 0 < res: # Only if input is positive done = True except ValueError as error: print("Please type in an positive integer.") else: print("Please type in an positive integer.") return res def data_files_updater(): """ Used to read all files in dir data_files_in and update/create the files in dir work_data_files folder. This is what the note is about in the beginning. It's specified from assignment to get data from three files uddated/created. Note: Third file is updated manualy. Will get automated in next verision. To make updates on these files I have chosen to use files fetched direktly from nasdaq. (Could have used json but i wanted to have a good sourse of data that didnt cost anything.) :return: a list of all available stocks. """ function_specific_work_list = [] # Used to append all names of the stocks available in data_files_in dir. stock_list_out = [] # Used to append all created stocks instanses file_out_index = open("work_data_files/index.csv", 'w') # First file created file_out_index.write("Format: date, index\n") file_out = open("work_data_files/movments.csv", 'w') # Second file created file_out.write("Format: date, closeprice\n") for filename in os.listdir('data_files_in'): if filename == ".DS_Store": # A hidden file (from macOS) in dir that is not readable. continue with open("data_files_in/" + filename, 'r') as csv_file: csv_reader = csv.reader(csv_file, delimiter=";") next(csv_reader) next(csv_reader) if filename.split("0")[0] == "_SE": # _SE means that its the index file omxs30 for line in csv_reader: file_out_index.write( str(line[0]) + ", " + ((str(line[3])).replace(",", ".") + "\n").replace(" ", "")) else: stock = filename.split("-")[0] # all other files are stock dara files from nasdaq file_out.write(stock + "\n") function_specific_work_list.append(stock) for line in csv_reader: file_out.write( str(line[0]) + ", " + ((str(line[6])).replace(",", ".") + "\n").replace(" ", "")) file_out.close() file_out_index.close() for item in function_specific_work_list: stock_list_out.append(Stock(item)) # creating stocks and appends them in list return stock_list_out def stock_data_updater(days): """ Used to read from all files in dir work_data_files and update all available stock attributes with up to date data. :param days: How long the period is for calculating stocks attributes. :return: nothing """ i = 0 low = 0 # used to store lowest price on stock in stock csv file from nasdaq high = 0 # used to store highest price on stock in stock csv file from nasdaq values = [0, 0, 0, 0] # array that is used to store values in during execution of this function with open("work_data_files/index.csv", 'r') as data: csv_reader = csv.reader(data) # used to navigate through csv files next(csv_reader) for line in csv_reader: if i == 0: values[0] = (float(line[1])) if i == (days - 1): values[1] = (float(line[1])) i += 1 i = 0 # reset i to 0 for stock in stock_list: with open("work_data_files/movments.csv", 'r') as data1, open("work_data_files/fundamentals.txt", 'r') as data2: csv_reader = csv.reader(data1) # used to navigate through csv files for line in csv_reader: if line[0].strip().upper() == stock.name.upper(): for row in csv_reader: if i == 0: high = float(row[1]) low = float(row[1]) values[2] = (float(row[1])) if i == (days - 1): values[3] = (float(row[1])) if i <= (days - 1): if low <= float(row[1]): high = float(row[1]) elif high >= float(row[1]): low = float(row[1]) i += 1 i = 0 for row in data2: # Reads fundamental data from specified file. if row.strip() == stock.name: stock.solidity = float(data2.readline().strip()) stock.pe = float(data2.readline().strip()) stock.ps = float(data2.readline().strip()) stock.movement = round(100 * ((values[2] - values[3]) / values[2]), 2) stock.beta = round((values[2] / values[3]) / (values[0] / values[1]), 3) stock.last = values[2] stock.first = values[3] stock.high = high stock.low = low def available_stocks(): """ Used to display all available stocks. :return: nothing """ i = 1 for stock in stock_list: print(str(i) + " - " + stock.name) i += 1 def main(): """ Main program. Starts with a welcome message and then executes the menue. :return: nothing """ print( "\n——————————-—————Welcome to the stock picking guide!——————————-————— \n All data is not to be taken seriously. " "\n Go with your gut.\n\nPlease press enter to start! ") input() menu() def menu_choice(): """ Used to get input on what the user wants to do :return: an integer correspondning to the chosen menu option. """ done = False while not done: res = get_int_input("Type in your choice here:\n> ") if res <= 4: done = True else: print("Your input is not a valid choice. Please type in an integer 1 - 4. \n") return res def analysis_choice(prompt_string): """ Used to display the available stocks and :param prompt_string: :return: """ done = False while not done: try: i = 1 print("\n" + prompt_string + "can be done on the following stocks:\n") for item in stock_list: print(str(i) + " - " + item.name) i += 1 res = get_int_input("\nWhich stock do you want to analyse?\n> ") if res <= i - 1: done = True else: print("Your input is not a valid choice. Please type in an integer 1 -", len(stock_list), "\n") except IndexError as error: print("Your input is not a valid choice. Please type in an integer 1 -", len(stock_list), "\n") return res def execute(choice, days): """ Used to execute the option that the user chose. :param choice: an integer corresponding the the chosen option :return: (nothing) """ if choice == 1: print(stock_list[analysis_choice("Fundamental analysis") - 1].fundamental_analysis()) input("\nPlease press enter to continue.\n\n\n\n") menu() elif choice == 2: print(stock_list[analysis_choice("Technical analysis") - 1].technical_analysis(days)) input("\nPlease press enter to continue.\n\n\n\n") menu() elif choice == 3: done = False i = 1 while not done: try: print("\n—————Available stocks sorted by beta value————
\n") for stock in sorted(stock_list): print(i, "-", stock.name, stock.beta) i += 1 except NameError as error: print("There are no avaliable stocks to sort.\n Please add stocks in to the program.") else: done = True input("\nPlease press enter to continue.\n\n\n\n") menu() elif choice == 4: exit() def menu(): """ 
 Used to display the menu: ———————--———-—————Meny———————————————————
 What would you like to do?
 1 - Fundamental analysis (Long term) 
 2 - Technical analysis (Short term)
 3 - List of available stocks by their beta value 
 4 - Exit Which alternative do you choose? And then execute the execute function with the menu_choice function so that the user can make a chioce. :return: (nothing) 
 """ print( "\n——————————-—————Meny———————————————————
\n What would you like to do?\n\n 1 - Fundamental analysis (Long term)\n 2 - Technical analysis (Short term)
" "\n 3 - List of available stocks by their beta value\n 4 - Exit\n") execute(menu_choice(), days=30) # Execute the chioce of menu_choice if __name__ == "__main__": stock_list = data_files_updater() stock_data_updater(30) main()
n = int(input('Digite um número inteiro: ')) r = n % 2 if (r == 0): print('O número digitado foi {}, ele é PAR'.format(n)) else: print('O número digitado foi {}, ele é IMPAR'.format(n))
''' Leia 3 valores de ponto flutuante A, B e C e ordene-os em ordem decrescente, de modo que o lado A representa o maior dos 3 lados. A seguir, determine o tipo de triângulo que estes três lados formam, com base nos seguintes casos, sempre escrevendo uma mensagem adequada: se A ≥ B+C, apresente a mensagem: NAO FORMA TRIANGULO se A2 = B2 + C2, apresente a mensagem: TRIANGULO RETANGULO se A2 > B2 + C2, apresente a mensagem: TRIANGULO OBTUSANGULO se A2 < B2 + C2, apresente a mensagem: TRIANGULO ACUTANGULO se os três lados forem iguais, apresente a mensagem: TRIANGULO EQUILATERO se apenas dois dos lados forem iguais, apresente a mensagem: TRIANGULO ISOSCELES Entrada A entrada contem três valores de ponto flutuante de dupla precisão A (0 < A) , B (0 < B) e C (0 < C). Saída Imprima todas as classificações do triângulo especificado na entrada. ''' listo = [] listo = input().split(" ") listo = [float(i) for i in listo] listo = sorted(listo, reverse=True) A = listo[0] B = listo[1] C = listo[2] if (A >= B + C): print('NAO FORMA TRIANGULO') else: if (A**2 == B**2 + C**2): print('TRIANGULO RETANGULO') if (A**2 > B**2 + C**2): print('TRIANGULO OBTUSANGULO') if (A**2 < B**2 + C**2): print('TRIANGULO ACUTANGULO') if (A == B and B == C): print('TRIANGULO EQUILATERO') if ((B == C and A != B) or (A == C and A != B) or (A == B and A != C)): print('TRIANGULO ISOSCELES')
#from math import sqrt, exp, tan, pi, log, sin, e import string import random from random import randint ### # Enter file names here read_file = raw_input("Enter the file name to read from: ") write_file = raw_input("Enter the file name to write to: ") ### numberOfRotors = 40 chars = string.printable[:98] charsList = [] for s in chars: charsList.append(s) wheelList = [] numbersList = [1] def getRandom(item): """function to sort the characters randomly""" return randint(0,200) random.seed(1863472) #so that the random wheel starting positions are the same every time for i in range(numberOfRotors): tempChars = list(chars) tempChars.sort(key=getRandom) wheelList.append(tempChars) numbersList.append(randint(2,100)) def Init(L,s): """Initializes a rotor, L, to the starting location, s.""" while L[0]!=s: a=L[0] del L[0] L.append(a) def Turn(L): """Takes a list and turns it one letter.""" a=L[0] del L[0] L.append(a) def locate(L,s): """Finds the location of a character, s, in a list, L""" n=0 for i in L: if i==s: a=n n+=1 return a def change(L,s): """Takes in a character and a gear and changes the character accordingly L:list s:string """ a=locate(charsList,s) b=L[a] return b def reversechange(L,s): """The opposite of change, for the part after the reflector. L:list s:string """ b=locate(L,s) a=charsList[b] return a def reflector(s): a=['o', '6', '?', '7', 'P', '!', ' ', '%', '.', 's', 'i', 'I', 'N', '*', '-', 'p', ']', '<', 'l', 'x', 'U', 'Y', 'y', '#', 'v', 'Z', 'd', '>', '9', '8', '@', 'w', '`', ')', 'c', '+', 'Q', '\t','b', '4', 'E', 'H', 'D', 'O', 'F', '^', '&', 'G', 'C'] b=['u', 'g', 'h', 'S', 'm', '{', 'R', 'A', '_', 'q', 'T', 'z', 'J', 'j', 'r', '0', 'X', '[', '"', 'V', 'n', '$', 'B', '\n', 'L', 'k', 'K', '}', '\\', 'a', ';', 'f', '\r', 'e', '2', ',', '5', 'W', 't', "'", '(', 'M', '|', '1', '=', '~', ':', '3', '/'] if s in a: return b[a.index(s)] elif s in b: return a[b.index(s)] def Encrypt(s,InitS=""): """s is the string to be encrypted. InitS is the initialization string. It must be 'numberOfRotors' characters long.""" s=str(s) n=0 if (InitS!=""): for i in InitS: Init(wheelList[n],i) n+=1 result = '' count=0 for i in s: a=i for j in wheelList: a=change(j,a) a=reflector(a) for j in range(numberOfRotors): l=wheelList[numberOfRotors-1-j] a=reversechange(l,a) result+=a for j in range(numberOfRotors): if count%numbersList[j]==0: Turn(wheelList[j]) count+=1 return result password = raw_input("Enter your password here: ") with open(read_file, 'r') as myfile: data=myfile.read() newData = Encrypt(data,password[:numberOfRotors]) with open(write_file, 'w') as myfile: myfile.write(newData)
#!/usr/bin/env python # -*- coding: utf-8 -*- """Funkce pro generovani site bodu ve 2D prostoru""" import matplotlib.pyplot as plt import numbers def frange(start, stop, step): i = start while i < stop: yield i i += step def generate_points(start, end, step): if isinstance(step, numbers.Real): data = [(i, j) for i in frange(start, end, step) for j in frange(start, end, step)] else: data = [(i, j) for i in range(start, end, step) for j in range(start, end, step)] return data def main(): data = generate_points(-20, 20, 1) x, y = zip(*data) plt.scatter(x, y) plt.show() if __name__ == '__main__': main()
''' Bunny Prisoner Locating ======================= Keeping track of Commander Lambda's many bunny prisoners is starting to get tricky. You've been tasked with writing a program to match bunny prisoner IDs to cell locations. The LAMBCHOP doomsday device takes up much of the interior of Commander Lambda's space station, and as a result the prison blocks have an unusual layout. They are stacked in a triangular shape, and the bunny prisoners are given numerical IDs starting from the corner, as follows: | 7 | 4 8 | 2 5 9 | 1 3 6 10 Each cell can be represented as points (x, y), with x being the distance from the vertical wall, and y being the height from the ground. For example, the bunny prisoner at (1, 1) has ID 1, the bunny prisoner at (3, 2) has ID 9, and the bunny prisoner at (2,3) has ID 8. This pattern of numbering continues indefinitely (Commander Lambda has been taking a LOT of prisoners). Write a function answer(x, y) which returns the prisoner ID of the bunny at location (x, y). Each value of x and y will be at least 1 and no greater than 100,000. Since the prisoner ID can be very large, return your answer as a string representation of the number. Languages ========= To provide a Python solution, edit solution.py To provide a Java solution, edit solution.java Test cases ========== Inputs: (int) x = 3 (int) y = 2 Output: (string) "9" Inputs: (int) x = 5 ''' def bunnyCounter(x,y): def seriesSum(start,end): #sum of an arithmatic series return (start+end)*(abs(start-end)+1)/2 return seriesSum(x,1)+seriesSum(x,x+y-2) print(bunnyCounter(3,2))
There is a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. The player can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus '1' or '2'. The player must avoid the thunderheads. Determine the minimum number of jumps it will take to jump from the starting postion to the last cloud. It is always possible to win the game. For each game, you will get an array of clouds numbered '0' if they are safe or '1' if they must be avoided. #!/bin/python3 import math import os import random import re import sys # Complete the jumpingOnClouds function below. def jumpingOnClouds(c): count = 0 idx = 0 while idx != len(c): try: if c[idx+2] == 1: idx += 1 else: idx += 2 except: idx += 1 count +=1 return count-1 if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) c = list(map(int, input().rstrip().split())) result = jumpingOnClouds(c) fptr.write(str(result) + '\n') fptr.close()
def iq_test(numbers): numbers = numbers.split(" ") ctr_even = 0 ctr_odd = 0 ans = 0 for i in range (len(numbers)): numbers[i] = int(numbers[i]) if numbers[i] % 2 != 0: ctr_odd +=1 else: ctr_even +=1 for j in range (len(numbers)): if ctr_even == 1 and numbers[j] % 2 == 0: ans = j+1 if ctr_odd == 1 and numbers[j] % 2 != 0: ans = j+1 return ans
# def stringreverse(request): # a = "" # # for i in request[-1:-len(request)-1:-1]: # for i in request[::-1]: # a = a + i # print(a) # request = input("enter the string") # stringreverse(request) # from random import randint # for i in range(5): # print(random(5,1))
# a = [1, 2, 3, 4] # print(sum(a)) def largest(a): max = a[0] for i in range(0, len(a)): if a[i] > max: max = a[i] print(max) a = [3,55,6,1,2] res = largest(a) # print(res) from collections import Counter l1 = [1, 2, 3, 4, 5] l2 = [4, 5, 6, 7, 7, 8, 9] print(Counter(l1),Counter(l2))
a,b=[],[] for i in range(-4, 5): if i >= 0: a.append(i) else: b.append(i) print(a,b)
def bubble(a): try: for i in range(0, len(a)-1): if a[i] > a[i+1]: temp = a[i] a[i], a[i+1] = a[i+1], temp for i in range(len(a)): print(a[i], end=' ') except Exception as e: print(e) a = [10, 3, 1, 5, 2, 8, 0, 7] bubble(a)
class Employee: bonus = 2 emp_count = 10 cname = 'google' def __init__(self,name,pay): self.name = name self.pay = pay self.mail = name+'@'+self.cname+'.com' def display(self): return f'employee name is {self.name} and salary is {self.pay} and mail-id is {self.mail}' class Developer(Employee): bonus = 10 def __init__(self,name,pay,prog_lang): super().__init__(name,pay) self.prog_lang = prog_lang class Manager(Employee): def __init__(self,name,pay,emp = None): super().__init__(name,pay) if emp is None: self.emp = [] else: self.emp = emp def addemp(self,employ): if employ not in self.emp: self.emp.append(employ) def removemp(self,employ): if employ in self.emp: self.emp.remove(employ) def listemp(self): return f'{self.emp}' e1 = Employee('ganavi',60000) d1 = Developer('test',30000,'python') m1 = Manager('test',30000,[]) print(m1.listemp()) m1.addemp("new") m1.addemp("john") print(m1.listemp()) m1.removemp("new") print(m1.listemp()) #print(help(Developer)
''' ****************************************************************************** code name:- genetic algorithm to evaluate a function function :- x/(1+x**2) ****************************************************************************** ''' from random import random, randint,sample import math def calculate(x): ''' input:- a number output:- value calculated on based on function purpose:- to evaluate the contraint function ''' a=float(x/(1+(x**2)))#constraint for the problem return a def mapping(list): ''' input:-a list of n random integers output:-a list of n calculated values purpose:- to map the contraint function to the list approch :- list comprehension ''' return [calculate(x) for x in list]#mapping with contraint def individual(length, min, max): ''' input:-range and size of the list to be created output:-a list of n random integers purpose:- to generate n random numbers based on the range and size of the list provided ''' return [ randint(min,max) for x in range(length) ]#random number generation def evolution(individual): ''' input:- a population of n numbers output:- fitness of population purpose:- to evaluate the fitness of the gven population! ''' fitness=mapping(individual) return fitness def probability(list): ''' input:-a list of n numbers output:-a list containing the probabilities purpose:- to evaluate the probability of each member ''' s=sum(list)#sum of all prob=[] for z in range(0,len(list)): temp=list[z]/s#probability calculation prob.append(temp) return prob def random_append(size): ''' input:-size of list to generate output:-list of size specied containg numbers between 0-1 generated randomally purpose:- ''' r=[] for i in range(size): r.append(random())#random number generation between 0-1 return r def roullete_population(rand,population,cum_prob): ''' input:-list of random number,sample population,cummulative probability output:-selected population purpose:- perform genetic selection on basis of random list ''' new_pop=[] len_cf=len(cum_prob) for a in rand: if a<=cum_prob[0]: new_pop.append(population[0]) else: for i in range(1,len_cf): if(i<len_cf): if cum_prob[i-1] < a <=cum_prob[i]: new_pop.append(population[i]) else: new_pop.append(x[len_cf]) return new_pop def cumm(prob): ''' input:-a list containing probability output:-a list containing random probability purpose:-to calculate cummulative probability from probabilities ''' cumm=[] cumm.append(prob[0]) for z in range(1, len(prob)): #calculating cummulative probability cumm.append(cumm[z-1] + prob[z]) return cumm def crossover(size,cross_ratio,population,min,max): ''' input:-population of specified size in range min-max and crossover ratio output:-crossovered population of same size and in range purpose:- to perform crossover and perform genetic mating to generate next generation ''' parent=[] parentpos=[] parentnumber=0 ra=random_append(size) for i in range(0,size): if ra[i]<cross_ratio: parentnumber=parentnumber+1 #crossover possible if more than 1 parents # single parent cannot do crossover if parentnumber>=2: ba=[] temp=math.log2(max) bitsize=math.floor(temp)+1 #converting to binary for i in range(0,size): temp=binary(population[i],bitsize) ba.append(temp) #check for crossover possibility for i in range(0,size): if ra[i]<cross_ratio: parent.append(ba[i]) parentpos.append(i) lengthparent=len(parent) #generating cut position cut=cutposition(lengthparent,bitsize) #mating of even possible #1-1 mating only if parentnumber%2!=0: parentnumber=parentnumber-1 #performing mating and change in population for new generation for i in range(0,parentnumber,2): child=mating(parent[i],parent[i+1],cut[i]) child1=binarytoint(child[0]) child2=binarytoint(child[1]) if (min<=child1 and child1<=max) and (min<=child2 and child2<=max): population[parentpos[i]]=child1 population[parentpos[i+1]]=child2 return population def binarytoint(list): ''' input:-a 2d list of n binary numbers output:-a 1d list of n integers purpose:- to convert binarylist to a integer ''' val=0 for i in range(0,len(list)): #bitwise transformtion val=(list[i]*(2**i))+val return val def mating(parent1,parent2,position): ''' input:-2 parents and their mating position output:- a list of 2 childs purpose:- to perform mating of parents and generation of offsprings ''' # single point cut child=[] child.append([]) child.append([]) #no swapping before cut positon for i in range(0,position): child[0].append(parent1[i]) child[1].append(parent2[i]) #swapping after cut position for i in range(position+1,len(parent1)): child[0].append(parent2[i]) child[1].append(parent1[i]) return child def cutposition(size,bitsize): ''' input:-size of population,size of each binary list in one individual output:-list of cut positions purpose:- to generate cut position depending on population ''' cut=[] for i in range(0,size): temp=randint(1,bitsize) cut.append(temp) return cut def binary(item,no_of_bits): ''' input:-item in integer and no_of_bits in case of padding is required output:-binary number with suitable padding purpose:- to generate binary list for integer ''' temp=[int(i) for i in str(bin(item))[2:]] temp_size=len(temp) #padding extra 0 in front if required while(temp_size<=no_of_bits): temp.insert(0,0) temp_size=temp_size+1 return temp def mutation(size,population,mutation_ratio,min,max): ''' input:-population and he mutation ratio output:-mutated population purpose:- to perform genetic mutation on the population ''' ba=[] #calculating bit size to generate at max bits in binary alpha=math.log2(max) bitsize=math.floor(alpha)+1 #binary conversion for i in range(0,size): temp=binary(population[i],bitsize) ba.append(temp) total=bitsize*size #calculating mutation bits mut=int(mutation_ratio*total) mut_bits=sample(range(0,total),mut) #converting mutation bits to 2d indexes for i in range(0,mut): temp=[] row=int(mut_bits[i]/bitsize) col=mut_bits[i]%bitsize #inversion on mutation for i in range(0,bitsize): if i!=col: temp.append(ba[row][i]) else: if ba[row][col]==1: temp.append(0) elif ba[row][col]==0: temp.append(1) delta=binarytoint(temp) #checking mutation on bounds if min<=delta and delta<=max: ba[row]=temp gamma=binarytoint(ba[row]) population[row]=gamma return population def genetic(): ''' input:- genetic parameters from user output:- value at which the constraint is maximized purpose:-to use genetic algorithm procedure to evaluate the objective approch:- use of genetic algorithm to solve complex computational problem ''' min=int(input("enter the min value of range :- ")) max=int(input("enter the max value of range :- ")) iteration=int(input("enter the no iterations :-")) count=int(input("enter population size:-")) cross_ratio=float(input("enter cross over ratio in percentage 0.00-1.00 recommended 0.60 :-")) mutation_ratio=float(input("enter mutation ratio in percentage 0.00-1.00 recommended 0.10 :-")) population=individual(count,min,max) objective=0 check=0 index=0 index1=0 for i in range(0,iteration): print("iteration no") print(i) print ("population") print(population) fit=evolution(population) print("fitness") print(fit) param=population[index1] prob=probability(fit) cummulative=cumm(prob) rand=random_append(count) nextgen=roullete_population(rand,population,cummulative) population=crossover(count,cross_ratio,nextgen,min,max) population=mutation(count,population,mutation_ratio,min,max) print(population) fit=[] fit=evolution(population) for i in range(0,count): if objective<fit[i]: objective=fit[i] index=i print("max value at ") print(population[index]) genetic()
import requests import datetime class PyCanliiBase(object): """ The base object in the pycanlii library. All objects in the library inherit from it. """ def __init__(self, apikey, language): self._key = apikey self._lang = language def _request(self, url, authenticated, *url_variables, **query_parameters): """ Sends a request to the input url, with the url parameters place in order with a / between each and with the query parameters input. :return: A response object """ if authenticated: query_parameters['api_key'] = self._key url += "/" + self._lang.name for var in url_variables: url += "/" + var result = None if len(query_parameters): result = requests.get(url, params=query_parameters) else: result = requests.get(url) result.raise_for_status() return result def _getDate(self, daystr): """ Accepts a string of the form "YYYY-MM-DD" and returns a date object representing that date, if daystr is the empty string, None is returned. :param daystr: A string in the format "YYYY-MM-DD" representing a date :return: A date object determined by the input string """ if daystr == "": return None else: return datetime.date(int(daystr[0:4]), int(daystr[5:7]), int(daystr[8:10]))
class SudokuSolver(object): """ SudokuSolver class. This class requires a list representation of a sudoku, and will then try to solve it. Usage: Instantiate an object from the class and pass a start_board. Then you can use the exposed methods. Exposed methods: solve -- Attempts to solve the sudoku board_is_valid -- Check wheter the board with which the object is instantiated is a valid board. """ def __init__(self, start_board): ''' Initializer for the SodukoSolver object. Requires a sudoku board as argument. Assumes the given board is validated.''' self.is_solved = False self.board = deepcopy(start_board) def solve(self, board): ''' Main sudoku solver routine. Note: this method works recursively. It's a brute-force approach (very) loosely based on https://en.wikipedia.org/wiki/Sudoku_solving_algorithms ''' # Pointer to keep track of the next position to be # checked. Represented as next_pos[row, col]. next_pos = [0, 0] # If there is no empty new location available, all # squares are filled in and the sudoku is considered complete. if not self.next_empty_location(board, next_pos): self.board = board self.is_solved = True return True # Update the current row and col to check based on the pointer. # Remember: the pointers were updated to represent a new square. current_row = next_pos[0] current_col = next_pos[1] # Go over digits 1 up to and including 9. # Note: start value is inclusive, end value is exclusive for value in range(1, 10): if self.is_legal_move(board, current_row, current_col, value): # Check if the considered move is legal # If it is legal, assign value to the square board[current_row][current_col] = value # Do all of the above recursively until we found a # solution or considered every possible value. Remember: # the next_pos gets updated each time. Which makes this # brute-force algorithm. if self.solve(board): return True # If we tried all options (1 to 9) recursively and encountered # an error, reset the tried square to zero and try again. board[current_row][current_col] = 0 # By returning false we "drop down a level" in the recursive trace. # This way, we can backtrack through the trace without having to keep # track of a regular stack/queue return False def board_is_valid(self): ''' Check if a given board solely exists of legal positions. A position is considered legal if and only if: - The positions value is unique in its row AND - The positions value is unique in its column AND - The positions value is unique in its 3x3 box A board is considered valid if all of it's inputted values comply with the above three rules. ''' if ENABLE_DEBUG: print("GLOBAL DEBUG -- Checking to see if starting board is" " valid.") board = self.board is_valid = True # Innocent until proven otherwise for i, row in enumerate(board): for j, col in enumerate(row): # Temporarily unset given position, because the checked value # will always be set in its own row, column and box. _, board[i][j] = self.board[i][j], None # Squares containing a value of zero are unsolved and can thus # be skipped. Since all unsolved squares are represented by 0, # they will never be unique in the row, column and box. if _ != 0: is_valid = self.is_legal_move(board, i, j, _) board[i][j] = _ if not is_valid: return is_valid board[i][j] = _ return is_valid def exists_in_column(self, board, col, val): ''' Determine if a given value exists in the given column. ''' for i in range(9): if board[i][col] == val: return True return False def exists_in_row(self, board, row, val): ''' Determine if a given value exists in the given row. ''' for i in range(9): if board[row][i] == val: return True return False def exists_in_box(self, board, row, col, val): ''' Determine if a given value exists in the given 3x3 box. ''' for i in range(3): for j in range(3): # Given row/col is not always top left of box # so this needs to be taken into account if board[i+(row - row % 3)][j+(col - col % 3)] == val: return True return False def is_legal_move(self, board, row, col, val): ''' Takes a given row, column and value and decides wheter placing the value at this row/column is permitted or not. A move is considered legal if: - The value is unique to its own row - The value is unique to its own column - The value is unique to its own 3x3 box - The value is a value in the inclusive set of [1,9]''' if (not self.exists_in_column(board, col, val) and not self.exists_in_row(board, row, val) and not self.exists_in_box(board, row, col, val) and 1 <= val <= 9): return True return False def next_empty_location(self, board, next_pos): ''' Determines the next empty location that is available on the board. Next_pos is a list passed in, and contains pointers (represented as [row, col]) to the next available position. If a proper new location is found, the next_pos pointer gets updated and True is returned. If there is no empty position, False is returned. ''' for row in range(9): for col in range(9): if board[row][col] == 0: # A value of 0 is regarded as an empty square # If we encounter it, we found the next empty # square. Which means we can update the next_pos # pointer. next_pos[0] = row next_pos[1] = col return True return False def print_sudoku(self): ''' Prints a given sudoku grid to console. ''' hor_line = "++---+---+---++---+---+---++---+---+---++" print(hor_line.replace('-', '=')) for i, row in enumerate(self.board): cur_line = "" for j, val in enumerate(row): cur_line += "|" if j % 3 == 0: cur_line += "|" if val is 0: cur_line += ' . ' else: cur_line += ' {} '.format(val) cur_line += "||" print(cur_line) if (i+1) % 3 == 0: print(hor_line) class SudokuGrid(object): def __init__(self, puzzle_list): ''' Initializer for a new SudokuGrid object. This class can create an empty sudoku grid, print a sudoku grid to console and has a method to manually fill a sudoku grid with values for testing purposes. ''' # Create empty board self.board = self.create_board() self.board = self.fill_puzzle_start(self.board, puzzle_list) def create_board(self): ''' Creates an empty sudoku grid. ''' num_rows = 9 num_cols = 9 empty_grid = [ [0 for cols in range(num_cols)] for rows in range(num_rows) ] return empty_grid def fill_puzzle_start(self, empty_grid, puzzle_list): ''' Allows developers to fill the sudoku grid with manual values for testing purposes. ''' # Fill the grid with manual values for testing purposes puzzle_start = copy(empty_grid) # First row # puzzle_start = [ # [5, 3, 0, 0, 7, 0, 0, 0, 0], # [6, 0, 0, 1, 9, 5, 0, 0, 0], # [0, 9, 8, 0, 0, 0, 0, 6, 0], # [8, 0, 0, 0, 6, 0, 0, 0, 3], # [4, 0, 0, 8, 0, 3, 0, 0, 1], # [7, 0, 0, 0, 2, 0, 0, 0, 6], # [0, 6, 0, 0, 0, 0, 2, 8, 0], # [0, 0, 0, 4, 1, 9, 0, 0, 5], # [0, 0, 0, 0, 8, 0, 0, 7, 9] # ] puzzle_start = puzzle_list return puzzle_start def print_puzzle_fancy(self, board): ''' Prints a given sudoku grid to console. ''' hor_line = "++---+---+---++---+---+---++---+---+---++" print(hor_line.replace('-', '=')) for i, row in enumerate(board): cur_line = "" for j, val in enumerate(row): cur_line += "|" if j % 3 == 0: cur_line += "|" if val is 0: cur_line += ' . ' else: cur_line += ' {} '.format(val) cur_line += "||" print(cur_line) if (i+1) % 3 == 0: print(hor_line)
##Ashley Speigle ##Lab04: Simulation Part 2 import random patients = ["Bob", "Herbert", "Joe", "Suzy", "Bertha", "Alice", "Don", "Billy", "Andrew", "George","Fred", "Cain", "Adam", "Eve", "Peter", "Noel", "Ashley", "Linda", "Richard", "Brandon"] class patient: def __init__(self,name): self.name = name def nurse(wr): wr.addPatients2(wr.removePatients()) class waitingRoom: # keep track of patients before nurse def __init__(self): self.patientsWaiting = [] self.patientsWaitingForever = [] def addPatients(self,patient): self.patientsWaiting.append(patient) def removePatients(self): return self.patientsWaiting.pop(0) # keep track of patients waiting to see physician or not def addPatients2(self,patient): self.patientsWaitingForever.append(patient) def removePatients2(self): return self.patientsWaitingForever.pop(0) def emptyRoom(self): #tells if room is empty if self.patientsWaiting == []: return True else: return False def emptyRoom2(self): #tells if room is empty if self.patientsWaitingForever == []: return True else: return False class examRoom: def __init__(self): self.roomTime = 0 self.patient = None self.patientTime = 0 #tells how long the patient should be in room def addPatients4(self,wr): #go to waiting room self.patient = wr.removePatients2() self.patientTime = random.randrange(15,21) def time(self): return self.patientTime def emptyRoom(self): #tells if room is empty if self.patient == None: return True else: return False def removePatients4(self): x = self.patient self.patient = None return x #assign physician for exam rooms #keep track how long the patient has been in the room def timeSpentInRoom(self): return self.roomTime def increasedTime(self): self.roomTime += 1 #advance time w/ for w = waitingRoom() e1 = examRoom() e2 = examRoom() e3 = examRoom() e4 = examRoom() e5 = examRoom() e6 = examRoom() for y in patients: w.addPatients(y) def updateTime(): nurse(w) if not e1.emptyRoom(): e1.increasedTime() if e1.time() >= e1.timeSpentInRoom(): e1.removePatients4() if e1.emptyRoom(): if not w.emptyRoom2(): e1.addPatients4(w) if not e2.emptyRoom(): e2.increasedTime() if e2.time() >= e2.timeSpentInRoom(): e2.removePatients4() if e2.emptyRoom(): if not w.emptyRoom2(): e2.addPatients4(w) if not e3.emptyRoom(): e3.increasedTime() if e3.time() >= e3.timeSpentInRoom(): e3.removePatients4() if e3.emptyRoom(): if not w.emptyRoom2(): e3.addPatients4(w) if not e4.emptyRoom(): e4.increasedTime() if e4.time() >= e4.timeSpentInRoom(): e4.removePatients4() if e4.emptyRoom(): if not w.emptyRoom2(): e4.addPatients4(w) if not e5.emptyRoom(): e5.increasedTime() if e5.time() >= e5.timeSpentInRoom(): e5.removePatients4() if e5.emptyRoom(): if not w.emptyRoom2(): e5.addPatients4(w) if not e6.emptyRoom(): e6.increasedTime() if e6.time() >= e6.timeSpentInRoom(): e1.removePatients4() if e6.emptyRoom(): if not w.emptyRoom2(): e6.addPatients4(w)
# Written by Aaron Barge # Copyright 2019 import math class Coord(object): def __init__(self): return class Cartesian(Coord): def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "(x = " + str(self.x) + ", y = " + str(self.y) + ")" def __eq__(self, p2): self_new = self.round() p2_new = self.round() if type(p2) is type(self): return self_new.x == p2_new.x and self_new.y == p2_new.y else: p2_new = p2.toCartesian() return self_new == p2_new print("Something didn't work") return False def toPolar(self): r = math.sqrt(self.x ** 2 + self.y ** 2) theta = math.atan(self.y / self.x) polar = Polar(r, theta) print(polar) return polar def round(self): return Cartesian(round(self.x, 3), round(self.y, 3)) class Polar(Coord): def __init__(self, r, theta): self.r = r self.theta = theta def __str__(self): return "(r = " + str(self.r) + ", theta = " + str(self.theta) + ")" def __eq__(self, p2): self_new = self.round() p2_new = p2.round() if type(p2) is type(self): return self_new.r == p2_new.r and self_new.theta == p2_new.theta else: p2_new = p2.toPolar() return self_new == p2_new print("Something didn't work") return False def toCartesian(self): cartesian = Cartesian(self.r * math.cos(self.theta), self.r * math.sin(self.theta)) print(cartesian) return cartesian def round(self): return Polar(round(self.r, 3), round(self.theta, 3)) def Test(): def checkCartesian(): def EqualTo(): p1 = Cartesian(0, 2) p2 = Cartesian(0, 2) print("Testing Cartesian Equal To") return p1 == p2 def NotEqualTo(): p1 = Cartesian(0, 2) p2 = Cartesian(2, 0) print("Testing Cartesian Not Equal To") return p1 != p2 if not EqualTo(): return False if not NotEqualTo(): return False return True def checkPolar(): def EqualTo(): p1 = Polar(5, 0) p2 = Polar(5, 0) print("Testing Polar Equal To") return p1 == p2 def NotEqualTo(): p1 = Polar(5, 0) p2 = Polar(5, math.pi) print("Testing Polar Not Equal To") return p1 != p2 if not EqualTo(): return False if not NotEqualTo(): return False return True def checkBoth(): def EqualTo(): p1 = Cartesian(-5, 0) p2 = Polar(5, math.pi) print("Testing Both Equal To") return p1 == p2 def NotEqualTo(): p1 = Cartesian(5, 0) p2 = Polar(5, math.pi) print("Testing Both Not Equal To") return p1 != p2 if not EqualTo(): return False if not NotEqualTo(): return False return True if not checkCartesian(): return False if not checkPolar(): return False if not checkBoth(): return False return True Test()
def main(): weeks = [39.86, 33.11, 30.45, 36.39, 33.10, 0, 7.94, 36.49, 37.59, 27.36, 32.54, 25.83, 31.14, 26.34, 25.86, 28.21, 26.08, 27.65, 27.08, 8.00, 10.26, 18.46, 17.87, 25.73, 26.37, 9.30, 37.94, 22.71, 0, 33.56, 28.47, 29.19, 13.36, 22.35, 22.07, 21.90, 21.17, 22.83, 29.66, 21.53, 21.37, 21.89, 22.34, 24.16, 14.26, 17.31, 0.00, 37.79, 32.39, 26.65, 27.97, 0.00, 31.68, 32.10, 38.90, 32.04, 0.00, 30.71, 37.42] hour_average = 100 week = 0 while hour_average >= 10: hour_average = year_average(weeks) if week % 4 == 0: weeks.append(8) else: weeks.append(0) week = week + 1 print("You made it %d weeks" %week) def year_average(weeks): total_hours = 0 for week in weeks[-52:]: total_hours += week return total_hours / 52 if __name__ == "__main__": main()
#!/usr/bin/env python # coding: utf-8 # In[14]: class Human: #single person details class name = "manoj" age = 25 #attributes gender = "male" def Run(self): #function print("manoj is running.....") object = Human() #object print(object.name, object.age, object.gender) object.Run() # In[16]: class Person: def __init__(self, name , age , gender): # by init constructor we can create multiple objects with class attributes self.name = name self.age = age self.gender = gender object = Person("manoj",25,"male") #object is used to access of class variables print(object.name, object.age, object.gender) object2 = Person("yoga", 26, "male") print(object2.name, object2.age, object2.gender) # In[15]: # inheritance is just like family relation # 1 single inheritance # by using inheritance we can access parent class through child class, but parent class cant access child class class Parent: pname = "manohar" def Driving(self): print("I am driving a car") class Child(Parent): name = "manoj" def Learning(self): print("I was learning a car from my father") object2 = Child() print(object2.name) object2.Learning() object2.pname # In[21]: #multi level inheritance class Grandfather: def g_landproperties(self): print("I have some land") class Father(Grandfather): def f_landproperties(self): print("I belongs to my father properties") class Child(Father,Grandfather): def c_landproperties(self): print("I belongs to my father and my grandfather properties") object1 = Child() object1.c_landproperties() object1.f_landproperties() object1.g_landproperties() # In[3]: # Hierarchical inheritance it means single base class and multiple derived class class Father: def Captain(self): print("I am the captain of this house") class Son(Father): def Player1(self): print("I am main player of this house") class Daughter(Father): def Player2(self): print("I am key player of this house") object1 = Son() object2 = Daughter() object1.Player1() object2.Player2() object2.Captain() # In[4]: # Multiple inheritance class Father: def Captain(self): print("I am father of my son") class Mother: def Vicecaptain(self): print("I am mother of my son") class Son(Mother, Father): def Player(self): print("I am son of my father and my mother") obj = Son() obj.Vicecaptain() obj.Captain() obj.Player() # In[10]: #polymorphism means many forms # it divides into two types compile time and Run time """compile time means method overloading almost as same as default parameter in functions Run time means method override""" class Base: def add(self,a,b,c=100): print(a+b+c) obj = Base() obj.add(100,200) class Derivedclass: def add(self,a,b=100): print(a+b) obj = Derivedclass() obj.add(100,200) obj.add(100) #here b value takes default given value 100 # In[11]: # runtime :method override class Base: def Vehicleloan(self): print("some due for vehicleloan") class Derived(Base): def Vehicleloan(self): print("no due for vechicleloan") obj = Derived() obj.Vehicleloan() # In[3]: #abstraction method # first we have to import ABC, abstraction method # In this we have to put decorator abstraction method from abc import ABC,abstractmethod class Abstractionmethod(ABC): @abstractmethod def Running(self): print("yes i am running") class Constructormethod(Abstractionmethod): def Running(self): print("changed into constructormethod") obj = Constructormethod() obj.Running() # In[4]: """Encapsulation means wrapping of data and methods""" # In[12]: #Data hiding means we having public and private data to access # whenever we start with __(double underscore) it means hiding we cant access out of class. we can access inside a class class Base: __a = 10 b = 30 def __Display(self): print(self.__a) print("a and b values display") def Show(self): self.__Display() obj = Base() print(obj.b) obj.Show() # In[1]: os.getdir() # In[3]: import os os.getcwd() # In[4]: os.path # In[ ]:
text = "This is a new text now\n" filename = "foo.txt" # apart from reading a file you can also # store data in it. This can be done by # adding a parameter in the open() function. # a : append -> will append at the end # w : write -> will overwrite (clears the file) # r : read # no parameter : automatically read # the file is created automatically, # once the open(..., "w") - function # in writing mode is initiated # we can use the "with" keyword to simplify # the file opening process with open(filename, "a") as f: f.write(text) # the file is closed automatically after # the "with" clause is over print("FINISHED WRITING, START READING") with open(filename, "r") as f: content = f.read() print(content) print("Done")
# coding=utf-8 # Task 1 # create a string, which is a welcome message, with a placeholder for the name # enter the name and print it. # reminder: # you can add placeholders and fill in variables like this: # greeting = "hello" # name = "my name" # print(f"Greeting: {greeting}, Name: {name}") name = "Alfred" print(f"Willkommen auf unserer Homepage {name}") # Task 2 # now create a welcome string with 2 placeholders and insert 2 variables vorname = "Joe" nachname = "Johnson" print(f"Begrüßungstext {vorname} {nachname}")