content stringlengths 7 1.05M |
|---|
def word_len(word):
"""Returns the length of word not counting spaces
>>> word_len("a la carte")
8
>>> word_len("hello")
5
>>> word_len('')
0
>>> word_len("coup d'etat")
10
"""
num = len(word)
for i in range(len(word)):
if word[i] == " ":
num = num-1
... |
def gray_to_binary(gray,bits=4):
"""converts a given gray code to its binary number"""
mask = 1 << (bits - 1)
binary = gray & mask
for i in xrange(bits-1):
bmask = 1 << (bits - i-1)
gmask = bmask >> 1
if (binary & bmask) ^ ((gray & gmask) << 1):
binary = binary | gm... |
# Problem URL: https://leetcode.com/problems/search-in-rotated-sorted-array-ii
class Solution:
def binarySearch(self, array, begin, end, target):
mid = (begin + end)//2
while (begin<=end):
if array[mid] == target:
return True
elif array[mid] < target:... |
# A*搜寻算法
# open_list: 可达到的点集合
# close_list: 已到达的点集合
# F: 从起点到某个格子,再从该格子到终点的总距离预估
# G: 从起点到当前格子的距离
# H: 从当前格子到终点的距离
# F = G + H
# 迷宫需要是一个规则的矩形
maze = [
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[... |
# 問題URL: https://atcoder.jp/contests/abc127/tasks/abc127_a
# 解答URL: https://atcoder.jp/contests/abc127/submissions/14655259
a, b = map(int, input().split())
if a <= 5:
print(0)
elif a <= 12:
print(b // 2)
else:
print(b)
|
# -*- coding: utf-8 -*-
class Solution:
def largestOddNumber(self, num: str) -> str:
for index, digit in enumerate(reversed(num)):
if int(digit) % 2 == 1:
return num[:len(num) - index]
return ''
if __name__ == '__main__':
solution = Solution()
assert '5' == so... |
produce = ['apple','banana', 'cucumber']
volumes = ['one piece', 'cup', 'handful']
d = {}
for i in range(len(produce)):
if produce[i] not in d:
d[produce[i]] = volumes[i]
print(d.items()) |
"""This test's if user successfully registered """
def test_successful_register(successful_registration):
assert successful_registration.email == 'example@email.com'
assert successful_registration.password == 'Password'
assert successful_registration.confirm == 'Password'
response = successful_registra... |
"""
For the opening ceremony of the upcoming sports event an even number of athletes were picked.
They formed a correct lineup, i.e. such a lineup in which no two boys or two girls stand together.
The first person in the lineup was a girl. As a part of the performance,
adjacent pairs of athletes (i.e. the first one tog... |
def get_settings_dot_py_changes(config):
"""Return dictionaries with changed strings of settings.py"""
INSERTED = { # Value inserted before line with key
"from pathlib import Path": "import sys, os\n",
"# Quick-start development settings": (
'# Environment flag\n'
... |
class Jobs:
tag = ''
time_requested = 0
finished = False
def __init__(self, tag_, time_requested_):
self.tag = tag_
self.time_requested = time_requested_
|
class Solution:
#given a list of integer
#return an integer
def maxArea(self, height):
res = 0
left = 0
right = len(height) - 1
while left < right:
if height[left] < height[right]:
res = max(res, height[left] * (right - left))
left ... |
l3 = list(filter(lambda x: 1000 <= x <= 9999, list(int(n * (n + 1)/2)
for n in range(9999))))
l4 = list(filter(lambda x: 1000 <= x <= 9999, list(int(n*n)
for n in range(9999))))
l5 = list(filter(lambda x: 1000 <= x ... |
#
# PySNMP MIB module FN100-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FN100-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:00:25 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... |
#### Translator
eng_fr={'hello':'salut',
'very':'tres',
'good':'Bon',
'see':'voir',
'soon':'bientôt',
'bye':'au revoir',
"house":"maison",
"apple":"pomme",
"tree":"arbre",
"horse":"cheval",
"yellow":"jaune",
"keyboard":"clavier",
... |
def aio_documented_by(original):
def wrapper(target):
target.__doc__ = "Aio function: {original_doc}".format(original_doc=original.__doc__)
return target
return wrapper
def documented_by(original):
def wrapper(target):
target.__doc__ = original.__doc__
return target
r... |
class TurboSMSRouter(object):
app_label = 'turbosms'
db_name = 'turbosms'
def db_for_read(self, model, **hints):
if model._meta.app_label == self.app_label:
return self.db_name
return None
def db_for_write(self, model, **hints):
if model._meta.app_label == self... |
"""
This module implements the FLOAT class, used (sparingly please!) for real number storage and manipulation.
(Ian Howie Mackenzie - April 2009, July 2017)
"""
class FLOAT(float):
"""
simple float handling
"""
def __new__(self, x=0.0):
""" create our (immutable) float
force invalid x to... |
BROWSER_IMPLICIT_WAIT_TIME = 5
MODAL_TRANSITION_WAIT_TIME = 2
BOOTSTRAP_SWITCH_TRANSITION_WAIT_TIME = 1
PAGE_LOADING_WAIT_TIME = 5
PAGE_LOADING_LONG_WAIT_TIME = 10 |
'''
Class
/is holding plate = True
/
attributes:/
/ \
/ tables_responsible = [4, 5, 6]
waiter (object)
\
\ / def take_order(table, order)
... |
# Split-initiator sequences from
# Sequences retrieved from https://dev.biologists.org/content/develop/suppl/2018/06/21/145.12.dev165753.DC1/DEV165753supp.pdf
# Sequences below include 2nt spacers on 3' end of odd and 5' end of even to allow for bending to present initiator.
initiators = {
"B1": {
"odd": "... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class ChoiceFactoryOptions:
def __init__(
self,
inline_separator: str = None,
inline_or: str = None,
inline_or_more: str = None,
include_numbers: bool = None,
) -> None:
... |
"""
Time complexity: O(n*m) (where n = nth sequence, m = length of the longest sequence)
Space complexity: O(m) (for the resulting sequence)
"""
def look_and_say(n):
sequence = "1"
for _ in range(n - 1):
sequence = "".join(groups(sequence))
return sequence
"""
Return an array with pairs [occurrences... |
#!/usr/bin/env python
# $Id: listsets.py,v 2.1 2004/07/14 17:38:53 zeller Exp $
def listminus(c1, c2):
"""Return a list of all elements of C1 that are not in C2."""
s2 = {}
for delta in c2:
s2[delta] = 1
c = []
for delta in c1:
if not s2.has_key(delta):
c.append... |
2227
247
2216
3705
555
166
977
1900
4858
1337
3934
3599
4200
1598
2940
2359
2756
3753
1332
3646
706
428
3958
974
2744
2501
1209
2579
4987
334
2169
2175
4273
2890
3569
1006
2539
3855
1353
2677
1369
2008
59
311
1294
3008
1717
3271
1563
867
3466
187
4939
4719
1485
1243
1898
1169
4667
228
1743
4146
661
2831
158
724
2289
19... |
def docking_data_01(lines):
mask = None
data = dict()
for line in [line.split() for line in lines]:
if line[0] == 'mask':
mask = line[2]
else:
index = line[0]
bits = "{0:b}".format(int(line[2]))
bits = (36-len(bits))*'0' + bits
mask... |
# File: smime_consts.py
# Copyright (c) 2020 Splunk Inc.
#
# Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
# Sign email action related constants
SMIME_SIGN_PROGRESS_MSG = "Signing email message"
SMIME_SIGN_OK_MSG = "Email message signed successfully"
SMIME_SIGN_ERR_MSG = "Error occurred w... |
print("""
084) Faça um programa que leia nome e peso de várias pessoas, guardando tudo
em uma lista. No final, mostre:
A) Quantas pessoas foram cadastradas.
B) Uma listagem com as pessoas mais pesadas.
C) Uma listagem com as pessoas mais leves.
""")
listaDePessoasEPesos = []
maiorPeso = menorPeso = 0
pessoasMaisPesada... |
_list = ['int', 'bool', 'str']
def sys_macro_load():
result = ''
for _type in _list:
with open(f'cool_compiler/codegen/v1_mips_generate/general_macros//{_type}.mips') as mips:
text = mips.read()
mips.close()
result += text[text.index('#region'): text.index('#endregi... |
# coding=utf-8
class App:
TESTING = True
# ReverseProxy.HTTP_X_SCRIPT_NAME='/__'
HOST_URL = 'http://pay.lvye.com'
class Checkout:
ZYT_MAIN_PAGE = 'http://pay.lvye.com/__/main'
VALID_NETLOCS = ['pay.lvye.com']
AES_KEY = "2HF5UKPIADDYBHDSKOVP9GMA80MU2IV2"
PAYMENT_CHECKOUT_VALID_SECONDS = 1 * 60 ... |
"""
This module contains the TissueMAPs interface to Napari
plugin.
"""
|
def get_file_list(num_files):
"""
formats number of files in olympus format
:param num_files:
:return: list of file numbers
"""
file_list = []
for num in range(1, num_files+1):
num = str(num)
to_add = 4-len(num)
final = '0'*to_add+num
file_list.append(final)
... |
# -*- coding: utf-8 -*-
"""
Editor: Zhao Xinlu
School: BUPT
Date: 2018-03-21
算法思想: 合并k个排序链表--分治,时间复杂度为O(nklogk)
"""
"""
Definition of ListNode
"""
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
class Solution:
"""
@param lists: a list of ListNode... |
n = int(input())
p_list = sorted(list(map(int, input().split())))
ret = 0
for i in range(n):
ret += (n-i) * p_list[i]
print(ret) |
expected_output = {
"power_stack": {
"Powerstack-1": {
"allocated_power": 575,
"mode": "SP-PS",
"power_supply_num": 1,
"reserved_power": 0,
"switch_num": 1,
"switches": {
1: {
"allocated_power": 575,... |
class HtmlEmitter(object):
def emit(self, s):
self.file.write(s)
def emit_line(self, s=""):
self.emit(s)
self.emit("\n")
def initialize(self, filename, title, author, date):
self.file = open(filename, "w")
self.emit_line("""<html>
<head>
<link re... |
#
# PySNMP MIB module ENTERASYS-ACTIVATION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENTERASYS-ACTIVATION-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:03:07 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... |
# Cut the sticks
# Given the lengths of n sticks, print the number of sticks that are left before each cut operation.
#
# https://www.hackerrank.com/challenges/cut-the-sticks/problem
#
def cutTheSticks(arr):
# Complete this function
# algorithme:
# il faut soustraire la valeur minimale à chaque fois
#... |
def Qklnu(cfg,k,l,nu) : #function q=Qklnu(k,l,nu)
#
#% Computes Q, neccesary constant#% Computes Q, neccesary consta... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017-05-23 16:23
# @Author : Max
# @File : singleton.py
def singleton(cls):
instance = cls()
instance.__call__ = lambda: instance
return instance
|
# One way to serialize a binary tree is to use pre-order traversal.
# When we encounter a non-null node, we record the node's value. If it is a null node,
# we record using a sentinel value such as #.
# _9_
# / \
# 3 2
# / \ / \
# 4 1 # 6
# / \ / \ / \
# # # # # # #
# For example, the a... |
# HSX hsxuc_events.v1.00p hsxuc_derived.v1.00p
# aliases
aliases = {
"QPIRxMatch1": "Q_Py_PCI_RX_PMON_BOX_MATCH1",
"QPIRxMask1": "Q_Py_PCI_RX_PMON_BOX_MASK1",
"IRPFilter": "IRP_PCI_PMON_BOX_FILTER",
"PCUFilter": "PCU_MSR_PMON_BOX_FILTER",
"QPIRxMask0": "Q_Py_PCI_RX_PMON_BOX_MASK0",
"CBoFi... |
def find_syntax_error(line):
correct = True
incorrect_char = None
complete = True
closing_chars = []
to_close = []
chunk_characters = {
'(': ')',
'{': '}',
'[': ']',
'<': '>'
}
for char in line:
if char in chunk_characters.keys():
... |
class Solution:
def getMaximumGenerated(self, n: int) -> int:
nums = [0,1] + [0]*(n-1)
if n < 2: return nums[n]
for i in range(2, n+1):
if i % 2 == 0 and i//2 <= n:
nums[i] = nums[i//2]
if i % 2 == 1 and i//2 + 1 <= n:
nums[i] = nums[i//2] + nums[i//2+1]
return max(nums)
|
# Copyright 2018 The go-python Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
doc="str"
assert str(b"") == "b''"
assert str(b"hello") == r"b'hello'"
assert str(rb"""hel"lo""") == r"""b'hel"lo'"""
assert str(b"""he
llo""") == r"""b'he... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
return f"{self.val} -> {self.next}"
def mergeLists(lists: List[ListNode]) -> ListNode:
processed_lists = set()
head = None
ptr = None
while True:
# нахождение наименьше... |
setup(
name="better-max-tools-installer",
version="1.0.0",
description="Installer for the Better Max Tools Python package.",
long_description="",
long_description_content_type="text/markdown",
url="https://github.com/thomascswalker/better-max-tools",
author="Thomas Walker",
author_email=... |
def merge(A, left, mid, right):
global cnt
inf = 10**9
L = A[left:mid] + [inf]
R = A[mid:right] + [inf]
i = 0
j = 0
for k in range(left, right):
cnt += 1
if L[i] < R[j]:
A[k] = L[i]
i += 1
else:
A[k] = R[j]
j += 1
def... |
""" Python Program to check Armstrong Number (as 153) """
def checkArmstrong(num):
num = str(num)
order = len(num)
res = 0
for i in num:
res += pow(int(i),order)
return True if res == int(num) else False
N = int(input("Enter the number: "))
if checkArmstrong(N):
print(N,"is... |
class Solution:
def recursiveExist(self, board, i, j, visited, word, k):
# visited.add((i, j))
visited.append((i, j))
if k == len(word):
return True
elif board[i][j] == word[k]:
for di, dj in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
i_, j_ = i +... |
class Weekdays(object):
"""A mock enum. When pep 435 rolls out, this can be upgraded to be a proper
enum.
ref: http://www.python.org/dev/peps/pep-0435/
"""
Sunday = 0
Monday = 1
Tuesday = 2
Wednesday = 3
Thursday = 4
Friday = 5
Saturday = 6
_to_string = {
0: 'Su... |
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
|
print("Hello Word.")
def nome(parameter_list):
a = parameter_list.split(" ", 2)
print(a)
nome('dag cirino mano dev')
nome('dagmar aparecido') |
def construct_square(s):
p = len(s)
d_max = int((10**p)**.5)
d_min = int((10**(p-1))**.5)
for d in range(d_max, d_min -1, -1):
n = str(d * d)
if sorted(s.count(c) for c in set(s)) == sorted(n.count(c) for c in set(n)):
return int(n)
return -1
if __name__ == '__main__':... |
# Lexical scoping in Python and an interesting scenario with resolving value in class.
# Author: Zhuo Lu
# Test suite 1
def test1():
"""
Try to change a nonlocal variable of a parent frame.
"""
def noeffect():
# Uncomment the following line to show that local variable referenced before assign... |
# nested2.py
#
# Nested loop Example 2
# CSC 110
# Fall 2011
#accumulators for the outer loop
sumOuter = 0
for outer in [1, 2, 3, 4]:
print('Outer loop iteration', outer)
sumOuter += outer
sumInner = 0 # accumulator for this inner loop
# notice that the inner loop's repetitions is based on the va... |
class Atom(object):
""" """
def __init__(self, index, name=None, residue_index=-1, residue_name=None):
"""Create an Atom object
Args:
index (int): index of atom in the molecule
name (str): name of the atom (eg., N, CH)
residue_index (int): index of residue i... |
#-----------------------------------------------------------------------------#
# MODULE DESCRIPTION #
#-----------------------------------------------------------------------------#
"""RedBrick Options Module; contains RBOpt class."""
#------------------------... |
def method1(ll1, ll2, n1, n2):
hs = set()
for i in range(0, n1):
hs.add(ll1[i])
print("Intersection:")
for i in range(0, n2):
if ll2[i] in hs:
print(ll2[i], end=" ")
if __name__ == "__main__":
"""
from timeit import timeit
ll1 = [7, 1, 5, 2, 3, 6]
ll2 = [3, ... |
# rock = 0
# paper = 1
# scissors = 2
# paper beats rock
# scissors beats paper
# rock beats scissors
print("Player 1: Type 0 for rock, type 1 for paper, type 2 for scissors")
first_player = int(input())
print("Player 2: Type 0 for rock, type 1 for paper, type 2 for scissors")
second_player = int(input())
if first_pl... |
#!/usr/bin/env python3
"""
Module with functions to performs element-wise operations
"""
def np_elementwise(mat1, mat2):
"""
addition, subtraction, multiplication, and division
Returns the new matrix
"""
return(mat1 + mat2, mat1 - mat2, mat1 * mat2, mat1 / mat2)
|
table_id_map = {
1: "__all_core_table",
2: "__all_root_table",
3: "__all_table",
4: "__all_column",
5: "__all_ddl_operation",
101: "__all_meta_table",
102: "__all_user",
103: "__all_user_history",
104: "__all_database",
105: "__all_database_history",
106: "__all_tablegroup",
107: "__all_tablegro... |
#
# PySNMP MIB module HUAWEI-RIPV2-EXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-RIPV2-EXT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:36:24 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
"""Commonly used utilities."""
__all__ = ('sexpr', 'bap_comment', 'run', 'ida', 'abstract_ida_plugins',
'config', 'bap_taint')
|
"""
19. Altere o programa anterior para que ele aceite apenas números entre 0 e
1000.
"""
numeros = []
numeros = input("Informe um conjunto de números: ").split()
numeros = [int(x) for x in numeros]
while numeros[0] < 0 or numeros[-1] > 1000:
numeros = input("Informe um conjunto de números: ").split()
numero... |
# -*- coding: utf-8 -*-
"""
pip_services_runtime.commands.ICommand
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Interface for commands.
:copyright: Digital Living Software Corp. 2015-2016, see AUTHORS for more details.
:license: MIT, see LICENSE for more details.
"""
class ICommand(object):
... |
# Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file acc... |
class Expansion(object):
__expansion_table = [
31, 0, 1, 2, 3, 4,
3, 4, 5, 6, 7, 8,
7, 8, 9, 10, 11, 12,
11, 12, 13, 14, 15, 16,
15, 16, 17, 18, 19, 20,
19, 20, 21, 22, 23, 24,
23, 24, 25, 26, 27, 28,
27, 28, 29, 30, 31, 0
]
__p = [
1, 2, 3, 4, 5, 8, 9, 10,
11, 14, 15, 16, 17, 20,... |
"""
Finding a peak element:
Given an array of integers.Find a peak element in it. An array element is peak if it is
NOT smaller than its neighbors. For corner elements, we need to consider only one
neighbor. For example, for input array {5,10,20,15}, 20 is the only peak element.
"""
# A python 3 program to find a p... |
# -*- coding: utf-8 -*-
__author__ = "WeizhongTu"
__date__ = '2014.08.01'
# ************************************************
# ---- 网站相关 ----
# URL显示方式
URL_STYLE = 'recommand'
# ---- 文章相关 ----
# ************************************************
#
# 后台文章编辑器样式
# 从这些中选择 'besttome', 'mini', 'normal',更多请在 DjangoUeditor/... |
#
# PySNMP MIB module TIPPINGPOINT-REG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TIPPINGPOINT-REG-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:23:40 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
class SandwichBar:
def whichOrder(self, available, orders):
for i, o in enumerate(orders):
if all(map(lambda e: e in available, o.split())):
return i
return -1
|
CENTS_PER_DOLLAR = 100
class Order(object):
def __init__(self, id, owner, ticker, type, price, qty):
if int(id) < 0:
raise ValueError()
if round(float(price), 2) <= 0:
raise ValueError()
if int(qty) <= 0:
raise ValueError()
self.__id = id
... |
# fileType=Python, blankLineCounts=3, commentCounts=5, commentInLineCounts=0, fileSize=259, lineCounts=7, rowLineCounts=15
def add(x, y):
"""
Hello World """ '''
# Real Second line '''
'''Second''' ''' line
'''
string = "Hello World #\
"
y += len(string)
# Add the two ... |
#!/usr/bin/python3
for i in range(ord('z'), ord('a') - 1, -1):
if (i % 2 != 0):
i = i - 32
i = chr(i)
print("{}".format(i), end='')
|
VERSION = (0, 4, 2)
def get_version():
return '%s.%s.%s' % VERSION
version = get_version()
|
"""
URL: https://codeforces.com/problemset/problem/49/A
Author: Safiul Kabir [safiulanik at gmail.com]
"""
s = ''.join(input().split()).lower()
if s[-2] in ['a', 'e', 'i', 'o', 'u', 'y']:
print('YES')
else:
print('NO')
|
"""
Connecting Cities With Minimum Cost
There are n cities labeled from 1 to n.
You are given the integer n and an array connections where connections[i] = [xi, yi, costi]
indicates that the cost of connecting city xi and city yi (bidirectional connection) is costi.
Return the minimum cost to connect all the n cit... |
cont = contIdade = contHomens = contMulher20 = 0
print('-=' * 15, '\nCadastro de Pessoas')
print('-=' * 15)
while True:
idade = int(input('\033[1mDigite a idade:\033[m '))
if idade >= 18:
contIdade += 1
sexo = ' '
while sexo not in 'MmFf':
sexo = str(input('\033[1mDigite o sexo [M/F]:\03... |
n = int(input().strip())
for i in range(1, n + 1):
cnt = 0
for j in list(str(i)):
if j in ['3', '6', '9']:
cnt += 1
if cnt > 0:
print('-' * cnt, end=' ')
else:
print(i, end=' ')
|
def test_add_group(app, json_groups):
group = json_groups
old_groups = app.group.get_group_list()
app.group.create(group)
# new list is longer, because we added 1 element
assert app.group.count() == len(old_groups) + 1
# if new list length is correct, then we can compare lists.
# so we can... |
class Vector(object):
def __init__(self, x,y):
self.x = x
self.y = y
super(Vector, self).__init__(self, x,y)
|
# Lists
courses=['History','Math','Physics','Compsci']
courses_2=['Football','Basketball']
print("Slicing Examples")
print(len(courses))
print(courses)
print(courses[-1])
print(courses[0:3])
print(courses[::-1])
print("\nAdd")
courses.append('Art')
print(courses)
print("\nInsert at the beginning")
co... |
class DiscordParseException(Exception):
"""An exception that is thrown when parsing Discord's representation of a channel / role / user mention fails."""
def parse_discord_str(content_str: str, type_chars: str) -> int:
"""Parses Discord's representation of a channel / role / user mention into an ID."""
if ... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Created by Ross on 19-1-8
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def solve(ln: ListNode):
if not ln:
return
p = ln
while p:
print(p.val, end=' ')
p = p.next
print()
def test1():
... |
#!/bin/python3
# Calculates factorial
def fact(n):
f = 1
while n > 0:
f *= n
n -= 1
return f
# Calculates Poisson Distribution
def poissonDist(k, l):
return (l**k*(2.71828**(-l)))/fact(k)
if __name__ == '__main__':
x = float(input())
y = float(input())
print(... |
"""
The validation module converts data to and from request format (or at least
calls the converters that do so) and also converts dotted numeric formats into
sequences (e.g. a.0 and a.1 onto a[0] and a[1]). It also includes some
validation exceptions.
"""
class FormishError(Exception):
"""
Base class for all ... |
# Luis Espino 2017
# Búsqueda por anchura y profundidad
# Problema matriz de 3x3
#
# 1 2 3
# 4 5 6
# 7 8 9
def sucesores(n):
if n == 1: return [2, 4, 5]
elif n == 2: return [1, 3, 4, 5, 6]
elif n == 3: return [2, 5, 6]
elif n == 4: return [1, 2, 5, 7, 8]
elif n == 5: return [1, 2, 3, 4, 6, 7 ,8, 9... |
expected_output = {
'model': 'WS-C3650-48PD',
'os': 'iosxe',
'platform': 'cat3k_caa',
'version': '03.06.07E',
}
|
#
# PySNMP MIB module DKSF-54-1-X-X-1 (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DKSF-54-1-X-X-1
# Produced by pysmi-0.3.4 at Wed May 1 12:47:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
#
# print("What's your name?")
# name = input("> ")
#
# print("Hi " + name)
a = 60
b = 7
c = 500
if a > b:
if a > c:
print(a)
else:
print(c)
else:
if b > c:
print(b)
else:
print(c) |
coset_init = lib.coset_init_ll
insert = lib.cs_insert_ll
remove = lib.cs_remove_ll
get_s = lib.cs_get_size_ll
clear = lib.cs_clear_ll
get_min = lib.cs_min_ll
get_max = lib.cs_min_ll
upper_bound = lib.cs_upper_bound_ll
rupper_bound = lib.cs_rupper_bound_ll
get_k = lib.cs_get_k_ll |
"""Email templates"""
verification = \
"""
<html>
<head></head>
<body>
<p>Hi!,<br>
Thanks for using 360buys! Please confirm your email address by clicking
on the link below. We'll communicate with you from time to time via email
so it's important that we h... |
"""
Profile ../profile-datasets-py/div83/062.py
file automaticaly created by prof_gen.py script
"""
self["ID"] = "../profile-datasets-py/div83/062.py"
self["Q"] = numpy.array([ 2.135165, 2.544134, 3.283269, 4.205042,
4.999855, 5.317752, 5.205453, 5.320982,
... |
# Copyright 2004-2008 Roman Yakovenko.
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
"""
This file contains indexing suite v2 code
"""
file_name = "indexing_suite/container_traits.hpp"
code = """// C... |
a = int(input())
b = int(input())
if a > b:
print(1)
elif a < b:
print(2)
else:
print(0) |
"""文字列基礎
文字関連の判定メソッド
英字であるかを判定する isalpha
[説明ページ]
https://tech.nkhn37.net/python-isxxxxx/#_isalpha
"""
print('=== isalpha ===')
print('abcdefgh'.isalpha())
print('abc12345'.isalpha())
|
parrot = "Norwegian Blue"
for char in parrot:
print(char)
|
num1=float(input('Primeiro número: '))
num2=float(input('Segundo número: '))
if num1 > num2:
print('\033[4;31;42mO primeiro valor é maior.\033[m')
elif num2 > num1:
print('\033[1;33;45mO segundo valor é maior.\033[m')
else:
print('Os valores são iguais.')
|
# """
# This is the robot's control interface.
# You should not implement it, or speculate about its implementation
# """
#class Robot:
# def move(self):
# """
# Returns true if the cell in front is open and robot moves into the cell.
# Returns false if the cell in front is blocked and robot sta... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.