content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
inputFile = str(input("Input file")) f = open(inputFile,"r") data = f.readlines() f.close() runningFuelSum = 0 for line in data: line = line.replace("\n","") mass = int(line) fuelNeeded = (mass//3)-2 runningFuelSum += fuelNeeded while(fuelNeeded > 0): fuelNeeded = (fuelNeeded//3)-2 ...
input_file = str(input('Input file')) f = open(inputFile, 'r') data = f.readlines() f.close() running_fuel_sum = 0 for line in data: line = line.replace('\n', '') mass = int(line) fuel_needed = mass // 3 - 2 running_fuel_sum += fuelNeeded while fuelNeeded > 0: fuel_needed = fuelNeeded // 3 -...
class Settings: def __init__(self): self.screen_width, self.screen_height = 800, 300 self.bg_color = (225, 225, 225)
class Settings: def __init__(self): (self.screen_width, self.screen_height) = (800, 300) self.bg_color = (225, 225, 225)
class Solution: def sortColors(self, nums: List[int]) -> None: zero = -1 one = -1 two = -1 for num in nums: if num == 0: two += 1 one += 1 zero += 1 nums[two] = 2 nums[one] = 1 nums[zero] = 0 elif num == 1: two += 1 one += 1 ...
class Solution: def sort_colors(self, nums: List[int]) -> None: zero = -1 one = -1 two = -1 for num in nums: if num == 0: two += 1 one += 1 zero += 1 nums[two] = 2 nums[one] = 1 ...
# an ex. of how you might use a list in practice colors = ["green", "red", "blue"] guess = input("Please guess a color:") if guess in colors: print ("You guessed correctly!") else: print ("Negative! Try again please.")
colors = ['green', 'red', 'blue'] guess = input('Please guess a color:') if guess in colors: print('You guessed correctly!') else: print('Negative! Try again please.')
# Do not edit this file directly. # It was auto-generated by: code/programs/reflexivity/reflexive_refresh load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def backwardCpp(): http_archive( name="backward_cpp" , build_file="//bazel/deps/backward_cpp:build.BUILD" , sha256...
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive') def backward_cpp(): http_archive(name='backward_cpp', build_file='//bazel/deps/backward_cpp:build.BUILD', sha256='16ea32d5337735ed3e7eacd71d90596a89bc648c557bb6007c521a2cb6b073cc', strip_prefix='backward-cpp-aa3f253efc7281148e9159eda52b851339fe94...
print('~'*30) print('BANCOS AVORIK') print('~'*30) nt50 = nt20 = nt10 = nt1 = 0 saque = int(input('Quantos R$ deseja sacar?\n')) resto = saque while True: if resto > 50: nt50 = resto // 50 resto = resto % 50 print(f'{nt50} nota(s) de R$ 50.') if resto > 20: nt20 = resto // 20 ...
print('~' * 30) print('BANCOS AVORIK') print('~' * 30) nt50 = nt20 = nt10 = nt1 = 0 saque = int(input('Quantos R$ deseja sacar?\n')) resto = saque while True: if resto > 50: nt50 = resto // 50 resto = resto % 50 print(f'{nt50} nota(s) de R$ 50.') if resto > 20: nt20 = resto // 20...
ButtonA, ButtonB, ButtonSelect, ButtonStart, ButtonUp, ButtonDown, ButtonLeft, ButtonRight = range(8) class Controller: def __init__(self): self.buttons = [False for _ in range(8)] self.index = 0 self.strobe = 0 def set_buttons(self, buttons): self.buttons = buttons def...
(button_a, button_b, button_select, button_start, button_up, button_down, button_left, button_right) = range(8) class Controller: def __init__(self): self.buttons = [False for _ in range(8)] self.index = 0 self.strobe = 0 def set_buttons(self, buttons): self.buttons = buttons ...
# wordCalculator.py # A program to calculate the number of words in a sentence # by Tung Nguyen def main(): # declare program function: print("This program calculates the number of words in a sentence.") print() # prompt user to input the sentence: sentence = input("Enter a phrase: ") ...
def main(): print('This program calculates the number of words in a sentence.') print() sentence = input('Enter a phrase: ') list_word = sentence.split() count_word = len(listWord) print() print('Number of words:', countWord) main()
class LexHelper: offset = 0 def get_max_linespan(self, p): defSpan = [1e60, -1] mSpan = [1e60, -1] for sp in range(0, len(p)): csp = p.linespan(sp) if csp[0] == 0 and csp[1] == 0: if hasattr(p[sp], "linespan"): csp = p[sp].line...
class Lexhelper: offset = 0 def get_max_linespan(self, p): def_span = [1e+60, -1] m_span = [1e+60, -1] for sp in range(0, len(p)): csp = p.linespan(sp) if csp[0] == 0 and csp[1] == 0: if hasattr(p[sp], 'linespan'): csp = p[sp]....
settings = {} settings['version'] = "0.1" settings['port'] = 36000 settings['product'] = "MOPIDY-PLEX" settings['debug_registration'] = False settings['debug_httpd'] = False settings['host'] = "" settings['token'] = None
settings = {} settings['version'] = '0.1' settings['port'] = 36000 settings['product'] = 'MOPIDY-PLEX' settings['debug_registration'] = False settings['debug_httpd'] = False settings['host'] = '' settings['token'] = None
def is_leap(year): if year >= 1900 and year <= pow(10,5): leap = False if year%4 == 0: if year%100 == 0: if year%400 == 0: leap = True else: leap = False else: leap = True return l...
def is_leap(year): if year >= 1900 and year <= pow(10, 5): leap = False if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: leap = True else: leap = False else: leap = True r...
def threshold_distance_mask(r, h): return r < h
def threshold_distance_mask(r, h): return r < h
load("@bazel_tools//tools/build_defs/repo:jvm.bzl", "jvm_maven_import_external") _default_server_urls = ["https://repo.maven.apache.org/maven2/", "https://mvnrepository.com/artifact", "https://maven-central.storage.googleapis.com", "http://gitblit...
load('@bazel_tools//tools/build_defs/repo:jvm.bzl', 'jvm_maven_import_external') _default_server_urls = ['https://repo.maven.apache.org/maven2/', 'https://mvnrepository.com/artifact', 'https://maven-central.storage.googleapis.com', 'http://gitblit.github.io/gitblit-maven', 'https://repository.mulesoft.org/nexus/content...
class OptionsStub(object): def __init__(self): self.debug = True self.guess_summary = False self.guess_description = False self.tracking = None self.username = None self.password = None self.repository_url = None self.disable_proxy = False self...
class Optionsstub(object): def __init__(self): self.debug = True self.guess_summary = False self.guess_description = False self.tracking = None self.username = None self.password = None self.repository_url = None self.disable_proxy = False sel...
service_dict = { 'NetworkService':{ 'getTargetsWithRelationshipTypeForResourceById':{}, 'getTargetsByRelationshipForSourceId':{}, 'getSourcesWithThisTargetByRelationshipCount':{}, 'deleteResource':{}, 'getSourceURIWithThisTargetByRelatiobnshipForResourceId':{}, 'getAl...
service_dict = {'NetworkService': {'getTargetsWithRelationshipTypeForResourceById': {}, 'getTargetsByRelationshipForSourceId': {}, 'getSourcesWithThisTargetByRelationshipCount': {}, 'deleteResource': {}, 'getSourceURIWithThisTargetByRelatiobnshipForResourceId': {}, 'getAllAttachmentOnlyResourceIDs': {}, 'getNamesAndAli...
### Stupid, but extensible spam detector STOP_SPAM_WORDS = ["Loan", "Lender", ".trade", ".bid", ".men", ".win"] def is_spam(request): if 'email' in request.form: if any( [ word.upper() in request.form['email'].upper() for word in STOP_SPAM_WORDS]): return True if 'username' in request.f...
stop_spam_words = ['Loan', 'Lender', '.trade', '.bid', '.men', '.win'] def is_spam(request): if 'email' in request.form: if any([word.upper() in request.form['email'].upper() for word in STOP_SPAM_WORDS]): return True if 'username' in request.form: if any([word.upper() in request.fo...
EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'findadoctor2@gmail.com' EMAIL_HOST_PASSWORD = 'Qwerty1@' EMAIL_USE_TLS = True
email_host = 'smtp.gmail.com' email_port = 587 email_host_user = 'findadoctor2@gmail.com' email_host_password = 'Qwerty1@' email_use_tls = True
#! /usr/bin/env Python3 list_of_tuples = [] list_of_tuples_comprehension = ([(i, j, i * j) for i in range(1, 11) for j in range(1, 11)]) for i in range(1, 11): for j in range(1, 11): list_of_tuples.append((i, j, i * j)) print(list_of_tuples) print('************') print(list_of_tuples_comprehension)
list_of_tuples = [] list_of_tuples_comprehension = [(i, j, i * j) for i in range(1, 11) for j in range(1, 11)] for i in range(1, 11): for j in range(1, 11): list_of_tuples.append((i, j, i * j)) print(list_of_tuples) print('************') print(list_of_tuples_comprehension)
TARGET_BAG = 'shiny gold' def get_data(filepath): return [line.strip() for line in open(filepath).readlines()] def parse_rule(rule): rule = rule.split(' ') adj, color = rule[0], rule[1] container_bag = '%s %s' % (adj, color) bags_contained = {} if rule[4:] == ['no', 'other', 'bags.']: ...
target_bag = 'shiny gold' def get_data(filepath): return [line.strip() for line in open(filepath).readlines()] def parse_rule(rule): rule = rule.split(' ') (adj, color) = (rule[0], rule[1]) container_bag = '%s %s' % (adj, color) bags_contained = {} if rule[4:] == ['no', 'other', 'bags.']: ...
class Instance: def __init__ (self, alloyfp): self.bitwidth = '4' self.maxseq = '4' self.mintrace = '-1' self.maxtrace = '-1' self.filename = alloyfp self.tracel = '1' self.backl = '0' self.sigs = [] self.fields = [] def add_sig(self, sig...
class Instance: def __init__(self, alloyfp): self.bitwidth = '4' self.maxseq = '4' self.mintrace = '-1' self.maxtrace = '-1' self.filename = alloyfp self.tracel = '1' self.backl = '0' self.sigs = [] self.fields = [] def add_sig(self, sig)...
# Find square root using newton raphson num = 987 eps = 1e-6 iteration = 0 sroot = num/2 while abs(sroot**2-num)>eps: iteration+=1 if sroot**2==num: print(f'At Iteration {iteration} : Found It!, the cube root for {num} is {sroot}') break sroot = sroot - (sroot**2-num)/(2*sroot) print(f'...
num = 987 eps = 1e-06 iteration = 0 sroot = num / 2 while abs(sroot ** 2 - num) > eps: iteration += 1 if sroot ** 2 == num: print(f'At Iteration {iteration} : Found It!, the cube root for {num} is {sroot}') break sroot = sroot - (sroot ** 2 - num) / (2 * sroot) print(f'At Iteration {iter...
HEADLINE = "time_elapsed\tsystem_time\tyear\tmonth\tday\tseasonal_factor\ttreatment_coverage_0_1\ttreatment_coverage_0_10\tpopulation\tsep\teir\tsep\tbsp_2_10\tbsp_0_5\tblood_slide_prevalence\tsep\tmonthly_new_infection\tsep\tmonthly_new_treatment\tsep\tmonthly_clinical_episode\tsep\tmonthly_ntf_raw\tsep\tKNY--C1x\tKNY...
headline = 'time_elapsed\tsystem_time\tyear\tmonth\tday\tseasonal_factor\ttreatment_coverage_0_1\ttreatment_coverage_0_10\tpopulation\tsep\teir\tsep\tbsp_2_10\tbsp_0_5\tblood_slide_prevalence\tsep\tmonthly_new_infection\tsep\tmonthly_new_treatment\tsep\tmonthly_clinical_episode\tsep\tmonthly_ntf_raw\tsep\tKNY--C1x\tKNY...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): a, b = headA, headB while a != b: a = a.next if a else headB b =...
class Solution(object): def get_intersection_node(self, headA, headB): (a, b) = (headA, headB) while a != b: a = a.next if a else headB b = b.next if b else headA return a
class DriverMeta(type): def __instancecheck__(cls, __instance) -> bool: return cls.__subclasscheck__(type(__instance)) def __subclasscheck__(cls, __subclass: type) -> bool: return ( hasattr(__subclass, 'create') and callable(__subclass.create) ) and ( ...
class Drivermeta(type): def __instancecheck__(cls, __instance) -> bool: return cls.__subclasscheck__(type(__instance)) def __subclasscheck__(cls, __subclass: type) -> bool: return (hasattr(__subclass, 'create') and callable(__subclass.create)) and (hasattr(__subclass, 'logs') and callable(__su...
# Simple example using ifs cars = ['volks', 'ford', 'audi', 'bmw', 'toyota'] for car in cars: if car == 'bmw': print(car.upper()) else: print(car.title()) # Comparing Values # # requested_toppings = 'mushrooms' # if requested_toppings != 'anchovies': # print('Hold the Anchovies') # # # ...
cars = ['volks', 'ford', 'audi', 'bmw', 'toyota'] for car in cars: if car == 'bmw': print(car.upper()) else: print(car.title()) age = 18 if age >= 18: print('OK to vote')
class Squad(): def __init__(self, handler, role, hold_point): self.handler = handler if len(handler.squads[role]) > 0: self.id = handler.squads[role][-1].id + 1 else: self.id = 1 self.units = { handler.unit.MARINE: [], handler...
class Squad: def __init__(self, handler, role, hold_point): self.handler = handler if len(handler.squads[role]) > 0: self.id = handler.squads[role][-1].id + 1 else: self.id = 1 self.units = {handler.unit.MARINE: [], handler.unit.SIEGETANK: []} self.ro...
infile=open('pairin.txt','r') n=int(infile.readline().strip()) dic={} for i in range(2*n): sn=int(infile.readline().strip()) if sn not in dic: dic[sn]=i else: dic[sn]-=i maxkey=min(dic,key=dic.get) outfile=open('pairout.txt','w') outfile.write(str(abs(dic[maxkey]))) outfile.close...
infile = open('pairin.txt', 'r') n = int(infile.readline().strip()) dic = {} for i in range(2 * n): sn = int(infile.readline().strip()) if sn not in dic: dic[sn] = i else: dic[sn] -= i maxkey = min(dic, key=dic.get) outfile = open('pairout.txt', 'w') outfile.write(str(abs(dic[maxkey]))) outf...
''' Created on Dec 4, 2017 @author: atip ''' def getAdjSquareSum(): global posX, posY, valMatrix adjSquareSum = 0 adjSquareSum += valMatrix[maxRange + posX + 1][maxRange + posY] adjSquareSum += valMatrix[maxRange + posX + 1][maxRange + posY + 1] adjSquareSum += valMatrix[maxRange + posX][maxRange ...
""" Created on Dec 4, 2017 @author: atip """ def get_adj_square_sum(): global posX, posY, valMatrix adj_square_sum = 0 adj_square_sum += valMatrix[maxRange + posX + 1][maxRange + posY] adj_square_sum += valMatrix[maxRange + posX + 1][maxRange + posY + 1] adj_square_sum += valMatrix[maxRange + posX...
# # @lc app=leetcode id=77 lang=python3 # # [77] Combinations # # @lc code=start class Solution: def combine(self, n, k): self.ans = [] nums = [num for num in range(1, n + 1)] if n == k: self.ans.append(nums) return self.ans else: ls = [] ...
class Solution: def combine(self, n, k): self.ans = [] nums = [num for num in range(1, n + 1)] if n == k: self.ans.append(nums) return self.ans else: ls = [] self.helper(nums, k, ls) return self.ans def helper(self, ar...
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/ # # 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 Software without restriction, including # without limitation the rights to use, copy,...
def get(prop, choices=None): prompt = prop.verbose_name if not prompt: prompt = prop.name if choices: if callable(choices): choices = choices() else: choices = prop.get_choices() valid = False while not valid: if choices: min = 1 ...
METR_LA_DATASET_NAME = 'metr_la' PEMS_BAY_DATASET_NAME = 'pems_bay' IN_MEMORY = 'mem' ON_DISK = 'disk'
metr_la_dataset_name = 'metr_la' pems_bay_dataset_name = 'pems_bay' in_memory = 'mem' on_disk = 'disk'
class Token(object): def __init__(self, access_token, refresh_token, lifetime): self.access_token = access_token # Access token value self.refresh_token = refresh_token # Token needed for refreshing access token self.lifetime = lifetime # Access token lifetime
class Token(object): def __init__(self, access_token, refresh_token, lifetime): self.access_token = access_token self.refresh_token = refresh_token self.lifetime = lifetime
def main(): print(hi) if __name__ == '__main__': main()
def main(): print(hi) if __name__ == '__main__': main()
class Node: def __init__(self, data): self.data = data self.next = None def __repr__(self): return self.data class LinkedList: def __init__(self): self.front = None self.rear = None def __repr__(self): current = self.front nodes = [] wh...
class Node: def __init__(self, data): self.data = data self.next = None def __repr__(self): return self.data class Linkedlist: def __init__(self): self.front = None self.rear = None def __repr__(self): current = self.front nodes = [] w...
def f(): a = 10 result = 0 result = sum_squares(a, result) print("Sum of squares: " + result) def sum_squares(a_new, result_new): while a_new < 10: result_new += a_new * a_new a_new += 1 return result_new
def f(): a = 10 result = 0 result = sum_squares(a, result) print('Sum of squares: ' + result) def sum_squares(a_new, result_new): while a_new < 10: result_new += a_new * a_new a_new += 1 return result_new
m = float(input('Digite um tamanho (em metros): ')) dm = m * 10 cm = m * 100 mm = m * 1000 dam = m / 10 hm = m / 100 km = m / 1000 print('convertendo...') print('[dm] =', dm) print('[cm] =', cm) print('[mm] =', mm) print('[dam] =', dam) print('[hm] =', hm) print('[km] =', km)
m = float(input('Digite um tamanho (em metros): ')) dm = m * 10 cm = m * 100 mm = m * 1000 dam = m / 10 hm = m / 100 km = m / 1000 print('convertendo...') print('[dm] =', dm) print('[cm] =', cm) print('[mm] =', mm) print('[dam] =', dam) print('[hm] =', hm) print('[km] =', km)
#Input, arguments def add(x,y): z = x + y b = 'I am here' a = 'hello' return z,b,a x = 20 y = 5 # Calling function print(add(x,y)) z = add(x,y) #same thing print(z) print(add(10,5)) #same thing
def add(x, y): z = x + y b = 'I am here' a = 'hello' return (z, b, a) x = 20 y = 5 print(add(x, y)) z = add(x, y) print(z) print(add(10, 5))
def main(request, response): referrer = request.headers.get("referer", "") response_headers = [("Content-Type", "text/javascript")]; return (200, response_headers, "window.referrer = '" + referrer + "'")
def main(request, response): referrer = request.headers.get('referer', '') response_headers = [('Content-Type', 'text/javascript')] return (200, response_headers, "window.referrer = '" + referrer + "'")
# # PySNMP MIB module IANA-ADDRESS-FAMILY-NUMBERS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IANA-ADDRESS-FAMILY-NUMBERS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 16:50:53 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Pytho...
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, constraints_intersection, value_range_constraint, single_value_constraint, constraints_union) ...
# regular assignment foo = 7 print(foo) # annotated assignmnet bar: number = 9 print(bar)
foo = 7 print(foo) bar: number = 9 print(bar)
VERSION = "0.7.0" LICENSE = "MIT - Copyright (c) 2021 Alex Vellone" MOTORS_CHECK_PER_SECOND = 20 MOTORS_POINT_TO_POINT_CHECK_PER_SECOND = 10 WEB_SOCKET_SEND_PER_SECOND = 10 SOCKET_SEND_PER_SECOND = 20 SOCKET_INCOMING_LIMIT = 5 SLEEP_AVOID_CPU_WASTE = 0.80
version = '0.7.0' license = 'MIT - Copyright (c) 2021 Alex Vellone' motors_check_per_second = 20 motors_point_to_point_check_per_second = 10 web_socket_send_per_second = 10 socket_send_per_second = 20 socket_incoming_limit = 5 sleep_avoid_cpu_waste = 0.8
model_fn = model_fn_builder( bert_config=bert_config, init_checkpoint=init_checkpoint, layer_indexes=layer_indexes, use_tpu=False, use_one_hot_embeddings=False) # If TPU is not available, this will fall back to normal Estimator on CPU # or GPU. estimator = tf.contrib.tpu.TPUEsti...
model_fn = model_fn_builder(bert_config=bert_config, init_checkpoint=init_checkpoint, layer_indexes=layer_indexes, use_tpu=False, use_one_hot_embeddings=False) estimator = tf.contrib.tpu.TPUEstimator(use_tpu=False, model_fn=model_fn, config=run_config, predict_batch_size=batch_size) input_fn = input_fn_builder(features...
# Exercico 1 - listas # Escreva program que leia a nome de 10 alunos # Armezene os nomes em uma lista # Imprema a lista nomes =[] for i in range(1,11): nome = [input(f'Informe o {i} Nome')] nomes.append(nome) for d in nomes: print(f' Nomes informados {d}')
nomes = [] for i in range(1, 11): nome = [input(f'Informe o {i} Nome')] nomes.append(nome) for d in nomes: print(f' Nomes informados {d}')
class Solution: def XXX(self, x: int) -> int: if x == 0: return 0 res = str(x) sign = 1 if res[0] == '-': res = res[1:] sign = -1 res = res[::-1] if res[0] == '0': res = res[1:] resint = int(res)*sign ...
class Solution: def xxx(self, x: int) -> int: if x == 0: return 0 res = str(x) sign = 1 if res[0] == '-': res = res[1:] sign = -1 res = res[::-1] if res[0] == '0': res = res[1:] resint = int(res) * sign ...
#Making a nice litte x o o o x o o o x tic tac toe board def printer(board): for i in range(3): for j in range (3): print(board[i][j], end="") if j<2: print(" | ", end="") print() if i<2: print("--+----+--") def main(): tictactoe=[[...
def printer(board): for i in range(3): for j in range(3): print(board[i][j], end='') if j < 2: print(' | ', end='') print() if i < 2: print('--+----+--') def main(): tictactoe = [[' ' for i in range(3)] for j in range(3)] for i in ...
#!/usr/bin/python # create_dict.py weekend = { "Sun": "Sunday", "Mon": "Monday" } vals = dict(one=1, two=2) capitals = {} capitals["svk"] = "Bratislava" capitals["deu"] = "Berlin" capitals["dnk"] = "Copenhagen" d = { i: object() for i in range(4) } print (weekend) print (vals) print (capitals) print (d)
weekend = {'Sun': 'Sunday', 'Mon': 'Monday'} vals = dict(one=1, two=2) capitals = {} capitals['svk'] = 'Bratislava' capitals['deu'] = 'Berlin' capitals['dnk'] = 'Copenhagen' d = {i: object() for i in range(4)} print(weekend) print(vals) print(capitals) print(d)
# to jest komentarz WIDTH = 550 HEIGHT = 550
width = 550 height = 550
# # @lc app=leetcode.cn id=617 lang=python3 # # [617] merge-two-binary-trees # None # @lc code=end
None
class Solution: def generatePossibleNextMoves(self, s: str) -> List[str]: results = [] for i in range(len(s) - 1): if s[i: i + 2] == "++": results.append(s[:i] + "--" + s[i + 2:]) return results
class Solution: def generate_possible_next_moves(self, s: str) -> List[str]: results = [] for i in range(len(s) - 1): if s[i:i + 2] == '++': results.append(s[:i] + '--' + s[i + 2:]) return results
heatmap_1_r = imresize(heatmap_1, (50,80)).astype("float32") heatmap_2_r = imresize(heatmap_2, (50,80)).astype("float32") heatmap_3_r = imresize(heatmap_3, (50,80)).astype("float32") heatmap_geom_avg = np.power(heatmap_1_r * heatmap_2_r * heatmap_3_r, 0.333) display_img_and_heatmap("dog.jpg", heatmap_geom_avg)
heatmap_1_r = imresize(heatmap_1, (50, 80)).astype('float32') heatmap_2_r = imresize(heatmap_2, (50, 80)).astype('float32') heatmap_3_r = imresize(heatmap_3, (50, 80)).astype('float32') heatmap_geom_avg = np.power(heatmap_1_r * heatmap_2_r * heatmap_3_r, 0.333) display_img_and_heatmap('dog.jpg', heatmap_geom_avg)
quantidade, menor, maior, soma = 0,0,0,0 quantidade = int(input()) while(quantidade>0): menor, maior, soma, final= 10,0,0,0 nome = input() dificuldade = float(input()) notas = input().split() notas = list(notas) for i in range(len(notas)): notas[i] = float(notas[i]) notas.sort() cont = 0 for i in range(len(n...
(quantidade, menor, maior, soma) = (0, 0, 0, 0) quantidade = int(input()) while quantidade > 0: (menor, maior, soma, final) = (10, 0, 0, 0) nome = input() dificuldade = float(input()) notas = input().split() notas = list(notas) for i in range(len(notas)): notas[i] = float(notas[i]) n...
ALLERGIES_SCORE = ['eggs', 'peanuts', 'shellfish', 'strawberries', 'tomatoes', 'chocolate', 'pollen', 'cats'] class Allergies: def __init__(self, score: int): self.score = score self.lst = self.list_of_allergies() def allergic_to(self, item: str) -> bool: retur...
allergies_score = ['eggs', 'peanuts', 'shellfish', 'strawberries', 'tomatoes', 'chocolate', 'pollen', 'cats'] class Allergies: def __init__(self, score: int): self.score = score self.lst = self.list_of_allergies() def allergic_to(self, item: str) -> bool: return item in self.lst ...
class Number: def __init__(self, start): self.data = start def __sub__(self, other): return Number(self.data - other) class Indexer: data = [5, 6, 7, 8, 9] def __getitem__(self, item): print('getitem:', item) return self.data[item] def __setitem__(self, index, va...
class Number: def __init__(self, start): self.data = start def __sub__(self, other): return number(self.data - other) class Indexer: data = [5, 6, 7, 8, 9] def __getitem__(self, item): print('getitem:', item) return self.data[item] def __setitem__(self, index, va...
# This helper file, setups the rules and rewards for the mouse grid system # State = 1, start point # Action - 1: Top, 2:Left, 3:Right, 4:Down def transition_rules(state, action): # For state 1 if state == 1 and (action == 3 or action == 4): state = 1 elif state == 1 and action == 1: state...
def transition_rules(state, action): if state == 1 and (action == 3 or action == 4): state = 1 elif state == 1 and action == 1: state = 5 elif state == 1 and action == 2: state = 2 elif state == 2 and action == 4: state = 2 elif state == 2 and action == 1: sta...
# # PySNMP MIB module HUAWEI-BRAS-SBC-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-BRAS-SBC-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:31:26 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_intersection, value_size_constraint, constraints_union) ...
description = 'Aircontrol PLC devices' group = 'optional' tango_base = 'tango://kompasshw.kompass.frm2:10000/kompass/aircontrol/plc_' devices = dict( spare_motor_x2 = device('nicos.devices.entangle.Motor', description = 'spare motor', tangodevice = tango_base + 'spare_mot_x2', fmtstr = '%...
description = 'Aircontrol PLC devices' group = 'optional' tango_base = 'tango://kompasshw.kompass.frm2:10000/kompass/aircontrol/plc_' devices = dict(spare_motor_x2=device('nicos.devices.entangle.Motor', description='spare motor', tangodevice=tango_base + 'spare_mot_x2', fmtstr='%.4f', visibility=()), shutter=device('ni...
def make_prime_table(n): sieve = list(range(n + 1)) sieve[0] = -1 sieve[1] = -1 for i in range(4, n + 1, 2): sieve[i] = 2 for i in range(3, int(n ** 0.5) + 1, 2): if sieve[i] != i: continue for j in range(i * i, n + 1, i * 2): if sieve[j] == j: ...
def make_prime_table(n): sieve = list(range(n + 1)) sieve[0] = -1 sieve[1] = -1 for i in range(4, n + 1, 2): sieve[i] = 2 for i in range(3, int(n ** 0.5) + 1, 2): if sieve[i] != i: continue for j in range(i * i, n + 1, i * 2): if sieve[j] == j: ...
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'publics', 'USER': 'publics_read_only', 'PASSWORD': r'read-only', 'HOST': '5.153.9.51', 'PORT': '5432', } } INSTALLED_APPS = ( 'contracts', 'law', 'deputies' ) # ...
databases = {'default': {'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'publics', 'USER': 'publics_read_only', 'PASSWORD': 'read-only', 'HOST': '5.153.9.51', 'PORT': '5432'}} installed_apps = ('contracts', 'law', 'deputies') secret_key = 'not-secret'
body_max_width = 15 body_max_height = 15 def validate_body_str_profile(body: str): body_lines = body.splitlines() width = len(body_lines[0]) height = len(body_lines) if width > body_max_width or height > body_max_height: raise ValueError("Body string is too big")
body_max_width = 15 body_max_height = 15 def validate_body_str_profile(body: str): body_lines = body.splitlines() width = len(body_lines[0]) height = len(body_lines) if width > body_max_width or height > body_max_height: raise value_error('Body string is too big')
n, x = map(int, input().split()) if (x > n // 2 and n % 2 == 0) or (x > (n + 1) // 2 and n % 2 == 1): x = n - x A = n - x B = x k = 0 m = -1 ans = n while m != 0: k = A // B m = A % B ans += B * k * 2 if m == 0: ans -= B A = B B = m print(ans)
(n, x) = map(int, input().split()) if x > n // 2 and n % 2 == 0 or (x > (n + 1) // 2 and n % 2 == 1): x = n - x a = n - x b = x k = 0 m = -1 ans = n while m != 0: k = A // B m = A % B ans += B * k * 2 if m == 0: ans -= B a = B b = m print(ans)
string_1 = input("String 1? ") string_2 = input("String 2? ") string_3 = input("String 3? ") print(string_1 + string_2 + string_3)
string_1 = input('String 1? ') string_2 = input('String 2? ') string_3 = input('String 3? ') print(string_1 + string_2 + string_3)
''' URL: https://leetcode.com/problems/slowest-key/ Difficulty: Easy Description: Slowest Key A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time. You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, and a so...
""" URL: https://leetcode.com/problems/slowest-key/ Difficulty: Easy Description: Slowest Key A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time. You are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, and a so...
# LeetCode #437 - Path Sum III # https://leetcode.com/problems/path-sum-iii/ # Prefix-sum hashing solution. Runs in linear time. # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = righ...
class Solution: @staticmethod def path_sum(root: TreeNode, targetSum: int) -> int: history = collections.Counter((0,)) def dfs(node, acc): if not node: return 0 acc += node.val count = history[acc - targetSum] history[acc] += 1 ...
class SearchToursData: def __init__(self, destination, tour_type, start_year, start_month, start_day, adults_num): self.destination = destination self.tour_type = tour_type self.start_year = start_year self.start_month = start_month self.start_day = start_day self.ad...
class Searchtoursdata: def __init__(self, destination, tour_type, start_year, start_month, start_day, adults_num): self.destination = destination self.tour_type = tour_type self.start_year = start_year self.start_month = start_month self.start_day = start_day self.ad...
def first_non_repeating_letter(string): lowercase_string = string.lower() result = [] for i in lowercase_string: if (lowercase_string.count(i) == 1): result.append(i) if (len(result) == 0): return "" else: if (string.find(result[0]) == -1 ): return re...
def first_non_repeating_letter(string): lowercase_string = string.lower() result = [] for i in lowercase_string: if lowercase_string.count(i) == 1: result.append(i) if len(result) == 0: return '' elif string.find(result[0]) == -1: return result[0].upper() else...
datasets = ('source',) def synthesis(job): d = {} agg = 0 for dt, x in datasets.source.iterate('roundrobin', ('DATE_OF_INTEREST', 'CASE_COUNT')): agg += x d[dt] = agg return d
datasets = ('source',) def synthesis(job): d = {} agg = 0 for (dt, x) in datasets.source.iterate('roundrobin', ('DATE_OF_INTEREST', 'CASE_COUNT')): agg += x d[dt] = agg return d
''' Created on 16 ago 2017 @author: Hamza ''' class MyClass(object): ''' classdocs ''' def __init__(self, params): ''' Constructor '''
""" Created on 16 ago 2017 @author: Hamza """ class Myclass(object): """ classdocs """ def __init__(self, params): """ Constructor """
class Solution: def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int: working = 0 for i, stu in enumerate(startTime): if stu <= queryTime and endTime[i] >= queryTime: working += 1 return working
class Solution: def busy_student(self, startTime: List[int], endTime: List[int], queryTime: int) -> int: working = 0 for (i, stu) in enumerate(startTime): if stu <= queryTime and endTime[i] >= queryTime: working += 1 return working
class Solution: def makeEqual(self, words: List[str]) -> bool: n = len(words) words = ''.join(words) letterCounter = Counter(words) print(letterCounter ) for letter in letterCounter: if letterCounter[letter] % n !=0: return False ...
class Solution: def make_equal(self, words: List[str]) -> bool: n = len(words) words = ''.join(words) letter_counter = counter(words) print(letterCounter) for letter in letterCounter: if letterCounter[letter] % n != 0: return False return ...
EARTH = 6371000 MOON = 1737100 MARS = 3389500 JUPITER = 69911000
earth = 6371000 moon = 1737100 mars = 3389500 jupiter = 69911000
#=============================================================================== # Created: 22 May 2019 # @author: AP (adapated from Jesse Wilson) # Description: Class to contain Anaplan connection details required for all API calls # Input: Authorization header string, workspace ID string, an...
class Anaplanconnection(object): """ classdocs """ def __init__(self, authorization, workspaceGuid, modelGuid): """ :param authorization: Authorization header string :param workspaceGuid: ID of the Anaplan workspace :param modelGuid: ID of the Anaplan model "...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def sumRootToLeaf(self, root: TreeNode) -> int: if root is None: return 0 sum = 0 def plusAllLeaves(...
class Solution: def sum_root_to_leaf(self, root: TreeNode) -> int: if root is None: return 0 sum = 0 def plus_all_leaves(node, parentPath): nonlocal sum curr_path = parentPath + str(node.val) if node.left is None and node.right is None: ...
DEFAULT_POSTGREST_CLIENT_HEADERS = { "Accept": "application/json", "Content-Type": "application/json", } DEFAULT_POSTGREST_CLIENT_TIMEOUT = 5
default_postgrest_client_headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} default_postgrest_client_timeout = 5
# https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ class TreeNode: def __init__(self, x, left=None, right=None): self.val = x self.left = left self.right = right class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'Tr...
class Treenode: def __init__(self, x, left=None, right=None): self.val = x self.left = left self.right = right class Solution: def lowest_common_ancestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': res = None def find_lca(node): if...
class Solution(object): def searchMatrix(self, matrix, target): if not matrix or target is None: return False rows, cols = len(matrix), len(matrix[0]) low, high = 0, rows* cols - 1 while low <= high: mid = (low + high) / 2 num = matrix[mid / cols...
class Solution(object): def search_matrix(self, matrix, target): if not matrix or target is None: return False (rows, cols) = (len(matrix), len(matrix[0])) (low, high) = (0, rows * cols - 1) while low <= high: mid = (low + high) / 2 num = matrix[m...
class SWTestCase: def __init__(self): pass @classmethod def configure(cls): pass def setUp(self): pass def tearDown(self): pass def run_all_test_case(self): for test in self.test_to_run: self.setUp() test() self.te...
class Swtestcase: def __init__(self): pass @classmethod def configure(cls): pass def set_up(self): pass def tear_down(self): pass def run_all_test_case(self): for test in self.test_to_run: self.setUp() test() self.t...
def even_odd(*args): args = list(args) command = args.pop() if command == "even": return [x for x in args if x % 2 == 0] return [x for x in args if not x % 2 == 0] print(even_odd(1, 2, 3, 4, 5, 6, "even")) print(even_odd(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "odd"))
def even_odd(*args): args = list(args) command = args.pop() if command == 'even': return [x for x in args if x % 2 == 0] return [x for x in args if not x % 2 == 0] print(even_odd(1, 2, 3, 4, 5, 6, 'even')) print(even_odd(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'odd'))
class UnionFind(): def __init__(self, n) -> None: self.par = [-1] * n self.siz = [1] * n # return root of x def root(self, x): if self.par[x] == -1: return x else: self.par[x] = self.root(self.par[x]) return self.par[x] # ret...
class Unionfind: def __init__(self, n) -> None: self.par = [-1] * n self.siz = [1] * n def root(self, x): if self.par[x] == -1: return x else: self.par[x] = self.root(self.par[x]) return self.par[x] def issame(self, x, y): return...
class Node: def __init__(self, k, v): self.key = k self.val = v self.pre = None self.nxt = None class LRUCache: def __init__(self, capacity: int): self.store = {} self.curCap = 0 self.cap = capacity self.tail = Node(0, 0) self.head = Nod...
class Node: def __init__(self, k, v): self.key = k self.val = v self.pre = None self.nxt = None class Lrucache: def __init__(self, capacity: int): self.store = {} self.curCap = 0 self.cap = capacity self.tail = node(0, 0) self.head = nod...
# Lab 5 ''' G=(V,E) Let V be the set v0,v1,v2,... (i.e., with ascending non-negative indices) and E be the set e0,e1,e2,... (i.e., with ascending non-negative indices) ''' class stack: def __init__(self): self.lifo = [] def push(self,ele): self.lifo = self.lifo + [ele] return True def po...
""" G=(V,E) Let V be the set v0,v1,v2,... (i.e., with ascending non-negative indices) and E be the set e0,e1,e2,... (i.e., with ascending non-negative indices) """ class Stack: def __init__(self): self.lifo = [] def push(self, ele): self.lifo = self.lifo + [ele] return True def p...
# omnibool.py # https://www.codewars.com/kata/5a5f9f80f5dc3f942b002309/train/python class Omnibool(): def __eq__(self, x): return True if __name__ == "__main__": omnibool = Omnibool() print(omnibool == True and omnibool == False)
class Omnibool: def __eq__(self, x): return True if __name__ == '__main__': omnibool = omnibool() print(omnibool == True and omnibool == False)
def get_test_accounts() -> dict: return { 'development': { 'color': '#388E3C', 'team': 'awesome-team', 'region': 'us-east-1', 'profiles': [ { 'profile': 'developer', 'account': '123495678901', ...
def get_test_accounts() -> dict: return {'development': {'color': '#388E3C', 'team': 'awesome-team', 'region': 'us-east-1', 'profiles': [{'profile': 'developer', 'account': '123495678901', 'role': 'developer', 'default': 'true'}, {'profile': 'readonly', 'account': '012349567890', 'role': 'readonly'}]}, 'live': {'co...
def NoC(): paid = int(input()) moneyL = [500, 100, 50, 10, 5, 1] count = 0 leftOver = 1000 - paid for each in moneyL: n = leftOver//each if n > 0: count += n leftOver -= n * each elif n == 0: pass return count print(NoC())
def no_c(): paid = int(input()) money_l = [500, 100, 50, 10, 5, 1] count = 0 left_over = 1000 - paid for each in moneyL: n = leftOver // each if n > 0: count += n left_over -= n * each elif n == 0: pass return count print(no_c())
def get_average(g): return sum(g) / len(g) n = int(input()) students_record = {} for _ in range(n): student, grade = input().split() if student not in students_record: students_record[student] = [] students_record[student].append(float(grade)) for s, g in students_record.items(): ave...
def get_average(g): return sum(g) / len(g) n = int(input()) students_record = {} for _ in range(n): (student, grade) = input().split() if student not in students_record: students_record[student] = [] students_record[student].append(float(grade)) for (s, g) in students_record.items(): average...
names = ["Alan", "Bruce", "Carlos", "David", "Emma"] scores = [90, 80, 85, 92, 81] for name in names: print("hello, %s!" % name)
names = ['Alan', 'Bruce', 'Carlos', 'David', 'Emma'] scores = [90, 80, 85, 92, 81] for name in names: print('hello, %s!' % name)
def insertShiftArray(arr, num): count = len(arr) middle = len(arr) // 2 shift_arr = [] for i in range(count): if i != middle: shift_arr.append(arr[i]) else: if count % 2 == 0: shift_arr.append(num) shift_arr.append(arr[i]) ...
def insert_shift_array(arr, num): count = len(arr) middle = len(arr) // 2 shift_arr = [] for i in range(count): if i != middle: shift_arr.append(arr[i]) elif count % 2 == 0: shift_arr.append(num) shift_arr.append(arr[i]) else: shift...
# Carve # sigs = [255,214,124,179,233] # msks = [0,9,3,12,6] # Door # sigs = [192,48] # msks = [15,15] # Freestanding # sigs=[0,0,0,0,16,64,32,128,161,104,84,146] # msks=[8,4,2,1,6,12,9,3,10,5,10,5] # Walls sigs=[251,233,253,84,146,80,16,144,112,208,241,248,210,177,225,120,179,0,124,104,161,64,240,128,224,176,242,24...
sigs = [251, 233, 253, 84, 146, 80, 16, 144, 112, 208, 241, 248, 210, 177, 225, 120, 179, 0, 124, 104, 161, 64, 240, 128, 224, 176, 242, 244, 116, 232, 178, 212, 247, 214, 254, 192, 48, 96, 32, 160, 245, 250, 243, 249, 246, 252] msks = [0, 6, 0, 11, 13, 11, 15, 13, 3, 9, 0, 0, 9, 12, 6, 3, 12, 15, 3, 7, 14, 15, 0, 15, ...
# # PySNMP MIB module ZONE-DEFENSE-MGMT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZONE-DEFENSE-MGMT-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:48:06 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, constraints_intersection, single_value_constraint, value_size_constraint, value_range_constraint) ...
print('4. testing integrated scan functions:') print('testing xanes') xanes(erange = [7112-30, 7112-20, 7112+30], estep = [2, 5], harmonic = None, acqtime=0.2, roinum=1, i0scale = 1e8, itscale = 1e8,samplename='test',filename='test')
print('4. testing integrated scan functions:') print('testing xanes') xanes(erange=[7112 - 30, 7112 - 20, 7112 + 30], estep=[2, 5], harmonic=None, acqtime=0.2, roinum=1, i0scale=100000000.0, itscale=100000000.0, samplename='test', filename='test')
class CouldNotConfigureException(BaseException): def __str__(self): return "Could not configure the repository." class NotABinaryExecutableException(BaseException): def __str__(self): return "The file given is not a binary executable" class ParametersNotAcceptedException(BaseException): ...
class Couldnotconfigureexception(BaseException): def __str__(self): return 'Could not configure the repository.' class Notabinaryexecutableexception(BaseException): def __str__(self): return 'The file given is not a binary executable' class Parametersnotacceptedexception(BaseException): ...
# # PySNMP MIB module Nortel-MsCarrier-MscPassport-BaseSnmpMIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-MsCarrier-MscPassport-BaseSnmpMIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:19:57 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davw...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, single_value_constraint, constraints_union, value_size_constraint, constraints_intersection) ...
c = open("__21_d03.txt") lin = c.readlines() ## Part 1 klin = [list([lin[i].split("\n")[0] for i in range(len(lin))][j]) for j in range(len(lin))] k2 = [1 if [klin[jj][len(klin[0])-ii-1] for jj in range(len(lin))].count('1') > [klin[jj][len(klin[0])-ii-1] for jj in range(len(lin))].count('0') else 0 for ii in range(...
c = open('__21_d03.txt') lin = c.readlines() klin = [list([lin[i].split('\n')[0] for i in range(len(lin))][j]) for j in range(len(lin))] k2 = [1 if [klin[jj][len(klin[0]) - ii - 1] for jj in range(len(lin))].count('1') > [klin[jj][len(klin[0]) - ii - 1] for jj in range(len(lin))].count('0') else 0 for ii in range(len(k...
# config.py # encoding:utf-8 DEBUG = True JSON_AS_ASCII = False
debug = True json_as_ascii = False
num = 42 list_of_numbers = [] for i in range(1, num+1): list_of_numbers.append(i) print(list_of_numbers) death = 3 for i in list_of_numbers: if i == num: if i == death: print("XX") else: print(i) elif i < 10: if i == death: print(f"XX", end=" -...
num = 42 list_of_numbers = [] for i in range(1, num + 1): list_of_numbers.append(i) print(list_of_numbers) death = 3 for i in list_of_numbers: if i == num: if i == death: print('XX') else: print(i) elif i < 10: if i == death: print(f'XX', end=' - '...
class Solution: def numMovesStonesII(self, stones: List[int]) -> List[int]: def helper(): n = len(stones) if (stones[-2] - stones[0] == n - 2 and stones[-1] - stones[-2] > 2) or (stones[-1] - stones[1] == n - 2 and stones[1] - stones[0] > 2): return 2 dq =...
class Solution: def num_moves_stones_ii(self, stones: List[int]) -> List[int]: def helper(): n = len(stones) if stones[-2] - stones[0] == n - 2 and stones[-1] - stones[-2] > 2 or (stones[-1] - stones[1] == n - 2 and stones[1] - stones[0] > 2): return 2 d...
class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: order_indx = {} for idx,letter in enumerate(order): order_indx[letter] = idx # compare adjacent words for i in range(len(words)-1): word1 = words[i] w...
class Solution: def is_alien_sorted(self, words: List[str], order: str) -> bool: order_indx = {} for (idx, letter) in enumerate(order): order_indx[letter] = idx for i in range(len(words) - 1): word1 = words[i] word2 = words[i + 1] if word1 == ...
def center(win, width=100, height=100): win.update_idletasks() width = width frm_width = win.winfo_rootx() - win.winfo_x() win_width = width + 2 * frm_width height = height titlebar_height = win.winfo_rooty() - win.winfo_y() win_height = height + titlebar_height + frm_width x = win.wi...
def center(win, width=100, height=100): win.update_idletasks() width = width frm_width = win.winfo_rootx() - win.winfo_x() win_width = width + 2 * frm_width height = height titlebar_height = win.winfo_rooty() - win.winfo_y() win_height = height + titlebar_height + frm_width x = win.winfo...
array = list(map(int, input('Enter the array of integers to be sorted(separated by spaces):').split())) for i in range(len(array)): min_idx = i for j in range(i + 1, len(array)): if array[min_idx] > array[j]: min_idx = j array[i], array[min_idx] = array[min_idx], array[i] print("Sorted ...
array = list(map(int, input('Enter the array of integers to be sorted(separated by spaces):').split())) for i in range(len(array)): min_idx = i for j in range(i + 1, len(array)): if array[min_idx] > array[j]: min_idx = j (array[i], array[min_idx]) = (array[min_idx], array[i]) print('Sort...
batch_size = 192*4 config = {} # set the parameters related to the training and testing set data_train_opt = {} data_train_opt['batch_size'] = batch_size data_train_opt['unsupervised'] = True data_train_opt['epoch_size'] = None data_train_opt['random_sized_crop'] = False data_train_opt['dataset_name'] = 'imagenet' ...
batch_size = 192 * 4 config = {} data_train_opt = {} data_train_opt['batch_size'] = batch_size data_train_opt['unsupervised'] = True data_train_opt['epoch_size'] = None data_train_opt['random_sized_crop'] = False data_train_opt['dataset_name'] = 'imagenet' data_train_opt['split'] = 'train' data_test_opt = {} data_test_...
# -*- coding: utf-8 -*- def main(): n = int(input()) ans = 0 for i in range(1, int(n ** 0.5) + 1): if n % i == 0 and (i ** 2) != n: m = n // i - 1 if n // m == n % m: ans += m print(ans) if __name__ == '__main__': main()
def main(): n = int(input()) ans = 0 for i in range(1, int(n ** 0.5) + 1): if n % i == 0 and i ** 2 != n: m = n // i - 1 if n // m == n % m: ans += m print(ans) if __name__ == '__main__': main()