content stringlengths 7 1.05M |
|---|
# User input
percentage = float(input("Enter your marks: "))
# Program operation & Computer output
if (percentage >= 90):
print("Your grade is A1 !")
elif (percentage >= 80):
print("Your grade is A !")
elif (percentage >= 70):
print("Your grade is B1 !")
elif (percentage >= 60):
print("Your ... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
def q_s(v):
if len(v) <=1:
return v
left, right = 0, len(v) - 1
item = v[int((left+right))/2]
left_value = [i for i in v if i < item]
right_value = [i for i in v if i > item]
return q_s(left_value) + [item] + q_s(right_value)
if __name... |
#
# PySNMP MIB module WWP-LEOS-OAM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WWP-LEOS-OAM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:31:22 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
# https://leetcode.com/problems/longest-palindromic-subsequence/
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
dp = [[0 for _ in range(len(s))] for _ in range(len(s))]
for row in range(len(s)):
for col in range(len(s)):
# Find len of longest common su... |
# Time: O(n)
# Space: O(1)
class Solution(object):
def findSubstringInWraproundString(self, p):
"""
:type p: str
:rtype: int
"""
letters = [0] * 26
result, length = 0, 0
for i in xrange(len(p)):
curr = ord(p[i]) - ord('a')
... |
# This file is intended for use by the drake_py_test macro defined in
# //tools/skylark:drake_py.bzl and should NOT be used by anything else.
"""A drake_py_test should not `import unittest`. In most cases, your
BUILD.bazel file should use `drake_py_unittest` to declare such tests, which
provides an appropriate main()... |
"""
将两个列表,合并为一个字典
姓名列表["张无忌","赵敏","周芷若"]
房间列表[101,102,103]
{101: '张无忌', 102: '赵敏', 103: '周芷若'}
"""
name=["张无忌","赵敏","周芷若"]
room=[101,102,103]
# dict01={}
# for i in range(len(name)):
# key=room[i]
# value=name[i]
# dict01[key]=value
# print(dict01)
dict02={room[i]:name[i] for i in range(len(name... |
# -- Project information -----------------------------------------------------
project = "PyData Tests"
copyright = "2020, Pydata community"
author = "Pydata community"
master_doc = "index"
# -- General configuration ---------------------------------------------------
html_theme = "pydata_sphinx_theme"
html_copy_s... |
test = { 'name': 'q5g',
'points': 1,
'suites': [ { 'cases': [ { 'code': ">>> 'result_q5g' in globals()\n"
'True',
'hidden': False,
'locked': False},
... |
# ========================
# Information
# ========================
# Direct Link: https://www.hackerrank.com/challenges/s10-poisson-distribution-2/problem
# Difficulty: Easy
# Max Score: 30
# Language: Python
# ========================
# Solution
# ========================
AVERAGE_X, AVERAGE_Y = [floa... |
def cap_11(packet):
# your code here
try:
if packet["RTMPT"]["string"] == '_result':
packet["RTMPT"]["string"] = '_123456'
print("cambiado")
return packet
except:
print("fallo")
return None
|
'''
Hardcoded string input
no filtering
sink: check if a file exists
'''
class Class_351:
def __init__(self, param):
self.var_351 = param
def get_var_351(self):
return self.var_351 |
class LiveDataFeed(object):
""" A simple "live data feed" abstraction that allows a reader
to read the most recent data and find out whether it was
updated since the last read.
Interface to data writer:
add_data(data):
Add new data to the feed... |
inv_count = 0
def sorter(l_res , r_res):
global inv_count
i = 0
r = 0
results = []
while i < len(l_res) and r < len(r_res):
if l_res[i] > r_res[r]:
results.append(r_res[r])
inv_count += len(l_res) - i
r += 1
else:
results.append(l_res... |
# -*- coding: utf-8 -*-
"""
ENERPIPLOT - Common constants & color palettes
"""
ROUND_W = 500
ROUND_KWH = .5
COLOR_REF_RMS = '#FF0077'
# summary (consumption) var plots
COLS_DATA_KWH = ['kWh', 'p_max', 'p_min', 't_ref']
COLORS_DATA_KWH = ['#8C27D3', '#972625', '#f4af38', '#8C27D3']
UNITS_DATA_KWH = ['kWh', 'W', 'W', ... |
#
# @lc app=leetcode.cn id=133 lang=python3
#
# [133] clone-graph
#
None
# @lc code=end |
def add_node(v):
if v in graph:
print(v,"already present")
else:
graph[v]=[]
def add_edge(v1,v2):
if v1 not in graph:
print(v1," not present in graph")
elif v2 not in graph:
print(v2,"not present in graph")
else:
graph[v1].append(v2)
graph[v2].append(... |
# ================================================================
def total_packet_size_bytes (s):
return (s ['packet_len'] +
s ['num_credits'] +
s ['channel_id'] +
s ['payload'])
def this_packet_size_bytes (s, n):
return (s ['packet_len'] +
s ['num_credits'] +... |
# print() supports formatting of console output that is rudimentary at best.
# You can choose how to separate printed objects, and you can specify what goes
# at the end of the printed line. That’s about it
# string modulo operator: <format_string> % <values>
# NOTE: If you’re acquainted with the printf() family of fu... |
class S(str):
# Symbol class: the only important difference between S and str is that S has a __substitute__ method
# Note that S('a') == 'a' is True. This lets us use strings as shorthand in certain places.
def __str__(self):
return "S('" + super(S, self).__str__() + "')"
def __repr__(self):
... |
def randomized_partition(arr, low, high):
"""Partition the array into two halfs according to the last element (pivot)
loop invariant:
[low, i] <= pivot
[i+1, j) > pivot
"""
i = low - 1
j = low
pivot = arr[high]
while j < high:
if arr[j] <= pivot:
i = i... |
class SwampyException(Exception):
pass
class ExWelcomeTimeout(SwampyException):
pass
class ExAbort(SwampyException):
pass
class ExInvocationError(SwampyException):
pass
|
# -*- coding:utf-8 -*-
# execute mode(prod/dev/testing)
ENV = 'prod'
# ENV = 'dev'
#ENV = 'testing'
# MRQ Task and Queue configuration
TASK_PATH = 'worker.tasks.CrawlCallHistory'
QUEUE_NAME = 'q-crawl'
#QUEUE_NAME = 'zhijie-crawl'
# SID setting (sec)
SID_EXPIRE_TIME = 300
STATE_TIME_OUT = 170
CRAWLER_TIME_OUT = 11... |
"""
aiida_abinit
The AiiDA plugin for ABINIT.
"""
__version__ = "0.1.0a0"
|
class CableTrayConduitBase(MEPCurve,IDisposable):
""" The CableTrayConduitBase class is implemented as the base class for cable tray or conduit """
def Dispose(self):
""" Dispose(self: Element,A_0: bool) """
pass
def getBoundingBox(self,*args):
""" getBoundingBox(self: Element,view: View) -> BoundingBoxX... |
# Crie um programa que leia qto dinheiro uma pessoa tem na carteira e mostre quantos doláres ela pode comprar.
# Considere 1 dolar igual a 3,27 reais
n1 = float(input('Informe o valor que tem na carteira R$: '))
conversao = n1 / 3.27
print('Com R${}, você poderá comprar US${:.2f}!'.format(n1,conversao))
|
#!/usr/bin/python3
def new_in_list(my_list, idx, element):
new_list = my_list[:]
if idx >= 0 and idx < len(my_list):
new_list[idx] = element
return new_list
|
# https://leetcode.com/problems/bitwise-ors-of-subarrays/
#
# algorithms
# Medium (32.02%)
# Total Accepted: 5,616
# Total Submissions: 17,538
class Solution(object):
def subarrayBitwiseORs(self, A):
"""
:type A: List[int]
:rtype: int
"""
cur, res = set(), set()
... |
"""
Class to parse and validate command-line arguments required by train, classify and evaluate.
"""
class ArgumentHandler:
def __init__(self):
#I/O
#data.py: DataHandler
self.logdir = None
self.max_tokens = 200
self.labels = ""
self.num_labels = 3
... |
class Body(object):
"""An class which is used to store basic properties about a body"""
def __init__(self, xPos, yPos, xVel, yVel, mass):
"""Create a new body
xPos - The x component of the position
yPos - The y component of the position
xVel - The x component of the velocity
... |
def main(type):
x = 0
print(type)
if type=="wl":
#a while loop
while (x <5):
print(x)
x = x + 1
elif type=="fl":
#a for loop
for x in range(5,10):
print(x)
elif type=="cl":
#a for loop over a collection
days = ["Mon", "Tue", "Wed", "Thurs", "Fri", "Sat", "Sun"]
for ... |
# Faça um algoritmo que leia o salario de um funcionario e mostre
# seu novo salario, com 15% de aumento.
salario = float(input('Digite o seu salario: '))
novosala = salario + salario * 0.15
print('O seu novo salário sera de {}{}' .format('\033[1;95m', novosala))
|
# Constants in FlexRay spec
cdCycleMax = 16000
cCycleCountMax = 63
cStaticSlotIDMax = 1023
cSlotIDMax = 2047
cPayloadLengthMax = 127
cSamplesPerBit = 8
cSyncFrameIDCountMax = 15
cMicroPerMacroNomMin = 40
cdMinMTNom = 1
cdMaxMTNom = 6
cdFES = 2
cdFSS = 1
cChannelIdleDelimiter = 11
cClockDeviationMax = 0.0015
cStrobeOffs... |
"""
1. 187_XXX -> Self define exception
"""
class NameIsError(Exception):
pass
class AgeIsError(Exception):
pass
class HahaIsError(Exception):
pass
def check_name(name):
if name.find("li") >= 0:
raise NameIsError("Collision with my king's ", name)
def check_age(age):
if age >= ... |
class Triple:
def __init__(self, subject, predicate, object):
self.subject = subject
self.predicate = predicate
self.object = object
|
def main():
return 0
if __name__ == "__main__":
for case in range(1, int(input()) + 1):
print(f"Case #{case}:", main())
|
file = open('input.txt', 'r')
Lines = file.readlines()
count = 0
# Strips the newline character
for line in Lines:
line_parts = line.strip().split(' ')
rule_part = line_parts[0].split('-')
min_rule = int(rule_part[0])
max_rule = int(rule_part[1])
password = line_parts[2]
char = line_parts[1][0]
char_count = pa... |
# Roman numeral/Decimal converter
# Roman to decimal conversion table
RomanValue = { 'I' : 1, 'V' : 5, 'X' : 10, 'L' : 50, 'C' : 100, 'D' : 500, 'M' : 1000 }
def RomanValueList (RomanNumber):
number = []
for i in RomanNumber:
number.append(RomanValue[i])
return number
# Convert Roman number stri... |
# Python Program To Handle Multiple Exceptions
def avg(list):
tot = 0
for x in list:
tot += x
avg = tot/len(list)
return tot, avg
# Call The avg() And Pass A List
try:
t, a = avg([1,2,3,4,5,'a']) # Here Give Empty List And try
print('Total = {}, Average = {}'.... |
# -*- coding: utf-8 -*-
#
# Copyright 2014-2022 BigML
#
# 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 ... |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 applicab... |
def dataset():
pass
def model():
pass
def loss():
pass
def opt():
pass |
class Response:
def __init__(self, message=None, data=None):
self.message = message
self.data = data
def build(self):
return {
"message": self.message,
"data": self.data
}
|
def main():
double_letters = 0
triple_letters = 0
input_file = open('input', 'r')
for line in input_file:
double_letters_found = False
triple_letters_found = False
characters = set(line.replace('\n', ''))
for character in characters:
if not double_letters_foun... |
coordinates_E0E1E1 = ((129, 120),
(129, 122), (129, 124), (130, 124), (131, 124), (132, 124), (133, 124), (134, 124), (135, 124), (136, 123), (136, 132), (137, 119), (137, 123), (138, 119), (138, 122), (139, 120), (139, 122), (140, 121), (140, 123), (141, 121), (141, 126), (142, 113), (142, 115), (142, 121), (142, 12... |
num = int(input('digite um numero pra daber sua tabuada: '))
for rep in range(0, 11):
print('{} x {:2} = {}'.format(rep, num, num*rep))
|
print("")
for i in range(5):
peso = float(input("Peso da {}ª Pessoa em Kg: ".format(i+1)))
if (i == 0):
maior = peso
menor = peso
elif (peso > maior): maior = peso
elif (peso < menor): menor = peso
print("O menor peso lido foi {:.2f}Kg".format(menor))
print("O maior peso... |
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
if len(preorder)==0:
return None
tn=TreeNode(preorder[0])
l=[]
r=[]
for i in preorder:
if i<preorder[0]:
l.append(i)
elif i>preorder[0]:
... |
n = int(input('digite um numero de 1 a 9999: '))
u = n % 10
d = n // 10 % 10
c = n // 100 % 10
m = n // 1000 % 10
print('A unidade', u)
print('A dezena', d)
print('A centena', c)
print('A milhar', m)
|
def stair(n):
if n == 0 or n == 1:
return 1
elif n == 2:
return 2
elif n == 3:
return 4
else:
return stair(n-3) + stair(n-2) + stair(n-1)
n = int(input())
print(stair(n))
|
#
# PySNMP MIB module CADANT-CMTS-EXPORTIMPORT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CADANT-CMTS-EXPORTIMPORT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:27:10 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python vers... |
class Problem:
"""
Given a string of different arrows designating to four directions.
Then we can rotate arrows so that they designate the same direction.
Example
"^^<>vvv" -> "^^^^^^^" -> 5 operations
"^^<>vvv" -> "vvvvvvv" -> 4 operations
"^^<>vvv" -> ">>>>>>>" -> 6 operations
Find t... |
#!/home/jepoy/anaconda3/bin/python
## at terminal which python
#simple fibonacci series
# the sum of two elements defines the next set
a, b = 0, 1
while b < 1000:
print(b, end = ' ', flush = True)
a, b = b, a + b
print() # line ending |
def create(type):
switcher = {
"L": LPiece(),
"O": OPiece(),
"I": IPiece(),
"J": JPiece(),
"S": SPiece(),
"T": TPiece(),
"Z": ZPiece()
}
return switcher.get(type.upper())
class Piece:
def __init__(self):
self._rotateIndex... |
class HelperBase:
def __init__(self, app):
self.app = app
def type(self, locator, text):
wd = self.app.wd
if text is not None:
wd.find_element_by_name(locator).click()
wd.find_element_by_name(locator).clear()
wd.find_element_by_name(locator).send_k... |
#!/usr/bin/python3
print("Hello World")
x=4
y="ok,google"
z=[4,77,x,y]
print(y)
print(z)
print(x,y)
|
major = 1
minor = 0
micro = None
pre_release = ".alpha"
post_release = None
dev_release = None
__version__ = '{}'.format(major)
if minor is not None:
__version__ += '.{}'.format(minor)
if micro is not None:
__version__ += '.{}'.format(micro)
if pre_release is not None:
__version__ += '{}'.format(pre_re... |
#############################
#PROJECT : ENCODER-DECODER
#Language :English
#basic encode and decode
#Contact me on ;
#Telegram : Zafiyetsiz0
#Instagram : Zafiyetsiz
#Discord : Zafiyetsiz#4172
##############################
print("1-Encoder ; 2-Decoder")
choise=int(input("Please type the number of transacti... |
def fib(a,b,n):
if(n==1):
return a
elif(n==2):
return b
else:
return fib(a,b,n-2)+fib(a,b,n-1)*fib(a,b,n-1)
r = input();
r = r.split(' ')
a = int(r[0])
b = int(r[1])
n = int(r[2])
print(fib(a,b,n)) |
#Actividad 2
a=1+2**-53
print(a)
b=a-1
print(b)
a=1+2**-52
print(a)
b=a-1 |
"""
DOBRO, TRIPLO E RAIZ QUADRADA
"""
n1 = int(input('Digite um número: '))
print('O dobro de {} é {} '.format(n1,n1*2))
print('O triplo de {} é {} '.format(n1,n1*3))
print('A raiz quadrada de {} é {:.2f} '.format(n1,pow(n1,(1/2))))
|
a = [{'001': '001', '002': '002'}]
print(a, type(a))
a = a.__str__()
print(a, type(a))
print(['------------------'])
init_list = [0 for n in range(10)]
init_list2 = [0] * 10
print(init_list)
print(init_list2)
# list - replace
a = ['110', '111', '112', '113']
for i in a:
print(i, a.index(i))
... |
# Check whether the string is palindrome or not considering
# only Alpha-Numeric Characters ignoring cases
s = input();
t = ''.join([i.lower() if i.isalnum() else '' for i in s])
if t==''.join(reversed(t)): print("It is a Palindrome String")
else: print("It is not a Palindrome String")
|
# cannot be changed by user:
coinbaseReward = 5000000000 #50 bitcoins
halvingInterval = 150
maxOutputsPerTx = 1000
scalingUnits = .000001 # units of cap
confirmations = 6
onchainSatoshiMinimum = 100
maxTxPerBlock = 20 # 200 transactions in a block plus coinbase (which is at index 0)
iCoinbasePriv = 100000000 # so... |
"""Formatter to extract the output files from a target."""
def format(target):
provider_map = providers(target)
if not provider_map:
return ""
outputs = dict()
# Try to resolve in order.
files_to_run = provider_map.get("FilesToRunProvider", None)
default_info = provider_map.get("Defaul... |
__all__ = [
'base_controller',
'basic_api_controller',
'advanced_api_controller',
'enterprise_only_controller',
]
|
"""
Definition of exceptions thrown by arrus functions.
"""
class ArrusError(Exception):
pass
class IllegalArgumentError(ArrusError, ValueError):
pass
class DeviceNotFoundError(ArrusError, ValueError):
pass
class IllegalStateError(ArrusError, RuntimeError):
pass
class TimeoutError(ArrusError, T... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
prev = 0
def ... |
all_boards = {
'sysop': 1,
'vote': 2,
'bbslists': 3,
'notepad': 6,
'Test': 7,
'Dance': 8,
'Board': 9,
'Wisdom': 10,
'Science': 12,
'Linux': 13,
'IBMThinkPad': 14,
'LifeScience': 15,
'BBShelp': 16,
'Mechanics': 17,
'Emprise': 18,
'Philosophy': 20,
'Lite... |
class RequestSourceValidator(object):
REQUIRED_AUTHENTICATIONS = ["manager", "host"]
SUPPORTED_TRANSPORT_METHODS = ['vddk', 'ssh']
def __init__(self, request):
self._request = request
self._errors = []
def validate(self):
for auth in self.REQUIRED_AUTHENTICATIONS:
... |
#coding: utf-8
#Classe que define uma estação da simulação
class Estacao:
#Construtor da classe
def __init__(self, idEstacao):
#Atributo responsável por armazenar o identificador de uma estação
self.idEstacao = idEstacao
#Atributo responsável por armazenar o slot de transmissã... |
string = input()
result = []
for index in range(len(string)):
if string[index].isupper():
result.append(index)
print(result)
|
x = 10
if (x % 2) == 0 and (x % 5) == 0:
print(x)
A1 = "ostrich"
print('o' in A1)
print('r' not in A1)
|
class Solution:
def XXX(self, nums: List[int]) -> bool:
length = len(nums)
global tag
tag = False
def dfs(idx):
if idx == length - 1:
global tag
tag = True
return
if idx >= length or nums[idx] < 1:
... |
# https://www.youtube.com/watch?v=fFVZt-6sgyo
# broute force
def subarraySum(nums, k):
count = 0
for i in range(len(nums)):
sub_sum = 0
for j in range(i, len(nums)):
sub_sum += nums[j]
if sub_sum == k:
count += 1
return count
# sliding window, only... |
def leer_archivo():
nombre = input("Nombre del archivo donde está el mapa: ")
f = open(nombre,"r")
lineas = f.readlines()
f.close()
mapa = []
for linea in lineas:
mapa.append([c for c in linea.rstrip()])
return mapa
def vecinos(mapa,i,j):
# entrega la lista de vecinos libres de ... |
# -*- coding: utf-8 -*-
'''
Management of Open vSwitch ports.
'''
def __virtual__():
'''
Only make these states available if Open vSwitch module is available.
'''
return 'openvswitch.port_add' in __salt__
def present(name, bridge):
'''
Ensures that the named port exists on bridge, eventually... |
# Copyright 2014 Dave Kludt
#
# 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 or agreed to in writing, s... |
'''P36 (**) Determine the prime factors of a given positive integer (2).
Construct a list containing the prime factors and their multiplicity.
Example:
* (prime-factors-mult 315)
((3 2) (5 1) (7 1))'''
base_divident=int(input('Enter number to find prime factors = '))
final_out=[]
original=base_divident #save... |
# This module contains a function to print Hello, World!
# Prints Hello, World!
def hello():
print("Hello, World!")
|
class Difference:
def __init__(self, a):
self.__elements = a
def computeDifference(self):
result = []
data_len = len(self.__elements)
for i in range(data_len):
for n in range(i, data_len):
if i == n:
continue
x = ... |
"""
The overridden attribute manager is a singleton that observes the scene to
react to attribute changes. If the attribute change is on an attribute
that is overridden by render setup, the attribute manager will attempt to
take the value change and reproduce it on the override itself.
This allows for convenient work... |
class notifyException(Exception):
"""Base class for other exceptions."""
code: int = None
payload: str = None
def __init__(self, message: str = None, *args, code: int = None, payload: str = None, **kwargs):
super(notifyException, self).__init__(*args, **kwargs)
self.args = (
... |
# https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii
class Solution:
def minMoves2(self, nums: List[int]) -> int:
nums = sorted(nums)
if len(nums) % 2 == 1:
mid = nums[len(nums) // 2]
else:
mid = (nums[len(nums) // 2] + nums[len(nums) // 2 - 1]) ... |
# encoding:utf-8
# AlgoPlus量化投资开源框架
# 微信公众号:AlgoPlus
# 官网:http://algo.plus
#///正常
ExchangeProperty_Normal = b'0'
#///根据成交生成报单
ExchangeProperty_GenOrderByTrade = b'1'
#///组织机构代码
IdCardType_EID = b'0'
#///中国公民身份证
IdCardType_IDCard = b'1'
#///军官证
IdCardType_OfficerIDCard = b'2'
#///警官证
IdCardType_PoliceIDCard = b'3'
#/... |
guests = ["sam","mike","darren"]
for i in range(len(guests)):
print("Hello, "+guests[i].title()+" you are invited to dinner")
print(" ")
print(guests[0]+" cant make it to dinner unfortunately")
guests[0] = "alicia"
for i in range(len(guests)):
print("Hello, "+guests[i].title()+" you are invited to di... |
__all__=[
'SG_disease',
'SG_weather',
'MY_dengue',
'MY_malaria',
'BN_disease',
'ID_malaria',
'PH_malaria',
'TH_disease',
'apps_who_int',
'wunderground'
] |
while True:
usr = input("Enter username: ")
with open("users.txt", "r") as file:
users = file.readlines()
users = [i.strip("\n") for i in users]
if usr in users:
print("Username exists")
continue
else:
print("Username is fine")
break
while Tru... |
class ServiceUnavailable(Exception):
"""Raised when you try to send a request to a service that is
unavailable.
"""
class ServiceError(Exception):
"""Raised when a service failed to fulfill your request."""
class UnknownRejection(Exception):
"""Raised when a service rejects your request, and you haven't
regis... |
# Atharv Kolhar
# Python Bytes
"""
Question:
1. Create a list 'solar_system' of Planets in the Solar System and
print the 4th planet.
Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto
2. Print the length of the 'solar_system'.
3. Remove the last planet Pluto from the list.
4. Reverse the list solar_... |
#!/usr/bin/env python
# encoding: utf-8
"""
Created by 'bens3' on 2013-06-21.
Copyright (c) 2013 'bens3'. All rights reserved.
""" |
def set_default_values(args, also_hyper_params=True):
# -set default-values for certain arguments based on chosen scenario & experiment
if args.tasks is None:
if args.experiment=='splitMNIST':
args.num_classes = 10
if args.experiment=='splitMNISToneclass':
args.num_class... |
[
{
'date': '2011-01-01',
'description': 'Neujahr',
'locale': 'de-DE',
'notes': '',
'region': '',
'type': 'NF'
},
{
'date': '2011-01-06',
'description': 'Heilige drei Könige',
'locale': 'de-DE',
'notes': '',
'region': 'B... |
# coding: utf-8
class DataBatch:
def __init__(self, mxnet_module):
self._data = []
self._label = []
self.mxnet_module = mxnet_module
def append_data(self, new_data):
self._data.append(self.__as_ndarray(new_data))
def append_label(self, new_label):
self._label.appe... |
"""
File: weather_master.py
Name: DiCheng
-----------------------
This program should implement a console program
that asks weather data from user to compute the
average, highest, lowest, cold days among the inputs.
Output format should match what is shown in the sample
run in the Assignment 2 Handout.
"""
# enter EX... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxLevelSum(self, root: TreeNode) -> int:
if root is None:
return 0
result, current = [], [root]
... |
test = {
'name': 'Question 4',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
>>> is_swap(19, 91)
False
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> is_swap(19, 19)
True... |
class Registry(dict):
def __init__(self, *args, **kwargs):
super(Registry, self).__init__(*args, **kwargs)
def register(self, module_name):
def register_fn(module):
assert module_name not in self
self[module_name] = module
return module
return regist... |
def findCandidate(A):
maj_index = 0
count = 1
for i in range(len(A)):
if A[maj_index] == A[i]: count += 1
else: count -= 1
if count == 0: maj_index, count = i, 1
return A[maj_index]
def isMajority(A, cand, k):
count = 0
for i in range(len(A)):
if A[i] == ... |
# unihernandez22
# https://atcoder.jp/contests/abc159/tasks/abc159_a
# math
print(sum(map(lambda i: int(i)*(int(i)-1)//2, input().split())))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.