content stringlengths 7 1.05M |
|---|
with open('day9.txt') as f:
data = f.read().splitlines()[0].split(' ')
nPlayers = int(data[0])
nMarbles = int(data[6])
# Players
playerScores = [0] * nPlayers
currentPlayer = -1
# Marbles
right = [None] * nMarbles
left = [None] * nMarbles
# Initialise
current = 0
total = 1
right[current] = current
left[... |
# 280. Wiggle Sort
# ttungl@gmail.com
# Given an unsorted array nums, reorder it in-place
# such that nums[0] <= nums[1] >= nums[2] <= nums[3]....
# For example, given nums = [3, 5, 2, 1, 6, 4],
# one possible answer is [1, 6, 2, 5, 3, 4].
class Solution(object):
def wiggleSort(self, nums):
"""
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Using the classifier
--------------------
.. toctree::
:maxdepth: 3
cv/base
cv/data
cv/helper
Cross-validation in MRIQC
----------------... |
def arithmeticExpression(a, b, c):
"""
Consider an arithmetic expression of the form a#b=c.
Check whether it is possible to replace # with one of
the four signs: +, -, * or / to obtain a correct
"""
return (
True if (a + b == c) or (a - b == c) or (a * b == c) or (a / b == c) else Fals... |
# 3. Conte o total de comidas citadas no dicionário e quantas se repetem.
lista = []
valor = []
itemData = [
{
"name": "Meowsy",
"species" : "cat",
"foods": {
"likes": ["tuna", "catnip"],
"dislikes": ["ham", "zucchini"]... |
def consulta(message):
resultado = {}
#################
resultado['telefone'] = message.split('TELEFONE: ')[1].split('\n')[0]
resultado['nome'] = message.split('NOME: ')[1].split('\n')[0]
resultado['cpfCnpj'] = message.split('CPF/CNPJ: ')[1].split('\n')[0]
resultado['operadora'] = message.split(... |
# Somar o preço dos produtos utilizando List Comprehension
carrinho = []
carrinho.append(("Camisa 1", 35))
carrinho.append(("Bone 1", 20))
carrinho.append(("Calça 1", 80))
total = sum([int(y) for x, y in carrinho])
print(total) |
LUCYFER_SETTINGS = {
"SAVED_SEARCHES_ENABLE": False,
"SAVED_SEARCHES_KEY": None,
}
|
r = 'S'
while r == "S":
n = int(input('Digite um numero: '))
r = str(input('Quer continuar [S/N]: ')).upper()
print('Acabou') |
def reverse(number):
stack = []
result = ""
for num in str(number):
stack.append(num)
for i in range(len(stack)):
result += stack.pop()
print(result)
return int(result)
reverse(3479)
|
T_Call = 0
T_Squat = 1
T_Shank = 2
T_Jump = 3
T_Slap = 4
T_EyeContact = 5
function_name_dict = {
T_Call: "call",
T_Squat: "squat",
T_Shank: "shank",
T_Jump: "jump",
T_Slap: "slap",
T_EyeContact: "eye_contact"
}
RESPECT_MAX = 255 |
def power_of_two(x):
if x == 1:
return True
if x < 1:
return False
return power_of_two(x / 2)
|
# 입력
p1, s1 = map(int, input().split())
s2, p2 = map(int, input().split())
# 출력
if p1+p2 > s1+s2:
print("Persepolis")
elif p1+p2 < s1+s2:
print("Esteghlal")
else: # 동점인 경우
if s1 > p2:
print("Esteghlal")
elif s1 < p2:
print("Persepolis")
else:
print("Penalty")
|
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
def search(lo, hi):
if nums[lo] == target == nums[hi]:
return [lo, hi]
if nums[lo] <= target <= nums[hi]:
mid = (lo + hi) // 2
l, r = search(lo, mid), sea... |
#15 Distance units
# Askng for distance in feet.
x = float(input("Enter the distance in feet = "))
inches = x * 12
yards = x * 0.33333
miles = x * 0.000189
print("Inches = ",inches," Yards = ",yards," Miles = ",miles)
|
# Generate n colors along a vector
def get_vector(a, b):
"""Given two points (3D), Returns the common vector"""
vector = ((b[0] - a[0]), (b[1] - a[1]), (b[2] - a[2]))
return vector
def get_t(n):
if n <= 2:
return [0, 1]
else:
t = []
for i in range(n):
if i == 0... |
load("@berty_go//:config.bzl", "berty_go_config")
load("@co_znly_rules_gomobile//:repositories.bzl", "gomobile_repositories")
load("@build_bazel_apple_support//lib:repositories.bzl", "apple_support_dependencies")
load("@build_bazel_rules_swift//swift:repositories.bzl", "swift_rules_dependencies")
def berty_bridge_conf... |
n = 95
for i in range(1,1000):
a = n ^ i
print(bin(a),a)
print(i,bin(n),n)
print() |
'''
Description : Use Of Basic Input / Output
Function Date : 07 Feb 2021
Function Author : Prasad Dangare
Input : Str
Output : --
'''
print("Enter One Number") # to display on screen
no = input() # to accept the standard input device ie keyword
print ("Your Number Is :... |
# Global Reach
# Demonstrates global variables
def read_global():
print("From inside the local scope of read_global(), value is:", value)
def shadow_global():
value = -10
print("From inside the local scope of shadow_global(), value is:", value)
def change_global():
global value
value = -10
... |
a = int(input("Enter: "))
reserve = a
temp = 0
rev=0
while a>0:
temp = a%10
a = a//10
rev = rev*10 + temp
if reserve == rev:
print("Palindrome")
else:
print("not") |
class Track(object):
id = 0
header_line = 1
filename = ""
key_color = "#FF4D55"
name = ""
description = ""
track_image_url = "http://lorempixel.com/400/200"
location = ""
gid = ""
order = -1
def __init__(self, id, name, header_line, key_color, location, gid, order):
... |
#!/usr/bin/env python3
if __name__ == '__main__':
students_list = []
while True:
command = input("Add, list, exit: ").lower()
if command == 'exit':
break
elif command == 'add':
last_name = input('Your last name^ ')
class_name = input('... |
# model settings
norm_cfg = dict(type='SyncBN', requires_grad=True)
model = dict(
type='EncoderDecoder',
# pretrained='checkpoints/metanet-b4/det_fmtb4_v1.pth.tar',
backbone=dict(
type='Central_Model',
backbone_name='MTB4',
task_names=('gv_patch', 'gv_global'),
main_task_name... |
# OpenWeatherMap API Key
weather_api_key = "2e751db150eed8a2a8ae9dc91e31a091"
# Google API Key
g_key = "AIzaSyBqrWs9x-quXSBQkAVuz-x7PP3t64gJj7E"
|
def validacao(p):
ok = False
while not ok:
n = str(input(p)).replace(',', '.').strip()
if n.isalpha() or n == '':
print(f'ERRO! "{n}" é um preço inválido!')
else:
ok = True
return float(n)
|
def main():
s = input()
weathers = ['Sunny', 'Cloudy', 'Rainy']
length = weathers.__len__()
index = weathers.index(s) + 1
if index >= length:
index = 0
print(weathers[index])
if __name__ == "__main__":
main()
|
# Find height of a given binary tree
class Node():
def __init__(self, value):
self.left = None
self.right = None
self.value = value
class Tree():
def height(self, node: Node):
if node is None or (node.left is None and node.right is None):
return 0
else:... |
# 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 writing, software
# d... |
def conta_caracter(s):
"""
Função que conta os caracteres de uma string.
:param s: String a ser contada
"""
resultado = {}
for caracter in s:
resultado[caracter] = resultado.get(caracter, 0) + 1
return resultado
if __name__ == '__main__':
print(conta_caracter('pêssego'))
... |
#!/usr/local/bin/python3
message = str(input("Message: "))
secret = ""
for character in reversed(message):
secret = secret + str(chr(ord(character)+1))
print(secret) |
class Solution:
def majorityElement(self, nums: List[int]) -> int:
counter = {}
for num in nums:
if num not in counter:
counter[num] = 1
else:
counter[num] += 1
for key, value in counter.items():
if value > ... |
oo000 = 0
for ii in range ( 11 ) :
oo000 += ii
if 51 - 51: IiI1i11I
print ( oo000 )
# dd678faae9ac167bc83abf78e5cb2f3f0688d3a3
|
"""
Author: PyDev
Description: Doubly Linked List with a Tail consist of a element, where the element is the
skeleton and consist of a value next, and previous variable/element.
There is a Head pointer to refer to the front of the Linked List.
The Tail pointer to refer to the end ... |
class Commit:
def __init__(self):
""" A simple feature container for each git commit """
self.features = {}
def add(self, key, value):
if key in self.features:
raise Exception("Do not overwrite features")
self.features[key] = value
def remove(self, key):
... |
APP_PORT = 7991
LOGFILE_PATH = "/var/log/application/db_replication.log"
MASTER_MYSQL = {
'host': '127.0.0.1',
'port': 3306,
'user': 'root',
'password': 'password'
}
|
"""
Numbers can be regarded as product of its factors. For example,
8 = 2 x 2 x 2;
= 2 x 4.
Write a function that takes an integer n and return all possible combinations of its factors.
Note:
You may assume that n is always positive.
Factors should be greater than 1 and less than n.
Examples:
input: 1
output:
[]
in... |
#############################################################################
#Replace with the persons name that you were texting
leftName = "Bob"
#Replace with your name
rightName = "John"
#############################################################################
|
BASE_DIR=""
DATA_DIR="/mnt/nfs/work1/akshay/akshay/projects/oracle_cb/data/"
REMOTE_PATH_TO_PYTHON="/mnt/nfs/work1/akshay/akshay/anaconda3/python3"
REMOTE_BASE_DIR="/mnt/nfs/work1/akshay/akshay/projects/oracle_cb/"
|
def prime(num):
flag=False
for a in range(2,num-1): #basically prime no are divisible by itself and by 1 only so set input value -1 so i takes previous num
if num%a==0:
flag=True
if flag==False:
print("prime")
else:
print("not prime")
num=int(input("enter... |
#!/usr/bin/env python
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
# Modifications Copyright (c) 2018 LG Electronics, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not ... |
"""
Some constants.
"""
VERSION = "0.1.0"
BAT = "bat"
LIGHT_THEME = "GitHub"
LEFT_SIDE, RIGHT_SIDE = range(2)
|
class Environment:
def __init__(self, bindings=None):
self.stack = [bindings or {}]
self.index = 0
def set(self, name, val, i=None):
"""
Assign value to a name. By default, names will be
stored in the lowest scope possible.
"""
i = i if i != None else sel... |
"""Chapter 5: Question 4.
A simple condition to check if a number is power of 2: n & (n-1) == 0
Example:
n = 1000
1000 & (1000 - 1)) = 1000 & 0111 = 0000 = 0
"""
def is_power_of_two(n):
"""Checks if n is a power of 2.
Args:
n: Non-negative integer.
"""
if n < 0:
raise Valu... |
HTTP_STATUS_CODES = {
"100": "Continue",
"101": "Switching Protocols",
"102": "Processing",
"200": "OK",
"201": "Created",
"202": "Accepted",
"203": "Non-Authoritative Information",
"204": "No Content",
"205": "Reset Content",
"206": "Partial Content",
"207": "Multi-Status",
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 16 00:26:52 2020
@author: RogelioTESI
"""
def es_primo(Numero):
resultado = True
rep = 0
for divisor in range(2,Numero):
if (Numero % divisor)==0:
resultado = False
break
rep = rep+(divisor-1)
return resultado,rep
x,rep... |
# Write your code here
N = int(input())
arr = list(map(int, input().split()))
def give_soln(n):
return ((2**n) - (1 + (n) + (n*(n-1)/2)))
my_dict = dict()
for i in arr:
if i in my_dict:
my_dict[i] += 1
else:
my_dict[i] = 1
count = 0
for side in my_dict:
if my_dict[side... |
"""This is where you modify constants"""
USER = "user"
PASSWORD = "pwd"
DATABASE_NAME = "mydb"
CATEGORIES = ["Fromages",
"Desserts",
"Viandes",
"Chocolats",
"Snacks", ]
PRODUCT_NUMBER = 1000
|
model = dict(
type='GroupFree3DNet',
backbone=dict(
type='PointNet2SASSG',
in_channels=3,
num_points=(2048, 1024, 512, 256),
radius=(0.2, 0.4, 0.8, 1.2),
num_samples=(64, 32, 16, 16),
sa_channels=((64, 64, 128), (128, 128, 256), (128, 128, 256),
... |
#!/usr/bin/env python
__all__ = ['adaptor', 'get_by_cai','util']
__author__ = "Rob Knight"
__copyright__ = "Copyright 2007-2012, The Cogent Project"
__credits__ = ["Rob Knight", "Stephanie Wilson", "Michael Eaton"]
__license__ = "GPL"
__version__ = "1.5.3"
__maintainer__ = "Rob Knight"
__email__ = "rob@spot.colorado.e... |
# Заява про звуження переліку лікарських форм (Додаток 16)
def test_15_lims_test_case_2_5(app):
app.session.login(password='111',
path_to_key='C:/98745612_7878789898_DU180323123055.ZS2')
app.first_application.create_fifth_application()
app.first_application.change_mpd_fifth()
a... |
# -*- coding: utf-8 -*-
class FieldError(Exception):
pass
class FieldDoesNotExist(Exception):
pass
class ReadOnlyError(AttributeError):
pass
|
# Created by MechAviv
# Quest ID :: 34931
# Not coded yet
sm.setSpeakerID(3001510)
sm.setSpeakerType(3)
sm.flipDialogue()
sm.setBoxChat()
sm.boxChatPlayerAsSpeaker()
sm.setBoxOverrideSpeaker()
sm.flipBoxChat()
sm.flipBoxChatPlayerAsSpeaker()
sm.setColor(1)
sm.sendNext("#face1#Good work! I'm getting the signal again. W... |
"""
Codemonk link: https://www.hackerearth.com/practice/basic-programming/bit-manipulation/basics-of-bit-manipulation/practice-problems/algorithm/monk-and-tasks/
Given an array, the number of tasks is represented by the number of ones in the binary representation of each integer
in the array. Print those integers ... |
__all__ = ["InvalidCredentialsException"]
class InvalidCredentialsException(Exception):
pass
class NoHostsConnectedToException(Exception):
pass
|
# More details on this kata
# https://www.codewars.com/kata/51c8e37cee245da6b40000bd
def solution(string,markers):
if len(string) == 0:
return ''
t, tt, test, l, j, ret= [], [], [], [], [], ''
s = string.split('\n')
for _s in s:
for m in markers:
if _s.find(m) != -1:
... |
# Copyright (c) 2018, Benjamin Shropshire,
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of condition... |
def leiaint(n=""):
n = str(n)
while not n.isdecimal():
n = str(input('Digite um número: ')).strip()
if not n.isdecimal():
print('\033[0;31mERRO! Digite um número inteiro válido.\033[m')
n = int(n)
return n
numero = leiaint()
print(f'Você acabou de digitar o número {numero}'... |
def get_global_config():
result = {
'outcome' : 'success',
'data' : {
'credentials_file' : r'./config/config.ini',
}
}
return result |
# Url to manually retrieve authorization code
AUTH_URL = "https://auth.tdameritrade.com/auth"
# API endpoint for token and authorization code authentication
OAUTH_URL = "https://api.tdameritrade.com/v1/oauth2/token"
# Quote endpoints
GET_QUOTES_URL = "https://api.tdameritrade.com/v1/marketdata/quotes"
GET_QUOTE_URL =... |
"""
Default django-evostream configuration
"""
EVOSTREAM_URI = 'http://127.0.0.1:7777'
|
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
def start():
print('\nThis is my Rock Paper Scissors Game!\n\n')
Player_one = "Kaly"
Player_two = "Erik"
def choices(Player_one_choice, Player_two_choice):
if Player_one_choice == 'rock' and Player_two_choice == 'paper':
return('Paper cover Rock! ' + Player_two + ' Wins !')
... |
def parameters():
epsilon = 0.0001 # regularization
K = 3 # number of desired clusters
n_iter = 5 # number of iterations
skin_n_iter = 5
skin_epsilon = 0.0001
skin_K = 3
theta = 2.0 # threshold for skin detection
return epsilon, K, n_iter, skin_n_iter, skin_epsilon, skin_K, theta
|
"""Constants used by the Netatmo component."""
API = "api"
DOMAIN = "netatmo"
MANUFACTURER = "Netatmo"
MODELS = {
"NAPlug": "Relay",
"NATherm1": "Smart Thermostat",
"NRV": "Smart Radiator Valves",
"NACamera": "Smart Indoor Camera",
"NOC": "Smart Outdoor Camera",
"NSD": "Smart Smoke Alarm",
... |
"""IntelliJ plugin debug target rule used for debugging IntelliJ plugins.
Creates a plugin target debuggable from IntelliJ. Any files in
the 'deps' and 'javaagents' attribute are deployed to the plugin sandbox.
Any files are stripped of their prefix and installed into
<sandbox>/plugins. If you need structure, first p... |
def perm(text1, text2):
return sum(ord(c) for c in text1) == sum(ord(c) for c in text2)
# test
one = 'abc'
two = 'bcaa'
print(perm(one, two))
|
class Problem:
def __init__(self, n, m):
self.n = n
self.m = m
self.answer = [0 for _ in range(m)]
self.used = [False for _ in range(n)]
def printAnswer(self):
for number in self.answer:
print(number,end=' ')
print()
def makeAnswer(self, index):
... |
class Node:
def __init__(self, data):
self.right = self.left = None
self.data = data
class Solution:
def insert(self, root, data):
if root is None:
return Node(data)
else:
if data <= root.data:
cur = self.insert(root.left, data)
... |
def define_suit(card):
if card.endswith("C"): return "clubs"
if card.endswith("D"): return "diamonds"
if card.endswith("H"): return "hearts"
if card.endswith("S"): return "spades" |
_base_ = [
'../_base_/models/retinanet_r50_fpn.py',
'../_base_/datasets/coco_detection.py',
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]
model = dict(
backbone=dict(
type='ResNetEMOD',
ar=dict(ratio=1. / 4.),
stage_with_ar=(True, True, True, True)
),... |
class ValorantApi(Exception):
pass
class InvalidOrMissingParameter(ValorantApi): # 400
pass
class NotFound(ValorantApi): # 404
pass
class AttributeExistsError(ValorantApi):
pass
|
class MobilePhone:
def __init__(self, memory):
self.memory = memory
class Camera:
def take_picture(self):
print("Say cheese!")
class CameraPhone(MobilePhone, Camera):
pass
iphone = CameraPhone('16GB')
print(iphone.memory)
iphone.take_picture() |
# ===============================================================
# =======================AST=HIERARCHY===========================
# ===============================================================
ERROR = 0
INTEGER = 1
class Node:
def __init__(self):
self.static_type = ""
class ProgramNode(Node):
de... |
# for i in range(17):
# print("{0:>2} in hex is {0:>02x}".format(i))
# #
# x = 0x20
# y = 0x0a
# #
# print(x)
# print(y)
# print(x * y)
# #
# print(0b101010)
# When converting a decimal number to binary, you look for the highest power
# of 2 smaller than the number and put a 1 in that column. You then take the
# r... |
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __repr__(self):
return str(self.val)
# Brute Force; Time: O(n^2); Space: O(n)
def next_larger_nodes(head):
res = []
slow = head
while slow:
fast = slow.next
while fa... |
print('Vamos realizar o fatorial: ')
n = int(input('Digite um número inteiro: '))
c = n
f = 1
print('{}! = '.format(n), end=' ')
while c > 0:
print(c, end=' ')
print(' x ' if c > 1 else ' = ', end=' ')
f *= c
c -= 1
print(f)
print('FIM!')
|
{
"targets": [
{
"target_name": "crc",
"sources": [ "./src/crc_module.c", "./src/crc.c" ]
},
]
} |
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
input_list = [0, 1, 2, 3, 4]
root = None
for val in input_list:
root = Node(val, root)
cur = root
while cur:
print(cur.val)
cur = cur.next
print('Stack after pop: ')
root = root.next
cur = root
while cu... |
class ExportObjStatus:
SUCCESS = 'success'
ERROR = 'error'
IN_PROGRESS = 'in_progress'
CHOICES = [
(SUCCESS, 'Success'),
(ERROR, 'Error'),
(IN_PROGRESS, 'In progress'),
]
|
class Base:
"""Base class readily accepts defaults"""
def __init__(self, **kws):
for k, v in kws.items():
if not hasattr(self, k):
setattr(self, k, v)
class Laziness(Base):
"""Generally lazy lookup"""
def __init__(self, method, **kws):
super().__init__(**k... |
def capitalize(string):
# We can't use title() here, consider the case: "123name" -> "123Name", which isn't correct.
for substring in string.split():
string = string.replace(substring, substring.capitalize())
return string |
# https://leetcode.com/problems/find-leaves-of-binary-tree/
class Solution:
def findLeaves(self, root: Optional[TreeNode]) -> List[List[int]]:
result = []
while root.left or root.right:
result.append(self.popLeaves(root, root, []))
result.append([root.val])
... |
class Monster:
def __init__(self, name, color):
self.name = name
self.color = color
def attack(self):
print('I am attacking...')
class Fogthing(Monster):
def attack(self):
print('I am killing...')
def make_sound(self):
print('Grrrrrrrrrr\n')
fogthing = Fogth... |
# if train_or_eval = True then 训练 else 测试
train_or_eval = False
# train_or_eval = True
if train_or_eval is not True:
# 测试的配置
task = 'denoising'
dataset_dir = r'/user51/mxy/data/J4R/frames_heavy_test_JPEG' # 测试图片包括边缘图的路径
dataset_gtc_dir = r'/user51/mxy/data/J4R/frames_heavy_test_JPEG'
# 相对... |
def compute():
numer = 1 # 分子
denom = 0 # 分母
for i in range(100):
numer, denom = e_contfrac_term(i) * numer + denom, numer
# this formula can only meet the specification of the molecular(分子),
# we cannot use this formula to get the right value of Denominator
ans = sum(int(c) fo... |
# https://codeforces.com/problemset/problem/1367/A
t = int(input())
for i in range(t):
s = input()
ss = [s[0]]
for i in range(0, len(s)-1, 2):
ss.append((s[i], s[i+1])[1])
print(''.join(ss)) |
"""
Column Explorer
===============================================================================
"""
# import ipywidgets as widgets
# from IPython.display import display
# from ipywidgets import GridspecLayout, Layout
# from .dashboard import document_to_html
# from .utils import load_filtered_documents
# cla... |
# coding : utf-8
'''
Copyright 2019 Agnese Salutari.
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 wr... |
ora_start=int(input("Ora="))
minut_start=int(input("Minute="))
durata_ore=int(input("Cate ore dureaza drumul="))
durata_minute=int(input("Cate minute dureaza drumul"))
ora_fin = ora_start+durata_ore
minute_fin = minut_start+durata_minute
if minute_fin>60:
minute_fin%=60
ora_fin+=1
print(ora_fin,minute_fin)
|
def digitDifferenceSort(a):
def dg(n):
s = list(map(int, str(n)))
return max(s) - min(s)
ans = [(a[i], i) for i in range(len(a))]
A = sorted(ans, key = lambda x: (dg(x[0]), -x[1]))
return [c[0] for c in A]
|
# Topology with a single loop
# A --- B --- C
# | |
# D --- E
topo = { 'A' : ['B', 'D'],
'B' : ['A', 'C', 'E'],
'C' : ['B'],
'D' : ['A', 'E'],
'E' : ['B', 'D'] }
|
class Body:
"""
Represents the status of the body, each part of the body has a name and a
value representing its status 1 = perferctly fine, 0 = unavailale
"""
def __init__(self, parts=None):
if parts is not None:
self.boyd_parts = parts.copy()
else:
self.bod... |
# fmt: off
cost_sequence = [
102267214109.0,
102267223999.0,
102269202999.00002,
102566201999.00002,
132365101999.0,
102475101999.00002,
102465101999.00002,
132465101999.0,
162165001999.0,
162565001999.0,
162965001999.0,
163965001999.0,
163955001999.0,
13406500199... |
#
# PySNMP MIB module IB-SMA-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IB-SMA-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:39:05 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... |
def computador_escolhe_jogada(n, m):
computadorRemove = 1
while computadorRemove != m:
if ((n - computadorRemove) % (m+1) == 0):
return computadorRemove
else:
computadorRemove += 1
return computadorRemove
def usuario_escolhe_jogada(n, m):
jogadaValida = False
... |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name : ecc
Description :
Author : x3nny
date : 2021/10/7
-------------------------------------------------
Change Activity:
2021/10/7: Init
---------------------------------------... |
def phone_number(num):
string = [(str(x)) for x in num]
string = ''.join(string)
return f'({string[:3]}) {string[3:6]}-{string[6:]}'
print(phone_number([1,2,3,4,5,6,7,8,9,0]))
|
"""
Sermin exceptions
"""
class RunError(Exception):
"""
Sermin error during a blueprint run
"""
pass
class ShellError(RunError):
"""
Sermin shell command failed
"""
pass
|
#!/usr/bin/env python
# coding:utf8
class Singleton(type):
__instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls.__instances:
cls.__instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls.__instances[cls]
class MetaclassSingleton(metaclass=Si... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.