content
stringlengths
7
1.05M
""" 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻: Implement the design of the Pasta class so that the following output is produced: print("Pasta Plate Count:", Pasta.pasta_plate_count) print("=======================") s1 = Pasta("Chicken") s1.set_ingredients("Farfalle",250, 11, 40, 10) s1.display_all_info() print("------------------------------...
""" Simply pretty print the adf """ class pprint: """ class to pretty print the data structure behind adf >>> pp = pprint() >>> pp.head() +------------------+------------------+------------------+ | c1 | c2 | c3 | +------------------+---------------...
description = 'NE1002 syringe pump' pv_root = 'E04-SEE-FLUCO:NE1002x-001:' devices = dict( inside_diameter_1002=device( 'nicos_ess.devices.epics.pva.EpicsAnalogMoveable', description='The Inside diameter of the syringe', readpv='{}DIAMETER'.format(pv_root), writepv='{}SET_DIAMETER'...
'''Faça um programa que leia o sexo de uma pessoa, mas só aceite os valores 'M' ou 'F'. Caso esteja errado peça a digitação novamente até ter um valor correto, ''' sexo = str(input('' '\nInforme "M" para Masculino ou "F" para Feminino : ')).upper().strip()[0] while sexo not in ['M', 'F']: pr...
# Delete Middle Node: Implement an algorithm to delete a node in the middle (i.e., any node but # the first and last node, not necessarily the exact middle) of a singly linked list, given only access to # that node. def delete_mid_node(node): if node is None or node.get_next_mode() is None: return False ...
''' Given an array of positive integers. Find the length of the longest sub-sequence such that elements in the subsequence are consecutive integers, the consecutive numbers can be in any order. ''' ## function work...!!!! ''' findLCS() function--> which takes the array arr[] and the size of the array as inputs and retu...
def make_song(verses = 99, beverage = "soda"): for num in range(verses, -1, -1): if num == 0: yield f"No more {beverage}!" elif num == 1: yield f"Only {num} bottle of {beverage} left!" else: yield f"{num} bottles of {beverage} on the wall." song = mak...
# par ou impar com funcoes def par_impar(x): if x % 2 == 0: return 'par' else: return 'impar' # Programa principal print(par_impar(int(input('Digite um valor inteiro: '))))
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def isPalindrome(self, head): if not head: return head count = 1 temp = head while temp.next: ...
def foo(): f = 0.0 while f < 10000000.0: f = f + 1.0 foo()
speed = 108 time = 12 dist = speed * time print(dist) # + Сложение 11 6 17 # - Вычитание 11 6 5 # * Умножение 11 6 66 # // Целочисленное деление 11 6 1 # % Остаток от деления 11 6 5 # ** Возведение в степень 2 3 8 goodByePhrase = 'Hasta la vista' person = 'baby' print(goodByePhrase + ', ' + person + '!') answer = '2...
#5. Un vendedor recibe mensualmente un sueldo base más un 10% # extra por comisión de sus ventas. El vendedor desea saber cuánto # dinero obtendrá por concepto de comisiones por las tres ventas que realiza en el mes y # el total que recibirá en el mes tomando en cuenta su sueldo base y comisiones. sueldo=float(input...
def helper(arr, left_pos, mid_pos, right_pos): sum1 = sum2 = 0 left_sum = right_sum = -9999 for i in range(mid_pos, left_pos - 1, -1): sum1 += arr[i] if sum1 > left_sum: left_sum = sum1 for i in range(mid_pos + 1, right_pos + 1): sum2 += arr[i] if sum2 > r...
CH_FONTS={ u'\u4e2d':bytearray([ 0x01,0x00,0x01,0x00,0x01,0x00,0x3f,0xfc, 0x21,0x04,0x21,0x04,0x21,0x04,0x21,0x04, 0x3f,0xfc,0x21,0x04,0x01,0x00,0x01,0x00, 0x01,0x00,0x01,0x00,0x00,0x00,0x00,0x00 ]), u'\u6587':bytearray([ 0x01,0x00,0x01,0x00,0x01,0x80,0x7f,0xfc, 0x18,0x10,0x08,0x20,0x0c,0x20,0x04,0x40, 0x02,0xc0,0x03,0...
class ConfirmationTypes: """Self explanatory :(""" """Received by server if the client's connection is refused. id:CLIENT_ID, type:CONNECTION_REFUSED""" CONNECTION_REFUSED = "CONNECTION_REFUSED" """Sent by either server or client to reject previous request id:CLIENT_ID, type:REJECTED, ...
""" This script includes all the functions for generic interviews """ def binary_to_decimal(decimal_num: str): """ Converts binary number to decimal number. @return: <int> int of the decimal number """ decimal_string = str(decimal_num) if len(decimal_string) > 0: first = decimal_string...
#encoding:utf-8 subreddit = 'im14andthisisdeep' t_channel = '@wokesouls' def send_post(submission, r2t): return r2t.send_simple(submission)
#utilities.py foodsize = 30 SCREEN_WIDTH = 1280 SCREEN_HEIGHT = 1024 RED = (255, 0, 0) BLUE = (0, 0, 255) BACKGROUND_COLOR = (0, 0, 0) AREA = 30 def compreso(num, low, high): """ checks whether or not a number is between low and high """ return num>=low and num<=high if __name__ == '__main__': s...
bot_token = '<your_bot_token>' fd_token = '<your_football_api_token>' fd_hostname = 'api.football-data.org' fd_protocol = 'https' loglevel = 'DEBUG'
""" Task Score: 100% Complexity: O(N*log(N)) """ def solution(A): """ Not even going to comment on this one... """ return len(set(A))
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Contains reference and master data used elsewhere in the program ''' # LED GPIO pin mappings # Used to provide user information on when the photos are being taken # and for the user to trigger the script by pressing the button controller # Need to use BOARD numbering ...
class Stack(object): def __init__(self): self.items =[] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def is_empty(self): return len(self.items) == 0 def peek(self): if not self.is_empty(): return self.ite...
def match(value, pattern, exact=False): if exact: return value == pattern pattern = pattern.split('*') if len(pattern) == 2: return value.startswith(pattern[0]) elif len(pattern) == 1: return value == pattern[0] else: raise ValueError(pattern) def match_any(val...
# Copyright 2020 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
# encoding: UTF-8 LOADING_ERROR = u'Error occurred when loading the config file, please check.' CONFIG_KEY_MISSING = u'Key missing in the config file, please check.' DATA_SERVER_CONNECTED = u'Data server connected.' DATA_SERVER_DISCONNECTED = u'Data server disconnected' DATA_SERVER_LOGIN = u'Data server login complet...
def countSpace(): count = 0 with open('test.txt') as file: for line in file: if ' ' in line: count += line.count(' ') print(count) return count def replaceSpace(): with open('test.txt') as file: content = file.read() content = content.replace(' ', '#') with open('test.txt', 'w') as file: file.writ...
# ====================================================================== # Copyright CERFACS (November 2018) # Contributor: Adrien Suau (adrien.suau@cerfacs.fr) # # This software is governed by the CeCILL-B license under French law and # abiding by the rules of distribution of free software. You can use, # modify a...
def nthprime(n: int) -> int: ''' Returns nth prime number. Reference: https://stackoverflow.com/a/48040385/13977061 ''' start = 2 count = 0 while True: if all([start % i for i in range(2, int(start**0.5 + 1))]): count += 1 if count == n: ...
# Реализуйте функцию sum_of_intervals, которая принимает на вход список интервалов и возвращает сумму # всех длин интервалов. В данной задаче используются только интервалы целых чисел от 1 до ∞ , которые представлены # в виде списков. Первое значение интервала всегда будет меньше, чем второе значение. Например, длина и...
x=int(input('enter value ')) for i in range(x): for j in range(x): if((i+j==4) or (i+j==5) or(i+j==6)or(i+j==7)or(i+j==8)): print((i+j)-(x-2) ,end=' ') else: print('*',end=' ') print()
def buildsquare(width=0,height=0): spaces = " " * (height // 6) lineshor = "|" + ("_" * (width // 5)) + "|" linesver = "|\n" * (height // 6) print(linesver + lineshor) #NO SNEAKING TO MY CODE, THIS NOT DONE
''' Escribir un programa que determine si un año es bisiesto. Un año es bisiesto si es múltiplo de 4 (por ejemplo 1984). Los años múltiplos de 100 no son bisiestos, salvo si ellos son también múltiplos de 400 (2000 es bisiesto, pero; 1800 no lo es). ''' def is_leap(year): if (year % 100 != 0 or year % 400 == ...
# Підрахувати, скільки разів серед символів заданого рядка зустрічається буква "а". # Рядок : "It is a long established fact that a reader." # Потрібно створити змінну count = 0 - де буде зберігатися кількість букви "а" . # Використати цикл for і умовний оператор if . # Надрукувати через print("Кількість б...
num_list = list() size = 0 try: for filename in ['5a.txt', '5b.txt']: with open(filename, 'r') as f: splited = f.read().split() size = len(splited) if len(splited) > size else size num_list.append(splited) for num in range(size): num_sum = 0 for index ...
grid = [[0,0,0,0,0,0,0,2,0], [9,7,0,0,0,0,4,0,0], [0,4,0,1,0,8,0,0,0], [0,0,0,6,0,3,0,7,0], [0,0,0,4,0,0,0,8,5], [0,0,8,0,0,5,0,3,0], [0,5,0,0,0,0,2,0,0], [0,0,0,0,0,1,0,6,3], [3,0,0,7,4,0,0,9,0]] def print_grid (grid) : for i in grid : for j in i : ...
#Reading input n,k n,k = map(int, input().split()) count = 0 #count denotes number of integers divisible by 3 for _ in range(0, n): t = int(input()) #check for divisibility by 3 if t%k==0: #If t is divisible by 3 increment count by 1 count+=1 #print answer print(count)
def make_data(data='created some data here'): return data def concat_data(left, right): return left + right def divide_by_zero(): return 1 / 0 def _make_generator(): yield "beep" _GENERATOR = _make_generator() def returns_generator(): return _GENERATOR def returns_fresh_generator(): retu...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: return self.getLeaves(root1...
"""Bazel rule for loading external repository deps for J2CL.""" load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") _IO_BAZEL_RULES_CLOSURE_VERSION = "master" _BAZEL_SKYLIB_VERSION = "0.7.0" def load_j2cl_repo_deps(): http_archive( name = "io_bazel_rules_closure", strip_prefix = "rules_clo...
# dictionaries method II # dictionaries dont follow input ordering eng2sp={'one':'uno','two':'dos','three':'tres'} print(eng2sp) # dictionaries are mutable # changing elements in a dictionary eng2sp['three']='changed' # to delete dictionaries del eng2sp['two'] print(eng2sp) print(len(eng2sp))
class Solution: def XXX(self, x: int) -> int: y=0 while x!=0: if ((y<-214748364)or (y>214748364)) : return 0 y=10*y+x%10 x=x/10 return y
"""Level3 configuration information """ #: Filename used to record frames that error out during decoding. ERROR_FILENAME = 'LEVEL3.ERR' #: Expire messages that have not been seen in this many minutes #: The longest interval time between sending is 15 minutes for some #: image products, so time should be greater than t...
g = [ list("-A----"), list("-ADDDD"), list("-A----"), list("-A---S"), list("-A---S"), list("PP---S") ] a, d, p, s = 0, 0, 0, 0 uh, ha, hs = 0, 0, 0 for i in range(int(input())): x, y = map(int, input().split()) x, y = x-1, y-1 c = g[y][x] if c == "A": a += 1 elif c ...
class DictUtil(object): # def __init__(self): # pass # 将dto转dict def dto2dict(object): dict = {} for key in dir(object): value = getattr(object, key) if not key.startswith('__') and not callable(value): dict[key] = value return dict
#!/usr/bin/env python3 example = """35 20 15 25 47 40 62 55 65 95 102 117 150 182 127 219 299 277 309 576""" def execute(): with open('2020/input/9.txt') as inp: lines = inp.readlines() xmas = [l.strip() for l in lines if len(l.strip()) > 0] xmas = [int(e) for e in xmas] return first_invalid(x...
class Node: def __init__(self, dataval=None): self.dataval = dataval self.nextval = None class SingleLinkedList: def __init__(self): self.headval = None def traverse(self): printval = self.headval list_string = "" while printval is not None: list...
# model model = Model() i1 = Input("op1", "TENSOR_FLOAT32", "{2, 2, 2, 2}") i2 = Input("op2", "TENSOR_FLOAT32", "{2, 2, 2, 2}") act = Int32Scalar("act", 0) # an int32_t scalar fuse_activation i3 = Output("op3", "TENSOR_FLOAT32", "{2, 2, 2, 2}") model = model.Operation("MUL", i1, i2, act).To(i3) # Example 1. Input in o...
### Author: HIROSE Masaaki <hirose31 _at_ gmail.com> global mysql_options mysql_options = os.getenv('DSTAT_MYSQL') or '' global target_status global _basic_status global _extra_status _basic_status = ( ('Queries' , 'qps'), ('Com_select' , 'sel/s'), ('Com_insert' ...
findNumber = 40 guessNumber = 0 while guessNumber != findNumber: guessNumber = int(input('Guess a number : ')) if findNumber == guessNumber: print('You guess ! That number is :', guessNumber) elif findNumber > guessNumber: print('Find number is greater than', guessNumber) else: ...
'''def é_hipotenusa(a): cateto1 = 0 cateto2 = 0 for i in range(1, a): for j in range(1, a): if i ** 2 + j ** 2 == a ** 2: cateto1 = i cateto2 = j break if cateto1 != 0 and cateto2 != 0: return True else: ...
def contador(inicio, fim, passo): for num in range(inicio, fim, passo): print(num, end=' ') print("Segue a contagem de 1 até 10, de 1 em 1:") contador(1,11, 1) print() print('-'*30) print("Segue a contagem de 10 até 0, de 2 em 2:") contador(10,-1,-2) print() print('-'*30) ini = int(input("Digite o início...
""" Write a method to determine the number of ways to decode a string. A msg string consists of letters from A-Z, which represent numbers in the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Examples: decodeString("521") => 2 Possible ways of decoding: EBA, EU decodeString("113021") => 0 Take 0 or 30, neith...
class Solution: # @param A : list of integers # @param B : list of integers # @return an integer def coverPoints(self, A, B): moves = 0 for i in range(len(A) - 1): if abs(A[i] - A[i + 1]) <= abs(B[i] - B[i + 1]): moves += abs(B[i] - B[i + 1]) else:...
class Volume(): def __init__(self, name, total, maxiops, maxbw): self.name = name self.total = total self.maxiops = maxiops self.maxbw = maxbw
def _gradle_build_impl(ctx): args = [] outputs = [ctx.outputs.output_log] args += ["--log_file", ctx.outputs.output_log.path] args += ["--gradle_file", ctx.file.build_file.path] if (ctx.attr.output_file_destinations): for source, dest in zip(ctx.attr.output_file_sources, ctx.outputs.output_f...
######################################## # QUESTION ######################################## # A square of squares # You like building blocks. You especially like building blocks that are squares. And what you even like more, is to arrange them into a square of square building blocks! # However, sometimes, you can't ...
print('\033[36m='*12, '\033[32mLendo notas', '\033[36m='*12) n1 = float(input('\033[35mDigite sua primeira nota: ')) n2 = float(input('Digite sua segunda nota: ')) media = (n1+n2)/2 print(f'\033[36mA sua média é {media:.1f} e vc está:') if media < 5: print('\033[31mReprovado!') elif media >= 7: print('\033[32mA...
# Introduction to Python # Non homogeneous collection of elements list1 = [12,12.8,'This is a string'] # Printing the list print(list1) print(list1[0]) print(list1[1]) print(list1[2]) # Adding elements to the list list1.append(50) list1.insert(0,'Another string') print(list1[3]) # Updating List list1[1] = 20 ...
# -*- coding: utf-8 -*- __author__ = """Josh Yudaken""" __email__ = 'josh@smyte.com' __version__ = '0.1.0'
class Solution(object): @staticmethod def isPalindrome(x): if x < 0: return False temp = str(x) return temp == temp[::-1] # Press the green button in the gutter to run the script. if __name__ == '__main__': print(Solution.isPalindrome(121)) print(Solution.isPalindro...
n1 = float(input("digite a nota 1 do aluno: ")) n2 = float(input("digite a nota 2 do aluno: ")) m = (n1 + n2) / 2 print("\n") print("a media do aluno entre {} e {} é igual a {}" .format (n1, n2, m)) print("\n") print("A média entre {:.1f} e {:.1f} é igual a {:.1f}" . format (n1, n2, m))
# http://codingbat.com/prob/p129981 def make_out_word(out, word): return out[0:2] + word + out[2:4]
# ************************************************************************* # # Copyright (c) 2021 Andrei Gramakov. All rights reserved. # # This file is licensed under the terms of the MIT license. # For a copy, see: https://opensource.org/licenses/MIT # # site: https://agramakov.me # e-mail: mail@agramakov.me # #...
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") TOPO_COMMIT = "8866b0a658247683bd4b852839ce91c6ba60f6ac" TOPO_SHA = "dc63356c3d34de18b0afdf04cce01f6de83e2b7264de177e55c0595b05dbcd07" def generate_topo_device(): http_archive( name = "com_github_onosproject_onos_topo", urls = ["...
# OutputHTML.py # # This class outputs an HTML page as title headings and tables. # class OutputHTML: def __init__(self): styles = [ "<style>", "<!--", "caption {", "font-size: 16pt;", "padding-top: 1em;", "padding-bottom: 0.5em;", "}", "table {", "border: 1px solid black;", "border-coll...
class Solution: def isAnagram(self, s: str, t: str) -> bool: listS = list(s) listS.sort() listT = list(t) listT.sort() return listS == listT
myDict = { "hello": 13, "world": 31, "!" : 71 } # iterating over key-value pairs: for key, value in myDict.items(): print ("key = %s, value = %s" % (key, value)) # iterating over keys: for key in myDict: print ("key = %s" % key) # (is a shortcut for:) for key in myDict.keys(): print ("key = %s"...
input() e = str(input()).split() j = 1 for i in e: if len(i) == 3: if i[0] == 'O' and i[1] == 'B': print('OBI', end='') elif i[0] == 'U' and i[1] == 'R': print('URI', end='') else: print(i, end='') else: print(i, end='') if j < len(e): print(end=' ') j += 1 print()
DURACLOUD_USERNAME = "duracloud_user" DURACLOUD_PASSWORD = "duracloud_password" DURACLOUD_SPACE_ID = "my_streaming_space" DURACLOUD_PROTOCOL = "http" DURACLOUD_HOST = "localhost" DURACLOUD_PORT = "8080"
{ 'variables': { 'target_arch%': 'ia32', 'library%': 'static_library', # build chakracore as static library or dll 'component%': 'static_library', # link crt statically or dynamically 'chakra_dir%': 'core', 'icu_args%': '', 'icu_include_path%': '', 'linker_start_group%': '', 'linker_...
def som_div_propres(n): sum = 0 for div in range(1, n): if n % div == 0: sum += div return sum def est_presque_parfait(n): return som_div_propres(n) == n - 1 def affiche_presque_parfait(k): for i in range(2**k): if est_presque_parfait(i): print(i) affiche_presque_parfait(10)
summary_features = ['ts', 'event_type', 'SID', 'ECID', 'session', 'game_type', 'game_number', 'episode_number', 'score', 'lines_cleared', ...
# Module: Utility # Author: Ajay Arunachalam <ajay.arunachalam08@gmail.com> # License: MIT version_ = "1.10.0" def version(): return version_ def __version__(): return version_
# OpenWeatherMap API Key weather_api_key = "Insert API Key" # Google API Key g_key = "Insert API Key"
# This script generates a create table statement # for all of the feature columns of a TSV. # # This table is useful for creating select statements. # # usage # cat mywellformedtsv.tsv | python create_feature_table.py > create_feature_table.sql create_string = """ CREATE TABLE IF NOT EXISTS features ( index INT, ...
""" Helper functions for the url_breadcrumbs template tag. Configure the template tag to call these helper functions, or functions of your own, by defining URL_BREADCRUMBS_FUNCTIONS in your Django settings and setting the value to a list of one or more callables. Each callable in the URL_BREADCRUMBS_FUNCTIONS setting...
# 입력받은 리스트 a를 오름차순으로 정렬할 것 # a[i] < value < a[j]를 범위를 가진 새 리스트 b로 슬라이싱할 것 # 리스트 b의 b[k]를 리턴시킬 것 def Q(i, j, k): length_of_list, number_of_call = input().split(' ') input_list = [int(param) for param in input().split(' ')].sort() new_list = input_list[i - 1:] + input_list[:j - 1] for _ in range(num...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: ''' 给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历) ''' def levelOrderBottom(self, root: TreeNode): if not root: ...
''' Desenvolva um programa que faça a tabuada de um número qualquer inteiro que será digitado pelo usuário, mas a tabuada não deve necessariamente iniciar em 1 e terminar em 10, o valor inicial e final devem ser informados também pelo usuário, conforme exemplo abaixo: Montar a tabuada de: 5 Começar por: 4 Terminar em: ...
""" link: https://leetcode.com/problems/construct-quad-tree problem: 矩阵生成四叉树 solution: 递归分治 """ class Solution: def construct(self, grid: List[List[int]]) -> 'Node': def f(x: int, y: int, l: int) -> Node: if l == 1: return Node(grid[x][y], True, None, None, None, None) ...
a = '9' * 127 while ('333' in a) or ('999' in a): if ('333' in a): a = a.replace('333','9',1) else: a = a.replace('999','3',1) print(a)
def encode_message(enigma, message): print("Message:", message) message = enigma.encode(message) print("Encoded message:", message)
letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] for i in range(len(letters)-1): if(i%2!=0): continue; print(letters[i])
"""2017 - Day 13 Part 1: Packet Scanners. You need to cross a vast firewall. The firewall consists of several layers, each with a security scanner that moves back and forth across the layer. To succeed, you must not be detected by a scanner. By studying the firewall briefly, you are able to record (in your puzzle inp...
def test_stickers(app): app.wd.get("http://localhost/litecart") goods = app.wd.find_elements_by_css_selector(".product") for g in goods: stickers = g.find_elements_by_xpath(".//div[contains(@class, 'sticker')]") assert len(stickers) == 1
# -*- coding: utf-8 -*- """ Created on Thu Sep 10 17:04:30 2015 @author: Wasit """ def inc(x=1): yield x+1
print("*** Dimensions") print(ds.dims) print("\n\n*** Coordinates") print(ds.coords) print("\n\n*** Attributes") print(ds.attrs)
""" Desafio 049 Problema: Refaça o desafio 009, mostrando tabuada de um número que o usuário escolher, só que agora utilizando um laço FOR. Resolução do problema: """ tabuada = int(input('Informe a tabuada que deseja ver: ')) for c in range(0, 11): print('{} X {:2} = {}'.format(tabuada, c, ta...
CODE_EXP_TIME = 600 # Expiration time from Codes TOKEN_EXP_TIME = 1000 # Expiration time from Token. CODE_MIN_CHAR = 26 # Miximun number of characteres from Authentication Code CODE_MAX_CHAR = 26 # Maximun number of characteres from Authentication Code CODE_CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwx...
class PodcastError(Exception): """Base class for all podcast exceptions.""" pass class NoResults(PodcastError): """Raised when no results are found.""" pass
class Solution: def numberOfPatterns(self, m: int, n: int) -> int: skip = [[0] * 10 for _ in range(10)] skip[1][3] = skip[3][1] = 2 skip[1][7] = skip[7][1] = 4 skip[3][9] = skip[9][3] = 6 skip[7][9] = skip[9][7] = 8 skip[1][9] = skip[9][1] = skip[2][8] = skip[8][2] = ...
class load_api_1: name="hash1" def __init__(self, data=b''): self.data = data def update(self, data=b''): self.data += data def digest(self): return 1516152524156352132515252551426 def hexdigest(self): return hex(self.digest()) class load_api_2: name="hash2" ...
# -*- coding: utf-8 -*- """ @Author: Lyzhang @Date: @Description: """
#!/usr/bin/env python # Copyright (c) 2015: # Istituto Nazionale di Fisica Nucleare (INFN), Italy # # 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/LICENS...
""" An evaluator for problems from the toy-socket suite to demonstrate external evaluation of objectives and constraints in Python """ def evaluate_toy_socket_objectives(suite_name, func, instance, x): y0 = instance * 1e-5 if suite_name == 'toy-socket': if func == 1: # Function 1 is the su...
# Example variable assignment and comparison x = 12 y = 1 print(x == y) # Test dict label_map = {"anxiety": 0, "depression": 1, "positive_mood": 2, "negative_mood": 3} # Example SQL queries selection_query = ( "SELECT JID, Journal FROM `journal` " "WHERE status = %(unique_timestamp)s " ) # Example SQL queries ins...
def crevasse_water_depth(x,y,t,thck,topg,*etc): depth = 0.0 if (t >= 10.0): depth = 20.0 if (t >= 20.0): depth = 0.0 return depth
#----------------------------------------------------------------------------- # Runtime: 44ms # Memory Usage: # Link: #----------------------------------------------------------------------------- class Solution: def permute(self, nums: [int]) -> [[int]]: if len(nums) == 1: return [ nums ] ...
# Write a method to replace all spaces in a string with '%20'. # You may assume that the string has sufficient space at the end to hold the additional characters, # and that you are given the "true" length of the string. # (Note: if implementing in Java, please use a character array so that you can perform this ope...
class GetChannelError(Exception): """Raises when fetch channel is failed.""" pass class SendMessageToChannelFailed(Exception): """Raises when send message to channel is failed.""" pass class EditChannelFailed(Exception): """Raises when editing the channel is failed.""" pass class Delete...