content
stringlengths
7
1.05M
fhand = open(input('Enter file name: ')) d = dict() for ln in fhand: if not ln.startswith('From '): continue words = ln.split() time = words[5] d[time[:2]] = d.get(time[:2],0) + 1 l = list() for key,val in d.items(): l.append((val,key)) l.sort() for val,key in l: print(key,val)
dbname='postgres' user='postgres' password='q1w2e3r4' host='127.0.0.1'
""" MIT License Copyright (c) 2021 Daud Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribu...
Blue = 0 Red = 0 Yellow = 0 Green = 0 Gold = 1 Health = 100 Experience = 0 if Gold == 1: print("The chest opens") Health += 50 Experience += 100 elif Blue == 1: print("DEATH Appears") Health -= 100 elif Red == 1: print("The chest burns you") Health -= 50 elif Y...
numList = [3, 4, 5, 6, 7] length = len(numList) for i in range(length): print(2 * numList[i])
# # @lc app=leetcode id=273 lang=python3 # # [273] Integer to English Words # # @lc code=start class Solution: def numberToWords(self, num: int) -> str: v0 = ["Thousand", "Million", "Billion"] v1 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve...
class JeevesException(Exception): """ Base exception class for jeeves. """ pass class UserNotAdded(JeevesException): """ An JeevesException that raises when there is not a user added to the server or "not found". Parameters ---------- name : string ...
''' IQ test ''' n = int(input()) numbers = list(map(int, input().split(' '))) even = 0 odd = 0 first_eve = -1 first_odd = -1 for i in range(n): if numbers[i] % 2 == 0: even += 1 if first_eve == -1: first_eve = i else: odd += 1 if first_odd == -1: first_odd...
class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: opened = set() N = len(rooms) opened.add(0) toOpen = rooms[0] while toOpen: nextRound = set() for room in toOpen: for newKey in rooms[room]: ...
class UndoSelectiveEnum(basestring): """ all|wrong Possible values: <ul> <li> "all" - Undo all shared data, <li> "wrong" - Only undo the incorrectly shared data </ul> """ @staticmethod def get_api_name(): return "undo-selective-enum"
km = float(input('De quantos kilómetros será a viagem? ')) if km <= 200: print('A viagem custará {:.2f}€ (0.1€/km)'.format(km * 0.1)) else: print('A visgem custará {:.2f} € (0.09€/km)'.format(km * 0.09))
''' Python program to compute the sum of the negative and positive numbers of an array of integers and display the largest sum. Original array elements: {0, 15, 16, 17, -14, -13, -12, -11, -10, 18, 19, 20} Largest sum - Positive/Negative numbers of the said array: 105 Original array elements: {0, 3, 4, 5, 9, -22, -44,...
'''input 549 817 715 603 1152 600 300 220 420 520 ''' # -*- coding: utf-8 -*- # AtCoder Beginner Contest # Problem A if __name__ == '__main__': a = int(input()) b = int(input()) c = int(input()) d = int(input()) print(min(a, b) + min(c, d))
# -*- coding: utf-8 -*- """Main module.""" def silly_sort(unsilly_list): """ This function was created in order to arrenge a range of rangers. Please, move on and don't ask me why. """ size = len(unsilly_list) for i in range(size): unsilly_list[i], unsilly_list[size-1-i] = \ ...
list_1 = [2,3,1,4,2,3,5,6,8,5,8,9,10,9,6] s = set(list_1) list_2 = list(s) #print(list_2) n = 3 l = len(list_1) #print(l) b = int((len(list_2)/n)) s1 = list_2.__getslice__(0, b) s2 = list_2.__getslice__(len(s1), len(s1)+b) #l1 = list(enumerate(s1, 1)) #l2 = list(enumerate(s2, 1)) print(s1,s2) #print(l1, l2)
#shape of small b: def for_b(): """printing small 'b' using for loop""" for row in range(7): for col in range(4): if col==0 or col in(1,2) and row in(3,6) or col==3 and row in(4,5) : print("*",end=" ") else: print(" ",end=" ") prin...
def get_token_files(parser, logic, logging, args=0): if args: if "hid" not in args.keys(): parser.print("missing honeypotid") return hid = args["hid"] for h in hid: r = logic.get_token_files(h) if r != "": parser.print("Tokens l...
class Queue: def __init__(self, initial_size=10): self.arr = [0 for _ in range(initial_size)] self.next_index = 0 self.front_index = -1 self.queue_size = 0
def alterarPosicao(changePosition, change): """This looks complicated but I'm doing this: Current_pos == (x, y) change == (a, b) new_position == ((x + a), (y + b)) """ return (changePosition[0] + change[0]), (changePosition[1] + change[1]) posicaoAtual = (10, 1) posicaoAtual = alterarPosicao(...
# -*- coding: utf-8 -*- """Responses. responses serve both testing purpose aswell as dynamic docstring replacement. """ responses = { "_v3_Availability": { "url": "/openapi/root/v1/features/availability", "response": [ {'Available': True, 'Feature': 'News'}, {'Available': Tr...
def retorno(): resp=input('Deseja executar o programa novamente?[s/n] ').lower() if(resp=='s'): print('-'*30) analisar() else: print('Processo finalizado com sucesso!') pass def cabecalho(titulo): print('-'*30) print(f'{titulo:^30}') print('-'*30) pas...
#reference to https://github.com/matterport/Mask_RCNN.git and mrcnn/utils.py def download_trained_weights(coco_model_path, verbose=1): """Download COCO trained weights from Releases. coco_model_path: local path of COCO trained weights """ if verbose > 0: print("Downloading pretrained model to ...
birthYear = input('Birth year: ') print(type(birthYear)) # değişkenin tipini öğrendik age = 2020 - int(birthYear) # değişkeni int veri tipine çevirdik print(type(age)) # değişkenin tipini öğrendik print(age) # Egzersiz weightLbs = input('Weight (lbs): ') weightKg = int(weightLbs) * 0.45 print(weightKg)
def divisores(n): div=[] for i in range(1,n-1): if n % i ==0: div.append(i) return div def amigos(a,b): div_a = divisores(a) div_b = divisores(b) sigma_a = sum(div_a) sigma_b = sum(div_b) if sigma_a == b or sigma_b == a: return True else: ...
""" blueberrymath. Open Source Mathematical Package. """ __version__ = "0.1.1" __author__ = 'Rogger Garcia | Fausto German'
#coding: utf-8 ''' Tables des correspondances Le rang 0 correspond à la position de l'information dans la trame MAESTRO Le rang 1 correspond a l'intitulé publié sur le broker Le rang 2 (optionnel) permet de remplacer le code de la trame par une information texte correspondante ''' RecuperoInfo=[ [1,"Etat du poêl...
def print_formatted(number): width = len(str(bin(number))) # Since the last column is always filled for i in range(1, number+1): print(str(i).rjust(width-2, '.') + oct(i).lstrip("0o").rjust(width-1, '.') + hex(i).lstrip("0x").upper().rjust(width-1, '.') + ...
# Copyright 2014 F5 Networks Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
# File: crowdstrike_consts.py # # Copyright (c) 2016-2020 Splunk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
HANDSHAKING = 0 STATUS = 1 LOGIN = 2 PLAY = 3
class Node: def __init__(self, data): self.data = data self.next = None class Queue: def __init__(self): self.head = None self.last = None self.l = [] def isEmpty(self): return self.head == None # Method to add an item to the queue def Enqueue(se...
datasets = { "cv-corpus-7.0-2021-07-21": { "directories": ["speakers"], "audio_extensions": [".wav", ".flac"], "transcript_extension": ".txt" }, "LibriTTS": { "directories": ["train-clean-100", "train-clean-360", "train-other-500"], "audio_extensions": [".wav", ".flac...
# Copyright 2019 DIVERSIS Software. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law o...
# https://app.codility.com/demo/results/trainingPURU8U-DP4/ def solution(array): set_array = set() for val in array: if val not in set_array : set_array.add(val) return len(set_array) if __name__ == '__main__': print(solution([0]))
# The key 'ICE' is repeated to match the length of the string and later they are xored taking eacg character at a time def xor(string,key): length = divmod(len(string),len(key)) key = key*length[0]+key[0:length[1]] return ''.join([chr(ord(a)^ord(b)) for a,b in zip(string,key)]) if __name__ == "__main__": ...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- """ Created Date: Wednesday October 23rd 2019 Author: Dmitry Kislov E-mail: kislov@easydan.com ----- Last Modified: Wednesday, October 23rd 2019, 9:08:59 am Modified By: Dmitry Kislov ----- Copyright (c) 2019 """
# ex-094 - Unindo Dicionários e listas lista = list() dados = dict() total = 0 while True: dados['nome'] = str(input('Nome: ')) while True: dados['sexo'] = str(input('Sexo [F/M]: ')).strip().upper()[0] if dados['sexo'] not in 'FM': print('ERRO! Responda apenas F ou M.') els...
Root.default = 'C' Scale.scale = 'major' Clock.bpm = 120 notas = [0, 3, 5, 4] frequencia = var(notas, 4) d0 >> play( '<x |o2| ><---{[----]-*}>', sample=4, dur=1/2 ) s0 >> space( notas, dur=1/4, apm=3, pan=[-1, 0, 1] ) s1 >> bass( frequencia, dur=1/4, oct=4, ) s2 >> spark( ...
class Cue: def __init__(self): pass def power_to_speed(self, power, ball=None): # Translate a power (0-100) to the ball's velocity. # Ball object passed in in case this depends on ball weight. return power*10 def on_hit(self, ball): # Apply some effect to ball on hi...
# # PySNMP MIB module UAS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/UAS-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:28:15 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)...
def maior_primo(num): if num < 2: return False else: for n in range(2, num): while num % n == 0: return num - 1 return num
class DragEventArgs(EventArgs): """ Provides data for the System.Windows.Forms.Control.DragDrop,System.Windows.Forms.Control.DragEnter,or System.Windows.Forms.Control.DragOver event. DragEventArgs(data: IDataObject,keyState: int,x: int,y: int,allowedEffect: DragDropEffects,effect: DragDropEffects) """...
""" max dimensions (width & height) of the material if the part is larger than the max dimensions then part must be `pieced` together kerf if our laser beam has a width of 20 mm (kerf - aka the thickness of the blade) and we do not factor this into our calculations (i.e., a kerf value of 0) then we wo...
# Recebe notas nado = int(input("Qual a idade do nadador?")) # Ifs if(nado >= 5 and nado <= 7): print("A categoria do nadador é Infantil A!!") elif(nado >= 8 and nado <= 10): print("A categoria do nadador é Infantil B!!") elif(nado >= 11 and nado <= 13): print("A categoria do nadador é Juvenil A!!") elif(na...
# Demo Python If ... Else - And ''' And The 'and' keyword is a logical operator, and is used to combine conditional statements. ''' # Test if a is greater than b, AND if c is greater than a: a = 200 b = 33 c = 500 if a > b and c > a: print("Both conditions are True")
def timesize(t): if t<60: return f"{t:.2f}s" elif t<3600: return f"{t/60:.2f}m" elif t<86400: return f"{t/3600:.2f}h" else: return f"{t/86400:.2f}d"
# .txt mesh converter def txt_mesh_converter(mesh_filename): # txt mesh converter, returns mesh variables with open(mesh_filename, 'r') as mesh_file: lines = mesh_file.readlines() # remove blank lines lines_list = [] for line in lines: if line.strip(): ...
getAllObjects = [ { "id": 1, "keyName": "SPREAD", "name": "SPREAD" } ]
""" [2017-10-20] Challenge #336 [Hard] Van der Waerden numbers https://www.reddit.com/r/dailyprogrammer/comments/77m6l4/20171020_challenge_336_hard_van_der_waerden/ # Description This one came to me via the always interesting [Data Genetics blog](http://datagenetics.com/blog/august12017/index.html). Van der Waerden'...
# # PySNMP MIB module CISCO-OPTICAL-MONITOR-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-OPTICAL-MONITOR-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:51:58 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3....
# Manter Ordem Alfabética def format_euro(num=0): num = float(num) string = f'{num:.2f}€' string_org = string.replace('.', ',') return string_org def tit(string, lengh=0): if lengh == 0: a = int(len(str(string)) / 2 + 2) else: a = int(lengh / 2 + 2) return f'''{'-=' * a} ...
class MetaDato: def __init__(self, nombreTabla, campos): pass def calcularRegistros(self): pass def getRegistro(self): pass
# day3 - sonar sweeps # def count_bits(bits, pos): ones = sum([int(b[pos]) for b in bits]) zeros = len(bits) - ones return (ones, zeros) def power(bits): width = len(bits[0]) gamma = [] epsilon = [] for i in range(0, width): (ones, zeros) = count_bits(bits, i) print(f"ones...
# WARNING: Do not edit by hand, this file was generated by Crank: # # https://github.com/gocardless/crank # class InstalmentSchedule(object): """A thin wrapper around a instalment_schedule, providing easy access to its attributes. Example: instalment_schedule = client.instalment_schedules.get() ...
""" GC-состав является важной характеристикой геномных последовательностей и определяется как процентное соотношение суммы всех гуанинов и цитозинов к общему числу нуклеиновых оснований в геномной последовательности. Напишите программу, которая вычисляет процентное содержание символов G (гуанин) и C (цитозин) в введенн...
nama = str(input("Masukkan Nama ")) nim = int(input("Masukkan NIM ")) uts = int(input("Masukkan Nilai UTS : ")) uas = int(input("Masukkan Nilai UAS : ")) hitungRataRata = (uts+uas)/2 if int(hitungRataRata) <= 40: nilai = 'E' elif int(hitungRataRata) <= 60: nilai = 'D' elif int(hitungRataRata) <= 70: ni...
''' Pattern Plus star pattern: Enter number of rows: 5 + + + + +++++++++ + + + + ''' number_rows=int(input('Enter number of rows: ')) for row in range(1,number_rows+1): for column in range(1,number_rows+1): if number_rows%2!=0: if row==((number_rows//2)+1) or colu...
class Solution: def maxRotateFunction(self, A: List[int]) -> int: n = len(A) if n <= 1: return 0 if n == 2: return max(A) result = -inf for i in range(n): result = max(result, sum([((j + i) % n) * v for j, v in enumerate(A)])) return result
#使用set去除元素,改变了数组顺序 def removeDuplicates(nums): # write your code here nums = list(set(nums)) return nums #用字典 def removeDuplicates(nums): # write your code here nums = {}.fromkeys(nums).keys() return nums #用字典并保持顺序 def removeDuplicates(nums): # write your code here l = list(set(nums)) ...
def demo_map(): num_list = list( range(1, 6) ) ## Example_#1: # compute x^2 for each element result = list( map( lambda x:x**2, num_list) ) # [1, 4, 9, 16, 25] print( result ) ## Example_#2: # compute 3x + 1 for each element result = list( map( lambda x:3*x+1, num_list) ) ...
TBF = 253 # Taxa Básica Financeira TJLP = 256 # Taxa de juros - TJLP TR = 226 # Taxa Referencial SELIC = 11 # Taxa de juros - Selic SELIC_ACUM_MES = 4390 # Taxa de juros - Selic acumulada no mês SELIC_META = 432 # Taxa de juros - Meta Selic definida pelo Copom CDI = 12 # Taxa de Juros - CDI ...
class Solution: def numWaterBottles(self, numBottles: int, numExchange: int) -> int: ans = numBottles // (numExchange - 1) + numBottles return ans if numBottles % (numExchange - 1) else ans - 1
class JouleHeatFraction: """The JouleHeatFraction object defines the fraction of electric energy released as heat. Notes ----- This object can be accessed by: .. code-block:: python import material mdb.models[name].materials[name].jouleHeatFraction import odbMaterial ...
self.description = "Sysupgrade with a set of sync packages replacing a set of local ones" sp1 = pmpkg("pkg2") sp1.replaces = ["pkg1"] sp2 = pmpkg("pkg3") sp2.replaces = ["pkg1"] sp3 = pmpkg("pkg4") sp3.replaces = ["pkg1", "pkg0"] sp4 = pmpkg("pkg5") sp4.replaces = ["pkg0"] for p in sp1, sp2, sp3, sp4: self.addpkg...
class NullDisplay: def __init__(self, board=None): pass def show_results(self): pass def draw(self): pass
n=int(input("How Many Time you Chack the Condition: ")) for i in range(1,n+1): num=int(input("Enter The Number To be Chack Even or Odd: ")) if(num%2==0): print("The Enterd Number is Even") else: print("The Enterd Number is odd")
def notas(*num, sit=0): """ :param num: valores de nota :param sit: se True apresenta a situação do boletim se False nao apresenta :return: dicionario um dict() com varias infos das notas """ soma = 0 count = 0 for c in num: soma += c count += 1 media = soma/count ...
class ShareInstance(): __session = None @classmethod def share(cls, **kwargs): if not cls.__session: cls.__session = cls(**kwargs) return cls.__session # Expand dict class Dict(dict): def get(self, key, default=None, sep='.'): keys = key.split(sep) for i, ke...
class BaseInfo: """ 异常信息 """ def __init__(self, message="", data=None, status=200, code=-1, template="{message}"): self.code = code self.template = template self.message = message self.data = data self.status = status def update(self, message=None, data=None...
emoji_dict = { "anger": ["\U0001F92C", "data/emoji/emoji_u1f92c.png"], "disgust": ["\U0001F616", "data/emoji/emoji_u1f616.png"], "fear": ["\U0001F633", "data/emoji/emoji_u1f633.png"], "happy": ["\U0001F604", "data/emoji/emoji_u1f604.png"], "neutral": ["\U0001F612", "data/emoji/emoji_u1f612.png"], ...
# coding=utf-8 class PMI: def __init__(self, document): self.document = document self.pmi = {} self.miniprobability = float(1.0) / document.__len__() self.minitogether = float(0)/ document.__len__() self.set_word = self.getset_word() def calcularprobability(self, docume...
# Section 5.16 snippets # Creating a Two-Dimensional List a = [[77, 68, 86, 73], [96, 87, 89, 81], [70, 90, 86, 81]] # Illustrating a Two-Dimensional List # Identifying the Elements in a Two-Dimensional List for row in a: for item in row: print(item, end=' ') print() # How the Nested Loops Execute f...
package_name = 'cms_search' name = 'django-cms-search' author = 'Benjamin Wohlwend' author_email = 'piquadrat@gmail.com' description = "An extension to django CMS to provide multilingual Haystack indexes" version = __import__(package_name).__version__ project_url = 'http://github.com/piquadrat/%s' % name license = 'BSD...
# Space: O(1) # Time: O(n) # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def addOneRow(self, root, v, d): if d==1: new_node = Tree...
# COSINE FUNCTION def cosine(x) -> float: """ Returns cosine of x radians """ return 0.0
''' Selection sort is an O(n^2) sorting algorithm. The logic is to find the smallest element in the unsorted portion of the array and swapping it in the right position. In the worst-case it takes n(n+1)/2 accesses. ''' def selsort(A,l,r): ''' Convention is that array elements are indexed from l to r-1.''' ...
def dominator(arr): res = 0 if len(arr) == 0: return -1 for x in arr: if arr.count(x) > len(arr) / 2: res = x break else: res = -1 return res
def move(instruction, x, y, w_x, w_y): if instruction[0] == 'N': w_y += instruction[1] if instruction[0] == 'S': w_y -= instruction[1] if instruction[0] == 'E': w_x += instruction[1] if instruction[0] == 'W': w_x -= instruction[1] if instruction[0] in ['L', 'R']: ...
DEBUG = True TEMPLATE_DEBUG = True # THIS MUST BE HTTPS DOMAIN_NAME="https://52.34.71.182:8000" #CSRF_COOKIE_SECURE = False #SESSION_COOKIE_SECURE = False DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'expfactory.db', } } #DATABASES = { # 'default': { # ...
# Writes down all combinations of plates COMBINATIONS = [1.25, 2.5, 5, 10, 25] # 1 kg is 2.20... pounds KILOS_POUNDS_CONVERSION_RATE = 2.20462 # Function that asks for str input def get_input_in_kilos(): return input("Enter weight in kilos: ") # function that converts punds to kilos def convert_kilos_to_pounds(k...
class Fila: def __init__(self, maxx): self.limit = maxx self.elementos = [0] * maxx self.ini = -1 self.end = -1 self._size = 0 self.offset = -1 def __len__(self): return self._size def insert(self, elem): if ((self._size) >= self.limi...
# O(N^2) def can_make_target1(arr, target): for i in range(len(arr)): for j in range(i, len(arr)): if arr[i] + arr[j] == target: return True return False # O(N) def can_make_target2(arr, target): looking_for = set() for a in arr: if a in looking_for: ...
# A somewhat special node as it is designed for use in skip list, in addition to having two pointers \ # it has three (next, previous and down). # This class is used by SortedLinkList, but is somewhat different to a regular link list node. class Node: def __init__(self, value, next=None, down=None, prev=None)...
expected_output = { 'rib_table': { 'ipv4': { 'num_multicast_tables': 1, 'num_unicast_tables': 3, 'total_multicast_prefixes': 0, ...
""" Complexities: Runtime O(n log n): 2 sort() executions with O(n log n) each, while iteration with O(n+n) Space O(1) """ def min_platforms(arrivals, departures): """ :param: arrival - list of arrival time :param: departure - list of departure time TODO - complete this method and return the minimum n...
# # @lc app=leetcode id=993 lang=python3 # # [993] Cousins in Binary Tree # # @lc code=start # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def isCousins(self, root...
#!/usr/bin/env python print('{:=^40}'.format (' Somente N° Pares de 1 até 50 ')) for c in range(1, 50+1): print('.', end='') if c % 2 == 0: print(c, end=' ') print('{:=^40}'.format(' Fim ')) #OTIMIZANDO EXERCICIO print('{:=^40}'.format (' Otimizado ')) for cont in range(2, 51, 2): print('.', end...
# number one solution def is_ipv4_address(s): """ Return True if 's' is a valid IPv4 address """ # split the string on dots s_split = s.split('.') return len(s_split) == 4 and all(num.isdigit() and 0 <= int(num) < 256 for num in s_split) # my Solution def isIPv4Address(inputString): ...
class StringParser: def __init__(self): self.parse_trees = [] def register(self,tree): self.parse_trees.append(tree) def parse(self, string): for tree in self.parse_trees: return tree.parse(string)
# -*- coding:utf-8 -*- # https://leetcode.com/problems/unique-paths-ii/description/ class Solution(object): def uniquePathsWithObstacles(self, obstacleGrid): """ :type obstacleGrid: List[List[int]] :rtype: int """ if not obstacleGrid or not obstacleGrid[0]: ...
def merge(pairs): pairs = sorted(pairs) j,tmp = 0, [] while j < len(pairs): a = pairs[j] if j < len(pairs) - 1: b = pairs[j+1] if a[1] == b[0]: a = (a[0], b[1]) j += 1 tmp += [a] j += 1 return tmp print(merge(sorted(set([(1,2),(2,3),(4,5),(5...
print('=' * 5, 'EX_029', '=' * 5) # radar aletrônico vel = float(input('Qual a velocidade do carro?\n')) if vel > 80: print('MULTADO! Você excedeu o limite de velocidade que é de 80km/h.') multa = (vel - 80) * 7 print('Você pagará uma multa no valor de R${:.2f}!'.format(multa)) print('Tenha um bom dia. Diri...
# 最小栈 class MinStack: def __init__(self): """ initialize your data structure here. """ self.data = [] self.helper = [] def push(self, x: int) -> None: self.data.append(x) if len(self.helper) > 0: x = min(x, self.helper[-1]) self.help...
def corner_move(game): return list(set(game.possible_moves()) & {1, 3, 7, 9}) def center_move(game): return list(set(game.possible_moves()) & {5}) def side_move(game): return list(set(game.possible_moves()) & {2, 4, 6, 8}) def test_if_win_is_possible(game, to_check=None): if to_check is None: ...
#打印1到100之间的整数,跳过可以被7整除的,以及数字中包含7的整数 for i in range(1,101): if i % 7 == 0 or i % 10 == 7 or i // 10 == 7: continue else: print(i)
class Solution: def maxProfit(self, prices) -> int: ''' Notice that we can complete as many transactions as we like. Therefore, a greedy rule are easily came out, that we buy it on the low price day which compares with the next day and sell it on the high price day which co...
def part1(): values = [i.split(" ") for i in open("input.txt").read().split("\n")] lights = [[False]*50 ,[False]*50,[False]*50,[False]*50,[False]*50,[False]*50] for command in values: if command[0] == "rect": length, height = (int(i) for i in command[1].split("x")) for i in ...
# https://blog.csdn.net/Violet_ljp/article/details/80556460 # https://www.youtube.com/watch?v=pcKY4hjDrxk # https://github.com/minsuk-heo/problemsolving/tree/master/graph def bfs(graph, start): vertexList, edgeList = graph visitedList = [] queue = [start] adjacencyList = [[] for vertex in vertexList] ...
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Communicator client code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights R...
# from collections import Counter, defaultdict # class Solution: # def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: # count = Counter(nums) # # print('count: {}'.format(count)) # tmp = nums.copy() #list(set(nums.copy())) # tmp.sort() # # print('tmp...