content stringlengths 7 1.05M |
|---|
#take a user input
i = input()
print (i)
#int
i = 23
#float
j = 23.5
#bool
k = True
# char
l = 'w'
#string
m = "word"
#input typecasting
print("Try to enter an alphabet")
value1 = input()
value2 = int(value1)
print (value2+1)
print("Please input integers only")
a = int(input())
b = int(input())
#Operator 1
pri... |
class Sensor:
"""Sensor, measures an amount """
last_measure = -1
def __init__(self, range_min=0, range_max=4095, average_converging_speed=1 / 2):
""" constructor.
:param range_min: min value of sensor
:param range_max: max value of sensor
:param average_converging_speed: s... |
"""
*Line-Direction*
Controls the direction of text.
"""
__all__ = ["LineDirection"]
css_syntax = "text-direction"
class LineDirection:
Name = "Direction" # [TODO} ident?
LeftToRight = "ltr"
RightToLeft = "rtl"
|
def add_native_methods(clazz):
def mapAlternativeName__java_io_File__(a0):
raise NotImplementedError()
clazz.mapAlternativeName__java_io_File__ = staticmethod(mapAlternativeName__java_io_File__)
|
card_number = "4532 1512 1994 8973"
print("*" * 12, card_number[-4:len(card_number)])
hidden_card_number = "*" * 12 + card_number[-4:]
print(hidden_card_number)
card_number = "4532151219948973"
print(card_number)
print(card_number[0:4]) #первые 4 символа
print(card_number[12:16]) #последние 4 символа
print(card_n... |
class Timings(object):
def __init__(self, j):
self.raw = j
if "blocked" in self.raw:
self.blocked = self.raw["blocked"]
else:
self.blocked = -1
if "dns" in self.raw:
self.dns = self.raw["dns"]
else:
self.dns = -1
if "... |
# -*- coding: utf-8 -*-
__author__ = "Paul Schifferer <dm@sweetrpg.com>"
"""Constants.
"""
# argument values
DEFAULT_PAGE_SIZE = 50
MAX_PAGE_SIZE = 200
# url parameters
PAGE_PARAM = "page[number]"
LIMIT_PARAM = "page[size]"
SORT_PARAM = 'sort'
INCLUDE_PARAM = "include"
# type info keys
ENDPOINT_PATH = "endpoint_path... |
def splitscore(file_dir):
score = []
Prefix_str = []
f = open(file_dir)
for line in f:
s =line.split()
score.append(float(s[-1]))
s = s[0] + ' ' + s[1] + ' ' + s[2] + ' '
Prefix_str.append(s)
return score,Prefix_str
file_dir1='submission/2019-01-28_15:45:05_fishnet15... |
"""Faça um programa que leia uma frase pelo teclado
e mostre quantas vezes aparece a letra “A”, em que posição ela aparece a primeira vez
e em que posição ela aparece a última vez."""
p = str(input('Digite uma frase qualquer: ')).strip().lower()
print(f'Na frase {p} a letra A aparece {p.count("a")} vezes.')
print('A p... |
layer_info = \
{1: {'B': 1, 'K': 96, 'C': 3, 'OY': 165, 'OX': 165, 'FY': 3, 'FX': 3, 'SY': 2, 'SX': 2, 'SFY': 1, 'SFX': 1, 'PY': 0, 'PX': 0, 'G': 1},
2: {'B': 1, 'K': 42, 'C': 96, 'OY': 165, 'OX': 165, 'FY': 1, 'FX': 1, 'SY': 1, 'SX': 1, 'SFY': 1, 'SFX': 1, 'PY': 0, 'PX': 0, 'G': 1},
3: {'B': 1, 'K': 42, 'C': 42, 'O... |
shelters = ['MNTG1', 'MNTG']
twitter_api_key = 'k5O4owMpAPDcI7LG7y4fue9Fc'
twitter_api_secret = 'XXXXX' #Edited out
twitter_access_token = '2150117929-qnttvTJW3uvP0QbZr2ZKxaBlrkRPa9FdUUWSxqx'
twitter_access_token_secret = 'XXXXX'
|
class LatticeModifier:
object = None
strength = None
vertex_group = None
|
"""
Django LDAP user authentication backend for Python 3.
"""
__version__ = (0, 11, 2)
|
class ModbusException(Exception):
def __init__(self, code):
codes = {
'1': 'Illegal Function',
'2': 'Illegal Data Address',
'3': 'Illegal Data Value',
'4': 'Slave Device Failure',
'5': 'Acknowledge',
'6': 'Slave Device Busy',
... |
'''2. Write a Python program to convert all units of time into seconds.'''
def time_conv(ty, tmo, twk, tdy, thr, tmin):
yr = 365 * 24 * 60 * 60 * ty
mont = 30 * 24 * 60 * 60 *tmo
week = 7 * 24 * 60 * 60 * twk
days = 24 * 60 * 60 * tdy
hrs= 60*60 * thr
mins =60* tmin
return f"{ty} year ={... |
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def postorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
stack = root and [root]
va... |
## Single ended filter chain element
#
class FilterElement(object):
## Constructor
def __init__(self):
self.nextelement = None ##! points at next in chain
self.name = "noname" ##! nicename for printing
## Call to input data into the filter
def input(self, data, meta=None):
r... |
def sequentialSearch(alist, item):
pos = 0
found = False
while pos < len(alist) and not found:
if alist[pos] == item:
found = True
else:
pos += 1
return found
if __name__ == '__main__':
test_list = [1, 2, 32, 8, 17, 19, 42, 13, 0]
print(sequentialSearc... |
class driven_range:
def main(self, inputData):
inputData.sort()
self.inputData = inputData.copy()
return self.generateResult()
def convertDigitalToAnalog(self, digitalValueRange, ADC_Sensor_Type):
# Formula used to convert Digital to Analog:
#
# Analog_Val... |
# Given 2 arrays, create a function that let's a user know (true/false) whether these two arrays contain any
# common items
# For Example:
# const array1 = ['a', 'b', 'c', 'x'];//const array2 = ['z', 'y', 'i'];
# should return false.
# -----------
# const array1 = ['a', 'b', 'c', 'x'];//const array2 = ['z', 'y', 'x'];
... |
# version_info should conform to PEP 386
# (major, minor, micro, alpha/beta/rc/final, #)
# (1, 1, 2, 'alpha', 0) => "1.1.2.dev"
# (1, 2, 0, 'beta', 2) => "1.2b2"
__version_info__ = (0, 1, 0, 'alpha', 0)
def _get_version(): # pragma: no cover
" Returns a PEP 386-compliant version number from version_info. "
a... |
class Options(object):
def __init__(self, dry_run=False, unoptimized=False, verbose=False, debug=False):
self.dry_run = dry_run
self.unoptimized = unoptimized
self.verbose = verbose
self.debug = debug
|
# Bubble Sort implementation.
def bubbleSort(array):
for i in range(len(array) - 1, -1, -1):
for j in range(i):
if array[j] > array[j+1]:
array = exchange(array, j, j+1)
print(array)
return array
# Exchange function implementation.
def exchange(array, i, j):
te... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 2 19:23:43 2019
@author: Lee
"""
|
words = [word.upper() for word in open('gettysburg.txt').read().split()]
theDictionary = {}
for word in words:
theDictionary[word] = theDictionary.get(word,0) + 1
print(theDictionary)
|
#!/usr/bin/env python3
# Small library for generating URLs of visualizations
class Constructor(object):
""" Constructs Google Static Maps API URLs
Constructs requests for the Google Static Maps API by storing substrings of
the overall URL which are created by the add_coords function. The
generate_url ... |
class Mobile:
def __init__(self, brand, price):
print("Inside Constructor")
self.brand = brand
self.price = price
def purchase(self):
print("Purchasing a mobile")
print("The mobile has brand", self.brand, "and price", self.price)
print("Mobile-1")
mob1 = Mobile("Apple",... |
def byte(n):
return bytes([n])
def rlp_encode_bytes(x):
if len(x) == 1 and x < b'\x80':
# For a single byte whose value is in the [0x00, 0x7f] range,
# that byte is its own RLP encoding.
return x
elif len(x) < 56:
# Otherwise, if a string is 0-55 bytes long, the RLP encoding
# consists of a s... |
# coding=utf-8
"""
if rotate_mode == "size":
channel = logging.handlers.RotatingFileHandler(
filename=options.log_file_prefix,
maxBytes=options.log_file_max_size,
backupCount=options.log_file_num_backups,
encoding="utf-8",
) # type: logging.Handler
elif rotate_mode == "time":
... |
pm = sm.getChr().getPotentialMan()
pm.addPotential(pm.generateRandomPotential(1))
sm.completeQuestNoRewards(12394)
sm.dispose()
|
class UpdateIpExclusionObject:
def __init__(self, filterIp, ipFilterId):
self.filterIp = filterIp
self.ipFilterId = ipFilterId
self.memo = None |
class PsKeyCode:
def __init__(self):
pass
def keycode_in_alpha_upper(self, code):
return 65 <= code <= 90
def keycode_in_alpha_lower(self, code):
return 97 <= code <= 122
def keycode_in_alpha(self, code):
return self.keycode_in_alpha_lower(
code
) o... |
def get_grandma(clause_atom, api):
"""Return a wayyiqtol/yiqtol/imperative from a clause tree.
Recursively climbs up a clause's ancestorial tree.
Stops upon identifying either wayyiqtol
or a yiqtol|impv grand(mother).
Returns:
a string of the ancestor's tense, or None.
"""
F, E, L... |
class AnalysisElement:
def __init__(self, validationResult, validationMessage):
self.validation_result = validationResult
self.validation_message = validationMessage
class AnalysisResult:
def __init__(self):
self.elements = []
def add_element(self, element: AnalysisElement):
... |
lim = 10000000
num = [True for _ in range(lim)]
for i in range(4, lim, 2):
num[i] = False
for i in range(3, lim, 2):
if num[i]:
for j in range(i * i, lim, i):
num[j] = False
oa = 0
ob = 0
mnp = 0
size = 1000
for a in range(-size + 1, size):
for b in range(1, size, 2):
np =... |
# -*- coding: utf-8 -*-
"""Tests package for Script Venv."""
__author__ = """Struan Lyall Judd"""
__email__ = 'sv@scifi.geek.nz'
|
# coding=utf-8
"""
Package init file
"""
__all__ = ["catch_event_type", "end_event_type", "event_type", "intermediate_catch_event_type",
"intermediate_throw_event_type", "start_event_type", "throw_event_type"]
|
STATS = [
{
"num_node_expansions": 0,
"search_time": 0.0260686,
"total_time": 0.161712,
"plan_length": 64,
"plan_cost": 64,
"objects_used": 261,
"objects_total": 379,
"neural_net_time": 0.10646533966064453,
"num_replanning_steps": 3,
"w... |
# Numbers are not stored in the written representation, so they can't be
# treated like strings.
a = 123
print(a[1])
|
def get_reversed_string(word):
return word[::-1]
while True:
string = input()
if string == 'end':
break
rev_str = get_reversed_string(string)
print(f'{string} = {rev_str}')
|
def ficha(jogador='<DESCONHECIDO>', gol=0):
print(f'O jogardor {jogador} fez {gol} gol(s)')
nome = str(input('Digite o nome do jogador: '))
gols = str(input(f'Digite o número de gols feito por {nome}: '))
if gols.isnumeric():
gols = int(gols)
else:
gols = 0
if nome.strip() == '':
ficha(gol=gols)
else:... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 24 10:04:30 2020
@author: luisc
"""
#x = 'Estou aqui'
try:
print(p)
except NameError:
print('Ops, deu um erro de variável não inicializada')
except:
print('Outro tipo de erro')
finally:
print('Estou sempre aqui')
# Raise - lança uma exceção para o usuá... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrderBottom(self, root: 'TreeNode') -> 'List[List[int]]':
if not root:
return
stack = [(ro... |
# def function_name_print(a,b,c,d):
#
# print(a,b,c,d)
def funargs(normal,*args, **kwargs):
print(normal)
for item in args:
print(item)
print("\nNow I would like to introduce some of our heroes")
for key,value in kwargs.items():
print(f"{key} is a {value}")
# As a tu... |
"""
This is template on how to configurate your setup for the weedlings model.
You may create a copy of this script and name it "_conf.py" so it will be not be tracked by the ".gitignore"
and is stored only locally.
The "_conf.py" than can be used in other scripts.
"""
PATH = "/home/yourname/projects/weedlings/" # ove... |
class MonoDevelopSvnPackage (Package):
def __init__ (self):
Package.__init__ (self, 'monodevelop', 'trunk')
def svn_co_or_up (self):
self.cd ('..')
if os.path.isdir ('svn'):
self.cd ('svn')
self.sh ('svn up')
else:
self.sh ('svn co http://anonsvn.mono-project.com/source/trunk/monodevelop svn')
se... |
META = {
'70B3D57050001AB9': {
'name': 'Pikkukosken uimaranta',
'lat': 60.227704,
'lon': 24.983821,
'servicemap_url': 'https://palvelukartta.hel.fi/unit/41960',
'site_url': '',
},
'70B3D57050001BBE': {
'name': 'Rastilan uimaranta',
'lat': 60.207977,
... |
class MBTA_Exception(Exception):
"""Superclass for all Exceptions raised in mbta package. """
pass
class MBTA_NotFound(MBTA_Exception):
""" Raised when search returns 404 (Not Found). """
def __init__(self, response, query_val):
parameter = response['errors'][0]['source']['parameter']
... |
#
# PySNMP MIB module CISCOSB-UDP (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-UDP
# Produced by pysmi-0.3.4 at Wed May 1 12:24:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... |
def entry_id(entry):
for field in ['id', 'link']:
ret = getattr(entry, field, None)
if ret:
return ret
raise Exception('no id field found in entry: {}'.format(entry))
|
print("~" * 60)
print("Tower of Hanoi")
def hanoi(n, src, dst, tmp):
if n > 0:
hanoi(n - 1, src, tmp, dst)
print(f"Move disk {n} from {src} to {dst}")
hanoi(n - 1, tmp, dst, src)
hanoi(4, "A", "B", "C")
print("~" * 60)
print("8 Queens Problem")
queen = [0 for _ in range(8)]
rfree = [Tr... |
class Function:
def __init__(self, name, param_types, return_type, line=0):
self.name = name
self.param_types = param_types
self.return_type = return_type
self.line = line
def __str__(self):
return Function.__qualname__
def getattr(self, name):
raise Attrib... |
class Solution:
def minStartValue(self, nums: List[int]) -> int:
total = minSum = 0
for num in nums:
total += num
minSum = min(minSum, total)
return 1 - minSum
|
def conduit_login(driver):
driver.find_element_by_xpath('//a[@href="#/login"]').click()
driver.find_element_by_xpath('//input[@placeholder="Email"]').send_keys("testmail61@test.hu")
driver.find_element_by_xpath('//input[@placeholder="Password"]').send_keys("Testpass1")
driver.find_element_by_xpath('//*[... |
class Node():
def __init__(self, val):
self.val = val
self.adjacent_nodes = []
self.visited = False
# O(E^d) where d is depth
def word_transform(w1, w2, dictionary):
# make dictionary into linked list
start_node = Node(w1)
end_node = Node(w2)
nodes = [start_node, end_node]
... |
# leetcode
class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
num = 366
one, seven, thirty = costs
dp = [0] * num
idx = 0
for i in range(1, num):
dp[i] = dp[i-1]
if i == days[idx]:
... |
'''
The Python repository "AA" contains the scripts, data,
figures, and text for nudged Arctic Amplification (AA) and
Upper-troposphere Tropical Warming (UTW). The model is SC-WACCM4.
We are interested in the large-scale atmospheric response to
Arctic sea ice loss in AA simulations compared to sea-ice forcing.
See Pe... |
# employees = {'marge': 3, 'mag': 2}
# employees['phil'] = '5'
# print(employees.values())
# new_list = list(iter(employees))
# for key, value in employees.iteritems():
# print(key,value)
# print(new_list)
# t = ('a', 'b', 'c', 'd')
# print(t.index('c'))
# print(1 > 2)
# myfile = open('test_file.txt')
# read =... |
sample_pos_100_circle = {
(0, 12, 14, 28, 61, 76) : (0.6606687940575429, 0.12955294286970329, 0.1392231402857147),
(0, 14, 26, 28, 61, 76) : (0.6775622847685568, 0.0898623709846611, 0.14956067316950022),
(0, 11, 12, 14, 23, 28, 42, 44, 76, 79, 89) : (0.6065886283561139, 0.20320288122581232, 0.140052078713... |
# -*- coding: utf-8 -*-
'''Top-level package for lico.'''
__author__ = '''Sjoerd Kerkstra'''
__email__ = 'w.s.kerkstra@example.com'
__version__ = '0.1.1'
|
help_guide = '''命令和二级命令均可只写首字母
/random help - 查阅帮助
/random - 在 [0, 100] 间取一个随机数
/random <数量> - 在 [0, 100] 间取若干个随机数
/random <a> <b> - 在 [a, b] 间取一个随机数
/random <a> <b> <数量> - 在 [a, b] 间取若干个随机数
/random bool - 取随机布尔值(True or False)
/random shuffle <序列> - 打乱该序列
/random choice <序列> - 在序列中挑一个元素
/random choice <序列> <数量> - 在序列中... |
"""Stub implementation containing j2kt_provider helpers."""
def _to_j2kt_jvm_name(name):
"""Convert a label name used in j2cl to be used in j2kt jvm"""
if name.endswith("-j2cl"):
name = name[:-5]
return "%s-j2kt-jvm" % name
def _to_j2kt_native_name(name):
"""Convert a label name used in j2cl t... |
# Author: zhao-zh10
# -----------
# User Instructions:
#
# Modify the the search function so that it becomes
# an A* search algorithm as defined in the previous
# lectures.
#
# Your function should return the expanded grid
# which shows, for each element, the count when
# it was expanded or -1 if the element was never ... |
class Solution:
"""
@param nums: A list of integers
@return: A list of integers includes the index of the first number and the index of the last number
"""
def subarraySum(self, nums):
d = {}
d[0] = -1
L = len(nums)
index = 0
count = 0
while index < L ... |
# python3
class HeapBuilder:
def __init__(self):
self._swaps = []
self._data = []
def ReadData(self):
global n
n = int(input())
self._data = [int(s) for s in input().split()]
assert n == len(self._data)
def WriteResponse(self):
print(len(self._swaps))
for swap in self._... |
# python dict of naming overrides
GENE_NAME_OVERRIDE = {
# pmmo Genes
'EQU24_RS19315':'pmoC',
'EQU24_RS19310':'pmoA',
'EQU24_RS19305':'pmoB',
# smmo Genes
'EQU24_RS05930':'mmoR',
'EQU24_RS05925':'mmoG',
'EQU24_RS05910':'mmoC',
'EQU24_RS05900':'mmoZ',
'EQU24_RS05895':'mmoB',
'EQU24_RS05890':'mmoY',
'EQU24... |
"""
107. Word Break
https://www.lintcode.com/problem/word-break/description?_from=ladder&&fromId=160
Memoization
"""
class Solution:
"""
@param: s: A string
@param: dict: A dictionary of words dict
@return: A boolean
"""
def wordBreak(self, s, dict):
# write your code here
if dic... |
class Coordinate:
coordX = 0
coordY = 0
def __init__(self, coordX=0, coordY=0):
self.coordX = coordX
self.coordY = coordY
pass
def set(self, coordX, coordY):
self.coordX = coordX
self.coordY = coordY
return coordX, coordY
if __name__ == '_... |
apiAttachAvailable = u'API Kullanilabilir'
apiAttachNotAvailable = u'Kullanilamiyor'
apiAttachPendingAuthorization = u'Yetkilendirme Bekliyor'
apiAttachRefused = u'Reddedildi'
apiAttachSuccess = u'Basarili oldu'
apiAttachUnknown = u'Bilinmiyor'
budDeletedFriend = u'Arkadas Listesinden Silindi'
budFriend = u'Arkadas'
bu... |
# Copyright (C) 2015-2016 Ammon Smith and Bradley Cai
# Available for use under the terms of the MIT License.
__all__ = [
'print_success',
'print_failure',
]
def print_success(target, usecolor, elapsed):
if usecolor:
start_color = '\033[32;4m'
end_color = '\033[0m'
else:
start... |
#
# PySNMP MIB module IANA-GMPLS-TC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IANA-GMPLS-TC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:19:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
'''
int():将一个数值或字符串转换成整数,可以指定进制。
float():将一个字符串转换成浮点数。
str():将指定的对象转换成字符串形式,可以指定编码。
chr():将整数转换成该编码对应的字符串(一个字符)。
ord():将字符串(一个字符)转换成对应的编码(整数)。
'''
a = 76
b = 'y'
print(int(a))
print(float(a))
print(str(a))
print(chr(a))
print(ord(b))
|
"""
Faça um programa que leia 3 números e fale qual é o maior e qual é o menor
"""
num1 = int(input('Digite o número 1: '))
num2 = int(input('Digite o número 2: '))
num3 = int(input('Digite o número 3: '))
menor = num1
if num2 < num1 and num2 <num3:
menor = num2
if num3 < num1 and num3 < num2:
menor = num3
ma... |
letters = ["a", "e", "t", "o", "u"]
word = "CreepyNuts"
if (word[1] in letters) and (word[6] in letters):
print(0)
elif (word[1] in letters) or (word[6] in letters):
print(1)
else:
print(2)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2017 - hongzhi.wang <hongzhi.wang@moji.com>
'''
Author: hongzhi.wang
Create Date: 2019-09-04
Modify Date: 2019-09-04
'''
|
def parse_input(file):
return [[int(h) for h in l] for l in open(file).read().splitlines()]
input = parse_input('./day 09/Xavier - Python/input.txt')
example = parse_input('./day 09/Xavier - Python/example.txt')
def get_neighbours(map,i,j):
neighbours = []
if i > 0:
neighbours.append((i-1,j))
... |
_base_ = ['./mask_rcnn_r50_8x2_1x.py']
model = dict(roi_head=dict(type='BTRoIHead',
bbox_head=dict(type='Shared2FCCBBoxHeadBT',
loss_cls=dict(type="EQLv2"),
loss_opl=dict(
... |
# -*- coding: utf-8 -*-
# System
SYSTEM_LANGUAGE_KEY = 'System/Language'
SYSTEM_THEME_KEY = 'System/Theme'
SYSTEM_THEME_DEFAULT = 'System'
# File
FILE_SAVE_TO_DIR_KEY = 'File/SaveToDir'
FILE_SAVE_TO_DIR_DEFAULT = ''
FILE_FILENAME_PREFIX_FORMAT_KEY = 'File/FilenamePrefixFormat'
FILE_FILENAME_PREFIX_FORMAT_DEFAULT = ... |
#Get roll numbers, name & marks of the students of a class(get from user) and store these details in a file- marks.txt
count = int(input("How many students are there in class? "))
fileObj = open('marks.txt',"w")
for i in range(count):
print("Enter details for student",(i+1),"below:")
rollNo = int(input("Rolln... |
# -*- coding: utf-8 -*-
"""Untitled1.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1W2P2nxzaV_t_ePeJDnZMmbLkhvRxqZaF
"""
#used for quick sort algo
#pivot is taken as last element
def lomutoPartition(arr,l,h):
pivot=arr[h]
i=l-1
for j in r... |
# id: 640;Stairs
# title:"Schody",
# about:"",
# robotCol:3,
# robotRow:10,
# robotDir:3,
# subs:[3,3,0,0,0],
# allowedCommands:0,
# board:" ggggggggGG gggggggGGg ggggggGGgg gggggGGggg ggggGGgggg gggGGggggg ggGGgggggg gGGggggggg GGgggggggg gggggggggg ... |
class DSU:
def __init__(self, N):
self.par = list(range(N))
def find(self, U):
if self.par[U] != U:
self.par[U] = self.find(self.par[U])
return self.par[U]
def union(self, U, V):
X, Y = self.find(U), self.find(V)
self.par[X] = Y
class Solution:
def... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 29 09:58:39 2018
@author: nsde
"""
#%%
#%%
def tf_mahalanobisTransformer(X, scope='mahalanobis_transformer'):
""" Creates a transformer function that for an given input matrix X,
calculates the linear transformation L*X_i """
with t... |
nome = ' Pedro da Silva Moreira'
nomeSeparado = nome.split()
print('O primeiro nome é:')
print(nomeSeparado[0])
#assim
print('O último nome é:')
print(nomeSeparado[-1])
#ou assim
print('O último nome é:')
print(nomeSeparado[len(nomeSeparado)-1])
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# simple dictionary
mybasket = {'apple':2.99,'orange':1.99,'milk':5.8}
print(mybasket['apple'])
# dictionary with list inside
mynestedbasket = {'apple':2.99,'orange':1.99,'milk':['chocolate','stawbery']}
print(mynestedbasket['milk'][1].upper())
# append more key
myba... |
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
if not grid or not grid[0]:
return 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]:
return self.dfs(grid, i, j)
return 0
def dfs... |
class Solution:
def addBinary(self, a, b):
res, carry = '', 0
i, j = len(a) - 1, len(b) - 1
while i >= 0 or j >= 0 or carry:
curval = (i >= 0 and a[i] == '1') + (j >= 0 and b[j] == '1')
carry, rem = divmod(curval + carry, 2)
res = str(rem) + res
... |
#this function would write data in the database
def write_data(name, phone, pincode, city, resources):
#here we will connect to database
#and write to it
f = open('/Users/mukesht/Mukesh/Github/covid_resource/resource_item.text', 'a')
f.write(name + ', ' + phone + ', ' + pincode + ', ' + city + ', [' + resource... |
def validate(n):
string = str(n)
mod = 0 if len(string) % 2 == 0 else 1 # 0 for even, 1 for odd
total = 0
for i, a in enumerate(string):
current = int(a)
if i % 2 == mod:
double = current * 2
if double > 9:
total += double - 9
else:
... |
expected_output = {
"interfaces": {
"Port-channel1": {
"name": "Port-channel1",
"protocol": "lacp",
"members": {
"GigabitEthernet0/0/1": {
"activity": "Active",
"age": 18,
"aggregatable": True,
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
inputs = [
"LLLRLLULLDDLDUDRDDURLDDRDLRDDRUULRULLLDLUURUUUDLUUDLRUDLDUDURRLDRRRUULUURLUDRURULRLRLRRUULRUUUDRRDDRLLLDDLLUDDDLLRLLULULRRURRRLDRLDLLRURDULLDULRUURLRUDRURLRRDLLDDURLDDLUDLRLUURDRDRDDUURDDLDDDRUDULDLRDRDDURDLUDDDRUDLUDLULULRUURLRUUUDDRLDULLLUDLULDUUDLDLRRLLLRLDUDRUU... |
'''Faça um programa que leia 4 notas, mostre as notas e a média na tela.'''
notas = []
nota1 = float(input('Digite a primeira nota: '))
notas.append(nota1)
nota2 = float(input('Digite a segunda nota: '))
notas.append(nota2)
nota3 = float(input('Digite a terceira nota: '))
notas.append(nota3)
nota4 = float(input('Di... |
#!/usr/bin/env python3
def num_sol(n):
if n==1:
return 1
if n==2:
return 2
solu=num_sol(n-1)+num_sol(n-2)
return solu
# def unrank(n, pos, sorting_criterion="loves_long_tiles"):
# return "(" + unrank(n_in_A, (pos-count) // num_B) + ")" + unrank(n - n_in_A -1, (pos-count) % num... |
def check_geneassessment(result, payload, previous_assessment_id=None):
assert result["gene_id"] == payload["gene_id"]
assert result["evaluation"] == payload["evaluation"]
assert result["analysis_id"] == payload.get("analysis_id")
assert result["genepanel_name"] == payload["genepanel_name"]
assert r... |
def run(m):
sites = m.qualify(["""
SELECT ?equip ?sensor ?setpoint ?sensor_uuid ?setpoint_uuid WHERE {
?setpoint rdf:type/rdfs:subClassOf* brick:Air_Flow_Setpoint .
?sensor rdf:type/rdfs:subClassOf* brick:Air_Flow_Sensor .
?setpoint bf:isPointOf ?equip .
?sensor b... |
# -*- coding: utf-8 -*-
'''
Author: Hannibal
Data:
Desc: local data config
NOTE: Don't modify this file, it's build by xml-to-python!!!
'''
fightbuff_map = {};
fightbuff_map[1001] = {"id":1001,"name":"强壮","type":"增益","refresh":1,"count":3,"data":[{"prop":"气血增加","value":"1000.0",},],};
fightbuff_map[1002] = {"id":10... |
class Edge:
def __init__(self, start, end):
self.start = start
self.end = end
def __str__(self):
return "<" + str(self.start) + " " + str(self.end) + ">"
|
class Solution:
def minOperations(self, boxes: str) -> List[int]:
ans = [0]*len(boxes)
lc = 0
lcost = 0
rc = 0
rcost = 0
for i in range(1,len(boxes)):
if boxes[i-1]=="1": lc+=1
lcost += lc
ans[i] = lcost
for i in range(len(... |
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
op = {
"+": lambda x, y: x + y,
"-": lambda x, y: x - y,
"*": lambda x, y: x * y,
"/": lambda x, y: x // y if x * y >= 0 else -(-x // y),
}
for token in tokens:
... |
'''Faça um programa que
leia o nome completo de uma pessoa, mostrando em
seguida o primeiro e o último nome separadamente.'''
print('''Não e necessário utilizarmos o len nessa situação, ficou entendido no
último exercício que a leitura pode ser vista de trás pra frente utilizando -1''')
next = input("Aperte enter para... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.