content stringlengths 7 1.05M |
|---|
"""
This includes constants that may be used in the connectivity_libs module.
"""
WEBTIMEOUT = 5
NUM_OF_WORKER_PROCESSES = 4
REGEX_IP = r'(?P<ip_address>(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))'
REGEX_EMAIL = r'[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a... |
##To find the kth maximum number in an array.
lst=[]
len=int(input("Enter the length of the array.\n"))
for i in range(0,len):
e=input("Enter the element.\n")
lst.append(e)
k=int(input("Enter the value of k\n"))
lst.sort(reverse=True)
f=k-1
print(lst[f])
|
# DFS 深度优先搜索
# DFS 广度优先搜索
def dfs(graph, node, visited=[]):
"""DFS"""
if node not in visited:
visited.append(node)
for n in graph[node]:
dfs(graph, n, visited)
return visited
def bfs(graph, start, path=[]):
"""BFS"""
queue = [start]
while queue:
vertex = q... |
__all__ = ['status_in_range', 'response_time_under',
'response_time_above', 'status_must_be']
def status_must_be(value: int = None, expected: int = 200) -> bool:
"""
Validates the status code of a HTTP call is as expected.
"""
return value == expected
def status_in_range(value: int, lower... |
# Lager en funksjon for å addere to tall.
def adder(tall1, tall2):
sum = tall1 + tall2
print("Summen av",tall1 ,"og", tall2 ,"er lik", sum)
# Kaller funksjonen med tallene som parameterverdi.
adder(10,11)
adder(5,10)
print("-------------------------------- ")
# Lager en funksjon som teller
def tellForekoms... |
"""
1 - Faça um Programa que peça a temperatura em graus Farenheit, transforme
e mostre a temperatura em graus Celsius:
C = (5 * (F-32) / 9).
"""
#leitura do valor em F
f = int(input("Temperatura em Farenheit: "))
#conversão de Farenheit para Celsius
c = (5*((f-32)/9))
#saída
print("{}°F equ... |
# create a list of movies
list_of_movies = None
list_of_movies = [
'Toy Story',
'Lion King',
'Coco'
]
# cycle through each movie title in the list of movies
# starting from the first item and ending at the last item
for movie_title in list_of_movies:
print('***{}***'.format(movie... |
'''
UFCG
PROGRAMAÇÃO 1
JOSE ARTHUR NEVES DE BRITO - 119210204
Letras Alternadas'''
def letras_alternadas(string):
s = ''
for i in range(0,len(string),2):
s += string[i]
return s
assert letras_alternadas("casa") == 'cs'
assert letras_alternadas("exemplo") == "eepo"
|
valor = list()
while True:
num = int(input('Digite um valor:'))
valor.append(num)
resp = str(input('Deseja continuar? [S/N]: ')).upper()
if resp == 'N':
break
print(valor)
print(f'Você digitou {len(valor)} elementos')
#outra forma de deixar de trás para frente
valor.sort(reverse=True)
print(f'... |
'''
Run through and ensure that all the required programs are installed on the system
and functioning
'''
|
def solution(n, computers):
def dfs(n, s, metrix, visited):
stack = [s]
visited.add(s)
while stack:
this = stack[-1]
remove = True
for i in range(n):
if this == i:
continue
if i in visited:
... |
def is_paired(input_string: str) -> bool:
input_string = clean_input_string(input_string)
if len(input_string) % 2 != 0:
return False
while input_string:
if not remove_bracket(input_string[0], input_string):
return False
return True
def remove_bracket(bracket: str, inpu... |
def _(string):
"""Emulates gettext method"""
return string
__version__ = "0.8.2"
__description__ = _("EncFS GUI managing tool")
__generic_name__ = _("EncFS manager")
|
def test_oops(client):
url = f'/fake-path'
response = client.get(url)
assert response.status_code == 404 |
#-*- coding: utf-8 -*-
class ValueDefinition:
str_val_dict = {}
val_str_dict = {}
@classmethod
def get(cls, data):
if not cls.val_str_dict:
cls.val_str_dict = dict(zip(cls.str_val_dict.values(), cls.str_val_dict.keys()))
if type(data) == str:
return cls.str_val_d... |
strip_words = [
'Kind',
'MAE',
'Pandemisch'
]
skip_names = [
'Water'
]
ignore_names = [
'alfalfa',
'ali',
'belladonna',
'cold',
'drank',
'gas',
'hot',
'linn',
'sepia',
'skin',
'slow',
'stol',
'ultra',
'vicks',
'vitamine',
'yasmin'
]
# re... |
class Solution:
def canJump(self, nums) -> bool:
"""
nums: List[int]
Given an array of non-negative integers, you are initially
positioned at the first index of the array.
Each element in the array represents your maximum jump length at that
position.
... |
#!/usr/bin/env python
esInputs = "/home/matthieu/.emulationstation/es_input.cfg"
esSettings = '/home/matthieu/.emulationstation/es_settings.cfg'
recalboxConf = "/home/matthieu/recalbox/recalbox.conf"
retroarchRoot = "/home/matthieu/recalbox/configs/retroarch"
retroarchCustom = retroarchRoot + '/retroarchcustom.cfg'
r... |
# 欧几里得求最大公约数
def gcd(num1, num2):
if (num1 < num2):
num1, num2 = num2, num1
while num2 != 0:
num1, num2 = num2, num1 % num2
return num1
if __name__ == '__main__':
print(gcd(8, 24))
|
def set_timer():
# WIP
pass
|
def check_inputs(number_of_models, model_1_inputs, model_2_inputs=None):
"""Checks that the user inputs make logical sense
e.g. have they specified the number of models to be 2
but only given data for one model."""
# check model comparison information
# check model 2 is added if number of models ... |
class Stack:
def __init__(self):
self.data = []
def push(self, value):
self.data.append(value)
def pop(self):
return self.data.pop()
def peek(self):
if len(self.data) > 0:
return self.data[-1:][0]
else:
return None
def size(self):
... |
class Ingredient():
def __init__(self, amount, unit, name):
self.amount = self.convert_to_decimal(amount)
self.unit = unit
self.name = name
def convert_to_decimal(self, amount):
try:
return float(amount)
except ValueError:
num, denom = amount.split('/')
return float(num) ... |
""" This is an AWS Lambda function to demonstrate the import of Lambda Layers
"""
# from lambdalayer import lambdalayer
def main(event, context):
"""Handler method for the AWS Lambda Function."""
print(f"*** Lambda 2: Execution of AWS Lambda function starts. ***")
print(f"*** Lambda 2: Trying to invoke ... |
"""Helper module to define static html outputs"""
__all__ = [
'add_header',
'row',
'rows',
'fig',
'card',
'card_deck',
'card_rows',
'title',
'div',
'table_from_df',
'hide',
'tabs',
'input'
]
def add_header(html:str, title="explainerdashboard")->str:
"""Turns a ... |
# Return the Nth Even Number
# nthEven(1) //=> 0, the first even number is 0
# nthEven(3) //=> 4, the 3rd even number is 4 (0, 2, 4)
# nthEven(100) //=> 198
# nthEven(1298734) //=> 2597466
# The input will not be 0.
def nth_even(n):
return 2 * (n - 1)
def test_nth_even():
assert nth_even(1) == 0
assert ... |
# https://www.codechef.com/problems/GOODBAD
for T in range(int(input())):
l,k=map(int,input().split())
s,c,b=input(),0,0
for i in s:
if(i>='A' and i<='Z'): c+=1
if(i>='a' and i<='z'): b+=1
if(c<=k and b<=k): print("both")
elif(c<=k): print("chef")
elif(b<=k): print("brother")
... |
x = """
.loader {
position: absolute;
top: 50%;
left: 50%;
margin-left: -HALFWIDTHpx;
margin-top: -HALFWIDTHpx;
width: 0;
height: 0;
visibility: initial;
transition: all .3s ease;
color: #fff;
font-family: Helvetica, Arial, sans-serif;
font-size: 2rem;
background-color: white;
border-radius:... |
# class Tree:
# def __init__(self, val, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
treeSum = 0
def solve(self, root):
def preOrder(root):
if root:
self.treeSum += root.val
preO... |
# 2.3.4 Iterators
class SequenceIterator:
"""An iterator for any of Python's sequence types."""
def __init__(self,sequence):
"""Create an iterator for the given sequence."""
self._seq = sequence # keep a reference to the underlying data
self._k = -1 # will increment to 0 ... |
def mdcN(*x):
'''Função codificada em Python que devolve o MDC de 'n' números passados
usando a fórmula: MDCn = MDC[MDC(n-1), xn] '''
#recebendo os dois primeiros numeos passados
x1 = x[0]
x2 = x[1]
#verificando qual dos dois é maior
if x1>x2:
maior = x1
menor = x2
else:
... |
class Service:
def __init__(self, name, connector_func, state_processor_method=None,
batch_size=1, tags=None, names_previous_services=None,
names_required_previous_services=None,
workflow_formatter=None, dialog_formatter=None, response_formatter=None,
... |
text = input()
command = input()
while command != 'Decode':
current_command = command.split('|')
action = current_command[0]
if action == 'Move':
num_of_letters = int(current_command[1])
substring = text[:num_of_letters]
text = text[num_of_letters:] + substring
elif action ==... |
"""
Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not
unary) +, -, or * between the digits so they evaluate to the target value.
Examples:
"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "... |
# To implement a stack using a list
# Made by Nouman
stack=[]
def push(x):
stack.append(x)
print("Stack: ", stack)
print(x," pushed into stack")
def pop():
x=stack.pop()
print("\nPopped: ",x)
print("Stack :",stack)
size=int(input("Enter size of stack: "))
print("\nEnter elements into stack: ")
for i in range... |
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
words = s.split(' ')
if len(pattern) != len(words): return False
w_to_p = {}
p_to_w = {}
for i, w in enumerate(words):
if pattern[i] not in p_to_w: p_to_w[pattern[i]] = w
if w not in ... |
class Solution:
@staticmethod
def naive(nums,target):
left,right = 0,len(nums)-1
while right>left+1:
mid = (left+right)//2
if nums[mid]>target:
right = mid
elif nums[mid]<target:
left = mid
else:
retu... |
"""Define mapping of litex components to generated zephyr output"""
class Mapping:
"""Mapping from litex component to generated zephyr output
:param name: Name of the mapping, only used during debugging
:type name: str
"""
def __init__(self, name):
self.name = name
|
#
# PySNMP MIB module CISCO-WAN-MG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-WAN-MG-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:02:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
#!/usr/local/bin/python3.3
def echo(message):
print(message)
return
echo('Direct Call')
x = echo
x('Indirect Call')
def indirect(func, arg):
func(arg)
indirect(echo, "Argument Call")
schedule = [(echo, 'Spam'), (echo, 'Ham')]
for (func, arg) in schedule:
func(arg)
def make(label):
def echo(me... |
class SqlQueries:
address_table_insert = ("""
SELECT DISTINCT address1 AS address1
, address2 AS address2
, address3 AS address3
, city AS city
, zip_code AS zip_code
, country AS country
, state AS state
FROM staging_restaurants
WHERE address... |
""" There is an array with some numbers. All numbers are equal except for one. Try to find it!
It’s guaranteed that array contains at least 3 numbers.
The tests contain some very huge arrays, so think about performance. """
def find_uniq(arr):
arr.sort()
if arr[0] == arr[1]:
return arr[-1]
el... |
peso = float(input('Digite seu peso atual: '))
altura = float(input('Digite sua altura: '))
imc = peso/altura**2
if imc < 18.5:
print('Seu imc é de {:.1f}. \nVocê está abaixo do peso ideal'.format(imc))
elif imc < 25:
print('Seu imc é de {:.1f}.\n\033[1;34mParabéns!! Você está no peso Ideal\033[m'.format(imc))
... |
"""
Unittests
=========
Tests are built for usage with **py.test**.
In data fixtures, not all settings and Sass sources will compile with
libsass. Some of them contains some errors for test needs.
* ``boussole.txt``: Is not an usable settings file, just a dummy file for base
backend tests;
* ``boussole.json``: Is ... |
class SketchGalleryOptions(Enum, IComparable, IFormattable, IConvertible):
"""
Enumerates all the sketch options.
enum SketchGalleryOptions,values: SGO_Arc3Point (6),SGO_ArcCenterEnds (7),SGO_ArcFillet (9),SGO_ArcTanEnd (8),SGO_Circle (5),SGO_CircumscribedPolygon (4),SGO_Default (0),SGO_FullEllipse (12)... |
def generateHTML(colors):
print(colors)
node1 = f"""id: '1',
label: 'Theme 1',
x: 7,
y: 1,
size: 1,
color: '{colors[0]}'"""
node2 = f"""id: '2',
label: 'Theme 2',
x: 12,
y: 1,
size: 1,
color: '{colors[1]}'"""
node3 = f"""i... |
def for_S():
""" Upper case Alphabet letter 'S' pattern using Python for loop"""
for row in range(7):
for col in range(5):
if row%3==0 and col>0 and col<4 or col==0 and row%3!=0 and row<3 or col==4 and row%3!=0 and row>3:
pri... |
CSRF_ENABLED = True
#SECRET_KEY设置当CSRF启用时有效,这将生成一个加密的token供表单验证使用,你要确保这个KEY足够复杂不会被简单推测。
SECRET_KEY = 'watson-customer-management'
#for local test
#UPLOAD_FOLDER = '/Users/wzy/Documents/PycharmProjects/WatsonRobot/app/static/resource'
#for bluemix
UPLOAD_FOLDER = '/home/vcap/app/app/static/resource'
MAX_CONTENT_LENGTH =... |
# DROP TABLES
arrivals_drop = "DROP TABLE IF EXISTS arrivals;"
airports_drop = "DROP TABLE IF EXISTS airports;"
countries_drop = "DROP TABLE IF EXISTS countries;"
temp_drop = "DROP TABLE IF EXISTS temp;"
# CREATE TABLES
arrivals_create = ("""CREATE TABLE IF NOT EXISTS arrivals (
arrival_id serial PRIMARY KEY,
country_... |
#普通索引
a=dict(name="CY",num=42)
print(a["name"])
#给字典中的key赋值
a["name"]="Challenger"
print(a)
#del 删除key
del a["name"]
print(a)
#使用in来检测字典中key是否存在
print("num" in a)
#与列表的不同之处
# 键类型:字典的键类型不一定为整形数据,键可以是任意不可变类型,比如浮点类型(实型)、字符串或者元租
# 自动添加:即使键起初在字典中并不存在,也可以为它赋值,字典就会建立新的项。而(在不使用append方法或者其他类似操作的情况下)不能将值关联到列表范围之外的索引上
# 表达式 ... |
command = input()
numbers = [int(x) for x in input().split()]
parity = 0 if command == 'Even' else 1
result = sum(filter(lambda x: x % 2 == parity, numbers))
print(result * len(numbers))
|
class ListNode:
def __init__(self, data, link=None):
self.data = data
self.link = link
|
temperature =int(input("Enter Temperature: "))
if temperature > 30:
print("It's a hot day")
elif temperature < 10:
print("It's a cold day")
else:
print("it's neither hot nor cold")
|
TRACKS = 'tracks'
STUDIES = 'studies'
EXPERIMENTS = 'experiments'
SAMPLES = 'samples'
SCHEMA_URL_PART1 = 'https://raw.githubusercontent.com/fairtracks/fairtracks_standard/'
SCHEMA_URL_PART2 = '/current/json/schema/fairtracks.schema.json'
TOP_SCHEMA_FN = 'fairtracks.schema.json'
TERM_ID = 'term_id'
ONTOLOGY = 'ontolo... |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 9 13:17:12 2020
@author: Administrator
"""
"""
给定以非递减顺序排序的三个数组,找出这三个数组中的所有公共元素.例如,给出下面三个数组:
ar1 = [2,5,12,20,45,85] , ar2 = [16,19,20,85,200] , ar3 = [3,4,15,20,39,72,85,190].
那么,这三个数组的公共元素为[20,85].
"""
def GetMin(arr1 , arr2 , arr3 , m , n , l):
if m... |
class Constant():
def __init__(self, value):
self._value = value
def __call__(self):
return self._value
y = Constant(5)
print((y()))
|
print(2, type(2))
print(3.5, type(3.5))
print([], type([]))
print(True, type(True))
print(None, type(None))
# code to put in a for-each loop for the Pattern Loop Exercise
|
def create_dimension_competitors(cursor):
cursor.execute('''CREATE TABLE dimension_competitors
( company_name text,
company_permalink text,
competitor_name text,
competitor_permalink text,
extracted_at text
)''') |
name_1 = input()
name_2 = input()
delimiter = input()
print(f"{name_1}{delimiter}{name_2}") |
def f(x):
for i in reversed([20, 19, 18, 17, 16, 15, 14, 13, 12, 11]):
if x % i != 0:
return False
return True
i = 20
while f(i) == False:
i += 20
print(i)
|
a=int(input("Enter any number "))
for x in range(1,a+1):
print(x)
|
class String:
"""Javascript methods for strings."""
def char_at(string, index):
"""Returns the character at a specified index in a string."""
return string[index]
def trim(string):
"""Removes whitespace from both sides of a string."""
return string.strip()
def... |
#Desafio: Melhore o desafio 61, perguntando para o usuário se ele quer mostrar mais alguns termos.
# O programa encerra quando ele diser que quer mostrar 0 termos.
prim_termo = int(input('Digite o 1º termo: '))
razao = int(input('Qual a razão dessa PA? '))
cont = 1
res = prim_termo
max = 10
print('Os 10 primeiros ter... |
def pre_order(root):
ret = []
stack, node = [], root
while stack or node:
if node:
ret.append(node.val)
stack.append(node)
node = node.left
else:
node = stack.pop()
node = node.right
return ret
def in_order(root):
ret = []... |
# Keep a dictionary that has items ordered in a deque structure
class DequeDict:
# Entry that holds the key, value
class DequeEntry:
def __init__(self, key, value):
self.key = key
self.value = value
self.prev = None
self.next = None
# Helpful for ... |
"""Escreva a função maior_primo que recebe um número inteiro maior ou igual a 2 como parâmetro
e devolve o maior número primo menor ou igual ao número passado à função"""
def eprimo (numero):
verificagem = divisor = 0
primo = False
while divisor <= numero:
divisor += 1
if numero % divi... |
#
# Copyright (C) 2000-2005 by Yasushi Saito (yasushi.saito@gmail.com)
#
# Jockey is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# Jockey is distr... |
# PyPy でのみ AC
T = input()
D = int(input())
m = 1000000007
def update(t, nt, v):
for i in range(10):
ni = i + v
if ni > 9:
ni -= 9
nt[ni] += t[i]
nt[ni] %= m
t = [0] * 10
t[0] = 1
for c in T:
nt = [0] * 10
if c != '?':
update(t, nt, int(c))
else:
... |
class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
if not points or len(points) == 1:
return 0
time = 0
for index,cur_point in enumerate(points):
if index == len(points) - 1:
return time
next_point = points[i... |
class Body:
def __init__(self, snake):
self.pos = snake.bodys[-1].lst_pos
if snake.bodys[-1].pos - snake.bodys[-1].lst_pos == 1:
self.lst_pos = self.pos -1
if snake.bodys[-1].pos - snake.bodys[-1].lst_pos == -1:
self.lst_pos = self.pos +1
i... |
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
top = left = 0
right = bottom = len(matrix) - 1
while top < bottom:
for i in range(bottom - top):
temp = mat... |
someone = input("Enter a famous name: ").strip().title()
place = input("Enter a place: ").strip().lower()
weekday = ""
while weekday not in ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]:
weekday = input("Enter a weekday: ").strip().lower()
adjective = input("Enter an adjective: ")... |
# Question: https://projecteuler.net/problem=73
# F(n) -> length of Farey Sequence (https://mathworld.wolfram.com/FareySequence.html)
N = 12000
# https://en.wikipedia.org/wiki/Farey_sequence#Next_term
# From 0/1 to end_n/end_d
def farey_sequence_length(end_n, end_d, n):
a, b, c, d = 0, 1, 1, n
ans = 1
w... |
#
# PySNMP MIB module RDN-CMTS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RDN-CMTS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:46:17 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,... |
# Nokia messages
nokia_update = [
(
"openconfig-interfaces:interfaces/interface[name=1/1/c1/2]",
{
"config": {
"name": "1/1/c1/2",
"enabled": True,
"type": "ethernetCsmacd",
"description": "Test Interface @ pygnmi"
... |
class _Snake:
def __init__(self, color):
self.head = ()
self.body = []
self.color = color
self.last_op = 'w'
self.score = 0
self.operation = {
'w': lambda x, y: (x - 1, y),
'a': lambda x, y: (x, y - 1),
's': lambda x, y: (x + 1, y)... |
c = 1
while True:
n = int(input())
if n == -1: break
print('Experiment {}: {} full cycle(s)'.format(c, n // 2))
c += 1
|
# Write a function that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
# SIMPLER APPROACH: 1 is the min answer we return. Iterate through the list and if we we see the val of min then increment min.
# O(n)t | O(1)s
def smallestPositiveInteger(A):
... |
# 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 countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is N... |
for i in range(0,10):
for j in range(10, -1, -1): # we count backwards to -1 so we include 0
if(i == j):
print("i == j, so we break")
break
else:
print("i = %d, j= %d" % (i, j))
|
temp = 0
respuesta = ''
def escribirArchivo(var):
archivo = open('temp.dat', 'a')
archivo.write(var+"\n")
def cerrarArchivo():
archivo = open('temp.dat', 'a')
archivo.close()
b = True
try:
while b == True:
temp = input(" Ingresa tu temperatura: ")
if(float(temp) > 37.5):
... |
name = "TensorFlow"
description = None
args_and_kwargs = (
(("--run-eagerly",), {
"help":"Running tensorflow in eager mode may be required for high memory models.",
"action":'store_true',
"default":False,
}),
(("--disable-gpu",), {
"help":"Disable GPU for high memory mode... |
#encoding:utf-8
subreddit = 'behindthegifs'
t_channel = '@r_behindthegifs'
def send_post(submission, r2t):
return r2t.send_simple(submission,
min_upvotes_limit=100,
text=False,
gif=False,
img=False,
album=True,
other=False
) |
class DPDSettingsObject(object):
DPD_API_USERNAME = None
DPD_API_PASSWORD = None
DPD_API_FID = None
DPD_API_SANDBOX_USERNAME = None
DPD_API_SANDBOX_PASSWORD = None
DPD_API_SANDBOX_FID = None
|
# -*- coding:utf-8 -*-
# author: hpf
# create time: 2020/12/15 11:07
# file: 116_填充每个节点的下一个右侧节点指针.py
# IDE: PyCharm
# 题目描述:
'''
给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有... |
class recipe_defs:
def __init__(self):
self.tags = ["Vegetarian",
"Vegan",
"Burger",
"Baby",
"High protein",
"Gluten free",
"Meat",
"Fish",
"Cold",
... |
# scored.py
# Repeatedly read test scores (from 0 to 100), until the user
# enter -1 to finish. The input part of the program will ensure
# that the numbers are in the correct range.
# For each score, report the corresponding grade:
# 90-100 = A, 80-89 = B, 70-79 = C, 60-69 = D, < 60 = F
# When you have all the scores,... |
def is_possible(m, n, times):
re = 0
for t in times:
re += m // t
if re >= n:
return True
return False
def solution(n, times):
answer = 0
times.sort()
l=0; r=1_000_000_000_000_000; m=0
while l <= r:
m = (l+r)//2
if is_possible(m, n, times):
... |
# -*-coding:utf-8 -*-
#Reference:**********************************************
# @Time : 2019-11-11 00:10
# @Author : Fabrice LI
# @File : 20191111_52_next_permutation.py
# @User : liyihao
# @Software : PyCharm
# @Description: Implement next permutation, which rearranges numbers into the lexicographicall... |
#aluguel do carro sendo 60 reais o dia e 0.15 o km rodado
print('calcule quanto fica o aluguel do carro')
dias = int(input('digite o numero de dias usado: '))
km = float(input('digite quantos km voçê rodou: '))
a = (dias*60)+(km*0.15)
print ('o valor do seu aluguel é de R${:.2f}'.format(a)) |
list1=[1,2,6,12]
iteration=0
print ("iteration", iteration, list1)
for i in range(len(list1)):
for j in range(len(list1)-1-i):
iteration=iteration+1
if list1[j]> list1[j+1]:
temp=list1[j]
list1[j] = list1[j+1]
list1[j+1]=temp # Swap!
print ("iteration", ... |
class TrackGroupStyle:
def __init__(self, distance=5, internal_offset=2, x_multiplier=1.05, show_label=True,
label_fontsize=16, label_fontweight="normal",
label_fontstyle='normal',
label_hor_aln='right', label_vert_aln='center',
label_y_shift=0,... |
def new_if(predicate, then, otherwise):
if predicate:
then
else:
otherwise
def p(x):
new_if(x > 5, print(x), p(x+1))
p(1) # what happens here? |
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
#################
# List indexing #
#################
# Classical position indexing
i = 0
while i < len(a):
print(a[i])
i += 1
# Negative indices
print(a[-1])
print(a[-2])
print(a[-3])
################
# List slicing #
################
# Elements between indices 3 and 7
p... |
'''
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
The solution set must not contain duplicate quadruplets.
Example:
Given array nums = [1, 0, -1, 0, -2... |
"""
@Author :Furqan Khan
@Email :furqankhan08@gmail.com
@Date :1/3/2017
Objective :
The purpose of this file /module /Class is to map to serve teh Rest request
Depending upon the requested url the views module will fetch the data from the backend
python files and would transform the data to json format ,and would... |
#SPDX-License-Identifier: MIT
"""
Metrics that provide data about platform & their associated activity
"""
|
#
# PySNMP MIB module Juniper-HTTP-Profile-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-HTTP-Profile-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:02:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... |
# create_trusted_globals_dict takes in a module name [module_name], a trusted values dictionary [trusted_values_dict],
# and a boolean [first_time].
# Called by run_test
def create_trusted_globals_dict(self):
# If module is being run for the first time, a trusted_values_dict entry doesn't exist; return an empt... |
class Truckloads:
def numTrucks(self, numCrates, loadSize):
if numCrates <= loadSize:
return 1
return self.numTrucks(numCrates/2, loadSize) + self.numTrucks((numCrates+1)/2, loadSize)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.