content stringlengths 7 1.05M |
|---|
#!/usr/bin/env python
def solution(A, K):
n = len(A)
if n == 0:
return A
K %= n
if K == 0:
return A
return A[-K:] + A[:n-K]
def test():
a = [3, 8, 9, 7, 6]
assert solution(a, 1) == [6, 3, 8, 9, 7]
assert solution(a, 6) == [6, 3, 8, 9, 7]
assert solution(a, 3) == ... |
# The MIT License (MIT)
#
# Copyright (C) 2020 - Ericsson
#
# 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, modify... |
# 29/06/2017
# inspired by /u/Toctave's solution
def talking_clock(time):
h, m = map(int, time.split(':'))
gt12, h = divmod(h, 12)
s = "It's "
s += ["twelve", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven"][h] + ' '
s += ["", "oh "][m > 0 and m < 10]
s ... |
'''위의 그림과 같이 육각형으로 이루어진 벌집이 있다.
그림에서 보는 바와 같이 중앙의 방 1부터 시작해서 이웃하는 방에 돌아가면서 1씩 증가하는 번호를 주소로 매길 수 있다.
숫자 N이 주어졌을 때, 벌집의 중앙 1에서 N번 방까지 최소 개수의 방을 지나서 갈 때 몇 개의 방을 지나가는지
(시작과 끝을 포함하여)를 계산하는 프로그램을 작성하시오. 예를 들면, 13까지는 3개, 58까지는 5개를 지난다.
첫째 줄에 N(1 ≤ N ≤ 1,000,000,000)이 주어진다.
입력으로 주어진 방까지 최소 개수의 방을 지나서 갈 때 몇 개의 방을 지나는지 출력한다.... |
metadata = {
"name": "",
"description": "",
"image": "",
"attributes": [
{"att_name": "max-speed", "value": 210},
{"att_name": "color", "value": "#550045"},
{"att_name": "price", "value": 294000},
{"att_name": "manufacture_date", "value": "01-12-2014"},
{"att_name... |
s, t = input().split()
a, b = map(int, input().split())
u = input()
if u == s:
print(a - 1, b)
else:
print(a, b - 1)
|
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Gender, obj[4]: Age, obj[5]: Education, obj[6]: Occupation, obj[7]: Bar, obj[8]: Coffeehouse, obj[9]: Restaurant20to50, obj[10]: Direction_same, obj[11]: Distance
# {"feature": "Occupation", "instances": 23, "metric_value": 0.9656, "depth... |
n=int(input('Upisite broj učenika u razredu: '))
zbroj=0.0
for i in range(n):
broj=float(input('Unesi visinu {0}. učenika:'.format(i+1)))
zbroj+=broj
print('\nSrednja visina učenika je {0:0.2f}'.format(zbroj/n)) |
class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
# Find euclidean distances
distance_points = [(self.find_euclidean(point, [0, 0]), point[0], point[1]) for point in points]
# Quickselect to sort the distance points
self.quickselect(dist... |
valor = int(input("Digite un número: "))
if valor==10:
print("Felicidades, has ganado 10 puntos")
else:
print(":(")
|
decr = 7
for x in range(4,0,-1):
for y in range(x,5):
print(" ",end="")
print(str(decr)*decr)
decr-=2 |
#Exercício Python 12: Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto.
preço = float(input('Qual é o preço do produto? R$ '))
novo = preço-(preço * 5 / 100)
print(f'O produto que custava R$ {preço:.2f}, na promoção com desconto de 5% vai custar R$ {novo:.2f}') |
# -*- coding: utf-8 -*
"""
:py:class:`BaseTokenEmbedding` is an abstract class for get token embedding
"""
class BaseTokenEmbedding(object):
"""BaseTokenEmbedding
"""
def __init__(self, emb_dim, vocab_size):
self.name = "token_emb"
self.emb_dim = emb_dim
self.vocab_size = vocab_si... |
# Property example
class Person:
first_name = property()
@first_name.getter
def first_name(self):
return self._first_name
@first_name.setter
def first_name(self, value):
if not isinstance(value, str):
raise TypeError('Expected a string')
self._first_name = value... |
"""
Exercício 2. Escreva uma função que apaga do dicionário anterior, todas as palavras que sejam ‘stopwords’.
Ver https://gist.github.com/alopes/5358189
"""
stopwords = ['de', 'a', 'o', 'que', 'e', 'do', 'da', 'em', 'um', 'para', 'é', 'com', 'não', 'uma', 'os', 'no', 'se', 'na', 'por', 'mais', 'as', 'dos', 'c... |
#Make a script that prints out numbers from 1 to 10
for i in range(1,11):
print(i)
|
# -*- coding: utf-8 -*-
# Classe Bomba de Combustível: Faça um programa completo utilizando classes e métodos que:
# a. Possua uma classe chamada bombaCombustível, com no mínimo esses atributos:
# i. tipoCombustivel
# ii. valorLitro
# iii. quantidadeCombustivel
# b. Possua no mínimo esses... |
#accuracy
p = clf.predict([xtest])
count = 0
for i in range(0,21000):
count += 1
if p[i]:
print(actual_label[i])
else:
print("0")
print("ACCURACY", (count/21000)*100) |
def isPrime(N):
if N == 1:
return False
for i in range(2, N):
if N % i == 0:
return False
return True
def isPrimeBetter(N):
if N <= 1:
return False
if N <= 3:
return True
if N % 2 == 0 or N % 3 == 0:
return False
... |
##
# Portions Copyright (c) Microsoft Corporation. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# THIS CODE IS PROVIDED... |
#Cada clase de Python y cada objeto de Python está pre-equipado con un conjunto de atributos útiles
# que pueden usarse para examinar sus capacidades.
#La propiedad "__dict__".
#Observemos cómo esta propiedad trata con los métodos.
#Encuentra todos los métodos y atributos definidos.
# Localiza el contexto en el que exi... |
def bonAppetit(bill, k, b):
shares_brian = (sum(bill)+bill[k])/2
shares_anna = (sum(bill) - bill[k])/2
if shares_anna == b:
return print('Bon Appetit')
else:
return print(int(bill[k]/2))
bill = [3, 10, 2, 9]
n = 4
k = 1
b = 12
bonAppetit(bill, k, b)
|
def get_age(name):
# if name == "Fuck":
# print("Mat day")
# return 1
# else
print("Khong mat day")
return 19
#1
age = get_age("Tam")
#2
xxx = input("> ")
get_age(xxx)
#3
get_age(xxx + "Tam")
#4
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f"You have {cheese_count} cheeses!")
print(f"Y... |
# used for module loading
class NagoyaRouter:
def db_for_read(self, model, **hints):
"""
Attempts to read nagoya models from nagoyadb.
"""
if model._meta.app_label == 'nagoya':
return 'nagoya'
return 'default'
|
"""
Custom exception classes for the ZAP CLI.
.. moduleauthor:: Daniel Grunwell (grunny)
"""
class ZAPError(Exception):
"""
Generic exception for ZAP CLI.
"""
def __init__(self, message, extra=None):
super(ZAPError, self).__init__(message)
self.extra = extra
|
# Day 7: split, join, and Slices
# Exercises
# Ask the user to enter their given name and surname in response to a single prompt. Use split to extract the names, and then assign each name to a different variable.
# For this exercise, you can assume that the user has a single given name and a single surname.
fullnam... |
# Create a Multinomial Naive Bayes classifier: nb_classifier
nb_classifier = MultinomialNB()
# Fit the classifier to the training data
nb_classifier.fit(tfidf_train, y_train)
# Create the predicted tags: pred
pred = nb_classifier.predict(tfidf_test)
# Calculate the accuracy score: score
score = metrics.accuracy_scor... |
# Write a function that returns the groups in the school by year (as a string), separated with a comma and space in the form of "1a, 1b, 1c, 1d, 2a, 2b (....) 6d, 7a, 7b, 7c, 7d".
# Examples:
# csSchoolYearsAndGroups(years = 7, groups = 4) ➞ "1a, 1b, 1c, 1d, 2a, 2b, 2c, 2d, 3a, 3b, 3c, 3d, 4a, 4b, 4c, 4d, 5a, 5b, 5c,... |
"""Animals module."""
class Animal:
"""Animal class."""
# Class object attributes apply to all instances (go before __init__)
is_alive = True
def __init__(self):
"""__init__ is used to initialize the attributes of an object."""
print("Animal created")
def whoAmI(self):
"... |
# calculate the supereffect of the attacker against defender
# part of the pokemon database website written by Ross Grogan-Kaylor and Jimmy Zhong
word_maps_col_row_num = {
"fire":0,
"water":1,
"bug":2,
"poison":3,
"electric":4,
"fairy":5,
"fighting":6,
"psychic":7,
"ground":8,
... |
class VariantStats:
def __init__(self, stats, total_count):
self.total_count = total_count
self.stats = stats # {field: {value: count}, field: {min:min,max:max}, ...}
def __getitem__(self, filter_name):
return self.stats[filter_name]
def get(self, filter_name):
return se... |
costs = [2, 2, 6, 5, 4]
values = [6, 3, 5, 4, 6]
def one_zero_package_max_value(n: int, c: int):
print("one_zero_package_max_value(%d, %d)" % (n, c))
"""
一共有N件物品,第i(i从1开始)件物品的重量为w[j],价值为v[j]。在总重量不超过背包承载上限W的情况下,能够装入背包的最大价值是多少?
时间复杂度:O(n)
:param n: 第n个item
:param c: pick number
:return: i... |
a = float(input())
if a < 100:
print('Less than 100')
elif a <= 200:
print('Between 100 and 200')
elif a > 200:
print('Greater than 200')
|
# Prints visualisation of the sequences.
for t in range(500):
if t % 5 == 0:
a = 'D'
else:
a = '-'
if t % 7 == 0:
b = 'D'
else:
b = '-'
if t % 13 == 0:
c = 'D'
else:
c = '-'
print(t, a, b, c)
|
def add_parser(subparsers):
parser = subparsers.add_parser(
"thingpedia",
help="Work with thingpedia-common-devices",
)
parser.add_children(__name__, __path__)
|
class Classe:
def __init__(self, attr):
self.atributo = attr
def metodo(self):
self.atributo += 1
print(self.atributo)
a = Classe(0)
a.metodo()
a.metodo()
|
#!/usr/bin/python
# configuration for syndicatelib
SYNDICATE_SMI_URL="http://localhost:8080"
SYNDICATE_OPENID_TRUSTROOT="http://localhost:8081"
SYNDICATE_OPENCLOUD_USER="jcnelson@cs.princeton.edu"
SYNDICATE_OPENCLOUD_PASSWORD=None
SYNDICATE_OPENCLOUD_PKEY="/home/jude/Desktop/research/git/syndicate/ms/tests/user_test... |
{
5 : {
"operator" : "selection",
"numgroups" : 100
}
}
|
def MergeSortRecusive(arr):
'''
Time complexity: O(n * log n)
'''
m = len(arr) // 2
if len(arr) <= 1:
return arr
else:
LS = []
RS = []
M = [arr[m]]
for i in range(len(arr)):
if i == m:
continue
... |
#不使用加号来实现两个数相加。
'''
'^':异或运算,即为无进位的加法
‘&’:与运算,结果左移一位即为应该有的进位,将其与异或结果相加--递归直到与出来为0,则异或结果是相加结果
负数的处理:会溢出!==> python溢出时用&0xFFFFFFFF来避免溢出
'''
def aplus(a,b):
mask = 0xFFFFFFFF
while(b != 0):
a1 =(a^b)&mask
b1 = ((a&b) << 1)&mask
a = a1
b = b1
return a
def getSum(a, b):
... |
# -*- coding: utf-8 -*-
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
### Alias : BridgeServer.update_distributor & Last Modded : 2022.02.27. ###
Coded with Python 3.10 Grammar by purplepig4657
Description : PosServer Update Distributor (with git)
Use linux crontab to run t... |
class ConfigSections:
"""
Container including enums for sections that can be used in config file.
"""
PROJECT = "PROJECT"
CPU_TARGET = "CPU_TARGET"
FPGA_TARGET = "FPGA_TARGET"
PLUGIN = "PLUGIN"
STRUCTURE = "STRUCTURE"
FPGASIM = "FPGASIM"
class BoardNames:
"""
... |
__author__ = 'sulantha'
class SortingObject:
def __init__(self, values):
self.record_id = 0 if 'record_id' not in values else values['record_id']
self.study = values['study']
self.rid = values['rid']
self.scan_type = values['scan_type']
self.scan_date = values['scan_date']
... |
class Robot:
def __init__(self, name):
self.__name = name
def __eq__(self, other):
return isinstance(other, Robot) and self.get_name() == other.get_name()
def get_name(self):
return self.__name
def __repr__(self):
return self.get_name()
ro = Robot("ro")
print(str(... |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class ServiceProcessEntry(object):
"""Implementation of the 'ServiceProcessEntry' model.
Specifies the name of a Service running on the Cluster as well as a list
of process IDs associated with that service.
Attributes:
process_ids (list... |
# Generated file, do not modify by hand
# Generated by 'rbe_autoconfig_autogen_ubuntu1604' rbe_autoconfig rule
"""Definitions to be used in rbe_repo attr of an rbe_autoconf rule """
toolchain_config_spec0 = struct(config_repos = [], create_cc_configs = True, create_java_configs = True, env = {"ABI_LIBC_VERSION": "glib... |
# Paths
SMPL_MODEL_DIR = './smpl' # Path to SMPL model directory
SSP_3D_PATH = './ssp_3d' # Path to SSP-3D dataset root directory
# Constants
FOCAL_LENGTH = 5000.
|
#
# PySNMP MIB module ONEACCESS-GLOBAL-REG (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ONEACCESS-GLOBAL-REG
# Produced by pysmi-0.3.4 at Mon Apr 29 20:22:42 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
# *-* coding:utf-8 *-*
"""Module states Paraiba"""
def start(st_reg_number):
"""Checks the number valiaty for the Paraiba state"""
#st_reg_number = str(st_reg_number)
weights = [9, 8, 7, 6, 5, 4, 3, 2]
digit_state_registration = st_reg_number[-1]
if len(st_reg_number) != 9:
return False
... |
def load(h):
return ({'abbr': 1, 'code': 1, 'title': 'first'},
{'abbr': 2, 'code': 2, 'title': 'second'},
{'abbr': 3, 'code': 3, 'title': 'third'},
{'abbr': 4, 'code': 4, 'title': 'fourth'})
|
#
# Copyright (c) 2017 Joy Diamond. All rights reserved.
#
@gem('Sapphire.Priority')
def gem():
share(
'PRIORITY_ATOM', 1, # atom
'PRIORITY_TUPLE', 2, # tuple
'PRIORITY_POSTFIX', 3, # . () and []
'PRIORITY_P... |
# coding: utf-8
class Solution:
# @param {int} n an integer
# @return {int[][]} a square matrix
def generateMatrix(self, n):
# Write your code here
ret = [[1 for i in xrange(n)] for i in xrange(n)]
k = 1 # 初始值
loop = 0 # 已走过圈数
while loop <= (n / 2): # 用小于等于可以覆盖... |
# coding: utf8
{
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" est une expression en option tels que "field1 = \'newvalue\'". Vous ne pouvez pas mettre \xc3\xa0 jour ou supprimer les r\xc3\xa9sultats d\'une jointure "a JOIN"',
'%Y-%m-%d': '... |
'''
Given an input of a 2D array of integers, removes all duplicates from the array.
Empty sub-arrays are removed.
'''
map = {}
def remove_duplicates(all_nums):
end_index = len(all_nums) #length of all_nums
i = 0 #current index of all_nums
while(i < end_index):
j = 0 #current index of sub-array
... |
#--------------------------------------------------------------------------
# Scrapy Settings
#--------------------------------------------------------------------------
BOT_NAME = 'scrapy_frontier'
SPIDER_MODULES = ['scrapy_recording.spiders']
NEWSPIDER_MODULE = 'scrapy_recording.spiders'
HTTPCACHE_ENABLED = True
RE... |
# try:
# num = int(input("数字: "))
# result = 100 / num
# print(result)
# print('Done')
# except ValueError:
# print('无效的输入')
# except ZeroDivisionError:
# print('无效的输入')
# except KeyboardInterrupt:
# print('\nBye-bye')
# except EOFError:
# print('\nBye-bye')
############################... |
BLOCK_SIZE = 1024
SERVER_IP = None
BACKING_FNs = ['../songs/lamprey/drums.wav', '../songs/lamprey/bass.wav',
'../songs/lamprey/piano.wav', '../songs/lamprey/violin.wav']
STARTUP_DELAY = 1.0
MAX_AUDIO_OUTPUT_QUEUE_LENGTH = 10
|
class MockReader(object):
"""
Class for unit testing to record all actions taken to the reader and
report them to the tests.
"""
def __init__(self):
self.recorded_actions = list()
self.mock_results = list()
self.mock_result_index = 0
self.raise_exception_on = None
... |
PUZZLE_PRICE = 2.60
TALKING_DOLL_PRICE = 3
TEDDY_BEAR_PRICE = 4.10
MINION_PRICE = 8.20
TRUCK_PRICE = 2
trip_price = float(input())
puzzles_count = int(input())
talking_dolls_count = int(input())
teddy_bears_count = int(input())
minions_count = int(input())
trucks_count = int(input())
total_count = puzzles_count + ta... |
# To jest komentarz, zaczal sie od # - nic nie zmienia w kodzie, ale go opisuje
print('1. Wstęp:\n\n')
# 1. Poniżej mamy 2 zmienne o typie tekstowym
text1 = 'Hello '
text2 = 'World'
#Funkcja print() sluzy do wypisania czegos na ekran
#Dodawanie tekstu do tekstu oznacza łączenie go
print(text1 + text2)
#Dodawanie lub in... |
ATArticle = 0
ATString = 1
ATBasePrice = 2
ATReleased = 3
ATEmblemPrices = 4
AHat = 0
AGlasses = 1
ABackpack = 2
AShoes = 3
ABoysHat = 4
ABoysGlasses = 5
ABoysBackpack = 6
ABoysShoes = 7
AGirlsHat = 8
AGirlsGlasses = 9
AGirlsBackpack = 10
AGirlsShoes = 11
APriceTest = 5
APriceBasic = 250
APriceBasicPlus = 400
APriceCoo... |
def setup():
size(500,500)
smooth()
noLoop()
def draw():
background(100)
stroke(136, 29, 203)
strokeWeight(110)
line(100,150,400,150)
stroke(203, 29, 163)
strokeWeight(60)
line(100,250,400,250)
stroke(203, 29, 29)
strokeWeight(110)
line(100,350,400... |
load("//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external")
def dependencies():
import_external(
name = "com_google_errorprone_error_prone_annotations",
artifact = "com.google.errorprone:error_prone_annotations:2.2.0",
artifact_sha256 = "6ebd22ca1b9d8ec06d41de8d64e0596... |
def get_collocated_senses(input_offset):
"""
Find collacated senese for a given offset.
"""
# syntagnet sense id length is 9. Add paddings to the front
if len(input_offset) <9:
padding = '0' * (9 - len(input_offset))
sense_id_pos = padding + input_offset
synta... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Créé le 16 Oct 2018
@author: PierreLeGuen
'''
class Project:
""" Classe permettant de réupérer les attributs communs à tout les bâtiments du projet """
def __init__(self, numProject, rows, columns, occupiedCells):
"""
Constructeur de la clas... |
# 汽车
def build_car(build_name, version, **more_info):
print('制造商是:'+build_name)
print('型号:'+version)
print('更多信息:')
for k, v in more_info.items():
print(k+';'+v)
build_car('上海大众', 'xs1', 颜色='black', speed='fast')
|
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
# This is a nullcontext for both sync and async. 3.7 has a nullcontext,
# but it is only for sync use.
class NullContext:
def __init__(self, enter_result=None):
self.enter_result = enter_result
def __enter__(self):
r... |
class AyaChanBotError(Exception):
pass
class AnimeImageSearchingError(AyaChanBotError):
pass
|
# lc697.py
# LeetCode 697. Degree of an Array `E`
# acc | 100% | 41'
# A~0g29
class Solution:
def findShortestSubArray(self, nums: List[int]) -> int:
if len(nums) == len(set(nums)):
return 1
count = Counter(nums)
deg = max(count.values())
ans = len(nums)
for k,... |
cnt = 0
c = int(input())
a = []
for i in range(c):
x = int(input())
a.append(x)
for x in a:
cnt += x
print(cnt) |
{
"targets": [
{
"include_dirs": [
"<!(node -e \"require('nan')\")"
],
"target_name": "cppaddon",
"sources": [ "src/lib.cpp" ]
}
]
}
|
#
# @lc app=leetcode id=276 lang=python3
#
# [276] Paint Fence
#
# @lc code=start
class Solution:
def numWays(self, n: int, k: int):
if n == 0:
return 0
if n == 1:
return k
same = 0
diff = k
for _ in range(1, n):
tmp = diff
dif... |
load("@rules_pkg//:providers.bzl", "PackageVariablesInfo")
def _debvars_impl(ctx):
return PackageVariablesInfo(values = {
"package": ctx.attr.package,
"version": ctx.attr.version,
"arch": ctx.attr.arch,
})
debvars = rule(
implementation = _debvars_impl,
attrs = {
"packa... |
test = {
'name': '',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
>>> a
[1, 8, 7, 20, 13, 32, 19, 44, 25, 56, 31, 68, 37, 80, 43, 92, 49, 104, 55, 116, 61, 128, 67, 140, 73, 152, 79, 164, 85, 176, 91, 188, 97, 200]
""",
'hidden': False,
... |
class Solution:
#description: Given an integer n, return the number of trailing zeroes in n!.
def trailingZeroes(self, n: int) -> int:
nFactorial = self.factorial(n)
total = 0
while nFactorial%10 == 0 and nFactorial > 0:
total += 1
nFactorial = nFactorial//10
... |
'''01 - Faça um Programa que peça dois números e imprima o maior deles.'''
n1 = float(input('Digite um número: '))
n2 = float(input('Digite outro número: '))
maior = 0
if n1 > n2:
maior = n1
else:
maior = n2
print(f'O maior número digitado foi o {maior}')
|
class MyHashSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.num_buckets = 100
self.buckets = [[] for _ in range(self.num_buckets)]
def hash_func(self, inp):
return inp%self.num_buckets
def add(self, key):
"... |
class ClassFairnessMetadata(object):
# :brief Store metadata for an update needed to guarantee class-based fairness
# :param num_classes [int] total no. of classes
# :param class_id_to_num_examples_dict [dict<int, int>] maps class id to no. of examples in class
def __init__(self, num_classes, class_id_t... |
class OblioAlg(object):
def __init__(self):
self.known_tuples = {}
def put(self, attempted_tuple, response):
# This is a callback that the oblio engine feeds the results
# of your guess to.
self.known_tuples.update({attempted_tuple: response})
def produce(self):
rai... |
class BaseParser:
"""
This class is the abstract for the different parser objects.
Like the miseq and directory parser, a new parser class needs the following static methods
find_single_run(directory)
find_runs(directory)
get_required_file_list()
get_sample_sheet(direc... |
N40H = {
'magnet_material' : "Arnold/Reversible/N40H",
'magnet_material_density' : 7450, # kg/m3
'magnet_youngs_modulus' : 160E9, # Pa
'magnet_poission_ratio' :.24,
'magnet_material_cost' : 712756, # $/m3
'magnetization_direction' : 'Parallel',
'B_r' ... |
# class Tree:
# def __init__(self, val, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def solve(self, preorder, inorder):
pi = 0
n = len(preorder)
def helper(i,j):
nonlocal pi
if i > j:
... |
# -*- coding: utf-8 -*-
# DATA
DATAFILE_PATH = "./data/"
INVENTORY_AV_EXPORT = "data.txt"
BACKLOG_EXPORT = "bl.txt"
HFR_EXPORT = "hfr.txt"
SCHEDULE_URL = "https://www.toki.co.jp/purchasing/TLIHTML.files/sheet001.htm"
VALIDATION_DB = "validate.csv"
TRANSLATION_DB = "translate.csv"
OUTFILE = "_materials.xlsx"
# SHIPPIN... |
class FrameData(object):
def __init__(self, number, name, box_count, boxes):
self.number = number
self.name = name
self.box_count = box_count
self.boxes = boxes
def to_serialize(self):
return {
"number": self.number,
"name": self.name,
... |
frase = input('Digite o seu nome completo: ')
print ('Nome em maiúsculo: {}'. format(frase.upper()))
print ('Nome em minúsculo: {}'.format(frase.lower()))
let = len(frase)
esp = frase.count(' ')
total = int(let-esp)
print ('Quantidade total de letras: {}'.format(total))
dividido = frase.split()
let1nome = len(dividido[... |
#
# Copyright 2013 Quantopian, 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 wr... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"... |
def email(em, text):
"""
发送邮件
:return:
"""
print(em, text)
def msg(tel, text):
"""
发送短信
:return:
"""
print(tel, text)
def wechat(num, text):
"""
发送微信
:return:
"""
print(num, text)
# 编写功能:假设用户购买课程,然后给alex发送提醒;
if 1 == 1:
msg('188888888', '张进购买了一个学位课')... |
# Time: O(n)
# Space: O(n)
class Solution(object):
def pushDominoes(self, dominoes):
"""
:type dominoes: str
:rtype: str
"""
force = [0]*len(dominoes)
f = 0
for i in range(len(dominoes)):
if dominoes[i] == 'R':
f = len(dominoes)... |
"""Information tracking the latest published configs."""
bazel = "0.26.0"
registry = "marketplace.gcr.io"
repository = "google/rbe-ubuntu16-04"
digest = "sha256:94d7d8552902d228c32c8c148cc13f0effc2b4837757a6e95b73fdc5c5e4b07b"
configs_version = "9.0.0"
|
def swap(d, k1, k2):
value1 = d[k1]
value2 = d[k2]
d[k1] = value2
d[k2] = value1 |
def area(l, w):
if (l <0 or w< 0):
raise ValueError("Only positive integers, please")
return l*w |
# program r3_00_read.py
# Pierwsze wczytywanie danych i walidacja - funkcja read_datas ostateczna
# Definiujemy funkcję wczytującą dane
def read_datas():
def float_input(user_info, user_prompt, min_value):
print("---[ wczytujemy dane]------------")
print(user_info)
user_input = input(user_... |
class APIException(Exception):
"""The API server returned an error."""
def __init__(self, code, msg):
super(APIException, self).__init__(msg)
self.code = code
class KeepException(Exception):
"""Generic Keep error."""
pass
class LoginException(KeepException):
"""Login exception."""
... |
"""
17173 : 배수들의 합
URL : https://www.acmicpc.net/problem/17173
Input #1 :
10 2
2 3
Output #1 :
42
Input #2 :
1000 3
3 5 7
Output #2 :
272066
"""
n, m = map(int, input().split())
k = list(map(int, input().split()))
s = set()
for ki in k:
for m... |
"""
Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common pr... |
class VALInstanceStatus(object):
"""
Model which represents the status of an VAL instance.
Possible status values are:
* name
* image_name
* created_at
* status
* ip
* used_memory
* used_cpu
* network_tx_bytes
* network_rx_bytes
"""
def __init__(self):
... |
def comp_fill_factor(self):
"""Compute the fill factor of the winding"""
if self.winding is None:
return 0
else:
(Nrad, Ntan) = self.winding.get_dim_wind()
S_slot_wind = self.slot.comp_surface_wind()
S_wind_act = (
self.winding.conductor.comp_surface_active()
... |
abr = {'Alaska':'AK',
'Alabama':'AL',
'Arkansas':'AR',
'Arizona':'AZ',
'California':'CA',
'Colorado':'CO',
'Connecticut':'CT',
'District of Columbia':'DC',
'Delaware':'DE',
'Florida':'FL',
'Georgia':'GA',
'Hawaii':'HI',
'Iow... |
class Photo:
def __init__(self, id, user_id, upload_time, latitude_ref, latitude, longitude_ref, longitude, filename, is_featured):
self.id = id
self.user_id = user_id
self.upload_time = upload_time
self.latitude_ref = latitude_ref
self.latitude = latitude
self.longit... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.