content
stringlengths
7
1.05M
#! /usr/bin/python3 def a(k, x1, x2, x3, x4, x5): def b(): def c(): return a(k, x1, x2, x3, x4, x5) nonlocal k k -= 1 return a(k, c(), x1, x2, x3, x4) return x4 + x5 if k <= 0 else b() for i in range(0,8): print(a(i,1,-1,-1,1,0))
""" 57. Insert Interval Example 1: Input: intervals = [[1,3],[6,9]], newInterval = [2,5] Output: [[1,5],[6,9]] Example 2: Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] Output: [[1,2],[3,10],[12,16]] Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]. ...
class Solution: def fizzBuzz(self, n): """ :type n: int :rtype: List[str] """ list = [] for i in range(1, n + 1): div3 = i % 3 == 0 div5 = i % 5 == 0 if div3 and div5: list.append("FizzBuzz") elif div3: ...
""" * Create Image. * * The createImage() function provides a fresh buffer of pixels to play with. * This example creates an image gradient. """ def setup(): size(640, 360) global img img = createImage(230, 230, ARGB) pixCount = len(img.pixels) for i in range(pixCount): a = map(i, 0...
class Match(): def __init__(self, span, value): self.span = span self.token = span.text self.value = value self.start = span[0].idx self.end = span[0].idx + len(span.text) def contains(self, other): return self.start <= other.start and self.end >= ot...
def thesaurus(*args, sort=False) -> dict: """Формирует словарь, в котором ключи — первые буквы слов, а значения — списки, содержащие слова, начинающиеся с соответствующей буквы :param *args: перечень слов :param sort: признак необходимости сортировки словаря по алфавиту (True - сортировать, False - не ...
class Mapping(): # TODO: add support for one_of=str(group) which extends required # It should be used to group multiple mappings together and only one of # the mapping of the group can and has to be set. Mappings of one_of # cannot have default value. def __init__(self, name, source=None, required=T...
# generated from genmsg/cmake/pkg-genmsg.context.in messages_str = "/home/ubuntu/catkin_ws/src/navigation/costmap_2d/msg/VoxelGrid.msg" services_str = "" pkg_name = "costmap_2d" dependencies_str = "std_msgs;geometry_msgs;map_msgs" langs = "gencpp;genlisp;genpy" dep_include_paths_str = "costmap_2d;/home/ubuntu/catkin_w...
# Language: Python 3 i = 4 d = 4.0 s = 'HackerRank ' int2 = int(input()) double2 = float(input()) string2 = input() int2_i = i + int2 double2_d = d + double2 string2_s = s + string2 print(int2_i, double2_d, string2_s, sep="\n")
a = list(map(int,input().split())) def heapsort(arr,e): i=1 while i<e: upheap(arr,i) i+=1 i-=1 while i>0: tmp=arr[0] arr[0]=arr[i] arr[i]=tmp i-=1 downheap(arr,i) def leftC(i): return int(((i) + 1) * 2 - 1) def rightC(i): return int(((i) ...
fname = input('Enter the file name') try: f = open(fname) except: print('The file could not be opened') quit() total = 0 count = 0 for line in f: if 'X-DSPAM-Confidence' in line: print(line) i = line.find(': ') + 1 total += float(line[i:len(line)]) count += 1 print('Av...
# -*- coding: utf-8 -*- # @Author : Ecohnoch(xcy) # @File : configs.py # @Function : TODO app_redis_hostname = 'my_redis' app_redis_port = 6379 app_info_key = 'INFO_KEY' app_response_key = 'RESPONSE_KEY' app_error_key = 'ERROR_KEY' app_kafka_host = 'my_kafka:9092' app_kafka_topic = 'user_queue' app_kafka_ke...
# DROP TABLES songplay_table_drop = "DROP TABLE IF EXISTS songplays" user_table_drop = "DROP TABLE IF EXISTS users" song_table_drop = "DROP TABLE IF EXISTS songs" artist_table_drop = "DROP TABLE IF EXISTS artists" time_table_drop = "DROP TABLE IF EXISTS time" # CREATE TABLES songplay_table_create = ("""CREATE TABLE ...
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ for _ in [0]*int(input()): n,x,*a=map(int,input().split()) a=sorted(a) b=a[0]-a[1] print(min(x,n-1+b)-b)
""" pierre de fermat 17th frensh mathematician century: * a^p -a --> a is all numbers from 1 to p not including p * if all the outcome from the quation are divisble by p then p is a prime * note:we dont need to include the number it self because the outcome will be always divisble by the number """ number = 5 d...
class DjangoUser(object): def dangerous_method(self): pass def safe_method(self): pass def get_user(): # without an inference tip, this will be un-inferrable return DjangoUser.objects.get(id=1337) user = get_user() # dangerous_method call #1 user.dangerous_method() def get_users()...
[ i+j for i in range(1) for j in range(2) ] { x * x for x in seq } { y.attr : z() for y, z in mapping }
# Adding a new method during runtime: class A: def foo(self): print('A.foo()') x = A() y = A() x.foo() # A.foo() y.foo() # A.foo() def foo2(self): print('A.foo2()') A.foo2 = foo2 x.foo2() # A.foo2() y.foo2() # A.foo2()
# imgur key client_id = '757aa7465befd6c' client_secret = '83a2c6c8c7465d26236561a4e9bd15edb326805c' fgoAlbum_id = 'b3ylv' gmAlbum_id = '0HaTw' foodAlbum_id = 'XGsgM' access_token = '3b74c308d3d087d3b14518d24ffe92d0f5162f3f' refresh_token = '804352730072e91b4f0f0d1ebad4620c30837912' # line bot key line_channel_access_...
#!/usr/bin/python3.7+ # -*- coding:utf-8 -*- """ @auth: cml @date: 2021/2/23 @desc: ... """
# -*- coding: utf-8 -*- def main(): a = int(input()) b = int(input()) c = int(input()) d = int(input()) p = int(input()) print(min(a * p, b + max(0, (p - c)) * d)) if __name__ == '__main__': main()
score_configs = { 'CHEAT' : 1, 'TRUST' : -1, 'single_cheat' : 3, 'single_trust' : -1, 'both_trust' : 2, 'both_cheat' : 0, } players_configs = { 'Bot': 3, 'Follower': 3, 'Gambler': 3, 'Pink': 3, 'Follower_2': 3, 'Black': 3, 'Single_Mind': 3, 'Sherlock': 3, } ...
class PillowtopCheckpointReset(Exception): pass class PillowNotFoundError(Exception): pass class PillowtopIndexingError(Exception): pass class PillowConfigError(Exception): pass class BulkDocException(Exception): pass
# -*- coding: utf-8 -*- """ @File : __init__.py @Time : 2019/12/22 下午8:52 @Author : yizuotian @Description : """
nome = input('Digite seu nome completo: ') apenasletras = nome.replace(" ","") dividido = nome.split() primeironome = dividido[0] print('''Em maiusculo: {} Em minúsculo: {} Nº de letras total: {} Nº de letras primeiro nome: {} '''.format(nome.upper(),nome.lower(),len(apenasletras),len(primeironome)))
# Write a program, which keeps a dictionary with synonyms. The key of the dictionary will be the word. The value will # be a list of all the synonyms of that word. You will be given a number n – the count of the words. After each word, # you will be given a synonym, so the count of lines you have to read from the conso...
"""Configuration file for mapping counting and detection tasks.""" file_mapping_counting = { "Columbus_CSUAV_AFRL": "COWC_Counting_Columbus_CSUAV_AFRL.tbz", "Potsdam_ISPRS": "COWC_Counting_Potsdam_ISPRS.tbz", "Selwyn_LINZ": "COWC_Counting_Selwyn_LINZ.tbz", "Toronto_ISPRS": "COWC_Counting_Toronto_ISPRS....
class Solution: def licenseKeyFormatting(self, S: str, K: int) -> str: result = [] for c in reversed(S): if c != '-': if len(result) % (K + 1) == K: result.append('-') result.append(c.upper()) return ''.join(reversed(result))
class Solution: def myAtoi(self, str: str) -> int: s = str if not s: return 0 s = s.strip() print(s) if s == "": return 0 multiplier = 1 if s[0] == '+': multiplier = 1 s = s[1:] elif s[0] == '-': ...
age = 40 # tipo inteiro age_text = "40" # tipo string print(age) print(age_text) print(type(age)) # type -> retorna o tipó de dado print(type(age_text)) # As estruturas de dados tem atributos e metodos # dir -> retorna a lista de metodo do objeto. my_name = ('Carl') print(my_name) print(dir(my_name)) print(help(m...
def isprime(n): c=0 for i in range(1,n+1): if n%i==0: c+=1 if c==2: print("prime number") else: print("not a prime number") def factorial(n): f=1 for i in range(1,n+1): f*=i print(f)
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: def postdfs(stop): if postorder and inorde...
SYSTEMS = "root.properties.systems" ITEMS = f"{SYSTEMS}.items" ID = f"{SYSTEMS}.items.properties.id" NAME = f"{SYSTEMS}.items.properties.name" VENDOR = f"{SYSTEMS}.items.properties.vendor" MODEL = f"{SYSTEMS}.items.properties.model" TYPE = f"{SYSTEMS}.items.properties.type" SERIAL_NUMBER = f"{SYSTEMS}.items.properties....
""" A pacman package builder. .. moduleauthor:: James Reed <jcrd@tuta.io> """
# Project Description located @ https://www.dumas.io/teaching/2021/fall/mcs260/nbview/projects/project3.html # MCS 260 Fall 2021 Project 3 # Umar Chaudhry # I completed this project completely with my own work and followed the project description to the best of my ability. " Create functions that help analyze or...
''' SHORT URLS BOT CONFIGURATION FILE Edit me before start Bot.py! ''' # Token of the bot. Get it one from https://telegram.me/BotFather TOKEN = "992522370:AAGK3lfg3SFjtWgWHoo6pz9BCy8Liiwvmms" # Telegram IDs list of admins of the bot (that can issue /users command) ADMINS = [] # Insert absolute path to databa...
my_room = { 'plaats': "Vlijmen", 'straat naam': "Molenstraat" , 'postcode': "5251 EN", 'huisnummer': 9, 'surface': 20, 'hoogte': 3, 'lengte': 5, 'breedte': 4, 'banken': 1, 'bureaus': 1, 'kasten': 1, 'deur': 1, 'ramen': 4, 'bed': 1, }
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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 ...
#pattern printing #pattern triangle pattern # print("hi pradeep") #Qn-1 ************************************************************ """I=1 #OUTPUT while i<=5: #* j=1 #** while j<=i: #*** print("*",end=" ") #**** ...
class AsyncnotiException(Exception): def __init__(self, message, code): super(Exception, self).__init__(message) self.message = message self.code = code
# class Tree: # def __init__(self, val, left=None, right=None): # self.val = val # self.left = left # self.right = right # class LLNode: # def __init__(self, val, next=None): # self.val = val # self.next = next class Solution: prev = None head = None def so...
class Solution: def getNoZeroIntegers(self, n: int) -> List[int]: for A in range(n): B = n - A if '0' not in str(A) and '0' not in str(B): return A, B
print("Teste WHILE") #O numero factorial é como 5 = 5*4*3*2*1 factorial_number = input("Entre com um número:") factorial_number = int(factorial_number) if factorial_number > 0: step = factorial_number total = factorial_number while step > 1: step -= 1 total *= step print("O fatori...
# output: ok a = {} assert(len(a) == 0) for i in range(0, 100): a[i] = i * 2 assert(len(a) == 100) for i in range(0, 100): assert i in a assert(a[i] == i * 2) assert 101 not in a for i in range(0, 100, 2): del a[i] assert(len(a) == 50) for i in range(0, 100): assert (i in a) == ((i % 2) != 0) a...
#CONFIG FILE #Made by Luka Dragar #@thelukadragar operatingmode="xyz" #"xy"---move only in xy #"xyz"--move in xy and z #---------------------------------------------- sendinginterval=0.15 #interval to send points[seconds] #try changing if there are problems myIP= "127.0.0.1" # localhost or your ip "192.168....
# the most common user agents by https://techblog.willshouse.com/2012/01/03/most-common-user-agents/ DEFAULT_USER_AGENTS = [ "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ...
class PlayerCharacter: membership = True def __init__(self, name, age): self.name = name self.age = age def shout(self): print(f"My name is {self.name}") @classmethod def adding_things(cls, num1, num2): return cls('Teddy', num1 + num2) @staticmethod def add...
# 42. Trapping Rain Water # Runtime: 131 ms, faster than 12.45% of Python3 online submissions for Trapping Rain Water. # Memory Usage: 15.7 MB, less than 35.74% of Python3 online submissions for Trapping Rain Water. class Solution: # Using Stacks def trap(self, height: list[int]) -> int: ans = 0 ...
n=int(input()) for i in range(n): brackets = input() stack=[] dictt={'(':')', '[':']', '{':'}'} flag=0 for b in brackets: #print(stack) if (len(stack)==0) and b in dictt.values(): flag=1 break elif (len(stack)==0) or b in dictt.keys(): stac...
def export_docs(documents, output_path): """ Exports a list of dictionaries to a single csv file :param documents: list of dictionaries :param output_path: file path to csv file """ for doc in documents: export_dict(doc, output_path) def export_dict(dictionary, output_path): """ Expo...
{ "targets": [ { "target_name": "index", "sources": ["src/index.cc"], "defines": [ 'ENC_PUBLIC_KEY="<!(echo $ENC_PUBLIC_KEY)"' ] }, ], }
OCTICON_THUMBSDOWN = """ <svg class="octicon octicon-thumbsdown" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M7.083 15.986c1.34.153 2.334-.982 2.334-2.183v-.5c0-1.329.646-2.123 1.317-2.614.329-.24.66-.403.919-.508a1.75 1.75 0 001.514.872h1a1.75 1.75 0 001....
''' Version Checker module entry point ''' __version__ = '0.2.2-alpha.2'
""" Classes and functions used to create and download LBRY Files. LBRY Files are Crypt Streams created from any regular file. The whole file is read at the time that the LBRY File is created, so all constituent blobs are known and included in the stream descriptor file. """
def main(): while True: try: print(''.join(list(chr(ord(word) - 7) for word in input()))) except EOFError: break pass if __name__ == '__main__': main()
print(""" Witaj, w prostym kalkulatorze ;)""") print("""wybierz porzadana operacje : + - dodawanie - - odejmowanie / - dzielenie * - mnozenie ** - potegowanie """) operacja = input("wybrana operacja : ") a = int(input("Podaj pierwsza liczbe : ")) b = int(input("Podaj druga liczbe : ")) if (operacja == '+'): ...
""" 使用封装数据的思想 创建员工类/部门类,修改实现下列功能. 1. 定义函数,打印所有员工信息, 格式:xx的员工编号是xx,部门编号是xx,月薪xx元. 2. 定义函数,打印所有月薪大于2w的员工信息, 格式:xx的员工编号是xx,部门编号是xx,月薪xx元. 3. 定义函数,打印所有员工的部门信息, 格式:xx的部门是xx,月薪xx元. 4. 定义函数,查找薪资最少的员工 5. 定义函数,根据薪资对员工列表升序排列 # 员工列表 list_employees = [ {"eid": 1001, "did": 9002, ...
class Request: def __init__(self): self.app = None self.base_url = None self.body = None self.cookies = {} self.fresh = None self.hostname = None self.ip = None self.ips = None self.method = None self.original_url = None self.pa...
#! /usr/bin/env python3 def are_same(serial): if (serial[0] != serial[1] and serial[1] != serial[2] and serial[0] != serial[2]): return False return True def check_serial(serial): try: serials = serial.split('-') except: return False if len(serials) != 3: return False try: X = [ord(a) for a in lis...
""" Functionality which could be shared among various serializes. """ class InjectUserMixin(object): """ Inject a user to object being created from the logged in user such that the Front-end does not need to supply the value """ def __init__(self, *args, **kwargs): super(InjectUserMixin, se...
class wordsServant: """class to look at words can remove repeadted words""" def __init__(self, text): self.text = text self.deleteWords = ["like", "maybe", "just"] # TODO lowercase for delete words self.list_text = self.text.split(" ") def repeatedWords(self): ...
#Exclude variants not in hearing loss panel if Panels not in {ACMG59}: return False
def check_palindrome_rearrangement(string): chars = set() for char in string: if char not in chars: chars.add(char) else: chars.remove(char) return len(chars) < 2 # Tests assert check_palindrome_rearrangement("carrace") assert not check_palindrome_rearrangement("da...
class Solution: def XXX(self, n: int) -> int: # 首先求出到达顶楼时,步长为2最大次数 step_2_max = n//2 # cnt表示爬到顶楼的方法种类 cnt = 0 for i in range(step_2_max+1): if i==0: cnt = 1 else: # i个步长为二的情况下,步长为1的个数为step_1_num step_1_n...
WEEKLY_STRADDLE_COLUMNS = ['TIMESTAMP', 'OPEN', 'HIGH', 'LOW', 'CLOSE', 'STRIKE', 'OPEN_C', 'HIGH_C', 'LOW_C', 'CLOSE_C', 'H-O_C', 'L-O_C', 'C-O_C', 'OPEN_P', 'HIGH_P', 'LOW_P', 'CLOSE_P', 'H-O_P', 'L-O_P', 'C-O_P'] OPTIONS_COLUMNS = ['TIMESTAMP', 'EXPIRY_DT', 'SYM...
# HAUL strings def startsWith(s, prefix): return s.startswith(prefix) def sub(s, startIndex, endIndex): return s[startIndex:endIndex] def rest(s, startIndex): return s[startIndex:] def length(s): return len(s) class _strings: def __init__(self, data): self.data = data def length(self): ...
#!python def linear_search(array, item): """return the first index of item in array or None if item is not found""" # implement linear_search_iterative and linear_search_recursive below, then # change this to call your implementation to verify it passes all tests return linear_search_iterative(array, i...
def printGraph(graph): for node in graph: print(node.toString()) def drawAsMatrix(graph, size = 3): ret = list() line = list() lastLine = 0 for i in range(0, len(graph)): ii = int(i/size) if not lastLine == ii: ret.append(line) lastLine = ii ...
# # PySNMP MIB module ATM-FORUM-TC-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ATM-FORUM-TC-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:15:02 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
weight = input('Please input your weight(kg)...>') height = input('Please input your height(cm)...>') weight = float(weight) height = float(height) / 100 bmi = weight / (height ** 2) print('{:>7s}\t{:> 3.2f}\tkg'.format('Weight', weight)) print('{:>7s}\t{:> 3.2f}\tcm'.format('Height', height*100)) print('{:>7s}\t{:>...
class BuildLog: FILE = 0 LINE_NUMBER = 1 WARNING_CODE = 2 MESSAGE = 3 def __init__(self, filePath): self._file = open(filePath, 'r') self._parseLog() def _parseLog(self): self._lines = self._file.readlines() self._lines[:] = [line for line in self._lines if ": w...
DEBUG = True SECRET_KEY = "Some secret key" HOST = "127.0.0.1" PORT = 5000
# !/usr/bin/env python3 # -*- cosing: utf-8 -*- fileprt = open("file2.txt", "r") content1 = fileptr.readline() content2 = fileptr.readline() print(content1) print(content2) fileprt.close()
human = { "PSSM_folder": '../data/Malonylation/Human/PSSM/', "SPD3_folder": '../data/Malonylation/Human/SPD3/', "encoded_file": '../data/Malonylation/Human/HM_encoded.csv', "data_folder": '../data/Malonylation/Human/HSA+SPD3/', "output": '../data/lemp/human/lemp_features.npz', "output_lemp_compa...
#It will print the index of e vowels = ['a', 'e', 'i', 'o', 'i'] index = vowels.index("e") print(index) #It will print the index of o vowels = ['a', 'e', 'i', 'o', 'i'] index=vowels.index("o") print(index)
print('Welcome to the tip calculator!') bill = float(input('What was the total bill? $')) tip = float(input('What percentage tip would you like to give? 10%, 12% or 15% ')) / 100 n_people = int(input('How many people to split the bill? ')) bill_person = (bill + bill * tip) / n_people print(f'Each person should pay ${b...
"""This is for opening and closing files with a few other features tucked in for fun""" def addToFile(filename, information, overwrite=False): '''(str, str [, bool]) -> True add content to the end of a file, or create a new file''' if overwrite: file = open(filename, "w") file.write(informat...
arr = list(map(int, input().split())) n = int(input()) for i in range(n, len(arr)): print(arr[i], end = ' ') for i in range(n): print(arr[i], end = ' ')
class BreakingTheCode: def decodingEncoding(self, code, message): if 'a' <= message[0] <= 'z': return ''.join('{0:02}'.format(code.index(e)+1) for e in message) d = dict(('{0:02}'.format(i), e) for i, e in enumerate(code, 1)) return ''.join(d[message[i:i+2]] for i in xrange(0, le...
def leia_float (): while True: try: num = float(input('Digite um numero real: ').replace(',', '.')) except (ValueError, TypeError): print('Por favor, digite um numero real valido! ') else: return num def leia_int (): while True: try: ...
with open('foo.txt', 'r') as file_read: for line in file_read: # NOTA: mejor que file_read.readlines(): print(line, end='')
# basic generator function # def myGen(n): # yield n # yield n+1 # g = myGen(1) # print(next(g)) # print(next(g)) # print(next(g)) def myGen(): yield "These" yield "words" yield "come" yield "one" yield "at" yield "a" yield "time" gen = myGen() for i in range(1, 9): print...
class Solution: def arrayNesting(self, nums: List[int]) -> int: result = 0 for i in range(len(nums)): if nums[i] != -1: start, count = nums[i], 0 while nums[start] != -1: temp = start start = nums[start] ...
# Practice_#1 # Quick Brown Fox # Use a for loop to take a list and print each element of the list in its own line. sentence = ["the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"] # Method_#1 for word in sentence: print(word) # Method_#2 ''' for index in range(0, len(sentence) ): prin...
#!/usr/bin/env python3 a = int(input("a = ")) b = int(input("b = ")) print("A válasz: " + str(a + b))
# The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. # # 73167176531330624919225119674426574742355349194934 # 96983520312774506326239578318016984801869478851843 # 85861560789112949495459501737958331952853208805511 # 125406987471585238630507156932909632952274...
## Based off of example at http://pro.arcgis.com/en/pro-app/tool-reference/data-management/calculate-field-examples.htm#ESRI_SECTION1_F3F8CD77A9F647ABBA678A76ADB86E15 ## Goal: calculate the percent increase of a numeric field ## Example use case: identify the rate of temperate increase as weather stations move inland ...
word = input('') word_count = 0 start = 0 croatia_word = [['c=', 'c-', 'dz=', 'd-', 'lj', 'nj', 's=', 'z=']] for i in range(len(croatia_word[0])): for j in range(len(croatia_word[0])): croatia = str(croatia_word[0][j]) if word.find(croatia, start) != -1: word_count += 1 ...
class SimpleWeightedEnsemble(object): def __init__(self): super(SimpleWeightedEnsemble, self).__init__() class XGBoostEnsemble(object): def __init__(self): super(XGBoostEnsemble, self).__init__() class MLPEnsemble(object): def __init__(self): super(MLPEnsemble, self).__init__()
""" LEETCODE 278 - FIRST BAD VERSION coded by Fatih Cinar on January 13th, 2020 """ # The isBadVersion API is already defined for you. # @param version, an integer # @return a bool # def isBadVersion(version): class Solution: def recFindFirstBadVersion(self, low, high): """ This ...
class MyMath: def add(self, a, b): if type(a) == list: if type(b) == list: return [i + j for i,j in zip(a,b)] else: return [i + b for i in a] else: return a + b def pow(self, base, power): if type(base) == list: ...
# Configuration file of staticmapservice HEADERS = {'User-Agent':'staticmapservice/0.0.1'} TILE_SERVER = 'http://a.tile.osm.org/{z}/{x}/{y}.png' IS_TMS = False # True if you use a TMS instead of OSM XYZ tiles # Default values can be overwritten in each request DEFAULT_WIDTH = '300' DEFAULT_HEIGHT = '200' DEFAULT_ZOO...
#!/usr/bin/python2.7 ############################################################################## # Global settings ############################################################################## # Describes all the garage doors being monitored GARAGE_DOORS = [ # { # 'pin': 16, # 'name': "Garage Doo...
# 6. Escreva um programa que receba o preço de dois produtos. Calcule um desconto de # 8% no primeiro produto, 11% no segundo e apresente o valor final a ser pago. produto1 = float(input("Digite o valor do produto 1: ")) produto2 = float(input("Digite o valor do produto 2: ")) valor1 = produto1 - (produto1 * 0.08) va...
class Baggage_classify_mod: def __init__(self,modelname,save_modelname): self.modelname = modelname self.save_modelname = save_modelname def fit_func(modelname,x_train,y_train): modelname.fit(x_train,y_train) return modelname def predict_func(m...
ficha = dict() ficha['nome'] = str(input('Nome: ')) ficha['média'] = float(input(f'Média de {ficha["nome"]}: ')) if ficha['média'] >= 7: ficha['situação'] = 'Aprovado' elif ficha['média'] <= 5: ficha['situação'] = 'Reprovado' else: ficha['situação'] = 'Recuperação' print('-=' * 30) for k, v in ficha.items()...
num = int(input("Digite um número: ")) lista = [] cont = 0 for i in range(1, num): div = [] for j in range(2, i): if i % j == 0 and i != j: div.append(i) cont += 1 if len(div) == 0: lista.append(i) print(lista) print(f"Foram realizadas {cont} divisões")
class Solution: def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ digits.reverse() ld = len(digits) index = 0 c = 1 while index < ld and c == 1: digits[index] += c c, digits[index] = digits[ind...
class Sorting: def swap(self, arr, pos1, pos2): arr[pos1], arr[pos2] = arr[pos2], arr[pos1] return def selection_sort(self, arr): for i in range(len(arr)): min_ind = i for j in range(i + 1, len(arr)): if arr[j] < arr[min_ind]: ...
class Atributo: def __init__(self,nombre,tipo): self.columnNumber = None self.nombre = nombre self.tipo = tipo self.isPrimary = False self.ForeignTable = None self.default = None self.isNull = True self.isUnique = False #Punteros ...