content stringlengths 7 1.05M |
|---|
def garterKnit(k,beg,end,length,c,side='l', knitsettings=[4,400,400], xfersettings=[2,0,300]):
if side == 'l':
start=1
else:
start=2
length=length+1
for b in range(start,length+1):
if b%2==1:
k.stitchNumber(xfersettings[0])
k.rollerAdvance(xfersetti... |
# Disable while we have Python 2.x compatability
# pylint: disable=useless-object-inheritance
"""This module contains classes and functionality relating to Sonos Groups."""
class ZoneGroup:
"""
A class representing a Sonos Group. It looks like this::
ZoneGroup(
uid='RINCON_000FD584236D0... |
def resolve():
'''
code here
'''
N, M, Q = [int(item) for item in input().split()]
a_list = [[int(item) for item in input().split()] for _ in range(Q)]
res = 0
for item in comb:
temp_res = 0
print(item)
for j in a_list:
a = j[0]-1
b = ... |
## @file GenXmlFile.py
#
# This file contained the logical of generate XML files.
#
# Copyright (c) 2011 - 2018, Intel Corporation. All rights reserved.<BR>
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
'''
GenXmlFile
'''
|
#
# PySNMP MIB module RBTWS-TRAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBTWS-TRAP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:53:51 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... |
"""433. Number of Islands"""
class Solution:
"""
@param grid: a boolean 2D matrix
@return: an integer
"""
def numIslands(self, grid):
# write your code here
## Practice:
if not grid:
return 0
self.directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
m =... |
"""
Code that changes input files and writes them back out. Useful for parameter sweeps.
See Also
--------
armi.reactor.converters
Code that changes reactor objects at runtime. These often take longer to run than
these but can be used in the middle of ARMI analyses.
"""
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'wtq'
# ftp登录到的路径
FTP_PATH = "/home/wtq/"
# 要连接的远程主机ip
HOST = '10.108.112.74'
# 远程文件的路径,相对于ftp的登录路径而言,mysql应该备份到该路径下
TARGET_DIRN = 'ftp_file/'
# 要下载的目标文件名
TARGET_FILE = 'key_words.sql'
# 登录的ftp用户名
USER = "wtq"
# 登录的密码
PASSWD = "123"
# 要下载到的本地文件地址
DOWNLOAD_FILE ... |
class MwClientError(RuntimeError):
pass
class MediaWikiVersionError(MwClientError):
pass
class APIDisabledError(MwClientError):
pass
class MaximumRetriesExceeded(MwClientError):
pass
class APIError(MwClientError):
def __init__(self, code, info, kwargs):
self.code = code
self... |
# _\__o__ __o/ o o o o__ __o o o/ o__ __o__/_ o__ __o
# v |/ <|> <|> <|> /v v\ <|> /v <| v <| v\
# / < > < > / \ /> <\ / > /> < > /... |
#!/usr/bin/python3
#-*- coding: UTF-8 -*-
# 文件名:environ.py
print ('Content-Type: text/html')
print ('Set-Cookie: name="菜鸟教程";expires=Wed, 28 Aug 2017 18:30:00 GMT')
print ()
print ("""
<html>
<head>
<meta charset="gbk">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<h1>Cookie set OK!</h1>
... |
def plot_table(data):
fig = plt.figure()
ax = fig.add_subplot(111)
col_labels = list(range(0,10))
row_labels = [' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ']
# Draw table
value_table = plt.table(cellText=data, colWidths=[0.05] * 10,
rowLabels... |
"""Qiskit-Braket exception."""
class QiskitBraketException(Exception):
"""Qiskit-Braket exception."""
|
class Settings:
def __init__(self):
self.screen_width = 800
self.screen_height = 600
self.black = (0, 0, 0)
self.white = (255, 255, 255)
self.red = (255, 0, 0)
self.green = (0, 255, 0)
self.blue = (0, 0, 255)
self.FPS = 90
|
N = 2
for i in range(1,N):
for j in range(1,N):
for k in range(1,N):
for l in range(1,N):
if i**3+j**3==k**3+l**3:
print(i,j,k,l) |
# Given a linked list, rotate the list to the right by k places, where k is non-negative.
# Example 1:
# Input: 1->2->3->4->5->NULL, k = 2
# Output: 4->5->1->2->3->NULL
# Explanation:
# rotate 1 steps to the right: 5->1->2->3->4->NULL
# rotate 2 steps to the right: 4->5->1->2->3->NULL
# Example 2:
# Input: 0->1->2->... |
def rainWaterTrapping(arr: list) -> int:
n = len(arr)
maxL = [1] * n
maxR = [1] * n
maxL[0] = arr[0]
for i in range(1, n):
maxL[i] = max(maxL[i - 1], arr[i])
maxR[n - 1] = arr[n - 1]
for i in range(n - 2, -1, -1):
maxR[i] = max(maxR[i + 1], arr[i])
total_water = 0
... |
n=int(input())
x=hex(n)[-1]
if x.isalpha():
x=ord(x)-87
print(bin(int(x))[-1]) |
BLACK = [0x00, 0x00, 0x00] # Floor
WHITE = [0xFF, 0xFF, 0xFF] # Wall
GOLD = [0xFF, 0xD7, 0x00] # Gold
BLUE = [0x00, 0x00, 0xFF] # Player
GRAY = [0x55, 0x55, 0x55] # Box
GREEN = [0x00, 0xAA, 0x00] # Key
PURPLE = [0xC4, 0x00, 0xC4] # Door
RED = [0xFF, 0x00, 0x00] # Teleport 1
BROWN = [0xA0, 0x50, 0x00] # Teleport 2 |
def stretched(a):
def rec(item, index):
if index == 1:
return [item]
r = [item]
r.extend(rec(item, index - 1))
return r
def tail(ar, index, result):
if len(ar) == 0:
return result
else:
result.extend(rec(ar.pop(0), index))
... |
# -*- coding: utf-8 -*-
# Authors: Y. Jia <ytjia.zju@gmail.com>
"""
Find the contiguous subarray within an array (containing at least one number) which has the
largest sum.
https://leetcode.com/problems/maximum-subarray/description/
"""
class Solution(object):
def maxSubArray(self, nums):
"""
:... |
count = 0
sum = 0
print('Before', count, sum)
for value in [9, 41, 12, 3, 74, 15]:
count = count + 1
sum = sum + value
print(count, sum, value)
print('After', count, sum, sum / count)
|
"""
module-wide / shared constants
***
attributes
***
*LOGGING_CFG*: logging configuration dictionary
***
"""
LOGGING_DICT = {
"version": 1,
"disable_existing_loggers": True,
"formatters": {
"verbose": {
"format": "[%(asctime)s] - [%(name)s] - [%(levelname)s]... |
#!/usr/bin/env python3
class InputComponent:
def __init__(self):
"""
Constructor in Python is always called `__init__`
You should initialize all object-level variables in the constructor
"""
self._observers = []
def register_observer(self, observer):
self._observ... |
def pattern_thirty_seven():
'''Pattern thirty_seven
1 2 3 4 5
2 5
3 5
4 5
5
'''
num = '12345'
for i in range(1, 6):
if i == 1:
print(' '.join(num))
elif i in range(2, 5):
space = -2 * i + 9 # using -2*n + 9 for ge... |
def listening_algorithm(to,from_):
counts = []
to = to.split(' ')
for i in range(len(from_)):
count = 0
var = from_[i].split(' ')
n = min(len(to),len(var))
for j in range(n):
if var[j] in to[j]:
count += 1
counts.append(count)
... |
'''
06 - Combining groupby() and resample()
A very powerful method in Pandas is .groupby(). Whereas .resample()
groups rows by some time or date information, .groupby() groups rows
based on the values in one or more columns.
For example, rides.groupby('Member type').size() would tell us how many
rides there were... |
"""
Growth rates
-------------
(order low to high) (a.k.a. time complexity of a function/ complexity class of a function):
O(1) -- Constant -- append, get item, set item.
O(logn) -- Logarithmic -- Finding an element in a sorted array.
O(n) -- Linear -- copy, insert, delete, ite... |
# model settings
weight_root = '/home/datasets/mix_data/iMIX/data/models/detectron.vmb_weights/'
model = dict(
type='M4C',
hidden_dim=768,
dropout_prob=0.1,
ocr_in_dim=3002,
encoder=[
dict(
type='TextBertBase', text_bert_init_from_bert_base=True, hidden_size=768, params=dict(num_... |
def rpc_gas_price_strategy(webu, transaction_params=None):
"""
A simple gas price strategy deriving it's value from the eth_gasPrice JSON-RPC call.
"""
return webu.manager.request_blocking("eth_gasPrice", [])
|
bot_token = "" # Bot token stored as string
bot_prefix = "" # bot prefix stored as string
log_level = "INFO" # log level stored as string
jellyfin_url = "" # jellyfin base url stored as string
jellyfin_api_key = "" # jellyfin API key stored as string
plex_url = "" # plex base url, stored as string
plex_api_key = "" #... |
class backupsolution:
"""Virtual Parent for all Backups
Highlevel-API:
@list_backups( cluster_identifier=None, backup_identifier=None)
@take_backup(kind,cluster_identifier=None)
@remove_backup(kind,backup_identifier=None)
@check(cluster_identifier=None)
@add_cluster(c... |
def run_diagnostic_program(program):
instruction_lengths = [0, 4, 4, 2, 2, 3, 3, 4, 4]
i = 0
while i < len(program):
opcode = program[i] % 100
modes = [(program[i] // 10**j) % 10 for j in range(2, 5)]
if opcode == 99:
break
instruction_length = instruction_lengths... |
multiline_str = """This is a multiline string with more than one line code."""
unicode = u"\u00dcnic\u00f6de"
raw_str = r"raw \n string"
# The value in triple-quotes """ assigned to the multiline_str is a multi-line string literal.
# The string u"\u00dcnic\u00f6de" is a Unicode literal which supports characters other... |
'''
Created on 2018年6月15日
@author: zhaohongxing
'''
class WechatHelper(object):
'''
classdocs
'''
def __init__(self, params):
'''
Constructor
'''
def isPicture(self,path):
if not path:
return False
if path... |
# In python lambda stands for an anonymous function.
# A lambda function can only perform one lines worth of operations on a given input.
greeting = lambda name: 'Hello ' + name
print(greeting('Viewers'))
# You can also use lambda with map(...) and filter(...) functions
names = ['Sherry', 'Jeniffer', 'Ron', 'Sam', '... |
{
"targets": [
{
"target_name": "MagickCLI",
"sources": ["src/magick-cli.cc"],
'cflags!': [ '-fno-exceptions' ],
'cflags_cc!': [ '-fno-exceptions' ],
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")"
],
'dependencies': [
"<!(node -p \... |
# -*- coding: utf-8 -*-
##############################################
# Export CloudWatch metric data to csv file
# Configuration file
##############################################
METRICS = {
'CPUUtilization': ['AWS/EC2', 'AWS/RDS'],
'CPUCreditUsage': ['AWS/EC2', 'AWS/RDS'],
'CPUCreditBalance': ['AWS/EC2', 'AWS/... |
NORTH, EAST, SOUTH, WEST = range(4)
class Compass(object):
compass = [NORTH, EAST, SOUTH, WEST]
def __init__(self, bearing=NORTH):
self.bearing = bearing
def left(self):
self.bearing = self.compass[self.bearing - 1]
def right(self):
self.bearing = self.compass[(self.bearing ... |
#!/usr/bin/env python
# encoding: utf-8
# 函数装饰器
def memp(func):
cache = {}
def wrap(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return wrap
# 第一题
@memp
def fibonacci(n):
if n <= 1:
return 1
return fibonacci(n - 1) + fibonacci(n -... |
class SavingsAccount:
'''Defines a savings account'''
#static variables
RATE = 0.02
MIN_BALANCE = 25
def __init__(self, name, pin, balance = 0.0):
self.name = name
self.pin = pin
self.balance = balance
def __str__(self):
result = "Name: " + self.name + "\n... |
MICROSERVICES = {
# Map locations to their microservices
"LOCATION_MICROSERVICES": [
{
"module": "intelligence.welcome.location_welcome_microservice",
"class": "LocationWelcomeMicroservice"
}
]
}
|
'''
最长公共子序列
描述
给定两个字符串,返回两个字符串的最长公共子序列(不是最长公共子字符串),可能是多个。
输入
输入为两行,一行一个字符串
输出
输出如果有多个则分为多行,先后顺序不影响判断。
输入样例
1A2BD3G4H56JK
23EFG4I5J6K7
输出样例
23G456K
23G45JK
'''
'''
d为方向矩阵
1:上
2:左上
3:左
4:左or上
'''
def LCS (a, b):
C = [[0 for i in range(len(b) + 1)] for i in range(len(a) + 1)] # 定义矩阵C保存最长公共子序列长度
d = [[0 for i in ra... |
ADDRESS_STR = ''
PRIVATE_KEY_STR = ''
GAS = 210000
GAS_PRICE = 5000000000
SECONDS_LEFT = 25
SELL_AFTER_WIN = False |
track_width = 0.6603288840524426
track_original = [(3.9968843292236325, -2.398085115814209), (4.108486819458006, -2.398085115814209),
(4.220117408752442, -2.398085115814209), (4.331728619384766, -2.3980848251342772),
(4.443350294494627, -2.398085115814209), (4.554988441467286, -2.398... |
class DealProposal(object):
'''
Holds details about a deal proposed by one player to another.
'''
def __init__(
self,
propose_to_player=None,
properties_offered=None,
properties_wanted=None,
maximum_cash_offered=0,
minimum_cash_wan... |
email = input()
while True:
line = input()
if line == 'Complete':
break
args = line.split()
command = args[0]
if command == 'Make':
result = ''
if args[1] == 'Upper':
for ch in email:
if ch.isalpha():
ch = ch.upp... |
# B_R_R
# M_S_A_W
# Accept a string
# Encode the received string into unicodes
# And decipher the unicodes back to its original form
# Convention of assigning characters with unicodes
# A - Z ---> 65-90
# a - z ---> 97-122
# ord("A") ---> 65
# chr(65) ---> A
# Enter a string to encode in uppercase
giv... |
# Backtracking is a general algorithm for finding all (or some) solutions to some computational problems, notably
# constraint satisfaction problems, that incrementally builds candidates to the solutions, and abandons a candidate
# ("backtracks") as soon as it determines that the candidate cannot possibly be complete... |
f = open('input.txt').readlines()
f = [line.strip().split(')') for line in f]
nodes = {}
for line in f:
nodes[line[1]] = set()
nodes['COM'] = set()
for line in f:
nodes[line[0]].add(line[1])
def predecessors(n):
global nodes
if n == 'COM':
return set([n])
for p in nodes:
if n ... |
#Creating a single link list static (Example-1)
class Node:
def __init__(self):
self.data=None
self.nxt=None
def assign_data(self,val):
self.data=val
def assign_add(self,addr):
self.nxt=addr
class ListPrint:
def printLinklist(self,tmp):
while(tm... |
# a *very* minimal conversion from a bitstream only fpga to fpga binary format
# that can be loaded by the qorc-sdk bootloader(v2.1 or above)
# 8 word header:
# bin version = 0.1 = 0x00000001
# bitstream size = 75960 = 0x000128B8
# bitstream crc = 0x0 (not used)
# meminit size = 0x0 (not used)
# meminit crc = 0x0 (n... |
class WrapperBase(object):
def __init__(self, instance_to_wrap):
self.wrapped = instance_to_wrap
def __getattr__(self, item):
assert item not in dir(self)
return self.wrapped.__getattribute__(item) |
# coding: utf-8
"""
Common utilities for the Widgets.
"""
TYPE_BTN_CONFIRM = "\u25a3"
TYPE_BTN_REJECT = "\u25c9"
TYPE_BTN_SELECT = "\u25c8"
def make_button_label(label: str, type=TYPE_BTN_CONFIRM, selected: bool = True) -> str:
"""
Turns any label into a button label standard.
:param label: Text
:re... |
def busca(inicio, fim, elemento, A):
if (fim >= inicio):
terco1 = inicio + (fim - inicio) // 3
terco2 = fim - (fim - inicio) // 3
if (A[terco1] == elemento):
return terco1
if (A[terco2] == elemento):
return terco2
if (elemento < A[terco1]):
... |
for _ in range(int(input())):
n = int(input())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
s = ""
for i in range(n):
b[i] -= a[i]
for i in range(1,n):
s += str(abs(b[i] - b[i - 1]))
print("TAK") if (s == s[::-1]) else print("NIE") |
#!/usr/bin/python3
class Complex:
def __init__(self, realpart, imagpart):
self.realpart = realpart
self.imagpart = imagpart
x = complex(3.0, -4.5)
print(x.real, x.imag)
class Test:
def prt(self):
print(self)
print(self.__class__)
t = Test()
t.prt()
|
__version__ = 0.1
__all__ = [
"secure",
"mft",
"logfile",
"usnjrnl",
]
|
letra = input("Digite uma letra: ").lower()
if letra == "a" or letra == "e" or letra == "i" or letra == "o" or letra == "u" or letra == "ão":
print("A letra digitada é uma vogal")
else:
print("A letra digitada é uma consoante") |
def transform_type(val):
if val == 'payment':
return 3
elif val == 'transfer':
return 4
elif val == 'cash_out':
return 1
elif val == 'cash_in':
return 0
elif val == 'debit':
return 2
else:
return 0
def transform_nameDest(val):
dest = val[0]
if dest == 'M':
return 1
elif dest == '... |
class Solution(object):
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
# sketchy but works
greaterThanZero = (num > 0)
powerOfTwo = ((num & (num - 1)) == 0)
oneInOddPosition = ((num & 0x55555555) == num)
return greaterThanZe... |
locs, labels = xticks()
xticks(locs, ("-10%", "-6.7%", "-3.3%", "0", "3.3%", "6.7%", "10%"))
xlabel("Percentage change")
ylabel("Number of Stocks")
title("Simulated Market Performance")
|
{ 'targets': [
{
'target_name': 'yajl',
'type': 'static_library',
'sources': [
'yajl/src/yajl.c',
'yajl/src/yajl_lex.c',
'yajl/src/yajl_parser.c',
'yajl/src/yajl_buf.c',
'yajl/src/yajl_encode.c',
'yajl/src/yajl_gen.c',
'yajl/src/yajl_alloc.c'... |
"""Numerai main tournament metadata.
Convenience module defining some of the more static variables of the
Numerai main tournament.
The tournament is constantly evolving. Metadata from this module might
be outdated. Retrieving the most recent information using the `fetch_`
functions of the `nntm.datasets` module shoul... |
def letUsCalculate():
print("Where n is the number of ELEMENTS in the SET, and R is the samples taken in the function\n")
print("///////////////////////////////\n")
print("///////////////////////////////\n")
print("///////////////////////////////\n")
print("///////////////////////////////\n")
pr... |
n=int(input('Numero:\n'))
i=1
while(i*i<=n):
i=i+1
print('La parte entera de la raiz cuadrada es: '+str(i-1)) |
# Drop Tables
songplay_table_drop = "DROP TABLE IF EXISTS songplays"
user_table_drop = "DROP TABLE IF EXISTS users"
song_table_drop = "DROP TABLE IF EXISTS songs"
artist_table_drop = "DROP TABLE IF EXISTS artists"
time_table_drop = "DROP TABLE IF EXISTS time"
# Create Tables
songplay_table_create =("""
CREATE T... |
dados = []
lista = []
maior = menor = 0
while True:
lista.append(str(input('Digite um nome: ')))
lista.append(float(input('Digite seu peso: ')))
while True:
escol = str(input('Quer continuar?[S/N] ')).upper().split()[0]
if escol in 'SN':
break
dados.append(lista[:])
lista... |
class Bit:
def __init__(self, n):
self.size = n
self.tree = [0] * (n + 1)
def sum(self, i):
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def add(self, i, x):
while i <= self.size:
self.tree[i] += x
... |
"""
Given a string s, find the longest palindromic substring in it.
I/P : "babad"
O/P : "bab"
"aba" is also a valid answer
I/P: "cbbd"
O/P: "bb
"""
# Approach 0 - get all possible substrings and check for palindrome.
# Approach 1: Using sliding window - Expanding around the center
"""
The core logic in this is:
1. Kee... |
def print_rules(bit):
rules = []
# Bit Toggle
rules.append((
"// REG ^= (1 << %d)" % bit,
"replace restart {",
" ld a, %1",
" xor a, #%s" % format((1 << bit) & 0xff, '#04x'),
" ld %1, a",
"} by {",
" bcpl %%1, #%d ; peephole replaced xor b... |
class RedirectException(Exception):
def __init__(self, redirect_to: str):
super().__init__()
self.redirect_to = redirect_to
|
AMAZON_COM: str = "https://www.amazon.com/"
DBA_DK: str = "https://www.dba.dk/"
EXAMPLE_COM: str = "http://example.com/"
GOOGLE_COM: str = "https://www.google.com/"
JYLLANDSPOSTEN_DK: str = "https://jyllands-posten.dk/"
IANA_ORG: str = "https://www.iana.org/domains/reserved"
W3SCHOOLS_COM: str = "https://www.w3sc... |
v = float(input('Qual a velocidade atual do carro? '))
if v > 80:
print('MULTADO! Você excedeu o limite pertimido que é 80km/h')
m = (v - 80) * 7
print('Você deve pagar um multa de {:.2f}'.format(m))
print('Você terá que pagar {}')
print('Tenha um bom dia! Dirija com segurança!')
|
#o objetivo desse algorítimo é ler o primeiro nome da cidade e falar se o primeiro
# nome corresponde ao solicitado
cidade = str(input('Qual o nome da cidade que você nasceu? ')).strip()
print(cidade[:5].upper() == 'SANTO')
|
def read_file_to_string(filename):
with open(filename, 'r') as fin:
return fin.read()
def write_string_to_file(filename, content):
with open(filename, 'w') as fout:
fout.write(content)
|
class SongLine:
# Uniquely ids all song lines
next_id = 0
def __init__(self, song_text: str, song):
"""A song line of a song
:type song_text: str
:param song_text: The lines text
:type song: Song.Song
:param song: The song this line is a part of
"""
#... |
# Coding up the SVM Quiz
clf.fit(features_train, labels_train)
pred = clf.predict(features_test)
|
# https://www.hackerrank.com/challenges/grading/problem
def gradingStudents(grades):
rounded = []
for g in grades:
if (g < 38) or ((g % 5) < 3) :
rounded.append(g)
else:
rounded.append(g + (5 - (g % 5)))
return rounded
|
#!/usr/bin/env python
# coding: utf-8
# In[3]:
class ChineseChef:
def make_chicken(self):
print("The Chef makes Chicken")
def make_salad(self):
print("The Chef Makes Salad")
def make_special_dish(self):
print("The Chef makes Orange Chicken")
def make_fried_rice(self):
... |
Experiment(description='Multi d regression experiment',
data_dir='../data/uci-regression',
max_depth=20,
random_order=False,
k=1,
debug=False,
local_computation=False,
n_rand=2,
sd=2,
jitter_sd=0.1,
max_job... |
N, S = map(int, input().split())
ans = 0
for i in range(1, N+1):
for j in range(1, N+1):
if i + j <= S:
ans += 1
print(ans) |
class Model(object):
__db = None
__cache_engine = None
@classmethod
def set_db(cls, db):
cls.__db = db\
@classmethod
def get_db(cls):
return cls.__db
@property
def db(self):
return self.__db
@classmethod
def set_cache_engine(cls, cache_engine):
... |
# Using third argument in range
lst = [x for x in range(2,21,2)]
print(lst)
# Without using third argument in range
lst1 = [x for x in range(1,21) if(x%2 == 0)]
print(lst1) |
def find_median_sorted_arrays(array_A, array_B):
m, n = len(array_A), len(array_B)
# 如果数组A的长度大于等于数组B,则交换数组
if m > n:
array_A, array_B, m, n = array_B, array_A, n, m
if n == 0:
raise ValueError
start, end, half_len = 0, m, (m + n + 1) // 2
while start <= end:
i = (start + ... |
v = input('Digite o seu sexo (F/M): ').upper().strip()[0]
while v not in 'MmFf':
v = str(input('Resposta inválida. Tente novamente (F/M): ')).strip().upper()[0]
print('Sexo {} registrado com Sucesso.'.format(v))
|
COLUMNS = [
'tipo_registro',
'nro_pv',
'nro_rv',
'dt_rv',
'bancos',
'nro_parcela',
'vl_parcela_bruto',
'vl_desconto_sobre_parcela',
'vl_parcela_liquida',
'dt_credito',
'livre'
] |
"""Calculate the Hamming Distance between two DNA Strands.
Given two strings each representing a DNA strand,
return the Hamming Distance between them.
"""
def distance(strand_a, strand_b):
"""Calculates the Hamming distance between two strands.
Args:
strand_a: A string representing a DNA strand.
... |
class Pista(object):# modelar una pista musical (cancion)
def __init__(self, nombre, favorita, duracion, artista):
self.nombre = nombre #Srting
self.favorita = favorita #tipo boolean
self.duracion = duracion #tipo float
self.artista = artista #String
#Getters and Setters
... |
# 1. Write a line of Python code that displays the sum of 468 + 751
print(0.7 * (220-33) +0.3 * 55)
print(0.8 * (225-33) +0.35 * 55)
|
class CyCyError(Exception):
"""
Base class for non-runtime internal errors.
"""
def rstr(self):
name = self.__class__.__name__
return "%s\n%s\n\n%s" % (name, "-" * len(name), self.__str__())
|
# https://leetcode.com/problems/insert-into-a-binary-search-tree/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def insertIntoBST(self, root: TreeNode, v... |
n = input("Digite algo: ")
print("É um número?", n.isnumeric())
print("É uma letra/palavra?", n.isalpha())
print("É algo vazio?", n.isspace())
print("É um alpha númerico?", n.isalnum())
print("Se for letra, está em maíusculo?", n.isupper())
print("Se for letra, está em minusculo?", n.islower())
print("Se for letra, es... |
#1
f = open('Grade2.txt', "a")
Score = open('Score1.txt',"r")
g=0
ll = Score.readline()
while ll != "":
l = ll.split(",")
#print(l)
eee = l[4][0:2]
e = int(eee)
if g <= e:
g=e
else:
g=g
ll = Score.readline()
print(ll)
f.write(str(g))
f.close()
Score.close() |
def multiplyTwoList(head1, head2):
# Code here
a=""
b=""
temp1=head1
while temp1!=None:
a+=str(temp1.data)
temp1=temp1.next
# print a
temp2=head2
while temp2!=None:
b+=str(temp2.data)
temp2=temp2.next
# print b
return (int(a)*int(b))%MOD
|
"""
Insertion sort
A simple sorting algorithm that builds the final sorted
array (or list) one item at a time. It is much less efficient on
large lists than more advanced algorithms such as quicksort, heapsort,
or merge sort.
Best Average Worst
n n2 n2
""" |
SERVER_ID = 835880446041784350
WELCOME_CHANNEL_ID = 842083947566989392
NOTIFICATIONS_CHANNEL_ID = 848976411082620978
STAFF_ROLE_ID = 842043939380264980
REACTIONS_MESSAGE_ID = 940644226004303902
REACTION_ROLES = {
"⬆️": 848971201946320916, # Server updates
"🥵": 848971574077292604, # Bot updates
"📰": 8489... |
""" local enclosing local enclosing local ,global,builtin (legb)"""
name = 'rajat puri'# global
def greet():
name = 'rajat' #local
def hello():
print("hello"+name) #enclosing local
hello()
greet()
len(hello()) #builtin
|
'''
Created on Sep 22, 2012
@author: Jason
'''
class DatasetError(Exception):
'''
I will use this class to raise dataset-related exceptions.
Common errors: Empty datasets provided, datasets with wrong
number of features, datasets lacking some feature or labels, etc
Used the ready-baked ... |
class App(object):
@property
def ScreenWidth(self):
return 1024
@property
def ScreenHeight(self):
return 768 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.