content stringlengths 7 1.05M |
|---|
DEBUG = False
# specify which folder in the static_folder is used to store essays
ESSAY_RESOURCE_FOLDER = 'essay_resources'
HOST = '127.0.0.1'
PORT = 8000
|
class Stack:
# Constructor
def __init__(self):
self.collection = []
# Append data on the top of the stack
def push(self, data):
self.collection.append(data)
# Remove and return the last item on the top of the stack
def pop(self):
return self.collection.pop()
... |
#
# Tutt library III location codes
#
FULL_CODE_MAP = {
'dacc': 'Digital Archives of Colorado College',
'ewww':'Online',
'ewwwd':'Online Government Documents',
'ewwwp':'Online Periodcals',
'ewwwn':'Online',
'tarf':'Tutt Reference',
'tarfa':'Tutt 1st Floor South',
'tarfc':'Tutt Reference... |
def isDigit(string):
#11ELF
try:
float(string)
except ValueError:
try:
complex(string)
except ValueError:
return False
return True |
"""def olá_Mundo():
return 'Olá Mundo'
def mestre(funcao):
return funcao()
executando = mestre(olá_Mundo)
print(executando)
"""
def mestre(funcao, *args, **kwargs):
return funcao(*args, **kwargs)
def fala_oi(nome):
return f'Oi {nome}'
def saudacao(nome, saudacao):
return f'{saudacao} {nome}'
e... |
nome = str(input('Digite um nome: ')).strip()
if nome == 'Marcelo José' or nome == 'José':
print('É um prazer te conhecer {}ZeroX{}!!!'.format('\033[4;31m', '\033[m'))
elif nome == 'André Luis' or nome == 'André':
print('É um prazer te conhecer {}BossNX{}!!!'.format('\033[4;34m', '\033[m'))
elif nome == 'João... |
#!/usr/bin/env python
# API Header parameter
header_param_name = 'project_id'
# Blockfrost Network URL
bf_url_cardano_mainnet = 'https://cardano-mainnet.blockfrost.io/api/v0/'
bf_url_cardano_testnet = 'https://cardano-testnet.blockfrost.io/api/v0/'
# Blockfrost Stake URL
bf_stake_url = 'accounts/'
bf_stake_rewards_u... |
def crop_to_square(x):
crop_width, remainder = divmod(abs(x.shape[0] - x.shape[1]), 2)
if x.shape[0] < x.shape[1]:
return x[:, crop_width : x.shape[1] - crop_width - remainder]
else:
return x[crop_width : x.shape[0] - crop_width - remainder]
|
"""
List of languages.
Auto-generated with `python -m scripts`.
"""
# START
langs = {
"aa": "afar",
"aaa": "ghotuo",
"aab": "alumo-tesu",
"aac": "ari",
"aad": "amal",
"aae": "albanês arbëreshë",
"aaf": "aranadan",
"aag": "ambrak",
"aah": "abu'arapesh",
"aai": "afade",
"ab": ... |
#!/usr/bin/env python
# software from PDBe: Protein Data Bank in Europe; https://pdbe.org
#
# Copyright 2018 EMBL - European Bioinformatics Institute
# 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 Licens... |
class Card:
SUIT_SYMBOLS = {
0: u"\u2666", # diamonds
1: u"\u2665", # hearts
2: u"\u2663", # clubs
3: u"\u2660" # spades
}
VALUE_NAMES = {
1: "A",
2: "2",
3: "3",
4: "4",
5: "5",
6: "6",
7: "7",
8: "8",
... |
# -----------------------------------------------------------
# Copyright (c) 2021. Danil Smirnov
# Write a program that determines whether a year with a given
# number ends with two zeros. If the year ends, then output "YES",
# otherwise output "NO".Write a program that determines whether
# a year wi... |
class Banner:
TEXT = """
________________________________________________________________________________
'####:'##::: ##::'#######::'####::'######::
. ##:: ###:: ##:'##.... ##:. ##::'##... ##:
: ##:: ####: ##: ##:::: ##:: ##:: ##:::..::
: ##:: ## ## ##: ##:::: ##:: ##::. ######::
: ##:: ##. ####: ##:::: ##:: ##:... |
# -*- coding: utf-8 -*-
@auth.requires_login()
def index():
return locals()
@auth.requires_login()
def cadastrar_medicamento():
form = SQLFORM(db.lista_medicamentos)
if form.process().accepted:
id = form.vars.id
redirect(URL(c='admin', f='ver_medicamento', args=id), client_side=True)
... |
emergency = ['conflict', 'violence', 'displacement', 'drought', 'earthquake', 'fire', 'flooding', 'freeze', 'health emergency', 'dengue', 'pneumonic plague', 'measles', 'landslide', 'tropical storm', 'typhoon', 'cyclone', 'hurricane', 'tsunami', 'urban disaster', 'volcanic eruption', 'volcano', 'refugee', 'terrorist at... |
#!/usr/bin/env python3
path_on_servers = '~/.dcp'
setup_cache = '.cache_setup'
listener_py = 'dcp/http_listener.py'
listener_deps = ['dcp/actions.py']
|
n=int(input("Enter the number"))
ls=[]
ls1=[]
co=0
for i in range(n):
ls.append(input())
if len(ls) == len(set(ls)):
print("No Repeated Values here")
else:
le=len(ls)
for i in range(le-1):
for j in range(i+1,le):
if ls[i]==ls[j]:
ls1.append(ls[j])
... |
#Nomes caso feito em duplas:
#Nome1: Everson Cordeiro da Silva R.A. 1901300
#Nome2: Luís Felipe Bocchini R.A 1901079
#FUNÇÃO DO CALCULO
def Calculo(valor):
#CORREÇÃO MONETARIA DOS IMPARES 1,3 E 7 PARA NÃO PEGAREM MOEDAS DE 0.50 A MAIS#
if round(valor%2,1) == round(0.1,1) or round(valor%2,1) == round(0.3,1) ... |
'''
Escreva um programa que receba um número inteiro positivo na entrada e verifique se é primo. Se o número for primo, imprima "primo". Caso contrário, imprima "não primo".
'''
numero = int(input("Digite um número: "))
count = 0
for i in range(1, numero + 1):
if numero % i == 0:
count += 1
print(i... |
MORSE_DICT_ATM = {
"A": ".-",
"B": "-...",
"C": "-.-.",
"D": "-..",
"E": ".",
"F": "..-.",
"G": "--.",
"H": "....",
"CH": "----",
"I": "..",
"J": ".---",
"K": "-.-",
"L": ".-..",
"M": "--",
"N": "-.",
"O": "---",
"P": ".--.",
"Q": "--.-",
"R"... |
# arrays are indexed (their conetnts get assigned a number)
# the index always starts at 0
choices = ["rock", "paper", "scissors"]
player_lives = 3
computer_lives = 3
total_lives = 3
#True and False are Boolen data types -> they are the equivalent of on or off, 1 or 0
player = False |
print ('='*50)
n = float ( input ('Digite o número: '))
print ('='*50)
##########################################################
print ('O dobro do número digitado é >>> {}'.format (n * 2))
print ('O tripo do número digitado é >>> {}'.format (n * 3))
print ('A raiz quadrada do número digitado é >>> {:.2f}'.format (pow... |
def merge(a: list, b: list) -> list:
"""Merges B into A in sorted order
a is modified in place and also returned
Args:
a: sorted list with enough buffer at the end to hold b
b: sorted list
Returns:
A single sorted list
"""
end_b = len(b) - 1
for idx, val in enumera... |
class Signal:
"""A convinience class that encapsulates a signal in order to
be used in the DisconnectedSignals context manager
"""
def __init__(self, signal, receiver, sender):
self.signal = signal
self.receiver = receiver
self.sender = sender
def connect(self):
... |
class UiGroup(object):
def __init__(self):
self.elements = []
def add_element(self, element):
self.elements.append(element)
def set_visible(self, value):
for e in self.elements:
e.set_visible(value)
def inputs(self, events):
for e in self.elements:
... |
login = input('nome de usuario: ')
senha = input('senha de usuario: ')
enedereço_de_gmail = input('insira o e-mail aqui: ')
cpf = int(input('insira o seu cpf pfv: '))
while cpf > 9999 or cpf < 1111: # supondo que cpf tenha 4 números
cpf = int(input('numero invalido\nDigite um número válido: '))
print('=====confir... |
class Solution:
def validPalindrome(self, s: str) -> bool:
def verify(s, left, right, counter=0):
while left < right:
if s[left] != s[right]:
if counter == 1:
return False
return verify(s, left+1, right, counter+1) o... |
def factorial(n):
result = 1
for number in range(1, n + 1):
result *= number
return result
# nPr = n! / (n - r)!
# 4 r=2
def permutation(n, r):
return factorial(n) // factorial(n - r)
# nCr = nPr / r!
def combination(n, r):
return permutation(n, r) // factorial(r)
print(combination(4, ... |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.13.7
# kernelspec:
# display_name: Python [conda env:bandit_38]
# language: python
# name: conda-env-bandi... |
#
# PySNMP MIB module INTELCORPORATIONSERVERHEALTH-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/INTELCORPORATIONSERVERHEALTH-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:55:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 7 02:58:39 2019
@author: sodatab
MITx: 6.00.1x
"""
"""
03.5-Finger Apply to Each 01
-----------------------------
Here is the code for a function applyToEach:
def applyToEach(L, f):
for i in range(len(L)):
L[i] = f(L[i])
Assume tha... |
class Pessoa:
def __init__(self, *filhos, nome=None, idade=37):
self.idade = idade
self.nome = nome
self.filhos = list(filhos)
def cumprimentar(self):
return 'Olá'
if __name__ == '__main__':
alan = Pessoa(nome='Alan')
batata = Pessoa(alan, nome= 'Batata')
print(Pes... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Triangle Project Code.
# Triangle analyzes the lengths of the sides of a triangle
# (represented by a, b and c) and returns the type of triangle.
#
# It returns:
# 'equilateral' if all sides are equal
# 'isosceles' if exactly 2 sides are equal
# 'scalene' ... |
# -*- coding: utf-8 -*-
"""Top-level package for hello-cc."""
__author__ = """lin zhang"""
__email__ = 'audreyr@example.com'
__version__ = '0.1.0'
|
def f(items):
items.append(100)
def g(items):
items.append(items.pop() * 2)
def h(items):
items.extend([items.pop()] * 10)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#ENSEMBLES keep function
def keep_ensembles(i, ensemble_results, results, ensemble_target, target, ensemble_patient, patient):
if i==0:
return ensemble_results.append(results), ensemble_target.append(target), ensemble_patient.append(patient)
else:
... |
# Given an array of distinct integers candidates and a target integer target,
# return a list of all unique combinations of candidates where the chosen numbers sum to target.
# You may return the combinations in any order.
# The same number may be chosen from candidates an unlimited number of times.
# Two combinati... |
class InstallmentForm(object):
def __init__(self):
pass
def media(self):
pass
def static(self):
pass
|
"""
Execute following command to ignore local changes on this file
$ git update-index --skip-worktree tests/tokens.py
Execute following command to track local changes on this file again
$ git update-index --no-skip-worktree tests/tokens.py
"""
API_TOKEN = '<Your API token>'
MESSENGER_HOOK_URL = '<Your hook url>'
|
n = int(input())
numbers = []
for _ in range(n):
numbers.append(int(input()))
for i in numbers:
if i % 7 == 0:
print(i ** 2)
|
"""
7. Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers
within the 32-bit signed integer range: [−231, ... |
# Crie um script Python que leia dois números e tente mostrar a soma entre eles
n1 = float(input("Digite o 1º número: "))
n2 = float(input("Digite o 2º número: "))
soma = n1 + n2
print("A soma entre {} e {} é: {}".format(n1, n2, soma)) |
"""
link: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal
problem: 给先序,中序,还原树
solution: 利用先序定根,中序划分左右的性质,递归划分子树的范围
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right =... |
class Solution:
def isMatch(self, s: str, p: str) -> bool:
self.s = s
self.p = p
@cache
def match(p_idx, s_idx):
if (s_idx == len(self.s) and
p_idx == len(self.p)):
return True
if p_idx == len(self.p):
... |
a=input()
b=input()
c=input()
if len(a)+len(b) == len(c):
print('YES')
else:
print('NO') |
def get_mean(collection):
"""
Obtain the average of a collection of objects.
Parameters
----------
collection : list
A list of numbers
Returns
-------
float
The mean of the numbers.
"""
return sum(collection) / len(collection)
|
# Adapted from code written by Paul Kippes and released as
# part of the Python standard library, see
# https://github.com/python/cpython/blob/v3.8.5/Lib/sqlite3/dump.py
CREATE_TABLE_PREFIX = "CREATE TABLE "
def iterdump(connection):
cu = connection.cursor()
yield "BEGIN TRANSACTION;"
writable_schema = F... |
class Room(object):
_registry = []
def __init__(self, name, exits, dexits, info, npcs, region, spawner = None):
self.name = name
self.exits = exits
self.dexits = dexits
self.info = info
self.npcs = npcs
self.region = region
self.spawner = spawner
self._registry.append(self)
vanco... |
def buildPalindrome(st):
if st == st[::-1]:
return st
for i in range(len(st)):
s = st + st[i::-1]
if s == s[::-1]:
return s
def buildPalindrome(st):
return re.sub(r"(\w+)\1", r"\1", st + st[::-1])
def buildPalindrome(st):
i = 0
while st[i:] != st[i:][::-1]:
... |
palavra = 'cachorro'
vazio = ''
def advinhar(preencher, letra):
temp = ''
for i, v in enumerate(palavra):
if preencher[i] == '_' and letra != v:
temp = temp + '_'
continue
temp = temp + v
return temp
def check():
if vazio == palavra:
prin... |
class AirCondition:
def __init__(self, brand, temperature):
self.brand = brand
self.temperature = temperature
@property
def temperature(self):
return self.__temperature
@temperature.setter
def temperature(self, value):
if 18 <= value <= 31:
self.__temper... |
def sum(xs):
# return the sum of all the elements in the list xs
# remove the following line
return 0
def test(test_case, expected):
actual = sum(test_case)
if actual == expected:
print("Passed test for " + str(test_case))
else:
print("Didn't pass test for " + str(test_case))
... |
"""
Cage acts as the place where the score is stored before it goes into the actual score
"""
class Box:
def __init__(self):
"""Initializes the class"""
self.value = 0
def reset(self):
"""reset the box (when a 1 is rolled or after the score is stored)"""
self.value = 0
def ... |
class APIError(Exception):
"""Raised when there is an API error"""
pass
class NotFound(Exception):
"""Raised on a 404 status code"""
pass
class UserNotFound(Exception):
"""Raised when a specified user cannot be found by the API"""
pass
class InvalidSearch(Exception):
"""Raised when a s... |
# Uma forma de ler um arquivo de texto em python:
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents + '\n')
# Essa é outra forma de ler um arquivo de texto em python sendo linha a linha:
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file... |
#Multiple of ten:
number_of_ten = input("Please enter a number to check whether its multiple of 10 or not:")
if (int(number_of_ten) % 10) == 0:
print("Yes, your",number_of_ten,"is multiple of ten.")
else:
print("No, your",number_of_ten,"is not multiple of ten.") |
# Practice Python Exercise 4 -- Divisors
#
# This script asks the user for a number and returns all of the divisors of that number.
# Get user input and convert to a number
x = input('Enter a number: ')
# Verify that input number is an integer
try:
x = float(x)
except ValueError:
print('The provided in put m... |
class CircularQueue:
DEFAULT_CAPACITY = 10
def __init__(self, initial_size = DEFAULT_CAPACITY):
self._data = [None] * initial_size
self._front = 0
self._back = 0
self._number_of_items = 0
def enqueue(self, item):
self._check_capacity()
self._data[self._back... |
def my_function(data=None):
return_value = None
if data is None:
return return_value
if isinstance(data, list):
sum_of_data = sum(data)
len_of_data = len(data)
return sum_of_data/len_of_data
else:
return return_value
|
def test_clean(imnetdb):
imnetdb.wipe_database()
imnetdb.ensure_database()
|
nome = input('Qual é o seu nome? ');
print('Prazer em te conhecer, {:20}!'.format(nome));
#Imprime a variavel 20 caracteres
print('Prazer em te conhecer, {:<20}!'.format(nome));
#O sinal de menor, alinha a esquerda
print('Prazer em te conhecer, {:>20}!'.format(nome));
#o sinal de maior alinha a direita
print('Prazer em... |
class Solution:
def arrayPairSum(self, arr: list[int]) -> int:
s, n = 0, len(arr)
arr.sort()
for i in range(0, n, 2):
s += arr[i]
return s
|
# 01.02.04 ASCII KAT
print("(---)")
print("(o o)")
print("(=Y=)")
print(" ( ) ")
|
"""
PrimitivePShape.
Using a PShape to display a primitive shape (in this case, ellipse).
"""
# The PShape object
circle = None
def setup():
size(640, 360, P2D)
smooth()
# Creating the PShape as an ellipse.
circle = createShape(ELLIPSE, 0, 0, 100, 50)
def draw():
background(51)
# We can d... |
MAILGUN_URL = "<your mailgun URL>"
MAILGUN_API_KEY = "<your mailgun key>"
MAILGUN_FROM = "<email from address>"
MAILGUN_TO = "<email to address>"
|
# -*- coding: utf-8 -*-
# https://github.com/RDFLib/rdflib-jsonld/blob/feature/json-ld-1.1/rdflib_jsonld/errors.py
class JSONLDException(ValueError):
pass
# http://www.w3.org/TR/json-ld-api/#idl-def-JsonLdErrorCode.{code-message}
RECURSIVE_CONTEXT_INCLUSION = JSONLDException("recursive context inclusion")
INVALID... |
GLOBAL_3 = "global 3"
"""Docs for global 3"""
class Class3:
"""Docs for class 3"""
def function_3():
"""Docs for function 3"""
|
def inverter_delay():
return 2
def and_gate_delay():
return 3
def or_gate_delay():
return 5 |
def html_tag(tag):
def wrap_text(msg):
print('<{0}>{1}</{0}>'.format(tag,msg))
return wrap_text
print_h1=html_tag('h1')
print_h1('Test Headline')
print_h1('Another Headline')
print_p=html_tag('p')
print_p('Test Paragraph') |
def bigint_check(val):
"""
Checks to see if `val` is or contains BIGINTs.
Args:
val (int, float, list): value or list of values to check.
Returns:
bool: True if `val` contains one or more BIGINT, False if not.
"""
if not isinstance(val, list) or isinstance(val, str):
va... |
class Tags(object):
@staticmethod
def from_json(tags_json):
result = []
for tag_json in tags_json:
tag = Tag(key=tag_json['Key'], value=tag_json['Value'])
return result |
n = int(input())
a = input().split()
cont = 0
x = []
while cont < n:
num = int(a[cont])
x.append(num)
cont += 1
print("Menor valor:",min(x))
print("Posicao:",x.index((min(x))))
|
"""
0783. Minimum Distance Between BST Nodes
Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in the tree.
Example :
Input: root = [4,2,6,1,3,null,null]
Output: 1
Explanation:
Note that root is a TreeNode object, not an array.
The g... |
class PredictedEntry:
content_hash = ""
web_address = ""
bias_value = 0.0
def __init__(self, content_hash, web_address, bias_value):
self.content_hash = content_hash
self.web_address = web_address
self.bias_value = bias_value |
#!/usr/bin/python
#create valid ipv4 address
def valid_ip(ip):
parts = ip.split('.')
return (
len(parts) == 4
and all(part.isdigit() for part in parts)
and all(0 <= int(part) <= 255 for part in parts)
)
ip_address = raw_input("enter ip to check: ")
if valid_ip(ip_address) is T... |
try:
file_path = input()
all_time = 0
with open(file_path) as file:
for line in file:
arguments = line.split(',')
distance = int(arguments[1]) - int(arguments[0]) + 1
speed = int(arguments[2])
time = float(distance / speed)
all_time += tim... |
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
if not root.left:
return self.minDepth(root.right) + 1
if not root.right:
return self.minDepth(root.left) + 1
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
|
dashboard_module_description = {
"cloud_element": ["Cloud Info", "Shows some info about the files in your cloud"],
"joke_element": ["Random Joke", "Shows a random joke and lets you vote"],
"quote_element": ["Random Quote", "Shows a random quote"],
"news_element": ["SWC News", "Shows the latest SWC news"... |
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming.")
with open(filename) as file_o:
line = file_o.read()
print(line) |
lines = open('data.csv').read().split('\n')
data = [(int(x[:x.find(',')]), float(x[x.find(',')+1:])) for x in lines if x]
REPORT_THRESHOLD = 0.23
def get_error(scale, elasticity, growth):
err = 0
bs_fac, fee_fac = 1 / (1 + elasticity), elasticity / (1 + elasticity)
for i, (block_size, avg_fee) in enum... |
def make_palindrome(s):
'''
recursion implementation
'''
#base case 1
if not s or len(s)==1:
return s
#base case 2
if s==s[::-1]:
return s
if s[0] == s[-1]:
return s[0]+make_palindrome(s[1:-1]) + s[-1]
else:
x = s[0] + make_palindrome(s[1:]) + s[... |
"""Package-specific exceptions."""
class NotFittedError(Exception):
"""Exception raised when predicting using an unfitted estimator."""
pass
class ConvergenceError(Exception):
"""Exception raised when a model fails to converge."""
pass
|
# Copyright 2017 QuantRocket - All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
print('\n',30*'=','\n', ' TERMOS DE UMA P.A.\n', 30*'=')
p = int(input('Primeiro termo: '))
r = int(input('Razão: '))
c = 0
m = 10
while c < m:
if c == 0:
print(f'P.A. = ', end = '')
k = p + c * r
print(k, end=' -> ')
c += 1
if m == c:
print('PAUSA')
mais = int(input('De... |
# following PEP 386
__version__ = "1.9.0"
default_app_config = 'statici18n.apps.StaticI18NConfig'
|
"""
Settings to initialize scrapy
"""
BOT_NAME = 'emblemsnake'
SPIDER_MODULES = ['emblemscraper.spiders']
NEWSPIDER_MODULE = 'emblemscraper.spiders'
USER_AGENT = 'emblemsnake (+http://www.pradyothkukkapalli.com)'
ROBOTSTXT_OBEY = True
SPIDER_MIDDLEWARES = {
'scrapy_splash.SplashDeduplicateArgsMiddleware': 100,
... |
def part1():
"""
Only two recipes are on the board: the first recipe got a score of 3, the second, 7.
Each of the two Elves has a current recipe: the first Elf starts with the first recipe,
and the second Elf starts with the second recipe.
To create new recipes, the two Elves combine their current recipes.
This ... |
# Assign a variable with a value
x = 5
# Assign a variable with String
y = "My Name is "
y = "Vamsi "
# Print the Value
print (x)
# Print the Type of Variable
print(type(x))
# Print the Value
print (y)
# Print the Type of Variable
print(type(y))
"""
Append same type int
"""
a = 5
b = 10
c = a+b
print("... |
def get_strings(city):
dict={}
for i in city.lower():
if not i.isalpha():
continue
dict[i]=dict.get(i, "")+"*"
return ",".join(f"{i}:{j}" for i,j in dict.items()) |
class SimpleScheduler(object):
def __init__(self, optimizer, lr):
self.optimizer = optimizer
self.lr = lr
def step(self):
self.optimizer.param_groups[0]['lr'] = self.get_lr()
self.optimizer.step()
def get_lr(self):
return self.lr |
class States(object):
def __init__(self):
self.init = 0
self.decimal = 1
self.decpoint = 2
self.afterdp = 3
self.e = 4
self.aftere = 5
self.sign = 6
self.nullpoint = 7
self.esign = 8
self.afteresign = 9
c... |
#!/usr/bin/python3
#!-*-coding:UTF8-*-
# 一个单独的无参数函数
def say_hello():
"""无参数的函数"""
print("Python: Hello world!")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
获取符号字典列表的
'''
class PinyinDict:
def __init__(self, datapath):
self.dict = self._genPinyinDict(datapath)
def _genPinyinDict(self, datapath):
'''
加载拼音符号列表,用于标记符号
返回一个列表list类型变量
'''
# if is not file
if not... |
#!/usr/bin/env python
# -*- mode:python; coding:utf-8 -*-
Config = {
'connect_default_host': "localhost",
'connect_default_port': "8083",
'schema_registry_default_host': "localhost",
'schema_registry_default_port': "8081",
} |
#Return an array containing the numbers from 1 to N
def fizzbuzz(n):
l = []
for i in range(1, n+1):
if i % 3 == 0 and i % 5 == 0:
l.append("FizzBuzz")
elif i % 3 == 0:
l.append("Fizz")
elif i % 5 == 0:
l.append("Buzz")
else:
l.appen... |
# Math
# Find the smallest prime palindrome greater than or equal to N.
#
# Recall that a number is prime if it's only divisors are 1 and itself, and it is greater than 1.
#
# For example, 2,3,5,7,11 and 13 are primes.
#
# Recall that a number is a palindrome if it reads the same from left to right as it does from rig... |
n, c, *a = map(int, open(0).read().split())
c1 = {}
c2 = {}
for i in range(1, 11):
c1[i] = 0
c2[i] = 0
for x in a[::2]:
c1[x] += 1
for x in a[1::2]:
c2[x] += 1
result = float('inf')
x = (n + 1) // 2
y = n - x
for i in range(1, 10):
for j in range(i + 1, 11):
result = min(result, ((x - c1[i... |
"""
@no 43
@name Multiply Strings
"""
class Solution:
def add(self, num1, num2):
ans = ''
count = 0
temp = 0
up = 0
while len(num1) - 1 - count >= 0 or len(num2) - 1 - count >= 0:
a = int(num1[len(num1) - 1 - count]) if len(num1) - 1 - count >= 0 else 0
... |
# Taxi (2150007) | Edelstein (1000064)
optionList = [
310040200, # Mine Entrance
310070000 # Haven
]
destination = sm.sendNext("Where would you like to go? #b\r\n"
"#L0# Verne Mine #l\r\n"
"#L1# Haven #l\r\n")
sm.warp(optionList[destination]) |
# linelist.py
# ALS 2017/06/14
# updated 2017/11/09: added MgII to narrowline
""" include line list for spectral line related operations """
# ======= for continuum subtraction ===========
narrowline = ['MgII', 'OII', 'OIII', 'OI', 'NII', 'NeV', 'SII', 'Ha', 'Hb', 'Hg', 'Hd', 'ArIII', 'NeIII', 'Dip', 'Mg', 'Na', 'He... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.