content stringlengths 7 1.05M |
|---|
def readHeaderFromFile(filename):
#datafile = open(filename, "r")
#headers=[]
#for line in datafile:
# entry = line.strip().split(";")
# #print(entry);
# if entry[0] == "Anz_Kunden":
# headers = entry
# return headers;
return ["Anz_Kunden", "Gesamtkosten"]
def... |
"""DFS.py
Algorithms for depth first search in Python.
We need to search iteratively rather than recursively in
order to avoid Python's low recursion limit.
D. Eppstein, July 2004.
"""
# Types of edges in DFS traversal.
# The numerical values are used in DepthFirstSearcher, change with care.
forward = 1 # traver... |
class Contract(object):
def __init__(self, ticker_index, ticker, exchange, name, size, price_tick):
self.ticker_index = ticker_index
self.ticker = ticker
self.exchange = exchange
self.name = name
self.size = size
self.price_tick = price_tick
class ContractTable(obj... |
# Default Settings File
APP_SESSION_KEY = 'fitbit2influx-test-session-key'
# Fitbit Web Hosts
FITBIT_WEB_HOST = 'www.fitbit.com'
FITBIT_API_HOST = 'api.fitbit.com'
# Fitbit Application Information
# CLIENT_ID = None
# CLIENT_SECRET = None
CALLBACK_URL = '/authorize'
# Token Validity in ms (default: 1 hr per Fitbit)
... |
def count_sheep(n):
sheep=""
for i in range(1, n+1):
sheep+=str(i) + " sheep..."
return sheep
|
# by Kami Bigdely
# Split temporary variable
patty_weight = 70 # [gr]
pickle_weight = 20 # [gr]
tomatoes_weight = 25 # [gr]
lettuce_weight = 15 # [gr]
buns_weight = 95 # [gr]
sandwich_weight = (2 * patty_weight + 4 * pickle_weight + 3 * tomatoes_weight + 2 * lettuce_weight
+ 2 * buns_weight)
print("NY ... |
class PDB:
def __init__(self, in_pdb, chain="L", resname="LIG", resnum=" 1"):
"""
Class to read and process PDB files.
:param in_pdb: pdb file path
:type in_pdb: str
:param chain: label of the chain of interest
:type chain: str
:param resname: label of the r... |
# Reads input, prints inverted and if it is a palindrome
phrase = str(input('Digite uma frase: ')).strip().upper()
words = phrase.split()
joined = ''.join(words)
inverted = ''
for letter in range(len(joined) - 1, -1, -1):
inverted += joined[letter]
print('A sua frase: \n{}'.format(phrase))
print('Invertida: \n{}'.... |
_base_ = ['./twins_pcpvt-s_fpn_fpnhead_8x4_512x512_80k_ade20k.py']
checkpoint = 'https://download.openmmlab.com/mmsegmentation/v0.5/pretrain/twins/pcpvt_base_20220308-0621964c.pth' # noqa
model = dict(
backbone=dict(
init_cfg=dict(type='Pretrained', checkpoint=checkpoint),
depths=[3, 4, 18, 3]), ... |
def get_product_order_validation(id: int):
message: list[str] = []
if not isinstance(id, int) or id is None or id == "" or id <= 0:
message.append("Id inválido")
return message
|
"""
Following are the topics we will cover today.
1) Recursive Function
2) Built-in Functions: min, max, count, len, split, zip, types, sum, sorted
"""
# #############################################################################
# 1) Recursive Function
# ###########################################################... |
serverko.trace('INFO: layout.py')
def layout_script_userJoined(userID) :
serverko.trace("JS:layout_script_userJoined " + userID)
#layout.send(userID)
# define layout area
class LayoutArea:
type = 'dummy'
id = 'dummy'
x = -111111
y = -111111
w = -111111
h = -111111
layout = 'hor'
state = 'dummy'
owner... |
'''
Exercise 2:
1. Write a script that takes a sentence from the user without any punctuation and prints
the sentence without any white spaces. Note a white space is represented by ' ', and
an empty string is represented by ''.
>>> enter a sentence: this is a SHORT sentence
thisisaSHORTsentence
2. Same as above except ... |
"""
The Collatz Conjecture states that for any natural number n, if n is even, divide it by 2.
If n is odd, multiply it by 3 and add 1. If you repeat the process continously for n, n will eventually reach 1.
For example, if n = 20, the resulting sequence will be:
[20, 10, 5, 16, 8, 4, 2, 1]
Write a program that will... |
print("Welcome to Band Name Generator")
yourName = input("What's your name?\n")
cityName = input("What's the name of the city you grew up in?\n")
carCompany = input("What's the name of your car company? \n")
birthMonth = input("What's your birth month? \n")
nameGenerator = cityName + yourName[4] + carCompany + birthMon... |
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
"""
Base class for CLI command. All CLI commands are modules in
scarab.commands.* packag and should implement scarab.commands.Base
interface: register and run methods.
"""
class Base(object):
"""A base command."""
def __init__(self):
pass
def... |
"""
Polity Module.
"""
class Polity(object):
"""
Polity class.
Args:
communities (list[Community]): A list of communities which belong to
the polity.
Attributes:
communities (list[Community]): A list of communities which belong to
the polity.
"""
def _... |
with open("col1.txt") as f1, open("col2.txt") as f2:
ret = ['{}\t{}'.format(p, c) for p, c in zip(f1.read().split('\n'), f2.read().split('\n'))]
with open("col3.txt", 'w') as f3:
f3.write('\n'.join(ret))
|
def move(i, j):
if i == 20 or j == 20:
return 1
else:
return move(i+1, j) + move(i, j+1)
if __name__ == "__main__":
print(move(0, 0))
|
###
#
# @package py.fileio
### Function to read file.
#
# @function read
# @param filename
def read(filename, encoding='utf-8'):
BUFFER = open(filename, 'rt', encoding=encoding)
text = BUFFER.read()
BUFFER.close()
# force LF line endings (\n)
text.replace('\r\n', '\n').replace('\r', '\n')
return text
### Fu... |
class pyarmstrongnum():
def __init__(self):
return None
def armstrong(self,num):
num = [int(i) for i in str(num)]
answer = [num[x]**len(num) for x in range(len(num))]
num = int(''.join(str(y) for y in num))
if sum(answer) ==num:
return str(num) + " is ... |
##########################################################
# Contains variables shared across owping tool components
##########################################################
#Version of the latency schema used
LATENCY_SCHEMA_VERSION = 1
# Default time between packets (in seconds) if not specified by user
DEFAULT_P... |
__author__ = "Prikly Grayp"
__license__ = "MIT"
__version__ = "1.0.0"
__email__ = "priklygrayp@gmail.com"
__status__ = "Development"
students = []
class Student():
def get_students_titlecase(self):
students_titlecase = []
for student in students:
students_titlecase.append(student['name'].title())
return s... |
'''
Aggregation Helper Functions
'''
def aggregation_insol(normalized_energy, insolation, frequency='D'):
'''
Insolation weighted aggregation
Parameters
----------
normalized_energy: Pandas series (numeric)
Normalized energy time series
insolation: Pandas series (numeric)
Time ... |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( seq ) :
n = len ( seq )
if ( n >= 9 ) :
return "-1"
result = [ None ] * ( n + 1 )
count = 1... |
class TemplateNotFoundError(FileNotFoundError):
def __init__(self, template_id, *args, **kwargs):
super().__init__(*args, **kwargs)
self.template_id = template_id
self.detail = f'Template not found with Template ID - "{template_id}"'
def __str__(self):
return self.detail
|
DEFAULT_DATA_ROOT = "/data"
# Default perception schema version
DEFAULT_PERCEPTION_VERSION = "0.0.1"
# Default Timing text for codetiming.Timer decorator
TIMING_TEXT = "[{name}] elapsed time: {:0.4f} seconds."
# Click CLI context settings
CONTEXT_SETTINGS = {
"help_option_names": ["-h", "--help"],
"show_def... |
"""Another example module, this time inside of a subpackage."""
def concat_2(a):
"""Concatenate the string "2" to to the end of an existing string object.
Parameters
----------
a : string
The string to be concatenated to.
Returns
-------
a+"2" : string
The resulting strin... |
n = input()
n = int(n)
arr = list(map(int, input().split()))
arr.sort()
if(arr[n-1] < 0) :
# 0 0
print("{} {}".format(arr[n-1], 1))
elif(arr[n-1] is 0) :
count = 0
for i in range(n-1, -1, -1) :
if(arr[i] is 0) :
count = count + 1
# 0 count
print("0 {}".format(count))
else :
... |
load("@cldr_json_data//:index.bzl", _ALL_CLDR_LOCALES = "LOCALES")
# List of locales the tool can generate files for.
LOCALES = _ALL_CLDR_LOCALES
# Labels resolving to the individual `generate-locale-tool` entry-points
GENERATE_LOCALES_TOOL_BIN = "//packages/common/locales/generate-locales-tool/bin"
GET_BASE_CURRENCI... |
def fatorial(n):
if n == 1:
return 1
else:
return n * fatorial(n-1)
n = int(input("Digite o número para o fatorial: "))
print(f"Fatorial: {fatorial(n)}")
|
n = int(input())
n1 = int(input())
def fact(a, b):
f1 = a
f2 = b
for i in range(a - 1, 0, -1):
f1 *= i
for j in range(b - 1, 0, -1):
f2 *= j
result = f1 / f2
return f'{result:.2f}'
print(fact(n, n1))
|
# Perfect numbers are numbers with the property such that the sum of all their factors equals themselves.
perfectNumbers = []
factors = []
for n in range(1, 10000, 1):
count = 1
for w in range(0, n):
if n%count == 0:
factors.append(count)
if count < n:
count+= 1
sum ... |
ENTRY_POINT = 'sort_even'
FIX = """
Remove sort helper function
"""
#[PROMPT]
def sort_even(l: list):
"""This function takes a list l and returns a list l' such that
l' is identical to l in the odd indicies, while its values at the even indicies are equal
to the values of the even indicies of l, but sor... |
print("Digite uma sequência de valores termiada por zero.")
soma = 0
valor = 1
while valor != 0:
valor = int(input("Digite um valor a ser somado:"))
soma += valor
print("A soma dos valores digitados é: ", soma)
|
# -*- coding: utf-8 -*-
N = int(input())
dic = { 'C': 0, 'R': 0, 'S': 0 }
for i in range(N):
amount, animal = input().split()
dic[animal] += int(amount)
total = dic['C'] + dic['R'] + dic['S']
print("Total: %d cobaias" % total)
print("Total de coelhos: %d" % dic['C'])
print("Total de ratos: %d" % dic['R'])
pri... |
class Config(object):
def __init__(self):
# model params
self.model = "AR_mem"
self.nsteps = 3 # equivalent to x_len
self.msteps = 5
self.attention_size = 32
self.l2_lambda = 1e-3
self.ar_lambda = 1e-1
self.ar_g = 1
# data params
... |
# API identifiers
# https://github.com/aeternity/protocol/blob/14db60b7db4d51618ebad539aaf6a0b40b72e633/epoch/api/api_encoding.md#encoding-scheme-for-api-identifiers-and-byte-arrays
# base58
ACCOUNT_ID = "ak" # base58 Account pubkey
BLOCK_PROOF_OF_FRAUD_HASH = "bf" # base58 Block Proof of Fraud hash
BLOCK_STATE_HASH... |
header = """Executable = /usr/bin/matlab
Universe = vanilla
RequestMemory = 6000
RequestCPUs = 16
getenv = True
logdir = logs
output = $(logdir)/$(Cluster)-$(Process).o
error = $(logdir)/$(Cluster)-$(Process).e
log = $(logdir)/$(Cluster)-$(Process).log
args = -nodisplay -singleCompThread
"""
for subj in [1, 2, 3]:
... |
"""Utilities for reading/writing our data."""
def SavePairs(pairs, filename):
with open(filename,'w') as f:
for pair in pairs:
f.write("{}\t{}\n".format(pair[0],pair[1]))
return
def ReadPairs(filename):
pairs = set()
with open(filename,'r') as f:
for line in f.readlines():
... |
p_paths = {"videodownloader": "C:\\Program Files\\4KDownload\\4kvideodownloader\\4kvideodownloader.exe",
"androidstudio": "C:\\Program Files\\Android\\Android Studio\\bin\\studio64.exe" ,
"anydesk" : "C:\\Program Files (x86)\\AnyDesk\\AnyDesk.exe" ,
"alexa" : "C:\\Program Files\\WindowsApps\\57540AMZNMobileLLC.Am... |
# -*- coding: utf-8 -*-
# MIT License
#
# Copyright (c) 2017 Tijme Gommers
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to... |
listaFilme = [Senhor_dos_anéis,Harry_potter]
listaJogos = [God_of_War,Counter_Strike_Source]
listaLivros = [O_Diario_de_anne_frank,Jojos_Bizarre_Adventures]
listaEsportes = [Handebol,basquete]
listaMÃE = [listaFilme,listaEsportes,listaJogos,listaLivros]
print(listaMÃE(listaLivros(0)))
del listaEsportes[0]
|
"""
Write a function that searches a list of names (unsorted) for the name "Bob" and returns the
location in the list. If Bob is not in the array, return -1.
Examples:
csWhereIsBob(["Jimmy", "Layla", "Bob"]) ➞ 2
csWhereIsBob(["Bob", "Layla", "Kaitlyn", "Patricia"]) ➞ 0
csWhereIsBob(["Jimmy", "Layla", "James"]) ➞ -1
... |
word = input()
dicc = {}
for char in word:
if char not in dicc.keys():
dicc[char] = 0
dicc[char] += 1
rainbow = 1
for x, y in dicc.items():
rainbow *= (y + 1) % 11092019
rainbow = rainbow % 11092019
print(rainbow) |
#Questão 2465 - passa a bolinha
def pega_proximo(matrix, lin, col):
proxi = -1
proxj = -1
if matrix[lin][col]['p'] == 'N':
proxi = lin
proxj = col+1
matrix[lin][col]['p'] = 'L'
elif matrix[lin][col]['p'] == 'L':
proxi = lin+1
proxj = col
matrix[lin][col... |
#!/usr/bin/env python3
__author__ = 'Andrej Palicka <andrej.palicka@merck.com>'
|
students_roll = (1,2,3,6,77,90)
print(students_roll.index(77))
|
# 5. Программа запрашивает у пользователя строку чисел, разделенных пробелом.
# При нажатии Enter должна выводиться сумма чисел.
# Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter.
# Сумма вновь введенных чисел будет добавляться к уже подсчитанной сумме.
# Но если вместо числа вводитс... |
def longestPalindrome(s: str) -> str:
result = ''
list1 = list(s)
left = 0
right = 0
for left in range(len(list1)):
char = list1[left]
for right in range(len(list1)):
if right > left and char == list1[right]:
string = ''.join(list1[left:right+1])
... |
# 1.uzd Uzrakstiet programmu, kas pārbauda lietotāja temperatūru.
# Ja lietotājs ievada zem 35, tad prasiet vai "nav par aukstu"
# Ja no 35 līdz 37 (ieskaitot), izvadiet "viss kārtībā"
# Ja ir pāri 37, tad izvadiet "iespējams drudzis"
print("1.uzdevums")
user_temp = float(input("ievadi savu temperatūru: "))
if user_tem... |
n = int(input("Whats your number?: "))
sumOrProduct = input("Sum or product?: ")
output = 0
if sumOrProduct.lower() == "sum":
for x in range(1, n + 1):
output += x
elif sumOrProduct.lower() == "product":
output = 1
for x in range(1, n + 1):
output *= x
print(output) |
#!/usr/bin/env python
__author__ = 'kinpa200296'
class mydefaultdict(object):
def __init__(self):
self._dict = dict()
def __getitem__(self, item):
if item not in self._dict:
self._dict[item] = mydefaultdict()
return self._dict[item]
def __setitem__(self, key, value):... |
# For each sample we input the integer identifiers
# of a single user and a single item
user_id_input = Input(shape=[1], name='user')
item_id_input = Input(shape=[1], name='item')
embedding_size = 16
dense_size = 128
dropout_embedding = 0.5
dropout_hidden = 0.2
user_embedding = Embedding(output_dim=embedding_size, in... |
# 수식의 괄호 유효성 검사
class ArrayStack:
def __init__(self):
self.data = []
def size(self):
return len(self.data)
def isEmpty(self):
return self.size() == 0
def push(self, item):
self.data.append(item)
def pop(self):
return self.data.pop()
def peek(self):
... |
guys = list()
data = list()
adults = junior = 0
for counter in range(0, 3):
data.append(str(input('Name: ')))
data.append(int(input('Age: ')))
guys.append(data[:])
data.clear()
print(guys)
for person in guys:
if person[1] >= 21:
print(f'{person[0]} has reached the legal age of majority.')
... |
# Normalization uncertainties
xsec_std = {
'TTJets_bkg': 0.06097560975609759,
'WZJets': 0.04770462700154329,
'STJets': 0.0666983590353544,
'TTJets_signal': 0.0609756097560975
}
norms = {"lumi": 0.02,
"mistag":0.05,
"tau_trigger":0.05,
"tau_id":0.06,
"ttmass":0.03,
... |
palavras = []
countprimeiro = countsegundo = 0
palavras.append(str(input('Digite uma expressão: ')))
for p in palavras:
for vogal in p:
if vogal == '(':
countprimeiro += 1
#print(vogal, end='')
elif vogal == ')':
countsegundo += 1
#print(vogal)
if cou... |
def extractSleepykoreanWordpressCom(item):
'''
Parser for 'sleepykorean.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
if "lucia" in item['tags']:
return buildReleaseMessageWithType(item, "Lu... |
def extractQxbluishWordpressCom(item):
'''
Parser for 'qxbluish.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('gtvftbv', 'Guide The Villain Father To Be Virtuous', ... |
lista = [1, 2, 3]
lista.insert(1, 'teste')
lista.append(10)
print(lista)
print(lista[1:-1])
print(2 in lista)
lista.reverse()
print(lista)
print('teste' not in lista)
|
while True:
try:
maximo = input()
except EOFError:
print(ult_max)
break
ult_max = maximo
|
matriz = [[], [], []]
# matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for lin in range(0, 3): # Representa as 3 linhas da matriz
for col in range(0, 3): # Representa as 3 colunas da matriz
matriz[lin].append(int(input(f'Digite um valor para [{lin}, {col}]: '))) # Adiciona os valor a matriz
# matriz[... |
class Situations:
TECHNICAL_FAILURE = 'технический сбой'
TECHNICAL_WORK = 'технические работы'
LIST = [TECHNICAL_FAILURE, TECHNICAL_WORK]
class Buttons:
ADD_CHAT = 'Добавить чат'
DELETE_CHAT = 'Удалить чат'
ADD_PROVIDER = 'Добавить провайдера'
DELETE_PROVIDER = 'Удалить провайдера'
ADD... |
def get_params_path_list(toppar_dir_path):
params_path_list = [
f"{toppar_dir_path}/top_all36_prot.rtf",
f"{toppar_dir_path}/par_all36m_prot.prm",
f"{toppar_dir_path}/top_all36_na.rtf",
f"{toppar_dir_path}/par_all36_na.prm",
f"{toppar_dir_path}/top_all36_carb.rtf",
f"{toppar_dir_path}/par... |
DEBUG = False
RRH_NUMBER = 3
CONNECTION_NUMBER = 5
POISSON_RATE = 1/4000.0
PACKET_SIZE_MEAN = 100
PACKET_SIZE_DEV = 20
PACKET_SIZE_MAX = 1000000
BASE_PORT = 3000
LG_SERVICE_PORT = 5001
BROADCAST_ADDRESS = '10.0.0.2'
|
#
# @lc app=leetcode id=704 lang=python
#
# [704] Binary Search
#
# https://leetcode.com/problems/binary-search/description/
#
# algorithms
# Easy (45.32%)
# Likes: 290
# Dislikes: 32
# Total Accepted: 62.1K
# Total Submissions: 127.6K
# Testcase Example: '[-1,0,3,5,9,12]\n9'
#
# Given a sorted (in ascending ord... |
class Message:
def __init__(self, pass_on=False):
self.pass_on = pass_on
class MessengerNodeMixin:
""" Implements a node that can send messages to its parent """
@property
def parent(self):
raise NotImplementedError
def handle_message(self, message):
""" This method must... |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( n , m ) :
return n if ( n == m ) else 1
#TOFILL
if __name__ == '__main__':
param = [
(57,57,),
(... |
class Solution:
# @return an integer
def trailingZeroes(self, n):
return sum(map(lambda x: n / (5**x) , range(1, 31)))
|
#!/usr/bin/env python3
class Solution:
def uniquePathsIII(self, grid):
self.left = 0
nr, nc = len(grid), len(grid[0])
for i in range(nr):
for j in range(nc):
if grid[i][j] == 0:
self.left += 1
elif grid[i][j] == 1:
... |
# Advent of Code Day 8
def parse_file(file):
with open (file, 'r') as f:
data=[]
for line in f.read().splitlines():
op, num = line.split()
num = int(num)
data.append([op, num])
return data
def execute_prog_part1(file):
data = parse_file(file)
acc =... |
class Player:
def __init__(self, player_name):
self.player_name = player_name
self.character = None
self.level = 1
self.hp = 100
self.mp = 1
self.win_record = {'win': 0, 'lose': 0}
self.score = 0
def get_name(self):
return self.player_name
d... |
def reporting(conn, result, timeout=None):
timeout = timeout or conn.global_timeout # -1 a.k.a. wait for ever
log_map = {
'debug': conn.logger.debug,
'error': conn.logger.error,
'warning': conn.logger.warning
}
while True:
try:
received = result.receive(tim... |
#
# This file contains the Python code from Program 7.6 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm07_06.txt
#
class OrderedListAs... |
'''
If you are going to add a camera to this list please test and fill in all
available settings.
'''
LOGITECH = 'logitechHD1080p'
PHILIPS = 'philips 3'
camera_settings = {
'logitechHD1080p': {
'res': ((1920, 1080, 3), (640, 480, 3), (1280, 720, 3), (480, 360, 3)),
'fps': ((30.0),)
},
'phi... |
#!/usr/bin/env python
def home_samples(adapter, year, month):
match = {"year": {"$eq": year}}
if month:
match["month"] = {"$eq": month}
pipe = [
{"$match": {"received_date": {"$exists": "True"}}},
{
"$project": {
"month": {"$month": "$received_date"},
... |
point_cloud_range = [-50, 0, -5, 50, 50, 3]
voxel_size = [0.25, 0.25, 8]
model = dict(
type='MMDA',
img_backbone=dict(
type='UNetResNet34',
out_channels=64,
pretrained=True),
img_seg_head=dict(
type='ImageSegHead',
in_channels=64,
num_classes=11
),
pts... |
""""
Dummy mocking module for pandas.
When pandas is not avaialbe we will import this module as graphlab.deps.pandas,
and set HAS_pandas to false. All methods that access pandas should check the HAS_pandas
flag, therefore, attributes/class/methods in this module should never be actually used.
"""
'''
Copyright (C) 201... |
#Faça um Programa que peça um número inteiro e determine se ele é par ou impar. Dica: utilize o operador módulo (resto da divisão).
numero = int(input("Digite um número: "))
if numero % 2 == 0:
print("O número é par")
else:
print("O número é impar") |
DOMAINS_TO_MONITOR = {"photoscape.ch"} # Sample malware domain
def rule(event):
return any(domain in event.get("domain") for domain in DOMAINS_TO_MONITOR)
def title(event):
return "Suspicious lookup to domain " + event.get("domain", "<UNKNOWN_DOMAIN>")
|
# Lugares em restaurante: Escreva um programa que pergunte ao usuario quantas pessoas estao em seu grupo para jantar. Se a resposta for maior que oito, exiba uma mensagem dizendo que eles deverao esperar uma mesa. Caso contrario, informe que sua mesa esta pronta.
question = int(input("Dear costumer.\nHow many people a... |
#
# PySNMP MIB module CRI-SERVER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CRI-SERVER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:12:30 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... |
'''
LICENSING
-------------------------------------------------
hypergolix: A python Golix client.
Copyright (C) 2016 Muterra, Inc.
Contributors
------------
Nick Badger
badg@muterra.io | badg@nickbadger.com | nickbadger.com
This library is free software; you can redistribute it and/o... |
# slice 切片
L=['one','two','three']
print(L[0:1])
print(L[1:3])
# 如果从0开始,可省略
print(L[:2])
# 从后往前
print(L[-2:])
L1 = list(range(100))
print(L1)
# 隔两个元素取一次
print(L1[:10:2])
#所有数,每5个取一个:
print(L1[::5])
#复制一个list
L2 = L1[:]
print(L2)
#tuple 同样可能用切片操作,结果仍是tuple
T1 = (1,2,3)
print(T1[:2])
## 字符串也可用切片操作,操作结果仍是字符串
... |
def empty_it(a, b, c, d, nested):
for i in range(a, c+1):
for j in range(b, d+1):
nested[i][j] = 0
return nested |
# -*- coding: utf-8 -*-
G = 0.01720209895 * 0.01720209895
def fromSI_L(l):
return l / 149597870700
def fromSI_T(t):
return t / 86400
def fromSI_M(m):
return m / 1.98892e30 |
class Team:
#Creates the team and initializes all the players
def __init__(self):
self._pg = null
self._sg = null
self._sf = null
self._pf = nul
self._c = null
self._g = null
self._util = null
|
"""
Faça um programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados
da área a ser pintada. Considere que a cobertura da tinta é de 1 litro para cada 3 metros quadrados e que
a tinta é vendida em latas de 18 litros, que custam R$ 80,00. Informe ao usuário a quantidades de latas de
tint... |
class Solution:
def XXX(self, x: int) -> int:
if x==0:
return 0
l,r = 1,x
while l<r-1:
mid = (l+r)//2
if mid**2>x:
r = mid
elif mid**2<x:
l = mid
elif mid**2==x:
return mid
ret... |
# Databricks notebook source
# MAGIC %md-sandbox
# MAGIC
# MAGIC <div style="text-align: center; line-height: 0; padding-top: 9px;">
# MAGIC <img src="https://databricks.com/wp-content/uploads/2018/03/db-academy-rgb-1200px.png" alt="Databricks Learning" style="width: 600px">
# MAGIC </div>
# COMMAND ----------
# M... |
# Python 3 program to find lexicographically
# next string
def nextWord(s):
# If string is empty.
if (s == " "):
return "a"
# Find first character from right
# which is not z.
i = len(s) - 1
while (s[i] == 'z' and i >= 0):
i -= 1
# If all characters are 'z', append
# an 'a' at the end.
if (i == -1):
... |
list1 = [5, 7, 3]
#print(5 in list1)
print(55 in list1)
if 5 in list1:
print("Yes its in list")
print(88 not in list1)
if 66 not in list1:
print("Not in listt") |
# AUTOGENERATED! DO NOT EDIT! File to edit: 00_core.ipynb (unless otherwise specified).
__all__ = ['first_function']
# Cell
def first_function(nom):
return(f'{nom} ets burro') |
web3 = Web3(Web3.HTTPProvider('https://kovan.infura.io/v3/<infura_project_id>'))
abi = '[{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"description","outputs":[{"internalType":"string","name":"","type":"string... |
"""
Helper functions
"""
def match_client(project_data, client_name):
"""
Given a project's json data, sees if the client name matches
"""
if client_name is None:
client_name = ""
if "clientName" in project_data and project_data["clientName"] == client_name:
return True
return ... |
algo = input('Digite algo: ')
print(type(algo))
print('É somente numeros:', algo.isnumeric())
print('É somente letras:', algo.isalpha())
print('É um alphanumerico:', algo.isalnum())
print('Está so com letras mainúsculas', algo.islower())
print('Está só com letras maiúsculas', algo.isupper())
print('Está capitalizada: ... |
# Semantic versioning
# MAJOR.MINOR.PATCH
__version__ = '1.1.1'
|
# These actually do something important...
def do_this():
print('do_this')
def do_that():
print('do_that')
def do_three():
print('do_three')
# These next four functions do the same thing
def first(x):
if x == 'one':
do_this()
else:
if x == 'two':
do_that()
... |
# Populating Next Right Pointers in Each Node II
# Definition for a Node.
class Node:
def __init__(self, val = 0, left = None, right = None, next = None):
self.val = val
self.left = left
self.right = right
self.next = next
def __repr__(self):
left = "<EMPTY>" if self.lef... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.