content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class Divider: def __init__(self): self.type = "divider" def to_dict(self): return self.__dict__ if __name__ == '__main__': print(Divider())
class Divider: def __init__(self): self.type = 'divider' def to_dict(self): return self.__dict__ if __name__ == '__main__': print(divider())
def toStr(n, base): convertString = "0123456789ABCDEF" if n < base: return convertString[n] else: return toStr(n // base, base) + convertString[n % base] print(toStr(10, 2))
def to_str(n, base): convert_string = '0123456789ABCDEF' if n < base: return convertString[n] else: return to_str(n // base, base) + convertString[n % base] print(to_str(10, 2))
pkgname = "python-pyudev" pkgver = "0.23.2" pkgrel = 0 build_style = "python_module" hostmakedepends = ["python-setuptools"] depends = ["eudev-libs"] checkdepends = ["python-pytest", "eudev-libs"] pkgdesc = "Python bindings to libudev" maintainer = "q66 <q66@chimera-linux.org>" license = "LGPL-2.1-or-later" url = "http...
pkgname = 'python-pyudev' pkgver = '0.23.2' pkgrel = 0 build_style = 'python_module' hostmakedepends = ['python-setuptools'] depends = ['eudev-libs'] checkdepends = ['python-pytest', 'eudev-libs'] pkgdesc = 'Python bindings to libudev' maintainer = 'q66 <q66@chimera-linux.org>' license = 'LGPL-2.1-or-later' url = 'http...
#!/usr/bin/env python ''' mcu: Modeling and Crystallographic Utilities Copyright (C) 2019 Hung Q. Pham. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.or...
""" mcu: Modeling and Crystallographic Utilities Copyright (C) 2019 Hung Q. Pham. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0...
SCREEN_TITLE = "Pandemic Simulator" # Size of screen to show, in pixels SCREEN_WIDTH = 1920 SCREEN_HEIGHT = 1080 # Colors BACKGROUND_COLOR = 31, 87, 60 NORMAL_COLOR = 215, 200, 66 INFECTED_COLOR = 204, 57, 146 WALL_COLOR = 51, 181, 119 IMMUNE_COLOR = 125, 117, 45
screen_title = 'Pandemic Simulator' screen_width = 1920 screen_height = 1080 background_color = (31, 87, 60) normal_color = (215, 200, 66) infected_color = (204, 57, 146) wall_color = (51, 181, 119) immune_color = (125, 117, 45)
# `md5sum * | awk ' { t = "\""$1"\","; $1 = "\""$2"\":"; $2 = t; print; } '` ORIG_MD5 = { "gamesummary.inc": "c058a82cc997d82cb6b135aec3d3e398", "current_rules.inc": "fa1f6df26241de95d1e2b67383c2382d", "header_base.inc": "47c04f5c37a02e14dd848898c9b1445c", # "about.html": "170c37c1a24bc3f5ed7fad5f0cd698...
orig_md5 = {'gamesummary.inc': 'c058a82cc997d82cb6b135aec3d3e398', 'current_rules.inc': 'fa1f6df26241de95d1e2b67383c2382d', 'header_base.inc': '47c04f5c37a02e14dd848898c9b1445c'}
SERVICE = "elasticsearch" APP = "elasticsearch" # standard tags URL = "elasticsearch.url" METHOD = "elasticsearch.method" TOOK = "elasticsearch.took" PARAMS = "elasticsearch.params" BODY = "elasticsearch.body"
service = 'elasticsearch' app = 'elasticsearch' url = 'elasticsearch.url' method = 'elasticsearch.method' took = 'elasticsearch.took' params = 'elasticsearch.params' body = 'elasticsearch.body'
class GridLocation(object): def __init__(self): self.siteId = None self.nx = None self.ny = None self.timeZone = None self.projection = None self.origin = None self.extent = None self.geometry = None self.crsWKT = None self.identifie...
class Gridlocation(object): def __init__(self): self.siteId = None self.nx = None self.ny = None self.timeZone = None self.projection = None self.origin = None self.extent = None self.geometry = None self.crsWKT = None self.identifier ...
# get the API from here: https://whois.whoisxmlapi.com/documentation/making-requests api_key_whoisxml = '' # get the API from here: https://docs.nameauditor.com/ api_key_nameauditor = ''
api_key_whoisxml = '' api_key_nameauditor = ''
# # PySNMP MIB module RIVERSTONE-DHCP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RIVERSTONE-DHCP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:49:05 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, single_value_constraint, constraints_union, constraints_intersection, value_size_constraint) ...
def info(): global a, b print(f"{a = }, {b = }") print(f"{a == b = }") print(f"{a is b = }") a = "hello" b = "hello" info() a += "o" b += "o" info() a = "hello" b = "hell" + 'o' info() o = 'o' a = "hello" b = "hell" + o info()
def info(): global a, b print(f'a = {a!r}, b = {b!r}') print(f'a == b = {a == b!r}') print(f'a is b = {a is b!r}') a = 'hello' b = 'hello' info() a += 'o' b += 'o' info() a = 'hello' b = 'hell' + 'o' info() o = 'o' a = 'hello' b = 'hell' + o info()
def test(): # Here we can either check objects created in the solution code, or the # string value of the solution, available as __solution__. A helper for # printing formatted messages is available as __msg__. See the testTemplate # in the meta.json for details. # If an assertion fails, the messag...
def test(): assert 'import numpy as np' in __solution__, 'Have you imported numpy in its short form?' i_exact = lambda x: x ** 3 - 2 * x ** 2 + 3 * x + 1 x = np.linspace(-1, 1) assert np.allclose(integrand_exact(x), i_exact(x)), 'Have you set up the integrand_exact function correctly?' value_exact =...
# -*- coding: utf-8 -*- # @Time : 2021/5/22 # @Author : Lart Pang # @GitHub : https://github.com/lartpang # This line will be programatically read/write by setup.py. # Leave them at the bottom of this file and don't touch them. __version__ = "0.2"
__version__ = '0.2'
class Solution: def findMaxConsecutiveOnes(self, nums: [int]) -> int: max_cons = 0 temp = 0 for val in nums: if val == 1: temp += 1 else: max_cons = max(max_cons, temp) temp = 0 max_cons = max(max_cons, temp) ...
class Solution: def find_max_consecutive_ones(self, nums: [int]) -> int: max_cons = 0 temp = 0 for val in nums: if val == 1: temp += 1 else: max_cons = max(max_cons, temp) temp = 0 max_cons = max(max_cons, temp)...
file_name = "../input/input2.txt" my_file = open(file_name) lines = my_file.readlines() count = 0 for line in lines: arr = list(map(lambda s: s.strip(), line.split(":"))) pattern, password = arr[0].split(" "), arr[1] first_pos, second_pos, symbol = int(pattern[0].split("-")[0]), int(pattern[0].split("-")[...
file_name = '../input/input2.txt' my_file = open(file_name) lines = my_file.readlines() count = 0 for line in lines: arr = list(map(lambda s: s.strip(), line.split(':'))) (pattern, password) = (arr[0].split(' '), arr[1]) (first_pos, second_pos, symbol) = (int(pattern[0].split('-')[0]), int(pattern[0].split(...
def read_input(file_name: str) -> [int]: with open("inputFiles/" + file_name, "r") as file: lines = file.read().splitlines()[0].split(",") return [int(i) for i in lines] def part1(input_value: [int]): min_fuel = -1 for i in range(max(input_value)): fuel = 0 for fish in inpu...
def read_input(file_name: str) -> [int]: with open('inputFiles/' + file_name, 'r') as file: lines = file.read().splitlines()[0].split(',') return [int(i) for i in lines] def part1(input_value: [int]): min_fuel = -1 for i in range(max(input_value)): fuel = 0 for fish in input...
class HighScores(object): def __init__(self, scores): self.scores = scores @property def scores(self): return self._scores @scores.setter def scores(self, value): self._scores = value self._sorted_scores = sorted(value, reverse=True) def latest(self): return self._scores[-1] def personal_best(self...
class Highscores(object): def __init__(self, scores): self.scores = scores @property def scores(self): return self._scores @scores.setter def scores(self, value): self._scores = value self._sorted_scores = sorted(value, reverse=True) def latest(self): ...
def notaPostulanteEstMultiple(): #Definir Variables notaFinal=0 #Datos de entrada areaCarrera=input("Introduce el area a la que corresponde tu carrera:\nB=Biomedicas\nI=Ingenieria\nS=Sociales") notaEP=float(input("Ingrese la nota de EP:")) notaRM=float(input("Ingrese la nota de RM:")) notaRV=float(inp...
def nota_postulante_est_multiple(): nota_final = 0 area_carrera = input('Introduce el area a la que corresponde tu carrera:\nB=Biomedicas\nI=Ingenieria\nS=Sociales') nota_ep = float(input('Ingrese la nota de EP:')) nota_rm = float(input('Ingrese la nota de RM:')) nota_rv = float(input('Ingrese la no...
# -*- coding: utf-8 -*- # AtCoder Beginner Contest def main(): n, t = list(map(int, input().split())) a = [int(input()) for _ in range(n)] duration = t # See: # https://beta.atcoder.jp/contests/abc024/submissions/2841120 for i in range(1, n): duration += min(t, a[i] - a[i - 1]) p...
def main(): (n, t) = list(map(int, input().split())) a = [int(input()) for _ in range(n)] duration = t for i in range(1, n): duration += min(t, a[i] - a[i - 1]) print(duration) if __name__ == '__main__': main()
class GeneralData: instance = None def __init__(self): self.input_file_path = None self.template = None @classmethod def get_instance(cls): if cls.instance is None: cls.instance = GeneralData() return cls.instance def load_params(self, args): se...
class Generaldata: instance = None def __init__(self): self.input_file_path = None self.template = None @classmethod def get_instance(cls): if cls.instance is None: cls.instance = general_data() return cls.instance def load_params(self, args): s...
#base class for hdlib # #v0.1 jan 2019 #hdaniel@ualg.pt # class Base: #def __repr__(self): # raise NotImplementedError('Subclass must implement "__repr__(self)" method') #May have problem is recursion if objets are composed recursively? def __str__(self): return "%s(%r)" % (self.__class__, s...
class Base: def __str__(self): return '%s(%r)' % (self.__class__, self.__dict__) @staticmethod def is_number(obj): """ Check if an object is integer. Multiply the object by zero. Any number times zero is zero. Any other result means that the object is not a...
class C(object): def __iadd__(self, rhs): return rhs class D(object): def __add__(self, rhs): return rhs c = C() # 0 C d = D() # 0 D c += 1 c # 0 int d += 1 d # 0 int
class C(object): def __iadd__(self, rhs): return rhs class D(object): def __add__(self, rhs): return rhs c = c() d = d() c += 1 c d += 1 d
# Authors: Stefanos Papanikolaou <stefanos.papanikolaou@mail.wvu.edu> # BSD 2-Clause License # Copyright (c) 2019, PapStatMechMat # All rights reserved. # How to cite SeaPy: # S. Papanikolaou, Data-Rich, Equation-Free Predictions of Plasticity and Damage in Solids, (under review in Phys. Rev. Materials) arXiv:1905.1128...
def pick_mode(Ep, col, s): p0 = Ep.reshape(s) rp0 = real(p0) return rp0 def fingerprint_from_txt(fs): z = [] for (i, f) in enumerate(fs): a = loadtxt(f) if i == 0: s = shape(A) Z.append(A.flatten()) d = Z.T x = D[:, :-1] y = D[:, 1:] (u2, sig2, vh...
liste1 = [1,3,5,7,9] liste2 = [0,2,4,6,8] liste3 = liste1+liste2 liste3 = [int(i*2) for i in liste3] for i in liste3: print(type(i))
liste1 = [1, 3, 5, 7, 9] liste2 = [0, 2, 4, 6, 8] liste3 = liste1 + liste2 liste3 = [int(i * 2) for i in liste3] for i in liste3: print(type(i))
{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import os \n", "import pandas as pd\n", "import numpy as np\n", "import sqlalchemy \n", "from sqlalchemy.ext.automap import automap_base\n", "from sqlalchemy.orm import session...
{'cells': [{'cell_type': 'code', 'execution_count': 1, 'metadata': {}, 'outputs': [], 'source': ['import os \n', 'import pandas as pd\n', 'import numpy as np\n', 'import sqlalchemy \n', 'from sqlalchemy.ext.automap import automap_base\n', 'from sqlalchemy.orm import session\n', 'from sqlalchemy import create_engine\n',...
love_maybe_lines = ['Always ', ' in the middle of our bloodiest battles ', 'you lay down your arms', ' like flowering mines ','\n' ,' to conquer me home. '] love_maybe_lines_stripped = [] for i in range(len(love_maybe_lines)): love_maybe_lines_stripped.append(love_maybe_lines[i].strip()) ...
love_maybe_lines = ['Always ', ' in the middle of our bloodiest battles ', 'you lay down your arms', ' like flowering mines ', '\n', ' to conquer me home. '] love_maybe_lines_stripped = [] for i in range(len(love_maybe_lines)): love_maybe_lines_stripped.append(love_maybe_lines[i].strip()) ...
class NodeGroupDisplay: def __init__(self): self.colors = ['k', 'b', 'r'] self.grpColors = {} self.leftGropColors = self.colors.copy() def getColor(self, MasterNodeNumber, MasterAvailable): if MasterAvailable == False: return 'g' if MasterNodeNumber in self....
class Nodegroupdisplay: def __init__(self): self.colors = ['k', 'b', 'r'] self.grpColors = {} self.leftGropColors = self.colors.copy() def get_color(self, MasterNodeNumber, MasterAvailable): if MasterAvailable == False: return 'g' if MasterNodeNumber in self...
# Copyright 2016 Cloudbase Solutions Srl # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
cd_types = {'vfat', 'iso'} cd_locations = {'cdrom', 'hdd', 'partition'} policy_ignore_all_failures = 'ignoreallfailures' san_policy_online_str = 'OnlineAll' san_policy_offline_str = 'OfflineAll' san_policy_offline_shared_str = 'OfflineShared' clear_text_injected_only = 'clear_text_injected_only' always_change = 'always...
# Enable debug mode. DEBUG = True # Secret key for session management. You can generate random strings here: # https://randomkeygen.com/ SECRET_KEY = 'my secret'
debug = True secret_key = 'my secret'
class Solution: def digitSum(self, s: str, k: int) -> str: while len(s) > k: s_temp = [] for i in range(0, len(s), k): sub_str = list(s[i:i+k]) sub_str = [int(ss) for ss in sub_str] s_temp.append(str(sum(sub_str))) s = ''.jo...
class Solution: def digit_sum(self, s: str, k: int) -> str: while len(s) > k: s_temp = [] for i in range(0, len(s), k): sub_str = list(s[i:i + k]) sub_str = [int(ss) for ss in sub_str] s_temp.append(str(sum(sub_str))) s = '...
def add_from_one_to(n): return n * (n + 1)/2 def multiply_from_one_to(n): product = 1 for i in range(1, n+1): product *= i return product print("Welcome to sum-or-product v3000") print("enter the number: ") n = int(input("> ")) print(f"Press 1 to add all the numbers from 1 to {n}") print(f"Press 2 to mu...
def add_from_one_to(n): return n * (n + 1) / 2 def multiply_from_one_to(n): product = 1 for i in range(1, n + 1): product *= i return product print('Welcome to sum-or-product v3000') print('enter the number: ') n = int(input('> ')) print(f'Press 1 to add all the numbers from 1 to {n}') print(f'...
vip_guests = set() regular_guests = set() guests_count = int(input()) for _ in range(guests_count): guest = input() is_digit = guest[0].isdigit() if is_digit: vip_guests.add(guest) else: regular_guests.add(guest) while True: reservation = input() if reservation == 'END': ...
vip_guests = set() regular_guests = set() guests_count = int(input()) for _ in range(guests_count): guest = input() is_digit = guest[0].isdigit() if is_digit: vip_guests.add(guest) else: regular_guests.add(guest) while True: reservation = input() if reservation == 'END': ...
s = list(input()) n = len(s) nn = n//3 s1 = s[:nn] s2 = s[nn:2*nn] s3= s[2*nn:3*nn] '''print(s) print(s1) print(s2) print(s3)''' res = "" for i in range(nn): if s1[i]==s2[i]: res+=s1[i] elif s1[i]==s3[i]: res+=s1[i] elif s2[i]==s3[i]: res+=s2[i] else: print("ERROR") print...
s = list(input()) n = len(s) nn = n // 3 s1 = s[:nn] s2 = s[nn:2 * nn] s3 = s[2 * nn:3 * nn] 'print(s)\nprint(s1)\nprint(s2)\nprint(s3)' res = '' for i in range(nn): if s1[i] == s2[i]: res += s1[i] elif s1[i] == s3[i]: res += s1[i] elif s2[i] == s3[i]: res += s2[i] else: ...
# This is the CircularQueue class class CircularQueue: # constructor for the class # taking input for the size of the Circular queue # from user def __init__(self, maxSize): self.queue = list() # user input value for maxSize self.maxSize = maxSize self.head = 0 s...
class Circularqueue: def __init__(self, maxSize): self.queue = list() self.maxSize = maxSize self.head = 0 self.tail = 0 def enqueue(self, data): if self.size() == self.maxSize - 1: return 'Queue is full!' else: self.queue.append(data) ...
def count_inversion(seq): if not hasattr(seq, "__iter__"): raise TypeError("a sequence expected") seqLen = len(seq) count = 0 if seqLen <= 1: return count for i in range(seqLen): for j in range(i + 1, seqLen): if seq[i] > seq[j]: ...
def count_inversion(seq): if not hasattr(seq, '__iter__'): raise type_error('a sequence expected') seq_len = len(seq) count = 0 if seqLen <= 1: return count for i in range(seqLen): for j in range(i + 1, seqLen): if seq[i] > seq[j]: count += 1 r...
#def AddVehicle(): vehType = 100 link = 1 lane = 2 pos = 0 desiredSpeed = 10 #for i in range(1000) #Vissim.Net.Vehicles.AddVehicleAtLinkPosition(vehType,link,lane,pos,desiredSpeed)
veh_type = 100 link = 1 lane = 2 pos = 0 desired_speed = 10
reviews = [ {'id': '1', 'authorID': '1', 'product': {'upc': '1'}, 'body': 'Love it!'}, {'id': '2', 'authorID': '1', 'product': {'upc': '2'}, 'body': 'Too expensive.'}, {'id': '3', 'authorID': '2', 'product': {'upc': '3'}, 'body': 'Could be better.'}, {'id': '4', 'authorID': '2', 'product': {'upc': '1'},...
reviews = [{'id': '1', 'authorID': '1', 'product': {'upc': '1'}, 'body': 'Love it!'}, {'id': '2', 'authorID': '1', 'product': {'upc': '2'}, 'body': 'Too expensive.'}, {'id': '3', 'authorID': '2', 'product': {'upc': '3'}, 'body': 'Could be better.'}, {'id': '4', 'authorID': '2', 'product': {'upc': '1'}, 'body': 'Prefer ...
print('hello world') print('bye bye cruel world') print('the end') print('final coit supposably')
print('hello world') print('bye bye cruel world') print('the end') print('final coit supposably')
t=int(input()) for i in range(t): num=int(input()) sum=int(num%10) while(num>=10): num=int(num/10) sum+=num print(sum)
t = int(input()) for i in range(t): num = int(input()) sum = int(num % 10) while num >= 10: num = int(num / 10) sum += num print(sum)
class Progress: def __init__(self, progress, message="N/A", max_progress=1.0): if progress > max_progress: raise Exception("Invalid progress: progress was " + str(progress) + " while max progress is " + str(max_progress)) self.progress = progress / max_progress self.message = me...
class Progress: def __init__(self, progress, message='N/A', max_progress=1.0): if progress > max_progress: raise exception('Invalid progress: progress was ' + str(progress) + ' while max progress is ' + str(max_progress)) self.progress = progress / max_progress self.message = me...
class Dominos: def __init__(self,name): self.name = name self.dic = {"Chicken Pizza":"","Beef Pizza":"","Cheese Pizza":""} self.ccount = 0 self.bcount = 0 self.cecount = 0 def addPizza(self,*obj): for elm in obj: if elm.topings == None: ...
class Dominos: def __init__(self, name): self.name = name self.dic = {'Chicken Pizza': '', 'Beef Pizza': '', 'Cheese Pizza': ''} self.ccount = 0 self.bcount = 0 self.cecount = 0 def add_pizza(self, *obj): for elm in obj: if elm.topings == None: ...
#!/usr/bin/env python # filename: decorators.py # # Copyright (c) 2015 Bryan Briney # License: The MIT license (http://opensource.org/licenses/MIT) # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software # and associated documentation files (the "Software"), to deal in the So...
def lazy_property(func): """ Wraps a property to provide lazy evaluation. Eliminates boilerplate. Also provides for setting and deleting the property. Use as you would use the @property decorator:: # OLD: class MyClass(): def __init__(): self._compute = None...
english_hindi = { "ENGLISH_TRAIN_FILE": 'corpus/master_corpus/english_hindi/eng_train_corpus_final.txt', "HINDI_TRAIN_FILE": 'corpus/master_corpus/english_hindi/hindi_train_corpus_final.txt', "DEV_ENGLISH": "corpus/master_corpus/english_hindi/english_dev_final.txt", "DEV_HINDI": "corpus/master_corpus/en...
english_hindi = {'ENGLISH_TRAIN_FILE': 'corpus/master_corpus/english_hindi/eng_train_corpus_final.txt', 'HINDI_TRAIN_FILE': 'corpus/master_corpus/english_hindi/hindi_train_corpus_final.txt', 'DEV_ENGLISH': 'corpus/master_corpus/english_hindi/english_dev_final.txt', 'DEV_HINDI': 'corpus/master_corpus/english_hindi/hindi...
class accountmodel(): def __init__(self): self.accounts = [] self.balances = {} def add_account(self,publicKeyString): if not publicKeyString in self.accounts: self.accounts.append(publicKeyString) self.balances[publicKeyString]=0 def get_balance(self, ...
class Accountmodel: def __init__(self): self.accounts = [] self.balances = {} def add_account(self, publicKeyString): if not publicKeyString in self.accounts: self.accounts.append(publicKeyString) self.balances[publicKeyString] = 0 def get_balance(self, pub...
# users are selected by repositories; this is the ID of the first repository to # scan REPOS_SINCE_ID = 4325672 # number of repositories to scan for owners; starting from REPOS_SINCE_ID REPOS_COUNT = 3000 # files to store the JSON data REPOS_DATASET = "repos.json" USERS_DATASET = "users.json"
repos_since_id = 4325672 repos_count = 3000 repos_dataset = 'repos.json' users_dataset = 'users.json'
REACTION_SMILES_SAMPLE = [ 'c1ccccc1>>c1cccnc1', 'c1ccccc1>CC(=O)O>c1cccnc1', 'c1cccnc1>>c1nccnc1', '[Cl].c1ccccc1>>c1cccnc1.[OH2]', '[Cl].c1ccccc1>CC(=O)O.[Na+]>c1cccnc1.[OH2]', ] REACTION_SMARTS_SAMPLE = [ '[c1:1][c:2][c:3][c:4]c[c1:5]>CC(=O)O>[c1:1][c:2][c:3][c:4]n[c1:5]', 'C(F)(F)F.[c1:...
reaction_smiles_sample = ['c1ccccc1>>c1cccnc1', 'c1ccccc1>CC(=O)O>c1cccnc1', 'c1cccnc1>>c1nccnc1', '[Cl].c1ccccc1>>c1cccnc1.[OH2]', '[Cl].c1ccccc1>CC(=O)O.[Na+]>c1cccnc1.[OH2]'] reaction_smarts_sample = ['[c1:1][c:2][c:3][c:4]c[c1:5]>CC(=O)O>[c1:1][c:2][c:3][c:4]n[c1:5]', 'C(F)(F)F.[c1:1][c:2][c:3][c:4]c[c1:5]>CC(=O)O>...
# Enter your code for "Graph nOOde" here. class Node: def __init__(self, id, label): self.id = id self.label = label self.neighbours = [] def __str__(self): return "(%d: %s)" % (self.id, self.label) def add_neighbour(self, neighbour, label): self.neighbours.append((label, neighbour)) def get...
class Node: def __init__(self, id, label): self.id = id self.label = label self.neighbours = [] def __str__(self): return '(%d: %s)' % (self.id, self.label) def add_neighbour(self, neighbour, label): self.neighbours.append((label, neighbour)) def get_neighbour...
UP = (0, 1) DOWN = (0, -1) LEFT = (-1, 0) RIGHT = (1, 0) UPLEFT = (-1, 1) UPRIGHT = (1, 1) DOWNLEFT = (-1, -1) DOWNRIGHT = (1, -1) DOT = (0, 0) NOTE_TYPES_TRANSLATOR = { 0: "red", 1: "blue", 3: "mine", } NOTE_CUR_DIRECTION_TRANSLATOR = { 0: "up", 1: "down", 2: "left", 3: "right", 4: "u...
up = (0, 1) down = (0, -1) left = (-1, 0) right = (1, 0) upleft = (-1, 1) upright = (1, 1) downleft = (-1, -1) downright = (1, -1) dot = (0, 0) note_types_translator = {0: 'red', 1: 'blue', 3: 'mine'} note_cur_direction_translator = {0: 'up', 1: 'down', 2: 'left', 3: 'right', 4: 'upleft', 5: 'upright', 6: 'downleft', 7...
def construct(a, b): res = [] for row in range(a): l = [] for col in range(b): l.append(row * col) res.append(l) return res input_str = raw_input() dimension = [int(x) for x in input_str.split(',')] print(construct(dimension[0],dimension[1]))
def construct(a, b): res = [] for row in range(a): l = [] for col in range(b): l.append(row * col) res.append(l) return res input_str = raw_input() dimension = [int(x) for x in input_str.split(',')] print(construct(dimension[0], dimension[1]))
lines = open('day-13.input').readlines() nbf = int(lines[0]) buses = set(lines[1].strip().split(',')) buses.remove('x') buses = [int(bus) for bus in buses] print(nbf) print(buses) earliest_bus_id = 0 for i in range(nbf, nbf + max(buses)): for bus in buses: if i % bus == 0: earliest_bus_id = bus p...
lines = open('day-13.input').readlines() nbf = int(lines[0]) buses = set(lines[1].strip().split(',')) buses.remove('x') buses = [int(bus) for bus in buses] print(nbf) print(buses) earliest_bus_id = 0 for i in range(nbf, nbf + max(buses)): for bus in buses: if i % bus == 0: earliest_bus_id = bus ...
#Program to Check whether a character is vowel or consonent n=input() #Taking th character from the user #defining the function def vowel(n): #Checking the character is in list of vowels or not if n in ["a","e","i","o","u","A","E","I","O","U"]: print("Output = Vowel") else: print("Output = C...
n = input() def vowel(n): if n in ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']: print('Output = Vowel') else: print('Output = Consonent') vowel(n)
_base_ = ['./super-resolution_dynamic.py', '../../_base_/backends/openvino.py'] backend_config = dict( model_inputs=[dict(opt_shapes=dict(input=[1, 3, 256, 256]))])
_base_ = ['./super-resolution_dynamic.py', '../../_base_/backends/openvino.py'] backend_config = dict(model_inputs=[dict(opt_shapes=dict(input=[1, 3, 256, 256]))])
T = int(input()) for _ in range(T): S1 = input() S2 = input() qcount = 0 discount = 0 for i in range(len(S1)): if((S1[i] == '?') or (S2[i] == '?')): qcount += 1 elif(S1[i] != S2[i]): discount += 1 print(discount, qcount+discount)
t = int(input()) for _ in range(T): s1 = input() s2 = input() qcount = 0 discount = 0 for i in range(len(S1)): if S1[i] == '?' or S2[i] == '?': qcount += 1 elif S1[i] != S2[i]: discount += 1 print(discount, qcount + discount)
class Solution: def longestCommonPrefix(self, strs): if len(strs) == 0: return "" st = strs[0] for s in strs: sl = len(s) while sl > 0: if s[0:sl] == st[0:sl]: st = s[0:sl] break sl -=...
class Solution: def longest_common_prefix(self, strs): if len(strs) == 0: return '' st = strs[0] for s in strs: sl = len(s) while sl > 0: if s[0:sl] == st[0:sl]: st = s[0:sl] break sl...
print("SE INICIA PROGRAMA") entrada=input().split(" ") entrada2=list(map(int,entrada)) print(entrada2) hasta=34 numero=0 suma=0 while(numero<=hasta): numero=numero+1 suma+=entrada2[numero-1] print(suma)
print('SE INICIA PROGRAMA') entrada = input().split(' ') entrada2 = list(map(int, entrada)) print(entrada2) hasta = 34 numero = 0 suma = 0 while numero <= hasta: numero = numero + 1 suma += entrada2[numero - 1] print(suma)
# # PySNMP MIB module OLD-CISCO-TS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OLD-CISCO-TS-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:24:33 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_size_constraint, constraints_union, value_range_constraint, constraints_intersection) ...
myList = [[(8,3), (5,6)], [(7,8), (11,13)]] converted = [elt for sub in myList for elt in sub] print(converted) res = list(zip(*converted)) print(res)
my_list = [[(8, 3), (5, 6)], [(7, 8), (11, 13)]] converted = [elt for sub in myList for elt in sub] print(converted) res = list(zip(*converted)) print(res)
def sayHello(): return 'hello' if __name__ == '__main__': print(sayHello())
def say_hello(): return 'hello' if __name__ == '__main__': print(say_hello())
s = input() t = input() if s==t: print('same') elif s.lower() == t.lower(): print('case-insensitive') else: print('different')
s = input() t = input() if s == t: print('same') elif s.lower() == t.lower(): print('case-insensitive') else: print('different')
class Item: def __init__(self, profit, weight): self.profit = profit self.weight = weight def zoKnapsack(items, capacity, currentIndex): if capacity <= 0 or currentIndex < 0 or currentIndex >= len(items): return 0 elif items[currentIndex].weight <= capacity: profit1 = items...
class Item: def __init__(self, profit, weight): self.profit = profit self.weight = weight def zo_knapsack(items, capacity, currentIndex): if capacity <= 0 or currentIndex < 0 or currentIndex >= len(items): return 0 elif items[currentIndex].weight <= capacity: profit1 = item...
class Node: def __init__(self,char): self.val = char self.links = [] def traverse(node,visited,mylist): if node.val in visited: return [] visited.add(node.val) mylist.append(node.val) if len(visited) == 5: return mylist if len(node.links)==0: retur...
class Node: def __init__(self, char): self.val = char self.links = [] def traverse(node, visited, mylist): if node.val in visited: return [] visited.add(node.val) mylist.append(node.val) if len(visited) == 5: return mylist if len(node.links) == 0: return...
cart_rnd = [34, 4, 43, 30, 24, 32, 40, 11, 20, 30, 3, 16, 53, 45, 0, 21, 43, 23, 44, 50, 9, 41, 37, 37, 11, 2, 26, 33, 18, 20] basepath = "../../../../../../Downloads/transferabledata/new/data_dcp/cartpoleData/data/hyperparam_v5/" cart_true = [basepath + "cartpole/online_learning/esarsa/step50k/sweep/"] cart_optim_knn...
cart_rnd = [34, 4, 43, 30, 24, 32, 40, 11, 20, 30, 3, 16, 53, 45, 0, 21, 43, 23, 44, 50, 9, 41, 37, 37, 11, 2, 26, 33, 18, 20] basepath = '../../../../../../Downloads/transferabledata/new/data_dcp/cartpoleData/data/hyperparam_v5/' cart_true = [basepath + 'cartpole/online_learning/esarsa/step50k/sweep/'] cart_optim_knn ...
def findDecision(obj): #obj[0]: Driving_to, obj[1]: Passanger, obj[2]: Weather, obj[3]: Temperature, obj[4]: Time, obj[5]: Coupon, obj[6]: Coupon_validity, obj[7]: Gender, obj[8]: Age, obj[9]: Maritalstatus, obj[10]: Children, obj[11]: Education, obj[12]: Occupation, obj[13]: Income, obj[14]: Bar, obj[15]: Coffeehouse,...
def find_decision(obj): if obj[1] > 0: if obj[2] <= 1: if obj[16] > 1.0: if obj[17] <= 3.0: if obj[11] > 0: return 'True' elif obj[11] <= 0: if obj[19] <= 0: if obj...
# https://leetcode.com/problems/max-number-of-k-sum-pairs/ # TLE class Solution: def maxOperations(self, nums: List[int], k: int) -> int: nums.sort() while nums[-1] >= k: nums.pop() count = 0 n = nums nums =[] ...
class Solution: def max_operations(self, nums: List[int], k: int) -> int: nums.sort() while nums[-1] >= k: nums.pop() count = 0 n = nums nums = [] for j in n: nums.append([j, False]) iterator = 0 while nums: for i i...
def emulate_latterfish_growth(fish_set, days): prev_fishes = fish_set for day in range(days): new_fishes = [0] * len(prev_fishes) for i, fish in enumerate(prev_fishes): if fish == 0: new_fishes[i] = 6 new_fishes.append(8) else: ...
def emulate_latterfish_growth(fish_set, days): prev_fishes = fish_set for day in range(days): new_fishes = [0] * len(prev_fishes) for (i, fish) in enumerate(prev_fishes): if fish == 0: new_fishes[i] = 6 new_fishes.append(8) else: ...
class Unauthorized(Exception): pass class Forbidden(Exception): pass class NotFound(Exception): pass class RequestFailed(Exception): pass
class Unauthorized(Exception): pass class Forbidden(Exception): pass class Notfound(Exception): pass class Requestfailed(Exception): pass
class Solution: # @param a, a string # @param b, a string # @return a string def addBinary(self, a, b): return '{0:b}'.format(int(a, 2) + int(b, 2))
class Solution: def add_binary(self, a, b): return '{0:b}'.format(int(a, 2) + int(b, 2))
def add(a, b): return def substract(a, b): return def multiply(a, b): return def divide(a, b): return
def add(a, b): return def substract(a, b): return def multiply(a, b): return def divide(a, b): return
# # PySNMP MIB module INTERFACETOPN-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/INTERFACETOPN-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:44:50 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, value_range_constraint, constraints_intersection, constraints_union, single_value_constraint) ...
## 3. Read the File Into a String ## f = open("dq_unisex_names.csv", 'r') names = f.read() ## 4. Convert the String to a List ## f = open('dq_unisex_names.csv', 'r') names = f.read() names_list = names.split('\n') first_five = names_list[:5] print(first_five) ## 5. Convert the List of Strings to a List of Lists ## ...
f = open('dq_unisex_names.csv', 'r') names = f.read() f = open('dq_unisex_names.csv', 'r') names = f.read() names_list = names.split('\n') first_five = names_list[:5] print(first_five) f = open('dq_unisex_names.csv', 'r') names = f.read() names_list = names.split('\n') nested_list = [] for name in names_list: comma...
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- class Meter(object): def __init__(self, value=0.0): self.value = float(value) def __get__(self, instance, owner): return self.value def __set__(self, instance, value): self.value = float(value) class Foot(object): def __get__(s...
class Meter(object): def __init__(self, value=0.0): self.value = float(value) def __get__(self, instance, owner): return self.value def __set__(self, instance, value): self.value = float(value) class Foot(object): def __get__(self, instance, owner): return instance.m...
lunch = input("What's for lunch? ") if lunch == "spam": print("Oh no, not spam!") else: print("Yum, I like " + lunch)
lunch = input("What's for lunch? ") if lunch == 'spam': print('Oh no, not spam!') else: print('Yum, I like ' + lunch)
global remoteObj def pressPower(): remoteObj.setKey(0) def pressMute(): remoteObj.setKey(1) def pressInput(): remoteObj.setKey(2) def pressVolPlus(): remoteObj.setKey(3) def pressVolMin(): remoteObj.setKey(4) def pressPagePlus(): remoteObj.setKey(5) def pressPageMin(): remoteObj.setKe...
global remoteObj def press_power(): remoteObj.setKey(0) def press_mute(): remoteObj.setKey(1) def press_input(): remoteObj.setKey(2) def press_vol_plus(): remoteObj.setKey(3) def press_vol_min(): remoteObj.setKey(4) def press_page_plus(): remoteObj.setKey(5) def press_page_min(): remo...
''' PROGRAM TO A LIST SORT IN ASCENDING AND DESCENDING ORDER i) LIST OF STRINGS ii) LIST OF NUMBERS''' #Assigning values to StrList = ['aaa','xxx','bbb'] NumList = [23,12,34] #Displaying given list print('\nList of strings:',StrList) print('List of numbers:',NumList) #Sorting list in ascending ord...
""" PROGRAM TO A LIST SORT IN ASCENDING AND DESCENDING ORDER i) LIST OF STRINGS ii) LIST OF NUMBERS""" str_list = ['aaa', 'xxx', 'bbb'] num_list = [23, 12, 34] print('\nList of strings:', StrList) print('List of numbers:', NumList) StrList.sort() NumList.sort() print('\nList of strings in ascending o...
with frontend.signin(): frontend.page("createreview", expect={ "document_title": testing.expect.document_title(u"Create Review"), "content_title": testing.expect.paleyellow_title(0, u"Create Review"), "pageheader_links": testing.e...
with frontend.signin(): frontend.page('createreview', expect={'document_title': testing.expect.document_title(u'Create Review'), 'content_title': testing.expect.paleyellow_title(0, u'Create Review'), 'pageheader_links': testing.expect.pageheader_links('authenticated', 'administrator'), 'script_user': testing.expect...
#34 # Time: O(logn) # Space: O(1) # Given an array of integers sorted in ascending order, find the starting and ending position of a given target value. # # Your algorithm's runtime complexity must be in the order of O(log n). # # If the target is not found in the array, return [-1, -1]. # # For example, # Given [...
class Binarysearchsol: def search_range(self, nums, target): left = self.binarySearch2(nums, target, lambda x, y: x >= y) print(left) if left >= len(nums) or nums[left] != target: return [-1, 1] right = self.binarySearch2(nums, target, lambda x, y: x > y) return ...
''' CSES Problem Set Introductory Problems - Repetitions # Author : Sunkeerth M # Description : You are given all You are given a DNA sequence: a string consisting of characters A, C, G, and T. Your task is to find the longest repetition in the sequence. This is a maximu...
""" CSES Problem Set Introductory Problems - Repetitions # Author : Sunkeerth M # Description : You are given all You are given a DNA sequence: a string consisting of characters A, C, G, and T. Your task is to find the longest repetition in the sequence. This is a maximu...
def contrastive_loss(pred_simi, gt_simi, margin=0.20): pos_pair = gt_simi * (1 - pred_simi) neg_pair = (1 - gt_simi) * torch.clamp(pred_simi - margin, min=0.) pos_pair = pos_pair ** 2 neg_pair = neg_pair ** 2 # Note that `gt_simi` acts here as a gate to avoid doing a for-loop and if/else return torch.mea...
def contrastive_loss(pred_simi, gt_simi, margin=0.2): pos_pair = gt_simi * (1 - pred_simi) neg_pair = (1 - gt_simi) * torch.clamp(pred_simi - margin, min=0.0) pos_pair = pos_pair ** 2 neg_pair = neg_pair ** 2 return torch.mean(pos_pair + neg_pair)
def coin(n): return gen_coin(n, "", []) def gen_coin(n, solution, res): if n==0: res.append(solution) else: gen_coin(n-1, solution+"H", res) gen_coin(n-1, solution+"T", res) return res
def coin(n): return gen_coin(n, '', []) def gen_coin(n, solution, res): if n == 0: res.append(solution) else: gen_coin(n - 1, solution + 'H', res) gen_coin(n - 1, solution + 'T', res) return res
# Class is declared That contains all the functions and variable class Area_parameters_volume: # Global single variable is declared that gets the calculated result calculate = 0 # Option function is declared that is called on lab_file1 page def option(self, value): # Condition to check value to be ...
class Area_Parameters_Volume: calculate = 0 def option(self, value): if value == 1: return self.area() elif value == 2: return self.perimeter() else: return self.volume() def area(self): print('\n ****Calculate Area **** \n') whil...
global path_x, path_y, n path_x = [2, 1, -1, -2, -2, -1, 1, 2] path_y = [1, 2, 2, 1, -1, -2, -2, -1] n = 8 def knight_tour(board, row, col, step): if step == n**2: return True for index in range(n): row_new = row + path_x[index] col_new = col + path_y[index] if move_is_vali...
global path_x, path_y, n path_x = [2, 1, -1, -2, -2, -1, 1, 2] path_y = [1, 2, 2, 1, -1, -2, -2, -1] n = 8 def knight_tour(board, row, col, step): if step == n ** 2: return True for index in range(n): row_new = row + path_x[index] col_new = col + path_y[index] if move_is_valid(b...
''' Accept a day number from the user, and display the day of the week that day is. 1. If the user enters a number between 1 and 7, then display the day of the week that number represents. 2. If the user enters a number that is less than 1 or greater than 7, then display an error message. NOTE: Make use of an...
""" Accept a day number from the user, and display the day of the week that day is. 1. If the user enters a number between 1 and 7, then display the day of the week that number represents. 2. If the user enters a number that is less than 1 or greater than 7, then display an error message. NOTE: Make use of an...
rfc_pipe = Pipeline([ ("vectorizer", CountVectorizer(min_df=2, stop_words='english')), ("rf", RandomForestClassifier(random_state=42, max_depth=3)) ]) rfc_pipe.fit(text_train, y_train) rfc_pipe.score(text_train, y_train) rfc_pipe.score(text_test, y_test)
rfc_pipe = pipeline([('vectorizer', count_vectorizer(min_df=2, stop_words='english')), ('rf', random_forest_classifier(random_state=42, max_depth=3))]) rfc_pipe.fit(text_train, y_train) rfc_pipe.score(text_train, y_train) rfc_pipe.score(text_test, y_test)
d = {} # To add a key->value pair, do this: d.setdefault(key, []).append(value) # To retrieve a list of the values for a key list_of_values = d[key] # To remove a key->value pair is still easy, if # you don't mind leaving empty lists behind when # the last value for a given key is removed: d[key].remove(value) # De...
d = {} d.setdefault(key, []).append(value) list_of_values = d[key] d[key].remove(value) if d.has_key(key) and d[key]: pass else: pass example = {} example.setdefault('a', []).append('apple') example.setdefault('b', []).append('boots') example.setdefault('c', []).append('cat') example.setdefault('a', []).append(...
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Trace path constants. # Prefix for the loading trace database files. TRACE_DATABASE_PREFIX = 'trace_database'
trace_database_prefix = 'trace_database'
# # Complete the timeConversion function below. # def timeConversion(s): hh = int(s[0:2]) if (s.find("PM") > 0): if hh == 12: s = s[0:s.find("PM")] else: hh += 12 s = s[0:s.find("PM")] s = s.replace(s[0:2], str(hh)) return s elif (s.fi...
def time_conversion(s): hh = int(s[0:2]) if s.find('PM') > 0: if hh == 12: s = s[0:s.find('PM')] else: hh += 12 s = s[0:s.find('PM')] s = s.replace(s[0:2], str(hh)) return s elif s.find('AM') > 0: hh += 12 s = s[0:s.find...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # TODO: use asyncio? def send_message(message): pass # TODO: use asyncio? def get_message(): message = {} return message
def send_message(message): pass def get_message(): message = {} return message
#!/usr/bin/python3 def append_write(filename="", text=""): with open(filename, mode="a", encoding="utf-8") as f: return f.write(text)
def append_write(filename='', text=''): with open(filename, mode='a', encoding='utf-8') as f: return f.write(text)
def foo(a): a = 4 a = 0 foo(a) print("%d\n" % a, end='')
def foo(a): a = 4 a = 0 foo(a) print('%d\n' % a, end='')
class WireframeModifier: crease_weight = None invert_vertex_group = None material_offset = None offset = None thickness = None thickness_vertex_group = None use_boundary = None use_crease = None use_even_offset = None use_relative_offset = None use_replace = None vertex_g...
class Wireframemodifier: crease_weight = None invert_vertex_group = None material_offset = None offset = None thickness = None thickness_vertex_group = None use_boundary = None use_crease = None use_even_offset = None use_relative_offset = None use_replace = None vertex_g...
description = 'camera setup' group = 'lowlevel' sysconfig = dict( datasinks = ['tifformat'], ) devices = dict( timer = device('nicos.devices.generic.VirtualTimer', description = 'timer for the camera', visibility = (), ), image = device('nicos.devices.generic.VirtualImage', de...
description = 'camera setup' group = 'lowlevel' sysconfig = dict(datasinks=['tifformat']) devices = dict(timer=device('nicos.devices.generic.VirtualTimer', description='timer for the camera', visibility=()), image=device('nicos.devices.generic.VirtualImage', description='image for the camera', size=(1024, 1024), visibi...
def catAndMouse(x, y, z): if abs(x-z)<abs(y-z): return "Cat A" elif abs(x-z)>abs(y-z): return "Cat B" else: return "Mouse C"
def cat_and_mouse(x, y, z): if abs(x - z) < abs(y - z): return 'Cat A' elif abs(x - z) > abs(y - z): return 'Cat B' else: return 'Mouse C'
def part1(): values = [[int(j) for j in i.split("=")[1].split("..")] for i in open("input.txt").read().split(": ")[1].split(", ")] for i in range(len(values)): values[i] = list(range(values[i][0], values[i][1]+1)) minX, maxX = min(values[0]), max(values[0]) minY, maxY = min(values[1]), max(valu...
def part1(): values = [[int(j) for j in i.split('=')[1].split('..')] for i in open('input.txt').read().split(': ')[1].split(', ')] for i in range(len(values)): values[i] = list(range(values[i][0], values[i][1] + 1)) (min_x, max_x) = (min(values[0]), max(values[0])) (min_y, max_y) = (min(values[1...
class ProximaError(Exception): def __init__(self, message, line, column): super(ProximaError,self).__init__() print('{} at line {}, column {}'.format(message, line, column)) def report_syntax_error(lexer, error): line = error.line column = error.column source_line = lexer.source_lines...
class Proximaerror(Exception): def __init__(self, message, line, column): super(ProximaError, self).__init__() print('{} at line {}, column {}'.format(message, line, column)) def report_syntax_error(lexer, error): line = error.line column = error.column source_line = lexer.source_lines...
class Argument: id = "" long = "" args = [] def __init__(self,id,long,args): self.id = id self.long = long self.args = args def get(self): if self.args.contains(self.id) or self.args.contains(self.long): i = 1 while i < len(self.args): if self.args[i] == self.id: ...
class Argument: id = '' long = '' args = [] def __init__(self, id, long, args): self.id = id self.long = long self.args = args def get(self): if self.args.contains(self.id) or self.args.contains(self.long): i = 1 while i < len(self.args): ...
# Maintain i1, i2 to store latest occurance of w1 and w2. When you find w1, do res = min(res, i - i2). Same for w2. class Solution: def shortestDistance(self, words: List[str], word1: str, word2: str) -> int: idx1, idx2 = float('-inf'), float('-inf') res = float('inf') for i, w in enumerate...
class Solution: def shortest_distance(self, words: List[str], word1: str, word2: str) -> int: (idx1, idx2) = (float('-inf'), float('-inf')) res = float('inf') for (i, w) in enumerate(words): if w == word1: res = min(res, i - idx2) idx1 = i ...
def modulo(s,n): return s & (n-1) def isPowerOfTwo(s): return s & (s-1) def turnOffLastBit(S): return (S & (S - 1)) def turnOnLastZero(S): return ((S) | (S + 1)) def turnOffLastConsecutiveBits(S): return ((S) & (S + 1)) def turnOnLastConsecutiveZeroes(S): return ((S) | (S-1))
def modulo(s, n): return s & n - 1 def is_power_of_two(s): return s & s - 1 def turn_off_last_bit(S): return S & S - 1 def turn_on_last_zero(S): return S | S + 1 def turn_off_last_consecutive_bits(S): return S & S + 1 def turn_on_last_consecutive_zeroes(S): return S | S - 1
N=int(input())//100*100 F=int(input()) while 1: if N%F==0: print(str(N)[-2:]) break N+=1
n = int(input()) // 100 * 100 f = int(input()) while 1: if N % F == 0: print(str(N)[-2:]) break n += 1
cids_before_shrink = \ {'201702-25401': {'audio_name': 'Lewisburg MROM 0', 'audio_pciid': '8086:a1f0', 'codename': 'Matira 5', 'form_factor': 'Desktop', 'kernel': '4.15.0-1027-oem', 'location': 'ceqa', 'make': 'D...
cids_before_shrink = {'201702-25401': {'audio_name': 'Lewisburg MROM 0', 'audio_pciid': '8086:a1f0', 'codename': 'Matira 5', 'form_factor': 'Desktop', 'kernel': '4.15.0-1027-oem', 'location': 'ceqa', 'make': 'Dell', 'model': 'Precision Tower 7820', 'network': 'Intel - 8086:15b9', 'processor': 'Intel(R) Xeon(R) Platinum...
### Palindrome Index - Solution def getIndex(s): rev_str = list(reversed(s)) if s == rev_str: return -1 i, idx_last = 0, len(s)-1 while i < idx_last: if s[i] != s[idx_last]: s.pop(i) if "".join(s) == "".join(list(reversed(s))): return i ...
def get_index(s): rev_str = list(reversed(s)) if s == rev_str: return -1 (i, idx_last) = (0, len(s) - 1) while i < idx_last: if s[i] != s[idx_last]: s.pop(i) if ''.join(s) == ''.join(list(reversed(s))): return i return idx_last ...