content stringlengths 7 1.05M |
|---|
# This function checks if the number(num)
# is a prime number or not
# and It is the most fastest, the most optimised and the shortest function I have created so far
# At first if number is greater than 1,
# and it is not devided by 2 and it is not to itself either,
# Then it devide this number to all prime numbers unt... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# 3. Программа, которая считывает длины катетов прямоугольного треугольника и вычисляет длину его гипотенузы
number1 = int(input('Введите длину первого катета: '))
number2 = int(input('Введите длину второго катета: '))
hypotenuse = (number1 ** 2 + number2 ** 2) ** 0.5
print... |
#!/usr/bin/env python3
def permurarion(s, start):
if not s or start<0:
return
if start == len(s) -1:
print("".join(s))
else:
i = start
while i < len(s):
s[i], s[start] = s[start], s[i]
permurarion(s, start+1)
s[i], s[start] = s[start... |
"""
Given a complete binary tree, count the number of nodes.
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last... |
##Patterns: E1128
def test():
return None
##Err: E1128
no_value_returned = test() |
def parse_mecab(block):
res = []
for line in block.split('\n'):
if line == '':
return res
(surface, attr) = line.split('\t')
attr = attr.split(',')
lineDict = {
'surface': surface,
'base': attr[6],
'pos': attr[0],
'pos1'... |
# Class decorator alternative to mixins
def LoggedMapping(cls):
cls_getitem = cls.__getitem__
cls_setitem = cls.__setitem__
cls_delitem = cls.__delitem__
def __getitem__(self, key):
print('Getting %s' % key)
return cls_getitem(self, key)
def __setitem__(self, key, value):
... |
t = int(input)
while t:
i = int(input())
print(sum([(-1 ** i) / (2 * i + 1) for i in range(i)]))
t -= 1
|
#
# PySNMP MIB module Finisher-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Finisher-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:03:08 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,... |
#!/usr/bin/env python3
N = int(input().strip())
arr = [int(i) for i in input().strip().split()]
sorted_arr = sorted(arr)
diff_arr = [sorted_arr[i + 1] - sorted_arr[i] for i in range(0, N - 1)]
min_diff = min(diff_arr)
idx = [i for i in range(len(diff_arr)) if diff_arr[i] == min_diff]
for i in idx:
print(sorted_arr... |
expected_output = {
"pod": {
1: {
"node": {
1: {
"name": "msl-ifav205-ifc1",
"node": 1,
"pod": 1,
"role": "controller",
"version": "5.1(2e)"
},
101:... |
#
# Copyright (c) 2017 Digital Shadows Ltd.
#
# Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
#
__version__ = '1.1.0'
|
# Вам нужно реализовать функцию rotate, которая должна принимать список в качестве аргумента и делать над ним следующее
# преобразование (список нужно изменять "на месте"!): последний элемент списка должен быть перемещён в начало списка
# (см. пример ниже). Если функция получает пустой список, то изменять его она не до... |
test = open('test.txt', 'r')
arr = []
for group in test:
arr.append(int(group.split()[0]))
# Correct Answers:
# - Part 1: 10884537
# - Part 2: 1261309
# ======= Part 1 =======
def part1():
for i in range(25, len(arr)):
sum = False
for j in range(i - 25, i):
if arr[i] -... |
#!/usr/bin/python3
# -*-coding:utf-8-*-
__author__ = "Bannings"
class Solution:
def detectCapitalUse(self, word: str) -> bool:
isupper = word[-1].isupper()
for i in range(len(word) - 2, -1, -1):
if word[i].isupper() != isupper and (isupper or i != 0):
return False
... |
# -*- coding: utf-8 -*-
"""
:author: David Siroky (siroky@dasir.cz)
"license: MIT License (see LICENSE.txt or
U{http://www.opensource.org/licenses/mit-license.php})
"""
VERSION = "1.6"
PROTOCOL_VERSION = 1
|
shapenet_30afd2ef2ed30238aa3d0a2f00b54836 = dict(filename= "30afd2ef2ed30238aa3d0a2f00b54836.png" , basic= "dining", subordinate= "dining_00" , subset="A", cluster= 1, object_num= 0, pose= 35, url= "https://s3.amazonaws.com/shapenet-graphical-conventions/30afd2ef2ed30238aa3d0a2f00b54836.png",width= 256, height= 256);
s... |
IN_PREDICTION="../predictionsULMFiT_200_noLM.csv"
IN_GOLD="../data/sentiment2/tgt-test.txt"
# pred-sentiment.txt Accuracy: 0.9025
# pred-sentiment-trans.txt 0.9008333333333334
# ../pred-sentiment2.txt" 0.9462672372800761
# ../pred-sentiment2-gru.txt 0.948644793152639
# ../pred-sentiment2-large.txt" 0.9481692819781264
... |
# Copyright 2020 The Google Earth Engine Community Authors
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
class Footers(object):
def __init__(self, footers: dict, document):
# TODO
self._footers = footers
self._document = document
|
def log_error(e):
"""
It is always a good idea to log errors.
This function just prints them, but you can
make it do anything.
"""
print(e)
|
# La secuencia de Fibonacci es una función matemática que se define recursivamente.
# En el año 1202, el matemático italiano Leonardo de Pisa, también conocido como Fibonacci,
# encontró una fórmula para cuantificar el crecimiento que ciertas poblaciones experimentan.
# Imagina que una pareja de conejos nace, un mach... |
# Input: A list / array with integers. For example:
# [3, 4, 1, 2, 9]
# Returns:
# Nothing. However, this function will print out
# a pair of numbers that adds up to 10. For example,
# 1, 9. If no such pair is found, it should print
# "There is no pair that adds up to 10.".
def pair10(given_list):
numbers_se... |
# 62. Unique Paths
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
paths = [[(0 if k > 0 and i > 0 else 1) for i in range(m)] for k in range(n)]
for col in range(1, m):
for row in range(1, n):
if row > 0:
paths[row][col] += path... |
# Finite State Expression Parser Function
# Authored by Vishnuprasadh
def parser(fa, fa_dict):
fa_dict.update({"start": ""})
fa_dict.update({"final": []})
fa_dict.update({"transitions": {}})
start = final = False # Keeps track of start and final states
init_tracker = -1 # Keeps track of the begi... |
"""
Allergies exercise
"""
class Allergies:
"""
Class to get all allergies from a score
"""
def __init__(self, score):
"""
Calculate list of allergies from score using dynamic programming
"""
self.dct = {
1: "eggs",
2: "peanuts",
... |
# CHALLENGE: https://www.hackerrank.com/challenges/30-2d-arrays
def build_arr():
arr = []
for arr_i in range(6):
arr_t = [int(arr_temp) for arr_temp in input().strip().split(' ')]
arr.append(arr_t)
return arr
def is_square_arr(arr):
for e in arr:
if len(e) != len(arr):
... |
class Solution:
def twoSum(self, nums, target):
'''
# leetcode problem: https://leetcode.com/problems/two-sum/
Method-1: Bruteforce
time compx: O(n^2)
space compx: O(1)
def twoSum(self, nums, targer):
"""TODO: Docstring for bruteForceTwoSum.
... |
'''
Задача «Удаление символа»
Условие
Дана строка. Удалите из этой строки все символы @.
'''
s = input()
# s = '@W@E@E@E@R'
# s.replace('W', ' ') # применение функции разобрать!
# s1 = s.replace('@', '') # применение функции разобрать!
print(s.replace('@', ''))
# print(s1)
|
#Copyright ReportLab Europe Ltd. 2000-2006
#see license.txt for license details
__version__=''' $Id: boxstuff.py 2960 2006-08-23 21:41:33Z andy $ '''
def anchorAdjustXY(anchor,x,y,width,height):
if anchor not in ('sw','s','se'):
if anchor in ('e','c','w'):
y -= height/2.
else:
... |
"""
This Module populate or provide the starting material
for running the SELECTA workflow.
Information from the process_selection table as well
as the SELECTA propertie.txt files are consumed here.
"""
__author__ = 'Nima Pakseresht, Blaise Alako'
class selection:
"""
This Class Initialise the SELECTA workfl... |
companions = int(input())
days = int(input())
coins = 0
for day in range(1, days + 1):
if day % 15 == 0:
companions += 5
if day % 10 == 0:
companions -= 2
if day % 5 == 0:
coins += (companions * 20)
if day % 3 == 0:
coins -= (companions * 2)
if day % 3 == ... |
dia=input('dia=')
mes=input('mes=')
ano=input('ano')
print('Você nasceu no dia', dia, 'de', mes,'de', ano,'. Correto?')
print('Você nasceu no dia {}'.format(dia),'de {}'.format(mes),'de {}'.format(ano),'. Correto?')
|
#
# PySNMP MIB module ZXTM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZXTM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:48: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 2019, 09:23:1... |
'''
Takes raw radiosonde data file from NSGRA-2, removes data that's not required by the simulator, outputs _filtered version.
This _filtered file is the file MAPLEAF expects when using radiosonde mean wind models
'''
if __name__ == "__main__":
# Adjust input (unfiltered) file location here
filePath ... |
class FakeTimer:
def __init__(self, time, function, args=None, kwargs=None):
self._time = time
self._function = function
self._args = args if args is not None else []
self._kwargs = kwargs if kwargs is not None else {}
self._canceled = False
self._started = False
... |
# Declare a variable of `name` with an input and a string of "Welcome to the Boba Shop! What is your name?".
name = input("Welcome to the Boba Shop! What is your name?")
# Check if `name` is not an empty string or equal to `None`.
if name != "" or name == None:
# If so, write a print with a string of "Hello" conca... |
# *************************************************************************
#
# Copyright (c) 2021 Andrei Gramakov. All rights reserved.
#
# This file is licensed under the terms of the MIT license.
# For a copy, see: https://opensource.org/licenses/MIT
#
# site: https://agramakov.me
# e-mail: mail@agramakov.me
#
#... |
class Solution:
def solve(self, nums, k):
mods = set()
last = 0
psum = 0
for num in nums:
psum += num
if psum%k in mods: return True
mods.add(last)
last = psum%k
return False
|
class FrameworkRichTextComposition(FrameworkTextComposition):
""" Represents a composition related to text input. You can use this class to find the text position of the composition or the result string. """
CompositionEnd=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the end posit... |
# -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
def minimumAbsoluteDifference(arr):
# Another way to define this problem is "find the pair of numbers with the smallest distance from each other".
# Easiest to begin approaching this problem is to sort the data set.
sorted_arr = list(sorted(arr))
pairs = zip(sorted_arr, sorted_arr[1:])
# The da... |
def sqrt(x):
i = 1
while i*i<=x:
i*=2
y=0
while i>0:
if(y+i)**2<=x:
y+=i
i//=2
return y
t=100**100
print(sum(
int(c) for c in str(sqrt(t*2))[:100]
))
ans = sum(
sum(int(c) for c in str(sqrt(i * t))[ : 100])
for i in range(1,101)
if sqrt(i)**2 != ... |
class Animal:
def __init__(self, name, color, age, gender):
self.name = name
self.color = color
self.age = age
self.gender = gender
@classmethod
def cry(cls):
print('类方法: 叫')
@classmethod
def run(cls):
print('类方法:跑')
class Cat(Animal):
def __... |
class CoolError(Exception):
def __init__(self, text, line, column):
super().__init__(text)
self.line = line
self.column = column
@property
def error_type(self):
return 'CoolError'
@property
def text(self):
return self.args[0]
def __str__(s... |
candyCan = ["apple", "strawberry", "grape", "mango"]
print(candyCan[1])
print(candyCan[-1])
print(candyCan[1:3]) |
class ListNode:
def __init__(self, value, prev=None, next=None):
self.value = value
self.prev = prev
self.next = next
def insert_after(self, value):
pass
def insert_before(self, value):
pass
def delete(self):
pass
class DoublyLinkedList:
def __init__(self, node=None):
self.head... |
"""Class for converter models."""
class InverterModels:
"""
SwitcInverter class.
Attributes:
():
"""
def ODE_model_single_phase_EMT(self,y,t,signals,grid,sim):
"""ODE model of inverter branch."""
self.ia,dummy = y # unpack current values of y... |
def count(start=0, step=1):
while True:
yield start
start += step
def cycle(p):
try:
len(p)
except TypeError:
# len() is not defined for this type. Assume it is
# a finite iterable so we must cache the elements.
cache = []
for i in p:
yie... |
# 169. Majority Element
# Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
# You may assume that the array is non-empty and the majority element always exist in the array.
class Solution(object):
def majorityElement(self, nums):
... |
'''
Assembling your data
Here, three DataFrames have been pre-loaded: g1800s, g1900s, and g2000s. These contain the Gapminder life expectancy data for, respectively, the 19th century, the 20th century, and the 21st century.
Your task in this exercise is to concatenate them into a single DataFrame called gapminder. Th... |
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.data = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.data.append(x)
def pop(self):
"""
:rtype: void
... |
description = 'collimator setup'
group = 'lowlevel'
devices = dict(
tof_io = device('nicos.devices.generic.ManualSwitch',
description = 'ToF',
states = [1, 2, 3],
lowlevel = True,
),
L = device('nicos.devices.generic.Switcher',
description = 'Distance',
moveable = '... |
inf = 2**33
DEBUG = 0
def bellmanFord(graph, cost, loop, start):
parent = [-1] * len(graph)
cost[start] = 0
for i in range(len(graph) - 1):
for u in range(len(graph)):
for v, c in graph[u]:
if (cost[u] + c < cost[v] and cost[u] != inf):
parent[v] = u
... |
def chop(t):
del t[0], t[-1]
return None
def middle(t):
return t[1:-1]
letters = ['a', 'b', 'c', 'd', 'e']
print(middle(letters))
|
"""Build extension to generate j2cl-compatible protocol buffers.
Usage:
j2cl_proto: generates a j2cl-compatible java_library for an existing
proto_library.
Example usage:
load("//java/com/google/protobuf/contrib/j2cl:j2cl_proto.bzl", "j2cl_proto_library")
proto_library(
name = "accessor",... |
# Day 20: http://adventofcode.com/2016/day/20
inp = [(5, 8), (0, 2), (4, 7)]
def allowed(blocked, n):
rng, *blocked = sorted([*r] for r in blocked)
for cur in blocked:
if cur[0] > n:
break
elif cur[0] > rng[-1] + 1:
yield from range(rng[-1] + 1, cur[0])
rng... |
'''
Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.
Example 1:
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.
Example 2:
... |
def problem_31():
"How many different ways can £2 be made using any number of 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p), and £2 (200p) coins?"
# Get the target value of the coin, as well as all possible coin values (in pence)
target_value = 200
coin_values = [1, 2, 5, 10, 20, 50, 100, 200]
polynomials... |
test = { 'name': 'q5_2',
'points': 1,
'suites': [ { 'cases': [ { 'code': '>>> # Hint: If you are getting 47 as your answer, you might be computing the biggest change rather than biggest decrease!;\n'
'>>> biggest_decrease != 47\n'
... |
def best_sum_tab(n, a):
table = [None for i in range(n + 1)]
table[0] = []
for i in range(n + 1):
if table[i] is not None:
for j in a:
if (i + j) < len(table):
temp = table[i] + [j]
if table[i + j] is None:
... |
if opt.save_every > 0 and num_updates % opt.save_every == -1 % opt.save_every:
valid_loss = self.eval(self.valid_data)
valid_ppl = math.exp(min(valid_loss, 100))
print('Validation perplexity: %g' % valid_ppl)
ep = float(epoch) - 1. + ((float(i) + 1.) / n_samples)
self.save(ep, valid_ppl, batch_ord... |
FEATURES = set(
[
"five_prime_utr",
"three_prime_utr",
"CDS",
"exon",
"intron",
"start_codon",
"stop_codon",
"ncRNA",
]
)
NON_CODING_BIOTYPES = set(
[
"Mt_rRNA",
"Mt_tRNA",
"miRNA",
"misc_RNA",
"rRNA",
... |
# Runtime: 20 ms
# Beats 100% of Python submissions
class Solution(object):
def checkRecord(self, s):
"""
:type s: str
:rtype: bool
"""
if s.count("LLL") > 0:
return False
if s.count("A") > 2:
return False
return True
# A more worked ... |
#Donald Hobson
#A program to make big letters out of small ones
#storeage of pattern to make large letters.
largeLetter=[[" A ",
" A A ",
" AAA ",
"A A",
"A A",],
["BBBB ",
"B B",
"BBBBB",
"B B",
"BBB... |
EGAUGE_API_URLS = {
'stored' : 'http://%s.egaug.es/cgi-bin/egauge-show',
'instantaneous' : 'http://%s.egaug.es/cgi-bin/egauge',
}
|
t = int(input())
for i in range(t):
n=int(input())
l=0
h=100000
while l<=h:
mid =(l+h)//2
r= (mid*(mid+1))//2
if r>n:
h=mid - 1
else:
ht=mid
l=mid+1
print(ht)
|
"""
Hello world application.
Mostly just to test the Python setup on current computer.
"""
MESSSAGE = "Hello World"
print(MESSSAGE)
|
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
dict_val = {}
result1 = []
result2 = []
for val in nums:
dict_val[val] = dict_val.get(val, 0) + 1
if dict_val[val] > 1:
result1.append(val)
else:
... |
# (c) 2012-2019, Ansible by Red Hat
#
# This file is part of Ansible Galaxy
#
# Ansible Galaxy is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by
# the Apache Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
... |
__author__ = 'arid6405'
class SfcsmError(Exception):
def __init__(self, status, message):
self.status = status
self.message = message
def __str__(self):
return "Error {}: {} ".format(self.status, self.message) |
print(' - '*14)
print('{:=^40}'.format('Banco Centavo Não'))
print(' - '*14)
saque = int(input('Qual valor você quer sacar? R$'))
print('='*40)
cel_50 = int(saque / 50)
if cel_50 > 0:
print(f'Total de {cel_50} cédulas de R$50')
cel_20 = int((saque % 50) / 20)
if cel_20 > 0:
print(f'Total de {cel_20} c... |
"""
The core calculation, ``work_hours+hol_hours- 13*7.4``,
translates as 'the total number of hours minus the number
of mandatory leave days times by the number of hours in the
average working day, which is :math:`\\frac{37}{5}=7.4`, which
altogether gives the total number of hours available to be worked.
Dividin... |
def decode(s):
dec = dict()
def dec_pos(x,e):
for i in range(x+1):
e=dec[e]
return e
for i in range(32,127):
dec[encode(chr(i))] = chr(i)
a=''
for index,value in enumerate(s):
a+=dec_pos(index,value)
return a |
print("---------- numero de discos ----------")
def hanoi(n, source, helper, target):
if n > 0:
# move tower of size n - 1 to helper:
hanoi(n - 1, source, target, helper)
print(source, helper, target)
# move disk from source peg to target peg
if source:
target.a... |
class Solution(object):
def rangeBitwiseAnd(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
k = 0
while n != m:
n >>= 1
m >>= 1
k += 1
return n << k
|
'''num=[2,5,9,1]
num[2]=3
num.append(7)
num.sort(reverse=True)
num.insert(2, 0)
#num.pop(2)
if 4 in num:
num.remove(4)
else:
print('Não achei o numero 4')
print(num)
print(f'tem {len(num)} elementos')
print()'''
valor=[]
for cont in range(0,5):
valor.append(int(input(f'Digite o valor {cont}: ')))
for c,v in... |
__author__ = 'schlitzer'
__all__ = [
'AdminError',
'AlreadyAuthenticatedError',
'AuthenticationError',
'BaseError',
'CredentialError',
'DuplicateResource',
'FlowError',
'InvalidBody',
'InvalidFields',
'InvalidName',
'InvalidPaginationLimit',
'InvalidParameterValue',
... |
class Solution:
def twoSum(self, nums: [int], target: int) -> [int]:
d = {int: int}
for i in range(len(nums)):
if target - nums[i] in d:
return [d[target-nums[i]], i]
else:
d[nums[i]] = i
return []
if __name__ == "__main__":
solut... |
#
# PySNMP MIB module HH3C-VSI-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-VSI-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:15:32 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,... |
class RemoveStoryboard(ControllableStoryboardAction):
"""
A trigger action that removes a System.Windows.Media.Animation.Storyboard.
RemoveStoryboard()
"""
|
vals = [0,10,-30,173247,123,19892122]
formats = ['%o','%020o', '%-20o', '%#o', '+%o', '+%#o']
for val in vals:
for fmt in formats:
print(fmt+":", fmt % val)
|
class RoutedCommand(object,ICommand):
"""
Defines a command that implements System.Windows.Input.ICommand and is routed through the element tree.
RoutedCommand()
RoutedCommand(name: str,ownerType: Type)
RoutedCommand(name: str,ownerType: Type,inputGestures: InputGestureCollection)
"""
def CanExecut... |
# File: gcloudcomputeengine_consts.py
#
# Copyright (c) 2021 Splunk Inc.
#
# Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
# Define your constants here
COMPUTE = 'compute'
COMPUTE_VERSION = 'v1'
# Error message handling constants
ERR_CODE_MSG = "Error code unavailable"
ERR_MSG_UNAVAILABL... |
#!/usr/bin/env python3
def byterize(obj):
objdict = obj.__dict__['fields']
def do_encode(dictio, key):
if isinstance(dictio[key], str) and len(dictio[key]) > 0 and key not in ['SecondaryAddr']:
dictio[key] = dictio[key].encode('latin-1')
elif hasattr(dictio[key], '__dict__'):
... |
"""Settings for the kytos/storehouse NApp."""
# Path to serialize the objects, this is relative to a venv, if a venv exists.
CUSTOM_DESTINATION_PATH = "/var/tmp/kytos/storehouse"
|
class DaftException(Exception):
def __init__(self, reason):
self.reason = reason
def __str__(self):
return "Error: " + self.reason
|
class Solution:
def transformArray(self, arr: List[int]) -> List[int]:
na = arr[:]
stable = False
while not stable:
stable = True
for i in range(1, len(arr) - 1):
if arr[i] < arr[i-1] and arr[i] < arr[i+1]:
na[i] = arr[i] + 1
... |
try:
p=8778
b=56434
#f = open("ab.txt")
p = b/0
f = open("ab.txt")
for line in f:
print(line)
except FileNotFoundError as e:
print( e.filename)
except Exception as e:
print(e)
except ZeroDivisionError as e:
print(e)
#except (FileNotFoundError , ZeroDivisionError):
... |
# ***************************************************************************************
# ***************************************************************************************
#
# Name : errors.py
# Author : Paul Robson (paul@robsons.org.uk)
# Date : 9th December 2018
# Purpose : Error classes
#
# *********... |
"""Unit tests for image_uploader.bzl."""
load(
"//skylark:integration_tests.bzl",
"SutComponentInfo"
)
load(
":image_uploader.bzl",
"image_uploader_sut_component",
)
load("//skylark:unittest.bzl", "asserts", "unittest")
load("//skylark:toolchains.bzl", "toolchain_container_images")
# image_uploader_su... |
# coding: utf8
"""
题目链接: https://leetcode.com/problems/kth-smallest-element-in-a-bst/description.
题目描述:
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
Follow up:
What ... |
def get_options_ratio(options, total):
return options / total
def get_faculty_rating(get_options_ratio):
if get_options_ratio > .9 and get_options_ratio < 1:
return "Excellent"
if get_options_ratio > .8 and get_options_ratio < .9:
return "Very Good"
if get_options_ratio > .7 and get_opt... |
"""Exceptions and Error Handling"""
def assert_(condition, message='', exception_type=AssertionError):
"""Like assert, but with arbitrary exception types."""
if not condition:
raise exception_type(message)
# ------ VALUE ERRORS ------
class ShapeError(ValueError):
pass
class FrequencyValueEr... |
'''
Given a word, you need to judge whether the usage of capitals in it is right or not.
We define the usage of capitals in a word to be right when one of the following cases holds:
All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Only the first letter in ... |
# See readme.md for instructions on running this code.
class HelpHandler(object):
def usage(self):
return '''
This plugin will give info about Zulip to
any user that types a message saying "help".
This is example code; ideally, you would flesh
this out for m... |
'''
Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.
Example 1:
Input: "ab-cd"
Output: "dc-ba"
Example 2:
Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"
Example 3:
Input: "Test1ng-Leet=code-Q!"
Output: "Qedo... |
"""Top-level package for Railyard."""
__author__ = """Konstantin Taletskiy"""
__email__ = 'konstantin@taletskiy.com'
__version__ = '0.1.0'
|
test_cases_q = [{'q': 'Stockholms län'},
{'q': 'Stockholms län Halmstad'},
{'q': 'Stockholms län Norrbotten'},
{'q': 'Stockholms län Järfälla'},
{'q': 'Stockholms län Sigtuna'},
{'q': 'Skåne län'},
{'q': 'Skåne län Luleå'},
... |
#
# PySNMP MIB module NMS-EPON-ONU-SERIAL-PORT (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NMS-EPON-ONU-SERIAL-PORT
# Produced by pysmi-0.3.4 at Mon Apr 29 20:12:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.