content stringlengths 7 1.05M |
|---|
'''
Constants
---
Constants used in other scripts. These are mostly interpretations of fields
provided in the Face2Gene jsons.
'''
HGVS_ERRORDICT_VERSION = 0
# Bucket name, from where Face2Gene vcf and json files will be downloaded
AWS_BUCKET_NAME = "fdna-pedia-dump"
# caching directory
CACHE_DIR = ".cache"
# tests... |
x = float(input("Digite x: "))
y = float(input("Digite y: "))
if 0 <= x <= 8 and 0 <= y <= 8:
if (0 <= x < 1 or 7 < x <= 8) and (0 <= y < 2): #pescoço
print("branco")
elif 3.5 <= x <= 4.5 and 3.5 <= y <= 4.5: #nariz
print("branco")
elif (1 <= x <= 3 or 5 <= x <= 7) and (7.25 <= y <= 7.75): ... |
"""
DAC typing class
ESP32 has two 8-bit DAC (digital to analog converter) channels, connected to GPIO25 (Channel 1) and GPIO26 (Channel 2).
The DAC driver allows these channels to be set to arbitrary voltages.<br The DAC channels can also be driven with DMA-style written sample data, via the I2S driver when using the... |
def f(x):
return ((2*(x**4))+(3*(x**3))-(6*(x**2))+(5*x)-8)
def reachEnd(previousm,currentm):
if abs(previousm - currentm) <= 10**(-6):
return True
return False
def printFormat(a,b,c,m,count):
print("Step %s" %count)
print("a=%.6f b=%.6f c=%.6f" %(a,b,c))
print("f(a)=%.6f f(... |
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
result = []
rows, columns = len(matrix), len(matrix[0])
up = left = 0
right = columns-1
down = rows-1
while len(result) < rows*columns:
for col in r... |
class NoProxy:
def get(self, _):
return None
def ban_proxy(self, proxies):
return None
class RateLimitProxy:
def __init__(self, proxies, paths, default=None):
self.proxies = proxies
self.proxy_count = len(proxies)
self.access_counter = {
path: {"limit":... |
#MARCELO CAMPOS DE MEDEIROS
#ADS UNIFIP P1 2020
#LISTA 02
'''
1- Faça um programa que solicite ao usuário o valor do litro de combustível (ex. 4,75)
e quanto em dinheiro ele deseja abastecer (ex. 50,00). Calcule quantos litros de
combustível o usuário obterá com esses valores.
'''
valor_gas = float(input('Qual o valo... |
months_json = {
"1": "January",
"2": "February",
"3": "March",
"4": "April",
"5": "May",
"6": "June",
"7": "July",
"8": "August",
"9": "September",
"01": "January",
"02": "February",
"03": "March",
"04": "April",
"05": "May",
"06": "June",
"07": "July",
"08": "August",
"09": "Septem... |
#coding: utf-8
'''
@Time: 2019/4/25 11:15
@Author: fangyoucai
'''
|
__all__ = ['EncryptException', 'DecryptException', 'DefaultKeyNotSet', 'NoValidKeyFound']
class EncryptException(BaseException):
pass
class DecryptException(BaseException):
pass
class DefaultKeyNotSet(EncryptException):
pass
class NoValidKeyFound(DecryptException):
pass
|
SCRABBLE_LETTER_VALUES = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10
}
# The first step is to implement some code that allows us to calculate the sco... |
#
# @lc app=leetcode id=86 lang=python3
#
# [86] Partition List
#
# https://leetcode.com/problems/partition-list/description/
#
# algorithms
# Medium (43.12%)
# Likes: 1981
# Dislikes: 384
# Total Accepted: 256.4K
# Total Submissions: 585.7K
# Testcase Example: '[1,4,3,2,5,2]\n3'
#
# Given the head of a linked l... |
# Cálculo de IMC
print("Vamos calcular seu IMC?")
nome = input("Digite o seu nome: ")
peso = float(input("Olá, {}, agora digite seu peso (em Kg, Ex: 68.9): " .format(nome)))
altura = float(input("Digite sua altura (em m, Ex: 1.80): "))
media = peso / (altura * altura)
print('Seu IMC é: {:.1f}'.format(media))
if media ... |
with open("input.txt", "r") as input_file:
input = input_file.read().split("\n")
passwords = list(map(lambda line: [list(map(int, line.split(" ")[0].split("-"))), line.split(" ")[1][0], line.split(" ")[2]], input))
valid = 0
for password in passwords:
count_letter = password[2].count(password[1])
if pass... |
music = {
'kb': '''
Instrument(Flute)
Piece(Undine, Reinecke)
Piece(Carmen, Bourne)
(Instrument(x) & Piece(w, c) & Era(c, r)) ==> Program(w)
Era(Reinecke, Romantic)
Era(Bourne, Romantic)
''',
'queries': '''
Program(x)
''',
}
life = {
'kb': '''
Musician(x) ==> Stressed(x)
(Student(x) & Te... |
"""3.3 Stack of Plates: Imagine a (literal) stack of plates. If the stack gets too high, it might topple.
Therefore, in real life, we would likely start a new stack when the previous stack exceeds some
threshold. Implement a data structure SetOfStacks that mimics this. SetOfStacks should be
composed of several stacks a... |
myl1 = []
num = int(input("Enter the number of elements: "))
for loop in range(num):
myl1.append(input(f"Enter element at index {loop} : "))
print(myl1)
print(type(myl1))
myt1 = tuple(myl1)
print(myt1)
print(type(myt1))
print("The elements of tuple object are: ")
for loop in myt1:
print(loop) |
# Scrapy settings for scraper project
BOT_NAME = 'scraper'
SPIDER_MODULES = ['scraper.spiders']
NEWSPIDER_MODULE = 'scraper.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Googlebot-News'
# Obey robots.txt rules
ROBOTSTXT_OBEY = True
# MONGO URI for accessing... |
## Data Categorisation
'''
1) Whole Number (Ints) - 100, 1000, -450, 999
2) Real Numbers (Floats) - 33.33, 44.01, -1000.033
3) String - "Bangalore", "India", "Raj", "abc123"
4) Boolean - True, False
Variables in python are dynamic in nature
'''
a = 10
print(a)
print(type(a))
a = 10.33
print(a)
print(type(a))
a =... |
class RelationType(object):
ONE_TO_MANY = "one_to_many"
ONE_TO_ONE = "one_to_one"
class Relation(object):
def __init__(self, cls):
self.cls = cls
class HasOne(Relation):
def get(self, id):
return self.cls.get(id=id)
class HasMany(Relation):
def get(self, id):
value = []... |
# Time: 03/18/21
# Author: HammerLi
# Tags: [Simulation]
# Title: 字符串匹配
# Content:
# 给出一个字符串和多行文字,在这些文字中找到字符串出现的那些行。
# 你的程序还需支持大小写敏感选项:当选项打开时,表示同一个字母的大写和小写看作不同的字符;
# 当选项关闭时,表示同一个字母的大写和小写看作相同的字符。
tar = input()
strict = bool(int(input()))
n = int(input())
for i in range(0, n):
src = input()
if strict:
... |
"""
Given an array of integers, find the subset of non-adjacent elements with the maximum sum.
Calculate the sum of that subset. It is possible that the maximum sum is , the case when all elements are negative.
"""
def maxSubsetSum(arr):
n = len(arr) # n = length of the array
dp = [0]*n # create a dp ... |
description = 'Alphai alias device'
group = 'lowlevel'
devices = dict(
alphai = device('nicos.devices.generic.DeviceAlias'),
)
|
{
'targets': [
{
'target_name': 'overlay_window',
'sources': [
'src/lib/addon.c',
'src/lib/napi_helpers.c'
],
'include_dirs': [
'src/lib'
],
'conditions': [
['OS=="win"', {
'defines': [
'WIN32_LEAN_AND_MEAN'
],
... |
# ---------------------------------------------------------------------
# Gufo Labs Loader:
# a plugin
# ---------------------------------------------------------------------
# Copyright (C) 2022, Gufo Labs
# ---------------------------------------------------------------------
class APlugin(object):
name = "a"
... |
# -*- coding: utf-8 -*-
# ______________________________________________________________________________
def boolean_func(experiment):
"""Function that returns True when an experiment matches and False otherwise.
Args:
experiment (:class:`~skassist.Experiment`): Experiment that is to be tested.
... |
class InvalidProxyType(Exception): pass
class ApiConnectionError(Exception): pass
class ApplicationNotFound(Exception): pass
class SqlmapFailedStart(Exception): pass
class SpiderTestFailure(Exception): pass
class InvalidInputProvided(Exception): pass
class InvalidTamperProvided(Exception): pass
class Port... |
class CreatePickupResponse:
def __init__(self, res):
"""
Initialize new instance from CreatePickupResponse class
Parameters:
res (dict, str): JSON response object or response text message
Returns:
instance from CreatePickupResponse
"""
self.fromR... |
test = { 'name': 'q1_3',
'points': 1,
'suites': [ { 'cases': [ {'code': '>>> type(max_estimate) in set([int, np.int32, np.int64])\nTrue', 'hidden': False, 'locked': False},
{'code': '>>> max_estimate in observations.column(0)\nTrue', 'hidden': False, 'locked': False}],... |
TYPES = {"int","float","str","bool","list"}
MATCH_TYPES = {"int": int, "float": float, "str": str, "bool": bool, "list": list}
CONSTRAINTS = {
"is_same_type": lambda x, y: type(x) == type(y),
"int" :{
"min_inc": lambda integer, min: integer >= min,
"min_exc": lambda integer, ... |
def main():
video = "NET20070330_thlep_1_2"
file_path = "optical_flow_features_train/" + video
optical_flow_features_train = open(file_path + "/optical_flow_features_train.txt", "r")
clear_of_features_train = open(file_path + "/clear_opt_flow_features_train.txt", "w")
visual_ids = []
for line ... |
prize_file_1 = open("/Users/MatBook/Downloads/prize3.txt")
List = []
prizes = []
for line in prize_file_1:
List.append(int(line))
first_line = List.pop(0)
for i in List:
print(i)
for j in List:
if i + j == first_line:
prizes.append((i,j))
print (... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
template = """/*
* * search_dipus
* * ~~~~~~~~~~~~~~
* *
* * Dipus JavaScript utilties for the full-text search.
* * This files is based on searchtools.js of Sphinx.
* *
* * :copyright: Copyright 2007-2012 by the Sphinx team.
* * :license: BSD, see LICENSE ... |
def classfinder(k):
res=1
while res*(res+1)//2<k:
res+=1
return res
# cook your dish here
for t in range(int(input())):
#n=int(input())
n,k=map(int,input().split())
clas=classfinder(k)
i=k-clas*(clas-1)//2
str=""
for z in range(n):
if ... |
class Config:
conf = {
"labels": {
"pageTitle": "Weatherman V0.0.1"
},
"db.database": "weatherman",
"db.username": "postgres",
"db.password": "postgres",
"navigation": [
{
"url": "/",
"name": "Home"
}... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:MT
@file:__init__.py.py
@time:2021/8/21 23:02
""" |
def is_leap(year):
leap = False
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
leap = True
else:
leap = False
else:
leap = True
return leap
year = int(input())
print(is_leap(year))
'''
In the Gregorian calend... |
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
occ = set()
n = len(s)
max_length = 0
cur = 0
for i in range(n):
if i != 0:
# 左指针向右移动一格,移除一个字符
occ.remove(s[i-1])
while cur < n and s[cur] not in occ:
... |
"""HackerEarth docs constants"""
DOC_URL_DICT = {
# 'doc_name': 'doc_url1',
# 'doc_name': 'doc_url2',
}
|
class Solution(object):
def maxSubArray1(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
this = maxsum = 0
for i in range(len(nums)):
this += nums[i]
if this > maxsum:
maxsum = this
elif this < 0:
... |
"""
EVEN IN RANGE: Use range() to print all the even numbers from 0 to 10.
"""
for number in range(11):
if number % 2 == 0:
if number == 0:
continue
print(number)
|
# -*- coding: utf-8 -*-
class DummyTile:
def __init__(self, pos, label=None):
self.pos = pos
# Label tells adjacent mine count for this tile. Int between 0...8 or None if unknown
self.label = label
self.checked = False
self.marked = False
self.adj_mines = None
... |
##Write code to switch the order of the winners list so that it is now Z to A. Assign this list to the variable z_winners.
winners = ['Alice Munro', 'Alvin E. Roth', 'Kazuo Ishiguro', 'Malala Yousafzai', 'Rainer Weiss', 'Youyou Tu']
z_winners = winners
z_winners.reverse()
print(z_winners) |
class Node:
def __init__(self, value, next_=None):
self.value = value
self.next = next_
class Stack:
def __init__(self, top=None):
self.top = top
def push(self, value):
self.top = Node(value, self.top)
def pop(self):
if self.top:
ret = self.top.value
self.top = self.top.next
... |
class Vector:
#exercise 01
def __init__(self,inputlist):
self._vector = []
_vector = inputlist
#exercise 02
def __str__(self):
return "<" + str(self._vector).strip("[]") + ">"
#exercise 03
def dim(self):
return len(self._vector)
#exercise 04
def get... |
s = 0
cont = 0
for c in range(1, 501, 2):
if c % 3 == 0:
cont += 1
s += c
print('A soma ente todos os {} ímpares múltiplos de 3 entre 1 e 500 é {}.'.format(cont, s)) |
# Protein sequence given
seq = "MPISEPTFFEIF"
# Split the sequence into its component amino acids
seq_list = list(seq)
# Use a set to establish the unique amino acids
unique_amino_acids = set(seq_list)
# Print out the unique amino acids
print(unique_amino_acids)
|
DEPTH = 16 # the number of filters of the first conv layer of the encoder of the UNet
# Training hyperparameters
BATCHSIZE = 16
EPOCHS = 100
OPTIMIZER = "adam"
|
#
# @lc app=leetcode id=160 lang=python
#
# [160] Intersection of Two Linked Lists
#
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# 参考:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/solution/tu-jie-xian... |
string=input("Enter a string:")
length=len(string)
mid=length//2
rev=-1
for a in range(mid):
if string[a]==string[rev]:
a+=1
rev=-1
else:
print(string,"is a palindrome")
break
else:
print(string,"is not a palindrome")
|
""" Given two arrays A and B of equal size, the advantage of A with respect to B
is the number of indices i for which A[i] > B[i].
Return any permutation of A that maximizes its advantage with respect to B.
Example 1:
Input: A = [2,7,11,15], B = [1,10,4,11] Output: [2,11,7,15]
ID... |
"""
Problem 10:
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.Find the sum of
all the primes below two million.
"""
sum = 0
size = 2000000
slots = [True for i in range(size)]
slots[0] = False
slots[1] = False
for stride in range(2, size // 2):
pos = stride
while pos < size - stride:
... |
# Argus was charged with guarding Io, which is not an ordinary cow. Io is quite an explorer, and she wanders off rather frequently, making Argus' life stressful. So the cowherd decided to construct an enclosed pasture for Io.
# There are nnn trees growing along the river, where Argus tends Io. For this problem, the riv... |
''' Compute a digest message '''
def answer(digest):
''' solve for m[1] '''
message = []
for i, v in enumerate(digest):
pv = message[i - 1] if i > 0 else 0
m = 0.1
a = 0
while m != int(m):
m = ((256 * a) + (v ^ pv)) / 129.0
a += 1
m = int(m)
... |
"""
Obkey package informations.
This file is a part of Openbox Key Editor
Code under GPL (originally MIT) from version 1.3 - 2018.
See Licenses information in ../obkey .
"""
MAJOR = 1
MINOR = 3
PATCH = 2
__version__ = "{0}.{1}.{2}".format(MAJOR, MINOR, PATCH)
__description__ = 'Openbox Key Editor'
__long_des... |
'''程序的状态码'''
OK = 0
class LogicErr(Exception):
code = None
data = None
def __init__(self,data=None):
self.data = data or self.__class__.__name__ # 如果 data 为 None, 使用类的名字作为 data 值
def gen_logic_err(name, code):
'''生成一个新的 LogicErr 的子类 (LogicErr 的工厂函数)'''
return type(name, (LogicErr,), {'... |
'''
http://pythontutor.ru/lessons/ifelse/problems/bishop_move/
Шахматный слон ходит по диагонали.
Даны две различные клетки шахматной доски, определите, может ли слон попасть с первой клетки на вторую одним ходом.
'''
a_x = int(input())
a_y = int(input())
b_x = int(input())
b_y = int(input())
if abs(a_x - b_x) == abs... |
# Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre a sua média.
nome = str(input("Digite o nome do(a) aluno(a): "))
not1 = float(input("Digite a 1ª nota de {}: ".format(nome)))
not2 = float(input("Digite a 2ª nota de {}: ".format(nome)))
media = (not1 + not2) / 2
print("Já que {} tirou {} ... |
# October 27th, 2021
# INFOTC 4320
# Josh Block
# Challenge: Anagram Alogrithm and Big-O
# References: https://bradfieldcs.com/algos/analysis/an-anagram-detection-example/
print("===Anagram Dector===")
print("This program determines if two words are anagrams of each other\n")
first_word = input("Please enter first wo... |
a=int(input())
b=int(input())
c=int(input())
if(a>b and a>c):
print("number 1 is greatest")
elif(b>a and b>c):
print("number 2 is greatest")
else:
print("number 3 is greatest")
|
# x_2_6
#
# ヒントを参考に「a」「b」「c」「d」がそれぞれどんな値となるかを予想してください
# ヒント
print(type('桃太郎'))
print(type(10))
print(type(12.3))
a = type('777') # => str
b = type(10 + 3.5) # => float
c = type(14 / 7) # => float
d = type(10_000_000) # => int
# print(a)
# print(b)
# print(c)
# print(d)
|
def main():
# Create and print a list named fruit.
fruit_list = ["pear", "banana", "apple", "mango"]
print(f"original: {fruit_list}")
fruit_list.reverse()
print(f"Reverse {fruit_list}")
fruit_list.append("Orange")
print(f"Append Orange {fruit_list}")
pos = fruit_list.index("apple")
... |
__author__ = "Eric Dose :: New Mexico Mira Project, Albuquerque"
# PyInstaller (__init__.py file should be in place as peer to .py file to run):
# in Windows Command Prompt (E. Dose dev PC):
# cd c:\Dev\prepoint\prepoint
# C:\Programs\Miniconda\Scripts\pyinstaller app.spec
|
"""
Spring.
Click, drag, and release the horizontal bar to start the spring.
"""
# Spring drawing constants for top bar
springHeight = 32 # Height
left = 0 # Left position
right = 0 # Right position
max = 200 # Maximum Y value
min = 100 # Minimum Y value
over = False # If mouse over
move = False ... |
# 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 ... |
"""
Space : O(1)
Time : O(n**2)
"""
class Solution:
def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
if t == 0 and len(nums) == len(set(nums)):
return False
for i, cur_val in enumerate(nums):
for j in range(i+1, min(i+k+1, len(nums))):
... |
def make_interval(depth, depth_integer_multiplier, num, step_num, start_val):
all_groups_str = "[\n"
for n in range(num):
all_groups_str += "\t["
for d in range(depth):
val = str(start_val * pow(depth_integer_multiplier, d))
if d == depth - 1:
i... |
class Config:
__instance = None
@staticmethod
def get_instance():
""" Static access method. """
if Config.__instance == None:
Config()
return Config.__instance
def __init__(self):
if Config.__instance != None:
raise Exception("This class can't b... |
class AFGR:
@staticmethod
def af_to_gr(dict_af):
dict_swap = {}
for keys in dict_af:
dict_swap[keys] = []
for list in dict_af[keys]:
dict_swap[keys].insert(len(dict_swap[keys]), list[0])
dict_swap[keys].insert(len(dict_swap[keys]), list[1]... |
animals = ["Gully", "Rhubarb", "Zephyr", "Henry"]
for index, animal in enumerate(animals):
# if index % 2 == 0:
# continue
# print(animal)
print(f"{index+1}.\t{animal}")
|
class FittingAndAccessoryCalculationType(Enum, IComparable, IFormattable, IConvertible):
"""
Enum of fitting and accessory pressure drop calculation type.
enum FittingAndAccessoryCalculationType,values: CalculateDefaultSettings (2),CalculatePressureDrop (1),Undefined (0),ValidateCurrentSettings (4)
""... |
"""
1232. 缀点成线
在一个 XY 坐标系中有一些点,我们用数组 coordinates 来分别记录它们的坐标,
其中 coordinates[i] = [x, y] 表示横坐标为 x、纵坐标为 y 的点。
请你来判断,这些点是否在该坐标系中属于同一条直线上,是则返回 true,否则请返回 false。
"""
class XYCheck:
def __init__(self, coordinates):
self.a = self.b = 0
x1, y1 = coordinates[0]
x2, y2 = coordinates[1]
self.... |
## Python Crash Course
# Exercise 6.4: Glossary#2:
# Now that you know how to loop through a dictionary, clean up the code from Exercise 6-3 (page 102)
# by replacing your series of print statements with a loop that runs through the dictionary’s keys and values.
# Whe... |
# Given an integer array arr, count element x such that x + 1 is also in arr.
# If there're duplicates in arr, count them seperately.
# Example 1:
# Input: arr = [1,2,3]
# Output: 2
# Explanation: 1 and 2 are counted cause 2 and 3 are in arr.
# Example 2:
# Input: arr = [1,1,3,3,5,5,7,7]
# Output: 0
# Explanatio... |
ES_HOST = 'localhost:9200'
ES_INDEX = 'pending-uberon'
ES_DOC_TYPE = 'anatomy'
API_PREFIX = 'uberon'
API_VERSION = ''
|
class Solution:
def solve(self, nums):
integersDict = {}
for i in range(len(nums)):
try:
integersDict[nums[i]] += 1
except:
integersDict[nums[i]] = 1
for integer in integersDict:
if integersDict[integer] != 3:
... |
class CharacterRaceList(object):
DEVA = 'DEVA'
DRAGONBORN = 'DRAGONBORN'
DWARF = 'DWARF'
ELADRIN = 'ELADRIN'
ELF = 'ELF'
GITHZERAI = 'GITHZERAI'
GNOME = 'GNOME'
GOLIATH = 'GOLIATH'
HALFELF = 'HALFELF'
HALFLING = 'HALFLING'
HALFORC = 'HALFORC'
HUMAN = 'HUMAN'
MINOTAUR... |
# 给定两个数组,编写一个函数来计算它们的交集。
class Solution:
def intersect(self, nums1: list, nums2: list) -> list:
inter = set(nums1) & set(nums2)
print(inter)
l = []
for i in inter:
l += [i] * min(nums1.count(i), nums2.count(i))
print(l)
return l
nums1 = [1, 2, 2, 1... |
print('\033[32m{:=^60}'.format('\033[36m Dividindo valores em várias listas \033[32m'))
lista = []
par = []
impar = []
while True:
lista.append(int(input('\033[36mDigite um número: ')))
resp = str(input('\033[32mQuer continuar? [S/N] ')).strip()[0]
if resp in 'Nn':
break
for c in range(len(lista)):
... |
# encoding:utf-8
# 401 错误
class UnauthorizedError(Exception):
pass
# 400 错误
class BadRequestError(Exception):
pass
class MediaTypeError(Exception):
pass
# 父异常
class RestfulException(Exception):
pass |
def inner_stroke(im):
pass
def outer_stroke(im):
pass
|
a, b, c = map(int, input().split())
h, l = map(int, input().split())
if a <= h and b <= l:
print("S")
elif a <= h and c <= l:
print("S")
elif b <= h and a <= l:
print("S")
elif b <= h and c <= l:
print("S")
elif c <= h and a <= l:
print("S")
elif c <= h and b <= l:
print("S")
else:... |
def funcao1 (a, b):
mult= a * b
return mult
def funcao2 (a, b):
divi = a / b
return divi
multiplicacao = funcao1(3, 2)
valor = funcao2(multiplicacao, 2)
print(multiplicacao)
print(int(valor))
|
# Plotting distributions pairwise (1)
# Print the first 5 rows of the DataFrame
print(auto.head())
# Plot the pairwise joint distributions from the DataFrame
sns.pairplot(auto)
# Display the plot
plt.show()
|
def log_text(file_path, log):
if not log.endswith('\n'):
log += '\n'
print(log)
with open(file_path, 'a') as f:
f.write(log)
def log_args(file_path, args):
log = f"Args: {args}\n"
log_text(file_path, log)
def log_train_epoch(file_path, epoch, train_loss, train_accuracy):
log... |
class Node:
def __init__(self, value, next):
self.value = value
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def add(self, value):
self.head = Node(value, self.head)
def remove(self):
to_remove = self.head
self.head = self.hea... |
lista = []
dicio = {}
idadeTot = 0
cont = 0
contMulher = 0
while True:
dicio['nome'] = str(input('Digite o nome: '))
while True:
dicio['sexo'] = str(input('Digite o sexo: [M/F] ')).upper()[0]
if dicio['sexo'] in 'MF':
break
else:
dicio['sexo'] = str(input('Digite ... |
# A. Way Too Long Words
# -------------------------------
# time limit per test1 second
# memory limit per test 256 megabytes
# input :standard input
# ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Advent of Code 2020
Day 13, Part 1
"""
def main():
with open('in.txt') as f:
lines = f.readlines()
arrival = int(lines[0].strip())
bus_ids = []
for n in lines[1].strip().split(','):
if n == 'x':
continue
else:
... |
#!/usr/bin/env python
#
# ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
# Charles A. Williams, GNS Science
# Matthew G. Knepley, University of Chicago
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://ge... |
t = int(input())
while (t!=0):
a,b,c = map(int,input().split())
if (a+b+c == 180):
print('YES')
else:
print('NO')
t-=1
|
# cool.py
def cool_func():
print('cool_func(): Super Cool!')
print('__name__:', __name__)
if __name__ == '__main__':
print('Call it locally')
cool_func()
|
"""Faça um programa que tenha uma função notas() que pode receber várias notas de alunos
e vai retornar um dicionário com as seguintes informações:
– Quantidade de notas
- A maior nota
– A menor nota
– A média da turma
– A situação (opcional)"""
def notas(* num, s=False):
"""
-> Função para coletar notas dos ... |
"""
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/
Given an integer array arr. You have to sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order.... |
class FieldDoesNotExist(Exception):
def __init__(self, **kwargs):
super().__init__(f"{self.__class__.__name__}: {kwargs}")
self.kwargs = kwargs
|
"""
Queue
https://algorithm.yuanbin.me/zh-hans/basics_data_structure/queue.html
"""
|
#
# PySNMP MIB module Unisphere-Products-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Products-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:26:09 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... |
'''
从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。假设字符串中只包含'a'~'z的字符。例如,在字
符串"arabcacfr"中,最长的不含重复字符的子字符串是"acfr",长度为4。
'''
class Solution:
def lengthOfLongestSubstring(self, s):
if len(s) <= 1:
return len(s)
head, tail = 0, 0
maxLen = 1
while tail+1 < len(s):
tail += 1 # 往窗口内添加元素
if s[tail] not in s[head: tai... |
'''8) Elabore um algoritmo que leia 3 valores inteiros (a,b e c) e os coloque em
ordem crescente, de modo que em a fique o menor valor, em b o valor intermediário e
em c o maior valor. '''
a = int(input("Digite o valor do primeiro valor: "))
b = int(input("Digite o valor do segundo valor: "))
c = int(input("Digite ... |
class Solution(object):
def findSubsequences(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
ans = []
def dfs(nums, start, path, ans):
if len(path) >= 2:
ans.append(tuple(path + []))
fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.