content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def lcs(str1, str2): if not str1 or not str2: return "" x, xs, y, ys = str1[0], str1[1:], str2[0], str2[1:] if x == y: return x + lcs(xs, ys) else: return max(lcs(str1, ys), lcs(xs, str2), key=len) def ascii_deletion_distance(str1, str2): sub = lcs(str1,str2) x,y,= sum([o...
def lcs(str1, str2): if not str1 or not str2: return '' (x, xs, y, ys) = (str1[0], str1[1:], str2[0], str2[1:]) if x == y: return x + lcs(xs, ys) else: return max(lcs(str1, ys), lcs(xs, str2), key=len) def ascii_deletion_distance(str1, str2): sub = lcs(str1, str2) (x, y)...
class SimulationResult: def __init__(self, initialTileList, coordinateList, moves, attackStrategy): self.initialTileList = initialTileList self.coordinateList = coordinateList self.moves = moves self.attackStrategy = attackStrategy def SimulationResultString(self): ...
class Simulationresult: def __init__(self, initialTileList, coordinateList, moves, attackStrategy): self.initialTileList = initialTileList self.coordinateList = coordinateList self.moves = moves self.attackStrategy = attackStrategy def simulation_result_string(self): re...
""" Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-value...
""" Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms....
ALPHA = dict({ ('A', 'A'): 0, ('C', 'C'): 0, ('G', 'G'): 0, ('T', 'T'): 0, ('A', 'C'): 110, ('C', 'A'): 110, ('A', 'G'): 48, ('G', 'A'): 48, ('A', 'T'): 94, ('T', 'A'): 94, ('C', 'G'): 118, ('G', 'C'): 118, ('C', 'T'): 48, ('T', 'C'): 48, ('G', 'T'): 110, ...
alpha = dict({('A', 'A'): 0, ('C', 'C'): 0, ('G', 'G'): 0, ('T', 'T'): 0, ('A', 'C'): 110, ('C', 'A'): 110, ('A', 'G'): 48, ('G', 'A'): 48, ('A', 'T'): 94, ('T', 'A'): 94, ('C', 'G'): 118, ('G', 'C'): 118, ('C', 'T'): 48, ('T', 'C'): 48, ('G', 'T'): 110, ('T', 'G'): 110}) delta = 30
# # PySNMP MIB module Dell-BRIDGEMIBOBJECTS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Dell-BRIDGEMIBOBJECTS-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:55:28 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3....
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_size_constraint, value_range_constraint, constraints_union, constraints_intersection) ...
""" Hosoya triangle (originally Fibonacci triangle) is a triangular arrangement of numbers, where if you take any number it is the sum of 2 numbers above. First line is always 1, and second line is always {1 1}. This printHosoya function takes argument n which is the height of the triangle (number of lines). For ...
""" Hosoya triangle (originally Fibonacci triangle) is a triangular arrangement of numbers, where if you take any number it is the sum of 2 numbers above. First line is always 1, and second line is always {1 1}. This printHosoya function takes argument n which is the height of the triangle (number of lines). For ...
def enumerate_states(n_states, state_len, state, results): if n_states > 0: for sym in ('x', 'o', '_'): enumerate_states(n_states - 1, state_len, state + sym, results) if len(state) == state_len: results.append(state) state_len = 9 results = [] enumerate_states(state_len, state_...
def enumerate_states(n_states, state_len, state, results): if n_states > 0: for sym in ('x', 'o', '_'): enumerate_states(n_states - 1, state_len, state + sym, results) if len(state) == state_len: results.append(state) state_len = 9 results = [] enumerate_states(state_len, state_len, ...
class Token(object): Name = 'name' String = 'string' Number = 'number' Operator = 'operator' Boolean = 'boolean' Undefined = 'undefined' Null = 'null' Regex = 'regex' EOF = '(end)' LITERALS = [String, Number, Boolean, Regex, Null, Undefined] def __init__(self, source, type,...
class Token(object): name = 'name' string = 'string' number = 'number' operator = 'operator' boolean = 'boolean' undefined = 'undefined' null = 'null' regex = 'regex' eof = '(end)' literals = [String, Number, Boolean, Regex, Null, Undefined] def __init__(self, source, type, ...
super_value = '<value>' class Program: def __init__(self) -> None: self.ty_list = [] self.types = {} self.data_list = [] self.data = {} self.func_list = [] self.functions = {} def __str__(self) -> str: result = ".TYPE\n" for ty in self.ty_list...
super_value = '<value>' class Program: def __init__(self) -> None: self.ty_list = [] self.types = {} self.data_list = [] self.data = {} self.func_list = [] self.functions = {} def __str__(self) -> str: result = '.TYPE\n' for ty in self.ty_list: ...
class ExternalID: def __init__(self, config, connection): self._config = config self._connection = connection def get(self): return self._connection.get(url='/organisation/external-id') def create(self, data): return self._connection.post(url='/organisation/external-id', pay...
class Externalid: def __init__(self, config, connection): self._config = config self._connection = connection def get(self): return self._connection.get(url='/organisation/external-id') def create(self, data): return self._connection.post(url='/organisation/external-id', p...
result = 0 ROWS = 6 COLUMNS = 50 screen = [[0 for _ in range(COLUMNS)] for __ in range(ROWS)] with open("input.txt", "r") as input: for line in input: line = line.strip() parsing = line.split() if parsing[0] == "rect": [x, y] = [int(n) for n in parsing[1].split("x")] ...
result = 0 rows = 6 columns = 50 screen = [[0 for _ in range(COLUMNS)] for __ in range(ROWS)] with open('input.txt', 'r') as input: for line in input: line = line.strip() parsing = line.split() if parsing[0] == 'rect': [x, y] = [int(n) for n in parsing[1].split('x')] ...
expected_output = { 'switch': { "1": { 'fan': { "1": { 'state': 'ok' }, "2": { 'state': 'ok' }, "3": { 'state': 'ok' } }, ...
expected_output = {'switch': {'1': {'fan': {'1': {'state': 'ok'}, '2': {'state': 'ok'}, '3': {'state': 'ok'}}, 'power_supply': {'1': {'state': 'not present'}, '2': {'state': 'ok'}}}}}
DEBUG=False SQLALCHEMY_ECHO=False SQLALCHEMY_DATABASE_URI="sqlite:///:memory:" SQLALCHEMY_TRACK_MODIFICATIONS=False # FLASK_ADMIN_SWATCH="cerulean" MQTT_CLIENT_ID="shelfie_server" # MQTT_BROKER_URL="mosquitto" # MQTT_BROKER_PORT=1883 # MQTT_USERNAME="mosquitto_userid" # MQTT_PASSWORD="mosquitto_password" MQTT_KEEPALIVE...
debug = False sqlalchemy_echo = False sqlalchemy_database_uri = 'sqlite:///:memory:' sqlalchemy_track_modifications = False mqtt_client_id = 'shelfie_server' mqtt_keepalive = 15 mqtt_tls_enabled = False shelf_labels = ['a', 'b', 'c']
VERSION = "0.0.1" # Application ENVADMIN_DB_NAME = "envadmin.json" DEFAULT_TABLE = "__default"
version = '0.0.1' envadmin_db_name = 'envadmin.json' default_table = '__default'
class Solution: def closestValue(self, root: TreeNode, target: float) -> int: upper = root.val lower = root.val while root : if target > root.val : lower = root.val root = root.right elif target < root.val : upper = ro...
class Solution: def closest_value(self, root: TreeNode, target: float) -> int: upper = root.val lower = root.val while root: if target > root.val: lower = root.val root = root.right elif target < root.val: upper = root....
# Engine class Engine(object): def __init__(self, room_map): self.room_map = room_map def play(self): current_room = self.room_map.opening_room() last_room = self.room_map.next_room('finished') while current_room != last_room: next_room_name = current_room.enter() ...
class Engine(object): def __init__(self, room_map): self.room_map = room_map def play(self): current_room = self.room_map.opening_room() last_room = self.room_map.next_room('finished') while current_room != last_room: next_room_name = current_room.enter() ...
#!/usr/bin/env python # _*_ coding:utf-8 _*_ class Solution(object): def isValid(self, s): if not s: return True length = len(s) if length % 2 == 1: return False l = [''] * length last = -1 for c in s: if c == '(' or c == '{' or ...
class Solution(object): def is_valid(self, s): if not s: return True length = len(s) if length % 2 == 1: return False l = [''] * length last = -1 for c in s: if c == '(' or c == '{' or c == '[': last += 1 ...
lr = 0.0001 dropout_rate = 0.5 max_epoch = 3136 #3317 batch_size = 4096 w = 19 u = 9 glimpse_hidden = 128 bp_hidden = 128 glimpse_out = 128 nGlimpse = 7 lstm_cell_size = 128 action_hidden_1 = 256 action_hidden_2 = 256
lr = 0.0001 dropout_rate = 0.5 max_epoch = 3136 batch_size = 4096 w = 19 u = 9 glimpse_hidden = 128 bp_hidden = 128 glimpse_out = 128 n_glimpse = 7 lstm_cell_size = 128 action_hidden_1 = 256 action_hidden_2 = 256
contestsData={}; individualData={} while True: data=input() if data!="no more time": dataList=data.split(" -> ") username=dataList[0]; contest=dataList[1]; pts=dataList[2] contestFound=False; userFound=False for j in contestsData: if j==contest: ...
contests_data = {} individual_data = {} while True: data = input() if data != 'no more time': data_list = data.split(' -> ') username = dataList[0] contest = dataList[1] pts = dataList[2] contest_found = False user_found = False for j in contestsData: ...
""" Various string parsers. """ def floatArgs(s, cnt=None, failWith=None): """ Parse a comma-delimited list of floats. Args: s - the string to parse cnt - if set, the required number of floats. failWith - if set, a string to flesh out error strings. Returns: a...
""" Various string parsers. """ def float_args(s, cnt=None, failWith=None): """ Parse a comma-delimited list of floats. Args: s - the string to parse cnt - if set, the required number of floats. failWith - if set, a string to flesh out error strings. Returns: a...
# Copyright 2019 Katteli Inc. # TestFlows.com Open-Source Software Testing Framework (http://testflows.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/lice...
def wstrip(s, word, left=True, right=True): """Strip word from the beginning or the end of the string. By default strips from both sides. """ step = len(word) start_pos = None end_pos = None if not word: return s while True: found = False if left and s.startswith(...
# # PySNMP MIB module HPNSASCSI-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPNSASCSI-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:42:18 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, single_value_constraint, value_range_constraint, constraints_union, constraints_intersection) ...
""" Q104 Max Depth of Binary Tree Easy Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Note: A leaf is a node with no children. """ # Definition for a binary tree node. class TreeNode: def __init__(se...
""" Q104 Max Depth of Binary Tree Easy Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Note: A leaf is a node with no children. """ class Treenode: def __init__(self, x): self.val = x ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/3/13 20:49 # @Author : Steve Wu # @Site : # @File : util.py # @Software: PyCharm # @Github : https://github.com/stevehamwu # find word def find_word(keyword, sentence, start=0, end=-1, strict=False): """ word: str 'abc' sentence: lis...
def find_word(keyword, sentence, start=0, end=-1, strict=False): """ word: str 'abc' sentence: list ['a', 'b', 'cd'] return: start_index, end_index: 0, 2 """ if not sentence: return (-1, -1) if end == -1 or end > len(sentence): end = len(sentence) if keyword in sentence[s...
''' Merge sort of singly linked list Merge sort is often prefered for sorting a linked list. The slow random access performance of linked list make other algorithms such as quicksort perform poorly and others such as heapsort completely impossible. ''' #Code class Node: def __init__(self,data): ...
""" Merge sort of singly linked list Merge sort is often prefered for sorting a linked list. The slow random access performance of linked list make other algorithms such as quicksort perform poorly and others such as heapsort completely impossible. """ class Node: def __init__(self, data): ...
# regular if/else statement a = 10 if a > 5: print('a > 5') else: print('a <= 5') # if/elif/else a = 3 if a > 5: print('a > 5') elif a > 0: print('a > 0') else: print('a <= 0') # assignment with if/else - ternary statement b = 'a is positive' if a >= 0 else 'a is negative' print(b)
a = 10 if a > 5: print('a > 5') else: print('a <= 5') a = 3 if a > 5: print('a > 5') elif a > 0: print('a > 0') else: print('a <= 0') b = 'a is positive' if a >= 0 else 'a is negative' print(b)
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def insertionSortList(self, head: ListNode) -> ListNode: node = head shead = None dummy = ListNode(0, head) while node: ...
class Listnode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def insertion_sort_list(self, head: ListNode) -> ListNode: node = head shead = None dummy = list_node(0, head) while node: node_next = node.next ...
#import wx Q3_IMPL_QT="ui.pyqt5" Q3_IMPL_WX="ui.wx" #Q3_IMPL="wx" #default impl #global Q3_IMPL Q3_IMPL=Q3_IMPL_QT Q3_IMPL_SIM='sim.default' #from wx import ID_EXIT #from wx import ID_ABOUT ID_EXIT = 1 ID_ABOUT = 2 MAX_PINS = 256 MAX_INPUTS = 256 MAX_OUTPUTS = 256 MAX_DYNAMICS = 256 MAX_SIGNAL_SIZE = 64
q3_impl_qt = 'ui.pyqt5' q3_impl_wx = 'ui.wx' q3_impl = Q3_IMPL_QT q3_impl_sim = 'sim.default' id_exit = 1 id_about = 2 max_pins = 256 max_inputs = 256 max_outputs = 256 max_dynamics = 256 max_signal_size = 64
# lec11prob5.py # # Lecture 11 - Classes # Problem 5 # # edX MITx 6.00.1x # Introduction to Computer Science and Programming Using Python ''' Consider the following code from the last lecture video. Your task is to define the following two methods for the intSet class: 1. Define an intersect method that returns a...
""" Consider the following code from the last lecture video. Your task is to define the following two methods for the intSet class: 1. Define an intersect method that returns a new intSet containing elements that appear in both sets. In other words, s1.intersect(s2) would return a new intSet of i...
# This test is here so we don't get a non-zero code from Pytest in Travis CI build. def test_dummy(): assert 5 == 5
def test_dummy(): assert 5 == 5
__metaclass__ = type #classes inherting from _UIBase are expected to also inherit UIBase separately. class _UIBase(object): id_gen = 0 def __init__(self): #protocol self._content_id = _UIBase.id_gen _UIBase.id_gen += 1 def _copy_values_deep(self, other): pass def _clone...
__metaclass__ = type class _Uibase(object): id_gen = 0 def __init__(self): self._content_id = _UIBase.id_gen _UIBase.id_gen += 1 def _copy_values_deep(self, other): pass def _clone(self): result = self.__class__() result._copy_values_deep(self) return ...
#https://www.codewars.com/kata/the-office-ii-boredom-score """Every now and then people in the office moves teams or departments. Depending what people are doing with their time they can become more or less boring. Time to assess the current team. You will be provided with an object(staff) containing the staff names a...
"""Every now and then people in the office moves teams or departments. Depending what people are doing with their time they can become more or less boring. Time to assess the current team. You will be provided with an object(staff) containing the staff names as keys, and the department they work in as values. Each de...
"""Docstring. Details """ __all__ = ('InvalidParameterError') class InvalidParameterError(Exception): """A specific exception for invalid parameter.""" def __init__(self, message): # pylint:disable=W0235 """Init function.""" super().__init__(message)
"""Docstring. Details """ __all__ = 'InvalidParameterError' class Invalidparametererror(Exception): """A specific exception for invalid parameter.""" def __init__(self, message): """Init function.""" super().__init__(message)
#!/usr/bin/env python3 class Node(object): def __init__(self, ip, port): self.ip = ip self.port=port self.name="Node: %s:%d" % (ip, port) def __name__(self): return self.name def start(self): return def stop(self): return
class Node(object): def __init__(self, ip, port): self.ip = ip self.port = port self.name = 'Node: %s:%d' % (ip, port) def __name__(self): return self.name def start(self): return def stop(self): return
description = 'PANDA Heusler-analyzer' group = 'lowlevel' includes = ['monofoci', 'monoturm', 'panda_mtt'] extended = dict(dynamic_loaded = True) devices = dict( ana_heusler = device('nicos.devices.tas.Monochromator', description = 'PANDA\'s Heusler ana', unit = 'A-1', theta = 'ath', ...
description = 'PANDA Heusler-analyzer' group = 'lowlevel' includes = ['monofoci', 'monoturm', 'panda_mtt'] extended = dict(dynamic_loaded=True) devices = dict(ana_heusler=device('nicos.devices.tas.Monochromator', description="PANDA's Heusler ana", unit='A-1', theta='ath', twotheta='att', focush='afh_heusler', focusv=No...
#!/usr/bin/env python ############################################################################# ## # This file is part of Taurus ## # http://taurus-scada.org ## # Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain ## # Taurus is free software: you can redistribute it and/or modify # it under the terms of t...
""" This module contains some Taurus-wide default configurations. The idea is that the final user may edit the values here to customize certain aspects of Taurus. """ t_form_custom_widget_map = {'SimuMotor': ('sardana.taurus.qt.qtgui.extra_pool.PoolMotorTV', (), {}), 'Motor': ('sardana.taurus.qt.qtgui.extra_pool.PoolM...
# -*- coding: utf-8 -*- def test_cookies_group(testdir): result = testdir.runpytest( '--help', ) # fnmatch_lines does an assertion internally result.stdout.fnmatch_lines([ 'cookies:', '*--template=TEMPLATE*', ])
def test_cookies_group(testdir): result = testdir.runpytest('--help') result.stdout.fnmatch_lines(['cookies:', '*--template=TEMPLATE*'])
class TestFixupsToPywb: # Test random fixups we've made to improve `pywb` behavior def test_we_do_not_try_and_rewrite_rel_manifest(self, proxied_content): # The '_id' here means a transparent rewrite, and no insertion of # wombat stuff assert ( '<link rel="manifest" href="/p...
class Testfixupstopywb: def test_we_do_not_try_and_rewrite_rel_manifest(self, proxied_content): assert '<link rel="manifest" href="/proxy/id_/http://localhost:8080/manifest.json"' in proxied_content def test_we_do_rewrite_other_rels(self, proxied_content): assert '<link rel="other" href="/prox...
def transpose(the_array): ret = map(list, zip(*the_array)) ret = list(ret) return ret def get_unique_list(dict_list, key="id"): # https://stackoverflow.com/questions/10024646/how-to-get-list-of-objects-with-unique-attribute seen = set() return [seen.add(d[key]) or d for d in dict_list if d a...
def transpose(the_array): ret = map(list, zip(*the_array)) ret = list(ret) return ret def get_unique_list(dict_list, key='id'): seen = set() return [seen.add(d[key]) or d for d in dict_list if d and d[key] not in seen] def color_variants(hex_colors, brightness_offset=1): return [color_variant(...
#################################################### # package version -- named "pkgdir.testapi" # this function is loaded and run by testapi.c; # change this file between calls: auto-reload mode # gets the new version each time 'func' is called; # for the test, the last line was changed to: # return x + y...
def func(x, y): return x + y
"""Author @Sowjanya""" """Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.""" class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: hashMap = {} for i,n in enumerate(nums): if (target-n) in...
"""Author @Sowjanya""" 'Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.' class Solution: def two_sum(self, nums: List[int], target: int) -> List[int]: hash_map = {} for (i, n) in enumerate(nums): if target - n in...
def part1(input) -> int: count1 = count3 = 0 for i in range(len(input) - 1): if input[i+1] - input[i] == 1: count1 += 1 elif input[i+1] - input[i] == 3: count3 += 1 return count1 * count3 def part2(input) -> int: valid = {} def possibleArrangements(input) -> ...
def part1(input) -> int: count1 = count3 = 0 for i in range(len(input) - 1): if input[i + 1] - input[i] == 1: count1 += 1 elif input[i + 1] - input[i] == 3: count3 += 1 return count1 * count3 def part2(input) -> int: valid = {} def possible_arrangements(inpu...
#!/usr/bin/python # -*- coding: UTF-8 -*- # Function: formatted text document by adding newline # Author: king def main(): print('This python script help you formatted text document.') fin = input('Input the file location : ') fout = input('Input the new file location: ') print('begin...') MAX_SI...
def main(): print('This python script help you formatted text document.') fin = input('Input the file location : ') fout = input('Input the new file location: ') print('begin...') max_size = 78 newlines = '' with open(fin, encoding='utf-8') as fp: lines = fp.readlines() for l...
s=0 i=0 v=0 while v>=0: v = float(input("digite o valor da idade: ")) if v>=0: s = s+v print(s) i = i+1 print(i) r = s/(i) print(r) print(r)
s = 0 i = 0 v = 0 while v >= 0: v = float(input('digite o valor da idade: ')) if v >= 0: s = s + v print(s) i = i + 1 print(i) r = s / i print(r) print(r)
__author__ = 'zz' class BaseVerifier: def verify(self, value): raise NotImplementedError class IntVerifier(BaseVerifier): def __index__(self, upper, bot): self.upper = upper self.bot = bot def verify(self, value): if isinstance(value, int): return False ...
__author__ = 'zz' class Baseverifier: def verify(self, value): raise NotImplementedError class Intverifier(BaseVerifier): def __index__(self, upper, bot): self.upper = upper self.bot = bot def verify(self, value): if isinstance(value, int): return False ...
# # LeetCode # Algorithm 141 Linked List Cycle # # Rick Lan, May 6, 2017. # See LICENSE # # Your runtime beats 69.76 % of python submissions. # # # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def...
class Solution(object): def has_cycle(self, head): """ :type head: ListNode :rtype: bool """ if head == None: return False crash = list_node(0) p = head p = p.next while p != None: if p == crash: return ...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param {ListNode} head # @param {integer} m # @param {integer} n # @return {ListNode} def reverseBetween(self, head, m, n): dumpy = ListNode(0) ...
class Listnode: def __init__(self, x): self.val = x self.next = None class Solution: def reverse_between(self, head, m, n): dumpy = list_node(0) dumpy.next = head pre = dumpy diff = n - m while m > 1: pre = pre.next m -= 1 ...
class Solution: def twoSum(self, nums, target: int): d = {} for i in range(len(nums)): j = target - nums[i] if j in d: return [d[j], i] else: d[nums[i]] = i s = Solution() print(s.twoSum( [3, 2, 4], 6))
class Solution: def two_sum(self, nums, target: int): d = {} for i in range(len(nums)): j = target - nums[i] if j in d: return [d[j], i] else: d[nums[i]] = i s = solution() print(s.twoSum([3, 2, 4], 6))
""" Addoperation class """ class AddOperation: """ Class for add operation """ def __init__(self, num1, num2): """ Init function """ self.num1 = num1 self.num2 = num2 self.result = 0 def process(self): """ Process function to perform operation""" self.resu...
""" Addoperation class """ class Addoperation: """ Class for add operation """ def __init__(self, num1, num2): """ Init function """ self.num1 = num1 self.num2 = num2 self.result = 0 def process(self): """ Process function to perform operation""" self.resul...
def tri_bulle(L): pointer = 0 while pointer < len(L): left = 0 right = 1 while right < len(L) - pointer: if L[right] < L[left]: L[left], L[right] = L[right], L[left] left += 1 right += 1 pointer += 1 return L print(tri_bulle([8, -1, 2, 5, 3, -2]))
def tri_bulle(L): pointer = 0 while pointer < len(L): left = 0 right = 1 while right < len(L) - pointer: if L[right] < L[left]: (L[left], L[right]) = (L[right], L[left]) left += 1 right += 1 pointer += 1 return L print(tri_b...
""" Brightness """ class Brightness(object): """ Brightness facade """ def current_level(self): return self._current_level() def set_level(self, level): return self._set_level(level) # private def _current_level(self): raise NotImplementedError() def _set_le...
""" Brightness """ class Brightness(object): """ Brightness facade """ def current_level(self): return self._current_level() def set_level(self, level): return self._set_level(level) def _current_level(self): raise not_implemented_error() def _set_level(self, lev...
t = int(input()) for case in range(t): s = input() numbers = '0123456789' if (s[0] == 'R' and (s[1] in numbers) and ('C' in s)): iC = 0 for i in range(len(s)): if (s[i] == 'C'): iC = i break row = s[1:iC] col = int(s[iC +...
t = int(input()) for case in range(t): s = input() numbers = '0123456789' if s[0] == 'R' and s[1] in numbers and ('C' in s): i_c = 0 for i in range(len(s)): if s[i] == 'C': i_c = i break row = s[1:iC] col = int(s[iC + 1:]) c...
# # PySNMP MIB module STACK-TOP (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/STACK-TOP # Produced by pysmi-0.3.4 at Wed May 1 15:10:55 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...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, value_size_constraint, value_range_constraint, single_value_constraint, constraints_intersection) ...
class Solution: def distributeCandies(self, candies): """ :type candies: List[int] :rtype: int """ if len(candies) == 0 or len(candies)%2 !=0: return 0 h = set() for i in candies: h.add(i) l=len(candies)/2 if(len(h)>l): ...
class Solution: def distribute_candies(self, candies): """ :type candies: List[int] :rtype: int """ if len(candies) == 0 or len(candies) % 2 != 0: return 0 h = set() for i in candies: h.add(i) l = len(candies) / 2 if le...
all_bps = """BFBBBBBLLR BBFFBBFRRL FBFBFFFRRL BBFFFBFRRL BFFBFBFRLL FFBBBFBLRL BFFFBFFLLR FBFFFFBLRR FBFFBBBRRR BFFBFFFLLR BFFFFFBLLL FFBBFFBLRR BFFFFFBRLR FBFBFBFLLL FFBFBFFLLL BBFFFFFLLL FFFBBBFLLL BBFFBFBLLR FFBFBFBRRR BFFBFFFRRR BBFFBFBRLR FFFBFBFLRL BBFFBBBLRR FBBFFFFLLR BBBFBBFLLL BFFFFBBRLL FBBFBFBRRL FFBBBFFRRR...
all_bps = 'BFBBBBBLLR\nBBFFBBFRRL\nFBFBFFFRRL\nBBFFFBFRRL\nBFFBFBFRLL\nFFBBBFBLRL\nBFFFBFFLLR\nFBFFFFBLRR\nFBFFBBBRRR\nBFFBFFFLLR\nBFFFFFBLLL\nFFBBFFBLRR\nBFFFFFBRLR\nFBFBFBFLLL\nFFBFBFFLLL\nBBFFFFFLLL\nFFFBBBFLLL\nBBFFBFBLLR\nFFBFBFBRRR\nBFFBFFFRRR\nBBFFBFBRLR\nFFFBFBFLRL\nBBFFBBBLRR\nFBBFFFFLLR\nBBBFBBFLLL\nBFFFFBBRL...
def Setup(Settings,DefaultModel): # set1-test_of_models_against_datasets/models_30m_640px.py Settings["experiment_name"] = "set1c_Models_Test_30m_640px" Settings["graph_histories"] = ['together', [0,1], [1,2], [0,2]] n=0 # 5556x_minlen30_640px 5556x_minlen20_640px 5556x_reslen20_299px 5556x_resle...
def setup(Settings, DefaultModel): Settings['experiment_name'] = 'set1c_Models_Test_30m_640px' Settings['graph_histories'] = ['together', [0, 1], [1, 2], [0, 2]] n = 0 Settings['models'][n]['dataset_name'] = '5556x_minlen30_640px' Settings['models'][n]['dump_file_override'] = 'SegmentsData_marked_R1...
#!/usr/bin/env python3 DEV = "/dev/input/event19" CONTROLS = { 144: [ "SELECT", "START", "CROSS", "CIRCLE", "SQUARE", "TRIANGLE", "UP", "RIGHT", "DOWN", "LEFT", ], 96: [ "CENTER", ] } def trial(n: int) -> None: for size in CONTROLS.keys(): for control in CONTROLS[size]: print(f"PRE...
dev = '/dev/input/event19' controls = {144: ['SELECT', 'START', 'CROSS', 'CIRCLE', 'SQUARE', 'TRIANGLE', 'UP', 'RIGHT', 'DOWN', 'LEFT'], 96: ['CENTER']} def trial(n: int) -> None: for size in CONTROLS.keys(): for control in CONTROLS[size]: print(f'PRESS {control}') with open(DEV, 'r...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None # class Solution(object): # def swapPairs(self, head): # """ # :type head: ListNode # :rtype: ListNode # """ class Solution(objec...
class Solution(object): def swap_pairs(self, head): dummy_head = list_node(-1) dummyHead.next = head (prev, p) = (dummyHead, head) while p != None and p.next != None: (q, r) = (p.next, p.next.next) prev.next = q q.next = p p.next = r ...
# Demo Python Functions - Keyword Arguments ''' Keyword Arguments You can also send arguments with the key = value syntax. This way the order of the arguments does not matter. ''' # Example: def my_function(child3, child2, child1): print("The youngest child is " + child3) my_function(child1 = "Emil", child2 = ...
""" Keyword Arguments You can also send arguments with the key = value syntax. This way the order of the arguments does not matter. """ def my_function(child3, child2, child1): print('The youngest child is ' + child3) my_function(child1='Emil', child2='Tobias', child3='Linus')
N, L = input().split() N = int(N) L = int(L) #print(N, L) s_list = input().split() citations = [ int(s) for s in s_list] def findHIndex(citations): citations.sort(reverse=True) N = len(citations) res = N for i in range(N): if citations[i]<i+1: res = i break retu...
(n, l) = input().split() n = int(N) l = int(L) s_list = input().split() citations = [int(s) for s in s_list] def find_h_index(citations): citations.sort(reverse=True) n = len(citations) res = N for i in range(N): if citations[i] < i + 1: res = i break return res k = ...
####################################### ## ADD SOME COLOR # pinched and tweaked from https://github.com/impshum/Multi-Quote/blob/master/run.py class color: white, cyan, blue, red, green, yellow, magenta, black, gray, bold = '\033[0m', '\033[96m','\033[94m', '\033[91m','\033[92m','\033[93m','\033[95m', '\033[30m', '\0...
class Color: (white, cyan, blue, red, green, yellow, magenta, black, gray, bold) = ('\x1b[0m', '\x1b[96m', '\x1b[94m', '\x1b[91m', '\x1b[92m', '\x1b[93m', '\x1b[95m', '\x1b[30m', '\x1b[30m', '\x1b[1m')
def lex_lambda_handler(event, context): intent_name = event['currentIntent']['name'] parameters = event['currentIntent']['slots'] attributes = event['sessionAttributes'] if event['sessionAttributes'] is not None else {} response = init_contact(intent_name, parameters, attributes) return response ...
def lex_lambda_handler(event, context): intent_name = event['currentIntent']['name'] parameters = event['currentIntent']['slots'] attributes = event['sessionAttributes'] if event['sessionAttributes'] is not None else {} response = init_contact(intent_name, parameters, attributes) return response de...
# Copyright (C) 2018 Henrique Pereira Coutada Miranda # All rights reserved. # # This file is part of yambopy # # """ submodule with classes to read BSE optical absorption spectra claculations and information about the excitonic states """
""" submodule with classes to read BSE optical absorption spectra claculations and information about the excitonic states """
BLACK = (0, 0, 0) GREY = (142, 142, 142) RED = (200, 72, 72) ORANGE = (198, 108, 58) BROWN = (180, 122, 48) YELLOW = (162, 162, 42) GREEN = (72, 160, 72) BLUE = (66, 72, 200)
black = (0, 0, 0) grey = (142, 142, 142) red = (200, 72, 72) orange = (198, 108, 58) brown = (180, 122, 48) yellow = (162, 162, 42) green = (72, 160, 72) blue = (66, 72, 200)
#!/usr/bin/env python def square_gen(is_true): i = 0 while True: yield i**2 i += 1 g = square_gen(False) print(next(g)) print(next(g)) print(next(g))
def square_gen(is_true): i = 0 while True: yield (i ** 2) i += 1 g = square_gen(False) print(next(g)) print(next(g)) print(next(g))
class A: def __bool__(self): print('__bool__') return True def __len__(self): print('__len__') return 1 class B: def __len__(self): print('__len__') return 0 print(bool(A())) print(len(A())) print(bool(B())) print(len(B()))
class A: def __bool__(self): print('__bool__') return True def __len__(self): print('__len__') return 1 class B: def __len__(self): print('__len__') return 0 print(bool(a())) print(len(a())) print(bool(b())) print(len(b()))
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None c = 0 class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: global c return_head = head prev = ListNode(0) prev.next = return_head ...
class Listnode: def __init__(self, x): self.val = x self.next = None c = 0 class Solution: def remove_nth_from_end(self, head: ListNode, n: int) -> ListNode: global c return_head = head prev = list_node(0) prev.next = return_head c = 0 print(n) ...
d1 = {1:'Sugandh', 2:'Divya', 3:'Mintoo'} print("deleting a key from the dictionary...") del d1[3] print(d1) print("deleting the same key again...") del d1[3] print(d1)
d1 = {1: 'Sugandh', 2: 'Divya', 3: 'Mintoo'} print('deleting a key from the dictionary...') del d1[3] print(d1) print('deleting the same key again...') del d1[3] print(d1)
class ObtenedorDeEntrada: def getEntrada(self): f = open ('Entrada.txt','r') entrada = f.read() print(entrada) f.close() return entrada #input("Introduce el texto\n")
class Obtenedordeentrada: def get_entrada(self): f = open('Entrada.txt', 'r') entrada = f.read() print(entrada) f.close() return entrada
{ "name": "train-nn", "s3_path": "s3://tht-spark/executables/SDG_Data_Technologies_Model.py", "executors": 2, }
{'name': 'train-nn', 's3_path': 's3://tht-spark/executables/SDG_Data_Technologies_Model.py', 'executors': 2}
# parameters of the system # data files temp = np.load('./data/temp_norm.npy') y = np.load('./data/total_load_norm.npy') load_meters = np.load('./data/load_meters_norm.npy') # system parameters T, num_meters = load_meters.shape num_samples = T # training parameters hist_samples = 24 train_samples = int(0.8 * num_...
temp = np.load('./data/temp_norm.npy') y = np.load('./data/total_load_norm.npy') load_meters = np.load('./data/load_meters_norm.npy') (t, num_meters) = load_meters.shape num_samples = T hist_samples = 24 train_samples = int(0.8 * num_samples) test_samples_a = int(0.1 * num_samples) use_mse = False if use_mse: loss_...
datas = { 'style' : 'sys', 'parent' :'boost', 'prefix' :['boost','simd'], }
datas = {'style': 'sys', 'parent': 'boost', 'prefix': ['boost', 'simd']}
class Solution: def maxProfit(self, prices: List[int]) -> int: profit = 0 buy = math.inf for price in prices: if price < buy: buy = price elif (p := price - buy) > profit: profit = p return profit
class Solution: def max_profit(self, prices: List[int]) -> int: profit = 0 buy = math.inf for price in prices: if price < buy: buy = price elif (p := (price - buy)) > profit: profit = p return profit
def maior_elemento(lista): elemento_ref = lista[0] maior_elemento = 0 for i in lista: if i >= elemento_ref: maior_elemento = i return maior_elemento
def maior_elemento(lista): elemento_ref = lista[0] maior_elemento = 0 for i in lista: if i >= elemento_ref: maior_elemento = i return maior_elemento
#!/usr/bin/env python # Copyright JS Foundation and other contributors, http://js.foundation # # 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....
class _Constants: default_test_count = 100 default_seed = 10000 test_case_in_a_file = 700 operand_count_max = 11 operand_count_min = 2 max = (1 << 53) - 1 min = -1 * max bitmax = (1 << 31) - 1 bitmin = -bitmax - 1 uint32max = (1 << 32) - 1 uint32min = 0 bitmax_exposant = ...
pjs_setting = {"hyperopt" :{"AGENT_TYPE":'"randomwalk"', "CIRCLE_TYPE":'"line"', "min_n_circle":1000, "max_n_circle":4000}, "gaopt" :{"AGENT_TYPE":'"ga"', "CIRCLE_TYPE":'"normal_sw"', "min_n_circle":500, "max_n_circle":3000}, "bayesopt" :{"AGENT_TYPE":'"randomwalk"', "CIRCLE_TYPE...
pjs_setting = {'hyperopt': {'AGENT_TYPE': '"randomwalk"', 'CIRCLE_TYPE': '"line"', 'min_n_circle': 1000, 'max_n_circle': 4000}, 'gaopt': {'AGENT_TYPE': '"ga"', 'CIRCLE_TYPE': '"normal_sw"', 'min_n_circle': 500, 'max_n_circle': 3000}, 'bayesopt': {'AGENT_TYPE': '"randomwalk"', 'CIRCLE_TYPE': '"quad"', 'min_n_circle': 10...
# 28. Implement strStr() class Solution: def strStr(self, haystack: str, needle: str) -> int: """ Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. """ if not len(needle): return 0 s = needle + '$' +...
class Solution: def str_str(self, haystack: str, needle: str) -> int: """ Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. """ if not len(needle): return 0 s = needle + '$' + haystack n = le...
__version__ = "11.0.2-2022.02.08" if __name__ == "__main__": print(__version__)
__version__ = '11.0.2-2022.02.08' if __name__ == '__main__': print(__version__)
array = [3,5,-4,8,11,1,-1,6] targetSum = 10 # def twoNumberSum(array, targetSum): # # Write your code here. # arrayOut = [] # for num1 in array: # for num2 in array: # if (num1+num2==targetSum) and (num1 != num2): # arrayOut.append(num1) # arrayOut.append...
array = [3, 5, -4, 8, 11, 1, -1, 6] target_sum = 10 def two_number_sum(array, targetSum): array_out = [] new_dict = {} for num1 in array: num2 = targetSum - num1 if num2 in newDict: arrayOut.append(num1) arrayOut.append(num2) final_list = sorted(arrayOut)...
# Print multiplication tables # 1 2 3 4 .. 10 # 2 4 6 8 20 # 3 6 9 12 30 # .. .. .. .. .. for i in range(1, 11): for j in range(1, 11): print(str(j * i) + '\t', end='') pri...
for i in range(1, 11): for j in range(1, 11): print(str(j * i) + '\t', end='') print('')
# -------------- ##File path for the file file_path #Code starts here def read_file(path): file=open(file_path,'r') sentence=file.readline() file.close() return sentence sample_message=read_file(file_path) # -------------- #Code starts here file_path_1,file_path_2 message_1=read_file(...
file_path def read_file(path): file = open(file_path, 'r') sentence = file.readline() file.close() return sentence sample_message = read_file(file_path) (file_path_1, file_path_2) message_1 = read_file(file_path_1) message_2 = read_file(file_path_2) print(message_1) print(message_2) def fuse_msg(messa...
# Python > Sets > The Captain's Room # Out of a list of room numbers, determine the number of the captain's room. # # https://www.hackerrank.com/challenges/py-the-captains-room/problem # k = int(input()) rooms = list(map(int, input().split())) a = set() room_group = set() for room in rooms: if room in a: ...
k = int(input()) rooms = list(map(int, input().split())) a = set() room_group = set() for room in rooms: if room in a: room_group.add(room) else: a.add(room) a = a - room_group print(a.pop())
class Config: device = 'cpu' RBF_url = "https://github.com/Practical-AI/deep_utils/releases/download/0.2.0/version-RFB-320.pth" RBF_cache = 'weights/vision/face_detection/ultra-light/torch/RBF/version-RFB-320.pth' RBF = None slim_url = "https://github.com/Practical-AI/deep_utils/releases/download/0....
class Config: device = 'cpu' rbf_url = 'https://github.com/Practical-AI/deep_utils/releases/download/0.2.0/version-RFB-320.pth' rbf_cache = 'weights/vision/face_detection/ultra-light/torch/RBF/version-RFB-320.pth' rbf = None slim_url = 'https://github.com/Practical-AI/deep_utils/releases/download/0....
alphabet = """1 2 3 4 5 6 7 8 9 10 11 12 """
alphabet = '1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n'
'''https://leetcode.com/problems/unique-paths/''' class Solution: def uniquePaths(self, m: int, n: int) -> int: dp = [1 for i in range(m)] for i in range(1,n): for j in range(1,m): dp[j] += dp[j-1] return dp[-1]
"""https://leetcode.com/problems/unique-paths/""" class Solution: def unique_paths(self, m: int, n: int) -> int: dp = [1 for i in range(m)] for i in range(1, n): for j in range(1, m): dp[j] += dp[j - 1] return dp[-1]
# Time: O(n) # Space: O(1) class Solution(object): def optimalDivision(self, nums): """ :type nums: List[int] :rtype: str """ if len(nums) == 1: return str(nums[0]) if len(nums) == 2: return str(nums[0]) + "/" + str(nums[1]) result = ...
class Solution(object): def optimal_division(self, nums): """ :type nums: List[int] :rtype: str """ if len(nums) == 1: return str(nums[0]) if len(nums) == 2: return str(nums[0]) + '/' + str(nums[1]) result = [str(nums[0]) + '/(' + str(...
experiments_20 = { 'data': {'n_experiments': 20, 'max_set_size': 500, 'network_filename': 'H_sapiens.net', #'S_cerevisiae.net' 'directed_interactions_filename': 'KPI_dataset', 'sources_filename': 'drug_targets.txt', 'terminals_filename': 'drug_expressions.txt', ...
experiments_20 = {'data': {'n_experiments': 20, 'max_set_size': 500, 'network_filename': 'H_sapiens.net', 'directed_interactions_filename': 'KPI_dataset', 'sources_filename': 'drug_targets.txt', 'terminals_filename': 'drug_expressions.txt', 'load_prop_scores': False, 'save_prop_scores': False, 'balance_dataset': True, ...
""" Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. """ org = [1,2,3,4,5,6,7] steps = 3 lis1 = org[steps+1:] l...
""" Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. """ org = [1, 2, 3, 4, 5, 6, 7] steps = 3 lis1 = org[steps ...
# pylint: disable=missing-docstring TEST = map(str, (1, 2, 3)) # [bad-builtin] TEST1 = filter(str, (1, 2, 3)) # [bad-builtin]
test = map(str, (1, 2, 3)) test1 = filter(str, (1, 2, 3))
expected = [ { "xlink_href": "elife00013inf001", "type": "inline-graphic", "position": 1, "ordinal": 1, } ]
expected = [{'xlink_href': 'elife00013inf001', 'type': 'inline-graphic', 'position': 1, 'ordinal': 1}]
APIYNFLAG_YES = "Y" APIYNFLAG_NO = "N" APILOGLEVEL_NONE = "N" APILOGLEVEL_ERROR = "E" APILOGLEVEL_WARNING = "W" APILOGLEVEL_DEBUG = "D" TAPI_COMMODITY_TYPE_NONE = "N" TAPI_COMMODITY_TYPE_SPOT = "P" TAPI_COMMODITY_TYPE_FUTURES = "F" TAPI_COMMODITY_TYPE_OPTION = "O" TAPI_COMMODITY_TYPE_SPREAD_MONTH = "S" TAPI_COMMODITY_T...
apiynflag_yes = 'Y' apiynflag_no = 'N' apiloglevel_none = 'N' apiloglevel_error = 'E' apiloglevel_warning = 'W' apiloglevel_debug = 'D' tapi_commodity_type_none = 'N' tapi_commodity_type_spot = 'P' tapi_commodity_type_futures = 'F' tapi_commodity_type_option = 'O' tapi_commodity_type_spread_month = 'S' tapi_commodity_t...
# # PySNMP MIB module ASCEND-MIBSCRTY-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBSCRTY-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:28:15 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
(configuration,) = mibBuilder.importSymbols('ASCEND-MIB', 'configuration') (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_size_const...
while True: s = input("Ukucaj nesto: ") if s == "izlaz": break if len(s) < 3: print("Previse je kratko.") continue print("Input je zadovoljavajuce duzine.") #mozete zadavati druge komande za neki rad ovdej
while True: s = input('Ukucaj nesto: ') if s == 'izlaz': break if len(s) < 3: print('Previse je kratko.') continue print('Input je zadovoljavajuce duzine.')
pancakes = int(input()) if pancakes > 3: print("Yum!") else: #if pancakes < 3: print("Still hungry!")
pancakes = int(input()) if pancakes > 3: print('Yum!') else: print('Still hungry!')
users_calculation = {} def request_addition(user, num1, num2): users_calcs = users_calculation.get(user) if (users_calcs is None): users_calcs = list() users_calcs.append(num1+num2) users_calculation[user] = users_calcs def get_last_calculation(user): users_calcs = users_calculation.ge...
users_calculation = {} def request_addition(user, num1, num2): users_calcs = users_calculation.get(user) if users_calcs is None: users_calcs = list() users_calcs.append(num1 + num2) users_calculation[user] = users_calcs def get_last_calculation(user): users_calcs = users_calculation.get(us...
def x(a, b, c): p = 5 b = int(x) print(b)
def x(a, b, c): p = 5 b = int(x) print(b)
# from https://en.wikipedia.org/wiki/Test_functions_for_optimization # # takes input parameters x,y # returns value in "ans" # optimal minimum at f(3,0.5) = 0 # parameter range is -4.5 <= x,y <= 4.5 def evaluate(x,y): return (1.5 - x + x*y)**2 + (2.25 - x + x*y*y)**2 + (2.625 - x + x*y*y*y)**2 def run(self,Inputs):...
def evaluate(x, y): return (1.5 - x + x * y) ** 2 + (2.25 - x + x * y * y) ** 2 + (2.625 - x + x * y * y * y) ** 2 def run(self, Inputs): if abs(self.y - 0.24392555296) <= 1e-05 and abs(self.x - 0.247797586626) <= 1e-05: print('Expected failure for testing ... x:' + str(self.x) + ' | y:' + str(self.y))...
# -*- coding: utf-8 -*- def create(): resourceDict = dict() return resourceDict def addOne(resourceDict, key, value): if (len(key)<=2): return 'err' if (key[0:2]!="##"): print("key must be like '##xx' : %s " % key) return 'err' resourceDict[key] = value return 'ok'
def create(): resource_dict = dict() return resourceDict def add_one(resourceDict, key, value): if len(key) <= 2: return 'err' if key[0:2] != '##': print("key must be like '##xx' : %s " % key) return 'err' resourceDict[key] = value return 'ok'
class DuplicateTagsWarning(UserWarning): def get_warning_message(self, duplicate_tags, name): return f"Semantic tag(s) '{', '.join(duplicate_tags)}' already present on column '{name}'" class StandardTagsChangedWarning(UserWarning): def get_warning_message(self, use_standard_tags, col_name=None): ...
class Duplicatetagswarning(UserWarning): def get_warning_message(self, duplicate_tags, name): return f"Semantic tag(s) '{', '.join(duplicate_tags)}' already present on column '{name}'" class Standardtagschangedwarning(UserWarning): def get_warning_message(self, use_standard_tags, col_name=None): ...
""" write your first program in python """ print("helloworld in python !!")
""" write your first program in python """ print('helloworld in python !!')