content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Solution:
def countBits(self, num: int) -> List[int]:
next_t = 1
bit_counts = [0] * (num + 1)
for n in range(1, num + 1):
if n == next_t:
bit_counts[n] = 1
next_t *= 2
else:
bit_counts[n] = bit_counts[int(next_t /... | class Solution:
def count_bits(self, num: int) -> List[int]:
next_t = 1
bit_counts = [0] * (num + 1)
for n in range(1, num + 1):
if n == next_t:
bit_counts[n] = 1
next_t *= 2
else:
bit_counts[n] = bit_counts[int(next_t ... |
# Question: https://projecteuler.net/problem=1
N = 1000
# A: number of integers in [1, N) that are divisible by 3
# B: number of integers in [1, N) that are divisible by 5
# C: number of integers in [1, N) that are divisible by 15 = 3 * 5
A = (N - 1) // 3
B = (N - 1) // 5
C = (N - 1) // 15
# sumA: sum of integers i... | n = 1000
a = (N - 1) // 3
b = (N - 1) // 5
c = (N - 1) // 15
sum_a = 3 * (A * (A + 1)) // 2
sum_b = 5 * (B * (B + 1)) // 2
sum_c = 15 * (C * (C + 1)) // 2
print(sumA + sumB - sumC) |
# You're working on a secret team solving coded transmissions.
# Your team is scrambling to decipher a recent message, worried it's a plot to break into a major European National Cake Vault.
# The message has been mostly deciphered, but all the words are backward! Your colleagues have handed off the last step to you.
... | print('\n-----===== Start =====-----\n')
def reverse(the_list):
for i in range(len(the_list) // 2):
(the_list[i], the_list[-(i + 1)]) = (the_list[-(i + 1)], the_list[i])
return the_list
def reverse_words(the_message):
reverse(the_message)
word_start = 0
for (i, el) in enumerate(the_message... |
class StubIO:
"""Mocks the functionality of the console IO service"""
def __init__(self):
self.inputs = []
self.outputs = []
def write(self, message):
self.outputs.append(str(message).strip())
def read(self, prompt):
"""Returns a fake input from the input list"""
... | class Stubio:
"""Mocks the functionality of the console IO service"""
def __init__(self):
self.inputs = []
self.outputs = []
def write(self, message):
self.outputs.append(str(message).strip())
def read(self, prompt):
"""Returns a fake input from the input list"""
... |
"""
Exercise 3
Python provides a built-in function called len that returns
the length of a string, so the value of len('allen')is 5.
Write a function named right_justify that takes a string named
s as a parameter and prints the string with enough leading
spaces so that the last letter of the string is in colu... | """
Exercise 3
Python provides a built-in function called len that returns
the length of a string, so the value of len('allen')is 5.
Write a function named right_justify that takes a string named
s as a parameter and prints the string with enough leading
spaces so that the last letter of the string is in column
70 o... |
# Solution to Project Euler problem 1
# Copyright (c) Nhut-Nam Le. All rights reserved.
def solution0(number, a, b):
if number < 0:
return 0
return sum([i for i in range(number) if i % a == 0 or i % b == 0])
print(solution0(10000, 3, 5))
def solution1(number, a, b):
return ((number - 1) // a)... | def solution0(number, a, b):
if number < 0:
return 0
return sum([i for i in range(number) if i % a == 0 or i % b == 0])
print(solution0(10000, 3, 5))
def solution1(number, a, b):
return (number - 1) // a * ((number - 1) // a + 1) * a // 2 + (number - 1) // b * ((number - 1) // b + 1) * b // 2 - (nu... |
AGENT_1_ID = 0
AGENT_2_ID = 1
# initialize policies
NUM_ACTIONS = 6 # 4 moves + 2 legal switches
NULL_ACTION_ID = NUM_ACTIONS
STATE_DIM = 57
NUM_MOVES = 4
SWITCH_OFFSET = 12 # env takes 16-21 as numbers corresponding to switches; CoPG distributions returns 4-5
TEAM = """
Tapu Fini @ Expert Belt
Ability: Misty Sur... | agent_1_id = 0
agent_2_id = 1
num_actions = 6
null_action_id = NUM_ACTIONS
state_dim = 57
num_moves = 4
switch_offset = 12
team = '\nTapu Fini @ Expert Belt \nAbility: Misty Surge \nEVs: 4 Def / 252 SpA / 252 Spe \nModest Nature \n- Hydro Pump \n- Ice Beam \n- Moonblast \n- Knock Off \n\nMamoswine @ Leftovers ... |
# -*- coding: utf-8
DEBUG = True
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 't)c0g-tbhgoe2ybv4(iyj%!07*si)co@rg21f&ejm3v=)u^_-8'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
ROOT_URLCONF = 'bitbucket.urls'
FIE... | debug = True
secret_key = 't)c0g-tbhgoe2ybv4(iyj%!07*si)co@rg21f&ejm3v=)u^_-8'
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}}
root_urlconf = 'bitbucket.urls'
field_encryption_key = 'SURdYnt6gHdgq84TgewXS6WayBQYlHt9Lr8Sryv9yOI='
installed_apps = ['django.contrib.auth', 'django.cont... |
step = 376
#1
current = 0
res = [0]
for i in range(1,2018):
current = ((current+step)%len(res))+1
res.insert((current), i)
print(res[current+1])
#2
current = 0
lenRes = 1
res = []
for i in range(1,50000001):
current = ((current+step)%lenRes)+1
lenRes+=1
if(current == 1):
print('.')
res.insert(0, i)
print... | step = 376
current = 0
res = [0]
for i in range(1, 2018):
current = (current + step) % len(res) + 1
res.insert(current, i)
print(res[current + 1])
current = 0
len_res = 1
res = []
for i in range(1, 50000001):
current = (current + step) % lenRes + 1
len_res += 1
if current == 1:
print('.')
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 2 01:56:42 2022
@author: ACER
"""
# listar los numeros primos del 1 al 100
num = 1
while num <= 100:
num = num + 1
cont = 1
a = 0
while cont <= num :
if num % cont == 0:
a = a+1
cont = cont +1
if a==2:
print(num)
... | """
Created on Wed Feb 2 01:56:42 2022
@author: ACER
"""
num = 1
while num <= 100:
num = num + 1
cont = 1
a = 0
while cont <= num:
if num % cont == 0:
a = a + 1
cont = cont + 1
if a == 2:
print(num) |
class InjectionRequest(object):
"""
Represents a injection request for sending to the Injection Api.
To be serialized into JSON string before sending to the Injection Api.
"""
def __init__(self, server_id: int, api_key: str, messages: list):
"""
Initializes a new instance of the Add... | class Injectionrequest(object):
"""
Represents a injection request for sending to the Injection Api.
To be serialized into JSON string before sending to the Injection Api.
"""
def __init__(self, server_id: int, api_key: str, messages: list):
"""
Initializes a new instance of the Add... |
a = input()
if a == "a":
print(-1)
else:
print("a")
| a = input()
if a == 'a':
print(-1)
else:
print('a') |
def init():
global session
session = {}
| def init():
global session
session = {} |
"""A thesaurus of words the player might use, so you can easily accept
synonyms of the word you want.
e.g. This will recognise take, pick, get or collect::
if do[0] in weatbag.words.take:
#...
"""
# Verbs
move = {'move', 'walk', 'go', 'travel', 'cross', 'pace', 'traverse'}
give = {'give', 'feed', 'present... | """A thesaurus of words the player might use, so you can easily accept
synonyms of the word you want.
e.g. This will recognise take, pick, get or collect::
if do[0] in weatbag.words.take:
#...
"""
move = {'move', 'walk', 'go', 'travel', 'cross', 'pace', 'traverse'}
give = {'give', 'feed', 'present', 'impa... |
# import torch
#
# x = torch.ones(2, 2, requires_grad = True)
# print(x.data)
# print(x.grad)
# print(x.grad_fn)
# print('*' * 10)
# y = x + 2
# print(y)
# print(y.grad)
# print(y.grad_fn)
# print('*' * 10)
#
# z = y * y * 3
# out = z.mean()
# print(z)
# print(out)
# print('*' * 10)
#
#
# out.backward()
# print(x.grad)... | a = -20007
print(a ** 2) |
t1 = 1,
print(type(t1))
t2 = 1, 2, 3
print(t2)
#<class 'tuple'>
#(1, 2, 3)
#truplas sao iteraveis e fatiaveis
t3 = 1,2, 'Thais', 4, 5
t4 = 6, 7, 8, 9, 10
t5 = t3 + t4
print(t5)
#(1, 2, 'Thais', 4, 5, 6, 7, 8, 9, 10)
n1,n2,n3,n4,*n_outros,n10 = t5
print(n1, n2, n3,n4)
print(*n_outros)
print(n10)
#1 2 Thais 4
#5 6 7... | t1 = (1,)
print(type(t1))
t2 = (1, 2, 3)
print(t2)
t3 = (1, 2, 'Thais', 4, 5)
t4 = (6, 7, 8, 9, 10)
t5 = t3 + t4
print(t5)
(n1, n2, n3, n4, *n_outros, n10) = t5
print(n1, n2, n3, n4)
print(*n_outros)
print(n10)
n1 = ('oi',)
print(n1 * 10)
t6 = (1, 2, 3, 4)
t6 = list(t6)
t6[2] = 300
t6 = tuple(t6)
print(t6) |
class MaxSubArrayBottomUp:
def __init__(self, prices):
self.prices = prices
self.sub_solutions = [None] * len(prices)
for i in range(len(self.prices)):
if i == 0:
self.sub_solutions[i] = self.prices[0]
else:
self.sub_solutions[i] = max(... | class Maxsubarraybottomup:
def __init__(self, prices):
self.prices = prices
self.sub_solutions = [None] * len(prices)
for i in range(len(self.prices)):
if i == 0:
self.sub_solutions[i] = self.prices[0]
else:
self.sub_solutions[i] = max... |
def lowest_product(input):
if len(input)<4:
return "Number is too small"
if "0" in input:
return 0
total=9**4
for i in range(len(input)-3):
total=min(total, (int(input[i])*int(input[i+1])*int(input[i+2])*int(input[i+3])))
return total | def lowest_product(input):
if len(input) < 4:
return 'Number is too small'
if '0' in input:
return 0
total = 9 ** 4
for i in range(len(input) - 3):
total = min(total, int(input[i]) * int(input[i + 1]) * int(input[i + 2]) * int(input[i + 3]))
return total |
class Solution:
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
if n == 1:
return "1"
if n == 2:
return "11"
s = "11"
for i in range(3, n + 1):
s += "*"
len_str = len(s)
count = 1
... | class Solution:
def count_and_say(self, n):
"""
:type n: int
:rtype: str
"""
if n == 1:
return '1'
if n == 2:
return '11'
s = '11'
for i in range(3, n + 1):
s += '*'
len_str = len(s)
count = ... |
class UnbError(Exception):
pass
class ResponseError(UnbError):
pass
class BadRequest(ResponseError):
pass
class Unauthorized(ResponseError):
pass
class Forbidden(ResponseError):
pass
class NotFound(ResponseError):
pass
class TooManyRequests(ResponseError):
pass
class InternalS... | class Unberror(Exception):
pass
class Responseerror(UnbError):
pass
class Badrequest(ResponseError):
pass
class Unauthorized(ResponseError):
pass
class Forbidden(ResponseError):
pass
class Notfound(ResponseError):
pass
class Toomanyrequests(ResponseError):
pass
class Internalservererr... |
"""
Session: 8
Topic: String functions: split, join
"""
str = 'This is a long string'
print (str)
"""
splint = str.split()
print ('split length is {} of word {} ' .format(len(splint), splint) )
splintn = str.split('n')
print ('splitn length is {} of word {} ' .format(len(splintn), splintn) )
"""
str1 = (':'.join(... | """
Session: 8
Topic: String functions: split, join
"""
str = 'This is a long string'
print(str)
"\n\nsplint = str.split()\nprint ('split length is {} of word {} ' .format(len(splint), splint) )\n\nsplintn = str.split('n')\nprint ('splitn length is {} of word {} ' .format(len(splintn), splintn) )\n"
str1 = ':'.join(str... |
#
# @lc app=leetcode id=401 lang=python
#
# [401] Binary Watch
#
# https://leetcode.com/problems/binary-watch/description/
#
# algorithms
# Easy (45.07%)
# Total Accepted: 61.8K
# Total Submissions: 136.8K
# Testcase Example: '0'
#
# A binary watch has 4 LEDs on the top which represent the hours (0-11), and
# the 6... | time_map = {0: ['0:00'], 1: ['1:00', '2:00', '4:00', '8:00', '0:01', '0:02', '0:04', '0:08', '0:16', '0:32'], 2: ['0:03', '0:05', '0:06', '0:09', '0:10', '0:12', '0:17', '0:18', '0:20', '0:24', '0:33', '0:34', '0:36', '0:40', '0:48', '1:01', '1:02', '1:04', '1:08', '1:16', '1:32', '2:01', '2:02', '2:04', '2:08', '2:16'... |
def barra(n=10, c="*"):
print(c*n)
L = [ [5, "-"], [10, "*"], [5] ]
for e in L:
barra(*e)
# barra(5, "-") barra(10, "*")
| def barra(n=10, c='*'):
print(c * n)
l = [[5, '-'], [10, '*'], [5]]
for e in L:
barra(*e) |
class DataPorter:
def __init__(self, model, **kwargs):
self.model = model
self.computing_device = kwargs.get('computing_device', 'cpu')
@staticmethod
def get_direct_parameters(module):
# TODO: Don't access protected attribute (check if name contains dot?)
return module._para... | class Dataporter:
def __init__(self, model, **kwargs):
self.model = model
self.computing_device = kwargs.get('computing_device', 'cpu')
@staticmethod
def get_direct_parameters(module):
return module._parameters.items()
@staticmethod
def get_direct_buffers(module):
... |
#! /usr/bin/python3
class Entity:
def __init__(self, id):
self._id = id
self._tags = []
self._componentids =[]
def get_id(self) -> int:
return self._id
def add(self, parameter):
if isinstance(parameter, str):
self._tags.append(parameter)
elif is... | class Entity:
def __init__(self, id):
self._id = id
self._tags = []
self._componentids = []
def get_id(self) -> int:
return self._id
def add(self, parameter):
if isinstance(parameter, str):
self._tags.append(parameter)
elif isinstance(parameter,... |
"""Rules for generating capnproto files.
"""
CapnpInfo = provider(
"Dependency info for generating capnp files",
fields = [
"includes",
"sources",
],
)
def _path_concat(*args):
path = ""
for arg in args:
if path == "":
path = arg
elif arg == "":
... | """Rules for generating capnproto files.
"""
capnp_info = provider('Dependency info for generating capnp files', fields=['includes', 'sources'])
def _path_concat(*args):
path = ''
for arg in args:
if path == '':
path = arg
elif arg == '':
pass
elif arg.startswith... |
class Person:
def __init__(self, name):
self.name = name
self._id = name.lower() # underscore prefix = "private" but only by convention
# when methods are defined in a class, it adds them as attributes to any instance of that class.
# when a method is called on an object, it automatically a... | class Person:
def __init__(self, name):
self.name = name
self._id = name.lower()
def display(self):
return f'{self.name} ({self.job})'
def same_name(self, other):
return self.name == other.name
class Somethingelse:
pass
x = something_else()
if __name__ == '__main__':
... |
def solution(s: str):
return "".join(sorted(s, reverse=True))
if __name__ == "__main__":
i = "Zbcdefg"
print(solution(i)) | def solution(s: str):
return ''.join(sorted(s, reverse=True))
if __name__ == '__main__':
i = 'Zbcdefg'
print(solution(i)) |
def eh_primo(x):
if (x==3) or (x==2):
return True
if (x<2) or (x%2==0):
return False
for i in range(3, int(x**0.5)+1, 2):
if x%i==0:
return False
return True
n = int(input())
for i in range(0,n):
num = int(input())
out = eh_primo(num)
if out == True:
... | def eh_primo(x):
if x == 3 or x == 2:
return True
if x < 2 or x % 2 == 0:
return False
for i in range(3, int(x ** 0.5) + 1, 2):
if x % i == 0:
return False
return True
n = int(input())
for i in range(0, n):
num = int(input())
out = eh_primo(num)
if out == ... |
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in nums:
j = target - i
tmp_nums_start_index = nums.index(i) + 1
tmp_nums = nums[tmp_nums_start_index:]
... | class Solution:
def two_sum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in nums:
j = target - i
tmp_nums_start_index = nums.index(i) + 1
tmp_nums = nums[tmp_nums_start_index:]
... |
DEBUG = True
UPLOADS_DEFAULT_DEST = 'uploads'
UPLOADED_RESUMES_ALLOW = ('pdf', 'PDF') # can't just use 'pdf' or ['pdf']
MAX_CONTENT_LENGTH = 32 * 1024 * 1024
MAX_CONTENT_LENGTH = 32 * 1024 * 1024
DB_USERNAME = 'vagrant'
DB_PASSWORD = 'vagrant'
DB_DATABASE = 'connect'
DB_HOST = '127.0.0.1'
TABLES = {}
TABLES['submis... | debug = True
uploads_default_dest = 'uploads'
uploaded_resumes_allow = ('pdf', 'PDF')
max_content_length = 32 * 1024 * 1024
max_content_length = 32 * 1024 * 1024
db_username = 'vagrant'
db_password = 'vagrant'
db_database = 'connect'
db_host = '127.0.0.1'
tables = {}
TABLES['submissions'] = 'CREATE TABLE IF NOT EXISTS ... |
class Solution:
# O(4^n) time | O(4^n) space
def letterCombinations(self, digits: str) -> List[str]:
dic = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl',
'6': 'mno', '7': 'pqrs', '8': 'tuv', "9": 'wxyz'}
n = len(digits)
if n < 1:
return []
lst = [ch f... | class Solution:
def letter_combinations(self, digits: str) -> List[str]:
dic = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
n = len(digits)
if n < 1:
return []
lst = [ch for ch in dic[digits[0]]]
for i in rang... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
server = "irc.freenode.net"
port = 6667
botname = "b0tsec"
chan = "#n0sec"
| server = 'irc.freenode.net'
port = 6667
botname = 'b0tsec'
chan = '#n0sec' |
# 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 __init__(self):
self.path = []
self.res = []
def make_tree(self, val, left, right):
... | class Treenode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def __init__(self):
self.path = []
self.res = []
def make_tree(self, val, left, right):
n = tree_node()
n.val = val... |
class Solution:
def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int:
@lru_cache(None)
def routes(start, fuel):
if fuel<0:
return 0
answer=0
#print('start:'+str(start)+', fuel:'+str(fuel)+', answer: '+str(an... | class Solution:
def count_routes(self, locations: List[int], start: int, finish: int, fuel: int) -> int:
@lru_cache(None)
def routes(start, fuel):
if fuel < 0:
return 0
answer = 0
if start == finish:
answer += 1
for i ... |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( arr , n ) :
mp = dict ( )
Sum = 0
count = 0
for i in range ( n ) :
if ( arr [ i ] == 0 ) :
... | def f_gold(arr, n):
mp = dict()
sum = 0
count = 0
for i in range(n):
if arr[i] == 0:
arr[i] = -1
sum += arr[i]
if Sum == 0:
count += 1
if Sum in mp.keys():
count += mp[Sum]
mp[Sum] = mp.get(Sum, 0) + 1
return count
if __name... |
#
# SPDX-FileCopyrightText: 2020 Amerlyq <amerlyq@gmail.com>
#
# SPDX-License-Identifier: CC0-1.0
#
"""
Main app
"""
__appname__ = 'flatmod'
__version__ = '0.1.0'
| """
Main app
"""
__appname__ = 'flatmod'
__version__ = '0.1.0' |
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
class Progression:
def __init__(self, start=0):
self._current = start
def _advance(self):
self._c... | class Progression:
def __init__(self, start=0):
self._current = start
def _advance(self):
self._current += 1
def __next__(self):
if self._current is None:
raise stop_iteration()
else:
answer = self._current
self._advance()
re... |
#input = '389125467' # example
input = '952316487' # my puzzle input
input = [int(n) for n in input]
next = {}
numcups = len(input)
for j in range(numcups):
next.update({input[j]: input[(j + 1) % numcups]})
steps = 100
# this is needed only in part 2
start = len(input) + 1
until = 1000000
next.update({input[-1]... | input = '952316487'
input = [int(n) for n in input]
next = {}
numcups = len(input)
for j in range(numcups):
next.update({input[j]: input[(j + 1) % numcups]})
steps = 100
start = len(input) + 1
until = 1000000
next.update({input[-1]: start})
for j in range(start, until):
next.update({j: j + 1})
next.update({unti... |
# Time: O(n)
# Space: O(1)
class Solution(object):
def shuffle(self, nums, n):
"""
:type nums: List[int]
:type n: int
:rtype: List[int]
"""
def index(i):
return 2*i if i < n else 2*(i-n)+1
for i in xrange(len(nums)):
j = i
... | class Solution(object):
def shuffle(self, nums, n):
"""
:type nums: List[int]
:type n: int
:rtype: List[int]
"""
def index(i):
return 2 * i if i < n else 2 * (i - n) + 1
for i in xrange(len(nums)):
j = i
while nums[i] >= 0... |
def egcd(a, b):
x1, x2 = 1, 0
y1, y2 = 0, 1
while b > 0:
tmp = a // b
x1, x2 = x2, x1 - tmp * x2
y1, y2 = y2, y1 - tmp * y2
a, b = b, a % b
return a, x1, y1
def modinv(a, b):
return egcd(a, b)[1] % b
| def egcd(a, b):
(x1, x2) = (1, 0)
(y1, y2) = (0, 1)
while b > 0:
tmp = a // b
(x1, x2) = (x2, x1 - tmp * x2)
(y1, y2) = (y2, y1 - tmp * y2)
(a, b) = (b, a % b)
return (a, x1, y1)
def modinv(a, b):
return egcd(a, b)[1] % b |
class Config():
def __init__(self, koji_host, koji_storage_host, arch, result_dir):
self.koji_host = koji_host
self.koji_storage_host = koji_storage_host
self.arch = arch
self.result_dir = result_dir
| class Config:
def __init__(self, koji_host, koji_storage_host, arch, result_dir):
self.koji_host = koji_host
self.koji_storage_host = koji_storage_host
self.arch = arch
self.result_dir = result_dir |
# two-finger pointer method. It is tedious to set the correct indices, conditions and extreme cases anyway
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
len1 = len(nums1)
len2 = len(nums2)
if len1 + len2 <= 1:
if len1 == 1:
... | class Solution:
def find_median_sorted_arrays(self, nums1: List[int], nums2: List[int]) -> float:
len1 = len(nums1)
len2 = len(nums2)
if len1 + len2 <= 1:
if len1 == 1:
return nums1[0]
elif len2 == 1:
return nums2[0]
else:
... |
# Class ini digunakan untuk menyimpan data Post dari database travelnesia
class Post:
# Constructor ini digunakan untuk inisialiasi data dari class Post
def __init__(self, post_id, title, username, location, location_rating, transport, vote, budget, content):
self.post_id = post_id
self.title = ... | class Post:
def __init__(self, post_id, title, username, location, location_rating, transport, vote, budget, content):
self.post_id = post_id
self.title = title
self.username = username
self.location = location
self.location_rating = location_rating
self.transport = ... |
'''
Simulation of signal propagation in the DWDM network
Optical signals, as defined via :class:`.info.SpectralInformation`, enter
:py:mod:`.elements` which compute how these signals are affected as they travel
through the :py:mod:`.network`.
The simulation is controlled via :py:mod:`.parameters` and implemented mainl... | """
Simulation of signal propagation in the DWDM network
Optical signals, as defined via :class:`.info.SpectralInformation`, enter
:py:mod:`.elements` which compute how these signals are affected as they travel
through the :py:mod:`.network`.
The simulation is controlled via :py:mod:`.parameters` and implemented mainl... |
def fact(n):
if(n==1):
return 1
else:
return n*fact(n-1)
a=int(input("ENTER A NUMBER"))
print(fact(a)) | def fact(n):
if n == 1:
return 1
else:
return n * fact(n - 1)
a = int(input('ENTER A NUMBER'))
print(fact(a)) |
class BaseTest(object):
def make_rpc_client(self):
err_msg = "make_rpc_client must be overridden in a subclass."
raise NotImplementedError(err_msg)
def test_send_rpc(self):
rpc_client = self.make_rpc_client()
result = rpc_client.send('eth_coinbase')
assert isinstance(re... | class Basetest(object):
def make_rpc_client(self):
err_msg = 'make_rpc_client must be overridden in a subclass.'
raise not_implemented_error(err_msg)
def test_send_rpc(self):
rpc_client = self.make_rpc_client()
result = rpc_client.send('eth_coinbase')
assert isinstance(... |
class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
cur = self.root
for c in word:
if c not in cur.children:
cur.children[c] = TrieNo... | class Trienode:
def __init__(self):
self.children = {}
self.is_word = False
class Trie:
def __init__(self):
self.root = trie_node()
def insert(self, word):
cur = self.root
for c in word:
if c not in cur.children:
cur.children[c] = trie_... |
"""
@Project : DuReader
@Module : __init__.py.py
@Author : Deco [deco@cubee.com]
@Created : 8/13/18 10:48 AM
@Desc : sentence embedding
nonparametric
parametric
""" | """
@Project : DuReader
@Module : __init__.py.py
@Author : Deco [deco@cubee.com]
@Created : 8/13/18 10:48 AM
@Desc : sentence embedding
nonparametric
parametric
""" |
################
'''
{
"e": "kline", // Event type
"E": 123456789, // Event time
"s": "BNBBTC", // Symbol
"k": {
"t": 123400000, // Kline start time
"T": 123460000, // Kline close time
"s": "BNBBTC", // Symbol
"i": "1m", // Interval
... | """
{
"e": "kline", // Event type
"E": 123456789, // Event time
"s": "BNBBTC", // Symbol
"k": {
"t": 123400000, // Kline start time
"T": 123460000, // Kline close time
"s": "BNBBTC", // Symbol
"i": "1m", // Interval
"f": 100, // First ... |
def aportecooperativa (INGRESOMENSUAL):
pregunta=INGRESOMENSUAL.isdigit()
if(pregunta):
pregunta1=int(INGRESOMENSUAL)
if (pregunta1<=2):
gasto=(pregunta1*0.01)
return gasto
elif ((pregunta1>2) and (pregunta1<=6)):
gasto=(pregunta1*0.02)
ret... | def aportecooperativa(INGRESOMENSUAL):
pregunta = INGRESOMENSUAL.isdigit()
if pregunta:
pregunta1 = int(INGRESOMENSUAL)
if pregunta1 <= 2:
gasto = pregunta1 * 0.01
return gasto
elif pregunta1 > 2 and pregunta1 <= 6:
gasto = pregunta1 * 0.02
... |
# Demo Python Strings - Escape Character
'''
Escape Character
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \ followed by the character you want to insert.
An example of an illegal character is a double quote inside a string that is surrounded by doubl... | """
Escape Character
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \\ followed by the character you want to insert.
An example of an illegal character is a double quote inside a string that is surrounded by double quotes:
Example with Error:
txt =... |
# CPU: 0.05 s
universities = set()
for _ in range(int(input())):
university, name = input().split()
if len(universities) >= 12:
break
elif university not in universities:
print(university, name)
universities.add(university)
| universities = set()
for _ in range(int(input())):
(university, name) = input().split()
if len(universities) >= 12:
break
elif university not in universities:
print(university, name)
universities.add(university) |
def menu():
x = 1
while x !=0 :
print (" Menu'")
print(" Descrizione Menu")
print(" VOCE MENU.....digita 1 --> ")
print(" VOCE MENU.... digita 2 --> ")
x = input("scegli cosa vuoi fare digita 0 per uscire............... --> ")
if x == "1":
return 1
... | def menu():
x = 1
while x != 0:
print(" Menu'")
print(' Descrizione Menu')
print(' VOCE MENU.....digita 1 --> ')
print(' VOCE MENU.... digita 2 --> ')
x = input('scegli cosa vuoi fare digita 0 per uscire............... --> ')
if x == '... |
class Team:
def __init__(self):
self.workers = [] # list of Worker objects
def hire(self, worker):
self.workers.append(worker)
def fire(self, pos):
self.workers.pop(pos)
| class Team:
def __init__(self):
self.workers = []
def hire(self, worker):
self.workers.append(worker)
def fire(self, pos):
self.workers.pop(pos) |
#
# PySNMP MIB module HUAWEI-SWITCH-SRV-RES-TRAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-SWITCH-SRV-RES-TRAP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:37:05 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, value_size_constraint, single_value_constraint, constraints_union) ... |
INGREDIENTS = [
"bone",
"undead eyeball",
"spider",
"fish tail",
"adamantine",
"tentacle of giant octopus or giant squid",
"ice",
"coal",
"food morsel",
"bitumen (a drop)",
"giant slug bile",
"jade dust",
"rotten egg",
"silver powder",
"artistic representatio... | ingredients = ['bone', 'undead eyeball', 'spider', 'fish tail', 'adamantine', 'tentacle of giant octopus or giant squid', 'ice', 'coal', 'food morsel', 'bitumen (a drop)', 'giant slug bile', 'jade dust', 'rotten egg', 'silver powder', 'artistic representation of caster', 'oils and unguents', 'soil mixture in a small ba... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 11 10:42:59 2020
@author: juanfe
"""
def sum2(a,b):
"""
:param a: (float) Primer variable a sumar
:param b: (float) Segunda varaible a sumar
:return c: (float) c=a+b
"""
c = a + b
return c
def sums(a,b,c):
"""
... | """
Created on Tue Aug 11 10:42:59 2020
@author: juanfe
"""
def sum2(a, b):
"""
:param a: (float) Primer variable a sumar
:param b: (float) Segunda varaible a sumar
:return c: (float) c=a+b
"""
c = a + b
return c
def sums(a, b, c):
"""
:param a: (float) Varaible a sumar.
:para... |
# This function returns pointer to LCA of two given
# values n1 and n2
# This function assumes that n1 and n2 are present in
# Binary Tree
def findLCA(root, n1, n2):
# Base Case
if root is None:
return None
# If either n1 or n2 matches with root's key, report
# the presence by returning root ... | def find_lca(root, n1, n2):
if root is None:
return None
if root.key == n1 or root.key == n2:
return root
left_lca = find_lca(root.left, n1, n2)
right_lca = find_lca(root.right, n1, n2)
if left_lca and right_lca:
return root
return left_lca if left_lca is not None else ri... |
# %% [114. Flatten Binary Tree to Linked List](https://leetcode.com/problems/flatten-binary-tree-to-linked-list/)
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
lst = list(to_list(p := root, True))
if r... | class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
lst = list(to_list((p := root), True))
if root:
root.left = None
for i in lst[1:]:
p.right = p = tree_node(i)
def to_list... |
class PWM:
def __enter__(self):
raise NotImplementedError()
def __exit__(self, exc_type, exc_value, traceback):
raise NotImplementedError()
def set_frequency(self, freq):
raise NotImplementedError()
def set_period(self, period_us):
raise NotImplementedError()
d... | class Pwm:
def __enter__(self):
raise not_implemented_error()
def __exit__(self, exc_type, exc_value, traceback):
raise not_implemented_error()
def set_frequency(self, freq):
raise not_implemented_error()
def set_period(self, period_us):
raise not_implemented_error()
... |
def solve(n, l):
l_len = len(l)
missing = ((l_len + 1) * (l_len + 2) // 2) - sum(l)
print(missing)
if __name__ == "__main__":
inp_n = [int(x) for x in input().split()]
inp_l = [int(x) for x in input().split()]
solve(n=inp_n[0], l=inp_l) | def solve(n, l):
l_len = len(l)
missing = (l_len + 1) * (l_len + 2) // 2 - sum(l)
print(missing)
if __name__ == '__main__':
inp_n = [int(x) for x in input().split()]
inp_l = [int(x) for x in input().split()]
solve(n=inp_n[0], l=inp_l) |
def neighbors(matrix,i,j,row,col):
mine = 0
if not ((i < 1) or (j < 1)):
if matrix[i - 1][j - 1]:
mine+=1
if not (i < 1):
if matrix[i - 1][j]:
mine+=1
if not ((i < 1) or (j >= col-1)):
if matrix[i - 1][j + 1]:
mine+=1
if not (j >= col-1):
... | def neighbors(matrix, i, j, row, col):
mine = 0
if not (i < 1 or j < 1):
if matrix[i - 1][j - 1]:
mine += 1
if not i < 1:
if matrix[i - 1][j]:
mine += 1
if not (i < 1 or j >= col - 1):
if matrix[i - 1][j + 1]:
mine += 1
if not j >= col - 1:... |
# https://leetcode.com/problems/unique-email-addresses/
class Solution:
def numUniqueEmails(self, emails):
"""
:type emails: List[str]
:rtype: int
"""
def create_unique_email(email):
local, domain = email.split('@')
built_local = []
for c... | class Solution:
def num_unique_emails(self, emails):
"""
:type emails: List[str]
:rtype: int
"""
def create_unique_email(email):
(local, domain) = email.split('@')
built_local = []
for c in local:
if c == '.':
... |
def removeDuplicates(nums):
prev = None
current = None
new_list = []
for i in nums:
current = i
if current != prev:
new_list.append(current)
prev = current
return new_list
| def remove_duplicates(nums):
prev = None
current = None
new_list = []
for i in nums:
current = i
if current != prev:
new_list.append(current)
prev = current
return new_list |
base_directional_light = {
'type': 'directional',
'direction': [[10.0, 10.0, 10.0]],
'ambient_color': [[0.5, 0.5, 0.5]],
'diffuse_color': [[0.5, 0.5, 0.5]],
'specular_color': [[0.5, 0.5, 0.5]],
}
base_point_light = {
'type': 'point',
'ambient_color': [[0.5, 0.5, 0.5]],
'diffuse_color': ... | base_directional_light = {'type': 'directional', 'direction': [[10.0, 10.0, 10.0]], 'ambient_color': [[0.5, 0.5, 0.5]], 'diffuse_color': [[0.5, 0.5, 0.5]], 'specular_color': [[0.5, 0.5, 0.5]]}
base_point_light = {'type': 'point', 'ambient_color': [[0.5, 0.5, 0.5]], 'diffuse_color': [[0.3, 0.3, 0.3]], 'specular_color': ... |
class Profile:
def __init__(self,n,f,t):
self.name = n.title() # ensures that both passwords have both upper and lower case letters
self.food = f.title()
self.time = t
self.Sentence = self.sentence()
def sentence(self):
if self.time == 0:
return (f'{self.... | class Profile:
def __init__(self, n, f, t):
self.name = n.title()
self.food = f.title()
self.time = t
self.Sentence = self.sentence()
def sentence(self):
if self.time == 0:
return f'{self.name} likes to eat {self.food} at 12am!'
elif self.time < 12:
... |
class InjectException(Exception):
"""Base class for all exceptions."""
pass
class NonInjectableTypeError(InjectException):
"""Raised when a type could not be injected (i.e. they are no corresponding bindings)."""
pass
class NoBindingFound(NonInjectableTypeError):
"""Raised when no binding was fo... | class Injectexception(Exception):
"""Base class for all exceptions."""
pass
class Noninjectabletypeerror(InjectException):
"""Raised when a type could not be injected (i.e. they are no corresponding bindings)."""
pass
class Nobindingfound(NonInjectableTypeError):
"""Raised when no binding was foun... |
# Below are implementations of some standard RL agents
class RandomAgent():
"""Random agent"""
def __init__(self, env):
self.env = env
def act(self, state):
return self.env.action_space.sample()
def reset(self):
pass
def learn(self, state, action, reward, next_state, done... | class Randomagent:
"""Random agent"""
def __init__(self, env):
self.env = env
def act(self, state):
return self.env.action_space.sample()
def reset(self):
pass
def learn(self, state, action, reward, next_state, done):
pass |
##Ejercicio 11
# Cual es la complejidad del codigo?
#
# Entrada:
# -
# Salida:
'''
si n 10 o 16
primer while 2
primer while 4
primer while 8
primer while 16
segundo while 16
segundo while 16
-------------
'''
#
#
# la complejidad resultante es de O log(log(n))
# ya que es un efecto ... | """
si n 10 o 16
primer while 2
primer while 4
primer while 8
primer while 16
segundo while 16
segundo while 16
-------------
"""
n = 16
p = 0
i = 1
while i < n:
p = p + 1
i = i * 2
print('primer while', i)
j = 1
while j < p:
j = j * 2
print('segundo while', i) |
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
def bruteforce():
for i in range(9):
for j in range(9):
boxr, boxc = i//3 , j//3
num = board[i][j]
if num=='.':
continue
... | class Solution:
def is_valid_sudoku(self, board: List[List[str]]) -> bool:
def bruteforce():
for i in range(9):
for j in range(9):
(boxr, boxc) = (i // 3, j // 3)
num = board[i][j]
if num == '.':
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vi: set expandtab shiftwidth=4 :
# auther: shun kawai
# ===============================
# function.py
# ===============================
def func(a, b):
print(a, "+", b, "=", a+b)
for x in range(1, 11):
func(x, x*x)
| def func(a, b):
print(a, '+', b, '=', a + b)
for x in range(1, 11):
func(x, x * x) |
# Kabupaten Bandung
kecamatan = {
'Ciwidey': { 'pusat': 'Lebakmuncang', 'luas': 48.47 },
'Rancabali': { 'pusat': 'Patengan', 'luas': 148.37 },
'Pasirjambu': { 'pusat': 'Pasirjambu', 'luas': 239.58 },
'Cimaung': { 'pusat': 'Cipinang', 'luas': 55 },
'Pengalengan': { 'pusat': 'Pangalengan', 'luas': 195.41 },
... | kecamatan = {'Ciwidey': {'pusat': 'Lebakmuncang', 'luas': 48.47}, 'Rancabali': {'pusat': 'Patengan', 'luas': 148.37}, 'Pasirjambu': {'pusat': 'Pasirjambu', 'luas': 239.58}, 'Cimaung': {'pusat': 'Cipinang', 'luas': 55}, 'Pengalengan': {'pusat': 'Pangalengan', 'luas': 195.41}, 'Kertasari': {'pusat': 'Cibeureum', 'luas': ... |
HAVE_RUN_INIT = "False"
def on_init(server):
global HAVE_RUN_INIT
HAVE_RUN_INIT = "True"
def on_message(msg, server):
if msg["text"] == u"test_init":
return HAVE_RUN_INIT
| have_run_init = 'False'
def on_init(server):
global HAVE_RUN_INIT
have_run_init = 'True'
def on_message(msg, server):
if msg['text'] == u'test_init':
return HAVE_RUN_INIT |
class Solution:
def arrangeCoins(self, n: int) -> int:
lo, hi = 0, n + 1
while lo < hi:
mi = (hi - lo) // 2 + lo
if mi * (mi + 1) // 2 <= n:
lo = mi + 1
else:
hi = mi
return lo-1
| class Solution:
def arrange_coins(self, n: int) -> int:
(lo, hi) = (0, n + 1)
while lo < hi:
mi = (hi - lo) // 2 + lo
if mi * (mi + 1) // 2 <= n:
lo = mi + 1
else:
hi = mi
return lo - 1 |
# Copyright 2018 Databricks, Inc.
VERSION = '1.2.1.dev0'
| version = '1.2.1.dev0' |
# Create a style for the shadow
label_style = lv.style_t()
lv.style_copy(label_style, lv.style_plain)
label_style.text.opa = lv.OPA._50
# Create a label for the shadow first (it's in the background)
shadow_label = lv.label(lv.scr_act())
shadow_label.set_style(lv.label.STYLE.MAIN, label_style)
# Create the main label
... | label_style = lv.style_t()
lv.style_copy(label_style, lv.style_plain)
label_style.text.opa = lv.OPA._50
shadow_label = lv.label(lv.scr_act())
shadow_label.set_style(lv.label.STYLE.MAIN, label_style)
main_label = lv.label(lv.scr_act())
main_label.set_text('A simple method to create\n' + 'shadows on text\n' + 'It even wo... |
def main():
f = open("Bridge_5000000.txt", "r")
lines = f.readlines()
f.close()
idx = 0
parsed_len = 0
with open("Bridge_5000000_parsed.txt", 'w') as g:
g.write(lines[0])
g.write(lines[1])
g.write(lines[2])
idx += 3
valid_cards_list = [set(list(range(13*0, 13*1))),
set(list(range(13*1, 13*2))),... | def main():
f = open('Bridge_5000000.txt', 'r')
lines = f.readlines()
f.close()
idx = 0
parsed_len = 0
with open('Bridge_5000000_parsed.txt', 'w') as g:
g.write(lines[0])
g.write(lines[1])
g.write(lines[2])
idx += 3
valid_cards_list = [set(list(range(13 * ... |
def strStr(haystack, needle):
if len(needle) == 0:
return 0
if needle in haystack:
return haystack.index(needle)
else:
return -1
| def str_str(haystack, needle):
if len(needle) == 0:
return 0
if needle in haystack:
return haystack.index(needle)
else:
return -1 |
def utility(countryId, numOfRemainingTeams):
if(storedValues[numOfRemainingTeams][countryId] != -1):
return storedValues[numOfRemainingTeams][countryId]
max = 0;
for i in range(numOfRemainingTeams + 1):
value = livesPerTeam[i][countryId] + utility(countryId - 1, numOfRemainingTeams - i)
if(value > max):
... | def utility(countryId, numOfRemainingTeams):
if storedValues[numOfRemainingTeams][countryId] != -1:
return storedValues[numOfRemainingTeams][countryId]
max = 0
for i in range(numOfRemainingTeams + 1):
value = livesPerTeam[i][countryId] + utility(countryId - 1, numOfRemainingTeams - i)
... |
def test_read_main(test_client):
response = test_client.get("/")
assert response.status_code == 200
assert response.json() == {"Hello": "World"}
| def test_read_main(test_client):
response = test_client.get('/')
assert response.status_code == 200
assert response.json() == {'Hello': 'World'} |
class Set():
def __init__(self):
self.items = {}
def has(self, value):
if self.items.get(value):
return True
return False
def add(self, value):
if not self.has(value):
self.items[value] = value
return True
return False
... | class Set:
def __init__(self):
self.items = {}
def has(self, value):
if self.items.get(value):
return True
return False
def add(self, value):
if not self.has(value):
self.items[value] = value
return True
return False
def del... |
### The following code implements the Convolutional Neural Network on MNIST dataset in pytorch.
"""
Step 1: Load the data
"""
train_dataset = dsets.MNIST(root = './data',
train = True,
transform = transforms.ToTensor(),
download = True
... | """
Step 1: Load the data
"""
train_dataset = dsets.MNIST(root='./data', train=True, transform=transforms.ToTensor(), download=True)
test_dataset = dsets.MNIST(root='./data', train=False, transform=transforms.ToTensor(), download=True)
'\nStep 2: Make the dataset iterable\n'
batch_size = 100
n_iters = 6000
num_epochs =... |
results = []
for x in data:
y = delayed(inc)(x)
results.append(y)
total = delayed(sum)(results)
total.compute()
| results = []
for x in data:
y = delayed(inc)(x)
results.append(y)
total = delayed(sum)(results)
total.compute() |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 3 19:34:03 2021
@author: Dhiman
"""
def countingValleys(steps, path):
# Write your code here
depth = 0
n = 0
for i in range(len(path)):
if(path[i] == 'U'):
depth +=1
... | """
Created on Thu Jun 3 19:34:03 2021
@author: Dhiman
"""
def counting_valleys(steps, path):
depth = 0
n = 0
for i in range(len(path)):
if path[i] == 'U':
depth += 1
if path[i] == 'D':
depth -= 1
if depth == -1:
n = n + 1
return n
x... |
# Python Program for Merge Sort
# Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves.
# The merge() function is used for merging two halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and ... | def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
l = arr[:mid]
r = arr[mid:]
merge_sort(L)
merge_sort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
... |
#!/usr/bin/python
def main():
try:
a = int(input("Input number: "))
b = int(input("Input number: "))
CubeSum = a**3 + b**3
print("The Cube sum is equal to " + str(CubeSum))
main()
except:
raise SystemExit
def message():
print("Press any non-number key to ter... | def main():
try:
a = int(input('Input number: '))
b = int(input('Input number: '))
cube_sum = a ** 3 + b ** 3
print('The Cube sum is equal to ' + str(CubeSum))
main()
except:
raise SystemExit
def message():
print('Press any non-number key to terminate')
messa... |
# blockgen.py
# Functions for generating Scratch JSON
def procedure(name, args, atomic, body):
argnames, argtypes = zip(*args)
return [0, 0,
[["procDef", name + " " + " ".join(argtypes), list(argnames), [""]*len(argnames), atomic],
body]]
def getparam(name):
return ["getparam", nam... | def procedure(name, args, atomic, body):
(argnames, argtypes) = zip(*args)
return [0, 0, [['procDef', name + ' ' + ' '.join(argtypes), list(argnames), [''] * len(argnames), atomic], body]]
def getparam(name):
return ['getparam', name, 'r']
def listappend(listname, val):
return ['append:toList:', val, ... |
out=[0,0,0]
x=int(input())
for i in range(x):
d=int(input())
g=d%3
out[g]+=1
print(" ".join([str(i)for i in out]))
| out = [0, 0, 0]
x = int(input())
for i in range(x):
d = int(input())
g = d % 3
out[g] += 1
print(' '.join([str(i) for i in out])) |
# WRITE YOUR SOLUTION HERE:
class LotteryNumbers :
def __init__(self, week_number: int, correct_numbers: list):
self.correct_numbers = correct_numbers
self.week_number = week_number
def number_of_hits(self,numbers: list):
return len([number for number in numbers if number in self.co... | class Lotterynumbers:
def __init__(self, week_number: int, correct_numbers: list):
self.correct_numbers = correct_numbers
self.week_number = week_number
def number_of_hits(self, numbers: list):
return len([number for number in numbers if number in self.correct_numbers])
def hits_i... |
numbers = int(input())
res_num = 0
for i in range (1, numbers + 1):
i = str(i)
res_num = 0
for num in range (len(i)):
res_num += int(i[num])
if res_num in(5, 7, 11):
print(f'{i} -> True')
else:
print(f'{i} -> False') | numbers = int(input())
res_num = 0
for i in range(1, numbers + 1):
i = str(i)
res_num = 0
for num in range(len(i)):
res_num += int(i[num])
if res_num in (5, 7, 11):
print(f'{i} -> True')
else:
print(f'{i} -> False') |
# This largely mimics the AST of Python 2.7 with additional nodes
# to support Cython specific constructs.
#------------------------------------------------------------------------------
# AST validation
#------------------------------------------------------------------------------
def assert_mod(node, var_name):
... | def assert_mod(node, var_name):
msg = '%s must be a mod node.' % var_name
assert isinstance(node, mode), msg
def assert_stmt(node, var_name):
msg = '%s must be a stmt node.' % var_name
assert isinstance(node, stmt), msg
def assert_stmts(items, var_name):
msg = '%s must be stmt nodes.' % var_name
... |
# Python program to find largest
# number in a list
# list of numbers
list1 = [10, 20, 4, 45, 99]
# sorting the list
list1.sort()
# printing the last element
print("Largest element is:", list1[-1])
| list1 = [10, 20, 4, 45, 99]
list1.sort()
print('Largest element is:', list1[-1]) |
class Roles(object):
Admin = 'ur:admin'
ApiKeyUser = 'apikey-user'
SessionUser = 'session-user'
class Permissions(object):
List = 'list'
View = 'view'
Edit = 'edit'
Create = 'create'
Delete = 'delete'
Import = 'import'
ListSupporters = 'listsupporters'
AdminPetition = ... | class Roles(object):
admin = 'ur:admin'
api_key_user = 'apikey-user'
session_user = 'session-user'
class Permissions(object):
list = 'list'
view = 'view'
edit = 'edit'
create = 'create'
delete = 'delete'
import = 'import'
list_supporters = 'listsupporters'
admin_petition = '... |
#########################################################
#
# Just scratch space, this won't execute or import properly.
#
#########################################################
name = "All executive parent domains"
compliance_stats(name, parents_only, utils.executive_only)
name = "All executive CFO Act parent do... | name = 'All executive parent domains'
compliance_stats(name, parents_only, utils.executive_only)
name = 'All executive CFO Act parent domains'
compliance_stats(name, parents_only, utils.cfo_act_only)
name = 'All executive CFO Act (minus DoD) parent domains'
compliance_stats(name, parents_only, utils.cfo_act_only_sans_d... |
t=int(input())
while(t):
t=t-1
a=list(map(int,input()))
a1=a[::-1]
if(a.count(1)<1):
print("NO")
else:
b1=int(a.index(1))
b2=a1.index(1)
b2=int(len(a)-b2)
b3=a[b1:b2]
if(int(sum(b3))==b2-b1):
print("YES")
else:
print("NO... | t = int(input())
while t:
t = t - 1
a = list(map(int, input()))
a1 = a[::-1]
if a.count(1) < 1:
print('NO')
else:
b1 = int(a.index(1))
b2 = a1.index(1)
b2 = int(len(a) - b2)
b3 = a[b1:b2]
if int(sum(b3)) == b2 - b1:
print('YES')
els... |
enter = input()
new_list = ""
explosion = 0
length = 0
while length < len(enter):
for i in range(len(enter)):
if not enter[i] == ">" and explosion > 0:
explosion -= 1
elif enter[i] == ">":
explosion += int(enter[i + 1])
new_list += enter[i]
else:
... | enter = input()
new_list = ''
explosion = 0
length = 0
while length < len(enter):
for i in range(len(enter)):
if not enter[i] == '>' and explosion > 0:
explosion -= 1
elif enter[i] == '>':
explosion += int(enter[i + 1])
new_list += enter[i]
else:
... |
s1 = "geeksforgeeks"
s2 = "geeks"
# Check If s2 is substring of s1
s2SubStrS1 = s2 in s1
print(s2SubStrS1)
# Concatenation
s3 = s1 + s2
print(s3)
# Find First Occurence Index of Substring s2
# NOTE : s2 must be Substring -> else gives an error
print(s1.index(s2))
# Find Last Occurence Index of Substring s2
# NOT... | s1 = 'geeksforgeeks'
s2 = 'geeks'
s2_sub_str_s1 = s2 in s1
print(s2SubStrS1)
s3 = s1 + s2
print(s3)
print(s1.index(s2))
print(s1.rindex(s2))
print(s1.rindex(s2, 1, len(s1)))
sc1 = 'geeks'
sc2 = sc1.upper()
sc3 = sc2.lower()
print(sc2)
print(sc3)
print(sc2.isupper())
print(sc3.islower())
sp1 = 'GeeksForGeeks Python Cour... |
#!/usr/bin/env python3
# Day 8: Power of Two
#
# Given an integer, write a function to determine if it is a power of two.
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and (n & (n - 1)) == 0
# Tests
assert Solution().isPowerOfTwo(1) == True
assert Solution().isPowerOfTwo(16) == Tru... | class Solution:
def is_power_of_two(self, n: int) -> bool:
return n > 0 and n & n - 1 == 0
assert solution().isPowerOfTwo(1) == True
assert solution().isPowerOfTwo(16) == True
assert solution().isPowerOfTwo(218) == False
assert solution().isPowerOfTwo(-16) == False |
# 'ctb6'
classlist = ['O', 'E-NR', 'E-OD', 'B-SP', 'S-AS', 'I-P', 'I-JJ', 'E-IJ', 'S-OD', 'I-OD', 'I-VA', 'E-ETC', 'B-CC', 'S-MSP', 'B-LC', 'E-VA', 'E-VC', 'E-DT', 'I-VC', 'S-PN', 'E-MSP', 'I-PU', 'E-VE', 'B-DT', 'S-CC', 'S-DT', 'S-DER', 'B-AD', 'S-VV', 'S-NR', 'B-OD', 'S-VE', 'B-NN-SHORT', 'S-LB', 'S-CS', 'I-CC', 'E-... | classlist = ['O', 'E-NR', 'E-OD', 'B-SP', 'S-AS', 'I-P', 'I-JJ', 'E-IJ', 'S-OD', 'I-OD', 'I-VA', 'E-ETC', 'B-CC', 'S-MSP', 'B-LC', 'E-VA', 'E-VC', 'E-DT', 'I-VC', 'S-PN', 'E-MSP', 'I-PU', 'E-VE', 'B-DT', 'S-CC', 'S-DT', 'S-DER', 'B-AD', 'S-VV', 'S-NR', 'B-OD', 'S-VE', 'B-NN-SHORT', 'S-LB', 'S-CS', 'I-CC', 'E-PN', 'E-P'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.