content
stringlengths
7
1.05M
# # Solution to Project Euler problem 6 # Copyright (c) Project Nayuki. All rights reserved. # # https://www.nayuki.io/page/project-euler-solutions # https://github.com/nayuki/Project-Euler-solutions # # Computers are fast, so we can implement this solution directly without any clever math. # However for the mathe...
"""Globally defined and used variables for the JWQL query anomaly feature. Variables will be re-defined when anomaly query forms are submitted. Authors ------- - Teagan King Use --- This variables within this module are intended to be directly imported, e.g.: :: from jwql.utils.query_config...
with open("sonar.txt") as sonar: depthstr = sonar.readline() previous = int(depthstr.strip()) increases = 0 for depthstr in sonar.readlines(): depth = int(depthstr.strip()) if depth > previous: increases += 1 previous = depth print(increases)
""" 给你一个长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。   示例: 输入: [1,2,3,4] 输出: [24,12,8,6]   提示:题目数据保证数组之中任意元素的全部前缀元素和后缀(甚至是整个数组)的乘积都在 32 位整数范围内。 说明: 请不要使用除法,且在 O(n) 时间复杂度内完成此题。 进阶: 你可以在常数空间复杂度内完成这个题目吗?( 出于对空间复杂度分析的目的,输出数组不被视为额外空间。) 来源:力扣(LeetCode) 链接:https://leetcode-cn.com...
class Solution: def validPalindrome(self, s: str) -> bool: if s == s[::-1]: return True left, right = 0 , len(s)-1 s = list(s) while left < right: if s[left] != s[right]: s_l = s[left+1:right+1] s_r = s[left:ri...
""" Null object for Telegram bot """ class BotNull: def __init__(self, logger): self.logger = logger def sendMessage(self, chat_id, text): self.logger.info("Skipping Telegram since no configuration was found")
""" Simple Python's Tornado wrapper which provides helpers for creating a new project, writing management commands, service processes, ... """ __version__ = '2.1.2'
""" Container for macros to fix proto files. """ load("@rules_proto//proto:defs.bzl", "proto_library") def format_import_proto_library(name, src, deps): """ Creates a new proto library with corrected imports. This macro exists as a way to build proto files that contain import statements in both Gradle ...
#coding:utf-8 ''' filename:custom_exception.py judge the number of age is even or odd ''' class NegativeAgeException(RuntimeError): def __init__(self,age): super().__init__() self.age = age def enterage(age): if age<0: raise NegativeAgeException('Only *POSITIVE* integers ar...
edad = 19 pago = False if (edad > 18): print ("Es mayor de edad") if pago == True: print ("Es mayor de edad y pagó") else: print ("Es mayor de edad y no pagó") else: print ("Es menor de edad")
def getExtensionObjectFromString(strExtension): try: assetID,tempData=strExtension.split("$") itemVER, tempData=tempData.split("@") itemID,tempData=tempData.split(";") return extensions(assetID,itemVER,itemID,tempData) except: return None class extensions...
# encoding: utf-8 # Copyright 2017 Virgil Dupras # This software is licensed under the "BSD" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.hardcoded.net/licenses/bsd_license def preprocess_paths(paths): if not isinstance(pat...
# 已下单 ORDERED =0 #已付款 PAYED =1 TYPE_ORDER = 0 TYPE_PAYED = 1
number = int(input()) salaperhour = int(input()) valorperhour = float(input()) print("NUMBER = {}".format(number)) print('SALARY = U$ {:.2f}'.format(salaperhour * valorperhour))
# # PySNMP MIB module CISCO-LWAPP-DOT11-CLIENT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-LWAPP-DOT11-CLIENT-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:05:02 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python vers...
''' @jacksontenorio8 Melhore o DESAFIO 061, perguntando perguntando para o usuário se ele quer mostrar mais termos. O programa encerra quando ele disser que quer mostrar 0 termos. ''' print('GERADOR DE PA') print('='*10) primeiro = int(input('Primeiro Termo: ')) razao = int(input('Razão da PA: ')) termo = primeiro i = ...
''' pyleaves/pyleaves/trainers/__init__.py trainers submodule of the pyleaves package contains trainer subclasses for use in pyleaves for assembling and executing full experiments. e.g. data preprocessing -> data loading -> model training -> model testing '''
#Exercício Python 042: Refaça o DESAFIO 035 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado: #- EQUILÁTERO: todos os lados iguais #- ISÓSCELES: dois lados iguais, um diferente #- ESCALENO: todos os lados diferentes a = float(input('1° seguimento: ')) b = float(input('2° seguimento...
# n = int(input()) # for i in range(n): # print("*"*i) # n = int(input()) # i = n # while i >=0: # print("*"*i) # i -= 1 # n = int(input()) # i = 0 # j = n # while i <=n: # print(" "*j+"*"*i) # i += 1 # j -= 1 # n = int(input()) # i = n # j = 0 # while i >=0: # p...
# Space: O(n) # Time: O(n) class RecentCounter: def __init__(self): self.data = [] self.count = 0 def ping(self, t: int) -> int: self.data.append(t) self.count += 1 while self.data[0] < max(0, t - 3000): self.data.pop(0) self.count -= 1 ...
print ("HELLO GUYS WELCOME TO (LEARN-PYTHON) THIS WILL HELP YOU LEARN\n 1.PYTHON\n ") print ("NOTE: IT WILL ONLY PROVIDE BASIC INFORMATION OF THE LANGUAGES.\n") language = input("ENTER THE NAME OF THE LANGUAGE WHICH YOU WANT TO LEARN: " ) print("\033[91m {}\033[00m" .format ("\nSYNTAXES:")) print ("\n1)Variables") pr...
languages = [] languages.append("Java") languages.append("Python") languages.append("C#") languages.append("Ruby") print(languages) numbers = [1, 2, 3] imdb_top_3 = [ "The Shawshank Redemption", "The Godfather", "The Godfather: Part II" ] print(imdb_top_3) empty = [] mixed = [1, True, "Three", [], Non...
""" Client stub for connecting to file operations server. Any Windows client (controller) abstractions should go here. """
class Solution: def reorganizeString(self, S: str) -> str: """Heap. Running time:O(nlogn) where n is the length of S. """ c = collections.Counter(S) heap = [(-v, k) for k, v in c.items()] heapq.heapify(heap) res = '' while heap: v, k = hea...
# Datasets FACE_FORENSICS = 'ff++' FACE_FORENSICS_DF = 'ff++_df' FACE_FORENSICS_F2F = 'ff++_f2f' FACE_FORENSICS_FSW = 'ff++_fsw' FACE_FORENSICS_NT = 'ff++_nt' FACE_FORENSICS_FSH = 'ff++_fsh' CELEB_DF = 'celeb-df' DEEPER_FORENSICS = 'deeperface' DFDC = 'dfdc' # Manipulation type of FaceForensics++ DF = 'Deepfakes' F2F ...
""" Copyright 2019 Skyscanner Ltd 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 dis...
def test_input_text(expected_result, actual_result): assert expected_result == actual_result, \ "expected {}, got {}".format(expected_result, actual_result) def main(): test_input_text(8, 8) test_input_text(8, 11) if __name__ == "__main__": main()
pattern_zero=[0.0, 0.01492194674, 0.02938475666, 0.0303030303, 0.04338842975, 0.04522497704, 0.05693296602, 0.05968778696, 0.06060606061, 0.07001836547, 0.07369146006, 0.07552800735, 0.0826446281, 0.08723599633, 0.08999081726, 0.09090909091, 0.0948117539, 0.10032139578, 0.10399449036, 0.10583103765, 0.10651974288, 0.11...
LIMITS = {'BNB/BTC': {'amount': {'max': 90000000.0, 'min': 0.01}, 'cost': {'max': None, 'min': 0.001}, 'price': {'max': None, 'min': None}}, 'BNB/ETH': {'amount': {'max': 90000000.0, 'min': 0.01}, 'cost': {'max': None, 'min': 0.01}, ...
numeros = [] numero = 0 pares = [] impares = [] cont = 0 while True: opcao = ' ' numero = int(input('Digite um número: ')) #Poderia usar numeros.append(int(input('Digite valor: '))) numeros.append(numero) while opcao not in 'SN': opcao = str(input('Deseja continuar? [S/N] ')).strip().upper() ...
class Bullet: def __init__(self, x, y, vx, vy, sender, color): self.pos = (x, y) self.vel = (vx, vy) self.sender = sender self.color = color bullets = [] bullets.append(Bullet(0, 1, 2, 3, 'mr. r', (13, 14, 15))) print(bullets[0].sender)
SQLTYPECODE_CHAR = 1 # NUMERIC * / SQLTYPECODE_NUMERIC = 2 SQLTYPECODE_NUMERIC_UNSIGNED = -201 # DECIMAL * / SQLTYPECODE_DECIMAL = 3 SQLTYPECODE_DECIMAL_UNSIGNED = -301 SQLTYPECODE_DECIMAL_LARGE = -302 SQLTYPECODE_DECIMAL_LARGE_UNSIGNED = -303 # INTEGER / INT * / SQLTYPECODE_INTEGER = 4 SQLTYPECODE_INTEGER_UNSIGNED = -...
# Must check this video: https://tinyurl.com/vfmnqt4 class Solution(object): def nextPermutation(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ i = j = len(nums) - 1 while i > 0 and nums[i - 1] >= nums...
class Solution(object): def addStrings(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ result = [] i, j, carry = len(num1) - 1, len(num2) - 1, 0 while i >= 0 or j >= 0 or carry: if i >= 0: carry += or...
NORTH = 0 EAST = 1 SOUTH = 2 WEST = 3 class Robot: def __init__(self, bearing=NORTH, x=0, y=0): self.coordinates = (x, y) self.bearing = bearing def turn_right(self): self.bearing += 1 self.bearing %= 4 def turn_left(self): self.bearing += 3 self.bearing %...
mydict = {'name':'albert','age':28,'city':'Beijing'} print(mydict) mydict2 = dict(name='allen',age=26,city='boston') print(mydict2) value = mydict['name'] print(value) mydict['email'] = 'albert@hotmail.com' print(mydict) mydict['email'] = 'hello@hotmail.com' print(mydict) del mydict['name'] print(mydict) mydict.p...
def get_UnorderedGroupChildren(self): """ List all non-metadata children of an :py:class:`UnorderedGroupType` """ # TODO: should not change order return self.get_RegionRef() + self.get_OrderedGroup() + self.get_UnorderedGroup()
#Schreibe eine Funktion "haeufigkeiten()", #welche zu jedem Zeichen eines übergebenen Strings #die Häufigkeit ermittelt, mit der dieses Zeichen im String vorkommt. #Zurückgegeben wird ein Dictionary, #in welchem jedes Zeichen dessen Vorkommenshäufigkeit zugeordnet wird. def haeufigkeiten(text): #der Text muss...
# -*- coding: utf-8 -*- REPORT_BANNER = """ ╒══════════════════════════════════════════════════════════════════════════════╕ │ │ │ /$$$$$$ /$$ │ │ /$...
def writeFastqFile(filename,reads): fhw=open(filename,"w") for read in reads: fhw.write("@"+read+"\n") fhw.write(reads[read][0]+"\n"+reads[read][1]+"\n"+reads[read][2]+"\n") def writeFastaFile(filename,seqs): fhw=open(filename,"w") for id in seqs: fhw.write(">"+id+"\n"+seqs[id...
class AlembicUtilsException(Exception): """Base exception for AlembicUtils package""" class SQLParseFailure(AlembicUtilsException): """An entity could not be parsed""" class FailedToGenerateComparable(AlembicUtilsException): """Failed to generate a comparable entity""" class UnreachableException(Alemb...
tup1 = ('physics', 'chemistry', 1997, 2000) tup2 = (1, 2, 3, 4, 5, 6, 7 ) print ("tup1[0]: ", tup1[0]) print ("tup2[1:5]: ", tup2[1:5]) # Following action is not valid for tuples # tup1[0] = 100
def validate_name(name): if name.replace(" ", "").isalpha(): return True else: return False def validate_height_in_cm(height): if height < 300 and height > 10: return True else: return False def validate_weigth_in_kg(weight): if weight < 200 and weight > 0: ...
fd = open('Sales.txt','a') fd.write("1111,Ashish,63278648732,1001,5 Star,5,4,20 \n") fd.close()
# Teoria """ Loop for Loop -> Estrutura de repetição For -> Uma dessas estruturas # Em C for (int i = 0, int < 10, int ++ { //execução do loop } # Em Python for item in interavel: //execução do loop Utilizamos loops para iterar sobre sequencias ou valores iteráveis Exemplos de iteráveis: - String - Lista...
""" Longest Palindromic Subsequence Given a sequence, find the length of the longest palindromic subsequence in it. Example : Input:"bbbab" Output:4 """ def lps(s): r = s[::-1] n = len(s) dp = [[0 for _ in range(n+1)] for _ in range(n+1)] for i in range(1, n+1): for j in range(1, n+1): ...
def compact(lst): return list(filter(bool,lst)) print(compact([0,1,False,True,2,'',3,'a','s',34]))
class Solution: """ @param list: The coins @param k: The k @return: The answer """ def takeCoins(self, list, k): # Write your code here n = len(list) presum = [0] * (1 + n) for i in range(n): presum[i + 1] = presum[i] + list[i] ret...
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: morse = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."] transformations = set()...
def test_example_silver(): assert 567 == seat_id("BFFFBBFRRR") assert 119 == seat_id("FFFBBBFRRR") assert 820 == seat_id("BBFFBBFRLL") def test_silver(): with open("input.txt") as file: seats = file.read().split("\n") assert 842 == max([seat_id(seat) for seat in seats]) def test_gold():...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def in_order_traverse_2(self, root, last_val) -> bool: if root.left is None: last_val.append(root.val) else:...
'''(USANDO BREAK) Crie um programa que leia vários números inteiros pelo teclado. O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre eles (desconsiderando o flag(999))''' numero=int(input('Digite um número(99...
n1 = int(input('Digite um número: ')) n2 = int(input('Digite outro número: ')) s = n1 + n2 print('A soma entre', n1, 'e', n2, 'vale:', s) print(f'A soma entre {n1} e {n2} vale: {s}') print('A soma entre {0} e {1} vale: {2}'.format(n1, n2, s)) # print(type(n1))
hangman_txt = (""" _________ |/ | | | | | ========""", """ _________ |/ | | | | | | ...
"""Define battery utilities.""" BATTERY_STATE_OFF = "off" BATTERY_STATE_ON = "on" def calculate_binary_battery(value: float) -> str: """Calculate a "binary battery" value (OK/Low).""" if value == 0: return BATTERY_STATE_OFF return BATTERY_STATE_ON
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: size = len(s) dp = [False] * (size + 1) dp[0] = True for i in range(1, size + 1): for j in range(i): if dp[j] and s[j:i] in wordDict: dp[i] = True ...
# Time: O(m + n) # Space: O(1) # 1071 # For strings S and T, we say "T divides S" if and only if S = T + ... + T  (T concatenated with itself # 1 or more times) # # Return the largest string X such that X divides str1 and X divides str2. class Solution(object): def gcdOfStrings(self, str1, str2): """ ...
# https://adventofcode.com/2018/day/3 total_overlaps = 0 fabric = {} with open('./data.txt', 'r') as ffile: data = ffile.read().strip().split('\n') for data_row in data: parts = data_row.split('@') parts2 = parts[1].split(':') left, top = parts2[0].split(',') width, height = par...
#!/usr/bin/env python # coding: utf-8 # In[ ]: def TicTacDraw(board): n=len(board) d={'0':'O','1':'X','2':' '} for i in range(n): s=' ' for j in range(n): if j == (len(board[i])-1): s=s+d[str(board[i][j])] else: s=s+d[str(board[i][j]...
# -*- coding: utf-8 -*- ################################################################################ # LexaLink Copyright information - do not remove this copyright notice # Copyright (C) 2012 # # Lexalink - a free social network and dating platform for the Google App Engine. # # Original author: Alexander Marqu...
#import matplotlib.pyplot as plt # import torch # from torchvision import datasets, transforms # import helper # image = Image.open('new_digit.png') # image = image.resize((400, 400)) # new_image.save('image_400.jpg') results = ['a','b'] for ite, (brackets) in results: print(ite) print(brackets) #print(c...
CONST_TIMED_ROTATING_FILE_HANDLER = 'TimedRotatingFileHandler' CONST_SOCKET_HANDLER = 'SocketHandler' CONST_FILE_HANDLER = 'FileHandler' CONST_ROTATING_FILE_HANDLER = 'RotatingFileHandler' CONST_STREAM_HANDLER = 'StreamHandler' CONST_NULL_HANDLER = 'NullHandler' CONST_WATCHED_FILE_HANDLER = 'WatchedFileHandler' CONST_...
def calc_pos(dna, temp): n = len(dna) m = len(temp) pos = [] for i in range(n-m+1): if dna[i:i+m] == temp: pos.append(i+1) return pos fin = open('rosalind_subs.txt') dna = fin.readline().strip() temp = fin.readline().strip() pos = calc_pos(dna, temp) for i in pos: print (i, end = " ") print() fin.close()
fitbitSettings = { 'ClientID': '', 'ClientSecret':'', 'CallbackUrl': '', 'OAuthAuthorizeUri':'', 'OAuthAccessRefreshTokenRequestUri': '', 'LoggingApp':'FitbitDataImporter', 'LoggingDirectory':'', 'LogFileName': 'FitbitDataImport.log' } fitbitDataConfigSettings = [] HEART_RATE_SETTINGS = ...
# -*- coding: utf-8 -*- """Untitled1.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1c4ELojr5RJIgfRft7MhpjXDLvmoQLe-A """ R = 4 C = 4 # Function to print the required traversal def counterClockspiralPrint(m, n, matrix) : k = 0; l = 0 ...
"""Atomistic ToolKit (ATK) Some useful tools in the daily life of atomistic simulations. Maintained by Leopold Talirz (leopold.talirz@gmail.com) """
#!/usr/bin/python3 # 存在重复 def containsDuplicate(nums: list) -> bool: nums.sort() for i in range(len(nums) - 1): if nums[i] == nums[i + 1]: return True return False if __name__ == '__main__': arr = [1, 2, 3, 4] print(arr) flag = containsDuplicate(arr) print(flag)
class UserResponse: _raw_input = "" _split_input = [] def __init__(self, prompt=""): # get input with prompt self._raw_input = input(prompt) def get_key(self): if self._raw_input == "": return None # if input is not null then slit it by space-characters an...
def getMinimumUniqueSum(arr): n = len(arr) arr = sorted(arr) unique = list(set(arr)) i = 0 if len(arr) != len(unique): while len(arr) != len(unique): temp = arr[i] print(temp) for j, item in enumerate(unique): if temp == item: ...
class Complex(object): def __init__(self, real, image): self.real = real self.image = image def __mul__(self, other): return Complex( self.real * other.real - self.image * other.image, self.real * other.image + self.image * other.real ) def __str__(s...
# -*- coding: utf-8 -*- __version__ = "1.0" __author__ = "Kacper Kowalik"
""" URIs templates for resources exposed by the Weather API 2.5 """ ICONS_BASE_URL = 'http://openweathermap.org/img/w/%s.png'
""" PASSENGERS """ numPassengers = 26795 passenger_arriving = ( (4, 8, 6, 6, 2, 1, 1, 5, 5, 0, 0, 2, 0, 12, 5, 4, 3, 5, 7, 4, 0, 3, 4, 0, 1, 0), # 0 (12, 11, 10, 11, 6, 5, 4, 4, 3, 1, 0, 0, 0, 8, 5, 6, 5, 4, 4, 1, 2, 2, 1, 1, 0, 0), # 1 (5, 10, 9, 10, 2, 3, 5, 2, 3, 2, 1, 0, 0, 14, 11, 5, 1, 8, 3, 4, 1, 4, 4, 1...
# -------------------------------------------------------------------------- # Basic generation of the Fibonacci number sequence written in Python # link: https://www.mycompiler.io/view/6S2zX4i # author: milk # -------------------------------------------------------------------------- # python fibonacci.py # to ...
#!/usr/bin/python def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where each tuple is of the f...
# -*- coding: utf-8 -*- """ Created on Wed Sep 3 12:07:10 2020 @author: Georg Maubach Programmieren Sie eine Klasse Becher, die Volumen und Fullmenge des Bechers in Milliliter als Fliesskommazahl speichert. Schreiben Sie einen Konstruktor für Volumen und Fullmenge, setzen Sie fur leere Becher ein Standarda...
Ciudades=['Saltillo', 'Monterrey', 'Piedras Negras', 'San Pedro', 'Guadalajara'] print(Ciudades[0].title()) print(Ciudades[1].title()) print(Ciudades[2].title()) print(Ciudades[3].title()) print(Ciudades[4].title()) mensaje="Mi ciudad favorita es " + Ciudades[0].title()+ "." print(mensaje) M1="Me gusta viajar a " + C...
MATCHING_TICKETS_KEYS = ['id', 'category', 'status', 'date', 'price_id', 'quantity', 'section', 'row', 'remarks', 'user_id', 'username', 'updated_at'] MATCHING_TICKETS = ''' SELECT src.id, src.category, src.status, src.`date`, src.price_id, src.quantity, src.section, src.row, src.remarks, src.u...
description = 'Beam limiter at position 1' group = 'lowlevel' display_order = 25 pvprefix = 'SQ:ICON:board1:' devices = dict( bl1left = device('nicos_ess.devices.epics.motor.HomingProtectedEpicsMotor', epicstimeout = 3.0, description = 'Beam limiter 1 -X', motorpv = pvprefix + 'B1nX', ...
class Counter: def __init__(self,low,high): self.current = low self.last = high def __iter__(self): return self #instead of: return iter("...") - this way 'self' here is set up with 'next' below def __next__(self): # here we define __next__ because the 'self' returned from the __iter__ above is not an iterat...
""" Asked by: Flipkart [Medium]. Snakes and Ladders is a game played on a 10 x 10 board, the goal of which is get from square 1 to square 100. On each turn players will roll a six-sided die and move forward a number of spaces equal to the result. If they land on a square that represents a snake or ladder, they will ...
""" Spanish dictionary. """ words = { "basisOfRecord": {"MachineObservation": "Observación con máquina"}, "lifeStage": {"adult": "adulto", "juvenile": "juvenil"}, "organismQuantityType": {"individuals": "individuos"}, "preparations": {"photograph": "fotografía"}, "sampleSizeUnit": {"trap-nights": "t...
test = { 'name': 'q3c', 'points': 2, 'suites': [ { 'cases': [ {'code': '>>> independents_with_ratings.num_rows == 91\nTrue', 'hidden': False, 'locked': False}, { 'code': ">>> independents_with_ratings.labels == ('Rank', 'Restaurant', 'Sales', 'Average Check', 'City',...
# Copyright 2017 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
def test_assert_false(): assert False, 'The assert should fail' # xfail def test_assert_passed(): assert True, 'The assert should pass'
#Dictionary: Dict={1:'Hi','name': 'Hello',3:'how are you?'} #accessing a element using key print(f'Accessing a element using a key: {Dict["name"]}') #accessing a element using key print(f'Accessing an element using a key: {Dict[1]}') #accessing a element using get() print(f'Accessing an element using get()...
class AumbryError(Exception): def __init__(self, message): self.message = message super(AumbryError, self).__init__(message) class LoadError(AumbryError): pass class SaveError(AumbryError): pass class ParsingError(AumbryError): pass class DependencyError(AumbryError): def __i...
""" Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory? Example 1: Input: nums = [2,2,1] Output: 1 Example 2: Input: nums = [4,1,2,1,2] Output: 4 Examp...
# Creamos un objeto como si fuese JSON { # targets son los objetivos donde va a tener que hacer la complilacion, como son mas de uno los ponemos en un array por ahroa un elemento! "targets": [ { # le ponemos el nombr que deseemos a nuestro modulo "target_name" : "addon", ...
"""Custom exceptions classes""" class CoatiException(Exception): pass class CLIException(CoatiException): pass
class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ try: return nums.index(target) except: return -1
""" Nome: Beatiful_Color Função: Estilizar sessões de um texto, com diversas cores e estilos Autor: Állan Rocha Data: 10/8/2017 """ FONT_COLORS = { 'style' : '', 's': '', 'black': '30', 'b': '30', 'red': '31', 'r': '31', 'green': '32', 'g': '32', 'yellow': '33', 'y': '33', '...
@kernel def sample(device, data, samples, wait): for i in range(samples): try: device.sample_mu(data[i]) delay(wait) except RTIOUnderflow: continue @kernel(flags={"fast-math"}) def ramp(board, channels, starts, stops, steps, duration, now): at_mu(now) dt ...
# Version is set for releases by our build system. # Be extremely careful when modifying. version = 'SNAPSHOT' """DC/OS version"""
# Copyright (c) 2018-Present Advanced Micro Devices, Inc. See LICENSE.TXT for terms. #!/usr/bin/evn python3 # tvals = [8, 16, 32, 64, 128, 256] # nw_args = {f'-s {s} -t {t}':[] for s in [16384, 32768] for t in tvals} # lud_args = {f'-s {s} -t {t}':[] for s in [16384, 8192] for t in tvals} gEnvVars = { 'ATMI_D...
#!/usr/bin/env python3 def fibonacci(n): fib = [1, 1] if n <= 2: return fib for num in range(2, n): x = fib[num-1] + fib[num-2] fib.append(x) return fib if __name__ == "__main__": print(fibonacci(10))
number = float(input()) intervalos = ["[0,25]", "(25,50]", "(50,75]", "(75,100]"] if(number < 0 or number > 100): print("Fora de intervalo") else: if(number <= 25): print("Intervalo", intervalos[0]) else: if(number <= 50): print("Intervalo", intervalos[1]) else: if(number <= 75): print("Intervalo", i...
input = """ a v b. :- b. a v x v y :- x. x v y :- y. :- not x, not y. """ output = """ """
# Love Calculator # 💪 This is a Difficult Challenge 💪 # Instructions # You are going to write a program that tests the compatibility between two people. # To work out the love score between two people: # > Take both people's names and check for the number of times the letters in the word TRUE occurs. Then c...
""" Ejercicio 11 Desarrolle un algoritmo, que dado como dato una temperatura en grados Fahrenheit, determine el deporte que es apropiado practicar a esa temperatura, teniendo en cuenta la siguiente tabla: Deporte Temperatura Natación Temp. > 85 Tenis 70 < Temp. <= 85 Golf 32 < Temp...