content stringlengths 7 1.05M |
|---|
class Solution:
def finalPrices(self, prices: List[int]) -> List[int]:
res = []
for i in range(len(prices)):
for j in range(i+1,len(prices)):
if prices[j]<=prices[i]:
res.append(prices[i]-prices[j])
break
if j==len(p... |
"""Tests for the sbahn_munich integration"""
line_dict = {
"name": "S3",
"color": "#333333",
"text_color": "#444444",
}
|
N, M = map(int, input().split())
for i in range(1, M + 1):
if i % 2 == 1:
j = (i - 1) // 2
print(1 + j, M + 1 - j)
else:
j = (i - 2) // 2
print(M + 2 + j, 2 * M + 1 - j)
|
# for n in range(400,500):
# i = n // 100
# j = n // 10 % 10
# k = n % 10
# if n == i ** 3 + j ** 3 + k ** 3:
# print(n)
# 第一道题(16)
# input("请输入(第一次):")
# s1 = input("请输入(第二次):")
# l1 = s1.split(' ')
# l2 = []
# for i in l1:
# if i.isdigit():
# l2.append(int(i))
# for i in l2:
# ... |
"""
A query transformer is a function that accepts a program and returns a program, plus a priority level.
Higher priority transformers are placed closer to the front of the list. We’re ensuring is a function,
because we’re going to evaluate it later 31 .
We’ll assume there won’t be an enormous number of transformer ad... |
#!/usr/bin/python3.6.8+
# -*- coding:utf-8 -*-
"""
@auth: cml
@date: 2020-12-2
@desc: ...
"""
class JobStatus(object):
PENDING = 0 # 任务等待执行
STARTED = 100 # 任务执行开始
PROCESS = 110
POLLING = 120
CALLBACK = 130
SUCCESS = 200 # 任务执行成功
RETRY = 300 # 任务重试
FAILURE = 400 # 任务执行失败
... |
summary = 0
i = 0
while i < 5:
summary = summary + i
print(summary)
i = i + 1
|
# Store the version here so:
# 1) we don't load dependencies by storing it in __init__.py
# 2) we can import it in setup.py for the same reason
# 3) we can import it into your module module
# https://stackoverflow.com/questions/458550/standard-way-to-embed-version-into-python-package
__version__ = '1.6.1'
release_note... |
input = """
c(2).
p(1).
a(2).
d(2,2,1).
okay(X):- c(X), #count{V:a(V),d(V,X,1)} = 1.
ouch(X):- p(X), #count{V:a(V),d(V,X,1)} = 1.
"""
output = """
{a(2), c(2), d(2,2,1), okay(2), p(1)}
"""
|
#
# PySNMP MIB module XXX-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/XXX-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:44:42 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, 09:23:15)... |
# 添加嘉宾
names = []
names.append('singi')
names.append('lily')
names.append('sam')
print('I find a big dining-table,I can invite more friends.')
names.insert(0, 'xiaoling')
names.insert(2, 'fangsi')
names.append('zhangqing')
greets = ',would you like to have dinner with me ?'
print(names[0]+greets)
print(names[1]+gre... |
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'conditions': [
['OS!="win"', {
'variables': {
'config_h_dir':
'.', # crafted for gcc/linux.
},
}, { # else, ... |
# def mul(a):
# return lambda b:b*a
# singler = mul(1) # addition = lambda b:b*1
# doubler = mul(2) # addition = lambda b:b*2
# tripler = mul(3) # addition = lambda b:b*3
# print(doubler(7)) # 7*2 = 14
# print(tripler(7)) # 7*3 = 21
# print(singler(7)) # 7*1 = 7
class Student:
def __init__(self, fna... |
class MyError(Exception):
pass
class PropertyContainer(object):
def __init__(self):
self.props = {}
def set_property(self, prop, value):
self.props[prop] = value
def get_property(self, prop):
return self.props.get(prop)
def has_property(self, prop... |
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
}
def getWordScore(word, n):
"""
Returns the score for a word. Assu... |
primeiro = int(input('Digite o priemiro termo da PA: '))
razão = int(input('Digite a razão da PA: '))
termo = primeiro
cont = 1
total = 0
mais = 10
while mais != 0:
total += mais
while cont <= total:
print(f'{termo} ', end='')
termo += razão
cont += 1
print('Pausa')
mais = int(in... |
# code....
a = 1
b = 2
c = 3
s = a+b+c
r = s/3
print(r)
# code....
'''
def average():
a=1
b=2
c=3
s=a+b+c
r=s/3
print(r)
average()
'''
'''
#input
#parameter
#argument
def average(a,b,c):
s=a+b+c
r=s/3
print(r)
average(10,20,30)
'''
def average(a, b, c):
s = a+b+c
r = s/3
... |
"""
Base settings for Proxito
Some of these settings will eventually be backported into the main settings file,
but currently we have them to be able to run the site with the old middleware for
a staged rollout of the proxito code.
"""
class CommunityProxitoSettingsMixin:
ROOT_URLCONF = 'readthedocs.proxito.url... |
'''
This is the Settings File for the Mattermost-Octane Bridge.
You can change various variables here to customize and set up the client.
'''
'''----------------------Mattermost Webhook Configuration----------------------'''
#URL of the webhook from mattermost. To create one go to `Main Menu -> Integrations -> Incom... |
def hello_world(request):
request_json = request.get_json()
name = 'World'
if request_json and 'name' in request_json:
name = request_json['name']
headers = {
'Access-Control-Allow-Origin': 'https://furikuri.net',
'Access-Control-Allow-Methods': 'GET, POST',
'Access-Contr... |
#Copyright ReportLab Europe Ltd. 2000-2016
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/graphics/charts/__init__.py
__version__='3.3.0'
__doc__='''Business charts'''
|
total_budget = 0
while True:
destination = input()
if destination == "End":
break
minimal_budget = float(input())
while True:
command = input()
if command == "End":
break
money = float(command)
total_budget += money
if total_budge... |
print('Crie sua P.A. de 10 termos')
n1 = int(input('Digite o primeiro termo da P.A.: '))
r = int(input('Digite a razão: '))
termo = n1
c = 1
print('A P.A. é (', end='')
while c <= 10:
print('{}'.format(termo), end='')
print(', ' if c < 10 else '', end='')
termo += r
c += 1
print(')')
|
price = float(input())
puzzles = int(input())
dolls = int(input())
bears = int(input())
minions = int(input())
trucks = int(input())
total_toys = puzzles + dolls + bears + minions + trucks
price_puzzles = puzzles * 2.6
price_dolls = dolls * 3
price_bears = bears * 4.1
price_minions = minions * 8.2
pric... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of groupthink.
# https://github.com/emanuelfeld/groupthink
# This project is in the public domain within the United States.
# Additionally, the Government of the District of Columbia waives
# copyright and related rights in the work worldwide through t... |
load("//python:compile.bzl", "py_proto_compile", "py_grpc_compile")
load("@grpc_py_deps//:requirements.bzl", "all_requirements")
def py_proto_library(**kwargs):
name = kwargs.get("name")
deps = kwargs.get("deps")
verbose = kwargs.get("verbose")
visibility = kwargs.get("visibility")
name_pb = name ... |
def indexof(listofnames, value):
if value in listofnames:
value_index = listofnames.index(value)
return(listofnames, value_index)
else: return(-1)
|
""" Page object file """
class Page():
""" Page object, it contains information about the pare we are refering, index, items per page, etc. """
page_index = 0
items_per_page = 0
def __init__(self, items_per_page, page_index):
""" Creates the page """
self.page_index = int(page_index)
... |
{
"cells": [
{
"cell_type": "code",
"execution_count": 64,
"metadata": {},
"outputs": [],
"source": [
"# Import libraries\n",
"import os, csv"
]
},
{
"cell_type": "code",
"execution_count": 65,
"metadata": {},
"outputs": [],
"source": [
"#variables for the script\n",
... |
# 题意:给出一个仅包含字符'(',')','{','}','['和']',的字符串,判断给出的字符串是否是合法的括号序列。括号必须以正确的顺序关闭,"()"和"()[]{}"都是合法的括号序列,但"(]"和"([)]"不合法。
# @param s string字符串
# @return bool布尔型
#
class Solution:
def isValid(self , s ):
# write code here
if not s: return True
stack = []
dic = {'{':'}','[':']','(':')'}
... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
__all__ = ["args", "colors", "libcolors", "routine"]
__version__ = "0.96"
|
def area(msg):#declaracao da funcao com o parametro msg
print(msg)#aqui msg e a area
print('Controle de Terrenos')
print('-' * 20)
l = float(input('Largura (m): '))
c = float(input('Comprimento (m): '))
area(f'A área do seu terreno {l}X{c} é de {l*c}m².')
|
# -*- coding: utf-8 -*-
"""Module compliance_suite.exceptions.user_config_exception.py
This module contains class definition for user config file exceptions.
"""
class UserConfigException(Exception):
"""Exception for user config file-related errors"""
pass |
"""Type stubs for _pytest._code."""
# This class actually has more functions than are specified here.
# We don't use these features, so I don't think its worth including
# them in our type stub. We can always change it later.
class ExceptionInfo:
@property
def value(self) -> Exception: ...
|
def get_primes(n):
primes = [] # stores the prime numbers within the reange of the number
sieve = [False] * (n + 1) # stores boolean values indicating whether a number is prime or not
sieve[0] = sieve[1] = True # marking 0 and 1 as not prime
for i in range(2, n + 1): # loops over all the numbers to... |
"""
Module: 'urequests' on esp32 1.12.0
"""
# MCU: (sysname='esp32', nodename='esp32', release='1.12.0', version='v1.12 on 2019-12-20', machine='ESP32 module (spiram) with ESP32')
# Stubber: 1.3.2
class Response:
''
def close():
pass
content = None
def json():
pass
text = None
def... |
s = "([}}])"
stack = []
if len(s) % 2 == 1:
print(False)
exit()
for i in s:
if i == "(":
stack.append("(")
elif i == "[":
stack.append("[")
elif i == "{":
stack.append("{")
elif i == ")":
if len(stack) < 1:
print(False)
exit()
if... |
"""Day 07"""
def process(filename):
with open(filename) as infile:
positions = [int(x) for x in infile.readline().strip().split(',')]
min_x = min(positions)
max_x = max(positions)
costs = {x: 0 for x in range(min_x, max_x + 1)}
for pos in costs.keys():
for crab in positions:
... |
class Foo:
pass
class Bar(Foo):
def __init__(self):
super(Bar, self).__init__() # [super-with-arguments]
class Baz(Foo):
def __init__(self):
super().__init__()
class Qux(Foo):
def __init__(self):
super(Bar, self).__init__()
class NotSuperCall(Foo):
def __init__(self)... |
"""The Ray autoscaler uses tags/labels to associate metadata with instances."""
# Tag for the name of the node
TAG_RAY_NODE_NAME = "ray-node-name"
# Tag for the kind of node (e.g. Head, Worker). For legacy reasons, the tag
# value says 'type' instead of 'kind'.
TAG_RAY_NODE_KIND = "ray-node-type"
NODE_KIND_HEAD = "he... |
_base_ = [
'../retinanet_r50_fpn_1x_coco.py',
'../../_base_/datasets/hdr_detection_minmax_glob_gamma.py',
]
# optimizer
# lr is set for a batch size of 8
optimizer = dict(type='SGD', lr=0.0005, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None) # dict(grad_clip=dict(max_norm=35, norm_t... |
# solution 1:
class Solution1:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1 or numRows >= len(s):
return s
L = [''] * numRows
index, step = 0, 1
for x in s:
L[index] += x
if index == 0:
step = 1
... |
MANIFEST = {
"hilt": {
"h1": {
"offsets": {"blade": 0, "button": {"x": (8, 9), "y": (110, 111)}},
"colours": {
"primary": (216, 216, 216), # d8d8d8
"secondary": (141, 141, 141), # 8d8d8d
"tertiary": (180, 97, 19), # b46113
... |
# Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
# determine if the input string is valid.
# An input string is valid if:
# Open brackets must be closed by the same type of brackets.
# Open brackets must be closed in the correct order.
# Note that an empty string is also considered val... |
""" TW10: Words by Prefix
Team: Tam Tamura, Andrew Nalundasan
For: OMSBA 2061, Seattle University
Date: 11/3/2020
"""
def wordByPrefix(prefix_length, word):
my_dict = {}
for key in word:
for letter in word:
prefix_key = letter[:prefix_length]
letter = word[:prefix_len... |
"""Version information."""
# The following line *must* be the last in the module, exactly as formatted:
__version__ = "0.16.1"
|
## @file
# Standardized Error Hanlding infrastructures.
#
# Copyright (c) 2007 - 2015, Intel Corporation. All rights reserved.<BR>
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text... |
ELECTRUM_VERSION = '4.1.5-radc' # version of the client package
APK_VERSION = '4.1.5.0' # read by buildozer.spec
PROTOCOL_VERSION = '1.4' # protocol version requested
# The hash of the mnemonic seed must begin with this
SEED_PREFIX = '01' # Standard wallet
SEED_PREFIX_SW = '100' # S... |
"""
Class for all excpetions used in following scripts
- geocoder.py
- geocoder_input.py
"""
class OverlappingGeographyError(Exception):
def __init__(self, message):
self.message = message
# msg: geodataframe has overlapping polygons representing geographic features
# please how shapefiles are pro... |
class Node(object):
def __init__(self, name, follow_list, intention, lane):
self.name = name
self.follow_list = follow_list
self.intention = intention
self.lane = lane
def __eq__(self, other):
if isinstance(other, Node):
if self.name == other.get... |
#!python
"""
ANNOTATE FUNCTIONS WITH TIME AND SPACE COMPLEXITY!!!!!
"""
def linear_search(array, item):
"""return the first index of item in array or None if item is not found"""
return linear_search_iterative(array, item)
# return linear_search_recursive(array, item)
def linear_search_iterative(ar... |
class MikanException(Exception):
"""Generic Mikan exception"""
class ConversionError(MikanException, ValueError):
"""Cannot convert a string"""
|
"""
Minimum edit distance computes the cost it takes to get from one string to another string.
This implementation uses the Levenshtein distance with a cost of 1 for insertions or deletions and a cost of 2 for substitutions.
Resource: https://en.wikipedia.org/wiki/Edit_distance
For example, getting from "intention" ... |
# Escribir un programa que muestre la sumatoria de todos los múltiplos de 7 encontrados entre el 0 y el 100.
# Summing all the multiples of 7 from 0 to 100.
total = 0
for i in range(101):
if i % 7 == 0:
total = total+i
print("Sumatoria de los múltiplos de 7:", total)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Function to encrypt message using key is defined
def encrypt(msg, key):
# Defining empty strings and counters
hexadecimal = ''
iteration = 0
# Running for loop in the range of MSG and comparing the BITS
for i in range(len(msg)):
... |
number_of_participants, number_of_pens, number_of_notebooks = map(int, input().split())
if number_of_pens >= number_of_participants and number_of_notebooks >= number_of_participants:
print('Yes')
else:
print('No')
|
"""
Custom exceptions for nflfastpy module
"""
class SeasonNotFoundError(Exception):
pass |
""""
Generator Expression
Em aulas anteriores foi abordado:
- List Comprehension;
- Dictionary Comprehension;
- Set Comprehension.
Não foi abordado:
- Tuple Comprehension ... porque elas se chamam Generators
nomes = ['Carlos', 'Camila', 'Carla', 'Cristiana', 'Cristina', 'Vanessa']
print(any8[nomes[0... |
numero1 = int(input("Digite o primeiro número: "))
numero2 = int(input("Digite o segundo número: "))
numero3 = int(input("Digite o terceiro número: "))
if (numero1 < numero2 and numero2 < numero3):
print("crescente")
else:
print("não está em ordem crescente") |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Now write a program that calculates the minimum fixed monthly payment needed
in order pay off a credit card balance within 12 months.
By a fixed monthly payment, we mean a single number which does not change each month,
but instead is a constant amount that will be ... |
# -*- coding: utf-8 -*-
"""
@file
@brief This the documentation of this module (myexampleb).
"""
class myclass:
"""
This is the documentation for this class.
**example with a sphinx directives**
It works everywhere in the documentation.
.. exref::
:title: an example of use
Ju... |
class Pessoa:
def __init__(self, codigo, nome, endereco, telefone):
self.__codigo = int(codigo)
self.nome = str(nome)
self._endereco = str(endereco)
self.__telefone = str(telefone)
def imprimeNome(self):
print(f"Você pode chamar essa pessoa de {self.nome}.")
def __i... |
# coding: utf-8
# Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
# Aula 17 (Listas (Parte 1))
valores = []
while True:
valor = int(input('Digite um Valor ou -1 para Finalizar: '))
if valor < 0:
print('\nFinalizando...')
break
else:
valores.append(valor)
print(f'Foram digitados {len(valores)} números')
valores.sort(reverse=True)
print(f'Lista ord... |
# Curbrock Summon 2
CURBROCK2 = 9400930 # MOD ID
CURBROCKS_ESCAPE_ROUTE_VER2 = 600050040 # MAP ID
CURBROCKS_ESCAPE_ROUTE_VER3 = 600050050 # MAP ID 2
sm.spawnMob(CURBROCK2, 190, -208, False)
sm.createClock(1800)
sm.addEvent(sm.invokeAfterDelay(1800000, "warp", CURBROCKS_ESCAPE_ROUTE_VER3, 0))
sm.waitForMobDeath(CURBRO... |
def getNumBags(color):
if color=='':
return 0
numBags=1
for bag in rules[color]:
numBags+=bag[1]*getNumBags(bag[0])
return numBags
with open('day7/input.txt') as f:
rules=dict([l.split(' contain') for l in f.read().replace(' bags', '').replace(' bag', '').replace('.', '').replace(' ... |
class SVDError(Exception):
"""Generic errors."""
pass
|
'''
Largest rectangle area in a histogram::
Find the largest rectangular area possible in a given histogram where the largest rectangle can be made of a number of contiguous bars.
For simplicity, assume that all bars have same width and the width is 1 unit.
'''
def max_area_histogram(histogram):
stack = list()... |
def sort(arr):
# Start index 0.
start = 0
# End index
end = len(arr)-1
while start <= end:
# Swap all positive value with last index end & decrease end by 1.
if arr[start] >= 0:
arr[start], arr[end] = arr[end], arr[start]
end -= 1
else:
# ... |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'chromium_code': 1,
},
'includes': [
'../build/win_precompile.gypi',
'base.gypi',
],
'targets': [
{
'tar... |
"""Define mixins to easily compose custom FilterDefinition classes."""
class TermsQueryMixin:
"""A mixin for filter definitions that need to apply term queries."""
def get_query_fragment(self, data):
"""Build the query fragments as term queries for each selected value."""
value_list = data.ge... |
# Look at the charactercreator_character table
# GET_CHARACTERS = """
# SELECT *
# FROM charactercreator_character;
# """
# How many total Characters are there? (302)
TOTAL_CHARACTERS = """
SELECT COUNT(*) as number_of_characters
FROM charactercreator_character;
"""
# How many of each specific subclass?
# TOTAL_SUBC... |
def translate_bbox(bbox, y_offset=0, x_offset=0):
"""Translate bounding boxes.
This method is mainly used together with image transforms, such as padding
and cropping, which translates the left top point of the image from
coordinate :math:`(0, 0)` to coordinate
:math:`(y, x) = (y_{offset}, x_{offse... |
k=0
while k!=1:
print(k)
k+=1
|
class Some_enum(Enum):
some_literal = "some_literal"
class Something(Some_enum):
pass
class Reference:
pass
__book_url__ = "dummy"
__book_version__ = "dummy"
associate_ref_with(Reference)
|
task = '''
Реализовать проект расчета суммарного расхода ткани на производство одежды.
Основная сущность (класс) этого проекта — одежда, которая может иметь
определенное название. К типам одежды в этом проекте относятся пальто и костюм.
У этих типов одежды существуют параметры: размер (для пальто) и рост (для костюма)... |
def orangesRotting(elemnts):
if not elemnts or len(elemnts) == 0:
return 0
n = len(elemnts)
m = len(elemnts[0])
rotten = []
for i in range(n):
for j in range(m):
if elemnts[i][j] == 2:
rotten.append((i, j))
mins = 0
def dfs(rotten):
... |
input = """
2 18 3 0 3 19 20 21
1 1 1 0 18
2 23 3 0 3 19 24 25
1 1 2 1 21 23
3 5 21 19 20 24 25 0 0
6 0 5 5 21 19 20 24 25 1 1 1 1 1
0
21 a
19 b
20 c
24 d
25 e
28 f
0
B+
0
B-
1
0
1
"""
output = """
COST 1@1
"""
|
class TaskA:
def run(self):
V, A, B, C = map(int, input().split())
pass
class TaskB:
def run(self):
A = int(input())
B = int(input())
C = int(input())
X = int(input())
counter = 0
for a in range(A+1):
for b in range(B+1):
... |
def banner_text(text):
screen_width = 80
if len(text) > screen_width - 4:
print("EEK!!")
print("THE TEXT IS TOO LONG TO FIT IN THE SPECIFIED WIDTH")
if text == "*":
print("*" * screen_width)
else:
centred_text = text.center(screen_width - 4)
output_string = "**{0... |
######################################################## FLASK SETTINGS ##############################################################
#Variable used to securly sign cookies
##THIS IS SET IN DEV ENVIRONMENT FOR CONVENIENCE BUT SHOULD BE SET AS AN ENVIRONMENT VARIABLE IN PROD
SECRET_KEY = "dev"
########################... |
'''
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100"、"5e2"、"-123"、"3.1416"、"-1E-16"、"0123"都表示数值,但"12e"、"1a3.14"、"1.2.3"、"+-5"及"12e+5.4"都不是。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/biao-shi-shu-zhi-de-zi-fu-chuan-lcof
'''
class Solution:
def isNumber(self, s: str) -> bool:
states = [
{ ' ... |
def init():
global brightness
global calibration_mode
brightness = 500
calibration_mode = False
|
class Node:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
class SingleLinkedList:
def __init__(self):
self.head = None
def add(self, ele):
new_node = Node(ele)
if self.head is None:
self.head = new_node
... |
def solution(A):
total = sum(A)
m = float('inf')
left_sum = 0
for n in A[:-1]:
left_sum += n
v = abs(total - 2*left_sum)
if v < m:
m = v
return m
|
#! /usr/bin/env python3
"""
constants.py - Contains all constants used by the device manager
Author:
- Pablo Caruana (pablo dot caruana at gmail dot com)
Date: 12/3/2016
"""
number_of_rows = 3 # total number rows of Index Servers
number_of_links = 5 # number of links to be ... |
#!/usr/bin/python2
#
# Copyright (c) 2012 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
"""
Some common boilerplates and helper functions for source code generation
in files dgen_test_output.py and dgen_decode_out... |
def matrix_form():
r = int(input("Enter the no of rows"))
c = int(input("Enter the no of columns"))
matrix=[]
print("Enter the enteries")
for i in range(r):
a = []
for j in range(c):
a.append(int(input()))
matrix.append(a)
return(matrix)
def check_matrix(fi... |
description = 'PGAA setup with XYZOmega sample table'
group = 'basic'
sysconfig = dict(
datasinks = ['mcasink', 'chnsink', 'csvsink', 'livesink']
)
includes = [
'system',
'reactor',
'nl4b',
'pressure',
'sampletable',
'pilz',
'detector',
'collimation',
]
devices = dict(
mcasin... |
"""Queue represented by a pseudo stack (represented by a list with pop and append)"""
class Queue:
def __init__(self):
self.stack = []
self.length = 0
def __str__(self):
printed = "<" + str(self.stack)[1:-1] + ">"
return printed
"""Enqueues {@code item}
@param item
... |
# Assignment 1 Day 8
# write a decorator function for taking input for you
# any kind of function you want to build
def getInput(calculate_arg_fuc):
def wrap_function():
print("Enter two numbers ")
a=int(input("Enter first number = "))
b=int(input("Enter second number = "))
... |
def unlock(m):
return m.lower().translate(
str.maketrans(
'abcdefghijklmnopqrstuvwxyz',
'22233344455566677778889999'
)
)
|
"""
A Token is a button or other object on the table that represents a position, a game state, layer state, or some other piece of info
"""
class Token(object):
def __init__(self, name, table):
self.table = table
self.name = name
self.seat = None
|
nis=get('nis')
q1="xpto1"
q2=nis + "xpto2"
query=query1.q2
koneksi=0
q=execute(query,koneksi)
|
def nearest_mid(input_list, lower_bound_index, upper_bound_index, search_value):
return lower_bound_index + (
(upper_bound_index - lower_bound_index)
// (input_list[upper_bound_index] - input_list[lower_bound_index])
) * (search_value - input_list[lower_bound_index])
def interpolation_search(o... |
#Leia o ano de nascimento de 7 pessoas e mostre quantas ja atingiram a maioridade e quantas ainda não
for c in range(1,8):
p=int(input('Qual o ano de seu nascimento? '))
a=2021-p
if a>= 18:
print('A pessoa numero {} já é maior de idade'.format(c))
else:
print('A pessoa numero {} não é... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Provide function to calculate SDE distance
@auth: Jungang Zou
@date: 2021/05/05
"""
def SDE(front, values1, values2):
shifted_dict = {}
for i in front:
shifted_dict[i] = [(values1[i], values2[i])]
shifted_list = []
for j in front:
... |
"""
funktsioonid.py
Funktsioonide ja protseduuride kasutamine
"""
#
# Protseduur
#
def minu_funktsioon():
print("See on protseduur")
# Kutsume funktsiooni välja
minu_funktsioon()
#
# Funktsioon
#
def liida(num1, num2):
return num1 + num2
sum = liida(3, 5)
print(sum)
# Näide vaikeväärtuste kasutamisest
# ... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
#List and function
# In[6]:
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# list with mixed data types
my_list = [1, "Hello", 3.4]
# In[7]:
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
# In[11]:
# List indexing
my_list = ['p', '... |
def pickingNumbers(a):
# Write your code here
max = 0
for i in a:
c = a.count(i)
d = a.count(i-1)
e = c+d
if e>max:
max = e
return max
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.