content stringlengths 7 1.05M |
|---|
s = b'abc'; print(s.isspace(), s)
s = b'a-c'; print(s.isspace(), s)
s = b'a c'; print(s.isspace(), s)
s = b'a\tc'; print(s.isspace(), s)
s = b' '; print(s.isspace(), s)#半角スペースつ3
s = b'\r\n'; print(s.isspace(), s)
#s = b' '; print(s.isspace(), s)#全角スペース SyntaxError: bytes can only contain ASCII literal characters.
s ... |
class LampStateBase(object):
"""Состояние лампы"""
def get_color(self):
raise NotImplementedError()
class GreenLampState(LampStateBase):
def get_color(self):
return 'Green'
class RedLampState(LampStateBase):
def get_color(self):
return 'Red'
class BlueLampState(LampStateBas... |
a=[5,20,15,20,25,50,20]
b=set(a)
b.remove(20)
print(b)
|
#condições
nome = str(input('Digite seu nome: ')).strip().lower()
if 'isis' in nome:
print('Que nome bonito vc tem!')
else:
print('Você ainda pode mudar seu nome!')
print('fim')
#media
n1 = float(input('Digite sua nota: '))
n2 = float(input('Digite outra nota: '))
media = (n1 + n2)/2
if media >= 7:
print('... |
x = int(input('Digite o ano que quer saber: '))
y = x%4
if y == 0 and x%100 !=0 or x%400 == 0:
print('O ano de {} é bissexto'.format(x))
else:
print('O ano de {} não é bissexto '.format(x)) |
FEATKEY_NR_IMAGES = "nr_images"
FEATKEY_IMAGE_HEIGHT = "height"
FEATKEY_IMAGE_WIDTH = "width"
FEATKEY_ORIGINAL_HEIGHT = "original_height"
FEATKEY_ORIGINAL_WIDTH = "original_width"
FEATKEY_PATIENT_ID = "patient_id"
FEATKEY_LATERALITY = "laterality"
FEATKEY_VIEW = "view"
FEATKEY_IMAGE = "pixel_arr"
FEATKEY_IMAGE_ORIG = "... |
def get_packages_dict(activities):
"""
将activity对应的dict转化为package对应的dict
:param activities: 用户定义的程序和活动dict
:return: package对应的dict
"""
packages = activities.copy()
for key in packages:
packages[key] = packages[key][
1 if packages[key].__contains__('#') else 0:... |
# DDA Algorithm
def draw_line(x0, y0, x1, y1):
dy = y1 - y0
dx = x1 - x0
m = dy / dx
current_y = y0
print(f'dy = {dy}')
print(f'dx = {dx}')
print(f'm = {m}')
for index in range (x0, x1 + 1):
print(f'x = {index}, y = {round(current_y)}')
current_y = curren... |
# 函数,通过注解来告知用户或者开发者
def getValue(word: str='hahha') -> set:
"""哈哈"""
return set(word)
|
"""String constants.
Once defined, it becomes immutable.
"""
class _const:
class ConstError(TypeError):
pass
def __setattr__(self, name, value):
if name in self.__dict__:
raise self.ConstError
self.__dict__[name] = value
def __delattr__(self, name):
if name in self.__dict__:
raise... |
""" Distributor init file
Distributors: you can add custom code here to support particular distributions
of numpy_demo.
For example, this is a good place to put any checks for hardware requirements.
The numpy_demo standard source distribution will not put code in this file, so you
can safely replace this file with y... |
class Strategy:
moneymanagement = None
def __init__(self, moneymanagement):
self.moneymanagement = moneymanagement
def can_find_pattern(self, data):
if self.moneymanagement.checkDrawdown() < - float(self.moneymanagement.algorithm.Portfolio.Cash) * 0.1:
return False
r... |
# Attribute types
STRING = 1
NUMBER = 2
DATETIME = 3
# Analysis Types
SENTIMENT_ANALYSIS = 1
DOCUMENT_CLUSTERING = 2
CONCEPT_EXTRACTION = 3
DOCUMENT_CLASSIFICATION = 4
# Analysis Status
NOT_EXECUTED = 1
IN_PROGRESS = 2
EXECUTED = 3
# Creation Status
DRAFT = 1
COMPLETED = 2
# Visibilities
PUBLIC = 1
PRIVATE = 2
TEAM... |
#!/usr/bin/env python3
# coding:utf-8
f = open("yankeedoodle.csv")
nums = [num.strip() for num in f.read().split(',')]
f.close()
res = [int(x[0][5] + x[1][5] + x[2][6]) for x in zip(nums[0::3], nums[1::3], nums[2::3])]
print(''.join([chr(e) for e in res]))
|
hex_colors = {
"COLOR_1": "#d9811e",
"TEXT_BUTTON_LIGHT": "#000000",
"BUTTON_1": "#dfdfdf",
"BACKGROUND": "#dfdfdf",
"LABEL_TEXT_COLOR_LIGHT": "black",
"FRAME_1_DARK": "#2b2b42",
"TEXT_BUTTON_DARK": "white",
"BUTTON_DARK": "#292929",
"BACKGROUND_DARK": "#292929",
"LABEL_TEXT_CO... |
## Mel-filterbank
mel_window_length = 25 # In milliseconds
mel_window_step = 10 # In milliseconds
mel_n_channels = 40
## Audio
sampling_rate = 16000
# Number of spectrogram frames in a partial utterance
partials_n_frames = 160 # 1600 ms
## Voice Activation Detection
vad_window_length = 30 # In millisecond... |
#python3
for t in range(int(input())):
count = 0
s,w1,w2,w3 = map(int,input().split())
if((w1+w2+w3)<=s):
count = 1
elif((w1+w2)<=s):
if(w3 <= s):
count = 2
else:
count = 1
elif((w2+w3)<=s):
if(w3 <= s):
count = 2
else:... |
# Moeda
# 108
# Crie um módulo chamado moeda.py que tenha as funções incorporadas aumentar(), diminuir(), dobro() e metade(). Faça também um programa que importe esse módulo e use algumas dessas funções.
def aumentar(preco = 0, taxa = 0):
return preco + (preco * taxa / 100)
def diminuir(preco = 0, taxa = 0):
... |
# ================================================= #
# Trash Guy Animation #
# (> ^_^)> #
# Made by Zac (trashguy@zac.cy) #
# Version 4.1.0+20201210 #
# Donate: ... |
'''
что будет на выходе из приведенного кода?
'''
i = 100
while i > 0:
if i == 40:
break
print(i, end='*')
i -= 20 |
with open('F_T_W copy/ada_fund.json') as f:
data = json.load(f)
print(data)
|
class Dice(object):
__slots__ = ['sides']
def __init__(self, sides):
self.sides = sides
class DiceStack(object):
__slots__ = ['amount', 'dice']
def __init__(self, amount, dice):
self.amount = amount
self.dice = dice |
_cmds_registry = {}
def register(cmd:str, alias:str) -> bool:
if alias in _cmds_registry:
return False
else:
_cmds_registry[alias] = cmd
return True
def get_cmd(alias:str) -> str:
if alias in _cmds_registry:
return _cmds_registry[alias]
else:
return ''
|
class Meta(type):
def __new__(mcs, name, bases, namespace):
#mcs -> Metaclasse
#name -> Nome da classe
#base -> Classes pai da das subsclasses
#namespace -> Tudo que tem na classe em forma de dicionario
print(name)
if name == 'A': #
return type._... |
def word_form(number):
ones = ('', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
'nine')
tens = ('', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy',
'eighty', 'ninety')
teens = ('ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen',
... |
""" Settings default definition for Nine CMS """
__author__ = 'George Karakostas'
__copyright__ = 'Copyright 2015, George Karakostas'
__licence__ = 'BSD-3'
__email__ = 'gkarak@9-dev.com'
""" Default recommended settings """
# INSTALLED_APPS = (
# 'admin_bootstrapped_plus',
# # 'bootstrap3',
# 'django_admin... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Created by Ross on 19-1-10
def solve_dp(length):
if length < 2:
return 0
elif length == 2:
return 1
elif length == 3:
return 2
products = [0] * (length + 1)
products[0] = 0
products[1] = 1
products[2] = 2
products[3] ... |
__author__ = 'Ladeinde Oluwaseun'
__copyright__ = 'Copyright 2018, Ladeinde Oluwaseun'
__credits__ = ['Ladeinde Oluwaseun, amordigital']
__license__ = 'BSD'
__version__ = '1.5.1'
__maintainer__ = 'Ladeinde Oluwaseun'
__email__ = 'oluwaseun.ladeinde@gmail.com'
__status__ = 'Development'
|
a=10
b=5
print('Addition:', a+b)
print('Substraction: ', a-b)
print('Multiplication:', a*b)
print('Division: ', a/b)
print('Remainder: ', a%b)
print('Exponential:', a ** b) |
CHUNK_SIZE = (1024**2) * 50
file_number = 1
with open('encoder-5-3000.pkl', 'rb') as f:
chunk = f.read(CHUNK_SIZE)
while chunk:
with open('encoder-5-3000_part_' + str(file_number), 'wb') as chunk_file:
chunk_file.write(chunk)
file_number += 1
chunk = f.read(CHUNK_SIZE)
|
def app(amb , start_response):
arq=open('index.html','rb')
data = arq.read()
status = "200 OK"
headers = [('Content-type',"text/html")]
start_response(status,headers)
return [data] |
#!/usr/bin/env python3
SIZE = 100
with open('03-output.pbm', 'wb') as f:
f.write(b'P4\n100 100\n')
for i in range(SIZE):
counter = 0
xs = b''
for j in range(SIZE):
counter += 1
if (i + j) % 2 == 0:
xs += b'1'
else:
xs ... |
#
# PySNMP MIB module RSTP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RSTP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:50:24 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, 09:23:1... |
class Payment:
"""Class for handling payments
"""
def __init__(self):
self.flag_1 = 1
def payment_process(self, dist, delivery_charge, bill, time_avg, delivery_time):
"""Print final invoice generated with details
Args:
dist (float): Distance b/w user and... |
"""
File: settings.py
------------------------
This file holds all the constant variables
so that they can be globally called upon
and accessed by all of the other programs
"""
LEXICON_FILE = "Lexicon.txt" # File to read word list from
SCORE_FILE = 'highscores.txt' # File that stores all the scores
GRID_DIMENSIO... |
#Done by Carlos Amaral in 16/07/2020
"""
Write a function that accepts two parameters: a city name
and a country name. The function should return a single string of the form
City, Country , such as Santiago, Chile . Store the function in a module called
city _functions.py.
Create a file called test_cities.py that test... |
#..............example 1 combine................
# s = "ABC"
# s2 = "123"
# L = [x+y for x in s for y in s2]
# print(L)
#..............example 2 remove duplicates................
# L = [1, 3, 2, 1, 6, 4, 2, 98, 82]
# L2 = []
# for x in L:
# if x not in L2:
# L2.append(x)
# print(L2)
#.......... |
""" var object
this is for storing system variables
"""
class Var(object):
@classmethod
def fetch(cls, name):
"fetch var with given name"
return cls.list(name=name)[0]
@classmethod
def next(cls, name, advance=True):
"give (and, if advance, then increment) a counter variable"... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# +
# __doc__ string
# _
__doc__ = """test of ocs_common"""
# +
# function: test_ocs_common() to keep py.test happy
# -
def test_ocs_common():
assert True
|
def main(request, response):
headers = []
if "cors" in request.GET:
headers.append(("Access-Control-Allow-Origin", "*"))
headers.append(("Access-Control-Allow-Credentials", "true"))
headers.append(("Access-Control-Allow-Methods", "GET, POST, PUT, FOO"))
headers.append(("Access-Co... |
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive", "http_jar")
load("@bazel_tools//tools/build_defs/repo:jvm.bzl", "jvm_maven_import_external")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("@bazelrio//:deps_utils.bzl", "cc_library_headers", "cc_library_shared", "cc_library_sourc... |
class Display(object):
@classmethod
def getColumns(cls):
raise NotImplementedError
@classmethod
def getRows(cls):
raise NotImplementedError
@classmethod
def getRowText(cls, row):
raise NotImplementedError
def show(self):
for i in range(int(self.getRows())):... |
def fact(a):
if a<=1:
return 1
return a*fact(a-1)
a = int(input())
for i in range(a):
n=int(input())
print(fact(n))
|
#!/usr/bin/env python
# coding: utf-8
class Solution:
def numSubarrayProductLessThanK(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if not nums:
return 0
prod = nums[0]
head, tail = 0, 0
count = 0
w... |
""" Binary Search Algortihm
--------------------------------------------------
"""
#iterative implementation of binary search in Python def binary_search(a+list, item):
""" Performs iterative bonary search to find the position of an integer in a given, sorted, list.
a_list -- sorted list of integers
item -- integer yo... |
'''
package fitnesse.slim;
import java.util.List;
import fitnesse.util.ListUtility;
'''
'''
Packs up a list into a serialized string using a special format. The list items must be strings, or lists.
They will be recursively serialized.
Format: [iiiiii:llllll:item...]
All lists (including lists within lists) ... |
def selection_sort(array):
N = len(array)
for i in range(N):
# Find the min element in the unsorted a[i .. N - 1]
# Assume the min is the first element.
minimum_element_index = i
for j in range(i + 1, N):
if (array[j] < array[minimum_element_index]):
... |
def store_email(liste_mails):
res = {}
for addr in liste_mails:
n = addr.split('@')
if n[1] not in res:
res[n[1]] = []
res[n[1]].append(n[0])
res[n[1]].sort()
return res
print(store_email(["ludo@prof.ur", "andre.colon@stud.ulb",
"thierry@profs.ulb"... |
width = 10
precision = 4
value = decimal.Decimal("12.34567")
f"result: {value:{width}.{precision}}"
rf"result: {value:{width}.{precision}}"
foo(f'this SHOULD be a multi-line string because it is '
f'very long and does not fit on one line. And {value} is the value.')
foo('this SHOULD be a multi-line string, but no... |
"""
Here are data files describing three graphs: g1.txt, g2.txt, g3.txt.
The first line indicates the number of vertices and edges, respectively. Each
subsequent line describes an edge (the first two numbers are its tail and head,
respectively) and its length (the third number).
NOTE: some of the edge lengths are negat... |
# Event: LCCS Python Fundamental Skills Workshop
# Date: May 2018
# Author: Joe English, PDST
# eMail: computerscience@pdst.ie
# Purpose: A program to demonstrate string concatenation
noun = input("Enter a singular noun: ")
print("The plural of "+noun+" is "+noun+"s")
|
elements = {
0: {
"element": 0,
"description": "",
"dynamic": False,
"bitmap": False,
"len": 0,
"format": "",
"start_position": 0,
"end_position": 0
},
1: {
"element": 1,
"description": "Bitmap Secondary",
"dynamic": Fal... |
def write_html(messages):
file = open("messages.html","w")
html = []
html.append('<html>\n<head>\n\t<meta http-equiv="Content-Type" content = "text/html" charset=UTF-8 >\n')
html.append('\t<link rel="stylesheet" href="body.css">\n')
html.append('\t<base href="../../"/>\n')
html.append('\t<title>... |
msg = str(input('Número ponto flutuante: '))
numf = msg.replace(',', '.')
print(numf)
n = float(numf)
print(n) |
class ViradaCulturalSpider(CrawlSpider):
name = "virada_cultural"
start_urls = ["http://conteudo.icmc.usp.br/Portal/conteudo/484/243/alunos-especiais"]
def parse(self, response):
self.logger.info('A response from %s just arrived!', response.url)
|
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
darkBlue = (0,0,128)
white = (255,255,255)
black = (0,0,0)
pink = (255,200,200)
|
#Programa 3.1- Exemplo de sequência e tempo
divida = 0
compra = 100
divida = divida + compra
compra = 200
divida = divida + compra
compra = 300
divida = divida + compra
compra = 0
print (divida)
|
def createWordList(filename):
text_file= open(filename,"r")
temp = text_file.read().split("\n")
text_file.close()
temp.pop() #remove the last new line
return temp
def canWeMakeIt(myWord, myLetters):
listLetters=[]
for letter in myLetters:
listLetters.append (letter)
for x in m... |
expected_output = {
"BDI3147": {
"interface": "BDI3147",
"redirects_disable": False,
"address_family": {
"ipv4": {
"version": {
1: {
"groups": {
31: {
"group_nu... |
# User Configuration variable settings for pitimolo
# Purpose - Motion Detection Security Cam
# Created - 20-Jul-2015 pi-timolo ver 2.94 compatible or greater
# Done by - Claude Pageau
configTitle = "pi-timolo default config motion"
configName = "pi-timolo-default-config"
# These settings should both be False if thi... |
# This problem was asked by Facebook.
# Given a binary tree, return all paths from the root to leaves.
# For example, given the tree:
# 1
# / \
# 2 3
# / \
# 4 5
# Return [[1, 2], [1, 3, 4], [1, 3, 5]].
def getPaths(tree, path):
left = None
if tree.left:
left = getPaths(tree.left, path + [tree... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : __init__.py
# Author : yang <mightyang@hotmail.com>
# Date : 10.03.2019
# Last Modified Date: 11.03.2019
# Last Modified By : yang <mightyang@hotmail.com>
__all__ = ['pkgProj']
# from . import *
|
# Sum square difference
# Answer: 25164150
def sum_of_the_squares(min_value, max_value):
total = 0
for i in range(min_value, max_value + 1):
total += i ** 2
return total
def square_of_the_sum(min_value, max_value):
total = 0
for i in range(min_value, max_value + 1):
t... |
dia = input ('dia= ')
mes= input ('mês= ')
ano = input ('ano = ')
print ("você nasceu no dia " + dia + " no mês de " + mes + " de " + ano)
|
n1 = int(input('Digite um número: '))
n2 = int(input('Digite o segundo número: '))
n3 = n1 + n2
#comentário no pyton
print('{} + {} = {}'.format(n1, n2, n3)) |
# import pytest
def test_query_no_join(connection):
query = connection.get_sql_query(metrics=["total_item_revenue"], dimensions=["channel"])
correct = (
"SELECT order_lines.sales_channel as order_lines_channel,"
"SUM(order_lines.revenue) as order_lines_total_item_revenue "
"FROM anal... |
#%%
def validate_velocity_derivative():
pass
#%%
trial = 's1x2i7x5'
subject = 'AB01'
joint = 'jointangles_shank_x'
filename = '../local-storage/test/dataport_flattened_partial_{}.parquet'.format(subject)
df = pd.read_parquet(filename)
trial_df = df[df['trial'] == trial]
... |
"""
Descrição: Este programa converte dias, horas, minutos e segundos
Autor:Henrique Joner
Versão:0.0.1
Data:23/11/2018
"""
#Inicialização de variáveis
dias = 0
horas = 0
minutos = 0
segundos = 0
#Entrada de dados
dias = int(input("Digite o número de dias: "))
horas = int(input("Digite o número de horas: "))
... |
# Inheritance in coding is when one "child" class receives
# all of the methods and attributes of another "parent" class
class Test:
def __init__(self):
self.x = 0
# class Derived_Test inherits from class Test
class Derived_Test(Test):
def __init__(self):
Test.__init__(self) # do Test's __i... |
def restes(dividendes, diviseur):
'''restes (list(int) * int -> list(int)) : renvoie les restes de la division
euclidienne de chaque dividende par le diviseur'''
# Initialisation
'''restes (list(int)) : restes des divisions euclidiennes'''
restes = []
# Début du traitement
for divi... |
DEFAULT_NUM_IMAGES = 40
LOWER_LIMIT = 0
UPPER_LIMIT = 100
class MissingConfigException(Exception):
pass
class ImageLimitException(Exception):
pass
def init(config):
if (config is None):
raise MissingConfigException()
raise NotImplementedError
def download(num_images):
images_to_down... |
#new file as required
print ('ne1')
print ('ne2')
#C:\Users\kpmis\OneDrive\Documents\GitHub\wowmeter\new1.py
|
"""Convert Big-5 to UTF-8 and fix some trailing commas"""
with open("data/tetfp.csv", "rb") as f:
with open("data/tetfp_fixed.csv", "wb") as f2:
for line in f.readlines():
line = line.decode("big5").strip()
if line.endswith(","):
f2.write((line[:-1] + "\n").encode("ut... |
def includeme(config):
config.add_static_view('static', 'static', cache_max_age=0)
config.add_route('home', '/')
config.add_route('auth', '/auth')
config.add_route('add-stock', '/add-stock')
config.add_route('logout', '/logout')
config.add_route('portfolio', '/portfolio')
config.add_route('s... |
######################################################################
#
# File: b2sdk/transfer/transfer_manager.py
#
# Copyright 2022 Backblaze Inc. All Rights Reserved.
#
# License https://www.backblaze.com/using_b2_code.html
#
######################################################################
class TransferMan... |
#! python3
# -*- coding: utf-8 -*-
class OdoleniumError(Exception):
def __init__(self, msg):
super().__init__(msg)
|
def oeis_transform(seq: list):
"""
This function will receive an OEIS sequence, you should return the sequence after applying your transformation
"""
return seq
def input_transform(seq: list):
"""
This function will receive the input sequence, you should return the sequence after applying yo... |
"""
This package is the central point to find nice utilities in Matils.
Check out the code documentation it is very rich and provides informations and
valuable examples to start playing with Matils.
"""
|
# name = 'Samet Gedik'
# for letter in name:
# if letter == 'G':
# continue
# print(letter)
# x = 0
# while x < 5:
# x+=1
# if x == 2:
# continue
# print(x)
# 1-100 e kadar tek sayıalrın toplamı
x = 0
result = 0
while x <= 100:
x+=1
if x % ... |
numbers = [1, 2, 3, 10, 11, 15, 99]
def algo(n):
if n % 2 != 0:
return True
return False
def both_requisites(n):
if algo(n) and n > 10:
return True
return False
higher_than_ten = [num for num in numbers if both_requisites(num)]
print(higher_than_ten)
nombres = ['Alicia', 'María', '... |
numero = int(input('Me diga um numero: '))
resultado = numero % 2
if resultado == 0:
print('O numero {} é PAR'.format(numero))
else:
print('O numero {} é IMPAR'.format(numero))
|
"""
Given an integer (signed 32 bits), write a function to check whether it is
a power of 4.
Example:
Input: 16
Output: true
Follow up: Could you solve it without loops/recursion?
"""
#Difficulty: Easy
#1060 / 1060 test cases passed.
#Runtime: 28 ms
#Memory Usage: 13.6 MB
#Runtime: 28 ms, fa... |
while True:
print('-' * 50)
num = int(input('Quer ver a tabuada de qual valor? '))
print('-'*50)
if num < 0:
break
for i in range(1,11):
print(f'{num} x {i} = {num*i}')
print('Programa finalizado. \nObrigado e volte sempre!') |
def get_code_langs():
return [[164, 'MPASM', True],
[165, 'MXML', True],
[166, 'MySQL', True],
[167, 'Nagios', True],
[160, 'MIX Assembler', True],
[161, 'Modula 2', True],
[162, 'Modula 3', True],
[163, 'Motorola 68000 HiSoft Dev',... |
'''
TODO:
def get_wrapper
def get_optimizer
''' |
"""
day1ab - https://adventofcode.com/2020/day/1
Part 1 - 1019571
Part 2 - 100655544
"""
def load_data():
numbers = []
datafile = 'input-day1'
with open(datafile, 'r') as input:
for line in input:
num = line.strip()
numbers.append(int(num))
return numbers
def par... |
"""
File: caesar.py
Name: Yujing Wei
------------------------------
This program demonstrates the idea of caesar cipher.
Users will be asked to input a number to produce shifted
ALPHABET as the cipher table. After that, any strings typed
in will be encrypted.
"""
# This constant shows the original order of alphabetic... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# @Author : Ren Qiang
# %% 列表解析式 查找股票
stocks = {'MSFT': 165.51, 'FB': 174.79,
'YHOO': 19.63, 'IBM': 121.15, 'GOOG': 1210.41}
stocks_150 = {v: k for k, v in stocks.items() if v > 150}
print(stocks_150)
|
"""
异常处理
1. 目标:解决程序运行时的逻辑错误(数据超过有效范围).
不负责处理语法错误.
2. 现象:程序不再向下执行,而是不断向上返回.
3. 目的:将异常流程(向上),恢复为正常流程(向下).
4. 手段:四种写法
5. 价值:
保障程序可以按照既定的流程执行
就近原则
A --> B --> C --> D --> E --> ...
"""
# 1. 语法错误
# class MyClass:
# pass
#
# ... |
_base_ = 'fcos_r50_caffe_fpn_gn-head_1x_coco.py'
model = dict(
pretrained='open-mmlab://detectron2/resnet50_caffe',
backbone=dict(
dcn=dict(type='DCNv2', deform_groups=1, fallback_on_stride=False),
stage_with_dcn=(False, True, True, True)),
bbox_head=dict(
norm_on_bbox=True,
... |
#!/usr/bin/env python3
bank = [0, 2, 7, 0]
bank = [0, 5, 10, 0, 11, 14, 13, 4, 11, 8, 8, 7, 1, 4, 12, 11]
visited = {}
steps = 0
l = len(bank)
while tuple(bank) not in visited:
visited[tuple(bank)] = steps
m = max(bank)
i = bank.index(m)
bank[i] = 0 # Set the item to 0
quotient = m // l
bank ... |
def reorder_boxes(boxes):
boxes.sort()
ans = list()
for i in range(len(boxes) - 1, -1, -2):
if i - 1 >= 0:
ans.append(boxes[i] + boxes[i - 1])
else:
ans.append(boxes[i])
return ans
print(reorder_boxes([1, 2, 3, 4, 5, 6, 7]))
|
def sleep(seconds: float):
pass
def sleep_ms(millis: int):
pass
def sleep_us(micros: int):
pass |
class IEntry:
"""
* Entry interface - this will be shared across the projects
"""
SOURCE_CLI = 'cli'
SOURCE_GET = 'get'
SOURCE_POST = 'post'
SOURCE_FILES = 'files'
SOURCE_COOKIE = 'cookie'
SOURCE_SESSION = 'session'
SOURCE_SERVER = 'server'
SOURCE_ENV = 'environment'
S... |
for i in range(1, 11):
for j in range(1, 11):
a = i * j
if a < 10:
a = " " + str(a)
elif a < 100:
a = " " + str(a)
else:
a = str(a)
print(a, end=" ")
print()
|
class GaiaUtils:
@staticmethod
def convert_positive_int(param):
param = int(param)
if param < 1:
raise ValueError
return param |
class Attachment:
_SUPPORTED_MIME_TYPES = [
"application/vnd.google-apps.audio",
"application/vnd.google-apps.document", # Google Docs
"application/vnd.google-apps.drawing", # Google Drawing
"application/vnd.google-apps.file", # Google Drive file
"application/vnd.google-ap... |
A_CONSTANT = 45
def a_sum_function(a: int, b: int) -> int:
return a + b
def a_mult_function(a: int, b: int) -> int:
return a * b
class ACarClass:
def __init__(self, color: str, speed: int):
self.color = color
self.speed = speed
def describe(self) -> str:
return f'I am a {s... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
ha, hb = headA, headB
while ha != hb:
ha = ha.next if ha else headB
... |
r1 = int(input('Digite a reta 1: '))
r2 = int(input('Digite a reta 2: '))
r3 = int(input('Digite a reta 3: '))
a = r1 < (r2 + r3)
b = r2 < (r1 + r3)
c = r3 < (r1 + r2)
if a and b and c is True:
print('\nPode Foramr um Triangulo')
if r1 == r2 and r1 == r3:
print('É Um Triangulo EQUILÁTERO')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.