content stringlengths 7 1.05M |
|---|
""" Downloads clang and configures the crosstool using bazel's autoconf."""
load("@bazel_tools//tools/cpp:cc_configure.bzl", "cc_autoconf_impl")
load(":download_clang.bzl", "download_clang")
_TF_DOWNLOAD_CLANG = "TF_DOWNLOAD_CLANG"
_TF_NEED_CUDA = "TF_NEED_CUDA"
def _cc_clang_autoconf(repo_ctx):
if repo_ctx.os.e... |
num1 = 100 #经理
num2 = 200 #zhangsan
num3 = 300 #zhangsan
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Exceptions module
=============================
"""
class GPyPiException(Exception):
"""Core exception class, all exception inherit from this class."""
class GPyPiInvalidAtom(GPyPiException):
"""Raised when determining Portage Atom did not succeed."""
cla... |
A, B = map(int, input().split())
if 6*A < B or A > B:
print('No')
else:
print('Yes') |
#!/usr/bin/env python
def crearLista():
numero = int(input("Número de palabras de la lista:"))
if numero < 1:
print("Error. Debe ser un número >= 1")
return -1
else:
lista = []
for i in range(numero):
print("Palabra ", str(i + 1) + ": ", end="")
palab... |
#
# PySNMP MIB module RAD-SONET-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RAD-SONET-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:36:10 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
# https://leetcode.com/problems/shortest-palindrome/description/
#
# algorithms
# Hard (26.25%)
# Total Accepted: 63.7k
# Total Submissions: 242.7k
# beats 40.0% of python submissions
class Solution(object):
def shortestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
... |
def aumentar(preco=0, taxa=0, formato=False):
p = preco + (preco * taxa/100)
return p if formato == False else moeda(p)
def diminuir(preco=0, taxa=0, formato=False):
p = preco - (preco * taxa/100)
return p if formato == False else moeda(p)
def dobro(preco=0, formato=False):
p = preco * 2
ret... |
#!/usr/bin/env python
# Exercicio 3.9 - Escreva um programa que leia a quantidade de dias, horas, minutos e segundos do usuario. Calcule o total em segundos.
print(' ')
dia = int(input('Informe N° em dias: '))
hora = int(input('Informe N° em Horas: '))
minuto = int(input('Informe N° em Minutos: '))
segundos = int(in... |
'''Crie um programa que leia vários números inteiros
pelo teclado, o programa só vai parar quando o usuário
digitar o valor 777, que é a condição de parada
No final mostre quantos números foram digitados
e qual foi a soma entre eles
(desconsiderando o flag). '''
print('{:=^37}'.format('Code-Save'))
print('{:=^37}'.f... |
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 30 14:28:10 2020
@author: Abhishek Mukherjee
"""
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
tempLst=[]
tempDict=dict()
tempDict=[dict() for i in range(len(strs))]
for i in range(len(strs)):... |
# -*- coding: utf-8 -*-
"""Top-level package for src."""
__author__ = """krishna bhogaonker"""
__email__ = 'cyclotomiq@gmail.com'
__version__ = '0.1.0'
|
class General():
'''
this class runs the experiments with given number of users of each category
'''
def __init__(self, p_manager, c_manager, environment):
self.person_manager = p_manager
self.context_manager = c_manager
self.environment = environment
self.rewards_log = ... |
# usando generator, ele comsome menos memoria
generator = (i ** 2 for i in range(10) if i % 2 == 0)
#o next serve para extrair o valor do generator, importante o generator nbao e uma tupla
print(next(generator))
print(next(generator))
print(next(generator))
print(next(generator))
print(next(generator))
# print(next(ge... |
# Definition for singly-linked list.
class DbListNode(object):
def __init__(self, x, y):
self.key = x
self.val = y
self.next = None
self.prev = None
class LRUCache:
'''
leet code: 146
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。
它应该支持以下操作: 获取数据 get 和 写入数据 put 。
... |
tm = 1
while tm <= 5:
totalTm = 0
qt = int(input(f"Quantos alunos você possui na turma {tm}? "))
contTm1 = 1
ntotal = 0
while contTm1 <= qt:
n = input("Digite o nome do aluno: ").capitalize()
ntaAl = input("Digite a nota do aluno: ")
ntaAl = float(ntaAl.replace(",","."))
... |
def reverse_string(string):
reversed_list = []
string_as_list = list(string)
while string_as_list:
reversed_list.append(string_as_list.pop())
print(''.join(reversed_list))
reverse_string(input())
|
n, m = map(int, input().split())
for _ in range(n):
k, v = input().split()
|
#entrada
e, f, c = str(input()).split()
e = int(e)
f = int(f)
c = int(c)
#processamento
totalGarrafasVazias = e + f
totalRefri = 0
while totalGarrafasVazias >= c:
aux = totalGarrafasVazias // c
totalRefri += aux
totalGarrafasVazias = aux + (totalGarrafasVazias % c)
#saida
print(totalRefri)
|
f1 = 10
print(f1)
if f1:
a1 = 1
a2 = 2
a3 = 3
a4 = 4
a5 = 5
a6 = 6
elif f1:
print(f1)
print(f1)
print(f1)
print(f1)
print(f1)
a1 = 1
a2 = 2
a3 = 3
a4 = 4
a5 = 5
elif f1:
print(f1)
print(f1)
print(f1)
print(f1)
print(f1)
print(f1)
... |
def error_response(status:str, message:str):
"""
This function returns a dictionary of status and message
:param status: The status code of the response
:type status: str
:param message: The message you want to display to the end user
:type message: str
:return: A dictionary o... |
class ZException(Exception):
'''
Exception when z0 is suboptimal.
'''
def __init__(self, text, z, *args):
super(ZException, self).__init__(text, z, *args)
self.text = text
self.z = z
|
#
# PySNMP MIB module TUBS-PROC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TUBS-PROC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:27:58 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
n = int(input('Digite um número: '))
if n % 2 == 0:
print('O numero digitado é PAR!')
else:
print('O número digitado é ÍMPAR! ') |
def operate(opcode, arg1, arg2):
if (opcode==1):
return arg1+arg2
elif (opcode==2):
return arg1*arg2
elif (opcode==3):
return arg1
elif (opcode==4):
return arg1 |
class event(object):
def __init__(self):
self.__funcs = set()
def invoke(self, *args):
for f in self.__funcs:
f.__call__(*args)
def reg(self, func):
self.__funcs.add(func)
|
#!/bin/zsh
'''
Say you have a list of lists where each value in the inner lists is
a one-character string, like this:
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],... |
cycle_info={}
# populate some example cycle info
cycle_info['cycle']=1
cycle_info['time']=1.0
print(cycle_info)
|
"""
You are given a pointer to the root of a binary search tree and values to be inserted into the tree.
Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree.
You just have to complete the function
Input:
The value to be inserted is 6 on the tree be... |
#!/usr/bin/env python3
def minimumBribes(q):
bribes = 0
for i in range(len(q) - 1, -1, -1):
if q[i] - (i + 1) > 2:
print("Too chaotic")
return
for j in range(max(0, q[i] - 2), i):
if q[j] > q[i]:
bribes += 1
print(bribes)
if __name__ ==... |
file = open('./input.txt', 'r')
string = file.read()
lines = string.split()
int_lines = list(map(lambda x: int(x), lines))
result = 0
last_value = 10000
for value in int_lines:
if last_value < value:
result += 1
last_value = value
print(result) |
words_splitted = input("Give me some words: ")
words = words_splitted.split(",")
counter = 0
for i in range(len(words)):
if words[i-1].isalpha() == True:
counter += 1
print(counter) |
def test_vcf(filename):
with open(filename, encoding='utf-8') as handle:
for index, line in enumerate(handle):
line = line.replace('\n', '')
# Already read meta and header in self.__init__
if line.startswith('#'):
continue
list_line = line.sp... |
def gra(up, rundy, limit):
boczne = {
1 : [3,4,2,5],
2 : [6,1,3,4],
3 : [6,1,2,5],
4 : [6,1,2,5],
5 : [6,1,3,4],
6 : [3,4,2,5]
}
punkty = [0 for k in range(len(rundy[0]))]
wynik = punkty[:]
for i in range(len(rundy)):
runda = rundy[i]... |
def getRoadsPoints(sf, shapeval, show=False):
fields = sf.fields
if show:
print("Fields -> {0}".format(fields))
itype=None
iint=None
if shapeval.startswith("Airport"):
for i,val in enumerate(fields):
if val[0] == "FAA_AIRPOR":
itype = i-1
... |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/liudiyang1998/Git/ROS-Robotics-By-Example/Chapter_7_code/src/hector_slam/hector_mapping/msg/HectorDebugInfo.msg;/home/liudiyang1998/Git/ROS-Robotics-By-Example/Chapter_7_code/src/hector_slam/hector_mapping/msg/HectorIterData.msg"
services_str = ... |
'''
URL: https://leetcode.com/problems/powx-n
Time complexity: O(logn)
Space complexity: O(logn)
'''
class Solution:
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
res = self._aux_pow(x, abs(n))
if n < 0:
return 1 / res
... |
class GenericsException(Exception):
"""Base class for exceptions in generics package."""
class GenericsInterfaceFailed(GenericsException, TypeError):
"""When subject fails the interface of a generic function,
and that generic has no callable 'default' to fall back to."""
class GenericsNoDispatch(Generic... |
#!/usr/bin/env python
# -*- coding=utf-8 -*-
color={
"FG_BLAcK": "\033[30m", # 将字符的显示颜色改为黑色
"FG_RED" : "\033[31m", # 将字符的显示颜色改为红色
"FG_GREEN": "\033[32m", # 将字符的显示颜色改为绿色
"FG_YELLOW": "\033[33m", # 将字符的显示颜色改为黄色
"FG_BLUE" : "\033[34m", # 将字符的显示颜色改为蓝色
"FG_PINK" : "\033[35m", # 将字符的显示颜色... |
"""
__init__.py
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__docformat__ = 'restructuredtext'
__version__ = '0.4.3'
|
#
# @lc app=leetcode.cn id=103 lang=python3
#
# [103] 二叉树的锯齿形层次遍历
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
... |
"""
Test that linear solver convergence with correct rate of convergence
when applied to the problem with stable detonation.
"""
# class TestLinearStableConvergence:
# def test_linear_stable_convergence(self):
# pass
|
# 🚨 Don't change the code below 👇
height = input("enter your height in m: ")
weight = input("enter your weight in kg: ")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
bmi = int(weight) / float(height) ** 2
bmi_as_int = int(bmi)
print(bmi_as_int)
#!Or
weight_as_int = int(weight)
height_as_f... |
"""stack."""
class Stack(object):
def __init__(self, item):
self._data = [item]
def push(self, item):
self._data.append(item)
def pop(self):
if len(self._data) == 0:
raise ValueError('Your stack is empty')
return self._data.pop()
def getMin(self):
... |
# List of API keys
ALPACA_API_KEY = "PKV6PG76ZRMOXUSLQMC6"
ALPACA_SECRET_KEY = "YD22E2jiKZRfer69McRcQIJX0kxGpXy13I0oTIzN"
ALPACA_BASE_URL = "https://paper-api.alpaca.markets"
AMERITRADE_TOKEN = 'https://api.tdameritrade.com/v1/oauth2/token'
AMERITRADE_KEY = '6JWAH9JYWA5CSCOG5WC6PAPLYIASBTTV' |
REGION = "your_region_name"
BUCKET = "your_bucket_name"
DATABASE = "your_database_name"
TABLE = "your_table_name"
INDEX_COLUMN_NAME = "date"
|
class StatusLifecycle():
"""
This class represents a lifecycle of statuses.
"""
class InvalidLifecycleException(Exception):
"""
raised if a lifecycle is invalid
"""
pass
def __init__(self, *lifecycle_statuses):
"""
:param lifecycle_statuses: a set of ... |
class Math(object):
""" Provides constants and static methods for trigonometric,logarithmic,and other common mathematical functions. """
@staticmethod
def Abs(value):
"""
Abs(value: Single) -> Single
Returns the absolute value of a single-precision floating-point number.
value: A number ... |
# Copyright 2018 The Bazel Authors. 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
#
# Unless required by applicable la... |
numeros = [111, 7, 2, 1]
print(len(numeros))
print(numeros)
#Un nuevo elemento puede ser añadido al final de la lista existente:
#Dicha operación se realiza mediante un método llamado "append()".
#Toma el valor de su argumento y lo coloca al final de la lista que posee el método.
#La longitud de la lista aumenta en un... |
def aumento(num=0, p=0, form=False):
"""
-> Calcula uma porcentagem e soma
:param num: preço
:param p: porcentagem à calcular
:param form: (opcional) formatação (.2float e troca de ponto por virgula)
:return: :var f : que é o resultado do calculo de porcentagem
"""
f = num + (num * p / 1... |
## Error to exception
# The intention is to return an error
# from
def withdraw(self, amount):
if amount > self.balance:
return -1
else:
self.balance -= amount
return 0
# to
def withdraw(self, amount):
if amount > self.balance:
raise BalanceException() # or Exception
self... |
# -*- coding: utf-8 -*-
__version_info__ = '0.6.3'
__version__ = '0.6.3'
version = '0.6.3'
|
'''
Building your own digit recognition model
You've reached the final exercise of the course - you now know everything you need to build an accurate model to recognize handwritten digits!
We've already done the basic manipulation of the MNIST dataset shown in the video, so you have X and y loaded and ready to model ... |
'''
Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and a
boolean indicating if we are on vacation, return a string of the form "7:00"
indicating when the alarm clock should ring. Weekdays, the alarm should be
"7:00" and on the weekend it should be "10:00". Unless we are on vacation --
then on weekday... |
"""
Created on Jan 28 16:58 2020
@author: nishit
""" |
def original(abreviada):
out = '' # Concatenaremos la palabra original
i = 0 # Para los indices del string
while i < len(abreviada): # Recorremos los indices del string
n = int(abreviada[i]) # Obtenemos el numero de repeticiones
l = abreviada[i+1] # Obtenemos la letra
out += l * n #... |
test = {
'name': 'remove',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
scm> (remove 3 nil)
()
""",
'hidden': False,
'locked': False
},
{
'code': r"""
scm> (remove 2 '(1 3 2))
(1 3)
... |
# -*- coding: utf-8 -*-
#
# Author: Tomi Jylhä-Ollila, Finland 2016
#
# This file is part of Kunquat.
#
# CC0 1.0 Universal, http://creativecommons.org/publicdomain/zero/1.0/
#
# To the extent possible under law, Kunquat Affirmers have waived all
# copyright and related or neighboring rights to Kunquat.
#
def get_pr... |
# -*- coding:utf-8 -*-
# ---------------------------------------------
# @file BubbleSort.py
# @description Bubble Sort
# @author WcJun
# @date 2020/06/21
# ---------------------------------------------
# 时间复杂度: 最好:O(n) 最坏:(n^2)
# 稳定性: 稳定
# bubble_sort
def bubble_sort(origin_list):
length = len(origin_list)
... |
r = 'SIM'
while r == 'SIM':
n = int(input('Digite um valor: '))
r = str(input('Quer continuar? Sim/Não: ')).upper()
print('Fim')
|
#
# PySNMP MIB module ARISTA-QOS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ARISTA-QOS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:09:19 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... |
class Solution(object):
def findErrorNums(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
for i in range(len(nums)):
if nums[i] != i + 1:
cur = nums[i]
while True:
replace = nums[cur - 1]
... |
# twonums_sum returns the index of the nums inside the list that can become n
def twonums_sum(n, lst):
d = {}
for i in range(len(lst)):
d[lst[i]] = i # create number-subscript pair
for i in range(len(lst)):
if n - lst[i] in d:
return i, d[n-lst[i]]
return -1
l... |
class Solution:
def longestPalindrome(self, s: str) -> str:
if not s or len(s) <= 1:
return s
result = ''
max_len = 0
n = len(s)
dp = [[False] * n for _ in range(n)]
for i in range(n):
dp[i][i] = True
if 1 > max_len:
... |
# coding=utf-8
"""
Track your life like a pro on Google Calendar via your terminal.
"""
__version__ = '0.2.2'
__author__ = 'adamchainz'
__license__ = 'MIT'
|
class Computer:
def __init__(self,prog):
if type(prog)==str:
prog = [int(x.strip()) for x in prog.split(",") if x.strip()]
self.memory = prog
def evaluate(self):
pc = 0
while pc<len(self.memory) and self.memory[pc]!=99:
if self.memory[pc]==1:
from_, to_, store = self.memory[pc+1:pc+4]
self.memor... |
#
# PySNMP MIB module INTEL-ES480-VLAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/INTEL-ES480-VLAN-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:42:49 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
class BaseError(Exception):
pass
class AddQueryInvalid(Exception):
def __init__(self, exception, message="Parameter Add condition is invalid"):
self.message = message
self.exception = exception
super().__init__(self.message)
def __str__(self):
return f'{self.message}: {sel... |
"""
Django Extras
~~~~~~~~~~~~~
Extensions for Django to solve common development situations not (or not yet)
covered by the core Django framework.
"""
__version__ = '0.3'
|
lang1 = {'Hindi','Urdu'}
lang2= {'Punjabi'}
print("Original Set: ", lang2)
lang2 = lang1.copy()
print("Copied Set: ", lang2)
|
# Celcius to Fahrenheit Temperature Converter
cel = int(input('Enter Cº '))
f = (9 / 5) * cel + 32
print(cel, "celcius equals to", f, "fahrenheit degrees.")
|
def datacfg():
datacfg = dict()
datacfg['abalone'] = dict()
datacfg['abalone']['filepath'] = '.\\data\\abalone.pkl'
datacfg['abalone']['targets'] = ['rings']
datacfg['abalone']['probtype'] = ['regression', 'classification']
datacfg['autoMpg'] = dict()
datacfg['autoMpg']['filepath'] = '.\\dat... |
# -*- coding: utf-8 -*-
class Video():
"""
视频类(非番剧剧集)
"""
def __init__(self, aid = None, title = None):
if aid:
self.aid = aid # article id 即av号 json中的 'id' 与此相同
if title:
self.title = title # 标题 或 番剧名
self.cid = None # chat id 即弹幕池号
self.copyr... |
# Define echo
def echo(n):
"""Return the inner_echo function."""
# Define inner_echo
def inner_echo(word1):
"""Concatenate n copies of word1."""
echo_word = word1 * n
return echo_word
# Return inner_echo
return inner_echo
# Call echo: twice
twice = echo(2)
# Call echo: th... |
def my_function(function):
function()
print(my_function(lambda : 99))
|
class Tokenizer:
def tokenize(self, text):
# remove comments but keep empty lines instead
# to preserve line numbers
lines = text.splitlines()
lines = [('' if line.strip().startswith(';') else line) for line in lines]
t = '\n'.join(lines)
# expand symbols for easier... |
#!/usr/bin/env python3
bicycles = ["trek", "cannondale", "redline", "specialized"]
print("{}\n".format(bicycles))
print("{} Object type: {}".format("bicycles", type(bicycles)))
print(bicycles[0])
for bike in bicycles:
print(bike.title())
|
def merge(a: list, b: list) -> list:
i = 0
j = 0
c = [0 for _ in range(len(a) + len(b))]
while i < len(a) or j < len(b):
if j == len(b) or i < len(a) and a[i] < b[j]:
c[i + j] = a[i]
i += 1
else:
c[i + j] = b[j]
j += 1
return c
... |
class CORSMiddleware:
def process_response(self, request, response):
response['Access-Control-Allow-Origin'] = "*"
return response
|
#Exemplo de função em Python
def ola():
print("Olá!")
print("Olá!!!")
print("Alguém aí?")
ola()
ola()
ola()
#Exemplo fç ola com mome
def ola(name):
print("\n\nOlá, " + name,"!\n")
ola("Alice")
ola("Carlos")
|
# Copyright 2019, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Python test originally created or extracted from other peoples work. The
# parts from me are licensed as below. It is at least Free Software where
# it's copied from other people. In these cases, that will normally be
# indicated.
#
# L... |
# Write a Python program to
# input a string and change its
# case to Sentence case using capitalize()
# function. It will convert only the first
# (beginning)lower case letter to upper case.
# it will capitalize only first letter
# of a Sentence.
# The user will enter String
# during program execution
# Start of the ... |
# SPDX-License-Identifier: BSD-2-Clause
QEMU_SPECIAL_KEYS = {
" " : "spc",
"!" : "shift-1",
'"' : "shift-apostrophe",
"#" : "shift-3",
"$" : "shift-4",
"%" : "shift-5",
"&" : "shift-7",
"'" : "apostrophe",
"(" : "shift-9",
")" : "shift-0",
"*" : "shift-8",
"+" : "shift-e... |
class XSDSimpleTypeFontSize(XSDSimpleType):
"""The font-size can be one of the CSS font sizes (xx-small, x-small, small, medium, large, x-large, xx-large) or a numeric point size.
.. todo::
Better documentation.
"""
_UNION = [XSDSimpleTypeCssFontSize, XSDSimpleTypeDecimal]
XSD_TREE = XSDTree... |
#! Дан текст. Найти слова, состоящие из цифр, и сумму чисел, которые
# образуют эти слова (не используя регулярных выражений).
def find_sum(string):
string = string + ' '
new_string, words, word_library, numbers_lib, sum_words = '', [], {}, {}, 0
for symbol in string: # Разделяем текст на слов... |
# You are given two arrays (no duplicates): arr1 and arr2 where arr1 is a subset of arr2.
# For each item x in arr1 find the first proceeding number, y, in arr2 such that y > x and
# is to the right hand side of x in arr2. If such number does not exist, return -1.
#
# Ex.
# arr1 = [4, 1, 2]
# arr2 = [1, 3, 4, 2]
# outp... |
def solve(floor, room):
pass
if __name__ == '__main__':
num_tc = int(input())
for _ in range(num_tc):
k = int(input())
n = int(input())
print(solve(k, n))
|
def getData(self, device):
""" Returns a list of tuples like {controller, device, data} with data elements """
cam = self.Devices[device["id"]]['objOfCapture']
_, frame = cam.read()
if frame is None:
return []
height = np.size(frame, 0)
width = np.size(frame, 1)
deviceName = Misc.... |
class Solution:
def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
n = len(buildings)
if n == 0:
return []
if n == 1:
xLeft,xRight,y = buildings[0]
return [[xLeft,y],[xRight,0]]
leftSky = self.getSkyline(buildings[: n//2]... |
for i in range(1, 100 + 1):
text = ''
if i % 3 == 0:
text += 'Fizz'
if i % 5 == 0:
text += 'Buzz'
if text == '':
print(i)
else:
print(text)
|
def is_palindrome(n):
if str(n) == str(n)[::-1]:
return True
return False
# Examples:
is_palindrome(101) # True
is_palindrome(147) # False
|
def rest_error_response(Status,Message,Format = 'XML',TwilioCode = None,TwilioMessage = None):
response = {
"Status" : Status,
"Message" : Message
}
if TwilioCode is not None:
response['Code'] = TwilioCode
if TwilioMessage is not None:
response['MoreInfo'] = TwilioMessage
if Format == '' or Format == 'XML' o... |
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
class ObjectClassEnum(object):
"""Implementation of the 'ObjectClass' enum.
Specifies the object class of the principal (either 'kGroup' or 'kUser').
'kUser' specifies a user object class.
'kGroup' specifies a group object class.
'kComputer' ... |
# Copyright 2020 AUI, Inc. Washington DC, USA
#
# 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 ... |
""" Simple BMW ConnectedDrive API.
init file for backward compatibility
"""
# empty
|
# -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteNode(self, listNode, toDeleteNode):
if listNode == None or toDeleteNode == None:
return listNode
if listNode == toDeleteNode:
return list... |
# Write a program that reads in two floatingpoint numbers and tests whether they are
# the same up to two decimal places. Here are two sample runs.
# Enter a floating-point number: 2.0
# Enter a floating-point number: 1.99998
# They are the same up to two decimal places.
# Enter a floating-point number... |
def build_filter(args):
return Filter(args)
class Filter:
def __init__(self, args):
if args == '':
message = b'<empty commit message>'
else:
message = args.encode('utf8')
self.message = message
def commit_message_filter(self,commit_data):
# Only writ... |
# @Fábio C Nunes - 14.06.20
classe = {}
n = str(input('Digite o nome do aluno : '))
m = float(input('Digite a média do aluno: '))
if m > 7:
sit = 'Aprovado!'
else:
sit = 'Reprovado!'
classe['nome'] = n
classe['média'] = m
classe['situação'] = sit
print('*' * 30)
print(f'O aluno(a) {classe["nome"]} tirou {classe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.