content
stringlengths
7
1.05M
''' Constants --- Constants used in other scripts. These are mostly interpretations of fields provided in the Face2Gene jsons. ''' HGVS_ERRORDICT_VERSION = 0 # Bucket name, from where Face2Gene vcf and json files will be downloaded AWS_BUCKET_NAME = "fdna-pedia-dump" # caching directory CACHE_DIR = ".cache" # tests that count as chromosomal tests, if these are positive, cases will be # excluded CHROMOSOMAL_TESTS = [ 'CHROMOSOMAL_MICROARRAY', 'FISH', 'KARYOTYPE' ] # Test result descriptions, that will be counted as positive for our case # selection criteria POSITIVE_RESULTS = [ 'ABNORMAL', 'ABNORMAL_DIAGNOSTIC', 'DELETION_DUPLICATION', 'VARIANTS_DETECTED' ] NEGATIVE_RESULTS = [ 'NORMAL' 'NORMAL_FEMALE' 'NORMAL_MALE' 'NO_SIGNIFICANT_VARIANTS' ] # Translation of Face2Gene Mutation notation to HGVS operators HGVS_OPS = { 'SUBSTITUTION': '>', 'DELETION': 'del', 'DUPLICATION': 'dup', 'INSERTION': 'ins', 'INVERSION': 'inv', 'DELETION_INSERTION': 'delins', 'UNKNOWN': '' } # Translation of Description levels in Face2Gene to HGVS sequence types HGVS_PREFIX = { 'CDNA_LEVEL': 'c', 'PROTEIN_LEVEL': 'p', 'GENOMIC_DNA_LEVEL': 'g', 'UNKNOWN': '', 'RS_NUMBER': '' } # blacklist HPO illegal hpo terms ILLEGAL_HPO = [ 'HP:0000006' # autosomal-dominant inheritance ] CONFIRMED_DIAGNOSIS = [ "MOLECULARLY_DIAGNOSED", "CLINICALLY_DIAGNOSED", "CORRECTED_DIAGNOSIS" ] DIFFERENTIAL_DIAGNOSIS = [ "DIFFERENTIAL_DIAGNOSIS", ]
x = float(input("Digite x: ")) y = float(input("Digite y: ")) if 0 <= x <= 8 and 0 <= y <= 8: if (0 <= x < 1 or 7 < x <= 8) and (0 <= y < 2): #pescoço print("branco") elif 3.5 <= x <= 4.5 and 3.5 <= y <= 4.5: #nariz print("branco") elif (1 <= x <= 3 or 5 <= x <= 7) and (7.25 <= y <= 7.75): #sobrancelha print("branco") elif (((x-2)**2 + (y-6)**2 <= 1**2) and not ((x-2)**2 + (y-6)**2 <= 0.5**2)): #olho esquerdo print("branco") elif (((x-6)**2 + (y-6)**2 <= 1**2) and not ((x-6)**2 + (y-6)**2 <= 0.5**2)): #olho direito print("branco") elif 3 < x < 5 and 1.5 < y < 2.5: #boca print("branco") elif ((x-3)**2 + (y-2)**2 < 0.5**2): #boca esquerda print("branco") elif ((x-5)**2 + (y-2)**2 < 0.5**2): #boca direita print("branco") else: print("azul") else: print("branco")
""" DAC typing class ESP32 has two 8-bit DAC (digital to analog converter) channels, connected to GPIO25 (Channel 1) and GPIO26 (Channel 2). The DAC driver allows these channels to be set to arbitrary voltages.<br The DAC channels can also be driven with DMA-style written sample data, via the I2S driver when using the “built-in DAC mode”. This class includes full support for using ESP32 DAC peripheral. ESP32 DAC output voltage range is 0-Vdd (3.3 V), the resolution is 8-bits """ class DAC: def deinit(self): """ Deinitialize the dac object, free the pin used. """ pass def write(self, value): """ Set the DAC value. Valid range is: 0 - 255 The value of 255 sets the voltage on dac pin to 3.3 V """ pass def waveform(self, freq, type ,duration=0 ,scale=0 ,offset=0 ,invert=2): """ Generate the waveform on the dac output Arg Description freq the waveform frequency; valid range: 16-32000 Hz for sine wave 500-32000 Hz for noise 170 - 3600 Hz for triangle 170 - 7200 Hz for ramp and sawtooth type the waveform type, use one of the defined constants: SINE, TRIANGLE, RAMP, SAWTOOTH and NOISE duration optional, is given, waits for duration ms and stops the waveform scale optional, only valid for sine wave; range: 0-3; scale the output voltage by 2^scale offset optional, only valid for sine wave; range: 0-255; ofset the output voltage by offset value invert optional, only valid for sine wave; range: 0-3; invert the half-cycle of the sine wave """ pass def beep(self, freq, duration ,scale=0): """ Generate the sine wave beep on the dac output Arg Description freq fequency; valid range: 16-32000 Hz duration the duration of the beep in ms scale optional; range: 0-3; scale the output voltage by 2^scale """ pass def write_timed(self, data, samplerate ,mode ,wait=False): """ Output the values on dac pin from array or file using ESP32 I2S peripheral The data in array or file must be 8-bit DAC values The data from array or file obtained with machine.ADC.read_timed() can be used. Arg Description data array object or filename If an array object is given, write data from array object The array object can be array of type 'B', or bytearray If the filename is given, the datafrom the file will be output samplerate the sample rate at which the data will be output valid range: 5000 - 500000 Hz mode optional, default: machine.DAC.NORMAL; if set to machine.DAC.CIRCULAR the data from array or file will be repeated indefinitely (or until stopped) wait optional, default: False; if set to True waits for data output to finish """ pass def write_buffer(self, data, freq ,mode ,wait=False): """ Output the values on dac pin from an array using timer The in the array must be 8-bit DAC values The data from an array obtained with machine.ADC.collect() can be used. Arg Description data array object of type 'B' freq float; the frequency at which the data will be output valid range: 0.001 - 18000 Hz mode optional, default: machine.DAC.NORMAL; if set to machine.DAC.CIRCULAR the data from array will be repeated indefinitely (or until stopped). Some 'cliks' can be expected when playing continuously if the first value differs from the last one. wait optional, default: False; if set to True waits for data output to finish """ pass def wavplay(self, wavfile, correct): """ Plays the WAV file on dac pin Only PCM, 8-bit mono WAV files with sample rate >= 22000 can be played If the optional argument correct is given, the sample rate is corrected by correct factor. The allowed range is: -8.0 - +8.0 (float values can be entered). """ pass def stopwave(self): """ Stops the background proces started by dac.waveform(), dac.write_timed() or dac.wavplay() function. """ pass
def f(x): return ((2*(x**4))+(3*(x**3))-(6*(x**2))+(5*x)-8) def reachEnd(previousm,currentm): if abs(previousm - currentm) <= 10**(-6): return True return False def printFormat(a,b,c,m,count): print("Step %s" %count) print("a=%.6f b=%.6f c=%.6f" %(a,b,c)) print("f(a)=%.6f f(b)=%.6f f(c)=%.6f" %(f(a),f(b),f(c))) print("m=%.6f f(m)=%.6f" %(m,f(m))) def main(a,b,c): if (not (a < b and c < b)) or (not(f(a) > f(c) and f(b) > f(c))): return False count = 0 previousm = b+1 while True: if (b - c) >= (c - a): m = (b+c)/2 if f(m) >= f(c): b = m else: a = c c = m else: m = (a+c)/2 if f(m) >= f(c): a = m else: b = c c = m printFormat(a,b,c,m,count) if reachEnd(previousm,m): print("Minimum value=%.6f occurring at %.6f" %(f(m),m)) break previousm = m count += 1 main(-3,-1,-2.2)
class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: result = [] rows, columns = len(matrix), len(matrix[0]) up = left = 0 right = columns-1 down = rows-1 while len(result) < rows*columns: for col in range(left, right+1): result.append(matrix[up][col]) for row in range(up+1, down+1): result.append(matrix[row][right]) if up != down: for col in range(right-1, left-1, -1): result.append(matrix[down][col]) if left != right: for row in range(down-1, up, -1): result.append(matrix[row][left]) up += 1 down -= 1 left += 1 right -= 1 return result
class NoProxy: def get(self, _): return None def ban_proxy(self, proxies): return None class RateLimitProxy: def __init__(self, proxies, paths, default=None): self.proxies = proxies self.proxy_count = len(proxies) self.access_counter = { path: {"limit": paths[path], "count": 0} for path in paths.keys() } self.default = {"http": default, "https": default} def get(self, keyword_arguments): counter = self.access_counter.get(keyword_arguments["path"]) if counter is not None: proxy = self.proxies[ (counter["count"] // counter["limit"] - self.proxy_count) % self.proxy_count ] counter["count"] += 1 return {"http": proxy, "https": proxy} return self.default def ban_proxy(self, proxies): self.proxies = list(filter(lambda a: a not in [proxies.get("http", ''), proxies.get("https", '')], self.proxies)) return None
#MARCELO CAMPOS DE MEDEIROS #ADS UNIFIP P1 2020 #LISTA 02 ''' 1- Faça um programa que solicite ao usuário o valor do litro de combustível (ex. 4,75) e quanto em dinheiro ele deseja abastecer (ex. 50,00). Calcule quantos litros de combustível o usuário obterá com esses valores. ''' valor_gas = float(input('Qual o valor do combustível?R$ ')) num = float(input('Qual o valor que deseja abastecer?R$ ')) valor_tot = num / valor_gas print('-=' * 35) print(f'O valor abastecido foi R${num:.2f} e a quantidade de combustivél é {valor_tot:.2f}l.') print('-=' * 35) print(' OBRIGADO, VOLTE SEMPRE! ')
months_json = { "1": "January", "2": "February", "3": "March", "4": "April", "5": "May", "6": "June", "7": "July", "8": "August", "9": "September", "01": "January", "02": "February", "03": "March", "04": "April", "05": "May", "06": "June", "07": "July", "08": "August", "09": "September", "10": "October", "11": "November", "12": "December", } month_days = { "1": 31, "2": 28, "3": 31, "4": 30, "5": 31, "6": 30, "7": 31, "8": 31, "9": 30, "01": 31, "02": 28, "03": 31, "04": 30, "05": 31, "06": 30, "07": 31, "08": 31, "09": 30, "10": 31, "11": 30, "12": 31, }
#coding: utf-8 ''' @Time: 2019/4/25 11:15 @Author: fangyoucai '''
__all__ = ['EncryptException', 'DecryptException', 'DefaultKeyNotSet', 'NoValidKeyFound'] class EncryptException(BaseException): pass class DecryptException(BaseException): pass class DefaultKeyNotSet(EncryptException): pass class NoValidKeyFound(DecryptException): pass
SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 } # The first step is to implement some code that allows us to calculate the score # for a single word. The function getWordScore should accept as input a string # of lowercase letters (a word) and return the integer score for that word, # using the game's scoring rules. # A Reminder of the Scoring Rules # Hints You may assume that the input word is always either a string of # lowercase letters, or the empty string "". You will want to use the # SCRABBLE_LETTER_VALUES dictionary defined at the top of ps4a.py. You should # not change its value. Do not assume that there are always 7 letters in a hand! # The parameter n is the number of letters required for a bonus score (the # maximum number of letters in the hand). Our goal is to keep the code modular - # if you want to try playing your word game with n=10 or n=4, you will be able # to do it by simply changing the value of HAND_SIZE! Testing: If this function # is implemented properly, and you run test_ps4a.py, you should see that the # test_getWordScore() tests pass. Also test your implementation of getWordScore, # using some reasonable English words. Fill in the code for getWordScore in # ps4a.py and be sure you've passed the appropriate tests in test_ps4a.py before # pasting your function definition here. def getWordScore(word, n): """ Returns the score for a word. Assumes the word is a valid word. The score for a word is the sum of the points for letters in the word, multiplied by the length of the word, PLUS 50 points if all n letters are used on the first turn. Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is worth 3, D is worth 2, E is worth 1, and so on (see SCRABBLE_LETTER_VALUES) word: string (lowercase letters) n: integer (HAND_SIZE; i.e., hand size required for additional points) returns: int >= 0 """ if len(word) == 0: return 0 # wordScore is the cumulative score for this word wordScore = 0 # lettersUsed is cumulative number of letters used in this word lettersUsed = 0 for theLetter in word: # For each letter, determine it's value wordScore += SCRABBLE_LETTER_VALUES[theLetter] lettersUsed += 1 # Multiply score so far by number of letters used wordScore *= lettersUsed # if all letters were used, then add 50 to score if lettersUsed == n: wordScore += 50 return wordScore
# # @lc app=leetcode id=86 lang=python3 # # [86] Partition List # # https://leetcode.com/problems/partition-list/description/ # # algorithms # Medium (43.12%) # Likes: 1981 # Dislikes: 384 # Total Accepted: 256.4K # Total Submissions: 585.7K # Testcase Example: '[1,4,3,2,5,2]\n3' # # Given the head of a linked list and a value x, partition it such that all # nodes less than x come before nodes greater than or equal to x. # # You should preserve the original relative order of the nodes in each of the # two partitions. # # # Example 1: # # # Input: head = [1,4,3,2,5,2], x = 3 # Output: [1,2,2,4,3,5] # # # Example 2: # # # Input: head = [2,1], x = 2 # Output: [1,2] # # # # Constraints: # # # The number of nodes in the list is in the range [0, 200]. # -100 <= Node.val <= 100 # -200 <= x <= 200 # # # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def partition(self, head: ListNode, x: int) -> ListNode: if not head: return head smaller_dummy = ListNode(0) greater_dummy = ListNode(0) smaller = smaller_dummy greater = greater_dummy node = head while node: if node.val < x: smaller.next = node smaller = smaller.next else: greater.next = node greater = greater.next node = node.next greater.next = None smaller.next = greater_dummy.next return smaller_dummy.next # @lc code=end
# Cálculo de IMC print("Vamos calcular seu IMC?") nome = input("Digite o seu nome: ") peso = float(input("Olá, {}, agora digite seu peso (em Kg, Ex: 68.9): " .format(nome))) altura = float(input("Digite sua altura (em m, Ex: 1.80): ")) media = peso / (altura * altura) print('Seu IMC é: {:.1f}'.format(media)) if media < 18.5: print("Abaixo do peso") elif media >= 18.5 and media <= 24.9: # poderia ser feito: elif 18.5 <= media < 25: /o python aceita esse tipo/ print("Você está no seu peso ideal") elif media>=25.0 and media<=29.9: # elif 25 <= media < 30: print("Você está levemente acima do peso") elif media>=30.0 and media<=34.9: # elif 30 <= media < 35: print("Obesidade Grau 1") elif media>=35.0 and media<=39.9: # elif 35 <= media < 40: print("Obesidade Grau 2") else: print("Obesidade grau 3(mórbida)")
with open("input.txt", "r") as input_file: input = input_file.read().split("\n") passwords = list(map(lambda line: [list(map(int, line.split(" ")[0].split("-"))), line.split(" ")[1][0], line.split(" ")[2]], input)) valid = 0 for password in passwords: count_letter = password[2].count(password[1]) if password[0][0] <= count_letter <= password[0][1]: valid += 1 print(valid)
music = { 'kb': ''' Instrument(Flute) Piece(Undine, Reinecke) Piece(Carmen, Bourne) (Instrument(x) & Piece(w, c) & Era(c, r)) ==> Program(w) Era(Reinecke, Romantic) Era(Bourne, Romantic) ''', 'queries': ''' Program(x) ''', } life = { 'kb': ''' Musician(x) ==> Stressed(x) (Student(x) & Text(y)) ==> Stressed(x) Musician(Heather) ''', 'queries': ''' Stressed(x) ''' } Examples = { 'music': music, 'life': life }
"""3.3 Stack of Plates: Imagine a (literal) stack of plates. If the stack gets too high, it might topple. Therefore, in real life, we would likely start a new stack when the previous stack exceeds some threshold. Implement a data structure SetOfStacks that mimics this. SetOfStacks should be composed of several stacks and should create a new stack once the previous one exceeds capacity. SetOfStacks. push () and SetOfStacks. pop () should behave identically to a single stack (that is, pop ( ) should return the same values as it would if there were just a single stack). FOLLOW UP Implement a function popAt (int index) which performs a pop operation on a specific sub-stack. """ class SetOfStacks(): def __init__(self, max_stack_size: int, x=[]): self.core = [] self.max = max_stack_size for e in x: self.push(e) def __repr__(self): return repr(self.core) def pop_at(self, index: int): if not self.core: return if not index < len(self.core): return if not self.core[index]: return return self.core[index].pop() def pop(self): if not self.core: return while self.core and not self.core[-1]: self.core.pop() if self.core: return self.core[-1].pop() def push(self, value): if not self.core: self.core = [[value]]; return if len(self.core[-1]) == self.max: self.core.append([value]) else: self.core[-1].append(value) def peek(self): if self.core[n_stack]: return self.core[n_stack][-1] # test multi_stack = SetOfStacks(5, range(24)) # test push print(f'after push: stacks: {multi_stack}') # test pop_at for _ in range(6): print(f'after pop_at(2): {multi_stack.pop_at(2)}, stack: {multi_stack}') # test pop for i in range(20): multi_stack.pop() print(f'after pop: stacks: {multi_stack}')
myl1 = [] num = int(input("Enter the number of elements: ")) for loop in range(num): myl1.append(input(f"Enter element at index {loop} : ")) print(myl1) print(type(myl1)) myt1 = tuple(myl1) print(myt1) print(type(myt1)) print("The elements of tuple object are: ") for loop in myt1: print(loop)
# Scrapy settings for scraper project BOT_NAME = 'scraper' SPIDER_MODULES = ['scraper.spiders'] NEWSPIDER_MODULE = 'scraper.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent USER_AGENT = 'Googlebot-News' # Obey robots.txt rules ROBOTSTXT_OBEY = True # MONGO URI for accessing MongoDB MONGO_URI = "" MONGO_DATABASE = "" # sqlite database location SQLITE_DB = "" # pipelines are disabled by default ITEM_PIPELINES = { #'scraper.pipelines.SQLitePipeline': 300, #'scraper.pipelines.MongoPipeline': 600, }
## Data Categorisation ''' 1) Whole Number (Ints) - 100, 1000, -450, 999 2) Real Numbers (Floats) - 33.33, 44.01, -1000.033 3) String - "Bangalore", "India", "Raj", "abc123" 4) Boolean - True, False Variables in python are dynamic in nature ''' a = 10 print(a) print(type(a)) a = 10.33 print(a) print(type(a)) a = 'New Jersey' print(a) print(type(a))
class RelationType(object): ONE_TO_MANY = "one_to_many" ONE_TO_ONE = "one_to_one" class Relation(object): def __init__(self, cls): self.cls = cls class HasOne(Relation): def get(self, id): return self.cls.get(id=id) class HasMany(Relation): def get(self, id): value = [] tokens = id.split(",") for token in tokens: value += (self.cls.get(id=token.strip())) return value
# Time: 03/18/21 # Author: HammerLi # Tags: [Simulation] # Title: 字符串匹配 # Content: # 给出一个字符串和多行文字,在这些文字中找到字符串出现的那些行。 # 你的程序还需支持大小写敏感选项:当选项打开时,表示同一个字母的大写和小写看作不同的字符; # 当选项关闭时,表示同一个字母的大写和小写看作相同的字符。 tar = input() strict = bool(int(input())) n = int(input()) for i in range(0, n): src = input() if strict: if src.find(tar) != -1: print(src) else: if src.lower().find(tar.lower()) != -1: print(src) # Python3巨简单,模拟就行了
""" Given an array of integers, find the subset of non-adjacent elements with the maximum sum. Calculate the sum of that subset. It is possible that the maximum sum is , the case when all elements are negative. """ def maxSubsetSum(arr): n = len(arr) # n = length of the array dp = [0]*n # create a dp array of length n & initialize its values to 0 dp[0] = arr[0] # base dp[1] = max(arr[1], dp[0]) for i in range(2,n): # Because of the condition. No two adjacent elements can be picked. # Therefore we can either take one and then skip one, or skip one and run the subroutine. dp[i] = max(arr[i], dp[i-1], arr[i] + dp[i-2]) # in the dp, we store the max sum for the subarray up till the length of the subarray. # Hence simply return the last item in this to get the answer return dp[-1]
description = 'Alphai alias device' group = 'lowlevel' devices = dict( alphai = device('nicos.devices.generic.DeviceAlias'), )
{ 'targets': [ { 'target_name': 'overlay_window', 'sources': [ 'src/lib/addon.c', 'src/lib/napi_helpers.c' ], 'include_dirs': [ 'src/lib' ], 'conditions': [ ['OS=="win"', { 'defines': [ 'WIN32_LEAN_AND_MEAN' ], 'link_settings': { 'libraries': [ 'oleacc.lib' ] }, 'sources': [ 'src/lib/windows.c', ] }], ['OS=="linux"', { 'defines': [ '_GNU_SOURCE' ], 'link_settings': { 'libraries': [ '-lxcb', '-lpthread' ] }, 'cflags': ['-std=c99', '-pedantic', '-Wall', '-pthread'], 'sources': [ 'src/lib/x11.c', ] }], ['OS=="mac"', { 'link_settings': { 'libraries': [ '-lpthread', '-framework AppKit', '-framework ApplicationServices' ] }, 'xcode_settings': { 'OTHER_CFLAGS': [ '-fobjc-arc' ] }, 'cflags': ['-std=c99', '-pedantic', '-Wall', '-pthread'], 'sources': [ 'src/lib/mac.mm', 'src/lib/mac/OWFullscreenObserver.mm' ] }] ] } ] }
# --------------------------------------------------------------------- # Gufo Labs Loader: # a plugin # --------------------------------------------------------------------- # Copyright (C) 2022, Gufo Labs # --------------------------------------------------------------------- class APlugin(object): name = "a" def get_name(self) -> str: return self.name
# -*- coding: utf-8 -*- # ______________________________________________________________________________ def boolean_func(experiment): """Function that returns True when an experiment matches and False otherwise. Args: experiment (:class:`~skassist.Experiment`): Experiment that is to be tested. """ # ______________________________________________________________________________ def scoring_function(self, model, y_true, y_predicted_probability): """The scoring function takes a model, the true labels and the prediction and calculates one or more scores. These are returned in a dictionary which :func:`~skassist.Model.calc_results` uses to commit them to permanent storage. Args: scoring_function (:func:`function`): A python function for calculating the results given the true labels and the predictions. See :func:`~skassist.Model.scoring_function`. skf (:obj:`numpy.ndarray`): An array containing arrays of splits. E.g. an array with 10 arrays, each containing 3 splits for a 10-fold cross-validation with training, test and validation set. df (:obj:`pandas.DataFrame`): The DataFrame on which to evaluate the model. Must contain all feature, "extra" feature and target columns that the model requires. """
class InvalidProxyType(Exception): pass class ApiConnectionError(Exception): pass class ApplicationNotFound(Exception): pass class SqlmapFailedStart(Exception): pass class SpiderTestFailure(Exception): pass class InvalidInputProvided(Exception): pass class InvalidTamperProvided(Exception): pass class PortScanTimeOutException(Exception): pass
class CreatePickupResponse: def __init__(self, res): """ Initialize new instance from CreatePickupResponse class Parameters: res (dict, str): JSON response object or response text message Returns: instance from CreatePickupResponse """ self.fromResponseObj(res) def fromResponseObj(self, res): """ Extract _id, puid, business, businessLocationId, scheduledDate, scheduledTimeSlot, contactPerson, createdAt and updatedAt fields from json response object Parameters: res (dict, str): JSON response object or response text message """ if type(res) is dict and res.get('data') is not None: self.message = res.get("message") newPickup = res["data"] self._id = newPickup["_id"] self.puid = newPickup["puid"] self.business = newPickup["business"] self.businessLocationId = newPickup["businessLocationId"] self.scheduledDate = newPickup["scheduledDate"] self.scheduledTimeSlot = newPickup["scheduledTimeSlot"] self.contactPerson = newPickup["contactPerson"] self.createdAt = newPickup["createdAt"] self.updatedAt = newPickup["updatedAt"] else: self.message = str(res) def __str__(self): return self.message def get_pickupId(self): return self._id def get_message(self): return self.message
test = { 'name': 'q1_3', 'points': 1, 'suites': [ { 'cases': [ {'code': '>>> type(max_estimate) in set([int, np.int32, np.int64])\nTrue', 'hidden': False, 'locked': False}, {'code': '>>> max_estimate in observations.column(0)\nTrue', 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest'}]}
TYPES = {"int","float","str","bool","list"} MATCH_TYPES = {"int": int, "float": float, "str": str, "bool": bool, "list": list} CONSTRAINTS = { "is_same_type": lambda x, y: type(x) == type(y), "int" :{ "min_inc": lambda integer, min: integer >= min, "min_exc": lambda integer, min: integer > min, "max_inc": lambda integer, max: integer >= max, "max_exc": lambda integer, max: integer > max, "value_in": lambda integer, value_in: integer in value_in, "value_out": lambda integer, value_out: not integer in value_out }, "float": { "min_inc": lambda integer, min: integer >= min, "min_exc": lambda integer, min: integer > min, "max_inc": lambda integer, max: integer >= max, "max_exc": lambda integer, max: integer > max, "value_in": lambda float_, value_in: float_ in value_in, "value_out": lambda float_, value_out: not float_ in value_out }, "str": { "value_in": lambda string, value_in: string in value_in, "value_out": lambda string, value_out: not string in value_out }, "list": { "equal_len": lambda list_, len_: len(list_) == len_, "min_len" : lambda list_, min_len: len(list_) >= min_len, "min_inc": lambda list_, min: all(x >= min for x in list_), "min_exc": lambda list_, min: all(x > min for x in list_), "max_inc": lambda list_, max: all(x <= max for x in list_), "max_exc": lambda list_, max: all(x > max for x in list_) } } CONSTRAINT_CHECKS = { "int" :{ "min_inc": lambda min: type(min) in [int, float], "min_exc": lambda min: type(min) in [int, float], "max_inc": lambda max: type(max) in [int, float], "max_exc": lambda max: type(max) in [int, float], "value_in": lambda value_in: all([type(value) == int for value in value_in]), "value_out": lambda value_out: all([type(value) == int for value in value_out]) }, "float": { "min_inc": lambda min: type(min) in [int, float], "min_exc": lambda min: type(min) in [int, float], "max_inc": lambda max: type(max) in [int, float], "max_exc": lambda max: type(max) in [int, float], "value_in": lambda value_in: all([type(value) in [int,float] for value in value_in]), "value_out": lambda value_out: all([type(value) in [int,float] for value in value_out]) }, "str": { "value_in": lambda value_in: all([type(value) == str for value in value_in]), "value_out": lambda value_out: all([type(value) == str for value in value_out]) }, "list": { "equal_len": lambda len_: type(len_) == int and len_ > 0, "min_len" : lambda min: type(min) == int and min >= 0, "min_inc": lambda min: type(min) in [int,float], "min_exc": lambda min: type(min) in [int,float], "max_inc": lambda max: type(max) in [int,float], "max_exc": lambda max: type(max) in [int,float], } }
def main(): video = "NET20070330_thlep_1_2" file_path = "optical_flow_features_train/" + video optical_flow_features_train = open(file_path + "/optical_flow_features_train.txt", "r") clear_of_features_train = open(file_path + "/clear_opt_flow_features_train.txt", "w") visual_ids = [] for line in optical_flow_features_train: words = line.rstrip().split(' ') if len(words) == 2: if not int(words[1]) in visual_ids: visual_ids.append(int(words[1])) print("visual_ids", visual_ids) optical_flow_features_train.close() optical_flow_features_train = open(file_path + "/optical_flow_features_train.txt", "r") for line in optical_flow_features_train: words = line.rstrip().split(' ') if len(words) == 2: frame = int(words[0]) speaker_id = int(words[1]) else: # every id that each speaker gets during the video if speaker_id == 0 or speaker_id == 6 or speaker_id == 13 or speaker_id == 15 or speaker_id == 5 or speaker_id == 16 or speaker_id == 4 or speaker_id == 17 or speaker_id == 3 or speaker_id == 18: clear_of_features_train.write(str(frame) + ' ' + str(speaker_id) + '\n') for features in words: clear_of_features_train.write(str(features) + ' ') clear_of_features_train.write('\n') optical_flow_features_train.close() clear_of_features_train.close() if __name__ == "__main__": main()
prize_file_1 = open("/Users/MatBook/Downloads/prize3.txt") List = [] prizes = [] for line in prize_file_1: List.append(int(line)) first_line = List.pop(0) for i in List: print(i) for j in List: if i + j == first_line: prizes.append((i,j)) print (List) print( "you can have:", prizes)
#!/usr/bin/env python # -*- coding: utf-8 -*- template = """/* * * search_dipus * * ~~~~~~~~~~~~~~ * * * * Dipus JavaScript utilties for the full-text search. * * This files is based on searchtools.js of Sphinx. * * * * :copyright: Copyright 2007-2012 by the Sphinx team. * * :license: BSD, see LICENSE for details. * * * */ /** * * helper function to return a node containing the * * search summary for a given text. keywords is a list * * of stemmed words, hlwords is the list of normal, unstemmed * * words. the first one is used to find the occurance, the * * latter for highlighting it. * */ jQuery.makeSearchSummary = function(text, keywords, hlwords) {{ var textLower = text.toLowerCase(); var start = 0; $.each(keywords, function() {{ var i = textLower.indexOf(this.toLowerCase()); if (i > -1) start = i; }}); start = Math.max(start - 120, 0); var excerpt = ((start > 0) ? '...' : '') + $.trim(text.substr(start, 240)) + ((start + 240 - text.length) ? '...' : ''); var rv = $('<div class="context"></div>').text(excerpt); $.each(hlwords, function() {{ rv = rv.highlightText(this, 'highlighted'); }}); return rv; }}; /** * Search Module */ var Search = {{ _dipus_url: "{dipus_url}", _index: null, _pulse_status : -1, init : function (){{ var params = $.getQueryParameters(); if (params.q) {{ var query = params.q[0]; $('input[name="q"]')[0].value = query; this.performSearch(query); }} }}, stopPulse : function() {{ this._pulse_status = 0; }}, startPulse : function() {{ if (this._pulse_status >= 0) return; function pulse() {{ Search._pulse_status = (Search._pulse_status + 1) % 4; var dotString = ''; for (var i = 0; i < Search._pulse_status; i++) dotString += '.'; Search.dots.text(dotString); if (Search._pulse_status > -1) window.setTimeout(pulse, 500); }}; pulse(); }}, /** * perform a search for something */ performSearch : function(query) {{ // create the required interface elements this.out = $('#search-results'); this.title = $('<h2>' + _('Searching') + '</h2>').appendTo(this.out); this.dots = $('<span></span>').appendTo(this.title); this.status = $('<p style="display: none"></p>').appendTo(this.out); this.output = $('<ul class="search"/>').appendTo(this.out); $('#search-progress').text(_('Preparing search...')); this.startPulse(); this.query(query); }}, query : function(query) {{ var hlterms = []; var highlightstring = '?highlight=' + $.urlencode(hlterms.join(" ")); $('#search-progress').empty(); var url = this._dipus_url + "?q=" + $.urlencode(query); $.ajax({{ url: url, dataType: 'jsonp', success: function(json){{ for(var i = 0; i < json.hits.length; i++){{ var hit = json.hits[i]; var listItem = $('<li style="display:none"></li>'); var msgbody = hit._source.message; if (DOCUMENTATION_OPTIONS.FILE_SUFFIX == '') {{ // dirhtml builder var dirname = hit._source.path; if (dirname.match(/\/index\/$/)) {{ dirname = dirname.substring(0, dirname.length-6); }} else if (dirname == 'index/') {{ dirname = ''; }} listItem.append($('<a/>').attr('href', DOCUMENTATION_OPTIONS.URL_ROOT + dirname + highlightstring + query).html(hit._source.title)); }} else {{ // normal html builders listItem.append($('<a/>').attr('href', hit._source.path + DOCUMENTATION_OPTIONS.FILE_SUFFIX + highlightstring + query).html(hit._source.title)); }} if (msgbody) {{ listItem.append($.makeSearchSummary(msgbody, Array(query), Array(query))); Search.output.append(listItem); listItem.slideDown(5); }} else if (DOCUMENTATION_OPTIONS.HAS_SOURCE) {{ $.get(DOCUMENTATION_OPTIONS.URL_ROOT + '_sources/' + hit._source.path + '.txt', function(data) {{ if (data != '') {{ listItem.append($.makeSearchSummary(data, Array(query), hlterms)); Search.output.append(listItem); }} listItem.slideDown(5); }}); }} else {{ // no source available, just display title Search.output.append(listItem); listItem.slideDown(5); }} }}; Search.stopPulse(); Search.title.text(_('Search Results')); if (json.hits.length === 0){{ Search.status.text(_('Your search did not match any documents. Please make sure that all words are spelled correctly and that you\\'ve selected enough categories.')); }}else{{ Search.status.text(_('Search finished, found %s page(s) matching the search query.').replace('%s', json.hits.length)); }} Search.status.fadeIn(500); }}, error: function(XMLHttpRequest, textStatus, errorThrown) {{ console.log(textStatus, errorThrown); }} }}); }} }}; $(document).ready(function() {{ Search.init(); }}); """
def classfinder(k): res=1 while res*(res+1)//2<k: res+=1 return res # cook your dish here for t in range(int(input())): #n=int(input()) n,k=map(int,input().split()) clas=classfinder(k) i=k-clas*(clas-1)//2 str="" for z in range(n): if z==n-clas-1 or z==n-i: str+="b" else: str+="a" print(str)
class Config: conf = { "labels": { "pageTitle": "Weatherman V0.0.1" }, "db.database": "weatherman", "db.username": "postgres", "db.password": "postgres", "navigation": [ { "url": "/", "name": "Home" }, { "url": "/cakes", "name": "Cakes" }, { "url": "/mqtt", "name": "MQTT" } ] } def get_config(self): return self.conf def get(self, key): return self.conf[key]
#!/usr/bin/python # -*- coding: UTF-8 -*- """ @author:MT @file:__init__.py.py @time:2021/8/21 23:02 """
def is_leap(year): leap = False if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: leap = True else: leap = False else: leap = True return leap year = int(input()) print(is_leap(year)) ''' In the Gregorian calendar, three conditions are used to identify leap years: The year can be evenly divided by 4, is a leap year, unless: The year can be evenly divided by 100, it is NOT a leap year, unless: The year is also evenly divisible by 400. Then it is a leap year. '''
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: occ = set() n = len(s) max_length = 0 cur = 0 for i in range(n): if i != 0: # 左指针向右移动一格,移除一个字符 occ.remove(s[i-1]) while cur < n and s[cur] not in occ: occ.add(s[cur]) cur += 1 max_length = max(max_length, cur-i) return max_length if __name__ == '__main__': s = Solution() s1 = "abcabcbb" s2 = "bbbbb" s3 = "pwwkew" print(s.lengthOfLongestSubstring(s1)) print(s.lengthOfLongestSubstring(s2)) print(s.lengthOfLongestSubstring(s3)) print(s.lengthOfLongestSubstring(""))
"""HackerEarth docs constants""" DOC_URL_DICT = { # 'doc_name': 'doc_url1', # 'doc_name': 'doc_url2', }
class Solution(object): def maxSubArray1(self, nums): """ :type nums: List[int] :rtype: int """ this = maxsum = 0 for i in range(len(nums)): this += nums[i] if this > maxsum: maxsum = this elif this < 0: this = 0 return maxsum if maxsum != 0 else max(nums) def maxSubArray(self, nums): """ http://alfred-sun.github.io/blog/2015/03/11/ten-basic-algorithms-for-programmers/ :type nums: List[int] :rtype: int """ start = maxsum = nums[0] for num in nums[1:]: start = max(num, start + num) maxsum = max(maxsum, start) return maxsum
""" EVEN IN RANGE: Use range() to print all the even numbers from 0 to 10. """ for number in range(11): if number % 2 == 0: if number == 0: continue print(number)
# -*- coding: utf-8 -*- class DummyTile: def __init__(self, pos, label=None): self.pos = pos # Label tells adjacent mine count for this tile. Int between 0...8 or None if unknown self.label = label self.checked = False self.marked = False self.adj_mines = None self.adj_tiles = 0 self.adj_checked = 0 self.adj_unchecked = None def set_label(self, label): self.label = label self.checked = True def set_adj_mines(self, count): self.adj_mines = count self.checked = True def set_adj_tiles(self, count): self.adj_tiles = count def set_adj_checked(self, count): self.adj_checked = count def add_adj_checked(self): self.adj_checked = self.adj_checked + 1 def set_adj_unchecked(self, count): self.adj_unchecked = count def mark(self): self.marked = True
##Write code to switch the order of the winners list so that it is now Z to A. Assign this list to the variable z_winners. winners = ['Alice Munro', 'Alvin E. Roth', 'Kazuo Ishiguro', 'Malala Yousafzai', 'Rainer Weiss', 'Youyou Tu'] z_winners = winners z_winners.reverse() print(z_winners)
class Node: def __init__(self, value, next_=None): self.value = value self.next = next_ class Stack: def __init__(self, top=None): self.top = top def push(self, value): self.top = Node(value, self.top) def pop(self): if self.top: ret = self.top.value self.top = self.top.next return ret return def peek(self): if self.top: return self.top.value return def is_empty(self): if not self.top: return self.top is None class Queue: def __init__(self, front=None): self.front = front self.back = None def enqueue(self, value=None): if self.front is None: self.front = self.back = None(value) else: self.back.next = None(value) def dequeue(self): if self.front is None: return 'Queue is empty' ret = self.front.value self.front = self.front.next return ret class Pseudo_queue: """This class is a queue """ def __init__(self, front, tail): self.front = front self.tail = tail def enqueue(self, value=None): if (self.front.top == None) and (self.tail.top == None): self.front.push(value) return self.front.top.value if (self.front.top == None) and self.tail.top: while self.tail.top: self.front.push(self.tail.pop()) self.tail.push(value) return self.tail.top.value self.tail.push(value) return self.tail.top.value def dequeue(self): if (self.front.top == None) and (self.tail.top == None): return 'this queue is empty buddy' if (self.front.top == None) and self.tail.top: while self.tail.top: self.front.push(self.tail.pop()) self.front.pop() return self.front.pop()
class Vector: #exercise 01 def __init__(self,inputlist): self._vector = [] _vector = inputlist #exercise 02 def __str__(self): return "<" + str(self._vector).strip("[]") + ">" #exercise 03 def dim(self): return len(self._vector) #exercise 04 def get(self,index): return self._vector[index] def set(self,index,value): self._vector[index] = value def scalar_product(self, scalar): return [scalar * x for x in self._vector] #exercise 05 def add(self, other_vector): if not isinstance(other_vector) == True and type(other_vector) == Vector: raise TypeError elif not self.dim() == other_vector.dim(): raise ValueError else: return self.scalar_product(other_vector) #exercise 06 def equals(self,other_vector): if not self.dim() == other_vector.dim(): return False elif self == other_vector: return True else: for i in range(self.dim()): if self._vector[i] != other_vector._vector[i]: return False else: return True
s = 0 cont = 0 for c in range(1, 501, 2): if c % 3 == 0: cont += 1 s += c print('A soma ente todos os {} ímpares múltiplos de 3 entre 1 e 500 é {}.'.format(cont, s))
# Protein sequence given seq = "MPISEPTFFEIF" # Split the sequence into its component amino acids seq_list = list(seq) # Use a set to establish the unique amino acids unique_amino_acids = set(seq_list) # Print out the unique amino acids print(unique_amino_acids)
DEPTH = 16 # the number of filters of the first conv layer of the encoder of the UNet # Training hyperparameters BATCHSIZE = 16 EPOCHS = 100 OPTIMIZER = "adam"
# # @lc app=leetcode id=160 lang=python # # [160] Intersection of Two Linked Lists # # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None # 参考:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/solution/tu-jie-xiang-jiao-lian-biao-by-user7208t/ class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ pointA = headA pointB = headB while pointA != pointB: pointA = pointA.next if pointA is not None else headB pointB = pointB.next if pointB is not None else headA return pointA
string=input("Enter a string:") length=len(string) mid=length//2 rev=-1 for a in range(mid): if string[a]==string[rev]: a+=1 rev=-1 else: print(string,"is a palindrome") break else: print(string,"is not a palindrome")
""" Given two arrays A and B of equal size, the advantage of A with respect to B is the number of indices i for which A[i] > B[i]. Return any permutation of A that maximizes its advantage with respect to B. Example 1: Input: A = [2,7,11,15], B = [1,10,4,11] Output: [2,11,7,15] IDEA: Only relative order does matter, so one can apply greedy approach here Sort both arrays, and find the """ class Solution870: pass
""" Problem 10: The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.Find the sum of all the primes below two million. """ sum = 0 size = 2000000 slots = [True for i in range(size)] slots[0] = False slots[1] = False for stride in range(2, size // 2): pos = stride while pos < size - stride: pos += stride slots[pos] = False for idx, pr in enumerate(slots): if pr: sum += idx print('answer:', sum)
# Argus was charged with guarding Io, which is not an ordinary cow. Io is quite an explorer, and she wanders off rather frequently, making Argus' life stressful. So the cowherd decided to construct an enclosed pasture for Io. # There are nnn trees growing along the river, where Argus tends Io. For this problem, the river can be viewed as the OXOXOX axis of the Cartesian coordinate system, and the nnn trees as points with the yyy-coordinate equal 000. There is also another tree growing in the point (0,1)(0, 1)(0,1). # Argus will tie a rope around three of the trees, creating a triangular pasture. Its exact shape doesn't matter to Io, but its area is crucial to her. There may be many ways for Argus to arrange the fence, but only the ones which result in different areas of the pasture are interesting for Io. Calculate the number of different areas that her pasture may have. Note that the pasture must have nonzero area. t = int(input()) for i in range(t): n = int(input()) xs = list(map(int, input().split()))
''' Compute a digest message ''' def answer(digest): ''' solve for m[1] ''' message = [] for i, v in enumerate(digest): pv = message[i - 1] if i > 0 else 0 m = 0.1 a = 0 while m != int(m): m = ((256 * a) + (v ^ pv)) / 129.0 a += 1 m = int(m) message.append(m) return message
""" Obkey package informations. This file is a part of Openbox Key Editor Code under GPL (originally MIT) from version 1.3 - 2018. See Licenses information in ../obkey . """ MAJOR = 1 MINOR = 3 PATCH = 2 __version__ = "{0}.{1}.{2}".format(MAJOR, MINOR, PATCH) __description__ = 'Openbox Key Editor' __long_description__ = """ A keybinding editor for OpenBox, it includes launchers and window management keys. It allows to: * can check almost all keybinds in one second. * add new keybinds, the default key associated will be 'a' and no action will be associated; * add new child keybinds; * setup existing keybinds : * add/remove/sort/setup actions in the actions list; * change the keybind by clicking on the item in the list; * duplicate existing keybinds; * remove keybinds. The current drawbacks : * XML inculsion is not managed. If you want to edit many files, then you shall open them with `obkey <config file>.xml`; * `if` conditionnal tag is not supported (but did you knew it exists). """
'''程序的状态码''' OK = 0 class LogicErr(Exception): code = None data = None def __init__(self,data=None): self.data = data or self.__class__.__name__ # 如果 data 为 None, 使用类的名字作为 data 值 def gen_logic_err(name, code): '''生成一个新的 LogicErr 的子类 (LogicErr 的工厂函数)''' return type(name, (LogicErr,), {'code': code}) SmsErr = gen_logic_err('SmsErr', 1000) # 短信发送失败 VcodeErr = gen_logic_err('VcodeErr', 1001) # 验证码错误 LoginRequired = gen_logic_err('LoginRequired', 1002) # 用户未登录 UserFormErr = gen_logic_err('UserFormErr', 1003) # 用户表单数据错误 ProfileFormErr = gen_logic_err('ProfileFormErr', 1004) # 用户资料表单错误 RepeatSwipeErr = gen_logic_err('RepeatSwipeErr', 1005) # 重复滑动的错误 AreadyFriends = gen_logic_err('AreadyFriends',1006) # 重复好友 RewindLimited = gen_logic_err('RewindLimited',1007) #当天反悔次数达到上线 RewindTimeout = gen_logic_err('RewindTimeout',1008) #反悔超时 PermRequired = gen_logic_err('PermRequired',1009) #缺少某种权限
''' http://pythontutor.ru/lessons/ifelse/problems/bishop_move/ Шахматный слон ходит по диагонали. Даны две различные клетки шахматной доски, определите, может ли слон попасть с первой клетки на вторую одним ходом. ''' a_x = int(input()) a_y = int(input()) b_x = int(input()) b_y = int(input()) if abs(a_x - b_x) == abs(a_y - b_y): print('YES') else: print('NO')
# Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre a sua média. nome = str(input("Digite o nome do(a) aluno(a): ")) not1 = float(input("Digite a 1ª nota de {}: ".format(nome))) not2 = float(input("Digite a 2ª nota de {}: ".format(nome))) media = (not1 + not2) / 2 print("Já que {} tirou {} e {}, sua média é {:.2f}.".format(nome, not1, not2, media))
# October 27th, 2021 # INFOTC 4320 # Josh Block # Challenge: Anagram Alogrithm and Big-O # References: https://bradfieldcs.com/algos/analysis/an-anagram-detection-example/ print("===Anagram Dector===") print("This program determines if two words are anagrams of each other\n") first_word = input("Please enter first word: ") second_word = input("Please enter second word: ") ##def dector(first_word,second_word): ## if len(first_word) != len(second_word): ## return True ## ## first_word = sorted(first_word) ## second_word = sorted(second_word) ## ## if first_word != second_word: ## return False ## ## return True ## pass def dector(first_word, second_word): return sorted(first_word) == sorted(second_word) print(dector(first_word,second_word))
a=int(input()) b=int(input()) c=int(input()) if(a>b and a>c): print("number 1 is greatest") elif(b>a and b>c): print("number 2 is greatest") else: print("number 3 is greatest")
# x_2_6 # # ヒントを参考に「a」「b」「c」「d」がそれぞれどんな値となるかを予想してください # ヒント print(type('桃太郎')) print(type(10)) print(type(12.3)) a = type('777') # => str b = type(10 + 3.5) # => float c = type(14 / 7) # => float d = type(10_000_000) # => int # print(a) # print(b) # print(c) # print(d)
def main(): # Create and print a list named fruit. fruit_list = ["pear", "banana", "apple", "mango"] print(f"original: {fruit_list}") fruit_list.reverse() print(f"Reverse {fruit_list}") fruit_list.append("Orange") print(f"Append Orange {fruit_list}") pos = fruit_list.index("apple") fruit_list.insert(pos, "cherry") print(f"insert cherry: {fruit_list}") fruit_list.remove("banana") print(f"Remove Banana: {fruit_list}") last = fruit_list.pop() print(f"pop {last}: {fruit_list}") fruit_list.sort() print(f"Sorted: {fruit_list}") fruit_list.clear() print(f"cleared: {fruit_list}") if __name__ == "__main__": main()
__author__ = "Eric Dose :: New Mexico Mira Project, Albuquerque" # PyInstaller (__init__.py file should be in place as peer to .py file to run): # in Windows Command Prompt (E. Dose dev PC): # cd c:\Dev\prepoint\prepoint # C:\Programs\Miniconda\Scripts\pyinstaller app.spec
""" Spring. Click, drag, and release the horizontal bar to start the spring. """ # Spring drawing constants for top bar springHeight = 32 # Height left = 0 # Left position right = 0 # Right position max = 200 # Maximum Y value min = 100 # Minimum Y value over = False # If mouse over move = False # If mouse down and over # Spring simulation constants M = 0.8 # Mass K = 0.2 # Spring constant D = 0.92 # Damping R = 150 # Rest position # Spring simulation variables ps = R # Position v = 0.0 # Velocity a = 0 # Acceleration f = 0 # Force def setup(): size(640, 360) rectMode(CORNERS) noStroke() left = width / 2 - 100 right = width / 2 + 100 def draw(): background(102) updateSpring() drawSpring() def drawSpring(): # Draw base fill(0.2) baseWidth = 0.5 * ps + -8 rect(width / 2 - baseWidth, ps + springHeight, width / 2 + baseWidth, height) # Set color and draw top bar. if over or move: fill(255) else: fill(204) rect(left, ps, right, ps + springHeight) def updateSpring(): # Update the spring position. if not move: f = -K * (ps - R) # f=-ky a = f / M # Set the acceleration. f=ma == a=f/m v = D * (v + a) # Set the velocity. ps = ps + v # Updated position if abs(v) < 0.1: v = 0.0 # Test if mouse is over the top bar over = left < mouseX < right and ps < mouseY < ps + springHeight # Set and constrain the position of top bar. if move: ps = mouseY - springHeight / 2 ps = constrain(ps, min, max) def mousePressed(): if over: move = True def mouseReleased(): move = False
# 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 to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # NOTE: This class is auto generated by the jdcloud code generator program. class MediaClip(object): def __init__(self, mediaId=None, mediaIn=None, mediaOut=None, timelineIn=None, timelineOut=None, operations=None): """ :param mediaId: (Optional) 素材ID,此处,必须为视频点播媒资的视频ID :param mediaIn: (Optional) 素材片段在媒资中的入点 :param mediaOut: (Optional) 素材片段在媒资中的出点 :param timelineIn: (Optional) 素材片段在合成时间线中的入点 :param timelineOut: (Optional) 素材片段在合成时间线中的出点 :param operations: (Optional) """ self.mediaId = mediaId self.mediaIn = mediaIn self.mediaOut = mediaOut self.timelineIn = timelineIn self.timelineOut = timelineOut self.operations = operations
""" Space : O(1) Time : O(n**2) """ class Solution: def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool: if t == 0 and len(nums) == len(set(nums)): return False for i, cur_val in enumerate(nums): for j in range(i+1, min(i+k+1, len(nums))): if abs(cur_val - nums[j]) <= t: return True return False
def make_interval(depth, depth_integer_multiplier, num, step_num, start_val): all_groups_str = "[\n" for n in range(num): all_groups_str += "\t[" for d in range(depth): val = str(start_val * pow(depth_integer_multiplier, d)) if d == depth - 1: if n == num - 1: all_groups_str += "%s]\n" % val else: all_groups_str += "%s],\n" % val else: all_groups_str += "%s, " % val start_val += step_num all_groups_str += "]\n" return all_groups_str print(make_interval(12, 2, 10, 10, 10))
class Config: __instance = None @staticmethod def get_instance(): """ Static access method. """ if Config.__instance == None: Config() return Config.__instance def __init__(self): if Config.__instance != None: raise Exception("This class can't be created, use Config.getInstance() instead") else: Config.__instance = self self.db_driver="sqlite", self.sqlite_file = "database.sqlite" s = Config() print (s) s = Config.get_instance() print (s, id(s)) s = Config.get_instance() print (s, id(s))
class AFGR: @staticmethod def af_to_gr(dict_af): dict_swap = {} for keys in dict_af: dict_swap[keys] = [] for list in dict_af[keys]: dict_swap[keys].insert(len(dict_swap[keys]), list[0]) dict_swap[keys].insert(len(dict_swap[keys]), list[1]) return dict_swap @staticmethod def gr_to_af(dict_gr, estados_aceitacao): dict_swap = {} # Adicionando estado final dict_swap['F'] = [] estados_aceitacao.insert(len(estados_aceitacao), 'F') for keys in dict_gr: dict_swap[keys] = [] qtd_elementos = len(dict_gr[keys]) contador = 0 while contador < qtd_elementos: if contador+1 < len(dict_gr[keys]): if dict_gr[keys][contador+1].istitle(): dict_swap[keys].insert(len(dict_swap[keys]), [dict_gr[keys][contador], dict_gr[keys][contador+1]]) contador += 2 else: if AFGR.verifica_estado_final(dict_swap, dict_gr, keys, contador): dict_swap[keys].insert(len(dict_swap[keys]), [dict_gr[keys][contador], 'F']) contador += 1 else: if AFGR.verifica_estado_final(dict_swap, dict_gr, keys, contador): dict_swap[keys].insert(len(dict_swap[keys]), [dict_gr[keys][contador], 'F']) contador += 1 # Caso o ultimo elemento seja um nao terminal (NAO FINALIZADO TA REPETIDO O S) AFGR.verifica_estado_final(dict_swap, dict_gr, keys, contador-2) return dict_swap # Verifica os estados finais, tem que ver uma forma melhor no futuro @staticmethod def verifica_estado_final(dict_swap, dict_gr, keys, contador): for estados in dict_swap[keys]: if estados[0] == dict_gr[keys][contador] and estados[1] != 'F': estados[1] = 'F' return False return True
animals = ["Gully", "Rhubarb", "Zephyr", "Henry"] for index, animal in enumerate(animals): # if index % 2 == 0: # continue # print(animal) print(f"{index+1}.\t{animal}")
class FittingAndAccessoryCalculationType(Enum, IComparable, IFormattable, IConvertible): """ Enum of fitting and accessory pressure drop calculation type. enum FittingAndAccessoryCalculationType,values: CalculateDefaultSettings (2),CalculatePressureDrop (1),Undefined (0),ValidateCurrentSettings (4) """ def __eq__(self, *args): """ x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """ pass def __format__(self, *args): """ __format__(formattable: IFormattable,format: str) -> str """ pass def __ge__(self, *args): pass def __gt__(self, *args): pass def __init__(self, *args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __le__(self, *args): pass def __lt__(self, *args): pass def __ne__(self, *args): pass def __reduce_ex__(self, *args): pass def __str__(self, *args): pass CalculateDefaultSettings = None CalculatePressureDrop = None Undefined = None ValidateCurrentSettings = None value__ = None
""" 1232. 缀点成线 在一个 XY 坐标系中有一些点,我们用数组 coordinates 来分别记录它们的坐标, 其中 coordinates[i] = [x, y] 表示横坐标为 x、纵坐标为 y 的点。 请你来判断,这些点是否在该坐标系中属于同一条直线上,是则返回 true,否则请返回 false。 """ class XYCheck: def __init__(self, coordinates): self.a = self.b = 0 x1, y1 = coordinates[0] x2, y2 = coordinates[1] self.a = float(y1 - y2)/float(x1 - x2) self.b = float(y1 - x1 * self.a) def check(self, x, y): return self.a * x + self.b == y def checkStraightLine(coordinates): check = XYCheck(coordinates) for x, y in coordinates[2:]: if check.check(x, y) == False: return False return True def checkStraightLine2(coordinates): x1, y1 = coordinates[0] x2, y2 = coordinates[1] A = y2 - y1 B = -(x2 - x1) for x, y in coordinates[2:]: if A * (x - x1) + B * (y - y1) != 0: return False return True print(checkStraightLine([[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]])) #true print(checkStraightLine2([[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]])) #true print(checkStraightLine([[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]])) #false print(checkStraightLine2([[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]])) #false """ https://leetcode-cn.com/problems/check-if-it-is-a-straight-line/solution/da-qia-by-shun-zi-6-6s1g/ 将原列表的点移动相同的距离,使其经过原点, 利用方程式 A * x + B * y = 0, 得出常数A和B, 带入后续的点进行计算, 一旦发现结果不为0, 直接返回结果 """ print("========NEXT===斜率计算=======") def xielv(coordinates): x1, y1 = coordinates[0] x2, y2 = coordinates[1] for x, y in coordinates[2:]: if (x1 - x2) * (y2 - y) != (x2 - x) * (y1 - y2): return False return True print(xielv([[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]])) #true print(xielv([[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]])) #false
## Python Crash Course # Exercise 6.4: Glossary#2: # Now that you know how to loop through a dictionary, clean up the code from Exercise 6-3 (page 102) # by replacing your series of print statements with a loop that runs through the dictionary’s keys and values. # When you’re sure that your loop works, add five more Python terms to your glossary. # When you run your program again, these new words and meanings should automatically be included in the output. # def exercise_6_4(): print("\n") print("Following are key-value pairs stored in a dictionary..\n") pythonChapters = { 'HelloWorld':"Introduction to Python. First program.", 'Lists':"Collection of items in particular order.", 'Variables':"Different kind of data we can work with.", 'Dictionary':"Limitless type to store information.", 'Games In Python':"I am excited to develop my own game using Python!" } for chapter in pythonChapters.keys(): print(chapter.title(), ":", pythonChapters[chapter]); print("\n") if __name__ == '__main__': exercise_6_4()
# Given an integer array arr, count element x such that x + 1 is also in arr. # If there're duplicates in arr, count them seperately. # Example 1: # Input: arr = [1,2,3] # Output: 2 # Explanation: 1 and 2 are counted cause 2 and 3 are in arr. # Example 2: # Input: arr = [1,1,3,3,5,5,7,7] # Output: 0 # Explanation: No numbers are counted, cause there's no 2, 4, 6, or 8 in arr. # Example 3: # Input: arr = [1,3,2,3,5,0] # Output: 3 # Explanation: 0, 1 and 2 are counted cause 1, 2 and 3 are in arr. # Example 4: # Input: arr = [1,1,2,2] # Output: 2 # Explanation: Two 1s are counted cause 2 is in arr. def count_elements(arr): d = {} for i in arr: d[i] = 1 count = 0 for num in arr: num_plus = num + 1 if num_plus in d: count += 1 return count print(count_elements([1,1,2,2]))
ES_HOST = 'localhost:9200' ES_INDEX = 'pending-uberon' ES_DOC_TYPE = 'anatomy' API_PREFIX = 'uberon' API_VERSION = ''
class Solution: def solve(self, nums): integersDict = {} for i in range(len(nums)): try: integersDict[nums[i]] += 1 except: integersDict[nums[i]] = 1 for integer in integersDict: if integersDict[integer] != 3: return integer return nums[0]
class CharacterRaceList(object): DEVA = 'DEVA' DRAGONBORN = 'DRAGONBORN' DWARF = 'DWARF' ELADRIN = 'ELADRIN' ELF = 'ELF' GITHZERAI = 'GITHZERAI' GNOME = 'GNOME' GOLIATH = 'GOLIATH' HALFELF = 'HALFELF' HALFLING = 'HALFLING' HALFORC = 'HALFORC' HUMAN = 'HUMAN' MINOTAUR = 'MINOTAUR' SHARDMIND = 'SHARDMIND' SHIFTER = 'SHIFTER' TIEFLING = 'TIEFLING' WILDEN = 'WILDEN' class CharacterClassList(object): ARDENT = 'ARDENT' AVENGER = 'AVENGER' BARBARIAN = 'BARBARIAN' BARD = 'BARD' BATTLEMIND = 'BATTLEMIND' CLERIC = 'CLERIC' DRUID = 'DRUID' FIGHTER = 'FIGHTER' INVOKER = 'INVOKER' MONK = 'MONK' PALADIN = 'PALADIN' PSION = 'PSION' RANGER = 'RANGER' ROGUE = 'ROGUE' RUNEPRIEST = 'RUNEPRIEST' SEEKER = 'SEEKER' SHAMAN = 'SHAMAN' SORCERER = 'SORCERER' WARDEN = 'WARDEN' WARLOCK = 'WARLOCK' WARLORD = 'WARLORD' WIZARD = 'WIZARD' class CharacterRoleList(object): CONTROLLER = 'CONTROLLER' DEFENDER = 'DEFENDER' LEADER = 'LEADER' STRIKER = 'STRIKER' class AlignmentList(object): GOOD = 'GOOD' LAWFUL_GOOD = 'LAWFUL_GOOD' UNALIGNED = 'UNALIGNED' EVIL = 'EVIL' CHAOTIC_EVIL = 'CHAOTIC_EVIL' class DeitiesList(object): ASMODEUS = AlignmentList.EVIL AVANDRA = AlignmentList.GOOD BAHAMUT = AlignmentList.LAWFUL_GOOD BANE = AlignmentList.EVIL CORELLON = AlignmentList.UNALIGNED ERATHIS = AlignmentList.UNALIGNED GRUUMSH = AlignmentList.CHAOTIC_EVIL IOUN = AlignmentList.UNALIGNED KORD = AlignmentList.UNALIGNED LOLTH = AlignmentList.CHAOTIC_EVIL MELORA = AlignmentList.UNALIGNED MORADIN = AlignmentList.LAWFUL_GOOD PELOR = AlignmentList.GOOD SEHANINE = AlignmentList.UNALIGNED THE_RAVEN_QUEEN = AlignmentList.UNALIGNED TIAMAT = AlignmentList.EVIL TOROG = AlignmentList.EVIL VECNA = AlignmentList.EVIL ZEHIR = AlignmentList.EVIL class ScriptList(object): COMMON = 'COMMON' RELLANIC = 'RELLANIC' IOKHARIC = 'IOKHARIC' DAVEK = 'DAVEK' BARAZHAD = 'BARAZHAD' SUPERNAL = 'SUPERNAL' class LanguageList(object): COMMON = ScriptList.COMMON DEEP_SPEECH = ScriptList.RELLANIC DRACONIC = ScriptList.IOKHARIC DWARVEN = ScriptList.DAVEK ELVEN = ScriptList.RELLANIC GIANT = ScriptList.DAVEK GOBLIN = ScriptList.COMMON PRIMORDIAL = ScriptList.BARAZHAD SUPERNA = ScriptList.SUPERNAL ABYSSAL = ScriptList.BARAZHAD
# 给定两个数组,编写一个函数来计算它们的交集。 class Solution: def intersect(self, nums1: list, nums2: list) -> list: inter = set(nums1) & set(nums2) print(inter) l = [] for i in inter: l += [i] * min(nums1.count(i), nums2.count(i)) print(l) return l nums1 = [1, 2, 2, 1] nums2 = [2, 2] li = Solution().intersect(nums1, nums2) print(li)
print('\033[32m{:=^60}'.format('\033[36m Dividindo valores em várias listas \033[32m')) lista = [] par = [] impar = [] while True: lista.append(int(input('\033[36mDigite um número: '))) resp = str(input('\033[32mQuer continuar? [S/N] ')).strip()[0] if resp in 'Nn': break for c in range(len(lista)): if lista[c] % 2 == 0: par.append(lista[c]) else: impar.append(lista[c]) print('\033[36m-\033[32m='*40) print(f'\033[34mA lista completa é {lista}') print(f'A lista de pares é {par}') print(f'A lista de impares é {impar}')
# encoding:utf-8 # 401 错误 class UnauthorizedError(Exception): pass # 400 错误 class BadRequestError(Exception): pass class MediaTypeError(Exception): pass # 父异常 class RestfulException(Exception): pass
def inner_stroke(im): pass def outer_stroke(im): pass
a, b, c = map(int, input().split()) h, l = map(int, input().split()) if a <= h and b <= l: print("S") elif a <= h and c <= l: print("S") elif b <= h and a <= l: print("S") elif b <= h and c <= l: print("S") elif c <= h and a <= l: print("S") elif c <= h and b <= l: print("S") else: print("N")
def funcao1 (a, b): mult= a * b return mult def funcao2 (a, b): divi = a / b return divi multiplicacao = funcao1(3, 2) valor = funcao2(multiplicacao, 2) print(multiplicacao) print(int(valor))
# Plotting distributions pairwise (1) # Print the first 5 rows of the DataFrame print(auto.head()) # Plot the pairwise joint distributions from the DataFrame sns.pairplot(auto) # Display the plot plt.show()
def log_text(file_path, log): if not log.endswith('\n'): log += '\n' print(log) with open(file_path, 'a') as f: f.write(log) def log_args(file_path, args): log = f"Args: {args}\n" log_text(file_path, log) def log_train_epoch(file_path, epoch, train_loss, train_accuracy): log = f"epoch: {epoch}, Train loss: {train_loss}, Train accuracy: {train_accuracy}\n" log_text(file_path, log) def log_val_epoch(file_path, epoch, val_loss, val_acc): log = f"epoch: {epoch}, Val loss: {val_loss}, Val accuracy: {val_acc}\n" log_text(file_path, log) def log_test_metrics(file_path, precision, recall, f1, accuracy, cm): log = (f"Precision: {precision}\n" f"Recall: {recall}\n" f"F1 score: {f1}\n" f"Accuracy: {accuracy}\n" f"Confusion Matrix:\n{cm}\n") log_text(file_path, log) def log_target_test_metrics(file_path, target, precision, recall, f1): log = (f"{target}:\n" f"\tPrecision: {round(precision, 4)}\n" f"\tRecall: {round(recall, 4)}\n" f"\tF1 score: {round(f1, 4)}\n") log_text(file_path, log)
class Node: def __init__(self, value, next): self.value = value self.next = next class LinkedList: def __init__(self): self.head = None def add(self, value): self.head = Node(value, self.head) def remove(self): to_remove = self.head self.head = self.head.next to_remove.next = None def reverse(self): head = current = self.head prev = next = None while current: next = current.next current.next = prev prev = current current = next self.head = prev self.print() def print(self): current = self.head while current: print(current.value, end=" ") print("->", end = " ") if not current.next: print(current.next, end ="\n") current = current.next if __name__ == "__main__": ll = LinkedList() for i in range(10, 1, -1): ll.add(i) ll.print() ll.reverse()
lista = [] dicio = {} idadeTot = 0 cont = 0 contMulher = 0 while True: dicio['nome'] = str(input('Digite o nome: ')) while True: dicio['sexo'] = str(input('Digite o sexo: [M/F] ')).upper()[0] if dicio['sexo'] in 'MF': break else: dicio['sexo'] = str(input('Digite apenas M ou F: ')).upper()[0] dicio['idade'] = int(input('Digite a idade: ')) if dicio['sexo'] == 'F': contMulher += 1 cont += 1 idadeTot += dicio['idade'] lista.append(dicio.copy()) oper = str(input('Deseja continuar? [S/N] ')).strip().upper()[0] if oper not in 'SN': oper = str(input('Apenas S ou N, deseja continuar? ')).upper()[0] if oper == 'N': break mediaIdade = idadeTot / cont print('-=' * 30) print(f'O grupo tem um total de {cont} pessoas.') print(f'A média de idade do grupo é de {mediaIdade:.2f} anos.') print(f'A quantidade de mulheres no grupo é de {contMulher}.') for p in lista: if p['sexo'] in 'Ff': print(f'Nome: {p["nome"]}, Idade: {p["idade"]}.') print('A lista de pessoas que estão acima da média são: ') for p in lista: if p['idade'] > mediaIdade: print(f'Nome: {p["nome"]}, Sexo: {p["sexo"]}, Idade: {p["idade"]}.') print('-=' * 30)
# A. Way Too Long Words # ------------------------------- # time limit per test1 second # memory limit per test 256 megabytes # input :standard input # output :standard output # Sometimes some words like "localization" or "internationalization" are so long that writing # them many times in one text is quite tiresome. # Let's consider a word too long, if its length is strictly more than 10 characters. # All too long words should be replaced with a special abbreviation. # This abbreviation is made like this: we write down the first and the last letter of a word and between # them we write the number of letters between the first and the last letters. # That number is in decimal system and doesn't contain any leading zeroes. # Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n". # You are suggested to automatize the process of changing the words with abbreviations. # At that all too long words should be replaced by the abbreviation and the words that are not # too long should not undergo any changes. # Input # The first line contains an integer n (1 ≤ n ≤ 100). Each of the following n lines contains one word. # All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters. # Output # Print n lines. The i-th line should contain the result of replacing of the i-th word from the input data. # Examples # input # 4 # word # localization # internationalization # pneumonoultramicroscopicsilicovolcanoconiosis # output # word # l10n # i18n # p43s #solution to above problem t=int(input()) for i in range(t): s=input() if(len(s)<=10): print(s) else: print(s[0]+str(len(s)-2)+s[-1])
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Advent of Code 2020 Day 13, Part 1 """ def main(): with open('in.txt') as f: lines = f.readlines() arrival = int(lines[0].strip()) bus_ids = [] for n in lines[1].strip().split(','): if n == 'x': continue else: bus_ids.append(int(n)) waiting_time = [(n - arrival % n, n) for n in bus_ids] min_time = waiting_time[0][0] first_bus = waiting_time[0][1] for minutes, bus in waiting_time[1:]: if minutes < min_time: min_time = minutes first_bus = bus print(min_time * first_bus) if __name__ == '__main__': main()
#!/usr/bin/env python # # ---------------------------------------------------------------------- # # Brad T. Aagaard, U.S. Geological Survey # Charles A. Williams, GNS Science # Matthew G. Knepley, University of Chicago # # This code was developed as part of the Computational Infrastructure # for Geodynamics (http://geodynamics.org). # # Copyright (c) 2010-2017 University of California, Davis # # See COPYING for license information. # # ---------------------------------------------------------------------- # ## @file pylith/problems/__init__.py ## ## @brief Python PyLith crustal dynamics problems module initialization __all__ = ['EqDeformation', 'Explicit', 'Implicit', 'Problem', 'Solver', 'SolverLinear', 'SolverNonlinear', 'TimeDependent', 'TimeStep', 'TimeStepUniform', 'TimeStepUser', 'TimeStepAdapt', 'ProgressMonitor', ] # End of file
t = int(input()) while (t!=0): a,b,c = map(int,input().split()) if (a+b+c == 180): print('YES') else: print('NO') t-=1
# cool.py def cool_func(): print('cool_func(): Super Cool!') print('__name__:', __name__) if __name__ == '__main__': print('Call it locally') cool_func()
"""Faça um programa que tenha uma função notas() que pode receber várias notas de alunos e vai retornar um dicionário com as seguintes informações: – Quantidade de notas - A maior nota – A menor nota – A média da turma – A situação (opcional)""" def notas(* num, s=False): """ -> Função para coletar notas dos alunos e retornar informações gerais e a situação da turma. :param num: Notas da turma :param s: Situação (Boa, Razoável ou Ruim) :return: dicionário com informações sobre a turma """ soma = sum(num) qtd = len(num) maior = max(num) menor = min(num) media = soma / qtd if media >= 6: sit = 'Boa' elif media >= 5: sit = 'Razoável' else: sit = 'Ruim' total = {'Quantidade de notas': qtd, 'Maior nota': maior, 'Menor nota': menor, 'Média': media} if s: total['Situação'] = sit return total print(notas(2, 3, 5, 4, 1, 3, s=True)) print(notas(10, 7, 8, 10, s=True)) print(notas(4, 6, 7, 5, 6.5, 7, 5)) help(notas)
""" https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/ Given an integer array arr. You have to sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order. Return the sorted array. Example 1: Input: arr = [0,1,2,3,4,5,6,7,8] Output: [0,1,2,4,8,3,5,6,7] Explantion: [0] is the only integer with 0 bits. [1,2,4,8] all have 1 bit. [3,5,6] have 2 bits. [7] has 3 bits. The sorted array by bits is [0,1,2,4,8,3,5,6,7] Example 2: Input: arr = [1024,512,256,128,64,32,16,8,4,2,1] Output: [1,2,4,8,16,32,64,128,256,512,1024] Explantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order. Example 3: Input: arr = [10000,10000] Output: [10000,10000] Example 4: Input: arr = [2,3,5,7,11,13,17,19] Output: [2,3,5,17,7,11,13,19] Example 5: Input: arr = [10,100,1000,10000] Output: [10,100,10000,1000] Constraints: 1 <= arr.length <= 500 0 <= arr[i] <= 10^4 """ # time complexity: O(nlogn), space complexity: O(n) class Solution: def sortByBits(self, arr: List[int]) -> List[int]: scale = 1e5 for i in range(len(arr)): arr[i] = [bin(arr[i]).count('1')*scale+arr[i],arr[i]] arr.sort(key=lambda x:x[0]) return list(num[1] for num in arr)
class FieldDoesNotExist(Exception): def __init__(self, **kwargs): super().__init__(f"{self.__class__.__name__}: {kwargs}") self.kwargs = kwargs
""" Queue https://algorithm.yuanbin.me/zh-hans/basics_data_structure/queue.html """
# # PySNMP MIB module Unisphere-Products-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Products-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:26:09 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) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") iso, NotificationType, Counter64, Gauge32, ModuleIdentity, Counter32, IpAddress, Integer32, Unsigned32, TimeTicks, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "NotificationType", "Counter64", "Gauge32", "ModuleIdentity", "Counter32", "IpAddress", "Integer32", "Unsigned32", "TimeTicks", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "Bits") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") unisphere, = mibBuilder.importSymbols("Unisphere-SMI", "unisphere") usProducts = ModuleIdentity((1, 3, 6, 1, 4, 1, 4874, 1)) usProducts.setRevisions(('2001-12-07 15:36', '2001-10-15 18:29', '2001-03-01 15:27', '2000-05-24 00:00', '1999-12-13 19:36', '1999-11-16 00:00', '1999-09-28 00:00',)) if mibBuilder.loadTexts: usProducts.setLastUpdated('200112071536Z') if mibBuilder.loadTexts: usProducts.setOrganization('Unisphere Networks, Inc.') productFamilies = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 1, 1)) unisphereProductFamilies = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 1, 1, 1)) usErx = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 1, 1, 1, 1)) usEdgeRoutingSwitch1400 = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 1, 1, 1, 1, 1)) usEdgeRoutingSwitch700 = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 1, 1, 1, 1, 2)) usEdgeRoutingSwitch1440 = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 1, 1, 1, 1, 3)) usEdgeRoutingSwitch705 = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 1, 1, 1, 1, 4)) usMrx = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 1, 1, 1, 2)) usMrxRoutingSwitch16000 = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 1, 1, 1, 2, 1)) usMrxRoutingSwitch32000 = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 1, 1, 1, 2, 2)) usSmx = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 1, 1, 1, 3)) usServiceMediationSwitch2100 = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 1, 1, 1, 3, 1)) usSrx = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 1, 1, 1, 4)) usServiceReadySwitch3000 = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 1, 1, 1, 4, 1)) usUmc = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 1, 1, 1, 5)) usUmcSystemManagement = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 1, 1, 1, 5, 1)) oemProductFamilies = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 1, 1, 2)) marconiProductFamilies = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 1, 1, 2, 1)) usSsx = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 1, 1, 2, 1, 1)) usSsx1400 = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 1, 1, 2, 1, 1, 1)) usSsx700 = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 1, 1, 2, 1, 1, 2)) usSsx1440 = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 1, 1, 2, 1, 1, 3)) mibBuilder.exportSymbols("Unisphere-Products-MIB", usSsx1400=usSsx1400, usErx=usErx, usServiceMediationSwitch2100=usServiceMediationSwitch2100, oemProductFamilies=oemProductFamilies, usServiceReadySwitch3000=usServiceReadySwitch3000, usUmc=usUmc, usSmx=usSmx, usSsx1440=usSsx1440, unisphereProductFamilies=unisphereProductFamilies, usEdgeRoutingSwitch705=usEdgeRoutingSwitch705, usMrxRoutingSwitch16000=usMrxRoutingSwitch16000, usSsx=usSsx, usProducts=usProducts, usEdgeRoutingSwitch700=usEdgeRoutingSwitch700, usSsx700=usSsx700, usUmcSystemManagement=usUmcSystemManagement, marconiProductFamilies=marconiProductFamilies, productFamilies=productFamilies, usEdgeRoutingSwitch1440=usEdgeRoutingSwitch1440, usMrx=usMrx, usMrxRoutingSwitch32000=usMrxRoutingSwitch32000, usEdgeRoutingSwitch1400=usEdgeRoutingSwitch1400, PYSNMP_MODULE_ID=usProducts, usSrx=usSrx)
''' 从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。假设字符串中只包含'a'~'z的字符。例如,在字 符串"arabcacfr"中,最长的不含重复字符的子字符串是"acfr",长度为4。 ''' class Solution: def lengthOfLongestSubstring(self, s): if len(s) <= 1: return len(s) head, tail = 0, 0 maxLen = 1 while tail+1 < len(s): tail += 1 # 往窗口内添加元素 if s[tail] not in s[head: tail]: # 窗口内没有重复的字符,实时更新窗口最大长度 maxLen = max(maxLen, tail - head + 1) else: # 窗口内有重复字符,移动head直至窗口内不再含重复的元素 while s[tail] in s[head: tail]: head += 1 return maxLen def lengthOfLongestSubdtring1(self, s): if len(s)<=1: return len(s) head, tail=0, 0 maxLen=1 while tail+1<len(s): tail+=1 # 王窗口内添加元素 if s[tail] not in s[head:tail]:# 如果窗口内没有重复的字符,实时更新窗口的元素 maxLen=max(maxLen, tail-head+1) else: # 窗口内有重复字符,移动head直至窗口内不再含重复的元素 while s[tail] in s[head:tail]: head+=1 # 当有重复的数字时首指针会一直相加 return maxLen def lengthOfLongestSubdtring2(self, s): if len(s)<=1: return len(s) head, tail=0, 0 # 双指针 maxLen=1 while tail+1<len(s): tail+=1 if s[tail] not in s[head:tail]: maxLen=max(maxLen, tail-head+1) else: while s[tail] in s[head:tail]: head+=1 return maxLen s=Solution() print(s.lengthOfLongestSubdtring2("yyabcdabjcabceg")) # cdabj
'''8) Elabore um algoritmo que leia 3 valores inteiros (a,b e c) e os coloque em ordem crescente, de modo que em a fique o menor valor, em b o valor intermediário e em c o maior valor. ''' a = int(input("Digite o valor do primeiro valor: ")) b = int(input("Digite o valor do segundo valor: ")) c = int(input("Digite o valor do terceiro valor: ")) print(f"Antes: {a} - {b} - {c}") if a > b: a,b = b,a if a > c: a,c = c,a if b > c: b,c = c,b print(f"Depois: {a} - {b} - {c}")
class Solution(object): def findSubsequences(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ ans = [] def dfs(nums, start, path, ans): if len(path) >= 2: ans.append(tuple(path + [])) for i in range(start, len(nums)): if i != start and nums[i] == nums[i - 1]: continue if path and nums[i] < path[-1]: continue path.append(nums[i]) dfs(nums, i + 1, path, ans) path.pop() dfs(nums, 0, [], ans) return list(set(ans))