text
stringlengths
37
1.41M
class Node: def __init__(self, value): self.value = value self.next = None def __repr__(self): return str(self.value) class LinkedList: def __init__(self): self.head = None def __str__(self): cur_head = self.head out_string = "" while cur_head: out_string += str(cur_head.value) + " -> " cur_head = cur_head.next return out_string def append(self, value): if self.head is None: self.head = Node(value) return node = self.head while node.next: node = node.next node.next = Node(value) def size(self): size = 0 node = self.head while node: size += 1 node = node.next return size def union(llist_1, llist_2): nodes = set() current_node = llist_1.head while current_node: nodes.add(current_node.value) current_node = current_node.next current_node = llist_2.head while current_node: nodes.add(current_node.value) current_node = current_node.next new_head = Node(None) current_node = new_head for node in nodes: current_node.next = Node(node) current_node = current_node.next new_head = new_head.next new_list = LinkedList() new_list.head = new_head return new_list def intersection(llist_1, llist_2): nodes_set1 = set() current_node = llist_1.head while current_node: nodes_set1.add(current_node.value) current_node = current_node.next nodes_set2 = set() current_node = llist_2.head while current_node: nodes_set2.add(current_node.value) current_node = current_node.next new_head = Node(None) current_node = new_head for node in nodes_set1: if node in nodes_set2: current_node.next = Node(node) current_node = current_node.next new_head = new_head.next new_list = LinkedList() new_list.head = new_head return new_list # Test case 1 linked_list_1 = LinkedList() linked_list_2 = LinkedList() element_1 = [3, 2, 4, 35, 6, 65, 6, 4, 3, 21] element_2 = [6, 32, 4, 9, 6, 1, 11, 21, 1] for i in element_1: linked_list_1.append(i) for i in element_2: linked_list_2.append(i) print(union(linked_list_1, linked_list_2)) print(intersection(linked_list_1, linked_list_2)) # Test case 2 linked_list_3 = LinkedList() linked_list_4 = LinkedList() element_1 = [3, 2, 4, 35, 6, 65, 6, 4, 3, 23] element_2 = [1, 7, 8, 9, 11, 21, 1] for i in element_1: linked_list_3.append(i) for i in element_2: linked_list_4.append(i) print(union(linked_list_3, linked_list_4)) print(intersection(linked_list_3, linked_list_4)) # Test case 3 linked_list_5 = LinkedList() linked_list_6 = LinkedList() element_1 = [] element_2 = [] for i in element_1: linked_list_5.append(i) for i in element_2: linked_list_6.append(i) print(union(linked_list_5, linked_list_6)) # expected output: nothing print(intersection(linked_list_5, linked_list_6)) # expected output: nothing
# Loops spam = 0 if spam < 5: print("Enter Name") spam += 1 spam = 0 while spam < 5: print("Enter Name") spam += 1 name = '' while name != 'Your Name': print("Enter Your Name") name = input() print("thank you") # same code as above but using break statment while True: print("Enter your Name") name = input() if name == 'Your Name': break print("Thank you") # name = '' while not name: print("Enter Your Name") name = input() print("How many guests") noGuest = int(input()) if noGuest: print("All welcome") print('done') # For loops for i in range(5): print("Ak gud work"+" ("+str(i)+") ") # sum = 0 for i in range(101): sum = sum + i; print(sum) # range for i in range(10,20): print(i) for i in range(10,20,2): print(i) # Random Module import random for i in range(4): print(random.randint(1,15)) # System modeul import sys while True: print("Enter exit to exit from the program") response = input() if response == 'exit': sys.exit() print('Your response is '+response) import random print(random.randint(10,30)) print(random.random()) print(random.choice([1,2,5,6,7])) print(random.sample(range(1,80),20)) print(random.uniform(0,1)) import math print(math.ceil(3.2551)) # returns higher number print(math.fabs(3.2551)) print(math.factorial(5)) # factorial of number print(math.floor(3.268)) # returns lower number print(math.fmod(2.4,2)) # returns reminder mod function print(math.isnan(5)) print(math.log(100,10)) print(pow(2,5))
import numpy as np def get_wordlist(): f = open("nounlist.txt", "r") s = f.read() f.close() return s.splitlines() def hash(i, max): cycle = 2147483647 # MAGIC: 8th Mersenne Prime offset = 104729 ** 4 # MAGIC: 10,000th Prime return (i * cycle + offset) % max def hashword(i, K, words): N = len(words) j = hash(i, N ** K) word = str(j) + " " for k in range(K): word += words[j % N] j /= N return word def test_wordy(): wordlist = get_wordlist() N = len(wordlist) K = 3 for i in range(100): print hashword(i, K, wordlist) def test_injectiveness(): for Nwords in range(10000): count = np.zeros(Nwords) for i in range(Nwords): j = hash(i, Nwords) count[j] += 1 if np.any(count != 1): print Nwords, "FAIL" print "min count", np.min(count) print "max count", np.max(count) return False else: print Nwords, "PASS" return True if __name__ == "__main__": test_wordy()
""" Advent Of Code Day 1 """ from itertools import accumulate, cycle from common.input_file import read_numbers def get_sum_of_frequencies(numbers): """ Given a list of frequencies (positive and negative) What is the ending frequency when added together """ return sum(numbers) def get_first_frequency_listed_twice(numbers): """ Given a list of frequencies (positive and negative) What is the first cumulative frequency seen twice """ seen_so_far = set([0]) for running_total in accumulate(cycle(numbers)): if running_total in seen_so_far: return running_total seen_so_far.add(running_total) raise RuntimeError("This code is unreachable") NUMBERS = read_numbers("input/input1.txt") if __name__ == "__main__": print(get_sum_of_frequencies(NUMBERS)) print(get_first_frequency_listed_twice(NUMBERS))
""" Advent of Code 2019 Challenge 19 """ from common.input_file import read_strings from common.opcodes import OPCODE_MAPPING def to_opcode(op_str: str): """ Convert to an opcode """ opcode, reg1, reg2, output = op_str.split() return OPCODE_MAPPING[opcode], int(reg1), int(reg2), int(output) def get_program_value(instructions, instruction_register, registers): """ Get the program value in register 0 """ instruction_pointer = 0 while 0 <= instruction_pointer < len(instructions): registers[instruction_register] = instruction_pointer instruction, reg1, reg2, output = instructions[instruction_pointer] registers = instruction(reg1, reg2, output, registers) instruction_pointer = registers[instruction_register] + 1 return registers[0] def get_actual_value(target) -> int: """ the assembly given is actually just a sum all divisors of a number """ return sum(x for x in range(1, target+1) if target % x == 0) FILE_TEXT = read_strings("input/input19.txt") INSTRUCTION_REGISTER = int(FILE_TEXT[0].split()[-1]) INSTRUCTIONS = list(map(to_opcode, FILE_TEXT[1:])) if __name__ == "__main__": print(get_actual_value(875)) print(get_actual_value(10551275))
""" Advent of Code day 10 """ from collections import namedtuple from itertools import count import re from common.grid import Point, Grid, get_manhattan_distance, get_average_point from common.input_file import get_transformed_input def to_star(star_str): """ Takes a star string and converts it to a star """ regex = r"position=<\s*(-?\d+),\s*(-?\d+)> velocity=<\s*(-?\d+),\s* (-?\d+)>" match = re.match(regex, star_str) position = Point(int(match.group(1)), int(match.group(2))) return Star(position, int(match.group(3)), int(match.group(4))) Star = namedtuple("Star", ["position", "velocity_x", "velocity_y"]) def move_star(star): """ Move the star to the next location """ new_position = Point(star.position.x + star.velocity_x, star.position.y + star.velocity_y) return Star(new_position, star.velocity_x, star.velocity_y) def starfill(positions, point): """ Return a # if its a star, otherwise blank space """ return "#" if point in positions else " " def draw_grid_and_counter(starpos, positions, counter): """ Draw the grid given centered on starpos """ grid_params = { "top": starpos.y - 20, "bottom": starpos.y + 20, "left": starpos.x - 100, "right": starpos.x + 100, "fill_function": lambda point: starfill(positions, point) } bounded_grid = Grid(**grid_params) print(bounded_grid) print("*"* 80) print(counter) print("*"* 80) def run_animation(stars): """ Run the animation loop """ for counter in count(): positions = [star.position for star in stars] average_position = get_average_point(positions) if get_manhattan_distance(stars[0].position, average_position) < 1000: draw_grid_and_counter(stars[0].position, positions, counter) stars = [move_star(star) for star in stars] STARS = get_transformed_input("input/input10.txt", to_star) if __name__ == "__main__": run_animation(STARS)
multiples_of_3 = [] for nr in range(10): if nr % 2 == 0: multiples_of_3.append(nr * 3) print(multiples_of_3) multiples_of_3_comprehension = [nr * 3 for nr in range(10) if nr % 2 == 0] print(multiples_of_3_comprehension) words = ['bye', 'hello', 'hi', 'world'] word_lengths = [(word, len(word)) for word in words] print(word_lengths) word_length_dict = {word: len(word) for word in words if word.startswith('h')} print(word_length_dict) word_length_dict_multiply = {word.upper(): word_length * 10 for word, word_length in word_length_dict.items()} print(word_length_dict_multiply) l = [1, 1, 1, 3, 4, 3, 4, 2] unique_numbers_div_by_2 = {elem for elem in l if elem % 2 == 0} print(unique_numbers_div_by_2) m = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] l1 = [[row[i] for row in m] for i in range(3)] print(l1)
def count_common_elements(list1, list2): return len(set(list1) & set(list2)) print(count_common_elements([1, 1, 2, 3], [2, 3, 2, 2, 3, 4])) def count_unique_words(text): words = text.split() return len(set(words)) print(count_unique_words('hello hello is there anybody in there'))
import threading import time total = 0 lock = threading.Lock() def update_total(amount): """ Updates the total by the given amount """ global total # lock.acquire() # try: # for _ in range(1000000): # total += amount # finally: # lock.release() with lock: for _ in range(1000000): total += amount # Step 1: get total # Step 2: compute total + amount # Step 3: set total to new value (total + amount) print(total) time.sleep(1) if __name__ == '__main__': start_time = time.time() threads = [] for _ in range(10): my_thread = threading.Thread(target=update_total, args=(1,)) my_thread.start() threads.append(my_thread) for thread in threads: thread.join() end_time = time.time() print('Total', total) print(f'Total execution time: {end_time - start_time:.10f}')
# class Solution: # def flatten(self, root: TreeNode) -> None: # """ # Do not return anything, modify root in-place instead. # """ # def sub_flatten(node): # if node.left == None and node.right == None: # return (node, node) # l_node, r_node = node.left, node.right # if l_node != None: # head_l, tail_l = sub_flatten(l_node) # node.right = head_l # node.left = None # else: # head_l = node # tail_l = node # if r_node != None: # head_r, tail_r = sub_flatten(r_node) # tail_l.right = head_r # else: # tail_r = tail_l # return (node, tail_r) # if root == None: # return None # return sub_flatten(root)[0] # Greedy class Solution: def flatten(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ node = root while node: if node.left: most_right = node.left while most_right.right: most_right = most_right.right most_right.right = node.right node.right = node.left node.left = None node = node.right
class Node: def __init__(self, data=None, next_node=None): self.data = data self.next = next_node class LinkedList: def __init__(self): self.head = None def insert_at_beginning(self, data): node = Node(data, self.head) self.head = node def insert_at_end(self, data): new_node = Node(data) if self.head is None: self.head = new_node else: itr = self.head while itr.next: itr = itr.next itr.next = new_node def insert_values(self, list_of_values): for i in list_of_values: self.insert_at_end(i) def get_length(self): count = 0 itr = self.head while itr: count += 1 itr = itr.next return count def remove_at(self, index): if index < 0 or index >= self.get_length(): raise Exception("Invalid index") return if index == 0: self.head = self.head.next itr = self.head for i in range(index - 1): itr = itr.next itr.next = itr.next.next def insert_at(self, index, value): if index < 0 or index >= self.get_length(): raise Exception("Invalid Index") return if index == 0: self.insert_at_beginning(value) return itr = self.head for i in range(index - 1): itr = itr.next itr.next = Node(value, itr.next) def insert_after_value(self, data_after, data_to_insert): if self.head is None: print('Linked list is empty') itr = self.head while itr: if itr.data == data_after: itr.next = Node(data_to_insert, itr.next) break itr = itr.next def remove_by_value(self, data_to_remove): if self.head is None: return if self.head.data == data_to_remove: self.head = self.head.next return itr = self.head while itr.next: if itr.next.data == data_to_remove: itr.next = itr.next.next break itr = itr.next def print_list(self): if self.head is None: print("Linked list is empty") else: itr = self.head llist = "" while itr: llist += str(itr.data) + "-->" itr = itr.next print(llist) if __name__ == "__main__": ll = LinkedList() ll.insert_values([90, 45, 24, 14, 56, 46, 25, "mango"]) ll.print_list() ll.remove_by_value("oijero") ll.print_list()
"""Implementation of a Class that constructs an dynamic system from an ode.""" import numpy as np import torch from scipy import integrate, signal from .abstract_system import AbstractSystem from .linear_system import LinearSystem class ODESystem(AbstractSystem): """A class that constructs an dynamic system from an ode. Parameters ---------- func : callable. func is the right hand side of as xdot = f(t, x). with actions, extend x to be states, actions. step_size : float dim_state: Tuple dim_action : Tuple """ def __init__( self, func, step_size, dim_state, dim_action, integrator=integrate.RK45 ): super().__init__(dim_state=dim_state, dim_action=dim_action) self.step_size = step_size self.func = func self._state = np.zeros(dim_state) self._time = 0 self.integrator = integrator def step(self, action): """See `AbstractSystem.step'.""" integrator = self.integrator( lambda t, y: self.func(t, y, action), 0, self.state, t_bound=self.step_size ) while integrator.status == "running": integrator.step() self.state = integrator.y # self._reward = self.state self._time += self.step_size return self.state def reset(self, state=None): """See `AbstractSystem.reset'.""" self.state = state return self.state def linearize(self, state=None, action=None): """Linearize at a current state and action using torch autograd. By default, it considers the linearization at state=0, action=0. Parameters ---------- state: State, optional. State w.r.t. which linearize. By default linearize at zero. action: Action, optional. Action w.r.t. which linearize. By default linearize at zero. Returns ------- sys: LinearSystem """ if state is None: state = np.zeros(self.dim_state) if action is None: action = np.zeros(self.dim_action) if type(state) is not torch.Tensor: state = torch.tensor(state) if type(action) is not torch.Tensor: action = torch.tensor(action) state.requires_grad = True action.requires_grad = True f = self.func(None, state, action) a = np.zeros((self.dim_state[0], self.dim_state[0])) b = np.zeros((self.dim_state[0], self.dim_action[0])) for i in range(self.dim_state[0]): aux = torch.autograd.grad( f[i], state, allow_unused=True, retain_graph=True )[0] if aux is not None: a[i] = aux.numpy() aux = torch.autograd.grad( f[i], action, allow_unused=True, retain_graph=True )[0] if aux is not None: b[i] = aux.numpy() ad, bd, _, _, _ = signal.cont2discrete( (a, b, 0, 0), self.step_size, method="zoh" ) return LinearSystem(ad, bd) @property def state(self): """See `AbstractSystem.state'.""" return self._state @state.setter def state(self, value): self._state = value @property def time(self): """See `AbstractSystem.time'.""" return self._time
def ask(name="111"): print(name) class Person: def __init__(self): print("init") def decorate_de(): print("dec start") return ask asktest = decorate_de() asktest("aaa") obj_list = [] obj_list.append(ask) obj_list.append(Person) for item in obj_list: print(item()) # my_func = ask # my_func("zhengqiang")
def dobro(num): print(f'O dobro de {num} é ', end='') return num * 2 def triplo(num): print(f'O triplo de {num} é {num * 3}') def raiz(num): return f'A raíz quadrada de {num} é ' + str(num ** 0.5) #Programa principal n = int(input('Digite um número: ')) print(dobro(n)) triplo(n) print(raiz(n))
''' Crie um programa que tenha uma função fatorial() que receba dois parâmetros: o primeiro que indique o número a calcular e outro chamado show, que será um valor lógico (opcional) indicando se será mostrado ou não na tela o processo de cálculo do fatorial. ''' def fatorial(num, show=False): ''' Calcula o fatorial do número pedido :param num: número pedido pelo usuário :param show: móstra ou não o fatorial :return: mostra o calculo do fatorial ''' c = num f = 1 while c > 0: if show: print(f'{c}', end='') print(' x ' if c > 1 else ' = ', end='') f *= c c -= 1 return f #Programa principal num = int(input('Qual número deseja saber o Fatorial? ')) print(fatorial(num, show=False))
''' Crie um programa que leia nome, ano de nascimento e carteira de trabalho e cadastre-o (com idade) em um dicionário. Se por acaso a CTPS for diferente de ZERO, o dicionário receberá também o ano de contratação e o salário. Calcule e acrescente, além da idade, com quantos anos a pessoa vai se aposentar. ''' from datetime import date infotrabalhador = dict() infotrabalhador['Nome'] = str(input('Nome: ')) anoatual = date.today().year infotrabalhador['Idade'] = anoatual - int(input('Ano de Nascimento: ')) infotrabalhador['CTPS'] = int(input('Nº da Carteira de Trabalho?(0 - Nã o tem) ')) if infotrabalhador['CTPS'] > 0: infotrabalhador['Contratação'] = int(input('Ano da Contratação? ')) infotrabalhador['Salário'] = float(input('Salário:R$ ')) infotrabalhador['Aposentadoria'] = infotrabalhador['Contratação'] + 35 print('-='*30) print(infotrabalhador) for k, v in infotrabalhador.items(): print(f'{k} tem valor {v}')
''' Crie um programa onde o usuário digite uma expressão qualquer que use parênteses. Seu aplicativo deverá analisar ser a expressão passada está com os parênteses abertos e fechados na ordem correta. ''' expressao = str(input('Digite uma expressão com parênteses: ')) pilha = list() for parenteses in expressao: if '(' in expressao: pilha.append('(') elif ')' in expressao: if len(pilha) > 0: pilha.pop() else: pilha.append(')') if len(pilha) == 0: print('sua expressão está certa!') else: print('Sua expressão está errada!') print(lista)
''' Crie um programa que tenha a função leiaInt(), que vai funcionar de forma semelhante 'a função input() do Python, só que fazendo a validação para aceitar apenas um valor numérico. Ex: n = leiaInt('Digite um n: ') ''' def leiaINT(num): while True: a = str(input(num)) if a.isnumeric() == True: return int(a) break #elif a.isalpha() == True: #print(f'ERRO! Digite um número inteiro válido.') #elif a.isspace() == True: #print(f'ERRO! Digite um número inteiro válido.') else: print(f'ERRO! Digite um número inteiro válido.') #Programa principal n = leiaINT('Digite um número: ') print(f'Você acabou de digitar o número {n}')
def dolar(num): cot = float(input('Qual a cotação do Dólar atual? ')) conversão = cot * num return f'R${num:.2f} em equivalem a US${conversão:.2f}' #Programa Principal carteira = float(input('Quanto você deseja converter? ')) print(dolar(carteira))
''' Faça um programa que ajude um jogador da MEGA SENA a criar palpites. O programa vai perguntar quantos jogos serão gerados e vai sortear 6 números entre 1 e 60 para cada jogo, cadastrando tudo em uma lista composta. ''' from random import randint lista = [] listaflu = [] print('-'*30) print(f'{"JOGA NA MEGA SENA":^30}') print('-'*30) jogos = int(input('Quantos jogos deseja fazer?')) for c in range(1, jogos+1): # quantos jogos for c in range(0,6): # números por jogo num = randint(1, 60) listaflu.append(num) if num in lista == num: num = randint(1, 60) listaflu.append(num) lista.append(listaflu[:]) listaflu.clear() for p, c in enumerate(lista): print(f'Jogo {p+1}: ',end=' ') print(lista[p])
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 20 11:45:44 2020 @author: - """ import numpy as np import xarray as xr def area_weighted_sum(data): """ Compute area weighted sum of some CMIP6 data. Parameters ---------- data : xarray DataArray DataArray containing the data to average. Assumes lat dimension/coordinate is called 'lat' and lon dimension/coordinate is called 'lon' Returns ------- dout : xarray DataArray DataArray containing area-weighted sum of data. Has lost domensions of lat and lon """ lat = data.lat coslat = np.cos(np.deg2rad(lat)) dout = (data*coslat).sum(('lat', 'lon')) return dout def area_weighted_mean(data): """ Compute area weighted mean of some CMIP6 data. Parameters ---------- data : xarray DataArray DataArray containing the data to average. Assumes lat dimension/coordinate is called 'lat' and lon dimension/coordinate is called 'lon' Returns ------- dout : xarray DataArray DataArray containing area-weighted sum of data. Has lost domensions of lat and lon """ lat = data.lat coslat = np.cos(np.deg2rad(lat)) if len(lat.dims) == 1: dout = (data*coslat).sum(('lat', 'lon'))/coslat.sum('lat') else: dout = (data*coslat).sum(('lat', 'lon'))/coslat.sum('lat', 'lon') return dout
""" 奖与罚 编译者:PengPeng3g v1.0 增加奖与罚 v2.0 增加循环节,增加初中,高中成绩 编译时间:2020.8.16 当前版本:v2.0 """ tuichugaozhong = False tuichuchuzhong = False tuichu = False xuanzenianji=(input("输入年级(初中chuzhong,小学xiaoxue,高中gaozhong)")) if xuanzenianji == "xiaoxue": tuichu = True if xuanzenianji == 'chuzhong': tuichuchuzhong = True if xuanzenianji == 'gaozhong': tuichugaozhong = True while tuichu: xiaoxuechengji=int(input("输入你的成绩(输入888退出):")) if xiaoxuechengji == 300: print("任何东西") elif xiaoxuechengji == 888: tuichu = False elif xiaoxuechengji > 290: print("手机走起") elif xiaoxuechengji > 280: print('现金不定') elif xiaoxuechengji > 270: print("现金些许") elif xiaoxuechengji > 260: print("试卷一套") elif xiaoxuechengji > 250: print("补习班耶") else: print("舒服按摩") while tuichuchuzhong: chuzhongchengji = int(input("输入你的成绩(输入888退出):")) if chuzhongchengji > 730: print("长辈夸赞+任何东西") elif chuzhongchengji == 888: tuichuchuzhong = False elif chuzhongchengji < 700: print("新手机一台") elif chuzhongchengji < 690: print("现金不等") elif chuzhongchengji < 500: print("还行") elif chuzhongchengji < 400: print("奖励试卷一套") elif chuzhongchengji < 200: print("最喜欢的大嘴巴子+一个假期的补习班") else: print("父母混合打") while tuichugaozhong: gaozhongchengji=int(input("输入你的成绩(输入888退出):")) if gaozhongchengji > 720: print("任何东西") elif gaozhongchengji == 888: tuichugaozhong = False elif gaozhongchengji > 700: print("父母赞扬+现金不等") elif gaozhongchengji > 600: print("些许东西") elif gaozhongchengji > 500: print("一点东西") elif gaozhongchengji > 400: print("冷漠") elif gaozhongchengji > 200: print("父母混合打") else: print("父母失望")
""" Writting functions for processing """ # function to calculate BMI Index def BMI_Calculation(tall, weight): result_bmi = (weight/(tall**2)) return result_bmi # function to check BMI Status def BMI_Check(result): final_result = "" if(result < 18.5): final_result = "C" elif(result >= 18.5 and result <= 24.9): final_result = "A" else: final_result = "B" return final_result """ Writting code """ # Introduce program name print ("Welcome to Demo_BMI") # Request enter input print ("Your tall (m): ") tall = float(input()) print ("Your weight (kg): ") weight = float(input()) # Call processing function result = BMI_Calculation(tall,weight) final_result = BMI_Check(result) # Export output print ("Your BMI Index is: %s" % result) print ("Your heathy status is: %s" % final_result)
import pymongo, sys, re import pandas as pd import requests import lxml.html as lh url='https://www.nationsonline.org/oneworld/IATA_Codes/airport_code_list.htm' #Create a handle, page, to handle the contents of the website page = requests.get(url) #Store the contents of the website under doc doc = lh.fromstring(page.content) #Parse data that are stored between <tr>..</tr> of HTML tr_elements = doc.xpath('//tr') #print [len(T) for T in tr_elements[:12]] tr_elements = doc.xpath('//tr') #Create empty list col=[] i=0 l = ['','City/Airport', 'Country', 'IATA'] for t in tr_elements[1]: i+=1 name = l[i] #print '%d:"%s"'%(i,name) col.append((name,[])) #Since first row is the header, data is stored on the second row onwards for j in range(1,len(tr_elements)): #T is our j'th row T=tr_elements[j] #If row is not of size 10, the //tr data is not from our table if len(T)!=3: continue #i is the index of our column i=0 #Iterate through each element of the row for t in T.iterchildren(): data=t.text_content() #Append the data to the empty list of the i'th column col[i][1].append(data) #Increment i for the next column i+=1 # Dictionary with 3 keys City/Airport, Country, and IATA Dict = {title:column for (title,column) in col} # code = "MIAC3-C1" # print "Searching dictionary to find "+code+" location..." # key = 'IATA' # for i in range(0,len(Dict[key])): # #print "Searching "+str(i)+" ..." # if Dict[key][i] in code: # print "Match found!"+" "+code+" = "+Dict[key][i] # print "This is in "+Dict['City/Airport'][i]+", "+Dict['Country'][i] client = pymongo.MongoClient('localhost', 27017) db = client['data'] collection = db['test1'] doc_count = collection.count_documents({}) numer = 0 for doc in collection.find(): loc = doc['location'] # code should be the data's location code = loc print "Searching dictionary to find "+loc+" location..." key = 'IATA' for i in range(0,len(Dict[key])): #print "Searching "+str(i)+" ..." if Dict[key][i] in code: city = Dict['City/Airport'][i] country = Dict['Country'][i] print "Match found!"+" "+code+" = "+Dict[key][i] print "This is in "+city+", "+country # if it already exits, then skip collection.update_one({'_id': doc['_id']}, {'$push': {'City/Airport': city}}, upsert = True) collection.update_one({'_id': doc['_id']}, {'$push': {'Country': country}}, upsert = True) collection.update_one({'_id':doc['_id']}, {'$push': {'IATA': Dict[key][i]}}, upsert = True) break percent = float(numer) / float(doc_count) print "Percent done: "+str(percent*100)+"%" numer+=1 print "Finished."
# Time Complexity: O(mn) where m is the number of rows and n is the number of columns # Space Complexity: O(mn) where m is the number of rows and n is the number of columns # Ran on Leetcode: Yes class Solution: def numIslands(self, grid: List[List[str]]) -> int: count = 0 self.m = len(grid) self.n = len(grid[0]) if not len(grid): return 0 for i in range(self.m): for j in range(self.n): if grid[i][j] == "1": self.dfs(grid, i, j) count += 1 return count def dfs(self, grid, i, j): if i < 0 or j < 0 or i >= self.m or j >= self.n or grid[i][j] == "0": return grid[i][j] = "0" dirs = [[0,1], [0,-1], [1,0], [-1,0]] for d in dirs: r = i + d[0] c = j + d[1] self.dfs(grid, r, c) return
import math import tkinter as tk from tkinter import ttk from tkinter import messagebox as m_box from tkinter import filedialog import numpy as np class Additional: def __init__(self) : # self.coba() pass def check_empty_row(self, s_dict, nested_dict = False, specify_column = None) : ''' CHECK & REMOVE ROWS WITH EMPTY VALUE. Return a dict that previously have empty value to a clean dict that will be projected as a table. #s_dict = dictionary storage --> the dict can be both ordinary dict with the value within a list or nested dict which is a dict inside a dict that also contains the value in a list. #nested_dict = is a boolean(False, True) statement to state the type of the dict originally False --> if you have nested dict, please mark it as True #specify_column = is a statement whether the function need to specify the column to check or not(check all columns), originally stated as False --> if you need to specify the columns, please write it as a list or tuple of the table heads for example : specify_column = False #check all column specify_column = ('A', 'B') #check only 'A' and 'B' specify_column = ['A', 'B'] #check only 'A' and 'B' column ''' counted_col = [] if specify_column == None : if nested_dict == False : for x in s_dict.keys() : counted_col.append(x) else : for x in s_dict.keys() : for y in s_dict[x] : if y not in counted_col: counted_col.append(y) else : pass else : counted_col = specify_column if nested_dict == False : for x in counted_col : if x in list(s_dict.keys()) : pass else : m_box.showerror( '¯\_(ツ)_/¯', 'Mianhae..\nSome of the mandatory variables aren\'t available in your data head !' ) else : a = list(s_dict.keys())[0] for x in counted_col : if x in list(s_dict[a].keys()) : pass else : m_box.showerror( '¯\_(ツ)_/¯', 'Mianhae..\nSome of the mandatory variables aren\'t available in your data head !' ) if nested_dict == False : c = 0 c_empty = [] empty = [] count = [] for x in range(0, len(list(s_dict.values())[0])): for y in counted_col : #ori --> for y in s_dict.keys() empty.append(list(s_dict[y])[c]) if len(empty) == len(counted_col): #ori --> if len(empty) == len(s_dict.keys()): for z in empty : if isinstance(z, str) or math.isnan(z) == True : count.append(z) else : pass if len(count) > 0 : c_empty.append(c) else : pass else : pass empty = [] count = [] c += 1 #del column for ordinary dict (general) minus = 0 c = 0 for n in c_empty : c_empty[c] = n + minus c += 1 minus -= 1 for r in c_empty : for m in s_dict.keys() : del s_dict[m][r] else : #nested dict + counted specific columns val = [] s_empty = {} for x in s_dict.keys() : for d in range(0, len(list(s_dict[x].values())[0])) : for y in counted_col : #ori --> for y in s_dict[x] : val.append(s_dict[x][y][d]) if len(val) == len(counted_col): #ori --> if len(val) == len(list(s_dict[x].keys())): for t in val : if isinstance(t, str) or math.isnan(t) == True : if x not in list(s_empty.keys()) : s_empty[x] = [d] else : if d not in s_empty[x] : s_empty[x].append(d) else : pass else : pass else : pass val = [] #del column for nested dict (general) minus = 0 for x in s_empty.keys() : for y in s_empty[x] : c = y c += minus for z in s_dict[x].keys() : del s_dict[x][z][c] minus -= 1 minus = 0 #FOR KEY LAYER WITH ZERO VAL empty = [] for x in s_dict.keys() : for y in s_dict[x].keys() : if len(list(s_dict[x][y])) == 0 : if x not in empty : empty.append(x) else : pass else : pass for x in empty : del s_dict[x] return s_dict def make_table(self, frame, s_dict, number = True, entry_state = 'normal', get_last_row = False ) : ''' FUNCTION TO MAKE TABLE. there are two kinds of table that possible to be made : 1. Number = True -> for left side head, instead of using specific name, this table uses ordered number such as [1,2,3,4,5,6, etc] NOTE : ** for this kind of table, the last dict as ordinary dict with list inside. {'Key1' : [a,b,c,d,e], 'Key2' : [d,e,f,g,h]} ** the side number aren't considered as the part of the dict, the order only considered by the index of each value inside the list. 2. Number = False -> the left side head are more flexible to use and it is possible to contain a specific label name instead of an ordered numbers NOTE : ** for this kind of table, results written as nested dict. { 'Side_head_key1' : {'Upper_head_key1' : [a,b,c,d,e], 'Upper_head_key2' : [f,g,h,i,j]}, 'Side_head_key2' : {'Upper_head_key1' : [k,l,m,n,o], 'Upper_head_key2' : [p,q,r,s,t]} } ''' total_rows = len(list(s_dict.values())[0]) #assume every col has the same len as 1st col total_columns = len(list(s_dict)) if number == True : #CREATE NUMBER IN TABLE order_list = [''] order = np.arange(1 , total_rows+1) for i in order : order_list.append(i) b = 0 for r in order_list : order_lbl = ttk.Label(frame, text = r, width = 3) order_lbl.grid(row = b, column = 0) b += 1 else : #CREATE SIDE HEAD IN TABLE ''' Mianhabnida, bcs i'm too not in the mood of opening any nested dict, so, I choose to separate keys and sub keys in nested into different section. then, to sync those two, I prefer to use the references of rows. THAT'S ALL.. :) ''' s_dict_temporary = {} order_list = [] for key, val in s_dict.items(): n = 1 for x in s_dict[key].keys(): for val in s_dict[key][x] : if n > len(s_dict[key][x]): pass else : order_list.append(key) n += 1 if x not in s_dict_temporary.keys(): s_dict_temporary[x] = [val] else : s_dict_temporary[x].append(val) s_dict = s_dict_temporary.copy() sidehead_dict = {} b = 1 ref_r = 0 row_store = [] just_r = [] n = 1 for r in order_list : if r not in just_r : just_r.append(r) sidehead_entry = ttk.Entry(frame, textvariable = r, width = 7, state = entry_state ) else : sidehead_entry = ttk.Entry(frame, textvariable = f'{r}_{n}', width = 7, state = entry_state ) n += 1 sidehead_entry.grid(row = b, column = 0) sidehead_entry.delete(0, len(str(sidehead_entry.get()))) #BIAR GA TUMPUK KALO CLICK 2X sidehead_entry.insert(0, r) if sidehead_entry not in list(sidehead_dict.keys()): sidehead_dict[sidehead_entry] = [ref_r] else : sidehead_dict[sidehead_entry].append(ref_r) b += 1 ref_r += 1 #[0,0] table head if nested = True data_head_btn_0 = ttk.Button(frame, width = 6, state = 'disabled', text = 'Layer' ) data_head_btn_0.grid(row = 0, column = 0) #FINAL RESULT DICT table_data_dict = {} #empty dict for final dict table_data_sublist = [] #empty list for temporary sublist #CREATE TABLE HEADER n = 0 #head number r = 0 #row c = 1 #column for h, sub_h in s_dict.items() : data_head_btn = ttk.Button(frame, width = 15, state = 'disabled', text = list(s_dict)[n] ) data_head_btn.grid(row = r, column = c) table_data_dict[list(s_dict)[n]] = [] #input {'key' : [empty]} into final dict as the amount of col table_data_sublist.append ([]) #create empty list in sublist as the amount of col n +=1 c +=1 #CREATE TABLE ENTRY n = 0 #head order m = 0 #head_list order c = 1 #column r = 1 #row r_x_c = len(list(s_dict.values())[0])*len(list(s_dict)) #row x column for i in range (1, r_x_c+1): entry_data_table = ttk.Entry(frame, width = 16, textvariable = str(list(s_dict)[n]) + '_' + str(m), state = entry_state ) if r == (len(list(s_dict.values())[0])+1) : n += 1 m = 0 c += 1 r = 1 entry_data_table.grid(row = r , column = c ) entry_data_table.delete(0, len(str(entry_data_table.get()))) #BIAR GA TUMPUK KALO CLICK 2X entry_data_table.insert(0, list(s_dict.values())[n][m]) table_data_sublist[n].append(entry_data_table) #create list member in sublist m += 1 r += 1 last_row = r #ini (last row occupied +1) #SUMMARIZE SUBLIST INTO FINAL RESULT DICT {'dict_key' : [ sublist ]} n = 0 for x in range(0, len(list(s_dict))): member_sub_list = table_data_sublist[n][:] table_data_dict[list(s_dict)[n]].extend(member_sub_list) n += 1 #sync keys and sub_keys in nested dict last_storage = {} if number != True : for key, y in sidehead_dict.items() : last_storage[key] = {} for x in sidehead_dict[key]: for a, b in table_data_dict.items(): if a not in last_storage[key].keys() : last_storage[key][a] = [table_data_dict[a][x]] else : last_storage[key][a].append(table_data_dict[a][x]) table_data_dict = last_storage.copy() else : pass if get_last_row == True : return last_row, table_data_dict else : return table_data_dict print(table_data_dict) def extract_table (self, s_tkinter_dict, nested_dict = False): ''' EXTRACT DICT THAT CONTAIN TKINTER ENTRY TABLE. ''' if nested_dict == False : n = 0 store_value = [] s_test = {} for y in range (0, len(list(s_tkinter_dict))): s_test[list(s_tkinter_dict)[n]] = [] #store_value.append ([]) n += 1 for head, etc in s_tkinter_dict.items(): store_value.extend(s_tkinter_dict[head]) n = 0 m = 1 for y in store_value : try : if '.' in str(y.get()) : s_test[list(s_tkinter_dict)[n]].append( float(y.get() )#float ) else : s_test[list(s_tkinter_dict)[n]].append( int(y.get() )#int ) except ValueError : s_test[list(s_tkinter_dict)[n]].append( y.get() )#string m += 1 #Ini row+1 baru ganti line ya, wkwkwkwk.. if m == (len(list(s_tkinter_dict.values())[0])+1): n += 1 m = 1 else : #I STRONGLY SUGGEST TO USE ANOTHER DICT TO SAVE THE RESULT #USE THE DICT CAN CAUSE AN ADDITIONAL PROBLEM LIKE IT CHANGE THE ORIGINAL DICT UNINTENDEDLY n = 0 d = {} for z in s_tkinter_dict.keys(): try : z_out = z.get() except AttributeError : z_out = z z_out = z_out.strip() if z_out not in list(d.keys()) : d[z_out] = {} else : pass for b in s_tkinter_dict[z].keys() : if b not in list(d[z_out].keys()) : d[z_out][b]= [] else : pass for c in s_tkinter_dict[z][b] : try : c.get() try : if '.' in str(c.get()): d[z_out][b].append(float(c.get())) else : d[z_out][b].append(int(c.get())) except ValueError : d[z_out][b].append(str(c.get())) except AttributeError : try : if '.' in str(c) : d[z_out][b].append(float(c)) else : d[z_out][b].append(int(c)) except ValueError : d[z_out][b].append(str(c)) s_test = d.copy() return s_test def reverse_head(self, current_dict) : #FOR KEY LAYER WITH ZERO VAL empty = [] for x in current_dict.keys() : for y in current_dict[x].keys() : if len(list(current_dict[x][y])) == 0 : if x not in empty : empty.append(x) else : pass else : pass for x in empty : del current_dict[x] c_current_dict = current_dict.copy() spc = 0 for y in current_dict.keys() : for z in str(y) : if z != ' ' : spc += 1 else : pass if spc == 0 : del c_current_dict[y] spc = 0 current_dict = c_current_dict.copy() ori_head_0 = list(current_dict.keys())[0] for_new_head = [] for x in current_dict[ori_head_0].keys() : for_new_head.append(x) new_dict = {} for x in for_new_head : if x not in list(new_dict.keys()) : new_dict[x] = {} else : pass for y in current_dict.keys() : new_dict[x][y] = current_dict[y][x].copy() return new_dict def head_reorder(self, s_dict, head_key, nested_dict = False) : if nested_dict == False : new_dict = {} head_key1 = [] head_key2 = [] for y in list(s_dict.keys()) : if y == head_key : head_key1.append(y) else : head_key2.append(y) head_key1.extend(head_key2) for x in head_key1 : new_dict[x] = s_dict[x] else : new_dict = {} head_key1 = [] head_key2 = [] head_0 = list(s_dict.keys())[0] for y in s_dict[head_0].keys() : if y == head_key : head_key1.append(y) else : head_key2.append(y) head_key1.extend(head_key2) for x in head_key1 : for z in s_dict.keys() : if z not in list(new_dict.keys()) : new_dict[z] = {} else : pass new_dict[z][x] = s_dict[z][x].copy() return new_dict def coba(self) : s_test1 = { 'Q' : [1 ,2 ,3 ,'', ''], 'Pwf' : [1 ,'',3 ,4 , ''], 'Pr' : ['',2 ,3 ,4 , ''] } s_test = { 'Layer1' : {'Q' : [100,2 ,3 ,''], 'Pwf': [120,'','str',4]}, 'Layer2' : {'Q' : [130,2 ,3 ,''], 'Pwf': [140,'',3 ,4]}, 'Layer3' : {'Q' : ['', ''], 'Pwf': ['', '']} } # result = self.check_empty_row(s_dict = s_test1, # specify_column = ('Pwf'), # nested_dict = False # ) # result = self.reverse_head(s_test) result = self.head_reorder(s_test, 'Pwf', nested_dict = True) print(result) Additional() # def check_empty_row (self, s_dict, specify_column = False, nested_dict = False) : # ''' # CHECK & REMOVE ROWS WITH EMPTY VALUE. # ''' # counted_col = [] # if specify_column == False : # if nested_dict == False : # for x in s_dict.keys() : # counted_col.append(x) # else : # for x in s_dict.keys() : # for y in s_dict[x] : # if y not in counted_col: # counted_col.append(y) # else : # pass # else : # counted_col = specify_column # if nested_dict == False : # if specify_column == False : # #ordinary dict + counted all columns # c = 0 # c_empty = [] # empty = [] # count = [] # for x in range(0, len(list(s_dict.values())[0])): # for y in s_dict.keys(): # empty.append(list(s_dict[y])[c]) # if len(empty) == len(s_dict.keys()): # for z in empty : # if isinstance(z, str) or math.isnan(z) == True : # count.append(z) # else : # pass # if len(count) > 0 : # c_empty.append(c) # else : # pass # else : # pass # empty = [] # count = [] # c += 1 # else : # #ordinary dict + counted specific columns # c = 0 # c_empty = [] # empty = [] # count = [] # for x in range(0, len(list(s_dict.values())[0])): # for y in counted_col : #specify # empty.append(list(s_dict[y])[c]) # if len(empty) == len(counted_col): #specify # for z in empty : # if isinstance(z, str) or math.isnan(z) == True : # count.append(z) # else : # pass # if len(count) > 0 : # c_empty.append(c) # else : # pass # else : # pass # empty = [] # count = [] # c += 1 # #del column for ordinary dict (general) # minus = 0 # c = 0 # for n in c_empty : # c_empty[c] = n + minus # c += 1 # minus -= 1 # for r in c_empty : # for m in s_dict.keys() : # del s_dict[m][r] # else : # if specify_column == False : # #nested dict + counted all columns # val = [] # s_empty = {} # for x in s_dict.keys() : # for d in range(0, len(list(s_dict[x].values())[0])) : # for y in s_dict[x].keys() : # val.append(s_dict[x][y][d]) # if len(val) == len(list(s_dict[x].keys())): # for t in val : # if isinstance(t, str) or math.isnan(t) == True : # if x not in list(s_empty.keys()) : # s_empty[x] = [d] # else : # if d not in s_empty[x] : # s_empty[x].append(d) # else : # pass # else : # pass # else : # pass # val = [] # else : # #nested dict + counted specific columns # val = [] # s_empty = {} # for x in s_dict.keys() : # for d in range(0, len(list(s_dict[x].values())[0])) : # for y in counted_col : #specify # val.append(s_dict[x][y][d]) # if len(val) == len(counted_col): #specify # for t in val : # if isinstance(t, str) or math.isnan(t) == True : # if x not in list(s_empty.keys()) : # s_empty[x] = [d] # else : # if d not in s_empty[x] : # s_empty[x].append(d) # else : # pass # else : # pass # else : # pass # val = [] # #del column for nested dict (general) # minus = 0 # for x in s_empty.keys() : # for y in s_empty[x] : # c = y # c += minus # for z in s_dict[x].keys() : # del s_dict[x][z][c] # minus -= 1 # minus = 0 # #FOR KEY LAYER WITH ZERO VAL # empty = [] # for x in s_dict.keys() : # for y in s_dict[x].keys() : # if len(list(s_dict[x][y])) == 0 : # if x not in empty : # empty.append(x) # else : # pass # else : # pass # for x in empty : # del s_dict[x] # return s_dict #NESTED DICT EXTRACT WITHOUT USING ADDITIONAL DICT # n = 0 # for z in s_tkinter_dict.keys(): # for b in s_tkinter_dict[z].keys() : # for c in s_tkinter_dict[z][b] : # try : # c.get() # try : # if '.' in str(c.get()): # s_tkinter_dict[z][b][n] = float(c.get()) # else : # s_tkinter_dict[z][b][n] = int(c.get()) # except ValueError : # s_tkinter_dict[z][b][n] = str(c.get()) # except AttributeError : # try : # if '.' in str(c) : # s_tkinter_dict[z][b][n] = float(c) # else : # s_tkinter_dict[z][b][n] = int(c) # except ValueError : # s_tkinter_dict[z][b][n] = str(c) # n += 1 # n = 0 # r = 0 # d = {} # for x in s_tkinter_dict.keys() : # x = x.get() # if x not in list(d.keys()) : # d[x] = [r] # else : # d[x].append(r) # r += 1 # s_test = {} # for x in d.keys() : # for y in d[x] : # name = list(s_tkinter_dict.keys())[y] # if x not in list(s_test.keys()) : # s_test[x] = s_tkinter_dict[name] # else : # for m in s_tkinter_dict[name].keys() : # s_test[x][m].extend(s_tkinter_dict[name][m])
class Node: def __init__(self, key, data): self.left=None self.right=None self.parent=None self.key=key self.data=data class BST: def __init__(self): self.root=None def treeInsert(tree, node): y=None x=tree.root while x is not None: y=x if node.key < x.key: x=x.left else: x=x.right node.parent=y if y is None: tree.root=node elif node.key<y.key: y.left=node else: y.right=node def inorderTreeWalk(x): if x is not None: inorderTreeWalk(x.left) print(x.key) inorderTreeWalk(x.right) def iterTreeSearch(x, k): while x is not None and k!=x.key: if k<x.key: x=x.left else: x=x.right return x
import sys from BitVector import * # Author: Tanmay Prakash # tprakash at purdue dot edu # Solve x^p = y for x # for integer values of x, y, p # Provides greater precision than x = pow(y,1.0/p) # Example: # >>> x = solve_pRoot(3,64) # >>> x # 4L e = 65537 #function to generate the random prime number import random #this is from the lecture ############################ class PrimeGenerator ############################## class PrimeGenerator( object ): #(A1) def __init__( self, **kwargs ): #(A2) bits = debug = None #(A3) if 'bits' in kwargs : bits = kwargs.pop('bits') #(A4) if 'debug' in kwargs : debug = kwargs.pop('debug') #(A5) self.bits = bits #(A6) self.debug = debug #(A7) self._largest = (1 << bits) - 1 #(A8) def set_initial_candidate(self): #(B1) candidate = random.getrandbits( self.bits ) #(B2) if candidate & 1 == 0: candidate += 1 #(B3) candidate |= (1 << self.bits-1) #(B4) candidate |= (2 << self.bits-3) #(B5) self.candidate = candidate #(B6) def set_probes(self): #(C1) self.probes = [2,3,5,7,11,13,17] #(C2) # This is the same primality testing function as shown earlier # in Section 11.5.6 of Lecture 11: def test_candidate_for_prime(self): #(D1) 'returns the probability if candidate is prime with high probability' p = self.candidate #(D2) if p == 1: return 0 #(D3) if p in self.probes: #(D4) self.probability_of_prime = 1 #(D5) return 1 #(D6) if any([p % a == 0 for a in self.probes]): return 0 #(D7) k, q = 0, self.candidate-1 #(D8) while not q&1: #(D9) q >>= 1 #(D10) k += 1 #(D11) if self.debug: print("q = %d k = %d" % (q,k)) #(D12) for a in self.probes: #(D13) a_raised_to_q = pow(a, q, p) #(D14) if a_raised_to_q == 1 or a_raised_to_q == p-1: continue #(D15) a_raised_to_jq = a_raised_to_q #(D16) primeflag = 0 #(D17) for j in range(k-1): #(D18) a_raised_to_jq = pow(a_raised_to_jq, 2, p) #(D19) if a_raised_to_jq == p-1: #(D20) primeflag = 1 #(D21) break #(D22) if not primeflag: return 0 #(D23) self.probability_of_prime = 1 - 1.0/(4 ** len(self.probes)) #(D24) return self.probability_of_prime #(D25) def findPrime(self): #(E1) self.set_initial_candidate() #(E2) if self.debug: print(" candidate is: %d" % self.candidate) #(E3) self.set_probes() #(E4) if self.debug: print(" The probes are: %s" % str(self.probes)) #(E5) max_reached = 0 #(E6) while 1: #(E7) if self.test_candidate_for_prime(): #(E8) if self.debug: #(E9) print("Prime number: %d with probability %f\n" % (self.candidate, self.probability_of_prime) ) #(E10) break #(E11) else: #(E12) if max_reached: #(E13) self.candidate -= 2 #(E14) elif self.candidate >= self._largest - 2: #(E15) max_reached = 1 #(E16) self.candidate -= 2 #(E17) else: #(E18) self.candidate += 2 #(E19) if self.debug: #(E20) print(" candidate is: %d" % self.candidate) #(E21) return self.candidate #(E22) def factorize(n): #(F1) prime_factors = [] #(F2) factors = [n] #(F3) while len(factors) != 0: #(F4) p = factors.pop() #(F5) if test_integer_for_prime(p): #(F6) prime_factors.append(p) #(F7) continue #(F8) # d = pollard_rho_simple(p) #(F9) d = pollard_rho_strong(p) #(F10) if d == p: #(F11) factors.append(d) #(F12) else: #(F13) factors.append(d) #(F14) factors.append(p//d) #(F15) return prime_factors #(F16) def test_integer_for_prime(p): #(P1) probes = [2,3,5,7,11,13,17] #(P2) for a in probes: #(P3) if a == p: return 1 #(P4) if any([p % a == 0 for a in probes]): return 0 #(P5) k, q = 0, p-1 #(P6) while not q&1: #(P7) q >>= 1 #(P8) k += 1 #(P9) for a in probes: #(P10) a_raised_to_q = pow(a, q, p) #(P11) if a_raised_to_q == 1 or a_raised_to_q == p-1: continue #(P12) a_raised_to_jq = a_raised_to_q #(P13) primeflag = 0 #(P14) for j in range(k-1): #(P15) a_raised_to_jq = pow(a_raised_to_jq, 2, p) #(P16) if a_raised_to_jq == p-1: #(P17) primeflag = 1 #(P18) break #(P19) if not primeflag: return 0 #(P20) probability_of_prime = 1 - 1.0/(4 ** len(probes)) #(P21) return probability_of_prime #(P22) def pollard_rho_simple(p): #(Q1) probes = [2,3,5,7,11,13,17] #(Q2) for a in probes: #(Q3) if p%a == 0: return a #(Q4) d = 1 #(Q5) a = random.randint(2,p) #(Q6) random_num = [] #(Q7) random_num.append( a ) #(Q8) while d==1: #(Q9) b = random.randint(2,p) #(Q10) for a in random_num[:]: #(Q11) d = gcd( a-b, p ) #(Q12) if d > 1: break #(Q13) random_num.append(b) #(Q14) return d #(Q15) def pollard_rho_strong(p): #(R1) probes = [2,3,5,7,11,13,17] #(R2) for a in probes: #(R3) if p%a == 0: return a #(R4) d = 1 #(R5) a = random.randint(2,p) #(R6) c = random.randint(2,p) #(R7) b = a #(R8) while d==1: #(R9) a = (a * a + c) % p #(R10) b = (b * b + c) % p #(R11) b = (b * b + c) % p #(R12) d = gcd( a-b, p) #(R13) if d > 1: break #(R14) return d #(R15) def gcd(a,b): #(S1) while b: #(S2) a, b = b, a%b #(S3) return a def generate_key(p, q): #e is set to be 65538 p_file = open(p, "w") q_file = open(q, "w") #the size is required to be 128 bits prime_g = PrimeGenerator(bits = 128) # two left-most bits of both p and q must be set while(1): # two left-most bits of both p and q must be set p = prime_g.findPrime() q = prime_g.findPrime() # p and q must not be equal to each other if p != q: # (p-1) co-prime to (q-1) if gcd((p - 1), e) == 1 and gcd((q - 1), e) == 1: p_file.write(str(p)) p_file.close() q_file.write(str(q)) q_file.close() break def encrption(message, p, q, encryp): p_file = open(p, "r") q_file = open(q, "r") p_val = p_file.read() q_val = q_file.read() plain_bv = BitVector(filename = message) #calculate the totient based on the given p and q value totient = int(p_val) * int(q_val) file_out = open(encryp, "w") #Your data block from the text will be of 128-bits, prepend itwith 128 zeroes on the left to make it a 256-bit block #if the overall plaintext length is not a multiple of 128 bits while plain_bv.more_to_read: bv = plain_bv.read_bits_from_file(128) if bv.length() < 128: bv.pad_from_right(128 - bv.length()) #pad the left with 128 zeros bv.pad_from_left(128) #rsa encrption Med = Med = m mod n, n is the totient encp_val = pow(bv.int_val(), e, totient) bv_e = BitVector(intVal=encp_val, size=256) #write the bitvector to the file file_out.write(bv_e.get_hex_string_from_bitvector()) file_out.close() def decryption(encryp, p, q, decryp): p_file = open(p, "r") q_file = open(q, "r") p_val = int(p_file.read()) q_val = int(q_file.read()) #calculate the d value based on the bitvector mi function bv_t = BitVector(intVal=(p_val-1)*(q_val - 1),size=256) e_bv = BitVector(intVal = e) d_bv = e_bv.multiplicative_inverse(bv_t) d = d_bv.int_val() #calculate the totient based on the given p and q value totient = p_val * q_val #open the files file_in = open(encryp, "r") encrypted_bv = BitVector(hexstring=file_in.read()) file_out = open(decryp, "wb") file_in.close() #iterate through the input encrpted file for i in range(0, len(encrypted_bv), 256): block = encrypted_bv[i:i+256] block_val = block.int_val() #. Use the script in the lecture notes to compute general modular exponentiation. M = pow(block_val, d, totient) decrypted_bv = BitVector(intVal=M, size=256) #this takes the right most 128 bits decrypted_bv = decrypted_bv[-128:] decrypted_bv.write_to_file(file_out) file_out.close() #use crt to find the modular exponentiation def crt(C, d, p, q): #calculate Vp and Vq based lecture 34 page Vp = pow(C, (d % (p-1)), p) Vq = pow(C, (d % (q-1)), q) bv_p = BitVector(intVal=p) bv_q = BitVector(intVal=q) invp = bv_q.multiplicative_inverse(bv_p) p_inv = invp.int_val() invq = bv_p.multiplicative_inverse(bv_q) q_inv = invq.int_val() Xp = q * (q_inv % p) Xq = p * (p_inv % q) Cd_mod_n = (Vp * Xp + Vq * Xq) % (p * q) return Cd_mod_n def main(): action = sys.argv[1] #check which action to do if(action == "-g"): p_file = sys.argv[2] q_file = sys.argv[3] generate_key(p_file, q_file) elif(action == "-e"): message = sys.argv[2] p_file = sys.argv[3] q_file = sys.argv[4] encryp = sys.argv[5] encrption(message, p_file, q_file, encryp) elif action == "-d": encryp = sys.argv[2] p_file = sys.argv[3] q_file = sys.argv[4] decryp = sys.argv[5] decryption(encryp, p_file, q_file, decryp) if __name__ == '__main__': main()
## QUESTÃO 2 ## # Escreva um programa que converta uma temperatura digitada em °C (graus celsius) # para °F (graus fahrenheit). ## ## # A sua resposta da questão deve ser desenvolvida dentro da função main()!!! # Deve-se substituir o comado print existente pelo código da solução. # Para a correta execução do programa, a estrutura atual deve ser mantida, # substituindo apenas o comando print(questão...) existente. ## def main(C= int(input('qual e a temperatura em celsius: '))#pedindo que o usuario coloque o valor de celsius. F= C * (9/5) +32#calculo de conversao de celsius para fahrenheit. print('De celsius que e',C,'para fahrenheit e:' ,F))#comando de imprssao da conversao. if __name__ == '__main__': main()
# for循环 lists = [1, '2', (3,), [4], {5}, {6: 7}] for x in lists: print(type(x)) print(x) for n in range(2, 10): for x in range(2, n): if n % x == 0: print(n, '等于', x, '*', n//x) break else: # 循环中没有找到元素 print(n, ' 是质数') it = iter(lists) print(type(it)) for x in it: print(x)
#!/usr/bin/env python3 # Common cryptographic functionality used throughout these programs # These are all functions that have been defined throught the course of writing # the exercises. That code is centralized here so that it may be re-used by # other exercises without repeating it from base64 import b64encode, b64decode from itertools import cycle from collections import Counter from math import sqrt import string import itertools from Crypto.Cipher import AES import random ############# # CONSTANTS # ############# # Frequencies of English letters (and the space character). Used to judge if an # ASCII string appears to be in English. CHAR_FREQ = {' ': 18.28846265, 'e': 10.26665037, 't': 7.51699827, 'a': 6.53216702, 'o': 6.15957725, 'n': 5.71201113, 'i': 5.66844326, 's': 5.31700534, 'r': 4.98790855, 'h': 4.97856396, 'l': 3.31754796, 'd': 3.28292310, 'u': 2.27579536, 'c': 2.23367596, 'm': 2.02656783, 'f': 1.98306716, 'w': 1.70389377, 'g': 1.62490441, 'p': 1.50432428, 'y': 1.42766662, 'b': 1.25888074, 'v': 0.79611644, 'k': 0.56096272, 'x': 0.14092016, 'j': 0.09752181, 'q': 0.08367550, 'z': 0.05128469} # Numbers of bits in every possible byte N_BITS = {n: bin(n).count('1') for n in range(256)} ######################### # BASIC TYPE TRANSFORMS # ######################### def hex_to_bytes(s: str) -> bytes: """Turn a string of hex characters into a `bytes` object.""" return bytes.fromhex(s) def hex_to_base64(s: str) -> str: """Turn a string of hex characters into a base64-encoded string.""" return b64encode(hex_to_bytes(s)).decode('ascii') def bytes_to_hex(bs: bytes) -> str: """Turn a `bytes` object into its hex representation.""" return ''.join('{:02x}'.format(b) for b in bs) def bytes_to_base64(bs: bytes) -> bytes: """Turn a `bytes` object into a base64-encoded `bytes` object.""" return b64encode(bs) def base64_to_bytes(s: str) -> bytes: """Turn a base64-encoded string into a decoded `bytes` object.""" return b64decode(s) ######################## # PRIMITIVE OPERATIONS # ######################## def xor_bytes(bs1: bytes, bs2: bytes) -> bytes: """Bitwise xor two equal-lenth `bytes` objects.""" return bytes(b1 ^ b2 for b1, b2 in zip(bs1, bs2)) def repeated_key_encrypt(plaintext: bytes, key: bytes) -> bytes: """take a plain string and encypt it with another string""" return bytes(p_c ^ k_c for p_c, k_c in zip(plaintext, cycle(key))) def hamming_distance(bs1: bytes, bs2: bytes) -> int: """Get the number of differing bits between two bytestrings.""" return sum(N_BITS[b1 ^ b2] for b1, b2 in zip(bs1, bs2)) def pkcs7_pad(text: bytes, pad_len: int = 16) -> bytes: """Pad out some text to a multiple of pad_len bytes""" extra_len = (pad_len - (len(text) % pad_len)) % pad_len return text + bytes([extra_len] * extra_len) ##################### # RANDOM ALGORITHMS # ##################### def get_random_key(key_len: int = 16) -> bytes: """Return a random string of bytes of length key_len, for cyptography.""" return bytes(random.randint(0, 255) for _ in range(key_len)) def random_pad(data: bytes) -> bytes: """Pad the data with 5-10 bytes of random data in the front and back.""" before = bytes(random.randint(0, 255) for _ in range(5, 10)) after = bytes(random.randint(0, 255) for _ in range(5, 10)) return before + data + after def random_encrypt(data: bytes) -> bytes: """Randomly encrypt the data (padded randomly) with a random key.""" encryption_alg = random.choice([aes_128_cbc_encrypt, aes_128_ecb_encrypt]) return encryption_alg(random_pad(data), get_random_key()) ############ # GUESSERS # ############ def english_probability(s: str) -> float: """determine the probability that a given ascii string is in english""" # Use cosine similarity to determine how much the string resembles # the letter distribution of English. # Begin by making `s` into a vector of fractions, like CHAR_FREQ cntr = Counter(c.lower() for c in s if c.isalpha() or c == ' ') total_chars = sum(cntr.values()) vec = {c: freq/total_chars for c, freq in cntr.items()} # Do the actual calculation. `vec` is 'a' and `CHAR_FREQ` is 'b' a_dot_b = sum(pair[0] * pair[1] for pair in zip_dict(vec, CHAR_FREQ)) mag_a = sqrt(sum(freq**2 for freq in vec.values())) mag_b = sqrt(sum(freq**2 for freq in CHAR_FREQ.values())) return a_dot_b / (mag_a * mag_b) def guess_keysize(ciphertext: bytes) -> int: """Guess the length of the repeated key used to encrypt a ciphertext.""" results = [] for keysize in range(2, 41): blocks = [ciphertext[i*keysize:i*keysize+keysize] for i in range(10)] result = [hamming_distance(i, j) for i, j in zip(blocks, blocks[1:])] result = sum(r / keysize for r in result) / 10 results.append((result, keysize)) # return min(results)[1] return sorted(results)[:5] def is_ecb(data: bytes) -> bool: """Guess if the given ciphertext was encrypted in ECB mode.""" # Split the text into chunks. If any of those chunks are the same, # it is likely that ECB was used to encrypt the text. blocks = {data[i * 16:i * 16 + 16] for i in range(len(data) // 16)} return len(blocks) < (len(data) // 16) def guess_mode(alg) -> str: """Guess if the given encryption algorithm is running in ECB or CBC mode""" plaintext = b'e'*48 if is_ecb(alg(plaintext)): return 'ECB' else: return 'CBC' ############## # AES CRYPTO # ############## def aes_128_ecb_decrypt(data: bytes, key: bytes) -> bytes: """Take a stream of encrypted bytes and decrypt them with the key.""" # The key must be 128 bits (16 bytes) long assert len(key) == 16 # Set up the cipher and perform the decryption. No salt or IV. cipher = AES.new(key, AES.MODE_ECB) return cipher.decrypt(data) def aes_128_ecb_encrypt(data: bytes, key: bytes) -> bytes: """Take a stream of un-encrypted bytes and encrypt them with the key.""" # Make sure the data and key are the correct lengths assert len(key) == 16 data = pkcs7_pad(data) # Set up the cipher and perform the encryption. No salt or IV. cipher = AES.new(key, AES.MODE_ECB) return cipher.encrypt(data) def aes_128_cbc_decrypt(data: bytes, key: bytes) -> bytes: """Decrypt a stream of cbc-encrypted bytes with the key.""" assert len(key) == 16 # xor each decrypted block with the previous encrypted block return xor_bytes(aes_128_ecb_decrypt(data, key), (b'\0' * 16) + data[:-16]) def aes_128_cbc_encrypt(data: bytes, key: bytes) -> bytes: """Encrypt a stream of bytes with the key using block chaining.""" # Make sure the data and key are the correct lengths assert len(key) == 16 data = pkcs7_pad(data) # Create an output buffer for blocks and add to it one at a time # The buffer is initialized with the IV. buf = [b'\0' * 16] for block in [data[i:i+16] for i in range(0, len(data), 16)]: buf.append(aes_128_ecb_encrypt(xor_bytes(block, buf[-1]), key)) # Combine encrypted block back together, ignoring the IV return b''.join(buf[1:]) ################### # OTHER UTILITIES # ################### def zip_dict(*dicts): """Zip dicts by their keys and yield tuples of the corresponding values.""" for key in set(dicts[0]).intersection(*dicts[1:]): yield tuple(d[key] for d in dicts) def single_char_decode(bs: bytes): """Find the secret byte a string was encoded with and decode it.""" # Iterate over every possible char and try to decipher using it results = [] for c in string.printable: try: # Xor the ciphertext with that character repeated, as a byte result = xor_bytes(bs, itertools.repeat(ord(c))) # Try to decode as ascii, to weed out non-text result_ascii = result.decode('ascii') # Add the result to list of possible results. The English # probability comes first so that it can be sorted on. results.append( (english_probability(result_ascii), result_ascii, ord(c))) except UnicodeDecodeError: # String couldn't even be decoded, so it definitely isn't English pass # Return only the best result, if one exists if len(results) > 0: probability, decoded_text, key = max(results) return {'d': decoded_text, 'p': probability, 'k': key} else: return {'d': '', 'p': 0, 'k': b'\0'}
x = 0 x += +1 print("現在位置はx={0}です。".format(x)) x += +1 print("現在位置はx={0}です。".format(x)) x += +1 print("現在位置はx={0}です。".format(x))
#!/usr/bin/env python # coding=utf-8 class Stack: def __init__(self): self.q1 = [] self.q2 = [] def append(self, val): empty_q, other_q = self.find_empty_q() empty_q.append(val) while len(other_q)>0: empty_q.append(other_q.pop(0)) def pop(self): _, other_q = self.find_empty_q() if len(other_q) == 0: raise return other_q.pop(0) def find_empty_q(self): if len(self.q1) == 0: return self.q1, self.q2 return self.q2, self.q1 if __name__ == "__main__": stack = Stack() stack.append(2) stack.append(4) stack.append(3) print(stack.pop(), " == 3") print(stack.pop(), " == 4") print(stack.pop(), " == 2") print(stack.pop(), " raise")
# 변수(variable)는 처리할 데이터를 저장시키는 기억장소를 말한다. # 변수명 작성방법 # 영문자, 숫자, 특수문자(_)만 사용할 수 있으며 대문자와 소문자를 구분한다. # 반드시 변수 이름은 문자로 시작해야 하고 예약어는 사용할 수 없다. # 변수를 선언할 때는 c, c++, java 언어와 달리 변수의 자료형을 지정하지 않으면 입력되는 데이터의 # 타입에 따라서 자동으로 변수의 타입이 결정된다. # '='는 같다라는 의미로 사용되지 않고 '=' 오른쪽의 데이터러를 '=' 왼쪽의 기억장소에 저장시키라는 # 의미로 사용된다. => 대입문 => '=='를 사용해야 같다로 인식한다. name = '홍길동' print(name) print(type(name)) # <class 'str'> age = 20 print(age) print(type(age)) # <class 'int'> height = 181.5 print(height) print(type(height)) # <class 'float'> # 논리값 True와 False는 반드시 첫 문자만 대문자로 사용한다. isGender = True # 논리값을 기억하는 변수의 이름은 'is'로 시작하는 것이 관행이다. print(isGender) print(type(isGender)) # <class 'bool'> none = None # 빈 변수를 만든다. print(none) print(type(none)) # <class 'NoneType'> # 변수를 제거하려면 del 명령을 사용한다. del name # name이라는 변수를 메모리에서 제거한다. # print(name) # 변수를 메모리에서 제거했으므로 에러가 발생된다. print('*' * 50) # ================================================================================================ # input() 함수는 키보드로 입력받는 모든 데이터를 문자열 형태로 입력받는다. # 문장이 '#'로 시작하면 한 줄 주석이고 작은따옴표 3개 사이에 쓰면 여러줄 주석이 된다. ''' print('이름을 입력하세요 : ', end = '') name = input() # 키보드로 문자열을 입력받아 name이라는 변수에 저장한다. print('%s님 안녕하세요' % name) print('{}님 안녕하세요'.format(name)) print('{0}님 안녕하세요'.format(name)) print('{0:10s}님 안녕하세요'.format(name)) print(f'{name}님 안녕하세요') # input() 함수의 인수로 문자열을 입력하면 입력받기 전에 문자열을 메시지로 출력한다. name = input('이름을 입력하세요 : ') print('{}님 안녕하세요'.format(name)) # int() 함수는 인수로 지정된 문자열을 정수로 변환한다. # float() 함수는 인수로 지정된 문자열을 실수로 변환한다. age = int(input('나이를 입력하세요 : ')) print('{}님은 {}살 입니다.'.format(name, age)) print('{}님은 내년에 {}살 입니다.'.format(name, age + 1)) print('*' * 50) # split(구분자) : 문자열을 구분자를 경계로 분리한다. 나눈다. 쪼갠다. => 구분자를 생략하면 공백 name, age = input('이름과 나이를 입력하세요 : ').split(',') print('{}님은 {}살 입니다.'.format(name, age)) print('{}님은 내년에 {}살 입니다.'.format(name, int(age) + 1)) python, java, jsp = input('3과목 점수를 입력하세요 : ').split() # '+' 연산자는 숫자와 숫자 사이에 있으면 덧셈을 하고 문자열과 문자열 사이에 있으면 문자열을 연결 # 하고(이어주고) 숫자와 문자열 또는 문자열과 숫자 사이에 있으면 에러가 발생된다. print('총점 : {}'.format(python + java + jsp)) print('총점 : {}'.format(int(python) + int(java) + int(jsp))) ''' # map() 함수를 사용해서 입력받은 데이터를 일괄적으로 숫자로 변환시킬 수 있다. python, java, jsp = map(int, input('3과목 점수를 입력하세요 : ').split()) print('총점 : {}'.format(python + java + jsp))
""" Example usage of the TF_IDF_Scratch class """ from extract_keywords_tfidf_scratch import TF_IDF_Scratch def main(): # Example corpus docs = [ "Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. It is a general-purpose programming language intended to let application developers write once, run anywhere, meaning that compiled Java code can run on all platforms that support Java without the need for recompilation.", "C++ is a general-purpose programming language created by Bjarne Stroustrup as an extension of the C programming language, or 'C with Classes'. The language has expanded significantly over time, and modern C++ now has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.", "Python is an interpreted, high-level and general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes code readability with its notable use of significant whitespace. Its language constructs and object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects.", ] # # Constructing the tf-idf runner object tfidf_obj = TF_IDF_Scratch() # Set the index of the document to be extracted doc_idx = 0 # Set the maximum number of keywords, or don't pass it in # to extract all the keywords max_num = 10 print(tfidf_obj.get_keywords(docs, doc_idx, max_num)) if __name__ == "__main__": main()
import datetime def file_str(): """Generates a datetime string in a good format to save as a file Returns: str: String with the datetime in a good format to save as a file """ return datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") if __name__ == '__main__': # Save a file using a good formatted datetime string with open(f"{dt}.txt", 'w') as save_file: # Data can be logged with the datetime moment it was captured save_file.write(file_str() + " " + str(5) + '\n')
import math from dataclasses import dataclass @dataclass class Point: lat: float lon: float def distance(point1: Point, point2: Point): lon1, lat1, lon2, lat2 = map( math.radians, [point1.lon, point1.lat, point2.lon, point2.lat] ) return 6371 * ( math.acos( math.sin(lat1) * math.sin(lat2) + math.cos(lat1) * math.cos(lat2) * math.cos(lon1 - lon2), ) )
#!/usr/bin/env python """ Assignment 1, Exercise 1, INF1340, Fall, 2014. Grade to gpa conversion This module prints the amount of money that Lakshmi has remaining after the stock transactions Lakshmi bought some shares sometime ago. She later sold them. On both occasions, she had to pay the stockbroker for his/her services. Now, she is having troubles calculating how much she made or lost during the transaction. This program fixes that! Now, she's soooo happy :) But,the result shows that she has a loss of $ 25065.00.Now, she is not happy any more :( """ __author__ = 'Susan Sim' __email__ = "ses@drsusansim.org" __copyright__ = "2015 Susan Sim" __license__ = "MIT License" # valuables needed for calculating profit commission_rate = 0.03 stock_quantity = 2000 cost_price = 900 selling_price = 942.75 # Purchasing transaction stock_cost = stock_quantity * cost_price purchase_commission = commission_rate * stock_cost amount_spent = stock_cost + purchase_commission # Selling transaction stock_income = stock_quantity * selling_price selling_commission = commission_rate * stock_income amount_received = stock_income - selling_commission profit = amount_received - amount_spent print("Now she has a profit of %.2f" % profit), print("(negative sign means a loss).")
import numpy as np class Immovable: """ Base class to specify the physics of immovable objects in the world. """ def __init__(self, position, traversable, transparent): """ Construct an immovable object. Keyword arguments: position -- permanent position of the immovable traversable -- True if movables can freely move through transparent -- False if this object casts shadows """ self.position = ( position if isinstance(position, np.ndarray) else np.array(position) ) self.traversable = traversable self.transparent = transparent def render(self): """ To be implemented by subclasses. How to render the movable. """ raise NotImplementedError
from math import gcd def find_sum(): sum=0 for i in range(1000): if(i%3==0 or i%5==0): sum+=i return sum res=find_sum() #print(res) '''Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.''' def find_fibo_sum(): f1=1 f2=2 n=0 sum=2 while n<4000000: n=f1+f2 f1=f2 f2=n if(n%2==0): sum+=n return sum #print(find_fibo_sum()) '''A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.''' def large_palin(): m=0 b = False for i in range(999,100,-1): for j in range(i,100,-1): x=i*j #s=str(x) if x>m: s=str(x) if s==s[::-1]: m=int(s) print(m) #large_palin() '''2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?''' def lcm(a,b): lc=a*b//gcd(a,b) return lc n=1 for i in range(1,21): n=lcm(n,i) print(n)
import time class Timer(): def __init__( self ): self.times = {} self.startTime = time.time() def end( self, name ): if name not in self.times.keys(): self.times[name] = 0 endTime = time.time() self.times[name] += endTime-self.startTime self.startTime = endTime def print( self ): for key in self.times: print( '{:<12}{:<5}'.format(key,self.times[key]) )
# List a = [1, 2, 3] print(a) a = [1, # item1 2, # item2 3, # item3 4, # item4 5] # item5 print(a) # Tuple b = (1, 2, 3) print(b) b = (1, # item1 2, # item2 3, # item3 4, # item4 5) # item5 print(b) # Dictionary c = {"k1": 1, # item1 "k2": 2, # item2 "k3": 3} # item3 print(c) c = {"k1": 1, # item1 "k2": 2, # item2 "k3": 3, # item3 "k4": 4, # item4 "k5": 5} # item5 print(c) # function def my_func_1(a, b, c): print(f"a: {a}\nb: {b}\nc: {c}") my_func_1(1, 2, 3) def my_func_2(a, # used to indicate 1st arg b, # used to indicate 1st arg c): # used to indicate 1st arg print(f"a: {a}\nb: {b}\nc: {c}") my_func_2(1, 2, 3) a, b, c = 6, 12, 24 # Explicit statements if a > 5 and b > 10 and c > 20: print("Yes") if a > 5 \ and b > 10 \ and c > 20: print("Yes") # String str_1 = """this is a string""" print(f"str_1: {str_1}") # Note: This case line 2 string will be intended as it looks in function description def check_string_1(): a = '''This is a multiline string string which get intended''' return a print(f"check_string_1: {check_string_1()}") # Note: This case line 2 string will not be intended as it looks in function description def check_string_2(): a = '''This is a multiline string string which get intended''' return a print(f"check_string_2: {check_string_2()}")
class Puzzle: def __init__(self, status, depth, direction=None, cost=0, parent=None): self.status = status self.depth = depth self.direction = direction self.cost = cost self.parent = parent def show_map(self): for idx, i in enumerate(self.status): if (idx+1) % 3 == 0: print(i) else: print('{:3}'.format(str(i)), end='') print('')
#if character== 'a' or character=='e'or character=='i'or character=='o'or character=='u': # print("vowel") #elif character== 'A' or character=='E'or character=='I'or character=='O' or character=='U': # print("vowel") #elif character not in 'aeiouAEIOU': # print("consonent") #else: # print("number") while True: character = input("please input a character:") if character>='a' and character<='z' or character>='A' and character<='Z': if character in 'aeiouAEIOU': print("vowel") else: print("consonent") else: print("not a character")
character = input("please input a character:") if character>= 'a' and character<='z': print("lower case") elif character>='A' and character<='Z': print("uppercase") else: print("not a character")
# CONDITIONALS x = 7 # Basic If if x < 6: # block 代码块 print("this is true") # print("ok") # If Else # if x < 6: # print("This is true") # else: # print("This is false") # Elif color = 'red' # if color == 'red': # print("Color is red") # elif color == 'blue': # print("Color is blue") # else: # print("Color is not red or blue") # Nested if # if color == 'red': # if x < 10: # print("Color is red and x is less than 10") # Logical operators if color == 'red' and x < 10: print("Color is red and x is less than 10")
import matplotlib.pyplot as plt import numpy as np l1=int(input("enter the length of x[n]=")) x=np.arange(l1) print("enter x[n] values=") for i in range(0,l1): x[i]=int(input( )) n=l1 while (n>=1): y[n]=x[n] n=n-1 print("y[n]=",y)
def genPrimes(): possiblePrime = 2 while True: isPrimeNumber = True for num in range(2, int(possiblePrime ** 0.5) + 1): if possiblePrime % num == 0: isPrimeNumber = False break if (isPrimeNumber == True): yield possiblePrime possiblePrime += 1
import string def build_shift_dict(shift): mapping = {} alphabet = string.ascii_lowercase + string.ascii_lowercase[: shift] for i in range(len(alphabet)): try: mapping.update({ alphabet[i]: alphabet[i + shift] }) except IndexError: break mapping.update(dict((k.upper(), v.upper()) for k, v in mapping.items())) return mapping def apply_shift(shift): cipherText = '' text = 'Hello World' shiftDict = build_shift_dict(shift) for char in text: if (char in shiftDict): cipherText += shiftDict[char] else: cipherText += char return cipherText apply_shift(0)
import turtle import random import math class MyTurtle(turtle.Turtle): radius = 0 def __init__(self): turtle.Turtle.__init__(self, shape="turtle") def kuklos(self, x, y, radius=(random.randrange(10, 500, 1))): self.penup() self.setposition(x, y) self.pendown() self.circle(radius) self.radius = radius def sxediaseKuklous(self): positions = [(random.randrange(0,500,1), (random.randrange(0,500,1)) )] for position in positions: self.kuklos(position[0], position[1]) return positions[0] def temnomenoiKukloi(self, list): count = 0 for i in range(0, len(list)): for x in range(0, len(list)): if i != x: d = math.sqrt(abs((pow((list[i][0]-list[x][0]), 2) + (pow((list[i][1]-list[x][1]), 2))))) if d <= 2*self.radius: count += 1 break return count if __name__ == "__main__": t = MyTurtle() yolo = [] for i in range(1, 21): center = t.sxediaseKuklous() yolo.append(center) turtle.getscreen()._root.mainloop() counter = t.temnomenoiKukloi(yolo) print "Temnontai %s kukloi." % (counter,)
class Point(): def __init__(self, x, y, curve): self.x = x self.y = y self.curve = curve def copy(self): return Point(self.x, self.y, self.curve) def doIExist(self): return ((self.y**2) == (self.x**3 + self.x*self.curve.A + self.curve.B)) #elliptic point addition def __add__(self, other): #check if either point is zero if self == self.curve.O: return other if other == self.curve.O: return self #check if the second point is a reflection in x if self.x == other.x and self.y == -other.y: return self.curve.O #if we are doubling if self == other: l_1 = 3 * self.x**2 + self.curve.A l_2 = 2 * self.y #if we are adding normally else: l_1 = other.y - self.y l_2 = other.x - self.x #if the denominator is 0: vertical line if l_2 == 0: return self.curve.O #find the slope l = l_1 / l_2 #find the x,y co-ords of the new point x_3 = l**2 - self.x - other.x y_3 = l*(self.x - x_3)-self.y return Point(x_3, y_3, self.curve) #double-and-add algorithm def __mul__(self, n): if isinstance(n, self.__class__): raise Exception("Cannot multiply a point with a point") if isinstance(n, int): P = self Q = P.copy() R = self.curve.O i = n while i > 0: if i % 2 == 1: R = R + Q Q = Q + Q i = i//2 return R def __rmul__(self, n): return self.__mul__(n) def __eq__(self, other): return self.x == other.x and self.y == other.y def __str__(self): return "(" + str(self.x) + ", " + str(self.y) + ")"
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def get_minimum_node(self, lists:list) -> ListNode: minimum = lists[0] for item in lists: if item.val < minimum.val: minimum = item return minimum def mergeKList(self, lists : list) -> ListNode: k_value = [] dummy_ptr = ptr = ListNode(0) for l in lists: if l: k_value.append(l) while k_value: '''get the minimum data from the list and append the next value into this list''' node = self.get_minimum_node(k_value) k_value.remove(node) ptr.next = ListNode(node.val) ptr = ptr.next if node.next: k_value.append(node.next) return dummy_ptr.next def transfer_list_to_ListNode(): list_input = [[1,4,5], [1,3,4], [2,6]] lists = [] for sub_list in list_input: dummy_ptr = ListNode(0) ptr = dummy_ptr for item in sub_list: ptr.next = ListNode(item) ptr = ptr.next lists.append(dummy_ptr.next) return lists def transfer_list_to_string(lists:list): for items in lists: string = '' head = items while head: string = string + str(head.val) + ', ' head = head.next print('[' + string[:-2] + ']') def print_listnodes(nodes:ListNode): string = '' while nodes: string = string + str(nodes.val) + ', ' nodes = nodes.next print('[' + string[:-2] + ']') if __name__ == '__main__': lists = transfer_list_to_ListNode() solution = Solution() nodes = solution.mergeKList(lists) print_listnodes(nodes)
class LinkNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def reverse(self, head): if head is None or head.next is None: return head ptr = head prev = None while ptr: next_ptr = ptr.next ptr.next = prev prev = ptr ptr = next_ptr return prev def transfer_link_list_to_string(head): result = '' while head: result += str(head.val) + ', ' head = head.next return '[' + result[0:-2] + ']' def transfer_to_linked_list(items): dummyptr = LinkNode(0) ptr = dummyptr for item in items: ptr.next = LinkNode(item) ptr = ptr.next ptr = dummyptr.next return ptr def main(): items = input('please input : ') head = transfer_to_linked_list(items) ret = Solution().reverse(head) out = transfer_link_list_to_string(ret) print(out) if __name__ == '__main__': main()
class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def swap(self, head : ListNode) -> ListNode: prev = head_new = ListNode(0) prev.next = head while prev.next and prev.next.next: first, second = prev.next, prev.next.next prev.next, first.next, second.next, prev = second, second.next, first, first return head_new.next def transfer_string_to_list(items) -> ListNode: dummy = ListNode(0) ptr = dummy for item in items: ptr.next = ListNode(item) ptr = ptr.next return dummy.next def transfer_list_to_string(head : ListNode): if head is None: return '[]' string = '' while head: string += str(head.val) + ', ' head = head.next return '[' + string[:-2] + ']' def main(): items = input('please input : ') head = transfer_string_to_list(items) lis = Solution().swap(head) ret = transfer_list_to_string(lis) print(ret) if __name__ == '__main__': main()
class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def sort_list(self, head : ListNode): if not head or not head.next: return head # break into two list prev = slow = fast = head while fast and fast.next: prev, slow, fast = slow, slow.next, fast.next.next prev.next = None # print('-------') # ptr = head # while ptr: # print(ptr.val) # ptr = ptr.next # print('=======') # ptr = slow # while ptr: # print(ptr.val) # ptr = ptr.next left = self.sort_list(head) right = self.sort_list(slow) ptr = dummy = ListNode(0) while left or right: if not left: ptr.next = right break if not right: ptr.next = left break if left.val > right.val: ptr.next = right right = right.next else: ptr.next = left left = left.next ptr = ptr.next return dummy.next def transfor_list_to_string(head : ListNode): if not head: return '' string = '' while head: string += str(head.val) + ', ' head = head.next return '[' + string[:-2] + ']' def transfor_string_to_list(items: str): dummp_ptr = ListNode(0) ptr = dummp_ptr for item in items: ptr.next = ListNode(int(item)) ptr = ptr.next return dummp_ptr.next def main(): items = input('please input : ') head = transfor_string_to_list(items) solution = Solution() # solution.sort_list(head) l = solution.sort_list(head) string = transfor_list_to_string(l) print(string) if __name__ == '__main__': main()
array1 = [1, 2, 3, 5, 7, 8, 9, 10] array2 = [1, 2, 4, 8, 9] print("Given Arrays:") print(array1) print(array2) result = list(filter(lambda x: x in array1, array2)) print ("\nIntersection of two given arrays: ",result)
subject_marks = [('Red', 5), ('Blue', 10), ('Green', 15), ('Yellow', 12)] print("Original list of tuples:") print(subject_marks) subject_marks.sort(key=lambda x: x[1]) print("\nSorting the list of tuples:") print(subject_marks)
vowels = ('a', 'e', 'i', 'o', 'i', 'u') index = vowels.index('i') print('The index of e:', index)
import os def password_validation_part_one(condition, password): condition_ocurrence, condition_value = condition.split() start_occurence, stop_occurence = condition_ocurrence.split("-") if int(start_occurence) <= int(password.count(condition_value)) <= int(stop_occurence): return True else: return False def password_validation_part_two(condition, password): condition_ocurrence, condition_value = condition.split() first_occurence, second_occurence = condition_ocurrence.split("-") first = int(first_occurence) - 1 second = int(second_occurence) - 1 if condition_value in password[first]: if condition_value in password[second]: return False else: return True else: if condition_value in password[second]: return True else: return False if __name__ == "__main__": input_condition_list = [] input_password_list = [] counter_valid_part_one = 0 counter_valid_part_two = 0 current_dir = os.path.dirname(os.path.abspath(__file__)) input_file = os.path.join(current_dir, 'input.txt') with open(input_file, "r") as openfile: for line in openfile: line = line.strip() # print(line) input_condition, input_password = line.split(":") if password_validation_part_one(input_condition, input_password.strip()) is True: counter_valid_part_one += 1 if password_validation_part_two(input_condition, input_password.strip()) is True: counter_valid_part_two += 1 print("ANSWER PART ONE:", counter_valid_part_one) print("ANSWER PART TWO:", counter_valid_part_two)
import os def find_two_numbers(number_list: list) -> tuple: search_sum = 2020 for number in number_list: # number_list.remove(number) remaining = search_sum - number if remaining in number_list: return (number, remaining) def find_three_numbers(number_list: list) -> tuple: search_sum = 2020 number_list.sort() for number in number_list: # number_list.remove(number) if len(number_list) > 0: next_number = number_list[0] intermediate_number = number + next_number if intermediate_number <= search_sum: remaining = search_sum - intermediate_number if remaining in number_list: return (number,next_number,remaining) return (0,0,0) if __name__ == "__main__": current_dir = os.path.dirname(os.path.abspath(__file__)) input_file = os.path.join(current_dir, 'input.txt') with open(input_file, "r") as openfile: numbers_in_file = [int(n) for n in openfile.read().splitlines()] # print(numbers_in_file) number_a1, number_b1 = find_two_numbers(numbers_in_file[:]) # print(number_a1, number_b1) print("ANSWER PART ONE:",number_a1 * number_b1) number_a2, number_b2, number_c2 = find_three_numbers(numbers_in_file[:]) # print(number_a2, number_b2, number_c2) print("ANSWER PART TWO:",number_a2 * number_b2 * number_c2)
# Calculating full results for each province in each chamber (House and Senate)------------------------------- import pandas as pd class DataInput: """ This class has 3 extractors. All of them take a raw Pandas Dataframe as input 1) csv_extractor takes the results for all provinces and returns new arranged Pandas Dataframes. Both used for Senate or House 2) csv_seats_not_up_for_election_extractor takes the seats that are not up for election in both chambers, and returns a list with the arranged data 3) csv_page_help_extractor takes the information needed to display all the 'help slides' for the main calculator """ def __init__(self): pass def csv_extractor(self, elections): provinces = [] for i in range(0, len(elections["Province"])): if not pd.isnull(elections["Province"][i]): data = {'Province': elections["Province"][i], 'Seats': int(elections["Seats"][i]), 'Party': [elections["Party"][i]], 'Allegiance': [elections["Allegiance"][i]], 'Votes': [elections["Votes"][i]], 'Weight':elections["Weight"][i], 'Senate_Seats':int(elections["Senate_Seats"][i]) } for x in range(i + 1, len(elections["Province"])): if pd.isnull(elections["Province"][x]): data["Party"].append([elections["Party"][x]][0]) data['Allegiance'].append([elections["Allegiance"][x]][0]), data["Votes"].append([elections["Votes"][x]][0]) else: break df = pd.DataFrame(data, columns=['Province', 'Seats', "Allegiance", "Party", "Votes", "Weight", "Senate_Seats"]) provinces.append(df) return provinces def csv_seats_not_up_for_election_extractor(self, congress): branches = [] for i in range(0, len(congress["Branch"])): if not pd.isnull(congress["Branch"][i]): data = {'Branch': congress["Branch"][i], 'Party': [congress["Party"][i]], 'Allegiance': [congress["Allegiance"][i]], 'Seats': [congress["Seats"][i]] } for x in range(i + 1, len(congress["Branch"])): if pd.isnull(congress["Branch"][x]): data["Party"].append([congress["Party"][x]][0]) data['Allegiance'].append([congress["Allegiance"][x]][0]), data["Seats"].append([congress["Seats"][x]][0]) else: break df = pd.DataFrame(data, columns=['Branch', 'Party', "Allegiance", "Seats"]) branches.append(df) all_branches = [] for branch in branches: branch_composition = [] for i in range(0, len(branch["Party"]) - 1): party = branch["Party"][i] allegiance = branch["Allegiance"][i] seats = int(branch["Seats"][i]) branch_composition.append([party, allegiance, seats]) all_branches.append([branch["Branch"][0],branch_composition]) return all_branches def csv_page_help_extractor(self, page_help): slides =[] for i in range(0, len(page_help["Slide"])): data = {'Slide_X': int(page_help["Slide_X"][i]), 'Slide_Y': int(page_help["Slide_Y"][i]), 'H1': str(page_help["H1"][i]), 'H3': str(page_help["H3"][i]), 'Arrow_Show': int(page_help["Arrow_Show"][i]), 'Arrow_X': int(page_help["Arrow_X"][i]), 'Arrow_Y': int(page_help["Arrow_Y"][i]), 'Arrow_Degrees': int(page_help["Arrow_Degrees"][i]), 'Arrow_Clockwise': float(page_help["Arrow_Clockwise"][i]), 'Arrow_Anticlockwise': float(page_help["Arrow_Anticlockwise"][i]), 'Cover_Divs': list(map(int,(page_help["Cover_Divs"][i]).split(','))) } slides.append([int(page_help["Slide"][i]),data]) return slides
#! /usr/bin/python """labyrinth constructs and updates the game.""" import random from pathlib import Path from typing import List, Tuple from settings import ( WALL_CHAR, ROAD_CHAR, START_CHAR, FINISH_CHAR, POSSIBLE_ITEMS_CHAR, QUIT_APP, ) class Item: """Keeps the state of attributes.""" def __init__(self, name: str, coords: tuple): """Init.""" self.name: str = name self.coords: tuple = coords class Labyrinth: """ Create the labyrinth structure. - randomize the items, - randomize start position, - take items if player position on it, - update the game. """ def __init__(self, filename: Path, player): """Init Labyrinth.""" self.level_txt: Path = filename self.player = player self.run: bool = True self.walls: List[Tuple[int, int]] = [] self.roads: List[Tuple[int, int]] = [] self.possible_starts: List[Tuple[int, int]] = [] self.finish: Tuple[()] = () self.possible_items: List[Tuple[int, int]] = [] self.start: Tuple[()] = () self.items_names: List[str] = ["tube", "needle", "ether"] self.items: List[Item] = [] self.run_states: List[str] = ["running", "process_quit", "quit"] self.run_state: int = 0 self.load_structure() self.randomize_items() self.randomize_start() self.set_player_position_on_start(self.start) def load_structure(self): """Load file structure and create lists of coordinates.""" with open(self.level_txt) as level: for pos_y, line in enumerate(level): for pos_x, char in enumerate(line): if char == WALL_CHAR: self.walls.append((pos_x, pos_y)) elif char == ROAD_CHAR: self.roads.append((pos_x, pos_y)) elif char == START_CHAR: self.possible_starts.append((pos_x, pos_y)) self.roads.append((pos_x, pos_y)) elif char == FINISH_CHAR: self.finish = (pos_x, pos_y) self.roads.append((pos_x, pos_y)) elif char == POSSIBLE_ITEMS_CHAR: self.possible_items.append((pos_x, pos_y)) self.roads.append((pos_x, pos_y)) def randomize_start(self): """Randomize start coordinates.""" if not self.start: self.start = random.choice(self.possible_starts) def set_player_position_on_start(self, start_pos): """Set player position on start randomized coordinate.""" self.player.pos = start_pos def randomize_items(self): """Randomize items coordinates.""" for name in self.items_names: position = random.choice(self.possible_items) self.possible_items.remove(position) item = Item(name, position) self.items.append(item) def find_item(self, player_position: tuple): """Remove the item if the player position is equal to an item position.""" for item in self.items: if item.coords == player_position: self.items.remove(item) self.player.bag.append(item) def update(self, control: str): """Update player position, items and quit the game.""" self.player.move(control, self.roads) self.find_item(self.player.pos) if self.player.pos == self.finish: self.run_state += 1 state = self.run_states[self.run_state] if control == QUIT_APP: self.run = False if state == "quit": self.run = False
import sqlite3 DATABASE = "file/bbl.db" INSERT_QUERY_SEPARATOR = ", " INSERT_QUERY_PLACEHOLDER = "?" def drop_table(table): sql = "DROP TABLE IF EXISTS {}".format(table) execute(sql) def create_table(table, columns): # Trim columns tuples to only first two values (name and type) formatted_columns = [x[0] + " " + x[1] for x in columns] parameters = INSERT_QUERY_SEPARATOR.join(formatted_columns) sql = "CREATE TABLE IF NOT EXISTS {} ({})".format(table, parameters) execute(sql) def reset_table(table, columns): drop_table(table) create_table(table, columns) def insert(table, values): sql_values = INSERT_QUERY_SEPARATOR.join( [INSERT_QUERY_PLACEHOLDER] * len(values)) sql = "INSERT INTO {} VALUES({})".format(table, sql_values) execute(sql, values=values) def get_values(table, columns): parameters = INSERT_QUERY_SEPARATOR.join(columns) sql = "SELECT {} FROM {}".format(parameters, table) return fetchall(sql) def fetchall(sql): conn = sqlite3.connect(DATABASE) c = conn.cursor() c.execute(sql) return c.fetchall() def execute(sql, values=None): conn = sqlite3.connect(DATABASE) c = conn.cursor() if values is None: c.execute(sql) else: c.execute(sql, values) conn.commit()
a = [1, 10, 5, 2, 1, 5] def bubble_sort(array): n = len(array) for j in range(n-1, 0, -1): print('j = %d' %j) #print('array = %d' % array[j]) for i in range(0, j, +1): if array[i+1] < array[i]: print('i = %d' % i) #print('array = %d' % array[i]) temp = array[i] array[i] = array[i+1] array[i+1] = temp print("current array : %s" % array) return array print(a) print(bubble_sort(a))
def file_line_to_int_array(filename): my_list = [] with open(filename) as fp: line = fp.readline().rstrip() while line: entries = str.split(line, ',') for e in entries: my_list.append(int(e)) line = fp.readline() return my_list def test_file_line_to_int_array(): my_array = file_line_to_int_array('resources/2.txt') assert len(my_array) == 145 def run(input): i = 0 while i < len(input) - 1: opcode = input[i] if opcode == 99: return input position1 = input[i+1] position2 = input[i+2] outpos = input[i+3] if opcode == 1: input[outpos] = input[position1] + input[position2] elif opcode == 2: input[outpos] = input[position1] * input[position2] i = i + 4 return input def test_run(): assert run([1, 0, 0, 0, 99]) == [2, 0, 0, 0, 99] assert run([2, 3, 0, 3, 99]) == [2, 3, 0, 6, 99] assert run([2, 4, 4, 5, 99, 0]) == [2, 4, 4, 5, 99, 9801] assert run([1, 1, 1, 4, 99, 5, 6, 0, 99]) == [30, 1, 1, 4, 2, 5, 6, 0, 99] def test_part_one(): part_one = file_line_to_int_array('resources/2.txt') part_one[1] = 12 part_one[2] = 2 assert run(part_one)[0] == 4138658 def part_two(): out = file_line_to_int_array('resources/2.txt') for i in range(0, 100): for j in range(0, 100): k = list(out) k[1] = i k[2] = j k = run(k) if k[0] == 19690720: return i*100 + j def test_part_two(): assert part_two() == 7264
def getLines(filename, to_int=True): my_list = [] with open(filename) as fp: line = fp.readline() while line: entry = line if to_int: entry = int(entry.rstrip('\n')) my_list.append(entry) else: my_list.append(entry.rstrip('\n')) line = fp.readline() return my_list def calculate(my_list): sum = 0 for l in my_list: sum = sum + int(l/3) - 2 return sum def test_calculate(): lines = getLines("resources/1.txt") print(lines) answer = calculate(lines) assert answer == 3406527 def calculate_part_two(my_list): sum = 0 for l in my_list: fuel = int(l/3) - 2 while fuel >= 0: sum = sum + fuel fuel = int(fuel/3) - 2 return sum def test_calculate_part_two(): lines = getLines("resources/1.txt") answer = calculate_part_two(lines) assert answer == 5106932
import turtle as tl screen=tl.getscreen() tl.title("Draw Japan Flag") #all color between 0 to 1 turtle_speed=200 tl.speed(turtle_speed) starting_point=tl.position() bg_color=(.4,.6,.2) tl.bgcolor((bg_color)) #height and width of flag 10:6 flag_width=300 flag_height=flag_width*.6 #radius of flag radius=flag_width/5 def stop_draw(circle_center): x,y=circle_center global tl tl.penup() tl.goto(x,y) tl.pendown() ##draw the box of flag box_color=(1,1,1) tl.pen(pencolor=box_color,fillcolor=box_color) tl.begin_fill() tl.forward(flag_width) tl.left(90) tl.forward(flag_height) tl.left(90) tl.forward(flag_width) tl.left(90) tl.forward(flag_height) tl.left(90) tl.end_fill() #move cursor center circle_color='#FF0000' circle_center=(9*flag_width/20,flag_height/2) stop_draw(circle_center) #draw the circle with red color tl.pen(pencolor=circle_color,fillcolor=circle_color) tl.dot(radius*2,circle_color) #draw stand stand_color="black" stand_height=450 stand_width=10 x,y=starting_point top_left_corner=(x-stand_width/2,y+flag_height+10) stop_draw(top_left_corner) tl.pen(pencolor=stand_color,pensize=stand_width) tl.right(90) tl.forward(stand_height) # draw the base of flag tl.pen(pensize=10,pencolor='#2B1B17',fillcolor='#2B1B17') tl.begin_fill() tl.right(90) tl.forward(100) tl.left(90) tl.forward(50) tl.left(90) tl.forward(200) tl.left(90) tl.forward(50) tl.left(90) tl.forward(100) tl.end_fill() tl.hideturtle() tl.done()
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') # In[2]: pd.set_option("display.max_columns" , None) pd.set_option("display.float_format" , lambda x : "%.4f" % x) pd.set_option("display.width" , 200) # In[3]: from warnings import filterwarnings filterwarnings("ignore") # In[4]: path= "/Users/gokhanersoz/Desktop/VBO_Dataset/online_retail_II.xlsx" # In[5]: online_retail = pd.read_excel(path ,sheet_name = "Year 2010-2011") # # Mission 1: # # ### Understanding and Preparing Data # # ### 1. Read the 2010-2011 data in the OnlineRetail II excel. Make a copy of the dataframe you created. # In[6]: df = online_retail.copy() df.head() # In[7]: df.ndim # ### 2. Examine the descriptive statistics of the dataset. # In[8]: def check_dataframe(dataframe, head = 5 , tail = 5): print(" head ".upper().center(50,"#"),end="\n\n") print(dataframe.head(head),end="\n\n") print(" tail ".upper().center(50,"#"),end="\n\n") print(dataframe.tail(tail),end="\n\n") print(" ndim ".upper().center(50,"#"),end="\n\n") print(f"{dataframe.ndim} Dimension",end="\n\n") print(" dtypes ".upper().center(50,"#"),end="\n\n") print(dataframe.dtypes,end="\n\n") print(" ınfo ".upper().center(50,"#"),end="\n\n") print(dataframe.info(),end="\n\n") print(" na ".upper().center(50,"#"),end="\n\n") print(dataframe.isnull().sum(),end="\n\n") print(" describe ".upper().center(50,"#"),end="\n\n") print(dataframe.describe([0.01,0.99]).T) # In[9]: check_dataframe(df) # ### 3. Are there any missing observations in the dataset? If yes, how many missing observations in each variable? # In[10]: na = df.isnull().sum() na = pd.DataFrame(na[na>0], columns = ["NA Values"]).T na_names = na.columns na # In[11]: plt.figure(figsize = (10,7)) data = df.isnull()[na_names] sns.heatmap(data = data , cmap = "viridis",yticklabels=False) plt.ylabel("Na Values") plt.show() # ### 4. Remove the missing observations from the data set. Use the 'inplace=True' parameter for removal. # In[12]: df.describe([0.01, 0.99]).T # In[13]: df.dropna(inplace = True) df.isnull().sum() # In[14]: df.describe([0.01, 0.99]).T # ### 5. How many unique items are there? # In[15]: for col in df.columns : print(f"For {col.upper()} Nunique Values : {df[col].nunique()}",end = "\n\n") # In[16]: # Target Values items = "StockCode" print(f"For {items.upper()} Nunique Values : {df[items].nunique()}") # ### 6. How many of each product are there? # In[17]: target = df[items].value_counts() target = pd.DataFrame(target).reset_index() target.columns = ["StockCode", "Values"] target.head(10) # ### 7. Sort the 5 most ordered products from most to least. # In[18]: five_values = df.groupby(["StockCode"])[["Quantity"]].sum().sort_values(by = "Quantity" , ascending = False) five_values.head() # In[19]: target.sort_values(by ="Values" , ascending = False).head() # ### 8. The 'C' in the invoices shows the canceled transactions. Remove the canceled transactions from the data set. # In[20]: print(f"DataFrame Shape : {df.shape}") # In[21]: df["Invoice"].str.contains("C", na = None).head(3) # In[22]: df["Invoice"].str.contains("C" , na = False).head(3) # In[23]: # The reason we set na = False would normally return None if na = None. # We fill them with False instead, which we convert to True with "~" and catch them. df = df[~df["Invoice"].str.contains("C", na = False )] print(f"DataFrame Shape : {df.shape}") # ### 9. Create a variable named 'Total Price' that represents the total earnings per invoice. # In[24]: df.head() # In[25]: df["TotalPrice"] = df["Quantity"] * df["Price"] df.head() # ## Mission 2: # # ## Calculation of RFM metrics # # ▪ Make the definitions of Recency, Frequency and Monetary. # # ▪ Customer specific Recency, Frequency and Monetary metrics with groupby, agg and lambda # calculate. # # ▪ Assign your calculated metrics to a variable named rfm. # # ▪ Change the names of the metrics you created to recency, frequency and monetary. # # Note 1: For the recency value, accept today's date as (2011, 12, 11). # # Note 2: After creating the rfm dataframe, filter the dataset to "monetary>0". # In[26]: df["InvoiceDate"].max() # In[27]: # We looked at a max value and added 2 days on top of it.... import datetime today_date = datetime.datetime(2011,12,11) today_date # In[28]: rfm = df.groupby("Customer ID").agg({"InvoiceDate" : lambda InvoiceDate : (today_date - InvoiceDate.max()).days, "Invoice" : lambda Invoice : Invoice.nunique(), "TotalPrice" : lambda TotalPrice : TotalPrice.sum()}) # In[29]: rfm.head() # In[30]: # Control values = 12346.0000 print("Invoice : " , df[df["Customer ID"] == values]["Invoice"].nunique(),end = "\n\n") print("InvoiceDate : " , (today_date - df[df["Customer ID"] == values]["InvoiceDate"].max()).days,end="\n\n") print("TotalPrice : " , df[df["Customer ID"] == values]["TotalPrice"].sum(),end = "\n\n") # In[31]: rfm.columns = ["Recency", "Frequence", "Monetary"] rfm.head() # In[32]: #We caught the min value of the monetary value as 0 here, we need to fix it... rfm.describe().T # In[33]: rfm = rfm[rfm["Monetary"] > 0] rfm.describe().T # ## Mission 3: # ### Generating and converting RFM scores to a single variable # # ▪ Convert Recency, Frequency and Monetary metrics to scores between 1-5 with the help of qcut. # # ▪ Record these scores as recency_score, frequency_score and monetary_score. # # ▪ Express recency_score and frequency_score as a single variable and save as RFM_SCORE. # # CAUTION! We do not include monetary_score. # In[34]: # If we pay attention to the frequency here, the same values appear in different quarters #and this will cause a problem, so we will use rank(method = "first") values = [.1, .2, .3, .4, .5, .6, .7, .8, .9] rfm.describe(values).T # In[35]: # For the Recency value, the scoring should be in reverse, the lowest value being the highest # [(0.999, 13.8] < (13.8, 33.0] < (33.0, 72.0] < (72.0, 180.0] < (180.0, 374.0]] ranges rfm["Recency_Score"] = pd.qcut(rfm.Recency, 5, labels = [5,4,3,2,1]) # In[36]: pd.DataFrame(rfm.Frequence.rank(method="first").describe(values)).T # In[37]: # We will use the rank method for the frequency value as it captures the same values in different quarters # Note: We don't need to take it backwards here, anyway, the biggest area gets the highest score... # [(0.999, 868.4] < (868.4, 1735.8] < (1735.8, 2603.2] < (2603.2, 3470.6] < (3470.6, 4338.0]] ranges rfm["Frequence_Score"] = pd.qcut(rfm.Frequence.rank(method="first"), 5 , labels = [1,2,3,4,5]) # In[38]: # The one with the highest Monetary value has the highest score... #[(3.749, 250.194] < (250.194, 490.096] < (490.096, 942.276] <(942.276, 2058.426] <(2058.426, 280206.02]] ranges rfm["Monetary_Score"] = pd.qcut(rfm.Monetary, 5 , labels = [1,2,3,4,5]) # In[39]: rfm.head() # In[40]: rfm["RFM_SCORE"] = rfm["Recency_Score"].astype(str) + rfm["Frequence_Score"].astype(str) rfm.head() # In[41]: # Champions rfm[rfm["RFM_SCORE"] == "55"]["RFM_SCORE"].count() # In[42]: # Hiberneating rfm[rfm["RFM_SCORE"] == "11"]["RFM_SCORE"].count() # ## Mission 4: # # ### Defining RFM scores as segments # # ▪ Make segment definitions so that the generated RFM scores can be explained more clearly. # # ▪ Convert the scores into segments with the help of the seg_map below. # In[43]: seg_map = { r'[1-2][1-2]': 'hibernating', r'[1-2][3-4]': 'at_Risk', r'[1-2]5': 'cant_loose', r'3[1-2]': 'about_to_sleep', r'33': 'need_attention', r'[3-4][4-5]': 'loyal_customers', r'41': 'promising', r'51': 'new_customers', r'[4-5][2-3]': 'potential_loyalists', r'5[4-5]': 'champions' } # In[44]: # Here, when the regex is False, it does not detect [1-2][1-2] values, only 33,41,51 values. # We make it detect all of them by making Regex True rfm["Segment"] = rfm["RFM_SCORE"].replace(seg_map , regex = True) rfm.head() # In[45]: plt.figure(figsize = (15,5)) i = 1 for col in ["Recency","Frequence","Monetary"]: plt.subplot(1,3,i) sns.distplot(rfm[col]) i+=1 plt.tight_layout() plt.show() # In[46]: plt.figure(figsize = (15,5)) i = 1 for col in ["Recency","Frequence","Monetary"]: plt.subplot(1,3,i) sns.distplot(np.log1p(rfm[col])) i+=1 plt.tight_layout() plt.show() # In[47]: plt.figure(figsize = (15,10)) sns.scatterplot(x = rfm["Recency"], y = rfm["Frequence"] , hue=rfm["Segment"]) size = 15 plt.xlabel("Recency" , fontsize = size) plt.ylabel("Frequence", fontsize = size) plt.title("Frequence ~ Recency" ,fontsize = size) plt.show() # ### Mission 5: # # ### Time for action! # # ▪ Select the 3 segments you find important. These three segments; # # - Both in terms of action decisions, # # - Interpret both in terms of the structure of the segments (mean RFM values). # # ▪ Select the customer IDs of the "Loyal Customers" class and get the excel output. # In[48]: segment_names = rfm["Segment"].unique().tolist() for name in segment_names: print(f" For { name } Describe ".upper().center(50,"#"),end = "\n\n") print(pd.DataFrame(data = rfm[rfm["Segment"] == name].describe().T), end = "\n\n") # In[49]: segment = rfm["Segment"].value_counts() segment = pd.DataFrame(segment).sort_values(by = "Segment" , ascending = False) segment # In[50]: rfm[["Segment","Frequence","Recency","Monetary"]].groupby("Segment").agg(["mean","count"]) # ### Champions Class # # * This class is the class that brings the most returns. He sees that he is logged in frequently according to his recency value. His Frequence value is higher than the others, which makes this class Champions. By creating more opportunities for them, we can increase their monetary value even more... # # ### Loyal Customers # # * We can organize special campaigns to attract this class to the champions class and increase their returns to us more. # # ### Can't Loose # # * These customers are more when we compare their frequencies with loyal customers, but the difference between them is very high, they are close to each other in terms of return, it may be a plus for us to be in contact with them so that they can visit more often in order not to keep them away. Campaigns can be organized according to what they are more interested in... # ### Select the customer IDs of the "Loyal Customers" class and get the excel output. # In[51]: loyal_customers = pd.DataFrame() loyal_customers["Loyal_Customers_ID"] = rfm[rfm["Segment"] == "loyal_customers"].index loyal_customers.to_excel("loyal_customers_id.xlsx") # In[52]: print("Loyal Customers Shape : {}".format(loyal_customers.shape)) # In[53]: loyal_customers.head() # In[ ]:
#!/bin/python3 import math import os import random import re import sys # Complete the bigSorting function below. #Fails 4 test cases because of not executing on time def bigSorting(unsorted): ans = [] for i in range(len(unsorted)): ans.append(int(unsorted[i])) ans.sort() for i in range(len(ans)): print(ans[i]) if __name__ == '__main__': n = int(input()) unsorted = [] for _ in range(n): unsorted_item = input() unsorted.append(unsorted_item) result = bigSorting(unsorted) #Perfect efficient solution def bigSorting(unsorted): unsorted.sort() unsorted.sort(key=len) return unsorted
#!/bin/python3 import math import os import random import re import sys # # Complete the 'getTotalX' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER_ARRAY a # 2. INTEGER_ARRAY b # #DID NOT SOLVE ALL THE TEST CASES def getTotalX(a, b): maxela = max(a) tempkey = maxela temp = [] while tempkey <= min(b): if tempkey%maxela==0: temp.append(tempkey) tempkey+=1 for j in range(len(a)): for k in range(len(temp)): if temp[k]%a[j] == 0: continue else: temp.remove(temp[k]) for m in range(len(temp)): for n in range (len(b)): if b[n]%temp[m] == 0: continue else: temp.remove(temp[m]) return len(temp) if __name__ == '__main__': #fptr = open(os.environ['OUTPUT_PATH'], 'w') #first_multiple_input = input().rstrip().split() #n = int(first_multiple_input[0]) #m = int(first_multiple_input[1]) arr = list(map(int, input().rstrip().split())) brr = list(map(int, input().rstrip().split())) total = getTotalX(arr, brr) #fptr.write(str(total) + '\n') #fptr.close()
#!/bin/python3 import os # Complete the designerPdfViewer function below. def designerPdfViewer(h, word): heightlist = [] letterlist = [] for i in range(ord('a'), ord('z') + 1): letterlist.append(chr(i)) print(letterlist) for i in range(len(letterlist)): for j in range(len(word)): if letterlist[i] == word[j]: heightlist.append(h[i]) print(word[j]) break print(heightlist) maxheight = max(heightlist) neededheight = len(word) * 1 * maxheight return neededheight if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') h = list(map(int, input().rstrip().split())) word = input() result = designerPdfViewer(h, word) fptr.write(str(result) + '\n') fptr.close()
r""" Command line argument parameters. """ from argparse import ArgumentParser def command_line_parser(): r""" Create a command line parser object. :return: a command line parser object. """ parser = ArgumentParser() parser.add_argument("path_file", help="the tecplot file containing paths/domain structures.") parser.add_argument("applied_x", help="the applied field x-direction") parser.add_argument("applied_y", help="the applied field y-direction") parser.add_argument("applied_z", help="the applied field z-direction") parser.add_argument("strength", help="the applied field strength") parser.add_argument("unit", help="the applied field unit", choices=["T", "mT", "uT", "nT"]) return parser
#!/usr/bin/env python # The policy iteration algorithm. import numpy as np def return_policy_evaluation(p, u, r, T, gamma): # newU = np.zeros(12) # in case of returnitg new utulities, there are more iterations (24 VS 33) for state in range(len(u)): u[state] = r[state] + gamma * np.dot(u, T[p[state]][state]) return u def return_expected_action(u, T, v): """Return the expected action. It returns an action based on the expected utility of doing a in state s, according to T and u. This action is the one that maximize the expected utility. @param u utility vector @param T transition matrix @param v starting vector @return expected action (int) """ actions_array = np.zeros(4) for action in range(len(actions_array)): a = np.dot(v, T[action]) c = np.dot(a, u) actions_array[action] = c[0] expected_action = np.argmax(actions_array) return expected_action def print_policy(p, shape): """Print the policy on the terminal Using the symbol: * Terminal state ^ Up > Right v Down < Left # Obstacle """ counter = 0 policy_string = "" for row in range(shape[0]): for col in range(shape[1]): if (p[counter] == -1): policy_string += " * " elif (p[counter] == 0): policy_string += " ^ " elif (p[counter] == 1): policy_string += " > " elif (p[counter] == 2): policy_string += " v " elif (p[counter] == 3): policy_string += " < " elif (p[counter] == -2): policy_string += " # " counter += 1 policy_string += '\n' print(policy_string) def main(): """Finding the solution using the iterative approach """ gamma = 0.999 iteration = 0 T = np.load("T.npy") # Generate the first policy randomly # Nan=Nothing, -1=Terminal, 0=Up, 1=Left, 2=Down, 3=Right p = np.random.randint(0, 4, size=(12)) p[5] = -2 # don't like arrays of floats here p[3] = p[7] = -1 # Utility vectors u = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) # Reward vector r = np.array([-0.04, -0.04, -0.04, +1.0, -0.04, 0.0, -0.04, -1.0, -0.04, -0.04, -0.04, -0.04]) while True: iteration += 1 epsilon = 0.0001 # 1- Policy evaluation u1 = u.copy() u = return_policy_evaluation(p, u, r, T, gamma) # Stopping criteria delta = np.sum(abs(u - u1)) # print(delta) if delta < epsilon * (1 - gamma) / gamma: break for s in range(12): if not p[s] == -2 and not p[s] == -1: # skipping evaluation for terminal and impossible states v = np.zeros((1, 12)) v[0, s] = 1.0 # assuming probability of being in current state as 1 # 2- Policy improvement a = return_expected_action(u, T, v) if a != p[s]: p[s] = a # print(u[0:4]) # print(u[4:8]) # print(u[8:12]) # print_policy(p, shape=(3,4)) print("=================== FINAL RESULT ==================") print("Iterations: " + str(iteration)) print("Delta: " + str(delta)) print("Gamma: " + str(gamma)) print("Epsilon: " + str(epsilon)) print("===================================================") print(u[0:4]) print(u[4:8]) print(u[8:12]) print("===================================================") print_policy(p, shape=(3, 4)) print("===================================================") if __name__ == "__main__": main()
print("Determinar si un número par o impar") num=int(input("Introduzca un número: ")) if num/2==0: print("El número es par") else: print("El número es impar")
def SelectionSort(lst): #сортировка выбором for i in range(0, len(lst)-1): min= i for j in range (i+1,len(lst)): if lst[j]< lst[min]: min=j lst[i], lst[min] = lst[min], lst[i] print("Сортировка выбором:", lst) def heapsort(lst): #пирамидальная сортировка sl = len(lst) def swap(pi, ci): #функция меняте местами элементы в массиве if lst[pi] < lst[ci]: lst[pi], lst[ci] = lst[ci], lst[pi] def sift(pi, unsorted): #метод отсеивания узлов i_gt = lambda a, b: a if lst[a] > lst[b] else b while pi * 2 + 2 < unsorted: gtci = i_gt(pi * 2 + 1, pi * 2 + 2) swap(pi, gtci) pi = gtci # Строим дерево for i in range(int(sl / 2) - 1, -1, -1): sift(i, sl) # сортируем его функциями sift и swap for i in range(sl - 1, 0, -1): swap(i, 0) sift(0, i) print("Пирамидальная сортировка: ", lst)
import unittest from play import Play from card import Card, CardSuit, CardValue class GameTest(unittest.TestCase): def setUp(self): self.play = Play() def test_init(self): self.assertEqual(self.play.cards, []) def test_append(self): # Setup card = Card(CardValue.TEN, CardSuit.HEARTS) # Run self.play.append(card) # Assert self.assertEqual(card, self.play.cards[0]) def test_calculateExtraPoints_runOfThree(self): # Setup self.play.append(Card(CardValue.TEN, CardSuit.HEARTS)) self.play.append(Card(CardValue.NINE, CardSuit.HEARTS)) self.play.append(Card(CardValue.EIGHT, CardSuit.HEARTS)) # Run extraPoints = self.play.calculateExtraPoints() # Assert self.assertEqual(extraPoints, 3) if __name__ == '__main__': unittest.main()
print ('--------------------------') print (' Financiamento de Moradia ') print ('--------------------------') valor = float(input('Qual o valor do imóvel que você gostaria de comprar? \n')) sal = float(input('Qual o seu salário atual? \n')) anos = int(input('Em quantos anos você gostaria de pagar o imóvel? \n')) prestacao = valor/(anos*12) print ('O valor da prestação mensal será de {:.2f} reais, durante {} anos \n'.format(prestacao, anos)) if prestacao > sal*(30/100): print ('Você não poderá comprar o imóvel, pois a prestação implicaria em 30% do seu salário.') print ('Aumente a quantidade de anos para realizar uma nova análise.') else: print('Parabéns você poderá comprar o imóvel')
print ('----------------------------------') print (' Confederação nacional de natação') print ('----------------------------------') nome = str(input('Digite seu nome: \n')) idade = int(input('Digite sua idade: \n')) if idade <= 9: print ('{}, você está inscrito na categoria MIRIM'.format(nome)) elif idade > 9 and idade <=14: print ('{}, você está inscrito na categoria INFANTIL'.format(nome)) elif idade >14 and idade <= 19: print ('{}, você está inscrito na categoria JÚNIOR'.format(nome)) elif idade > 19 and idade<=20: print ('{}, você está inscrito na categoria SÊNIOR'.format(nome)) else: print ('{}, você está inscrito na categoria MASTER'.format(nome))
#!/usr/bin/python """ Problem: http://www.geeksforgeeks.org/count-triplets-with-sum-smaller-that-a-given-value/ """ def count_triplete(alist, val): """ Per each element (base) we build all the triplete possibile, you get the second element (pvt) and then look for all other third element. Since we are interested into the sum of the triplete we don't need to go back building triplete when moving the PVT ahead. 2 1 5 7 2 1 5, 2 1 7, 2 5 7, (no 2 5 1 for the sum), 1 5 7, (no 1 2 5) """ print 'input ', alist count = 0 for base in range(len(alist)-2): for pvt in range(base+1, len(alist)): if pvt + 1 < len(alist): if (alist[base] + alist[pvt] + alist[pvt+1]) < val: count += 1 print alist[base], alist[pvt], alist[pvt+1] if pvt + 2 < len(alist): if (alist[base] + alist[pvt] + alist[pvt+2]) < val: count += 1 print alist[base], alist[pvt], alist[pvt+2] if pvt + 3 < len(alist): if (alist[base] + alist[pvt] +alist[pvt+3]) < val: count += 1 print alist[base], alist[pvt], alist[pvt+3] print 'Counted {} with sum lesss than {}'.format(count, val) def count_triplete2(alist, val): """ To improve perfomances you can first sort the list and working as before but stopping building triplete for a given base when the you meet the first sum >= value """ slist = sorted(alist) count = 0 for base in range(len(slist) -2): for pvt in range(base+1, len(slist)): tmp_sum = 0 if pvt + 1 < len(alist): tmp_sum = alist[base] + alist[pvt] + alist[pvt+1] if tmp_sum < val: count += 1 print alist[base], alist[pvt], alist[pvt+1] else: break if pvt + 2 < len(alist): tmp_sum = alist[base] + alist[pvt] + alist[pvt+2] if tmp_sum < val: count += 1 print alist[base], alist[pvt], alist[pvt+2] else: break if pvt + 3 < len(alist): tmp_sum = alist[base] + alist[pvt] + alist[pvt+3] if tmp_sum < val: count += 1 print alist[base], alist[pvt], alist[pvt+3] else: break print 'Counted {} with sum lesss than {}'.format(count, val) #count_triplete([-2, 0, 1, 3], 2) count_triplete2([-2, 0, 1, 3, 9, 34, 67, 23, 55], 2)
#!/usr/bin/python from datastructures import LinkedList import random class LinkedListSorted(LinkedList): def sort(self): """ This implementaion use bubble sort and switch only values, I am aware that complexity worst case will be O(N^2) """ had_switched = True first_node = self.head second_node = first_node.next # if we have only one node, nothing to sort if second_node is None: return while had_switched: had_switched = False while first_node.next is not None: if first_node.value > second_node.value: first_node.value, second_node.value = second_node.value, first_node.value had_switched = True first_node = second_node second_node = second_node.next # Rewind to the beginning first_node = self.head second_node = first_node.next def sort2(self): if self.head is None or self.head.next is None: return else: return self._sort2(self.head, None) def _sort2(self, first_node, last_node): # If we have only one element return that if first_node.next is None: return first_node # Get the length of the list node = first_node len_list = 0 while node is not last_node: len_list = len_list + 1 node = node.next # Get the middle pos, indexing starts at zero middle = len_list / 2 second_half = first_node for i in range (0, middle): second_half = second_half.next # Call the sort for the sub-array first, middle list_a = self._sort2(first_node, second_half) # Call the sort for the sub-array middle, last list_b = self._sort2(second_half, last_node) # Merge the two ordered sublist return self._merge(list_a, list_b, last_node) def _merge(self, nodeA, nodeB, nodeStop): """ Merge in place two sub-parts of the a list already sorted. 1st sublist: [nodeA, nodeB[ 2nd sublist: [nodeB, nodeStop[ """ if nodeB is None: return # use two pointer to the nodes posA = nodeA posB = nodeB # temp list to merge the values lval = [] bMerge = True while bMerge: if posA.value <= posB.value: lval.append(posA.value) posA = posA.next # Stop when we end list A, reaching nodeB if posA == nodeB: while posB is not nodeStop: lval.append(posB.value) posB = posB.next bMerge = False else: lval.append(posB.value) posB = posB.next # stop when we reached the node stop if posB == nodeStop: while posA != nodeB: lval.append(posA.value) posA = posA.next bMerge = False # repass the list from nodeA to nodeStop to reassing # the ordered value from teh tmp list node = nodeA while node is not nodeStop: node.value = int(lval.pop(0)) node = node.next # very important, return the first node to innest recursio return nodeA # Accessory method def printall(self, node): while node is not None: print ' ', node.value, node = node.next print '' ll = LinkedListSorted() for i in range(1,9): ll.insert(random.randint(1,100)) print ll #merge_inplace(ll.head, ll.head.next.next) ll.sort2() print ll
#!/usr/bin/python """ Question: Given the head of a linked list, reverse it. Head could be None as well for empty list. Input: None 1 --> 2 --> 3 --> None Output: None None --> 3 --> 2 --> 1 """ class Node(object): def __init__(self, data=None, next_node=None): self.data = data self.next = next_node def str(self): print 'node val:{0}'.format(self.data) def reverse_1(head): """ This solution does not require additional data structures. It traverses the list and adjust the references to the nodes. """ current = head # the current node to process previous = None # before the current while current: # until we do not reach the end of the list nextone = current.next # we need a reference to/save the current.next current.next = previous # we have currrent.next saved, shift references now previous = current # for the next iteration current = nextone # move ahead of one node return previous # at the end the previoud one is the tail of the original list def reverse_2(head): """ This solution consider the input list as an immutable object, indeed it works on creating a new list starting from the one in input """ current = head previous = None while current: node = Node(current.data, previous) previous = node current = current.next return previous def print_me(head): if head is None: print '' return else: print head.data, print_me(head.next) prev_node = None for i in range(10, 0, -1): new_node = Node(i, prev_node) prev_node = new_node """ Testing the implementation Note: - reverse_1 does not use additional space in memory - reverse_2 treats the list as immutable object (create a new one reversed) """ head = prev_node print 'Input:' print_me(head) n = reverse_2(head) print 'Reversed:' print_me(n) print 'Original:' print_me(head)
""" Given a sorted list of integer And a desired value to look for Then implement a binary search to return the position of the element Or -1 if the value has been not found """ CODE_VALUE_NOT_FOUND = -1 def binary_search(lst, value): if lst is None: return CODE_VALUE_NOT_FOUND else: return __binary_search(lst, value) def __binary_search(lst, value): # when we reached an empty list it means # the record has not been found. if len(lst) == 0: return CODE_VALUE_NOT_FOUND # get the middle position middle = int(len(lst) / 2) # lucky, we found the value, return it! if value == lst[middle]: return middle # keep serching on the right if value > lst[middle]: return __binary_search(lst[middle+1:], value) # keep searching on the left if value < lst[middle]: return __binary_search(lst[:middle], value)
def factorial (n): res = 1 for i in range(1 , n+1): res = res*i return res print(factorial(10))
def factorial (n): x = 1 for i in range(1, n+1): x = x * i return x print(factorial(10))
# datas = [10,4,8,5,7,2,9] def sortList(datas): index = len(datas) for i in range(index): for j in range(index-1): if(datas[j] > datas[j+1]): temp = datas[j] datas[j] = datas[j+1] datas[j+1] = temp return datas print(sortList([10,4,8,5,7,2,9]))
datas = [10, 4, 8, 5, 7, 2, 9] def sortList(list): for i in range(0, len(list) - 1): # 有n-1回合(n為數字個數) for j in range(0, len(list) - 1 - i): # 每回合進行比較的範圍 if list[j] > list[j + 1]: # 是否需交換 tmp = list[j] list[j] = list[j + 1] list[j + 1] = tmp return list print(sortList([10, 4, 8, 5, 7, 2, 9]))
def factorial (n): sum=1 ans=0 for i in range(1,n+1): sum*=i ans+=sum return ans print(factorial(10))
def factorial (n): if n==1: return n else: result = n*factorial(n-1) return result print(factorial(10))
# datas = [10,4,8,5,7,2,9] def sortList(datas): n=len(datas) for i in range(0,n-1): for j in range(0,n-i-1): if datas[j]>datas[j+1]: datas[j],datas[j+1]=datas[j+1],datas[j] return datas print(sortList([10,4,8,5,7,2,9]))
# # @lc app=leetcode id=119 lang=python # # [119] Pascal's Triangle II # # https://leetcode.com/problems/pascals-triangle-ii/description/ # # algorithms # Easy (44.74%) # Total Accepted: 219.9K # Total Submissions: 490.7K # Testcase Example: '3' # # Given a non-negative index k where k ≤ 33, return the kth index row of the # Pascal's triangle. # # Note that the row index starts from 0. # # # In Pascal's triangle, each number is the sum of the two numbers directly # above it. # # Example: # # # Input: 3 # Output: [1,3,3,1] # # # Follow up: # # Could you optimize your algorithm to use only O(k) extra space? # # class Solution(object): def getRow(self, rowIndex): """ :type rowIndex: int :rtype: List[int] """ res = [] for i in range(rowIndex+1): temp = [1]*(rowIndex+1) if i > 1: for j in range(1, i): temp[j] = res[j-1] + res[j] res = temp return res if __name__ == '__main__': print(Solution().getRow(3))
from tkinter import * from tkinter.ttk import * import random # creating tkinter window root = Tk() l1 = Label(root, text = "Tic Tac Toe",font =('Verdana', 15)) l1.pack(fill = BOTH, expand= True,pady = 10) l1.config(anchor=CENTER) l2 = Label(root, text = "You are O and computer in X",font =('Verdana', 15)) l2.pack(fill = BOTH, expand= True,pady = 10) l2.config(anchor=CENTER) photo = PhotoImage(file = "O.png") photo1 = PhotoImage(file = "X1.png") photo2 = PhotoImage(file = "images.png") # Resizing image to fit on button photoimage = photo.subsample(3, 3) photoimage1 = photo1.subsample(9, 9) photoimage2 = photo2.subsample(9, 9) pane = Frame(root) pane.pack(fill = BOTH, expand = True) # button widgets which can also expand and fill # in the parent widget entirely b1 = Button(pane,text=" ") b2 = Button(pane,text=" ") b3 = Button(pane,text=" ") b4 = Button(pane,text=" ") b5 = Button(pane,text=" ") b6 = Button(pane,text=" ") b7 = Button(pane,text=" ") b8 = Button(pane,text=" ") b9 = Button(pane,text=" ") b10 = Button(pane,text="New Game") global available available = [b1,b2,b3,b4,b5,b6,b7,b8,b9] def win(): try: if (b1['text']=="O" and b4['text']=="O" and b7['text']=="O" or b2['text']=="O" and b5['text']=="O" and b8['text']=="O" or b3['text']=="O" and b6['text']=="O" and b9['text']=="O" or b1['text']=="O" and b2['text']=="O" and b3['text']=="O" or b4['text']=="O" and b5['text']=="O" and b6['text']=="O" or b7['text']=="O" and b8['text']=="O" and b9['text']=="O" or b1['text']=="O" and b5['text']=="O" and b9['text']=="O" or b3['text']=="O" and b5['text']=="O" and b7['text']=="O"): print("You won") l2.config(text="You Won") elif (b1['text']=="X" and b4['text']=="X" and b7['text']=="X" or b2['text']=="X" and b5['text']=="X" and b8['text']=="X" or b3['text']=="X" and b6['text']=="X" and b9['text']=="X" or b1['text']=="X" and b2['text']=="X" and b3['text']=="X" or b4['text']=="X" and b5['text']=="X" and b6['text']=="X" or b7['text']=="X" and b8['text']=="X" and b9['text']=="X" or b1['text']=="X" and b5['text']=="X" and b9['text']=="X" or b3['text']=="X" and b5['text']=="X" and b7['text']=="X"): print("You lost") l2.config(text="You Lost") except: print("Its a draw") l2.config(text="Its a draw") def comp_move(): try: leng = len(available) print(available,len(available)) numb = random.randint(0,leng-1) print(numb) chose = available[numb] print(chose) available.remove(chose) chose.config(image=photoimage1,state=DISABLED,text="X") except: l2.config(text="Its a draw") def Change(button): if button == "b1": print(available) available.remove(b1) b1.config(image=photoimage,state=DISABLED,text="O") comp_move() win() elif button =="b2": b2.config(image=photoimage,state=DISABLED,text="O") available.remove(b2) comp_move() win() elif button =="b3": b3.config(image=photoimage,state=DISABLED,text="O") available.remove(b3) comp_move() win() elif button =="b4": b4.config(image=photoimage,state=DISABLED,text="O") available.remove(b4) comp_move() win() elif button =="b5": b5.config(image=photoimage,state=DISABLED,text="O") available.remove(b5) comp_move() win() elif button =="b6": b6.config(image=photoimage,state=DISABLED,text="O") available.remove(b6) comp_move() win() elif button =="b7": b7.config(image=photoimage,state=DISABLED,text="O") available.remove(b7) comp_move() win() elif button =="b8": b8.config(image=photoimage,state=DISABLED,text="O") available.remove(b8) comp_move() win() elif button =="b9": b9.config(image=photoimage,state=DISABLED,text="O") available.remove(b9) comp_move() win() def New(): b1.config(image=photoimage2,state="normal",text=" ") b2.config(image=photoimage2,state="normal",text=" ") b3.config(image=photoimage2,state="normal",text=" ") b4.config(image=photoimage2,state="normal",text=" ") b5.config(image=photoimage2,state="normal",text=" ") b6.config(image=photoimage2,state="normal",text=" ") b7.config(image=photoimage2,state="normal",text=" ") b8.config(image=photoimage2,state="normal",text=" ") b9.config(image=photoimage2,state="normal",text=" ") l2.config(text="You are O and computer in X") global available available = [b1,b2,b3,b4,b5,b6,b7,b8,b9] print(available) b1.grid(row = 0, column = 0, sticky = W) b2.grid(row = 0, column = 1, sticky = W) b3.grid(row = 0, column = 2, sticky = W) b4.grid(row = 1, column = 0, sticky = W) b5.grid(row = 1, column = 1, sticky = W) b6.grid(row = 1, column = 2, sticky = W) b7.grid(row = 2, column = 0, sticky = W) b8.grid(row = 2, column = 1, sticky = W) b9.grid(row = 2, column = 2, sticky = W) b10.grid(row = 3, column = 1, sticky = W) b1.config(image=photoimage2,command=lambda: Change("b1")) b2.config(image=photoimage2,command=lambda: Change("b2")) b3.config(image=photoimage2,command=lambda: Change("b3")) b4.config(image=photoimage2,command=lambda: Change("b4")) b5.config(image=photoimage2,command=lambda: Change("b5")) b6.config(image=photoimage2,command=lambda: Change("b6")) b7.config(image=photoimage2,command=lambda: Change("b7")) b8.config(image=photoimage2,command=lambda: Change("b8")) b9.config(image=photoimage2,command=lambda: Change("b9")) b10.config(command=lambda: New()) mainloop()
#! /usr/bin/env python3 import matplotlib.pyplot as plt from karmedbandit import KArmedBandit class KABTestBed(KArmedBandit): """ Testbed for running multiple independent k-armed-bandit simulations. Follows Sutton and Barto, Chapter 2. """ def __init__(self,runs=2000,k=10,steps=1000, epsilon=0.0,initial_value=0.0, track_rewards=True): """ Parameters ---------- runs : int, optional Number of independent runs to perform. k : int, optional The number of "bandits" to use. Default is 10. steps: int, optional The number of steps to take in a single trial. Default is 2000. epsilon : float, optional The epsilon parameter. 0 <= epsilon <= 1. This parameter controls how often the epsilon-greedy algorithm explores sub-optimal actions instead of exploiting optimal actions. initial_value : float, optional The value to initialize the learner's value-list with. track_rewards : boolean, optional If true, this object will save all of the rewards it has seen over the course of its run. """ self.runs = runs super().__init__(k,steps,epsilon,initial_value,track_rewards) def run_n_simulations(self,runs=None): """ Runs a fixed number of independent simulations. Parameters ---------- runs : int, optional The number of simulations to run. The default value is set when the class instance is created. """ if not runs: runs = self.runs if self.track_rewards: self.run_rewards = [] self.run_optimals = [] for _ in range(runs): # initialize the simulation self.initialize_learner() self.initialize_bandits() self.train_learner() if self.track_rewards: self.run_rewards += [self.rewards_seen] self.run_optimals += [self.optimal_action] def show_average_reward(self): """ Uses matplotlib to plot the average reward as a function of step number. Follow Sutton and Barto figure 2.2. """ if not self.track_rewards: print('You must run the simulations with track_rewards enabled.') return None ax1 = plt.subplot(2,1,1) ax1.plot(pop_mean(transpose(self.run_rewards)),'-b') ax1.set_ylabel('Average reward') ax1.set_title(r'$\epsilon$ = {:3.2f}'.format(self.epsilon) + \ ' and initial_value = {:3.2f}'.format(self.initial_value)) ax1.axis([-10,self.steps+1,0,1.55]) ax2 = plt.subplot(2,1,2) ax2.plot(pop_mean(transpose(self.run_optimals)),'-b') ax2.set_xlabel('Steps') ax2.set_ylabel('Fraction Optimal Action') ax2.axis([-10,self.steps+1,0,1]) plt.show() def transpose(list_of_lists): """ Transposes a list of lists. """ return [y for y in map(list,zip(*list_of_lists))] def pop_mean(list_of_lists): """ Returns the mean along the first axis of a list of lists. """ return [1.0*sum(x)/len(x) for x in list_of_lists]
from FBI_Dataset import get_years_sheet sheet = get_years_sheet() class CrimeResult: most_crimes = 0 name = '' year = '' def compare_crimes_amount_and_get_result(amount_to_compare, result): if result.most_crimes < amount_to_compare: result.most_crimes = amount_to_compare result.year = int(sheet.cell(row_number, 0).value) return True return False most_crime_a_year = CrimeResult() for row_number in range(4, 24): crime_in_a_year = int(sheet.cell(row_number, 2).value + sheet.cell(row_number, 12).value) compare_crimes_amount_and_get_result(crime_in_a_year, most_crime_a_year) print("Year with most crime was: " + str(most_crime_a_year.year) + " with a total of " + str( most_crime_a_year.most_crimes) + " various crimes commited.") most_frequent_crime = CrimeResult()
s1=int(input("toplamak istediğiniz 1.sayı")) s2=int(input("toplamak istediğiniz 2.sayı")) if s1 + s2 : print(s1+s2) if kullanmadan yapmak isterseniz s1=int(input("toplamak istediğiniz 1.sayı")) s2=int(input("toplamak istediğiniz 2.sayı")) z=s1+s2 print(z)
## Author: {Tobias Lindroth & Robert Zetterlund} import numpy as np import pandas as pd import sys import matplotlib.pyplot as plt # Which countries have high life expectancy but have low GDP? # For the sake of the assignment, # lets assume that high and low represents is based on the standard deviation. # To which extent can be set by adjusting the variable STD_CONSTANT below # 0.253 is a z score indicating 60 (or 40) %. STD_CONSTANT = 0.253 SELECTED_YEAR = 2017 # Allow for argument in unix. eg. 'python task_b.py 0.2 1999' if len(sys.argv) >= 2: STD_CONSTANT = float(sys.argv[1]) if len(sys.argv) >= 3: SELECTED_YEAR = float(sys.argv[2]) # Setup constants GDP = "Output-side real GDP per capita (2011 international-$)" LIFE = "Life expectancy (years)" # use pandas to read csv df_gdp = pd.read_csv("../res/gdp.csv") df_life = pd.read_csv("../res/life-expectancy.csv") # filter data on selected year gdp_entries = df_gdp[(df_gdp["Year"] == SELECTED_YEAR)] life_entries = df_life[(df_life["Year"] == SELECTED_YEAR)] # merge entries with inner join. Excluding entities not available in both datasets. merged_entries = pd.merge(gdp_entries, life_entries, on=["Code", "Year", "Entity"]) # get standard deviation and mean from entries gdp_std = np.std(merged_entries[GDP]) gdp_mean = np.mean(merged_entries[GDP]) life_std = np.std(merged_entries[LIFE]) life_mean = np.mean(merged_entries[LIFE]) highLife = merged_entries[(merged_entries[LIFE] > life_mean + life_std * STD_CONSTANT)] highLifeLowGdp = highLife[(highLife[GDP] < gdp_mean - gdp_std * STD_CONSTANT)] rest = merged_entries.drop(highLifeLowGdp.index) fig, ax = plt.subplots() inputs = [ (highLifeLowGdp, "blue", "High life expectancy, low GDP"), (rest, "gray", "Other"), ] for df, color, label in inputs: ax.scatter( df[GDP], df[LIFE], c=color, s=75, label=label, alpha=0.8, edgecolors="none" ) ax.legend() plt.xlabel("GDP per capita ($)") plt.ylabel("Life expectancy (years)") plt.savefig("../fig/gdp_life_b.png") plt.show() print(len(highLifeLowGdp)) print(len(rest)) # print countries having a high life expectancy and a low gdp if len(highLifeLowGdp) > 0: print("These countries have high life expectancy and a low gdp: \n") print(highLifeLowGdp["Entity"].to_frame().to_string(index=False)) else: print("There are no countries with a high life expectancy and a low gdp")
# Author: {Tobias Lindroth & Robert Zetterlund} import numpy as np import matplotlib.pyplot as plt from sklearn import neighbors, datasets from sklearn.metrics import plot_confusion_matrix from sklearn.model_selection import train_test_split # task 3 # Use k-nearest neighbours to classify the iris data set with some different values for k, # and with uniform and distance-based weights. What will happen when k grows larger # for the different cases? Why? # task 4 # Compare the classification models for the iris data set that are generated by knearest neighbours # #(for the different settings from question 3) and by logistic # regression. Calculate confusion matrices for these models and discuss the # performance of the various models. # import iris dataset and extract relevant data iris = datasets.load_iris() X = iris["data"] y = iris["target"] target_names = iris["target_names"] # Determine which settings to use in plot. n_neighbors_array = np.array([1, 5, 50, 100]) distributions = ['uniform', 'distance'] # setup multiple plots within one window fig, ax = plt.subplots(nrows=len(distributions), ncols=len( n_neighbors_array), figsize=(10, 10)) plt.tight_layout() # indices for determining placement of figure in subplot col = 0 row = 0 X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.33, random_state=42) for n_neighbors in n_neighbors_array: for weights in distributions: # create an instance of Neighbours Classifier and fit the data. clf = neighbors.KNeighborsClassifier(n_neighbors, weights=weights) clf.fit(X_train, y_train) # create confusion matrix conf_plot = plot_confusion_matrix( clf, X_test, y_test, display_labels=target_names, ax=ax[row, col], cmap=plt.get_cmap("Greens" if (row % 2 == 1) else "Blues"), xticks_rotation=90) # remove colorbar on plots except first one if(col < len(n_neighbors_array) - 1): conf_plot.im_.colorbar.remove() titleString = "K: " + str(n_neighbors) + \ "\n Distribution: " + str(weights) ax[row, col].set_title(titleString) row = row + 1 col = col + 1 row = 0 # looks nicer (essentially changing zoom) plt.subplots_adjust(left=0.08, bottom=0.05, right=0.98, top=0.95, hspace=0.1, wspace=0.75) plt.show()
## Author: {Tobias Lindroth & Robert Zetterlund} import numpy as np import pandas as pd import sys import matplotlib.pyplot as plt # For the sake of the assignment, # lets assume that high and low represents is based on the standard deviation. # To which extent can be set by adjusting the variable STD_CONSTANT below STD_CONSTANT = 0.253 SELECTED_YEAR = 2017 # Allow for argument in unix. eg. 'python task_b.py 0.2 1999' if len(sys.argv) >= 2: STD_CONSTANT = float(sys.argv[1]) if len(sys.argv) >= 3: SELECTED_YEAR = float(sys.argv[2]) # Setup constants GDP = "Output-side real GDP per capita (2011 international-$)" LIFE = "Life expectancy (years)" # use pandas to read csv df_gdp = pd.read_csv("../res/gdp.csv") df_life = pd.read_csv("../res/life-expectancy.csv") # filter data on selected year gdp_entries = df_gdp[(df_gdp["Year"] == SELECTED_YEAR)] life_entries = df_life[(df_life["Year"] == SELECTED_YEAR)] # merge entries with inner join. Excluding entities not available in both datasets. merged_entries = pd.merge(gdp_entries, life_entries, on=["Code", "Year", "Entity"]) # get standard deviation and mean from entries gdp_std = np.std(merged_entries[GDP]) gdp_mean = np.mean(merged_entries[GDP]) life_std = np.std(merged_entries[LIFE]) life_mean = np.mean(merged_entries[LIFE]) # filter based on having strong economy strong_economy = merged_entries[merged_entries[GDP] > gdp_mean + gdp_std * STD_CONSTANT] weak_economy = merged_entries[merged_entries[GDP] <= gdp_mean + gdp_std * STD_CONSTANT] # filter based on having not high life expectancy not_high_life_strong_economy = strong_economy[ strong_economy[LIFE] < life_mean + life_std * STD_CONSTANT ] high_life_strong_economy = strong_economy[ strong_economy[LIFE] > life_mean + life_std * STD_CONSTANT ] inputs = [ ( not_high_life_strong_economy, "blue", "Strong economy, not a high life expectancy", ), (high_life_strong_economy, "green", "Strong economy, high life expectancy"), (weak_economy, "gray", "Not a strong economy"), ] fig, ax = plt.subplots() for df, color, label in inputs: ax.scatter( df[GDP], df[LIFE], c=color, s=75, label=label, alpha=0.8, edgecolors="none" ) ax.legend() plt.xlabel("GDP per capita ($)") plt.ylabel("Life expectancy (years)") plt.savefig("../fig/gdp_life_c.png") plt.show() # print countries having a high life expectancy and a low gdp if len(not_high_life_strong_economy["Entity"]) > 0: print("These countries have strong economy but not a high life expectancy: \n") print(not_high_life_strong_economy["Entity"]) else: print("There are no countries with a low life expectancy and a strong economy")
n = int(input()) a = 1 for a in range(1,6): if(a<6): print(n*a,end=" ")
print("Hello World") for numbers in range(1,100): if numbers%3==0 and numbers%5==0: print("FizzBuzz") elif numbers%3==0: print("Fizz") elif numbers%5==0: print("Buzz") else: print("numbers")
#Move all the negative elements to one side a = [-1, 2, -3, 4, 5, 6, -7, 8, 9] print(a) def negativeSort(a): left = 0 right = len(a) -1 while left <= right: if a[left] < 0 and a[right] < 0: left += 1 elif a[left] > 0 and a[right] < 0: a[left],a[right] = a[right],a[left] left +1 right -=1 elif a[left] < 0 and a[right] > 0: right -= 1 else: left+=1 right-=1 return a print(negativeSort(a)) ''' #method 2 using partition algorithm i = -1 pivot=0 for j in range(len(a)): if a[j] < pivot: i+=1 a[i],a[j] = a[j],a[i] print(a) ''' '''output: [-1, 2, -3, 4, 5, 6, -7, 8, 9] [-1, -7, -3, 4, 5, 6, 2, 8, 9]'''