content
stringlengths
7
1.05M
class Solution: def XXX(self, root: TreeNode) -> List[List[int]]: if root is None: return [] res = [] queue = [root] while queue: tmp = [] size = len(queue) while size: q = queue.pop(0) tmp.append(q.val) ...
""" The different types of errors the compiler can raise. """ class CompilerError(Exception): """ A general-purpose compiler error, which contains the position of the error as well as a formatted message. """ def __init__(self, filename, line, col, fmt, *args, **kwargs): super().__init__() ...
#!/usr/bin/env python3 def get_stream(path): with open(path, encoding='utf-8') as infile: return infile.read() stream = get_stream("input.txt") def find_in_list(list_, x, start=0): i = None try: i = list_.index(x, start) except ValueError: pass return i # Stream types...
sum = 0 for i in range(1, 101): sum += i print(sum)
interest = [ (0, "Hadoop"), (0, "Big Data"), (0, "HBase"), (0, "Java"), (0, "Spark"), (0, "Storm"), (0, "Cassandra"), (1, "NoSQL"), (1, "MongDB"), (1, "Cassandra"), (1, "HBase"), (1, "Postgres"), (2, "Python"), (2, "scikit-learn"), (2, "scipy"), (2, "numpy"), (2, "statsmodels"), (2, "pandas"), (3, "...
#!python def is_sorted(items): #TODO: write code to implement the selection sort algorithm for i in range(len(items)): #moving the boundary of the sorted section forward min_location = i for j in range(i + 1, len(items)): #finding the min value location in the unsorted section if items[j] < items[min_...
#$ID$ class Participant: """This class is used to create object for participant.""" def __init__(self): """Initialize parameters for participant object.""" self.participant_id = "" self.participant_person = "" def set_participant_id(self, participant_id): """Set part...
def count_neigbors_on(lights, i, j): return (lights[i-1][j-1] if i > 0 and j > 0 else 0) \ + (lights[i-1][j] if i > 0 else 0) \ + (lights[i-1][j+1] if i > 0 and j < len(lights) - 1 else 0) \ + (lights[i][j-1] if j > 0 else 0) \ + (lights[i][j+1] if j < len(lights) - 1 els...
'''Publisher form Provides a form for publisher creation ''' __version__ = '0.1'
"""Desenvolva um programa que pergunte a distância de uma viagem em km. Calcule o preço da passagem, cobrando R$ 0.50 po km para viagens de até 200km e R$ 0.45 para viagens mais longas""" dist = float(input('Informe a distância da viagem: ')) if dist > 200: valor = dist * 0.45 print('Valor da viagem é: {}'.form...
# Valores iniciais m = 0.5 g = 10 h = e = 0 # recebendo H h = float(input("Digite a altura: ")) # 1° quicada e = m*g*h-(0.2*m*g*h) # 2° Quicada e = e - (0.2*e) # 3° Quicada e = e - (0.2*e) # calculando novo h h = e/(m*10) # exibindo resultado print(f'A altura é de {h} após as 3 quicadas')
class Item(): def __init__(self, id_, value): self.id_ = id_ self.value = value class Stack(): def __init__(self): self.size = 0 self._items = [] def push(self, item): self._items.append(item) self.size += 1 def pop(self): item = None i...
NON_TERMINALS = [ "S", "SBAR", "SQ", "SBARQ", "SINV", "ADJP", "ADVP", "CONJP", "FRAG", "INTJ", "LST", "NAC", "NP", "NX", "PP", "PRN", "QP", "RRC", "UCP", "VP", "WHADJP", "WHAVP", "WHNP", "WHPP", "WHADVP", "X", "R...
# Error handling def fatal_error(error): """Print out the error message that gets passed, then quit the program. Inputs: error = error message text :param error: str :return: """ raise RuntimeError(error)
# Problem: # In one cinema hall, the chairs are arranged in rectangular shape in r row and c columns. # There are three types of projections with Tickets at different rates: # -> Premiere - Premiere, at a price of 12.00 BGN. # -> Normal - standard screening, at a price of 7.50 leva. # -> Discount - screening for chi...
# Title : TODO # Objective : TODO # Created by: Wenzurk # Created on: 2018/2/19 pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] print(pets) while 'cat' in pets: pets.remove('cat') print(pets)
class NotInServer(Exception): # The whole point of this is to do nothing def __init__(self): pass class NotWhitelisted(Exception): def __init__(self): pass
# Exercício Python 096: # Faça um programa que tenha uma função chamada área(), # que receba as dimensões de um terreno retangular (largura e comprimento) e mostre a área do terreno. def area(l, c): a = l * c print(f'A área de um terreno {l}x{c} é de {a}m².') print('Controle de Terrenos') print('-' * 20) x = ...
class Pagination(object): count = None def paginate_queryset(self, request, queryset, handler): raise NotImplementedError def get_paginated_response(self, request, data): raise NotImplementedError
# hello world def print_lol(the_list, indent=false, level=0): for each_item in the_list: if isinstance(each_item, list): print_lol(each_item, indent, level+1) else: if indent: for tab_stop in range(level): print("\t", end=' ') print(each_item)
def read_samplesCSV(spls): # reads in samples.csv file, format: Batch,Lane,Barcode,Sample,Alignments,ProviderName,Patient hdr_check = ['Batch', 'Lane', 'Barcode', 'Sample', 'Alignments', 'ProviderName', 'Patient'] switch = "on" file = open(spls, 'r') list_path = [] list_splID = [] list_providerNames = [] list_r...
while True: n_peer = int(input()) counter = 1 for i in range(2, n_peer): if n_peer%i == 1: print(i, end=' ') counter += 1 print() print(counter)
def read_next(*args): for el in args: for i in el: yield i for item in read_next('string', (2,), {'d': 1, 'i': 2, 'c': 3, 't': 4}): print(item, end='')
# ---------------------------------------------------------- # # Title: Listing 07 # Description: A module of multiple processing classes # ChangeLog (Who,When,What): # RRoot,1.1.2030,Created started script # ---------------------------------------------------------- # if __name__ == "__main__": raise Except...
""" 4 - Fizz Buzz - Se o parâmetro da função for divisível por 3, returne Fizz, se o parâmetro da função for divisível por 5, retorne buzz. Se o parâmetro da função for fivissível por 5 e por 3, return FizzBuzz, caso contrário, retorne o número enviado. """ def fizzBuzz(valor): if valor % 3 == 0 and valor % 5 == ...
califications = { 'anartz': 9.99, 'mikel': 5.01, 'aitor': 1.22, 'maite': 10, 'miren': 7.8, 'olatz': 9.89 } pass_students = [] # Obtener clave, valor elemento a elemento for key, value in califications.items(): if (value >= 5): pass_students.append(key) print("Notas del curso:") print(calif...
def qsort(arr): if len(arr) <= 1: return arr pivot = arr.pop() greater, lesser = [], [] for item in arr: if item > pivot: greater.append(item) else: lesser.append(item) return qsort(lesser) + [pivot] + qsort(greater)
class A(): def load_data(self): return [1,2,3,4,5] def __getitem__(self, item): a = self.load_data() return a[item] class B(A): def load_data(self): return ['a','b','c'] a = B() print(a[1])
""" Fixes the extra commas in some of the regions in the Russian data. """ file = open("data/2018-Russia-election-data.csv", "r", encoding="utf-8") TEXT = "" for line in file: if len(line.split(",")) == 5: last_char_index = line.rfind(",") new_line = line[:last_char_index] + "" + line[last_char_ind...
class CidrMaskConvert: def cidr_to_mask(self, val): val = int(val) if 1 > val or val > 32: return "Invalid" val = '.'.join([str((0xffffffff << (32 - val) >> i) & 0xff) for i in [24, 16, 8, 0]]) return val def mask_to_cidr(self, val): mask...
# name = input("Enter your name: ") # age = input("Enter your age: ") # print("Hello " + name + "! You are " + age) # create a calculator, be careful the input is a string num1 = input("Enter a number: ") num2 = input("Enter a number: ") # int does not work for decimal numbers result1 = int(num1) + int(n...
class Solution: # @param A : string # @return an integer def solve(self, s): n = len(s) lps = [0]*n i,l = 1,0 while i < n: if s[i]==s[l]: lps[i] = l+1 l+=1 i+=1 elif l > 0: l = lps[l-1] ...
""" Platform for DS-AIR of Daikin https://www.daikin-china.com.cn/newha/products/4/19/DS-AIR/ """
# formatting menu = [ ["egg", "bacon"], ["egg", "bacon", "sausage"], ["egg", "spam"], ["egg", "spam", "tomato"], ["egg", "spam", "tomato", "spam", "tomato"], ] for meal in menu: if "spam" in meal: print("Yeah, not there") else: print("{0} has the spam score of {1}" ...
class RandomResponseFrequency: """A RandomResponseFrequency is an object used to define frequency over a range of modes. This page discusses: Attributes ---------- lower: float A Float specifying the lower limit of the frequency range in cycles per time. upper: float A Float sp...
# # coding=utf-8 def normalize(block): """ Normalize a block of text to perform comparison. Strip newlines from the very beginning and very end Then split into separate lines and strip trailing whitespace from each line. """ assert isinstance(block, str) block = block.strip('\n') return [l...
""" Swap two variables' contents without using a 3rd variable. Not really useful in Python since you can do: `a, b = b, a`. Author: Christos Nitsas (nitsas) (nitsas.chris) Language: Python 3(.4) Date: April, 2016 """ __all__ = ['xor_swap'] def xor_swap(a, b): a ^= b # invert those bits of a...
class Solution(object): def strWithout3a3b(self, A, B): """ :type A: int :type B: int :rtype: str """ if A >= 2*B: return 'aab'* B + 'a'* (A-2*B) elif A >= B: return 'aab' * (A-B) + 'ab' * (2*B - A) elif B >= 2*A: re...
class Database: ''' A generic database that must implement at least the two methods declared below. The specific implementation of the database is left to Admin, but it can be any typical SQL or other database so long as it can implement a table where the key is a Hashable type and the value is Any type. ...
# 190. Reverse Bits class Solution: def reverseBits(self, n: int) -> int: bin_num = format(n, 'b') res = '0' * (32-len(bin_num)) + bin_num return int('0b' + res[::-1], 2)
T = int(input()) a=list(map(int,input().split())) for i in range(0,T): b = input() if(b == '+'): print(a[0]+a[1]) elif(b == '-'): print(a[0]-a[1]) elif(b == '*'): print(a[0]*a[1]) elif(b == '/'): print(a[0]//a[1]) elif(b == '%'): print(a[0]%a[1])
''' Quadrado Um quadrado quase mágico, de dimensões N N, é um quadrado que obedece à seguinte condição. Existe um número inteiro positivo M tal que: para qualquer linha, a soma dos números da linha é igual a M; e para qualquer coluna, a soma dos números da coluna é também igual a M. O quadrado seria mágico, e não ape...
name = input("whats your name\n") bebe = "october" print(bebe) print("hi") print (name) print("?!") print("tova") # pavtuk smiatam h = 2 c = 2 d = h*2 + c print(d)
""" Connected components and graph resilience """ def bfs_visited(ugraph, start_node): """ Takes the undirected graph ugraph and the node start_node and returns the set consisting of all nodes that are visited by a breadth-first search that starts at start_node. """ visited = set() stack = [start_node] ...
calories_per_click = dict([(str(index + 1), int(calories)) for index, calories in enumerate(input().split())]) total_calories_burned = sum([calories_per_click[c] for c in input()]) print(total_calories_burned)
# Notation x.y.z: # x: major release # y: minor release / new feature # z: build number / bug maintenance version = '0.5.1'
""" Utilities for VCF files. """ def walk_together(*readers, **kwargs): """ Simultaneously iteratate over two or more VCF readers. For each genomic position with a variant, return a list of size equal to the number of VCF readers. This list contains the VCF record from readers that have this vari...
class EvaluateConfig: def __init__(self): self.game_num = 100 self.replace_rate = 0.55 self.play_config = PlayConfig() self.play_config.c_puct = 1 self.play_config.change_tau_turn = 0 self.play_config.noise_eps = 0 self.evaluate_latest_first = True class Pla...
class FakeSingleton: def __init__(self, payload): self._payload = payload def instance(self): return self._payload
""" This module has various utilities for managing the CTCP protocol. It is is responsible for parsing CTCP data and making data ready to be sent via CTCP. """ X_DELIM = "\x01" M_QUOTE = "\x10" X_QUOTE = "\\" commands = ["ACTION", "VERSION", "USERINFO", "CLIENTINFO", "ERRMSG", "PING", "TIME", "FINGER"]...
''' What is going on everyone welcome to my if elif else tutorial video. The idea of this is to add yet another layer of logic to the pre-existing if else statement. See with our typical if else statment, the if will be checked for sure, and the else will only run if the if fails... but then what if you want to chec...
steps = 363 buffer = [0] currentValue = 1 currentPosition = 0 for i in range(1, 2018): currentPosition = (currentPosition+steps)%len(buffer) buffer.insert(currentPosition+1, currentValue) currentValue += 1 currentPosition += 1 print(buffer[(currentPosition+1)%len(buffer)])
#!/usr/bin/env python # -*- coding: utf-8 -*- """ __title__ = 'cprint' __author__ = 'JieYuan' __mtime__ = '19-1-10' """ class Cprint(object): def __init__(self): colors = ['green', 'yellow', 'black', 'cyan', 'blue', 'red', 'white', 'purple'] self.fc = dict(zip(colors, range(40, 97))) self....
quizzes = { 'moon': 'Most planets have at least one of this orbiting around.', 'black hole': "What comes in, never goes out.", 'sun': "Hot, hot, hot... It loves to be the center everything!.", 'elon musk': "He is a billionaire entrepreneur, philanthropist and visionary South-African-Canadian-American. Founder, CEO and ...
def findDecision(obj): #obj[0]: Coupon, obj[1]: Education, obj[2]: Occupation, obj[3]: Distance # {"feature": "Coupon", "instances": 51, "metric_value": 0.9931, "depth": 1} if obj[0]>1: # {"feature": "Occupation", "instances": 36, "metric_value": 0.9183, "depth": 2} if obj[2]<=19: # {"feature": "Education", "i...
class JSONWriter: def __init__(self, alerts, row_parser): self.alerts = alerts self.row_parser = row_parser def parse_alerts(self, vendor, url,product, webpage_name): collection = list() alerts_list = self.alerts failed_count = 0 skipped_count = 0 for a...
class Partisan_Gauge: def __init__(self): self.cultural_axis = 0 self.economic_axis = 0 self.authoritarian_axis = 0 def set_cultural_axis(self,cultural_axis): self.cultural_axis = cultural_axis def set_cultural_axis(self,cultural_axis): self.cultural_axis = cultural...
# Write your solution for 1.3 here! n = 0 i = 1 while i < 10000: n = n + i i = i + 1 print(i)
"""Windchill module. Connect to Windchill server, use workspaces (create/delete/list) List files and checkout status. """ def authorize(client, user, password): """Set user's Windchill login/password. Args: client (obj): creopyson Client user (str): user name password (str): passwor...
# Задача 2. Вариант 28. #Напишите программу, которая будет выводить на экран наиболее понравившееся вам высказывание, автором которого является Эпикур. Не забудьте о том, что автор должен быть упомянут на отдельной строке. # Цкипуришвили Александр # 25.05.2016 print("Каждый уходит из жизни так, словно только что ...
with open('./6/input_a.txt', 'r') as f: input = list(map(int,f.readline().strip().split(','))) fish = list([0,0,0,0,0,0,0,0,0]) for i in range(0,8): fish[i] = sum([1 for a in input if a == i]) def observe(days): for d in range(0,days): newfish = fish[0] for i in range(0,8): fi...
def center_text(*args, sep=' ', end='\n', file=None, flush=False): text='' for arg in args: text += str(arg) + sep left_margin = (80 - len(text)) // 2 print(" " * left_margin, text, end=end, file=file, flush=flush) # calling the function center_text("spams and eggs") center_text(12) center_text...
""" Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer". ...
#!/usr/bin/env python # encoding: utf-8 name = "R_Addition_COm/groups" shortDesc = u"" longDesc = u""" """ template(reactants=["COm", "Y_rad"], products=["YC.=O"], ownReverse=False) reverse = "COM_Elimination_From_Carbonyl" recipe(actions=[ ['LOSE_PAIR', '*1', '1'], ['CHANGE_BOND', '*1', -1, '*3'], ['G...
# ceasar_cypher_encryptor # rotate each letter by k # wrap around alphabet def ceasar_cypher_encryptor(s, k): ciphered = [] overflow_adjust = ord('z') - ord('a') for c in s: new_c = ord(c) + k if new_c > ord('z'): # overflow adjustment new_c = new_c - overflow_adjust c...
# Write a program to read through the mbox-short.txt # and figure out the distribution by hour of the day # for each of the messages. You can pull the hour out # from the 'From ' line by finding the time and then # splitting the string a second time using a colon. # # From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16...
def foo(a = 1, b = 2): return a + b price = foo(b = 4) for item in [[1, 2, 3], [4, 5, 6]]: print(item[0]) mylist = [['abc'], ['def', 'ghi']] mylist[-1][-1][-1] def eur_to_usd(euros, rate=0.8): return euros * rate print(eur_to_usd(10)) weight = input("How many kg?") price = weight * 2.5 print(price) ...
class RawNode(object): def __init__(self, chunk): self.chunk = chunk def render(self, ctx={}): return str(self.chunk)
RegionsVariablesMap = { "Zarem": { "Apple": { "Wofost": "Supply of apple zr", "Vensim": "apple zr", "KeyInVensimModel": "apple_zr" }, "Rice": { "Wofost": "supply of rice zr", "Vensim": "rice zr", "KeyInVensimModel": "ric...
# -*-coding:utf-8 -*- #Reference:********************************************** # @Time    : 2019-10-29 11:22 # @Author  : Fabrice LI # @File    : 20191029_135_combination_sum.py # @User    : liyihao # @Software : PyCharm # @Description: Given a set of candidtate numbers candidates and a target number target. # ...
#Criação das 4 listas filmes = ['Harry Potter', 'Zumbilandia', 'Invocação do Mal', 'O elo perdido'] jogos = ['Valorant', 'Dark Souls', 'Dont Starve Together', 'Cup Head'] livros = ['O homem de giz', 'Diario de um banana', 'A guerra dos tronos'] esporte = ['xadrez', 'futebol', 'basquete', 'volei'] #Adicionar 2 iten...
ctx.rule(u'START',u'{PROGRAM}') ctx.rule(u'PROGRAM',u'{STATEMENT}\n{PROGRAM}') ctx.rule(u'PROGRAM',u'') ctx.rule(u'STATEMENT',u';') ctx.rule(u'STATEMENT',u'') ctx.rule(u'STATEMENT',u'break') ctx.rule(u'STATEMENT',u'{VAR} = {EXPR}') ctx.rule(u'STATEMENT',u'local {VARLIST} = {EXPRLIST}') ctx.rule(u'STATEMENT',u'{FUNCTION...
#urnEletronica candidato_prefeito_1 = 0 candidato_prefeito_2 = 0 votos_brancos = 0 anulados = 0 def msg(): mensagem = input('INICIAR?SIM OU NÃO?') mensagem.lower() return mensagem def verdade_falso(): mensagem =msg() if mensagem == 'sim': return True else: return False def...
def detectHashtag(inputs): data = [] for tweet in inputs: hashtag = tweet.entities['hashtags'] for hash in hashtag: if hash['text'].lower() == 'testtweet': data.append(tweet) return data def interact(inputs, api, FILE_NAME): data = detectHashtag(inputs) ...
class Element: __slots__ = ('attributes', 'children') name = 'element' def __init__(self, *args, **kwargs): self.attributes = {k.replace('_', '-'): v for k, v in kwargs.items()} self.children = [] for item in args: if type(item) in (list, tuple): self.chil...
# factorial of a positive integer -- https://en.wikipedia.org/wiki/Factorial def factorial(n: int) -> int: """ >>> import math >>> all(factorial(i) == math.factorial(i) for i in range(20)) True >>> factorial(0.1) Traceback (most recent call last): ... ValueError: factorial() only a...
class FileExtensions: """ Class containing names for valid File Extensions """ spark: str = "spark" keras: str = "h5" h2o: str = "h2o" sklearn: str = "pkl" @staticmethod def get_valid() -> tuple: """ Return a tuple of the valid file extensions in Database...
''' Ряд - 3 ''' def printRangeOdd(n): start = int('1' + '0' * n) - 1 if (n == 1): end = 0 else: end = int('9' + '9' * (n - 2)) for i in range(start, end, -2): print(i, end=' ') print('') n = int(input()) printRangeOdd(n)
class Solution: """ @param nums: the gievn integers @return: the total Hamming distance between all pairs of the given numbers @ Time O(32*n) ~= O(n) @ for i in range(32): mask = 1 << i print(i) print("{0:b}".format(mask)) """ def totalHammingDistance(self, nums): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- ## Copyright Zeta Co., Ltd. ## written by @moeseth based on research by @aye_hnin_khine class MatchedWord(): def __init__(self, word, start): self.word = word self.start = start
#!/usr/bin/python3 # -*- coding: utf-8 -*- class Student(object): """构造函数, 从 info 中解析出 name, hours, qpoints, 并计算出 GPA""" def __init__(self, info): # 每一条 info 的格式是 'name\thours\tqpoints' name, hours, qpoints = info.split('\t') self.name = name self.hours = float(hours) self.qpoints = float(qpoints) # 根据公式...
''' LEGACY CODE Only use this to steal ideas from import time import hashlib import sys import json import os import secrets import string import base64 import ecdsa import secrets import string import logging # Node's blockchain copy """ Stores the transa...
# https://leetcode.com/problems/remove-element/description/ # # algorithms # Easy (41.9%) # Total Accepted: 312.2k # Total Submissions: 745.1k # beats 100.00% of python submissions class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int ...
NPep = int(input()) NLKgH = [] LKgH = [] rank = [] for each in range(NPep): KgH = list(input("The format should be: mass, height ").split(" ")) LKgH.append(KgH[0]) LKgH.append(KgH[1]) NLKgH.append(LKgH) LKgH = [] for each in range(1, len(LKgH)): rank.append(each) for each in range(1, len(rank)-...
# # @lc app=leetcode id=349 lang=python3 # # [349] Intersection of Two Arrays # # @lc code=start class Solution: def intersection(self, nums1: [], nums2: []) -> []: # * 直接转换成set计算交集 return list(set(nums1).intersection(set(nums2))) def test(self): assert(self.intersection([1,2,2,1], [2,...
def lower_bound(nums, target): l, r = 0, len(nums) while l < r: mid = (l + r) // 2 if nums[mid] < target: l = mid + 1 else: r = mid return l class Solution: def findMissingRanges(self, nums: List[int], lower: int, upper: int) -> List[str]: l, r =...
""" Apache Avro dependencies. """ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file") def avro_repositories(): http_file( name = "avro_tools", sha256 = "ab158f4af8f767d2358a29d8678939b2a0f96017490acfb4e7ed0708cea07913", urls = ["https://archive.apache.org/dist/avro/avro-1.10....
number = int(input("Number? ")) factorial = 1 while number > 0: factorial += factorial * (number - 1) number -= 1 print("Factorial: " + str(factorial))
__version__ = "0.9.6" __title__ = "joulescope" __description__ = 'Joulescope™ host driver and utilities' __url__ = 'https://joulescope.readthedocs.io' __author__ = 'Jetperch LLC' __author_email__ = 'joulescope-dev@jetperch.com' __license__ = 'Apache 2.0' __copyright__ = 'Copyright 2018-2021 Jetperch LLC'
""" index: 018 problem: 삼각형을 따라 내려가면서 합이 최대가 되는 경로 찾기 """ triangle = """75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 ...
## Multiply ## 8 kyu ## https://www.codewars.com//kata/50654ddff44f800200000004 def multiply(a, b): return a * b
def get_value_from_node_by_name(node, value_name): tmp_value_name = value_name if value_name == 'Color' and node.type == 'BSDF_PRINCIPLED': tmp_value_name = "Base Color" if tmp_value_name in node.inputs.keys(): if node.inputs[tmp_value_name].type == 'RGBA': r, g, b, a = node.in...
class ExamRoom: def __init__(self, n: int): self.occupied = [] self.n = n def seat(self) -> int: if not self.occupied: self.occupied.append(0) return 0 left, right = -self.occupied[0], self.occupied[0] maximum = (right - left) // 2 ...
DATA_DIR = './data/' SAVE_DIR = './pts/' DATA_FPATH = 'ml-100k/u.data' DATA_COLS = ['user_id', 'item_id', 'rating', 'timestamp'] POS_THRESH = 3.5 TRAIN_PATH = DATA_DIR + 'train.dat' VALID_PATH = DATA_DIR + 'valid.txt'
# -*- Python -*- # Given a source file, generate a test name. # i.e. "common_runtime/direct_session_test.cc" becomes # "common_runtime_direct_session_test" load("@local_config_cuda//cuda:build_defs.bzl", "if_cuda", "cuda_default_copts") # Sanitize a dependency so that it works correctly from code that includes...
#Файл созданный для записи необходимых токенов для сервиса #оформлен в виде get функций для того, чтобы данные нельзя было изменить def bot_token(): return "your_token" def yandex_token(): return "your_token"
class Solution: def minSubArrayLen(self, s: int, nums: list) -> int: # Time Complexity: O(n) # Space Complexity: O(1) # TODO Binary Search O(nlog(n)) if not nums or sum(nums) < s: return 0 min_len = len(nums) current_sum = 0 left = 0 for ...
# Adding an if statement so that the print statements aren't so wrong! # This was not part of the exercise animals = ['Dog', 'Cat', 'Dolphin', 'Wolf', 'Polar bear', 'Penguin'] for animal in animals: if animal == 'Dog' or animal == 'Cat': print(f"A {animal.lower()} would make a great pet!") else: ...
# Fibonacci series class FibonacciSeriesDemo: Instances = 0 def __init__(self): FibonacciSeriesDemo.Instances += 1 def displayFibonacci(self, title, value): first, second = 0, 1 print(f"----- {title}till {value} -----") print(f'FibonacciSeriesDemo.Instances: {self.Instance...
# ---------------------------------------------------------------------------- # CLASSES: nightly # # Test Case: lines.py # # Tests: mesh - 2D lines (unstructured), 3D lines (unstructured) # plots - mesh # # Programmer: Alister Maguire # Date: Tue Mar 17 08:50:32 PDT 2020 # # Mod...