content stringlengths 7 1.05M |
|---|
##
## This is my template descripton...
def main():
"""This is the 'main()' for this module. I will put
my description of what this does here..."""
print('Welcome to my Python template!')
##
## Call the 'main()' function...
if __name__ == '__main__':
main()
##
## End of file...
|
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
self.res = float('-inf')
def get_val(node):
if not node:
return 0
left = max(0,... |
# %% [1480. Running Sum of 1d Array](https://leetcode.com/problems/running-sum-of-1d-array/)
class Solution:
def runningSum(self, nums: List[int]) -> List[int]:
return itertools.accumulate(nums)
|
# Paint costs
##############################
#### Problem Description #####
##############################
# You are getting ready to paint a piece of art. The canvas and brushes that you want to use will cost 40.00. Each color of paint that you buy is an additional 5.00. Determine how much money you will need based ... |
def add_new_objects():
for object_type, desc, position in new_objects:
desc['position']=position
objs_in_position = get_objects_by_coords(position)
all_interactable = True
for obj_in_position in objs_in_position:
if not game_objects[obj_in_position]['interactable']:
... |
# 入力
A, B, K = map(int, input().split())
# 出力
ans = [n for n in range(A, 0, -1) if A % n == B % n == 0][K - 1]
print(ans)
|
#All Configurations
FILE_DUPLICATE_NUM = 2 # how many replications stored
FILE_CHUNK_SIZE = 1024*1024 # 1KB, the chunk size, will be larger when finishing debugging
HEADER_LENGTH = 16 # header size
SAVE_FAKE_LOG = False # for single point failure, will greatly reduce the performance
IGNORE_LOCK = True # for test... |
# Day of Week That Is k Days Later
# Days of the week are represented as three-letter strings.
# "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
# Write a javaScript function solution that, given a string
# S representing the day of the week and an integer K
# (between 0 and 500), returns the day of the week that
# is... |
class Accounts:
def __init__(self, first_name, last_name, user_name, password):
self.first_name = first_name
self.last_name = last_name
self.user_name = user_name
self.password = password
user_accounts = []
def save_account(self):
'''
this is a save function... |
sexo = ''
while sexo != 'M' and sexo != 'F':
sexo = str(input('Informe seu sexo: [M/F]: ')).upper()
if sexo != 'M' and sexo != 'F':
print('Opção inválida! Seleciona a letra correspondente.')
if sexo == 'M':
print('Masculino')
if sexo == 'F':
print('Feminino')
print('O sexo escolhi... |
def pyramid_pattern(n):
a = 2 * n-2
for i in range(0, n):
for j in range(0, a):
print(end=" ")
a = a-1
for j in range(0, i+1):
print("*", end=" ")
print("\r")
print(pyramid_pattern(10))
|
#!/usr/bin/python3
if __name__ == "__main__":
# open text file to read
file = open('write_file.txt', 'a')
# read a line from the file
file.write('This is a line appended to the file\n')
file.close()
file = open('write_file.txt', 'r')
data = file.read()
print(data)
file.close() |
load("@rules_proto//proto:repositories.bzl", "rules_proto_dependencies", "rules_proto_toolchains")
load("@rules_jvm_external//:defs.bzl", "maven_install")
load("@rules_jvm_external//:specs.bzl", "maven")
def _clojure_toolchain(ctx):
return [platform_common.ToolchainInfo(
runtime = ctx.attr.classpath,
... |
"""
Exceptions
"""
# Commands
class UsageError(Exception):
"""To indicate a command-line usage error"""
def __init__(self, *a, **kw):
self.print_help = kw.pop('print_help', True)
super(UsageError, self).__init__(*a, **kw)
# Settings
class ConfigurationError(Exception):
def __init__(self... |
for c in range(0, 6):
print('oi')
for b in range (0, 6):
print(b)
print('fim')
for b in range (6, 0, -1):
print(b)
print('fim')
n= int(input('Digite um numero: '))
for c in range(0, n):
print(c)
print('fim')
i = int(input('Inicio: '))
f = int(input('fim: '))
p = int(input('passos: ')... |
def leiaDinheiro(msg):
while True:
valor = input(msg).strip().replace(',', '.')
temp = valor
if temp.replace('.', '').isnumeric():
return float(valor)
print("\033[31mValor Inválido\033[m\n") |
#ex10 p.64 what was that?
# Examples of tabbed list, inline new line char, and escape sequence test
# Tabbed list example output
tlist= """
\t * item 1
\t * item 2
\t * item 3 """
print("This is a tabbed list:", tlist)
#print()
print("Split line after THIS,\nthe above is on it's own line")
print("This is a backsla... |
gritos = 3
soma = 0
while gritos > 0:
entrada = input()
if entrada == 'caw caw':
print(soma)
soma = 0
gritos -= 1
continue
entrada = int("".join(map(lambda x: '0' if x == '-' else '1', entrada)), 2)
soma += entrada
|
start_node = '0'
end_node = '8'
def a_star(start_node, end_node):
open_set = set(start_node)
closed_set = set()
g = {} # Store distance from start node.
parents = {} # Parents contain an adjacent map of all nodes.
# Distance of start node from itself is zero
g[start_node] = 0
parents[start_node] = start... |
# -*- coding: utf-8 -*-
"""
Implements of URLs manipulation.
"""
def remove_starting_backward_slash(value: str):
"""
Removes backward slash at the begin of string.
"""
if value.startswith('\\'):
return value[1:]
return value
def add_trailing_slash(value):
"""
Add slash to the en... |
data = open("day6.txt").read().split("\n\n")
def part_one():
total = 0
for group in data:
total += len(set(list(group.replace("\n", ""))))
return total
def part_two():
total = 0
for group in data:
total += len(set.intersection(*map(set, group.split())))
return total
print(p... |
print()
name = 'abc'.upper()
def get_name():
name = 'def'.upper()
print(f"inside: {name}")
get_name()
print(f"Outside: {name}")
print()
def get_name():
global name
name = 'def'.upper()
print(f"inside: {name}")
get_name()
print(f"Outside: {name}")
def get_name():
global name
#but
... |
# Read from a text file
#Open the file, read the value and close the file
f = open("output.txt","r")
text=f.read()
f.close()
print(text) |
botamusique = None
playlist = None
user = ""
is_proxified = False
dbfile = None
db = None
config = None
bot_logger = None
music_folder = ""
tmp_folder = ""
|
class Solution:
def postorderTraversal(self, root):
if root is None:
return []
traversal = []
root.parent = None
node = root
while node is not None:
while (node.left is not None or node.right is not None):
if node.left is... |
'''
Given a binary tree, return the preorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively?
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init_... |
t = [[3-i for i in range(3)] for j in range (3) ]
s = 0
for i in range (3):
s += t[i][i]
print(s)
#==============================
x = 1
x = x == x
print(x)
# ==============================
var = 0
while var < 6:
var += 1
if var % 2 == 0:
continue
print("#")
# ==========... |
# _*_ coding=utf-8 _*_
__author__ = 'lib.o'
max_title_length = 200
max_tags_length = 200
max_tag_length = 32
max_summary_length = 500
title = u"My blog"
second_title = u"this is my blog"
article_num_per_page = 25
|
class User:
"""
This class saves user's ids and states
"""
id = None
state = 0
def __init__(self, vk_id):
"""
Saves user's id
:param vk_id: User's vk id
"""
self.id = vk_id
print("New User with id: " + str(self.id))
def __str__(self):
... |
class Entity:
word = ""
start = 0
end = 0
ent_type = ""
def __init__(self, word, start, end, ent_type) :
self.word = word
self.start = start
self.end = end
self.ent_type = ent_type
def __str__(self) :
return self.word
def __repr__(self) :
... |
#function within function
def operator(op_text):
def add_num(num1,num2):
return num1+num2
def subtract_num(num1,num2):
return num1-num2
if op_text == '+':
return add_num
elif op_text == '-':
return subtract_num
else:
return None
# driver code
if __name__ == '__main__':
add_fn=operator('... |
iss_orbit_apogee = 417 * 1000 # Km to m
iss_orbit_perigee = 401 * 1000 # Km to m
earth_mu = 3.986e14 # m^3/s^-2
earth_r = 6.378e6 # m
dist = earth_r + iss_orbit_perigee
grav = earth_mu / dist**2
print(grav) |
class Compatibility():
def dir_ftp_to_windows(dir):
return dir.replace("/", "\\")
def dir_windows_to_ftp(dir):
return dir.replace("\\", "/") |
# Process sentence into array of acceptable words
def ProcessSentence(width, sentence):
pWords = []
for word in sentence.split(' '):
if len(word) <= (width - 4):
pWords.append(word)
else:
x = word
while len(x) > (width - 4):
pWords.append(x[:w... |
def definition():
"""
Verbose view of courses, for UI.
"""
sql = """
SELECT CONCAT(
ISNULL(a.qualification + ' ', ''),
a.description) as short_name, --standard name
a.pathway, c.aos_code, c.curriculum_id,
a.qualification as award,
a.qualification,
ISNULL(conf.chil... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def hasPathSum(self, root, sum):
if root:
return self.recursive(root, sum)
return False
def recursive(self, node,... |
class TransactWithCentralOptions(object, IDisposable):
"""
Options to customize Revit behavior when accessing the central model.
TransactWithCentralOptions()
"""
def Dispose(self):
""" Dispose(self: TransactWithCentralOptions) """
pass
def GetLockCallback(self):
... |
'''
8 * 9 ** (number - 1) all mod 1000000007
Status: Accepted
'''
###############################################################################
def main():
"""Read input and print output"""
modulus = 1000000007
for _ in range(int(input())):
print((8 * pow(9, int(input()) - 1, modulus)) % modul... |
def test():
# only check that the code runs and nwbfile.identifier is in the last line of the solution
assert "nwbfile.identifier" in __solution__.strip().splitlines()[-1], "Are you printing the session identifier?"
__msg__.good("Well done!")
|
x = 12
if x < 10:
print("x is less than 10")
elif x >= 10:
print("x is greater than or equal to 10") |
"""
SAN.AC.learning
~~~
Trains the voice in the given speech list.
Analyze speech files and retrieve the knowledge about this voice.
Finally, store the parameters of this voice to parody in the future.
:copyright: 2017 by Nhut Hai Huynh.
:license: MIT, see LICENSE for more details.
"""
|
#!/usr/bin/python3
"""
Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 2^31.
Find the maximum result of ai XOR aj, where 0 ≤ i, j < n.
Could you do this in O(n) runtime?
"""
class Solution:
def findMaximumXOR(self, nums):
"""
Brute force: O(n^2)
constrinat: 32 bi... |
# My Twitter App Credentials
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = "" |
class ResponseTimeoutException(Exception):
"""Raised when no 'ok' response is received from the pyboard"""
class PyBoardError(Exception):
"""
Raised in liue of an exception raised on a remote PyBoard
See the example ":ref:`examples.basic.remote-exception`" for more
details.
"""
|
# 문제: 55. Jump Game
# 링크: https://leetcode.com/problems/jump-game/
# 시간/공간: 480ms / 15.4MB
# 참고: https://leetcode.com/problems/jump-game/discuss/596454/Python-Simple-solution-with-thinking-process-Runtime-O(n)
class Solution:
def canJump(self, nums: List[int]) -> bool:
last_pos = len(nums) - 1 # 고려할 마지막 ... |
nome = 'Caio'
sobrenome = 'Cesar Pereira Neves'
print(len(nome + ' ' + sobrenome))
print(f'Seu nome é {nome} e a primeira letra do seu nome é: "{nome[0]}" e o indice dela é 0')
print(f'Seu nome é {nome} e a segunda letra do seu nome é: "{nome[1]}" e o indice dela é 1')
print(f'Seu nome é {nome} e a terceira letra do ... |
def mostrar(nome):
tam = len(nome) + 4
print('~'*tam)
print(f' {nome}')
print('~'*tam)
#PRINT ESPECIAL
mostrar('Boaventura')
mostrar('Maria Laura')
|
# noinspection PyUnusedLocal
# skus = unicode string
def calculate_offers(bill, item, quantity, offers):
bill = bill.copy()
for offer, price in offers:
bill[item]['offers'].append(
{'items': quantity / offer, 'price': price}
)
quantity = quantity % offer
return bill, ... |
PELVIS = 0
SPINE_NAVAL = 1
SPINE_CHEST = 2
NECK = 3
CLAVICLE_LEFT = 4
SHOULDER_LEFT = 5
ELBOW_LEFT = 6
WRIST_LEFT = 7
HAND_LEFT = 8
HANDTIP_LEFT = 9
THUMB_LEFT = 10
CLAVICLE_RIGHT = 11
SHOULDER_RIGHT = 12
ELBOW_RIGHT = 13
WRIST_RIGHT = 14
HAND_RIGHT = 15
HANDTIP_RIGHT = 16
THUMB_RIGHT = 17
HIP_LEFT = 18
KNEE_LEFT = 19
... |
begin_unit
comment|'# All Rights Reserved.'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You may obtain'
nl|'\n'
comment|'# a copy of the License at'
nl|'\n'
comment|'#... |
class intcode():
def __init__(self):
self.instructionPointer = 0
self.memory = []
self.stopped = False
def loadMemory(self, memList):
self.memory = memList.copy()
def loadProgram(self, programString):
numbers = programString.split(",")
self.memory = list(... |
"""
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
Note:
Bonus point if yo... |
# Problem: https://www.hackerrank.com/challenges/merge-the-tools/problem
def merge_the_tools(string, k):
num_sub = int(len(string)/k)
for sub_num in range(num_sub):
sub = string[sub_num*k:sub_num*k+k]
sub_list, unique_sub_list = list(sub), []
[unique_sub_list.append(letter) for letter i... |
### Model data
class catboost_model(object):
float_features_index = [
0, 1, 2, 5, 6, 7, 8, 10, 12, 13, 14, 15, 16, 17, 20, 22, 24, 27, 28, 31, 32, 33, 34, 35, 37, 38, 39, 46, 47, 48, 49,
]
float_feature_count = 50
cat_feature_count = 0
binary_feature_count = 31
tree_count = 40
float... |
"""
Binary Search Algorithm (Iterative Solution)
"""
def binary_search(a, t):
s, e = 0, len(a) - 1
while s <= e:
i = (s + e) // 2
x = a[i]
if t is x:
return i
elif t < x:
e = i - 1
else:
s = i + 1
return -1
|
# palindrome中间也是palindrome呀
class Solution(object):
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
if not s:
return False
left, right = 0, len(s) - 1
while left < right:
if s[left] != s[right]:
# 不要left... |
def adding_numbers(num1, num2, num3):
print('Have to add three numbers')
print('First Number = {}'.format(num1))
print('Second Number = {}'.format(num2))
print('Third Number = {}'.format(num3))
return num1 + num2 + num3
x = adding_numbers(10, 20, 30)
print('The function returned a value of ... |
'''
>>> increments([1, 5, 7])
[2, 6, 8]
>>> increments([0, 0, 0, 0, 0])
[1, 1, 1, 1, 1]
>>> increments([0.5, 1.5, 1.75, 2.5])
[1.5, 2.5, 2.75, 3.5]
>>> increments([570, 968, 723, 179, 762, 377, 845, 320, 475, 952, 680, 874, 708, 493, 901, 896, 164, 165, 404, 147, 917, 936, 205, 615, 518, 254, 856, 584, 287, 336,... |
def parallel(task_id, file_name, workers, parameters={}):
response = {
'task_id': task_id,
"user_output": "Command received",
'completed': True
}
responses.append(response)
return |
#First
i1 = str(input())
for i in i1:
print(i, end=" ")
#Second
i1 = "anant"
for i in range(0,len(i1)):
if i == len(i1) - 1:
print(i1[i],end="")
else:
print(i1[i], end=" ")
for i in range(0,3):
x = input()
print(x)
#Third
tuples = [
(-2.3391885553668246e-10, 8.473071450645254e-... |
h =float(input("Digite sua altura: "))
p = float(input("Digite seu peso: "))
imc = p/(h*h)
print("seu imc é", imc)
|
img = tf.placeholder(tf.float32, [None, None, None, 3])
cost = tf.reduce_sum(...)
my_img_summary = tf.summary.image("img", img)
my_cost_summary = tf.summary.scalar("cost", cost) |
class Stack:
def __init__(self, name, service_list):
self.name = name
self.service_list = service_list
def services(self):
return [x.attrs() for x in self.service_list]
def serializable(self):
return {
"name": self.name,
"services": self.services()
... |
class Message:
EVENT = "event"
MESSAGE = "message"
UPDATE = "update"
EPHEMERAL = "ephemeral"
|
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
basic usage::
>>> # Here is a quick simhash example
>>> from changanya.simhash import Simhash
>>>
>>> hash1 = Simhash('This is a test string one.')
>>> hash2 = Simhash('This is a test string TWO.')
>>> hash1 # doctest: +ELLIPSIS
<chang... |
maior = 0
menor = 0
for p in range(1, 6):
peso = float(input(f'Peso da {p}ª pessoa: '))
if p == 1:
maior = peso
menor = peso
else:
if peso > maior:
maior = peso
if peso < menor:
menor = peso
print('O maior peso foi de \033[1m{:.1f}Kg\033[m e o menor ... |
expected_output = {
"software-information": {
"package-information": [
{"comment": "EX Software Suite [18.2R2-S1]", "name": "ex-software-suite"},
{
"comment": "FIPS mode utilities [18.2R2-S1]",
"name": "fips-mode-utilities",
},
... |
"""
内置高阶函数
"""
class Employee:
def __init__(self, eid, did, name, money):
self.eid = eid # 员工编号
self.did = did # 部门编号
self.name = name
self.money = money
# 员工列表
list_employees = [
Employee(1001, 9002, "师父", 60000),
Employee(1002, 9001, "孙悟空", 50000),
Employee(10... |
#MenuTitle: Masters Overview
# -*- coding: utf-8 -*-
__doc__="""
Creates a new tab with rows of selected glyphs in all available master layers. Useful for comparing the different weights of a typeface.
"""
Font = Glyphs.font
Font.newTab()
for glyph in Font.selection:
Font.currentTab.layers.append(GSControlLayer(10))
... |
# reassign the dataframe to be the result of the following .loc
# .loc[start_row:end_row, start_column:end_column]
# .loc[:, "Under 5":"18 years"] will return all columns between and including
df["age_bin_0-19"] = df.loc[:, 'Estimate Male Under 5':'Estimate Male 18']
df = DataFrame(np.random.rand(4,5), columns = li... |
class Node:
pass
class ProgramNode(Node):
def __init__(self, declarations):
self.declarations = declarations
class DeclarationNode(Node):
pass
class ExpressionNode(Node):
pass
class ClassDeclarationNode(DeclarationNode):
def __init__(self, idx, features, parent, row , column):
self... |
a, b = map(int, input().split())
b -= 1
print(a * b + 1) |
#!/anaconda3/bin/python
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class LeetCode_21_495(object):
def mergeTwoLists(self, l1, l2):
prehead = ListNode(-1)
prev = prehead
while l1 and l2:
if l1.val <= l2.val:
prev.ne... |
countries = [[('Finland', 'Helsinki')], [('Sweden', 'Stockholm')], [('Norway', 'Oslo')]]
flatten = [p for p in countries for p in p]
dictofcountries = [{'country': flatten[i][0].upper(), 'city': flatten[i][1].upper()} for i in range(len(flatten))]
print(dictofcountries)
|
#!/usr/bin/env python3
# Modify the higher or lower program from this section to keep track of how
# many times the user has entered the wrong number. If it is more than 3
# times, print "That must have been complicated." at the end, otherwise
# print "Good job!"
number = 7
guess = -1
count = 0
print("Guess the numb... |
def test_model_with_one_index():
ddl = """
CREATE table v2.task_requests (
runid decimal(21) not null
,job_id decimal(21) not null
,object_id varchar(100) not null default 'none'
,pipeline_id varchar(100) not null default 'none'
,sequ... |
############################################################
# -*- coding: utf-8 -*-
#
# # # # # # #
# ## ## # ## # #
# # # # # # # # # # #
# # ## # ## ## ######
# # # # # # #
#
# Python-based Tool for interaction with the 10micron mounts
# GUI with PyQT5 fo... |
a, b = map(int, input().split())
# 1≤a, b≤10000
if 1 <= a and b <= 10000:
ans = a * b
if ans % 2 == 0:
print("Even")
else:
print("Odd")
|
def fun1(str1):
fun1(str1)
print("This is " + str1)
fun1("Issue")
|
class DatabaseConnectionInterface(object):
"""Abstract class for DatabaseConnection."""
def GetPoints(self, visit_location):
"""For given visit_location return initial set of points."""
raise NotImplemented()
def GetPoint(self, visit_location, point_name):
"""For given visit_location and Point nam... |
# URI Online Judge 1149
Entrada = input()
Entrada = list(map(int, Entrada.split()))
A = Entrada[0]
A_copy = A
sum = 0
for i in Entrada[1:]:
if i > 0:
N = i
for j in range(0,N):
sum += A_copy + j
print(sum) |
# Copyright 2021 Google LLC
#
# 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 to in writing, ... |
# http://python.coderz.ir/
list=[1,2,3,4,5]
list.append(6)
print(list)
tuple=(1,2,3)
dic={'key1':'A','key2':'B'}
print(dic['key1'])
class Human():
print("human class")
def walking(self):
print("human is walking")
class contact(Human):
print("contact is creating")
def __init__(self,name,f... |
DEFAULT_METADATA_TABLE = 'data'
DEFAULT_USER_TABLE = 'user'
DEFAULT_NAME_COLUMN = 'dataset'
DEFAULT_UPDATE_COLUMN = 'updated_at'
DEFAULT_RESTRICTED_TABLES = [DEFAULT_METADATA_TABLE, DEFAULT_USER_TABLE]
DEFAULT_METADATA_COLUMNS = [
dict(name='id', type_='Integer', primary_key=True),
dict(name='dataset', type_='S... |
#!/usr/bin/env python
# coding: utf-8
# This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).
# # Solution Notebook
# ## Problem: Implement common bit manipulation operations: get_bit, set_bi... |
def lz78(charstream, verbose=False):
dict = {}
p = ""
code = []
i = 0
while True:
c = charstream[i]
try:
dict[p + c]
p = p + c
except (KeyError):
if p == "":
o = 0
else:
o = dict[p... |
for number in range(1001):
string=list(str(number))
sum_of_each_digit=0
for j in range(len(string)):
int_number=int(string[j])
power_of_digit = int_number ** len(string)
sum_of_each_digit += power_of_digit
if number == sum_of_each_digit:
print (number, "Is amstrong Number")
|
spells = {
'levitate': 'Levioso',
'make fire': 'Incendio',
'open locked door': 'Alohomora'
}
# dictionary operators
print(spells['open locked door'])
print(spells['levitate'])
print(spells.keys())
print(dir(spells))
|
'''
12.Tendo como dados de entrada a altura de uma pessoa, construa um algoritmo que calcule seu peso ideal, usando a seguinte fórmula: (72.7*altura) - 58
'''
altura = float(input('Informe sua altura: '))
def peso_ideal(altura):
return (72.7 * altura) - 58
print('Seu peso ideal é ', peso_ideal(altura)) |
class Cleaning():
def __init__(self, df):
self.df = df
pass
def drop_null_cols(self, percent):
"""
A funciton to drop a column if a certain percent of its values
are null
"""
if percent > 1:
percent = percent/100
a = self.df
fo... |
def insertion_sort(array):
for i in range(1, len(array)):
currentValue = array[i]
currentPosition = i
while currentPosition > 0 and array[currentPosition - 1] > currentValue:
array[currentPosition] = array[currentPosition -1]
currentPosition -= 1
array[currentPosition] = currentValue
return array
#... |
class EbWrapper:
def set_eb_raw_json_data(self, eb_raw_json_data: dict):
if not type(eb_raw_json_data).__name__ == 'dict':
raise TypeError('The entered data must be of type dict')
self.eb_raw_json_data = eb_raw_json_data
return self
def get_environment_name(self):
... |
name = data.get('name', 'world')
logger.info("Hello Robin {}".format(name))
hass.bus.fire(name, { "wow": "from a Python script!" })
state = hass.states.get('sensor.next_train_status')
train_status = state.state
if train_status == 'ON TIME':
hass.services.call('light', 'turn_on', { "entity_id" : 'light.lamp', 'co... |
inputString = str(input())
tool = len(inputString)
count_3 = inputString.count('3')
count_2 = inputString.count('2')
count_1 = inputString.count('1')
regularWordage = '1' * count_1 + '2' * count_2 + '3' * count_3
for i in range(0,tool-1) :
if i%2 == 0:
pass
else:
regularWordage = regularWordage... |
oddcompnumlist = []
for i in range(2,10000):
if i%2!=0:
if 2**(i-1)%i!=1:
oddcompnumlist.append(i)
primlist = []
randlist = []
complist = []
for j in range(2,142):
boolist = []
for k in range(2,j):
if j%k != 0:
boolist.append('false')
elif j%k == 0:
... |
#
# PySNMP MIB module VERILINK-ENTERPRISE-NCMJAPISDN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/VERILINK-ENTERPRISE-NCMJAPISDN-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:26:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using... |
__all__ = ["WindowOperator"]
class WindowOperator(Operator):
pass
|
def allinstance(collection, legal_type):
"""
Checks the type of all items in a collection match a specified type
Parameters
----------
collection: list, tuple, or set
legal_type: type
Returns
-------
bool
"""
if not isinstance(collection, (list, tuple, set)):
illegal = type(collection).__name__
raise(T... |
# Read from the file words.txt and output the word frequency list to stdout.
with open('words.txt', 'r') as f:
line = f.readline()
word_occ_dict = {}
while line:
tokens = list( line.split() )
for t in tokens:
word_occ_dict[t] = word_occ_dict.get(t, ... |
# imports
def fifty_ml_heights(init_vol, steps, vol_dec):
vols = []
heights = []
# these values originate from Excel spreadsheet "Exp803..."
print (init_vol)
b = 0
m = 0.0024
if init_vol > 51000:
offset = 14 # model out of range; see sheet
else:
offset = 7 # mm Need ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.