content stringlengths 7 1.05M |
|---|
n, l, r = map(int, input().split())
box = []
for i in range(n):
box += [list(map(int, input().split()))]
total = 0
for i in range(n):
firstX = box[i][0] + box[i][1]
lastX = box[i][2] + box[i][3]
fx, lx = max(firstX, l), min(lastX, r)
uly = min(lx - box[i][2], box[i][3])
dly = max(box[i][3]+(lx... |
# Questão 8. Elabore um programa que utilize uma função que informe a
# quantidade de dígitos de um determinado número inteiro informado.
def quantidadeDigito(numero):
print(len(str(numero)))
num = int(input('Digite um número: '))
quantidadeDigito(num) |
#
D = {4:5, "apple":6, (4,3):"test"}
print(D)
print('\n')
for key in D:
print(key,D[key])
print('\n')
for item in D.items():
print(item)
print('\n')
for key,value in D.items():
print(key,value)
print('\n')
for value in D.values():
print(value)
print('\n')
L = [4 , 5, 7]
for ind,item in enumerat... |
# From : https://en.wikipedia.org/wiki/Computation_of_cyclic_redundancy_checks
# Most significant bit first (big-endian)
# x^16+x^12+x^5+1 = (1) 0001 0000 0010 0001 = 0x1021
def crc16(data):
rem = 0
n = 16
# A popular variant complements rem here
for d in data:
rem = rem ^ (d << (n-8)) # n... |
flash_size_table = {}
flash_size_table['4'] = 16
flash_size_table['6'] = 32
flash_size_table['8'] = 64
flash_size_table['B'] = 128
flash_size_table['C'] = 256
flash_size_table['D'] = 384
flash_size_table['E'] = 512
flash_size_table['F'] = 768
flash_size_table['G'] = 1024
flash_size_table['I'] = 2048
flash_si... |
def test():
assert (
"import Doc, Span" in __solution__ or "import Span, Doc" in __solution__
), "Did you import the Doc and Span correctly?"
assert doc.text == "I like David Bowie", "Did you create the Doc correctly?"
assert span.text == "David Bowie", "Did you create the span correctly?"
a... |
# mensagens que aparecem no "sistema"
# instructions
INPUT_INST = "Enter info:"
VAL1 = "FIRST VALUE"
VAL2 = "SECOND VALUE"
VAL3 = "THIRD VALUE"
op1 = "1 TO TEST A SAMPLE"
op2 = "2 TO END CONECTION"
# success
CONNECTED = "CONNECTED TO... |
pos=-1
def binarysearch(lst,num):
'''Function that returns True and index number of element if found else returns False and -1'''
lst.sort()#any sort algorithm can be used
print(lst)
l=0
u=len(lst)-1
while l<= u:
mid=(u+l)//2
if lst[mid] == num:
global pos
pos=mid
return True,pos
else:
... |
'''
函数的参数
- 位置参数
- 可变参数
- 关键字参数
- 命名关键字参数
'''
#参数默认值
def f1(a, b=5, c=10):
return a + b * 2 + c * 3
print(f1(1, 2, 3))
print(f1(100, 200))
print(f1(100))
print(f1(c=2, b=2, a=1))
#可变参数
def f2(*args):
sum = 0
for num in args:
sum += num
return sum
print(f2(1, 2, 3))
print(f2(1, 2, 3, 4, 5))
p... |
suffix = ['', 'K', 'M', 'B', 'T', 'P']
def human_format(num):
num = float('{:.3g}'.format(num))
magnitude = 0
while abs(num) >= 1000:
magnitude += 1
num /= 1000.0
return '{}{}'.format('{:f}'.format(num).rstrip('0').rstrip('.'), suffix[magnitude])
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@Filename :prime_origin.py
@Author :Arthur Zhan
@Init Time :2020/06/16
"""
def primes_1(num):
i = 2
lst = []
while len(lst) < num:
if 2 > i // 2 + 1:
limit = i
else:
limit = i // 2 + 1
for d in... |
#
# PySNMP MIB module NNCEXTSPVC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NNCEXTSPVC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:22:57 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... |
#!/usr/bin/python3
# -*- coding : UTF-8 -*-
"""
Name : Pyrix/Exceptions\n
Author : Abhi-1U <https://github.com/Abhi-1U>\n
Description : Exceptions are implemented here \n
Encoding : UTF-8\n
Version :0.7.19\n
Build :0.7.19/21-12-2020
"""
class ExceptionTemplate(Exception):
def __call__(se... |
# Client Messages
disconnectServer = "[x] Server disconnected."
keysUnpacked = "[+] Symmetric keys unpacked."
keysUnpackFail = "[x] Keys not unpacked. Try again."
welcome = "@Yo: You're in. Welcome to the underground."
# Default Commands
bootNoUser = "[!] Which user do you want to boot? Eg: /boot <user>"
bootUserNotFo... |
"""Aggregator functions are monkey patched into the DarshanReport object during
initialization of DarshanReport class.
.. note::
These functions are only enabled if the `darshan.enable_experimental(True)` function is called.
Example usage::
import darshan
import darshan.report
dasrhan.enable_experimental(Tr... |
class Solution:
"""
@param grid: Given a 2D grid, each cell is either 'W', 'E' or '0'
@return: an integer, the maximum enemies you can kill using one bomb
"""
def maxKilledEnemies(self, grid):
if grid == []:
return 0
n_row, n_col = len(grid), len(grid[0])
... |
# name: csc_devices.py
# desc: lists all devices with devicename, IP, username, password, secret
router_013 = {'device_name': 'router_013', 'device_type': 'cisco_nxos', 'ip': '1.1.1.10', 'username': 'dummy_username', 'password': 'dummy_password', 'port': 22, 'verbose': False, 'secret': 'dummy_secret', }
router_023... |
# class Persona:
# #def __init__(self):
# def __init__(self,nombre,apellido,edad):
# self.nombre = nombre
# self.apellido = apellido
# self.edad = edad
# persona1 = Persona('Juan','Castellanos',21)
# print(f'Objeto Persona 1: {persona1.nombre} {persona1.apellido} {persona1.edad}')
# #M... |
#
# PySNMP MIB module XEDIA-DRIVER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/XEDIA-DRIVER-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:42:41 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
DEFAULT_FILENAME = "output_test_file.txt"
DEFAULT_CONTENT = [
"Obi-Wan Kenobi: Hello there.",
"General Grievous: General Kenobi. You are a bold one."
]
def main():
filename = DEFAULT_FILENAME
content = DEFAULT_CONTENT;
with open(filename, "w") as text_file:
for line in content:
... |
def set_mode(mode_enum):
"""设置整机的3种运动模式"""
pass
def get_battery_percentage() -> int:
"""整机剩余电量,返回0-100的整数"""
pass
|
#
# @lc app=leetcode.cn id=303 lang=python3
#
# [303] 区域和检索 - 数组不可变
#
# https://leetcode-cn.com/problems/range-sum-query-immutable/description/
#
# algorithms
# Easy (71.37%)
# Likes: 328
# Dislikes: 0
# Total Accepted: 114.2K
# Total Submissions: 159.8K
# Testcase Example: '["NumArray","sumRange","sumRange","su... |
#
# PySNMP MIB module XYLAN-ATM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/XYLAN-ATM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:44:48 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... |
n1 = int(input('Um valor: '))
n2 = int(input('Outro valor: '))
s = n1 + n2
m = n1 * n2
d = n1 / n2
di = n1 // n2
e = n1 ** n2
print('A soma é {}, \nO produto é {}\nA dividão é {:.3f}'.format(s, m, d), end='')
print('A divisão inteira {}\nA potência {}'.format(di, e))
|
numero = int(input('Digite um numero:'))
tot = 0
for c in range(1,numero+1):
if numero % c == 0:
print('\033[33m', end=' ')
tot = tot + 1
else:
print('\033[35m',end=' ')
print('{}'.format(c), end='')
print('\n\033[mO numero {} foi divisivel {} vezes'.format(numero,tot))
if ... |
"""
LeetCode Problem 240. Search a 2D Matrix II
Link: https://leetcode.com/problems/search-a-2d-matrix-ii/
Written by: Mostofa Adib Shakib
Language: Python
Search space reduction Algorithm:
First, we initialize a (row, col)(row,col) pointer to the bottom-left of the matrix.
Then, until we find target and return true... |
# -*- coding: utf-8 -*-
# Scrapy settings for encyclopediaCrawler project
# scrapy basic settings
BOT_NAME = 'encyclopediaCrawler'
SPIDER_MODULES = ['encyclopediaCrawler.spiders']
NEWSPIDER_MODULE = 'encyclopediaCrawler.spiders'
# downloader settings
ROBOTSTXT_OBEY = False
COOKIES_ENABLED = False
RETRY_ENABLED = True... |
def count_down(num):
if num == 0:
return 0
else:
print(num)
num = num -1
return count_down(num)
print(count_down(10)) |
"""User account app"""
# pylint: disable=invalid-name
default_app_config = 'open_connect.accounts.apps.AccountsConfig'
|
#! /usr/bin/env python3
# author: Mark W. Naylor
# file: message.py
# date: 2018-Jan-28
def message(msg, name):
output = "{0}, {1}.".format(msg, name)
print(output)
def hello(name="world"):
message("Hello", name)
def goodbye(name="world"):
message("Goodbye", name)
def main():
#hello()
hell... |
"""
Pobierz od uzytkownika trzy dlugosci bokow i sprawdz, czy mozna z nich zbudowac trojkat.
"""
if __name__ == "__main__":
a = int(input())
b = int(input())
c = int(input())
if a + b > c and b + c > a and a + c > b:
print("z podanych bokow mozna zbudowac trojkat")
else:
print("z... |
__all__ = ("QuietExit", "EmbedExit")
class QuietExit(Exception):
"""
An exception that is silently ignored by its error handler added
in :ref:`cogs_error_handlers`.
The primary purpose of this class is to allow a command to be exited
from within a nested call without having to propagate return va... |
# -*- coding: utf-8 -*-
def comp_angle_opening(self):
"""Compute the average opening angle of the Slot
Parameters
----------
self : SlotMPolar
A SlotMPolar object
Returns
-------
alpha: float
Average opening angle of the slot [rad]
"""
Nmag = len(self.magnet)
... |
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/81079495
# IDEA : LINEAR SCAN
class Solution(object):
def binaryGap(self, N):
"""
:type N: int
:rtype: int
"""
binary = bin(N)[2:]
dists = [0] * len(binary)
left = 0
for i, b in enumer... |
def decimal2binario(d):
if d == 0:
return d
b = bin(d).lstrip("0b")
return b
|
TAS_TO_PORTAL_MAP = {'description': 'description',
'piId': 'pi_id',
'title': 'title',
'chargeCode': 'charge_code',
'typeId': 'type_id',
'fieldId': 'field_id',
'type': 'type_name',
... |
# Copyright (c) 2019 PaddlePaddle 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 appli... |
# Faça um Programa que peça o raio de um círculo, calcule e mostre sua área.
raio = float(input("Digite o raio do circulo: "))
area = 3.14 * raio
print("A área do circlo é de: ", area)
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# Solution A
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
dummy = ListNode(0)
dummy.next = head
cur = hea... |
# Feature objects: these are mapped to feature identifiers within the rich text
# feature registry (wagtail.core.rich_text.features). Each one implements
# a `construct_options` method which modifies an options dict as appropriate to
# enable that feature.
class BooleanFeature:
"""
A feature which is enabled ... |
#Listas parte 2
teste = list ()
teste.append('Gustavo')
teste.append(40)
print(teste)
galera = list()
galera.append(teste[:])
teste[0]='Maria'
teste[1]=22
galera.append(teste[:])
print(galera)
galeras = [['João', 19], ['Ana', 33], ['Joaquim', 13], ['Maria', 45]]
print(galeras)
print(galeras[0])
print(galeras[0][0])
p... |
# input
input_word = input("Enter a word: ")
vowels = ["a", "e", "i", "o", "u"]
num_vowels = 0
# response
for letter in input_word:
if letter in vowels:
num_vowels += 1
print(num_vowels)
|
# Exibe o o dobro, o triplo e a raiz quadrada de um número que o usuário dá entrada.
n = int(input('Digite um número: '))
x2 = n * 2
x3 = n * 3
rq = n ** (1/2) #Raiz quadrada do número n. n elevado a 1/2.
#rq = pow(n,(1/2)) #Raiz quadrada também, usanod a função pow(). Exponenciação.
print('O número é: {} e seu dobro é... |
"""Docstring for validate_input.py."""
class CheckUserInput(object):
"""docstring for CheckUserInput."""
def check_if_input_is_string(self, user_input):
"""Docstring for validating if input is str."""
if type(user_input) is not str:
return False
elif bool(user_input.strip(... |
class State:
def __init__(self, isInit = False, isFinish = False):
self._isInit = isInit
self._isFinish = isFinish
def setInit(self, nval):
self._isInit = nval
def isInit(self):
return self._isInit
def setFinish(self, nval):
self._isFinish = nval
d... |
class Trapeziums(object):
def __init__(self, left, left_top, right_top, right):
self.left = left
self.right = right
self.left_top = left_top
self.right_top = right_top
def membership_value(self, input_value):
if (input_value >= self.left_top) and (input_value <= self.rig... |
numlist=list()
while True:
x=input("Enter a no.")
if x=="done": break
x=float(x)
numlist.append(x)
print(sum(numlist)/len(numlist))
|
def TowerOfHanoi(n , first, last, mid):
if n == 1:
print ("Move disk 1 from rod",first,"to rod",last)
return
TowerOfHanoi(n-1, first, mid, last)
print ("Move disk",n,"from rod",first,"to rod",last )
TowerOfHanoi(n-1, mid, last, first)
n=int(input())
TowerOfHanoi(n, 'F', 'M', 'L') ... |
"""定义函数,根据小时、分钟、秒,计算总秒数
调用:提供小时、分钟、秒
调用:提供分钟、秒
调用:提供小时、秒
调用:提供分钟
"""
def calculate_cent(n1=0, n2=0, n3=0):
"""
一给我里giaogiao !
:param n1: 小时
:param n2: 分钟
:param n3: 秒
:return: 总秒数
"""
return n1 * 3600 + n2 * 60 + n3
print(calculate_cent(n2=3))
|
def crit_dim_var(var):
"""Check if nested dict or not
Arguments
---------
var : dict
Dictionary to test wheter single or multidimensional parameter
Returns
-------
single_dimension : bool
True: Single dimension, False: Multidimensional parameter
"""
single_dimension... |
db._DBProxy__ctxid = 'b85246688f24c14712e0a7dfb93413f5defd50c4'
db.getrecord(0)
db.checkcontext()
dbtree.get_children()
dbtree.get_children([1]) |
quantidade_habilidades, quantidade_texto = [int(n) for n in input().split()]
dicionario = dict()
for c in range(quantidade_habilidades):
habilidade_descricao = input().split()
dicionario[habilidade_descricao[0]] = float(habilidade_descricao[1])
for c in range(quantidade_texto):
salario = 0
while True... |
#
# PySNMP MIB module TUBS-IBR-XEN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TUBS-IBR-XEN-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:27:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
'''7. A Organização Mundial de Saúde usa a seguinte tabela para determinar a condição de um adulto,
para isso desenvolva um algoritmo para calcular o Índice de Massa Corporal (IMC) e apresenta-lo,
dado pela fórmula:
IMC = peso / (altura)2 (o número 2 significa, elevado ao quadrado)
CONDIÇÃO IMC em adultos
Abaixo do ... |
class BridgeWorker():
def __init__(self, thread_name, connection_string, process, action_queue):
self.thread_name = thread_name
self.connection_string = connection_string
self.process = process
self.action_queue = action_queue
self.should_shutdown = False
... |
# -*- Mode:python; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
#
# Copyright (C) 2014-2017 Regents of the University of California.
# Author: Jeff Thompson <jefft0@remap.ucla.edu>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License a... |
# The isBadVersion API is already defined for you.
# @param version, an integer
# @return a bool
# def isBadVersion(version):
class Solution:
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
i, j = 1, n
while i < j:
m = (i + j) // 2
... |
class Solution:
def spiralMatrixIII(self, R: int, C: int, r0: int, c0: int) -> 'List[List[int]]':
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
uncolored = R * C
result = []
x, y = r0, c0
turns = 0
while uncolored > 0:
dx, dy = directions... |
n,k=map(int,input().split())
x=[*map(int,input().split())]
forbidden=[False]*10
for i in range(0,10):
if i not in x:
forbidden[i]=True
ans=-1
for i in range(1,n+1):
fail=False
t=i
while i:
if forbidden[i%10]:
fail=True
break
i//=10
if not fail: ans=t
... |
class PaymentLink:
def __init__(
self,
url,
id
):
self.__url = url
self.__id = id
@property
def url(self):
""":rtype: str"""
return self.__url
@property
def id(self):
""":rtype: int"""
return self.__id
|
class palindrome():
def __init__(self,string):
self.string = string
def __call__(self):
testStr = self.string.lower()
for x in [" ","!",]:
testStr = testStr.replace(x,"")
if testStr == testStr[::-1]:
return True
else:
return False
def pri... |
"""
@author: Li Xi
@file: __init__.py.py
@time: 2019/10/29 16:20
@desc:
""" |
"""
this is a regional comment
"""
print('hello world') # this is a single line comment
print('Hello, World'.upper())
|
def headfront():
i01.head.neck.moveTo(90)
i01.head.rothead.moveTo(90)
|
# 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 isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return self... |
bot_major_version = 0
bot_minor_version = 1
bot_patch_version = 2
def bot_version_string():
return f'{bot_major_version}.{bot_minor_version}.{bot_patch_version}'
|
"""
@author: David Lei
@since: 5/11/2017
https://www.hackerrank.com/challenges/detect-whether-a-linked-list-contains-a-cycle/problem
A cycle exists if any node is visited once during traversal.
Both Passed :)
"""
def has_cycle_better(head): # a.k.a floyd cycle detection, hare & turtle.
# Idea: if a cycle exists... |
namesList = ['Tuffy','Ali','Nysha','Tim' ]
sentence = 'My dog sleeps on sofa'
names = ';'.join(namesList)
print(type(names), ':', names)
wordList = sentence.split(' ')
print((type(wordList)), ':', wordList)
additionExample = 'ganehsa' + 'ganesha' + 'ganesha'
multiplicationExample = 'ganesha' * 2
print('Text Additions... |
class Prompts:
def CPrompt():
ExtentionType = input("What type of extention do you want the output to be? Ex. exe \n")
ProjectName = input("Whats the name of the project?")
Flags = input("What other flags would you like to add? \n -g ")
|
class Solution:
# @param s, a string
# @return an integer
def titleToNumber(self, s):
alphabets = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
s = list(s)
sum = 0
for index, element in enu... |
def main():
# input
N, M = map(int, input().split())
ABs = [[*map(int, input().split())] for _ in range(M)]
# compute
adj = [[] for _ in range(N)]
for A, B in ABs:
A -= 1
B -= 1
adj[A].append(B)
adj[B].append(A)
ans = 0
for i, vs in enumerate(adj):
... |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\autonomy\parameterized_autonomy_request_info.py
# Compiled at: 2016-09-08 21:38:24
# Size of source ... |
num1 = 10
# 修复bug
num2 = 20000
num3 = 30
num4 = 40
str = 'v2.0开发完成'
|
#!/usr/bin/env python
# encoding: utf-8
TRANSLATION_MAP = {
'Added' : u'添加了',
'Deleted' : u'删除了',
'Removed' : u'删除了',
'Modified' : u'修改了',
'Renamed' : u'重命名或移动了',
'Moved' : u'移动了',
'Added directory' : u'新建了目录',
'Removed directory' : u'删除了目录',
'Renamed directory' : u'重命名了目录',
'Mo... |
def nswp(n):
if n < 2: return 1
a, b = 1, 1
for i in range(2, n + 1):
c = 2 * b + a
a = b
b = c
return b
n = 3
print(nswp(n))
|
#!/usr/bin/env python
#-*-coding:utf-8*-
# 程序实现的功能:打印三角形
row = int(input("请输入需要打印的行数:"))
i = 0
full_space = 4 * row - 3
while i < row:
init_space = int((full_space - (4 * (i + 1) - 3)) / 4)
print(' ' * init_space, end="")
print(' ' * init_space, end="")
j = 0
while j <= i:
if j == i:
print("*", end=... |
##def txt2BRAM2(CFile):
## """
## FUNCTION: txt2BRAM2(a str)
## a: text file name string
##
## - Initalizing a VHDL array with the contentes of a text file.
## """
##
# Python's variable declerations
#-------------------------------------------------------------------... |
description = "Lowtemperature setup for SPHERES" \
"Contains: SIS, doppler, shutter, sps and cct6"
group = 'basic'
includes = ['spheres',
'cct6']
startupcode = """
cct6_c_temperature.samplestick = 'lt'\n
cct6_c_temperature.userlimits = (0, 350)
""" |
def user_input():
'''
this function to get input from user
return to_currency, from_currency, date
'''
to_currency = input("what is your to currency code ? \n")
from_currency = input("what is your from currency code? \n")
date = input("what is your date? \n")
return to_cur... |
print(f'{"GERADOR DE DESCONTOS":.^60}')
produto = str(input('Nome do produto:'))
preco = float(input(f'Digite o preço do/a {produto}:'))
opc = int(input('[ 1 ] A vista\n[ 2 ] Parcelado\n-->: '))
if opc == 1:
des = float(input('Digite o desconto %: '))
valor = preco*des/100
print(f'O valor de produto:{produ... |
def foo(arg1, *, kwarg1):
pass
def bar():
pass |
#
# PySNMP MIB module DECserver-Accounting-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DECserver-Accounting-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:22:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... |
def point_in_region(lower_left_corner, upper_right_corner, x, y):
return (
x >= lower_left_corner.x
and x <= upper_right_corner.x
and y >= lower_left_corner.y
and y <= upper_right_corner.y) |
"""Programming support libraries.
The modules in this package
Module Summary
--------------
motleydatetime
Makes datetime manipulation easy and reliable. Potentially useful to any Python program
which uses the standard "datetime" module, especially when dealing with timezones or UTC datetimes.
... |
def duplicate_zeros(arr):
if 0 not in arr:
return arr
else:
array = []
for a in arr:
if a == 0:
array.extend([0, 0])
else:
array.append(a)
for i in range(len(arr)):
arr[i] = array[i] |
class MinStack(object):
def __init__(self):
self.s = []
self.min_s = []
def push(self, x):
self.s.append(x)
if self.min_s:
if self.min_s[-1] > x:
self.min_s.append(x)
else:
self.min_s.append(self.min_s[-1])
else:
... |
n1 = float(input('Primeiro segmento:'))
n2 = float(input('Segundo segmento:'))
n3 = float(input('Terceiro segmento:'))
if n1 < n2 + n3 and n2 < n3 + n1 and n3 < n1 + n2:
print('\33[1;32mOs segmentos acima podem formar um triangulo')
else:
print('\33[1;32mOs segmentos acima não podem formar um triangulo') |
# 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 ... |
# Guest & items
allGuests = {'Alice': {'apples': 5, 'pretzels': 12},
'Bob': {'ham sandwiches': 3, 'apples': 2},
'Carol': {'cups': 3, 'apple pies': 1}}
# function: get amount of a item(allGuests, item)
def totalBrought(guests, item):
# initiate a counter
numBrought = 0
# traverse va... |
print('================= Calculando novo Salário ===============')
sal = float(input('Digite o valor do salário R$ '))
aumento = 15
varsal = sal * aumento / 100
nvsal = varsal + sal
print('\n')
print('O salário atual é {:.2f} R$, e agora com o acréssimo de {:.2f} R$, ficará {:.2f} R$ '.format(sal,varsal,nvsal))
|
# This problem was asked by Yahoo.
# Write an algorithm that computes the reversal of a directed graph.
# For example, if a graph consists of A -> B -> C, it should become A <- B <- C.
####
graph1 = {}
graph1['A'] = ['B', 'C', 'D']
graph1['B'] = ['C', 'D']
graph1['C'] = ['D']
####
def reversegraph(gr):
ret = {}
... |
class Stack:
sizeof = 0
def __init__(self,list = None):
if list == None:
self.item =[]
else :
self.item = list
def push(self,i):
self.item.append(i)
def size(self):
return len(self.item)
def isEmpty(self):
if self.size()==0:
... |
if __name__ == '__main__':
# This is a line printing Hello World
# This is a second line comment
'''
This is a line printing Hello World
This is a second line comment
'''
print("Hello World") # This is a comment
|
def mutate_string(string, position, character):
stringlist = list(string)
stringlist[position] = character
string = ''.join(stringlist)
return string
|
__all__ = [
'NoDestinationError',
'DocDoesNotExist'
]
class NoDestinationError(BaseException):
"""There is no destination Git Repo configured for this Document"""
class DocDoesNotExist(BaseException):
"""The PaperDoc being requested does not exist"""
|
'''
请实现一个函数,用来判断一颗二叉树是不是对称的。
注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
'''
class TreeNode(object):
def __init__(self, x):
self.val=x
self.left=None
self.right=None
class Solution(object):
# 1.递归实现
def isSymmetrical(self, pRoot):
return self.selfIsSymmetrical(pRoot, pRoot)
def selfIsSymmetrical(self, pRoot1, p... |
flowers = input()
amount_flowers = int(input())
budget = int(input())
final_price = 0
one_rose_price = 5
one_Dahlias_price = 3.80
one_Tulips_price = 2.80
one_Narcissus_price = 3
one_Gladiolus_price = 2.50
if flowers == "Roses":
final_price = amount_flowers * one_rose_price
if amount_flowers > 80:
fin... |
CLASSES = {
'banana': 'банан',
'lemon': 'лимон',
'nectarine': 'нектарин',
'potato': 'картофель',
'zucchini': 'кабачок',
}
|
def main():
dic = {
'wide': [
'logs/pipelines/all_pcgrl/pcgrl_smb_wide_5.mscluster41.144549.out',
'logs/pipelines/all_pcgrl/pcgrl_smb_wide_4.mscluster40.144548.out',
'logs/pipelines/all_pcgrl/pcgrl_smb_wide_3.mscluster18.144536.out',
'logs/pipelines/all_pcgrl/... |
class ArXivAuthorNames:
def __init__(self, names_string):
self.names_string = self.__required(names_string)
def names(self):
"""
Converts name into a simple form suitable for the CrossRef search
"""
names = self.names_string.split(';')
out = list(map(self.__par... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.