content stringlengths 7 1.05M |
|---|
# 数据库名
Database_Name = "Security-Controller"
# 服务器域名
Host_Name = "https://rocket.work"
# 服务器存放静态文件地址
Static_Path = '/var/www/LouisYoung/static'
# 邮件发送名
Email_Sender = "Louis·Young"
# redis缓存
Redis_Data = "3"
|
def stock_list(listOfArt, listOfCat):
if len(listOfArt) == 0 or len(listOfCat) == 0:
return ""
books = {}
result = []
for book in listOfArt:
title_num = book.split()
title = title_num[0]
num = title_num[1]
if title[0] in books:
books[title[0]] += int... |
'''Функция Эйлера. Это важная функция в теории чисел: ф(п) определяется
как количество положительных целых чисел, меньших или равных п, взаимно
простых сп (никаких общих множителей, кроме пи 1). Составьте
функцию, получающую целочисленный аргумент п и возвращающую
ф(п). Глобальный код должен получать из командной с... |
list = ['a','e','i','o','u']
a = input("Enter a character: ")
if a in list :
print(a, "is vowel")
else :
print(a, "is consonant") |
#MOSTRAR TDS OS NUMEROS PARES QUE ESTAO NO INTERVALO DE 1 A 50
for par in range(1,51):#COLOCOU DE 1 ATE 51 PQ TEM Q MOSTRAR O 50 JA QUE ELE E PAR
if(par%2==0):
print(par, end=' ') #esse end deixa o numero do lado " " coloca espaco
print("\n")
|
class HivenError(Exception):
"""Base class for all Hiven exceptions"""
pass
|
# Day 1, puzzle 2: Sonar Sweep
with open("input", "r") as fd:
depths = [int(x) for x in fd.readlines()]
# this solution is largely going to be similar with 1-1's, but repeated to
# create appropriate sliding windows (which then get zipped for comparison)
window_a = zip(depths, depths[1:], depths[2:])
window_b = ... |
class Solution(object):
def addStrings(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
output = []
carry = 0
p1 = len(num1) - 1
p2 = len(num2) - 1
print('Hello World')
while p1 >= 0 or p2 >= 0:
... |
def solution(A):
num_count = {}
for num in A:
num_count[num] = num_count.get(num, 0) + 1
for num, count in num_count.items():
if count > len(A) // 2:
return A.index(num)
return -1
# https://codility.com/media/train/6-Leader.pdf
def solution_2(A):
size, value = 0, N... |
"""
Given an undirected graph with n vertices and m edges,
compute the number of connected components in it.
"""
def vertices_to_components(g):
"""
Build dictionary of vertices to connected component keys
"""
vertex_to_component = {}
key = 0
vertices = g.get_vertices()
for vertex in verti... |
class User:
def __init__(self,name):
self.name=name
def show(self):
print(self.name)
@classmethod
def class_foo(cls):
print(cls)
def printMessage(self):
print("hi")
user =User("ada66")
user.show()
user.age=35
user.class_foo()
print(user.age)
def showMsg():
print("hi")
user.show=showMsg
... |
for nname, net in ctx.nets:
ctx.lockNetRouting(nname)
ctx.cells["slice_i"].addInput("A0")
ctx.connectPort("ctr[26]", "slice_i", "A0")
ctx.cells["slice_i"].setParam("LUT0_INITVAL", "0101010101010101") # LED is active low so invert
ctx.cells["slice_i"].setParam("A0MUX", "A0") # remove constant mux on LUT input
|
ALPHABET = ''.join([chr(ord('a')+i) for i in range(26)])
class Possibility:
def __init__(self, letter, complete, extendable_end, extendable_start):
self.letter = letter
self.complete = complete
self.extendable_end = extendable_end
self.extendable_start = extendable_start
class Pa... |
class AddRequestToFormMixin(object):
def get_form_kwargs(self):
kwargs = super(AddRequestToFormMixin, self).get_form_kwargs()
kwargs.update({
'request': self.request,
})
return kwargs
|
def test_pass():
assert (1,2,3) == (1,2,3)
'''此处为被测方法,在PytestDemo1被引用'''
'''这个方法是个选出set中最大值的方法'''
def max(value):
_max = value[0]
for val in value:
if val > _max:
_max = val
return _max
def min(values):
_min = values[0]
for val in values:
if val < _min:
_min =... |
# Environment variables
ENV_GCS_PROJECT = "GCS_PROJECT"
ENV_GCS_BUCKET = "GCS_BUCKET"
ENV_GCS_ROOT = "GCS_ROOT"
ENV_CATALOG_PATH = "CATALOG_PATH"
|
l = []
while True:
try:
e = str(input())
if not e in l:
l.append(e)
except EOFError:
print(len(l))
break
|
SITE_PREFIX = '/infoset'
API_PREFIX = '{}/api/v1'.format(SITE_PREFIX)
API_EXECUTABLE = 'infoset-ng-api'
API_GUNICORN_AGENT = 'infoset-ng-gunicorn'
INGESTER_EXECUTABLE = 'infoset-ng-ingester'
|
"""
问题描述:N皇后问题是指在N*N的棋盘上要摆N个皇后,要求任何两个皇后不同行、不同列,也不在
同一条斜线上,给定一个整数n,返回n皇后的摆法有多少种。
举例:
n=1,返回1
n=2或者3,2皇后和3皇后无论怎么摆都不行,返回0
n=8,返回92
"""
class NQueenProblem:
@classmethod
def solve_by_recursive(cls, n):
if n < 1:
return 0
record = [0 for _ in range(n)]
return cls.recursive_deta... |
def checkPrime(a):
# start_times.append(datetime.now())
i = 1
while i < (a - 1):
i += 1
if a % i == 0:
return False
return True
lim = int(input("Choose integer: "))
list_to_lim = list()
for i in range(2, lim + 1):
if i%2==0:
continue
else:
list_to_lim... |
students = []
def read_file():
try:
f = open("students.txt", "r") # read text from a file using access mode r
for student in read_students(f):
students.append(student)
f.close()
except Exception:
print("Could not read file")
# use generator with yield to read eac... |
class Multiselect:
def __init__(self,data):
self.data=data
@classmethod
def init_from_options(cls,options):
data=[{"key":x,"value":False} for x in options]
return(cls(data))
def keys(self):
keys=[x["key"] for x in self.data]
return(keys)
def val... |
# -*- coding:utf-8 -*-
# file: __init__.py
# author: Mundy
# date: 2017/5/10 0010
"""
""" |
TITLE = 'Roguelike'
AUTHOR = 'Lukas Singer, Daniel Nimmervoll'
EMAIL = 'lukas42singer (at) gmail (dot) com'
COPYRIGHT = 'Copyright (C) 2017 - 2018 by {}'.format(AUTHOR)
CREDITS = [
"https://www.python.org/",
"https://vim.sourceforge.io/",
"http://www.roguebasin.com/",
""]
# the whole screen size
SCREE... |
"""Internal module that keeps the abstract Tracker class."""
class Tracker(object):
"""This class is an abstraction for all supported trackers."""
NOT_IMPLEMENTED_MSG = 'To be implemented in device-linked class'
def __init__(self):
"""Create an instance ready for connecting."""
self.__co... |
### Beautiful Days at the Movies - Solution
def beautifulDays(i, j, k):
count = 0
for x in range(i, j+1):
if abs(x - int(str(x)[::-1])) % k == 0:
count += 1
print(count)
i, j, k = map(int, input().split())
beautifulDays(i, j, k) |
def linha(lin):
print('-' * 45)
lista = []
while True:
valor = int(input('Digite um valor: '))
linha('')
if valor not in lista:
print(f'\033[34mO número {valor} foi adicionado com sucesso...\033[0m')
linha('')
lista.append(valor)
else:
print('\033[31mValor duplicado... |
def fight(player, bot):
while isAlive(player) and isAlive(bot):
player.playerHit(bot)
bot.botHit(player)
siin(player)
if isAlive(player):
print(player.name + " WON!!")
elif isAlive(bot):
print(bot.name + " WON!!")
else:
print("TIE!!!")
def hit(power):
... |
# Copyright (c) 2017 Dustin Doloff
# Licensed under Apache License v2.0
# Default methods and attributes associated with Targets. This is due to limitations in Bazel being
# unable to detect if an attribute of an object is a method or really an attribute
DEFAULT_TARGET_STRUCT_KEYS = [
"data_runfiles",
"default... |
class Transformers:
@staticmethod
def list2string(string_list: list, separator='\n') -> str:
"""
Turn list of objects into one string object.
:param separator:
:param string_list:
:return:
"""
if len(string_list) > 0:
return ''.join([f'{item}{s... |
# -*- coding: utf-8 -*-
VIDEO_RESOLUTIONS = ["highest", "high", "medium", "low"]
def findnth(haystack, needle, n):
"""
Find the nth occurrence of one string in another
"""
parts = haystack.split(needle, n + 1)
if len(parts) <= n + 1:
return -1
return len(haystack) - len(parts[-1]) - l... |
""" In a given grid, each cell can have one of three values:
the value 0 representing an empty cell; the value 1 representing a fresh
orange; the value 2 representing a rotten orange. Every minute, any fresh
orange that is adjacent (4-directionally) to a rotten orange becomes rotten.
Return the mi... |
"Public providers, aspects and helpers that are shipped in the built-in rules_nodejs repository."
load(
"//nodejs/private/providers:declaration_info.bzl",
_DeclarationInfo = "DeclarationInfo",
_declaration_info = "declaration_info",
)
load(
"//nodejs/private/providers:js_providers.bzl",
_JSModuleIn... |
def insertion_sort(A):
for i in range(1,len(A)):
key=A[i]
j=i-1
while j>=0 and A[j]>key:
A[j+1]=A[j]
j-=1
A[j+1]=key
return A
|
def test_min(prepared_tree_for_minimax):
assert prepared_tree_for_minimax[0][0] == 2
assert prepared_tree_for_minimax[0][1] == 1
assert prepared_tree_for_minimax[0][2] == -1
def test_max(prepared_tree_for_minimax):
assert prepared_tree_for_minimax[1][0] == 100
assert prepared_tree_for_minimax[1][1... |
id = []
val = []
soma, cont = 0, 0
while True:
vid = int(input('Id: '))
if vid < 0:
break
vval = int(input('Valor a pagar: '))
id.append(vid)
val.append(vval)
cont += 1
soma += vval
for i in range(cont):
print(f'Id: {id[i]}\nValor: {val[i]}')
print(f'Total: {soma}') |
## Set up SW Trigger
# Create an instance of the Software Trigger Module (ziDAQRecorder class).
trigger = daq.record()
trigger_path = '/%s/demods/%d/sample' % (device, demod_index)
triggernode = trigger_path + '.TrigAWGTrig1'#'.r'
trigger.set('trigger/0/triggernode', triggernode)
# Use an edge trigger.
trigg... |
class Funcioanrio:
def __init__(self):
self._matricula = None
self._nome = None
self._cargo = None
@property
def matricula(self):
return self._matricula
@property
def nome(self):
return self._nome
@property
def cargo(self):
return self._car... |
# Create a program to enter student information,
# store it as list of student and allow to search students by their name (partial)
'''
Tạo một chương trình để nhập thông tin sinh viên,
lưu trữ dưới dạng danh sách sinh viên và cho phép tìm kiếm sinh viên theo tên của họ (một phần)
'''
class Student:
... |
#
# PySNMP MIB module A3COM0017-STACK-CONFIG (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM0017-STACK-CONFIG
# Produced by pysmi-0.3.4 at Wed May 1 11:08:38 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... |
def inc(i):
return i + 1
def add(a, b):
return a + b
def sub(a, b):
return a - b
|
class SuperMetroidRooms:
addrToNumDoors = {
"0791F8" : 4,
"0792B3" : 2,
"0792FD" : 7,
"0793AA" : 1,
"0793D5" : 1,
"0793FE" : 6,
"079461" : 2,
"07948C" : 3,
"0794CC" : 3,
"0794FD" : 2,
"079552" : 2,
"07957D" : ... |
print('''
*******************************************************************************
| | | |
_________|________________.=""_;=.______________|_____________________|_______
| | ,-"_,="" `"=.| |
|_______________... |
@auth.requires_membership("Administradores")
def index():
query = request.vars.query or "auth_user"
grid = SQLFORM.grid(db[query],user_signature=False,editable=True,deletable=True,create=True)
return locals() |
# Elections newsfeed. Seconday strings are not being used at this point
newsfeed_strings = [
{ # VOTED
'primary' : {'string' : _('You voted "%s" for %s'),
'params' : ['issue_vote', 'issue_title']},
'secondary' : {'string' : _('%s voted "%s" for %s'),
'params... |
# ## Complete Doji
# import threading
# import pandas as pd
# from queue import Queue
# import time
# import requests
# file = open("stock_pred.txt", "w")
# data = pd.read_csv("C:\\Users\\BEST BUY\\Desktop\\NASDAQ_20200331.csv")
# symbols = data.iloc[:100,0:1].values
# th = Queue(maxsize = 4000)
def doji(arg):
# p... |
def definition():
"""UI breakdown of finance data"""
view = """
SELECT set_id, summary_code, account, account_description, sum(amount) as amount FROM v_mri_finance
GROUP BY set_id, summary_code, account, account_description
"""
return view
|
string = input("Enter a string: ")
reverse = reversed(string)
if list(string) == list(reverse):
print("It is a palindrome")
else:
print("It is not a palindrome") |
alunos = {}
sala = []
def notas():
'''
Essa funcao perguntará as notas dos alunos e dirá quais são suas
MENOR NOTA
MAIOR NOTA
MEDIA
SITUAÇÃO
:return:
'''
maior = menor = soma = 0
global sala
global alunos
dados = dict()
while True:
alunos['nome'] = str(input('... |
class DirectedEdge:
_edge = None
def __init__(self, edge):
# $edge should like :
# ( (from_index, point_info), (to_index, point_info) )
self._edge = edge
def fr(self):
return self._edge[0]
def to(self):
return self._edge[1]
def revere(self):
return... |
INITIAL_RPC_IF_ID = RPC_IF_ID
class _RPC_IF_ID(INITIAL_RPC_IF_ID):
def __repr__(self):
return '<RPC_IF_ID "{0}" ({1}, {2})>'.format(self.Uuid.to_string(), self.VersMajor, self.VersMinor) |
# Generate the output like: A(5), B(3), C(1) with input like ABBAAACB
print('Write your string:')
value = input()
dic_str = {}
list_count = []
count = 0
for i in value:
dic_str.update({i: ''})
# print(dic_str)
for x in dic_str:
result = "{}({})"
print(result.format(x, value.count(x)))
# print(... |
#Support variables for suit checking and card scoring
class Common():
ROYAL_FLUSH_CARD:str = {"T": "10",
"J": "11",
"Q": "12",
"K": "13",
"A": "14"}
VALUE_CARD:str = {"2": "2",
... |
# Задача 2. Вариант 21.
#Напишите программу, которая будет выводить на экран наиболее понравившееся вам высказывание, автором которого является Леонардо да Винчи. Не забудьте о том, что автор должен быть упомянут на отдельной строке.
# Platonova O. A.
# 29.05.2016
print("Истина была единственной дочерью времени.\n\t\... |
class MiningRig:
def __init__(self, hashpower, user):
self.hashpower = hashpower
self.mining_block = None
self.user = user
self.user._miningrigs.append(self)
def __str__(self):
return "Mining Rig Hashpower " + str(self.hashpower) + " owned by " + str(self.user)
|
N = int(input())
bfr = [[[0]*10 for i in range(3)] for j in range(4)]
for i in range(N):
b, f, r, v = [int(n) for n in input().split()]
bfr[b-1][f-1][r-1] += v
c = 0
for B in bfr:
for F in B:
print(' '.join([str(c) for c in F]).rjust(20))
# print('{:>20}'.format(' '.join([str(c) for c in F]))... |
class CardPack:
cardname = [i + j for i in ["♥️", "♦️", "♠️", "♣️"] for j in ["3","4","5","6","7","8","9","10","J","Q","K","A","2"]] + ["小王", "大王"]
def __init__(self, cards):
# cards is a list of 54 boolean elements
self.cards = cards
self.type_str, self.type_num, self.rank, self.length... |
def fibonacci(n):
if n < 0:
raise ValueError("n > 0")
print(fibonacci.hints)
print()
if n < len( fibonacci.hints ):
return fibonacci.hints[ n ]
else:
val = fibonacci(n-1) + fibonacci(n-2)
if len(fibonacci.hints) == n:
fibonacci.hints.append( val )
... |
# -*- coding: utf-8 -*-
"""
create on 2021-01-29 20:19
author @66492
"""
|
class nsfnet_layout_generate():
def __init__(self): #棱长
self.__number=28
self.__access_pos=[(-1.2,0.4),(-1.6,0),(-1.4,-0.4),(-1,0),(-0.6,-0.2),(-0.2,-0.6),(0,0),(0.4,0.2),(1,0),(0.6,-0.8),\
(0.8,0.6),(1.4,0.4),(1.2,-0.4),(1.6,0)]
self.__server_pos=[]
for d... |
def abs(number):
return -number if number < 0 else number
# print(max([1, 2, 3]))
# print(min([1, 2, 3, -10, 0, 3]))
# print(sum([1, 2, 3, 4, -4, -6]))
# print(abs(-10))
# print(abs(10))
# print(list(map(bool, [1, 2, 4, 'hello', True, []])))
print(ord('\n'))
print(chr(ord('f')))
print('hello')
|
def extract_command_from_request(request, fields):
command = {}
for field in fields:
if field in request.json:
command[field] = request.json[field]
return command
|
# song.py
"""
Small class to represent a song for the queue.
"""
# Copyright (C) 2021 JulioLoayzaM
#
# You may use, distribute and modify this code under
# the terms of the MIT license.
#
# See the LICENSE file for more details.
class Song():
"""
A class to represent a song. Stores the title, the name of the down... |
class BezierCurve(object,IDisposable):
"""
Represents a Bezier curve.
Note: as an exception,the bezier curve is not derived from Rhino.Geometry.Curve.
BezierCurve(controlPoints: IEnumerable[Point2d])
BezierCurve(controlPoints: IEnumerable[Point3d])
BezierCurve(controlPoints: IEnumerable[Poin... |
#
# @lc app=leetcode id=581 lang=python3
#
# [581] Shortest Unsorted Continuous Subarray
#
# https://leetcode.com/problems/shortest-unsorted-continuous-subarray/description/
#
# algorithms
# Easy (30.58%)
# Likes: 1985
# Dislikes: 97
# Total Accepted: 94.1K
# Total Submissions: 307.2K
# Testcase Example: '[2,6,4... |
#c
for row in range(7):
for col in range(7):
if (row==0 and col!=0) or (col==0 and row!=0 and row!=7 and row!=6)or (row==6 and col!=0):
print("*",end=" ")
else:
print(" ",end=" ")
print()
|
configuration = {
'SLEEP_TIME': 600,
'ST_IP': 'IP',
'PHONES': {
'{NAME1}': {'uuid': '{UUID}', 'status': None, 'count': 0},
'{NAME2}': {'uuid': '{UUID}', 'status': None, 'count': 0}
}
}
|
#!/opt/local/bin/python
bp_file="5_input.txt"
def load_file(filename):
record_list=[]
bpfile=open(filename, "r")
for i in bpfile:
record_list.append(i)
return record_list
def find_row(bpass):
bitmap=""
for i in bpass[0:7]:
# print(i,)
if i == "B":
bitmap+="1"
elif i == "F":
bit... |
# 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 kolit(s):
ile = 0
kolumny = ["" for k in range(len(s))]
i = 0
while len(s) > i:
for j in range(len(s[:i + 1])):
kolumny[j] += s[:i + 1][j]
s = s[i + 1:]
i += 1
for l in range(len(s)):
kolumny[l] += s[l]
for elem in kolumny:
if elem i... |
#!/usr/bin/python
#Collatz Sequence practice
def collatz(number):
newnum = 0
if number == 1:
return 0
elif number %2 == 0:
newnum = number/2
print(int(newnum))
collatz(newnum)
elif number %2 ==1:
newnum = 3*number +1
print(int(newnum))
collatz(ne... |
# -*- coding: utf-8 -*-
"""Top-level package for mycataloguer."""
__author__ = """Natan Brosztein"""
__email__ = 'code@natanbro.com'
__version__ = '0.1.0'
|
_base_ = [
'RepLKNet_upernet.py',
'../_base_/datasets/cityscapes_769x769.py', '../_base_/default_runtime.py',
'../_base_/schedules/schedule_80k.py'
]
# model settings
model = dict(
decode_head=dict(
num_classes=19,
align_corners=True),
auxiliary_head=dict(
num_classes=19,
... |
lesson_dates = [
'19.05.15',
'19.05.17',
'19.05.18',
'19.05.19',
'19.05.22',
]
student_marks = [
5,
4,
3,
2,
5
]
student_2_marks = [
4,
3,
5,
5,
4
]
date = input('Введите дату:\n')
for lesson_dates, mark, mark_2 in zip(lesson_dates, student_marks, student_2_ma... |
def main():
ps = pyscriber.Scriber()
x = 5
ps.p(x)
y = "hello"
ps.p(y)
a = [1, 2, 3]
ps.p(a)
b = {1: "a", 2: "b"}
ps.p(b)
if __name__=="__main__":
main()
|
print('=' * 5, 'AULA_006b', '=' * 5)
n0 = float(input('digite um valor: '))
print(n0)
n1 = str(input('digite um valor: '))
print(type(n1))
n2 = input('digite algo: ')
print(n2.isnumeric())
|
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
s = []
carry = 1
for i in range(len(digits) - 1, -1, -1):
d = digits[i] + carry
if d == 10:
s.append(0)
... |
class Solution(object):
def minMoves(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
smallest = min(nums)
return sum([n - smallest for n in nums])
|
#
# PySNMP MIB module BAY-STACK-UNICAST-STORM-CONTROL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BAY-STACK-UNICAST-STORM-CONTROL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:36:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Usi... |
# -*- coding: utf-8 -*-
"""
Parent namespace for WePay modules.
Copyright (c) 2015-2016 [WePay](https://wepay.com).
<http://opensource.org/licenses/Apache2.0>
"""
|
########################################
# If statement checking boundary conditions
# Shiva K
########################################
deposit = input("What is the deposit amount?")
if int(deposit) > 100:
print("You get a free toast!")
print("Have a nice day!")
|
__import__('cyborg.objects.driver_objects.driver_device')
__import__('cyborg.objects.driver_objects.driver_attribute')
__import__('cyborg.objects.driver_objects.driver_attach_handle')
__import__('cyborg.objects.driver_objects.driver_deployable')
__import__('cyborg.objects.driver_objects.driver_controlpath_id')
|
"""
Crie um sistema que gerencia o cadastro de alunos e professores em turmas.
Os usuáriosserão os membros da secretaria.
Eles devem conseguir visualizar os alunos matriculados emcada turma, com seus dados, suas notas e presenças.
Além disso, os secretários precisam teracesso a dados cadastrais dos pr... |
class Solution:
def multiply(self, num1: str, num2: str) -> str:
a = int(num1)
b = int(num2)
return str(a * b)
|
height = float(input("enter your height in m: "))
weight = float(input("enter your weight in kg: "))
bmi = round(weight / (height ** 2))
if bmi < 18.5:
message = f'Your BMI is {bmi}, you are underweight.'
elif bmi >= 18.5 and bmi <= 25:
message = f'Your BMI is {bmi}, you have a normal weight.'
elif bmi > 25 a... |
"""
-1.二叉搜索树的后序遍历序列
时间复杂度:O(n)
空间复杂度:O(n)
"""
#-*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def createTreeNode(listNode):
if not listNode:
return None
root = TreeNode(listNode[0])
level = [root]
j = 1
... |
# Preço da passagem
# Escreva um programa que pergunta a distância que um passageiro deseja percorrer em km. Seu programa deve imprimir o preço da passagem, cobrando R$0.50 por km para viagens de até 200km e R$0.45 por quilômetro extra para viagens mais longas. (Adaptado do ex. 4.6 livro Nilo Ney).
# O resultado deve s... |
def f1():
print("Hello")
def f2():
pass
f1()
f2()
for i in range(100):
if i%10==0:
print(i)
else:pass
"""Hello
0
10
20
30
40
50
60
70
80
90""" |
def milliseconds_to_seconds(milliseconds:int) -> int:
return int((milliseconds/1000)%60)
def milliseconds_to_minutes(milliseconds:int) -> int:
return int((milliseconds/(1000*60))%60)
def seconds_to_milliseconds(seconds:float) -> int:
return int(round(seconds,2)*1000)
|
def test_len(sample):
"""The normalized_query_data property should return a list of the same length as raw_query_data"""
assert len(sample.normalized_query_data) == len(sample['raw_query_data'])
def test_none_values(sample):
"""The normalized_query_data property should return a list that does not contain... |
def lookup(data, name, add_field=False):
path = [i.strip() for i in name.split('.')]
found_value = None
# get lookup dictionary/data:
try:
lookup = _ttp_["parser_object"].lookups
for i in path:
lookup = lookup.get(i,{})
except KeyError:
return data, None
# per... |
# Copyright 2016-2022 The FEAGI 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 applic... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021, 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivat... |
"""
Premium Question
https://leetcode.com/problems/closest-binary-search-tree-value-ii/
"""
__author__ = 'Daniel'
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def closestKValues(self, root, target, k):
... |
def echo():
print('MOCKNAME:MOCKREVNO')
def main():
echo()
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
class IPV4:
def __init__(self, ip="127.0.0.1"):
# Ip is to be stored as an array
# Check the data type of the IP input
if type(ip) == str:
self.Current_IP = self.Convert_STA(ip)
elif type(ip) == list:
self.Current_IP = type(ip)
# Verify The IPs validity
if not self.Verify_IP():
rai... |
# DomirScire
a=int(input())
b=int(input())
c=int(input())
print(pow(a,b))
print(pow(a,b,c))
|
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
combinations = []
def dfs(nums, currSum, i):
if currSum == target:
combinations.append(nums)
elif currSum < target:
for j in range(i, len(... |
# --- Deklaration einer Klasse mit Konstruktor und Factory/Class-Method als alternative Instanziierungsmöglichkeit --- #
class Circle:
def __init__(self, radius):
self.radius = radius
# --- Facorymethod, um eine Instanz der 'Cricle' Klasse mittels dem Durchmesse zu erstellen --- #
@classmethod
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.