content stringlengths 7 1.05M |
|---|
# Define minimum distance threshold in map
dist_thresh = 0.5
scaling_factor = int(1 / dist_thresh)
# Define threshold around goal
goal_thresh = int(scaling_factor * 1.5)
# Define map size
width, height = 300, 200
map_size = (scaling_factor * height), (scaling_factor * width)
# Define all the possible no. of actions
max... |
def outside(r, c, size):
if r < 0 or c < 0 or r >= size or c >= size:
return True
return False
def get_next_pos(r, c, command):
if command == 'up':
return r - 1, c
elif command == 'down':
return r + 1, c
elif command == 'left':
return r, c - 1
elif command == 'r... |
# eradicate a destroyed file system snapshot named myfs.mysnap
client.delete_file_system_snapshots(names=["myfs.mysnap"])
# Other valid fields: ids
# See section "Common Fields" for examples
|
'''
The Olympic competitions between 1952 and 1988 took place during the height of the Cold War between the United States of America (USA) & the Union of Soviet Socialist Republics (USSR). Your goal in this exercise is to aggregate the number of distinct sports in which the USA and the USSR won medals during the Cold W... |
grades = int(input())
name_exam = str(input())
grade = int(input())
poor_grade = 0
pas = True
average = 0
problems_solved = 0
last_name_exam = str()
while name_exam != "Enough":
if int(grade) <= 4:
poor_grade += 1
if poor_grade == grades:
pas = False
break
problems_solved += 1
a... |
# Coding is all about making things easier for ourselves.
# Some times you will be writing the same code over and
# over again. When this happens, it is often best to write
# a function.
# functions are defined with the def keyword:
def paulsFunction():
# anything inside the function will execute when I call it
... |
#! /usr/bin/env python
"""A package that implements HTTP 1.1"""
__all__ = ['grammar', 'params', 'messages', 'auth', 'client']
|
def narcissistic(num):
sum = 0
iterableNum = str(num)
for i in iterableNum:
sum += int(i) ** len(iterableNum)
return True if sum == num else False
# One-liner:
def narcissistic2(num):
return num == sum(int(i) ** len(str(num)) for i in str(num)) |
def answer_type(request, json_list, nested):
for question in json_list:
if question['payload']['object_type'] == 'task_instance':
question['answer_class'] = 'task_answer'
|
def test_example_resource(example_resource):
"""Check that the example resource was loaded correctly."""
assert len(example_resource) == 4
assert example_resource[0]["average"] == 6.29
|
#!/usr/bin/env python
# Copyright (c) 2013. Mark E. Madsen <mark@madsenlab.org>
#
# This work is licensed under the terms of the Apache Software License, Version 2.0. See the file LICENSE for details.
"""
Description here
"""
def getMingConfiguration(modules):
config = {}
for module in modules:
url... |
# Solution 1
# def remove_duplicates(arr):
# val_tracker = {}
# for num in arr:
# if num not in arr:
# val_tracker[num] = 1
# else:
# print('True')
# return True
# print('False')
# return False
# Solution 2
def remove_duplicates(arr):
unique ... |
index = 1
result = 0
while index < 1000:
if index % 3 ==0 or index % 5 == 0:
result = result + index
index = index + 1
print(result) |
class NoticeModel:
def __init__(self, dbRow):
self.ID = dbRow["ID"]
self.Message = dbRow["Message"]
self.Timestamp = dbRow["Timestamp"] |
def keep_one_mRNA_with_same_stop_codon_position(f):
output = []
nameset = set()
with open(f, 'r') as FILE:
for line in FILE:
if line[0] == '#':
output.append(line.strip())
else:
s = line.strip().split('\t')
if s[6] ==... |
#usr/bin/env python
#-*- coding:utf-8- -*-
FPS = 60 # 游戏帧率
QUICKFPS = 60
SLOWFPS = 15
WIN_WIDTH = 800 # 窗口宽度
WIN_HEIGHT = 980 # 窗口高度
BUBBLE_SPACE = 40
INIT_R = 10
DR = 4
NUMBER = 10
COLORS = {
"bg": (240, 255, 255), # 背景颜色
"bubble": (135, 206, 235),
# "select": (135, 206, 235),
"select": (0, 13... |
class Building(object):
def __init__(self, south, west, width_WE, width_NS, height=10):
self.south = south
self.west = west
self.width_WE = width_WE
self.width_NS = width_NS
self.height = height
def corners(self):
north_west = [self.south+self.width_NS, self.... |
def bio(*args):
header = ["Name", "Roll no.", "Regd no.", "Branch", "Stream", "Sem", "Phone no.", "Address"]
for head, data in zip(header, args):
print("%-10s: %s"%(head, data))
bio("Md.Azharuddin", "36725", "1701105431", "CSE", "B.Tech", "7th", "9078600498", "Arad Bazar, Balasore") |
# -*- coding: utf-8 -*-
"""
HackerRank practice problems
Companies: Dialpad, etc
"""
"print odd numbers between l and r"
def oddNumbers(l, r):
odd = []
while l<=r:
if l%2!=0:
odd.append(l)
l+=2
elif l==0:
l+=1
else:
l+=1
return odd
"pr... |
def sum_list(x):
sum = 0
for i in x:
sum += i
return sum
def str_cvt_lower(s):
"""konversi besar->kecil"""
return s.lower()
def str_cvt_upper(s):
"""konversi kecil->besar"""
return s.upper()
|
def sum_of_multiples(limit: int, factors: list) -> int:
"""Give sum of all the multiples of given numbers untill given limit"""
set_of_multiples = {i
for factor in factors
if factor != 0
for i in range(factor, limit, factor)
... |
class Subscription(object):
def __init__(self, sid, subject, queue, callback, connetion):
self.sid = sid
self.subject = subject
self.queue = queue
self.connetion = connetion
self.callback = callback
self.received = 0
self.delivered = 0
self.bytes = 0
... |
"""
Global Django Town exception and warning classes.
"""
class SettingError(Exception):
pass
class ThirdPartyDependencyError(Exception):
pass |
def add(a, b):
a += b
return a
class School(object):
def __init__(self,name,teachers=[]):
self.name = name
self.teachers = teachers
def add(self,teach_name):
self.teachers.append(teach_name)
def remove(self,teach_name):
self.teachers.remove(teach_name)
if __name__ =... |
class Animation():
def __init__(self):
self.vertex_n = 0
self.verticies = []
def get_coord(self, V_kind):
print("\n\t***\nFor vertex %s please enter:\n" % V_kind)
x = input('X: ')
y = input('Y: ')
z = input('Z: ')
pos = [x, y, z]
return pos
def add_Vertex(self):... |
#Faça um programa que leia um numero Inteiro
#qualquer e mostre sua tabuada
n = int(input('Informe um numero inteiro: '))
print('A tabuada do {} é:'.format(n))
i = 1
while i <= 10:
print('{} x {} = {}'.format(n, i, n*i))
i = i + 1
|
with open("input.txt", "r") as f:
lines = [line.strip() for line in f.readlines()]
gamma = ""
epsilon = ""
for i in range(0, len(lines[0])):
zero = 0
one = 0
for line in lines:
if line[i] == "0":
zero += 1
else: one += 1
if(zero >... |
def comp_height(self):
"""Compute the height of the Hole (Rmax-Rmin)
Parameters
----------
self : Hole
A Hole object
Returns
-------
H : float
Height of the hole
"""
(Rmin, Rmax) = self.comp_radius()
return Rmax - Rmin
|
COLOUR_CHOICES = [
('white', 'White'),
('grey', 'Grey'),
('blue', 'Blue'),
]
COLUMN_CHOICES = [
('12', 'Full Width'),
('11', '11/12'),
('10', '5/6'),
('9', 'Three Quarters'),
('8', 'Two Thirds'),
('7', '7/12'),
('6', 'Half Width'),
('5', '5/12'),
('4', 'One Third'),
... |
#$Id$#
class ExchangeRateList:
"""This class is used to create object for Exchange Rate List."""
def __init__(self):
"""Initialize parameters for exchange rate list."""
self.exchange_rates = []
def set_exchange_rates(self, exchange_rate):
"""Set exchange rate.
Args:
... |
x = 1 # int
y = 2.8 # float
z = 1j # complex
# convert from int to float
a = float(x)
# convert from float to int
b = int(y)
# convert from int to complex
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
|
"""Module containing the exception class for regexapp."""
class PatternError(Exception):
"""Use to capture error during pattern conversion."""
class EscapePatternError(PatternError):
"""Use to capture error during performing do_soft_regex_escape"""
class PatternReferenceError(PatternError):
"""Use to ... |
#week 5 - chapter 9 - dictionaries
#another collection, more than one value
#a list is a very linear collection of values that stay in order
#dictionary is a "bag" of values, each with its own label (key)
#like a mini database
#dictionaries have no order but always a key to find a value
"""
purse = dict()
purse["mon... |
def palindromo(str):
s = str.lower()
if(s == s[::-1]):
print("É um palíndromo")
else:
print("Não é palíndromo")
pali = "Ana"
palindromo(pali) |
class Identifier:
def __init__(self, id):
self.id = id
def eval(self, env):
if self.id in env:
return env[self.id]
else:
error("Referencing " + self.id + " before assignment")
def __repr__(self):
return "Identifier: {0}".format(self.i... |
WORKERS = 50
RESULT_FILE = 'results.json'
ZIP_CODE_FILE = './reference/zips.csv'
|
# 141, Суптеля Владислав
# 【Дата】:「09.03.20」
# 14. Дано натуральне число N. Виведіть слово YES, якщо число N є точним ступенем двійки, або слово NO в іншому випадку.
n = int(input("「Введите число」: "))
def chernosliv(n):
if n & (n-1) and n != 0: # побитовое сравнение n и того что перед ним
p... |
NAME = 'send_message.py'
ORIGINAL_AUTHORS = [
'Justin Walker'
]
ABOUT = '''
Sends a message to another channel.
'''
COMMANDS = '''
>>> .send #channel .u riceabove .m how are you?
Sends a message to #channel like
'IronPenguin from #channel says to riceabove: how are you?'
>>> .send #channel hi all
Sends a messag... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def printList(self):
temp = self.head
while temp :
print(temp.data, end=" ")
temp = temp.next
def append(self, new_data):
new_node = Node(new_data)
if self.hea... |
class IUserCommandRepository:
def create_user(self, user):
pass
def update_user_auth_token(self, user_id, auth_token):
pass
def increment_user_score(self, user_id, score):
pass
|
out = []
push = out.append
concate = ' '.join
while True:
try:
a, b = [int(x) for x in input().split()]
except EOFError:
break
ans = []
ans_append = ans.append
for num in range(a, b+1):
num = str(num)
length = len(num)
check = str(sum(pow(int(x), length) for x... |
def characters_between(start: str, end: str):
start = ord(start)
end = ord(end)
if start < end:
for letter in range(start + 1, end):
print(chr(letter), end=' ')
else:
for i in range(end + 1, start, -1):
print(chr(i), end=' ')
a = input()
b = input()
characters_b... |
def solve(sudoku):
find = find_empty(sudoku)
if not find:
return True
else:
row, col = find
for i in range(1,10):
if valid(sudoku, i, (row, col)):
sudoku[row][col] = i
if solve(sudoku):
return True
sudoku[row][col] = 0
r... |
# -*- coding: utf-8 -*-
# @Author: 何睿
# @Create Date: 2019-02-06 09:19:35
# @Last Modified by: 何睿
# @Last Modified time: 2019-02-06 17:33:50
class Solution:
def numSquares(self, n: 'int') -> 'int':
# 动态规划数组,dynamic[i]表示数字i可以最少可以有i个平方数相加
dynamic = [x for x in range(n + 1)]
... |
MONGODB_URI = "mongodb://localhost:27017"
MONGODB_DATABASE = 'Cose2'
MONGODB_USER_COLLECTION = 'users'
MONGODB_TOPIC_COLLECTION = 'topics'
MONGODB_COMMENT_COLLECTION = 'comments' |
#
# Copyright (c) 2010-2016, Fabric Software Inc. All rights reserved.
#
ext.add_cpp_quoted_include('Opaque.hpp')
ty = ext.add_opaque_type('MyOpaque')
ty = ext.add_opaque_type('MyOpaqueDer', extends='MyOpaque')
ext.add_func('MyOpaque_New', 'MyOpaque *', ['int'])
ext.add_func('MyOpaque_GetX', 'int', ['MyOpaque *'])
e... |
S = "パトカー"
T = "タクシー"
for s,t in zip(S,T):
print(s+ t,end="")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/1/11 12:10
# @File : leetCode_459.py
class Solution(object):
def repeatedSubstringPattern(self, s):
"""
:type s: str
:rtype: bool
"""
for i in range(len(s)):
tmp = s[i: i+2]
for j in... |
'''
Created on Mar 31, 2018
@author: Burkhard A. Meier
'''
# list with loop
loop_numbers = [] # create an empty list
for number in range(1, 101): # use for loop
loop_numbers.append(number) # append 100 numbers to list
print(loop_numbers)
# list compreh... |
Rt = [[1,2,3 ], [2, 4, 5], [3,6,7], [4,8,9],[5,10,11],[6,12,13],[7,14,15]]
def findRoot(RT):
S = set()
for i in RT:
for j in i:
S.add( j )
print (S)
for i in RT :
for j in i[1:]:
S.remove( j )
print (S)
try :
for i in S :
... |
def f(param):
"""
Args:
param
""" |
c.NbServer.base_url = '/paws-public/'
c.NbServer.bind_ip = '0.0.0.0'
c.NbServer.bind_port = 8000
c.NbServer.publisher_class = 'paws.PAWSPublisher'
c.NbServer.register_proxy = False
c.PAWSPublisher.base_path = '/data/project/paws/userhomes'
|
del_items(0x800A0E14)
SetType(0x800A0E14, "char StrDate[12]")
del_items(0x800A0E20)
SetType(0x800A0E20, "char StrTime[9]")
del_items(0x800A0E2C)
SetType(0x800A0E2C, "char *Words[118]")
del_items(0x800A1004)
SetType(0x800A1004, "struct MONTH_DAYS MonDays[12]")
|
# Excel Column Number
# https://www.interviewbit.com/problems/excel-column-number/
#
# Given a column title as appears in an Excel sheet, return its corresponding
# column number.
#
# Example:
#
# A -> 1
#
# B -> 2
#
# C -> 3
#
# ...
#
# Z -> 26
#
# AA -> 27
#
# AB -> 28
#
# # # # # # # # # # # # # # # # # # # # # # # ... |
ENV = 'testing'
DEBUG = True
TESTING = True
SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/flask_example_test'
SQLALCHEMY_TRACK_MODIFICATIONS = False
ERROR_404_HELP = False
|
"""
Implementation of a labeled property graph.
"""
# ===================================
# TODO: Number of relationships a node has
# TODO: Number of nodes that have a given relationship
# TODO: Number of nodes with a relationship
# TODO: Number of nodes with a label
# TODO: Traversals:
# - Depth first
# - Breadth-fi... |
#!/usr/bin/env python3
"""
Normal distriution
"""
class Normal:
"""
Normal distribution class
"""
def __init__(self, data=None, mean=0., stddev=1.):
if data is None:
self.mean = float(mean)
if stddev <= 0:
raise ValueError("stddev must be a positive valu... |
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
# 获得在s中最大的数字
while g and s:
max_s = s.pop()
left = 0
right = len(g) -1
while left<=right:
mid = (left+right)//2
... |
# Copyright 2018 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.
def ChangeToStr(change):
"""Turn a pinpoint change dict into a string id."""
change_id = ','.join(
'{repository}@{git_hash}'.format(**commit)
... |
# Copyright (C) 2018 Google Inc.
#
# 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 law or agreed to in writ... |
class TwythonError(Exception):
@property
def msg(self) -> str: ...
class TwythonRateLimitError(TwythonError):
@property
def retry_after(self) -> int: ...
class TwythonAuthError(TwythonError): ... |
try:
sc = input("Enter your score between 0.0 and 1.0: ")
#sc = 0.85
score = float(sc)
except:
if score > 1.0 or score < 0.0:
print("Error, input should be between 0.0 and 1.0")
quit()
if score >= 0.9:
print('A')
elif score >= 0.8:
print('B')
elif score >= 0.7:
print('C')
elif s... |
passw = input()
def Is_Valid(password):
valid_length = False
two_digits = False
only = True
digit = 0
let_dig = 0
if len(password) >= 6 and len(password) <= 10:
valid_length = True
else:
print('Password must be between 6 and 10 characters')
for i in password:
if ... |
## Números Primos
n=int(input('Digite um número: '))
e=0
for i in range(1,n+1):
if n %i == 0:
e += 1
print('\033[34m', end=' ')
else:
print('\033[33m', end=' ')
print('{}'.format(i), end=' ')
print('\033[0;30m')
if e != 2:
print('O número \033[1;31m{} \033[0;30mé divisível \033[1;31m{} \033[0;30... |
# Algebraic-only implementation of two's complement in pure Python
#
# Written by: Patrizia Favaron
def raw_to_compl2(iRaw, iNumBits):
# Establish minimum and maximum possible raw values
iMinRaw = 0
iMaxRaw = 2**iNumBits - 1
# Clip value arithmetically
if iRaw < iMinRaw:
iRaw = iMinRaw
if iRaw > iMaxRaw:
... |
"""The base command."""
class Base(object):
"""A base command."""
def __init__(self, options, *args, **kwargs):
self.args = args
self.kwargs = kwargs
self.configuration = self.get_configuration(
options=options
)
def run(self):
raise NotImplementedErro... |
with open('./input.txt') as input:
hits = {}
for line in input:
(x1, y1), (x2, y2) = [ map(int, point.split(',')) for point in line.strip().split(' -> ')]
if x1 == x2:
for y in range(min(y1, y2), max(y1, y2) + 1):
if (x1, y) in hits:
hits[... |
def get_cat_vars_dict(df, categorical_cols, feature_names, target_name):
cat_vars_dict = {}
for col in [ col for col in categorical_cols if col != target_name]:
cat_vars_dict[feature_names.index(col)] = len(df[col].unique())
return cat_vars_dict |
class RestApi(object):
def __init__(self, app):
self.app = app
self.frefix_url = self.app.config.get("API_URL_PREFIX") or ""
self.views = []
def register_api(self, bleuprint, view, endpoint, url):
view_func = view.as_view(endpoint)
links = {}
# detail_url = "{}<... |
class Kanji():
def __init__(self):
self.kanji = None
self.strokes = 0
self.pronunciation = None
self.definition = ""
self.kanji_shinjitai = None
self.strokes_shinjitai = 0
def __unicode__(self):
if self.kanji_shinjitai:
ks = " (%s)" % self.ka... |
def p_error( p ):
print
print( "SYNTAX ERROR %s" % str( p ) )
print
raise Exception |
numeros = []
par = []
impar = []
while True:
n = (int(input('Digite um numero: ')))
numeros.append(n)
if n % 2 == 0:
par.append(n)
else:
impar.append(n)
resp = str(input('Deseja continuar [S/N]: ')).strip().upper()[0]
while resp not in 'SN':
resp = str(input('Tente novam... |
def get_label_dict(dataset_name):
label_dict = None
if dataset_name == 'PASCAL':
label_dict = {
'back_ground': 0,
'aeroplane': 1,
'bicycle': 2,
'bird': 3,
'boat': 4,
'bottle': 5,
'bus': 6,
'car': 7,
... |
class BatchRunner:
def __init__(self,model,iter_n):
self.model = model
self.iter_n = iter_n
def run_model(self,start,end):
"""
Runs the model
"""
for i in range(start,end):
self.model.reset(i)
self.model.episode()
print(... |
start = 0
end = 1781
instance = 0
for i in range(150):
f = open(f"ec2files/ec2file{i}.py", "w")
f.write(f"from scraper import * \ns = Scraper(start={start}, end={end}, max_iter=30, scraper_instance={instance}) \ns.scrape_letterboxd()")
start = end + 1
end = start + 1781
instance += 1
f.close()... |
#
# Copyright (C) 2020 Arm Mbed. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
"""Utility scripts to abstract and assist with scripts run in the CI."""
|
class Vector2D:
def __init__(self, v):
"""
:type v: List[List[int]]
"""
self.iter = itertools.chain.from_iterable(v)
self.cnt = sum(len(lst) for lst in v)
def next(self):
"""
:rtype: int
"""
self.cnt -= 1
return next(self... |
class Config(object):
SECRET_KEY = "aaaaaaa"
debug = False
class Production(Config):
debug = True
CSRF_ENABLED = False
SQLALCHEMY_DATABASE_URI = "mysql://username:password@127.0.0.1/DBname"
migration_directory = "migrations"
|
# This program creates an object of the pet class
# and asks the user to enter the name, type, and age of pet.
# The program retrieves the pet's name, type, and age and
# displays the data.
class Pet:
def __init__(self, name, animal_type, age):
# Gets the pets name
self.__name = name
... |
#
# PySNMP MIB module SCSPATMARP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SCSPATMARP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:01:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... |
stundenlohn = input('Bitte Geben sie ihren Stundenlohn an ')
stunden = input('Wieviel Stunden am Tag Arbeiten sie? ')
tag = int(stunden) * int(stundenlohn)
Monat = int(tag) * 22
Jahr = int(Monat) * 12
print('ihr Stundenlohn beträgt ' + str(stundenlohn) +'€\r\n')
print('Sie verdienen '+ str(tag) +' € pro tag\r\n... |
# coding=utf-8
__author__ = 'lxn3032'
class ControllerBase(object):
def __init__(self, period, ValueType=float):
self.ValueType = ValueType
self.T = period
self.error_1 = ValueType(0)
self.error_2 = ValueType(0)
self.current_value = ValueType(0)
self.target_value = ... |
{
"cells": [
{
"cell_type": "code",
"execution_count": 20,
"id": "informative-england",
"metadata": {},
"outputs": [],
"source": [
"### This is the interworkings and mathematics behind the equity models\n",
"\n",
"### Gordon (Constant) Growth Model module ###\n",
"def Gordongrowth(d... |
# -*- coding: utf-8 -*-
"""Dot.notation attributes for dictionaries.
Includes recursive DotDict behavior for nested dictionaries.
"""
class DotDict(dict):
"""DotDict creates an interface for using dictionaries as attr containers.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, *... |
class SYCSException(Exception):
pass
class CredentialsException(SYCSException):
def __init__(self):
super(SYCSException, self).__init__('username or password not provided.')
class InvalidCredentialsException(SYCSException):
def __init__(self):
super(SYCSException, self).__init__('wrong u... |
def solution(A, B, s):
A.sort()
B.sort()
i = len(A) - 1
j = len(B) - 1
while 0 <= j <= len(B) - 1 and i:
pass
|
a = int(input())
for i in range(1, a+1):
if a % i == 0:
print(i)
|
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 applicab... |
class When_we_have_a_test:
@classmethod
def examples(cls):
yield 1
yield 3
def when_things_happen(self):
pass
def it_should_do_this_test(self, arg):
assert arg < 3
|
# Copyright 2021 Adobe. All rights reserved.
# This file is licensed to you 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 law ... |
class Solution:
def validTree(self, n: int, edges: list[list[int]]) -> bool:
if not n:
return True
adj = {i: [] for i in range(n)}
for n1, n2 in edges:
adj[n1].append(n2)
adj[n2].append(n1)
visit = set()
def dfs(i, prev):
if ... |
def get_accounts_for_path(client, path):
ou = client.convert_path_to_ou(path)
response = client.list_children_nested(ParentId=ou, ChildType="ACCOUNT")
return ",".join([r.get("Id") for r in response])
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apa... |
print('='*30)
print('{:^30}'.format('Banco ML'))
print('='*30)
valor = int(input('Valor a ser sacado: R$'))
totced = 0
ced = 50
while True:
if valor >= ced:
valor -= 50
totced += 1
else:
if totced > 0:
print(f'Total de {totced} cedulas de {ced} foram sacadas.')
if ced... |
# Busiest Time in The Mall
def find_busiest_period(data):
peak_time = peak_vis = cur_vis = i = 0
while i < len(data):
time, v, enter = data[i]
cur_vis += v if enter else -v
if i == len(data)-1 or time != data[i+1][0]:
if cur_vis > peak_vis:
peak_vis = cur_vis
peak_time = ti... |
def test__delete__401_when_no_auth_headers(client):
r = client.delete('/themes/1')
assert r.status_code == 401, r.get_json()
def test__delete__401_when_incorrect_auth(client, faker):
r = client.delete('/themes/1', headers={
'Authentication': 'some_incorrect_token'})
assert r.status_code == 4... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Author:贾江超
def find_missing_letter(chars):
ordArr = [ord(x) for x in chars]
l = len(ordArr)
for i in range(l - 1):
result = ordArr[i + 1] - ordArr[i]
if result == 1:
pass
else:
re = chr(ordArr[i] + 1)
retur... |
# Python 3.8.3
with open("input.txt", "r") as f:
puzzle_input = [int(i) for i in f.read().split()]
def fuel_needed(mass):
fuel = mass // 3 - 2
return fuel + fuel_needed(fuel) if fuel > 0 else 0
sum = 0
for mass in puzzle_input:
sum += fuel_needed(mass)
print(sum)
|
"""defines errors for canvasplus."""
"""Luke-zhang-04
CanvasPlus v1.3.0 (https://github.com/Luke-zhang-04/CanvasPlus)
Copyright (C) 2020 Luke Zhang
Licensed under the MIT License
"""
class Error(Exception):
"""Base class for other exceptions."""
pass
class InvalidUnitError(Error):
"""Raised when unit i... |
# Date: 2020/11/12
# Author: Luis Marquez
# Description:
# This is a simple program in which the binary search will be implemented to calculate a square root result
#
#BINARY_SEARCH(): This function realize a binary search
def binary_search():
#objective: The number in which the root will be cal... |
class Config(object):
DESCRIPTION = 'Mock generator for c code'
VERSION = '0.5'
AUTHOR = 'Freddy Hurkmans'
LICENSE = 'BSD 3-Clause'
# set defaults for parameters
verbose = False
max_nr_function_calls = '25'
charstar_is_input_string = False
UNITY_INCLUDE = '#include "unity.h"'
#... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.