content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Application:
def __init__(self) -> None:
self.commands = []
def add_command(self, command):
self.commands.append(command)
def run(self):
print("Running")
| class Application:
def __init__(self) -> None:
self.commands = []
def add_command(self, command):
self.commands.append(command)
def run(self):
print('Running') |
# Xor the message with a key stream. The message and the key need to be of
# equal length. (This is one time pad, a perfectly correct crypto scheme)
#
# Parameters:
# m - message in bytes; if expressed in string, we convert it to bytes
# k - keystream in bytes; if expressed in string, we convert it to bytes... | def xor(m, k):
if isinstance(m, str):
m = m.encode('utf-8')
if isinstance(k, str):
k = k.encode('utf-8')
assert len(m) == len(k)
return bytes([m[i] ^ k[i] for i in range(len(m))]) |
# https://www.codechef.com/problems/CHFCHK
for T in range(int(input())):
n,a=int(input()),list(map(int,input().split()))
print(min(a)) | for t in range(int(input())):
(n, a) = (int(input()), list(map(int, input().split())))
print(min(a)) |
def is_inc_list(arr):
print(arr)
for i in range(len(arr)):
arr[i] = arr[i] + 1
return arr
print(is_inc_list([1,3,4]))
| def is_inc_list(arr):
print(arr)
for i in range(len(arr)):
arr[i] = arr[i] + 1
return arr
print(is_inc_list([1, 3, 4])) |
SECURE_DIR_PATH = '/indirect'
TOKEN_FILE_NAME = 'token.txt'
BETA_TOKEN_FILE_NAME = 'beta.txt'
BETAMODE = True | secure_dir_path = '/indirect'
token_file_name = 'token.txt'
beta_token_file_name = 'beta.txt'
betamode = True |
def main():
rst = generate_series()
for _ in range(15):
print(next(rst))
def generate_series():
cur_idx = 1
cur_val = 1
while True:
if get_num_divisors(cur_val) == cur_idx:
cur_idx += 1
yield cur_val
cur_val = 1
cur_val +=1
def get_num_di... | def main():
rst = generate_series()
for _ in range(15):
print(next(rst))
def generate_series():
cur_idx = 1
cur_val = 1
while True:
if get_num_divisors(cur_val) == cur_idx:
cur_idx += 1
yield cur_val
cur_val = 1
cur_val += 1
def get_num_d... |
# Prestige Count
global PrestigeCount
PrestigeCount = 0
global MinerBought
MinerBought = False
global AscendCount
AscendCount = 0
# Multipliers for Prestige
global Mult
Mult = {"Wood": 90, "Stones": 90, "Food": 90, "Metal": 90, "Electricity": 90, "Prestige": 1, "Mandorium": 1}
# Map Level
global MapLevel
MapLevel = ... | global PrestigeCount
prestige_count = 0
global MinerBought
miner_bought = False
global AscendCount
ascend_count = 0
global Mult
mult = {'Wood': 90, 'Stones': 90, 'Food': 90, 'Metal': 90, 'Electricity': 90, 'Prestige': 1, 'Mandorium': 1}
global MapLevel
map_level = 0
global MusicPaused
music_paused = False |
n1 = float(input())
n2 = float(input())
n3 = float(input())
media = ((n1 * 2) / 10) + ((n2 * 3) / 10) + ((n3 * 5) / 10)
print(f"MEDIA = {media:.1f}") | n1 = float(input())
n2 = float(input())
n3 = float(input())
media = n1 * 2 / 10 + n2 * 3 / 10 + n3 * 5 / 10
print(f'MEDIA = {media:.1f}') |
class UninonSet:
def __init__(self, size) -> None:
# [0, 1, 2, 3, 4....]
self.root = [i for i in range(size)]
self.rank = [1] * size
def find(self, v):
if v == self.root[v]:
return v
self.root[v] = self.find(self.root[v])
return self.root[v]
def... | class Uninonset:
def __init__(self, size) -> None:
self.root = [i for i in range(size)]
self.rank = [1] * size
def find(self, v):
if v == self.root[v]:
return v
self.root[v] = self.find(self.root[v])
return self.root[v]
def union(self, v1, v2):
... |
def us_state_abbr_to_state_name(df, source_data_name):
df = df
state_abbr_to_fullname = {
'al': 'alabama',
'ak': 'alaska',
'az': 'arizona',
'ar': 'arkansas',
'ca': 'california',
'co': 'colorado',
'ct': 'connecticut',
'de': 'delaware',
'fl':... | def us_state_abbr_to_state_name(df, source_data_name):
df = df
state_abbr_to_fullname = {'al': 'alabama', 'ak': 'alaska', 'az': 'arizona', 'ar': 'arkansas', 'ca': 'california', 'co': 'colorado', 'ct': 'connecticut', 'de': 'delaware', 'fl': 'florida', 'ga': 'georgia', 'hi': 'hawaii', 'id': 'idaho', 'il': 'illino... |
# Problem: https://dashboard.programmingpathshala.com/practice/question?questionId=31§ionId=1&moduleId=1&topicId=2&subtopicId=25&assignmentId=5
t = int(input())
q = []
for i in range(t):
q.append(int(input()))
n = 10**6
spf = [-1]*(n+1) # Smallest Prime Factor
for i in range(2,n+1):
if spf[i] == -1:
... | t = int(input())
q = []
for i in range(t):
q.append(int(input()))
n = 10 ** 6
spf = [-1] * (n + 1)
for i in range(2, n + 1):
if spf[i] == -1:
for j in range(i ** 2, n + 1, i):
if spf[j] == -1:
spf[j] = i
print(spf[0:26])
for i in range(t):
num = q[i]
power = 0
pri... |
class Solution:
def circularArrayLoop(self, nums: List[int]) -> bool:
def advance(i: int) -> int:
return (i + nums[i]) % len(nums)
if len(nums) < 2:
return False
for i, num in enumerate(nums):
if num == 0:
continue
slow = i
fast = advance(slow)
while num * nu... | class Solution:
def circular_array_loop(self, nums: List[int]) -> bool:
def advance(i: int) -> int:
return (i + nums[i]) % len(nums)
if len(nums) < 2:
return False
for (i, num) in enumerate(nums):
if num == 0:
continue
slow = ... |
IP = [2, 6, 3, 1, 4, 8, 5, 7]
IP1 = [4, 1, 3, 5, 7, 2, 8, 6]
EP = [4, 1, 2, 3, 2, 3, 4, 1]
P4 = [2, 4, 3, 1]
P8 = [6, 3, 7, 4, 8, 5, 10, 9]
P10 = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6]
SUB0 = [[1, 0, 3, 2],
[3, 2, 1, 0],
[0, 2, 1, 3],
[3, 1, 3, 2]]
SUB1 = [[0, 1, 2, 3],
[2, 0... | ip = [2, 6, 3, 1, 4, 8, 5, 7]
ip1 = [4, 1, 3, 5, 7, 2, 8, 6]
ep = [4, 1, 2, 3, 2, 3, 4, 1]
p4 = [2, 4, 3, 1]
p8 = [6, 3, 7, 4, 8, 5, 10, 9]
p10 = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6]
sub0 = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]]
sub1 = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]]
def permute(p... |
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
'''
(
/\
( )
/\ /\
( )( )
T: O(4^n / sqrt(n)) and S: O(4^n / sqrt(n))
'''
result = []
def generate(s, nopen, nclose):
if len(s) =... | class Solution:
def generate_parenthesis(self, n: int) -> List[str]:
"""
(
/ ( )
/\\ / ( )( )
T: O(4^n / sqrt(n)) and S: O(4^n / sqrt(n))
"""
result = []
def generate(s, nopen, nclose):
if len(s) == 2 * n:
... |
# $Header: /nfs/slac/g/glast/ground/cvs/GlastRelease-scons/GlastClassify/GlastClassifyLib.py,v 1.6 2012/08/15 05:06:11 heather Exp $
def generate(env, **kw):
# if not kw.get('noGaudi', 0):
# env.Tool('addLibrary', library = env['gaudiLibs'])
if not kw.get('depsOnly', 0):
env.Tool('addLibrary', lib... | def generate(env, **kw):
if not kw.get('depsOnly', 0):
env.Tool('addLibrary', library=['GlastClassify'])
env.Tool('classifierLib')
env.Tool('ntupleWriterSvcLib')
env.Tool('xmlBaseLib')
env.Tool('facilitiesLib')
env.Tool('addLibrary', library=env['xercesLibs'])
env.Tool('addLibrary', ... |
CSV = "csv"
JSON = "json"
TABLE = "table"
TEXT = "text"
| csv = 'csv'
json = 'json'
table = 'table'
text = 'text' |
class DSU:
def __init__(self):
self.parent = [_ for _ in range(26)]
def find(self, s):
s_id = ord(s) - ord('a')
while self.parent[s_id] != s_id:
self.parent[s_id] = self.parent[self.parent[s_id]]
s_id = self.parent[s_id]
return s_id
def union(self, a... | class Dsu:
def __init__(self):
self.parent = [_ for _ in range(26)]
def find(self, s):
s_id = ord(s) - ord('a')
while self.parent[s_id] != s_id:
self.parent[s_id] = self.parent[self.parent[s_id]]
s_id = self.parent[s_id]
return s_id
def union(self, ... |
count_sheets = int(input())
sheets_per_hour = int(input())
days = int(input())
hours_for_reading_per_day = (count_sheets / sheets_per_hour ) / days
print(hours_for_reading_per_day)
| count_sheets = int(input())
sheets_per_hour = int(input())
days = int(input())
hours_for_reading_per_day = count_sheets / sheets_per_hour / days
print(hours_for_reading_per_day) |
__all__ = [
'__author__', '__classifiers__', '__desc__', '__license__',
'__package_name__', '__scripts__', '__url__', '__version__',
]
__author__ = 'Luke Powers'
__author_email__ = 'luke-powers@users.noreply.github.com'
# For more classifiers, see http://goo.gl/zZQaZ
__classifiers__ = [
'Development Status... | __all__ = ['__author__', '__classifiers__', '__desc__', '__license__', '__package_name__', '__scripts__', '__url__', '__version__']
__author__ = 'Luke Powers'
__author_email__ = 'luke-powers@users.noreply.github.com'
__classifiers__ = ['Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: D... |
class PageLayout(layouts.Layout):
def __init__(self, pdf_printer, page_num, container):
self._pdf_printer = pdf_printer
self._container = container
self._alignment = AlignmentLayout(pdf_printer, paper)
def outer_box_size(self):
return self._container.inner_box_size(),
def inner_box_size(self):
... | class Pagelayout(layouts.Layout):
def __init__(self, pdf_printer, page_num, container):
self._pdf_printer = pdf_printer
self._container = container
self._alignment = alignment_layout(pdf_printer, paper)
def outer_box_size(self):
return (self._container.inner_box_size(),)
d... |
# coding: utf8
# try something like
db = plugins.comments.db
Post = db.plugin_comments_post
@auth.requires_signature()
def index():
tablename = request.args(0)
record_id = request.args(1,cast=int)
Post.tablename.default = tablename
Post.record_id.default=record_id
if auth.user:
form = SQLF... | db = plugins.comments.db
post = db.plugin_comments_post
@auth.requires_signature()
def index():
tablename = request.args(0)
record_id = request.args(1, cast=int)
Post.tablename.default = tablename
Post.record_id.default = record_id
if auth.user:
form = sqlform(Post).process()
if for... |
# Lecture 3.6 slide 2
# Bisection search for a square root
# Value of x used in lecture are 25, 12345, 1234567
x = 25
epsilon = 0.01
numGuesses = 0
low = 0.0
high = x
ans = (high + low)/2.0 #Choose half of value x as starting guess
while abs(ans**2 - x) >= epsilon: #Too far apart
print('low = ' + str(low) + ' h... | x = 25
epsilon = 0.01
num_guesses = 0
low = 0.0
high = x
ans = (high + low) / 2.0
while abs(ans ** 2 - x) >= epsilon:
print('low = ' + str(low) + ' high = ' + str(high) + ' ans = ' + str(ans))
num_guesses += 1
if ans ** 2 < x:
low = ans
else:
high = ans
ans = (high + low) / 2.0
print... |
def solution(number):
dp = []
dp.append(1)
dp.append(2)
dp.append(4)
for n in range(3, number):
dp.append(dp[n-3]+dp[n-2]+dp[n-1])
return dp[number-1]
for _ in range(int(input())):
number = int(input())
print(solution(number))
| def solution(number):
dp = []
dp.append(1)
dp.append(2)
dp.append(4)
for n in range(3, number):
dp.append(dp[n - 3] + dp[n - 2] + dp[n - 1])
return dp[number - 1]
for _ in range(int(input())):
number = int(input())
print(solution(number)) |
dictionary = {
'Student': ['S1','S2','S3','S4'],
'Physics': [78,45,56,32],
'Chemistry': [45,12,56,98],
'Mathematics':[88,98,100,45]
}
m_total = 0
for values in list(dictionary.values())[1:]:
if max(values)>m_total:
m_total = max(values)
print(m_total) | dictionary = {'Student': ['S1', 'S2', 'S3', 'S4'], 'Physics': [78, 45, 56, 32], 'Chemistry': [45, 12, 56, 98], 'Mathematics': [88, 98, 100, 45]}
m_total = 0
for values in list(dictionary.values())[1:]:
if max(values) > m_total:
m_total = max(values)
print(m_total) |
def maskify(cc):
if len(cc) <= 4:
ans = ""
for i in cc:
ans = ans + i
else:
list = []
for i in cc:
list.append(i)
ans = ""
nLen = len(cc) - 4
for i in range(len(list)):
if i < nLen:
ans = ans + "#"
... | def maskify(cc):
if len(cc) <= 4:
ans = ''
for i in cc:
ans = ans + i
else:
list = []
for i in cc:
list.append(i)
ans = ''
n_len = len(cc) - 4
for i in range(len(list)):
if i < nLen:
ans = ans + '#'
... |
# Slicing a list
myList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 0 1 2 3 4 5 6 7 8 9
# -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
print (myList[-1]) # Prints the last value in the list
print (myList[0:5]) # list[start:end] end non-inclusive
print (myList[:-2]) # 0.....7
print (myList[1:]) # 1.....9
print (myLis... | my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(myList[-1])
print(myList[0:5])
print(myList[:-2])
print(myList[1:])
print(myList[0:9:2])
print(myList[-1:2:-1])
sample_url = 'http://trashbin.net'
print(sampleUrl)
print(sampleUrl[::-1])
print(sampleUrl[-4:])
print(sampleUrl[7:])
print(sampleUrl[7:-4]) |
# the first part of this creates a dictionary of the indices of each
# acceptable word it can find in the given string -- then it gets the
# word lengths by subtracting adjacent indices and appends each to the list
def sentence_words(s, ws):
# dictionary of indexes of each word in the string
sentence = {}
for w i... | def sentence_words(s, ws):
sentence = {}
for w in ws:
if w not in s:
continue
sentence[s.find(w)] = w
idxs = sorted(sentence.keys())
l = []
for (idx, x) in enumerate(idxs):
if idx is len(idxs) - 1:
word_length = len(s) - x
else:
wor... |
class MaxHeap:
def __init__(self):
self.heap = []
self.size = -1
def display(self):
return print(self.heap)
def insert(self, k):
self.heap.append(k)
self.size += 1
i = self.size
while True:
parent_node = self.heap[(i-1)//2] i... | class Maxheap:
def __init__(self):
self.heap = []
self.size = -1
def display(self):
return print(self.heap)
def insert(self, k):
self.heap.append(k)
self.size += 1
i = self.size
while True:
parent_node = self.heap[(i - 1) // 2] if i != 0... |
nome = "Pablo Oliveira Mesquita"
print(nome)
pos = []
for i in range(len(nome)):
if nome[i] == " ":
pos.append(i)
for i in range(len(pos)):
if i == 0:
print(nome[0:pos[i]])
else:
print('\n temos que pensar') | nome = 'Pablo Oliveira Mesquita'
print(nome)
pos = []
for i in range(len(nome)):
if nome[i] == ' ':
pos.append(i)
for i in range(len(pos)):
if i == 0:
print(nome[0:pos[i]])
else:
print('\n temos que pensar') |
class TextureProxy:
def __init__(self, _id: int):
self._id: int = _id
@property
def id(self) -> int:
return self.id
| class Textureproxy:
def __init__(self, _id: int):
self._id: int = _id
@property
def id(self) -> int:
return self.id |
'''Chat bot
Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
'''
def runBot():
print('running bot')
| """Chat bot
Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
"""
def run_bot():
print('running bot') |
## function use partition process of quick sort...
# here we assume pivot == 0.
def negative_element(arr):
pivot = 0
i = -1
for j in range(len(arr)):
if arr[j]<pivot:
i += 1
arr[i],arr[j] = arr[j],arr[i]
elif arr[j]>=pivot:
j+=1
return arr
## function... | def negative_element(arr):
pivot = 0
i = -1
for j in range(len(arr)):
if arr[j] < pivot:
i += 1
(arr[i], arr[j]) = (arr[j], arr[i])
elif arr[j] >= pivot:
j += 1
return arr
def negative_ele(arr):
left = 0
right = len(arr) - 1
while left <= ... |
chars: list = list()
for c in range(97, 97 + int(input())):
chars.append(chr(c))
for x in chars:
for y in chars:
for z in chars:
print(x+y+z)
| chars: list = list()
for c in range(97, 97 + int(input())):
chars.append(chr(c))
for x in chars:
for y in chars:
for z in chars:
print(x + y + z) |
menu = [
["egg", "spam", "bacon"],
["egg", "sausage", "bacon"],
["egg", "spam"],
["egg", "bacon", "spam"],
["egg", "bacon", "sausage", "spam"],
["spam", "bacon", "sausage", "spam"],
["spam", "egg", "spam", "spam", "bacon", "spam"],
["spam", "egg", "sausage", "spam"],
["chick... | menu = [['egg', 'spam', 'bacon'], ['egg', 'sausage', 'bacon'], ['egg', 'spam'], ['egg', 'bacon', 'spam'], ['egg', 'bacon', 'sausage', 'spam'], ['spam', 'bacon', 'sausage', 'spam'], ['spam', 'egg', 'spam', 'spam', 'bacon', 'spam'], ['spam', 'egg', 'sausage', 'spam'], ['chicken', 'chips']]
for x in range(1, 31):
fizz... |
def header():
print(' =================================================== ')
print('|%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%|')
print('|%%%%%%%%%%%%%%%%%% D O M I N O E S %%%%%%%%%%%%%%%%|')
print('|%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%|')
print('|%%%%%%%%%%%%%%%%%%%%%... | def header():
print(' =================================================== ')
print('|%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%|')
print('|%%%%%%%%%%%%%%%%%% D O M I N O E S %%%%%%%%%%%%%%%%|')
print('|%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%|')
print('|%%%%%%%%%%%%%%%%%%%%%%%%%%... |
class Solution:
def uniquePathsIII(self, grid: List[List[int]]) -> int:
count = len([x for r in grid for x in r if x == 0]) + 2
start = [[i,j] for i in range(len(grid)) for j in range(len(grid[0])) if grid[i][j] == 1][0]
self.ans = 0
self.dfs(grid, start[0], start[1], 0, count)
... | class Solution:
def unique_paths_iii(self, grid: List[List[int]]) -> int:
count = len([x for r in grid for x in r if x == 0]) + 2
start = [[i, j] for i in range(len(grid)) for j in range(len(grid[0])) if grid[i][j] == 1][0]
self.ans = 0
self.dfs(grid, start[0], start[1], 0, count)
... |
S = input()
odd = S[0::2]
even = S[1::2]
if((set(odd) <= {'R', 'U', 'D'}) and (set(even) <= {'L', 'U', 'D'})):
print('Yes')
else: print('No') | s = input()
odd = S[0::2]
even = S[1::2]
if set(odd) <= {'R', 'U', 'D'} and set(even) <= {'L', 'U', 'D'}:
print('Yes')
else:
print('No') |
def test_root_page_has_swaggerui(client):
rv = client.get('/')
assert b'Name Request API' in rv.data
| def test_root_page_has_swaggerui(client):
rv = client.get('/')
assert b'Name Request API' in rv.data |
def create_table(cur):
cur.execute(
'''
CREATE TABLE IF NOT EXISTS blob (
id INTEGER PRIMARY KEY AUTOINCREMENT,
hash TEXT UNIQUE,
state INTEGER
)
''')
cur.execute(
'''
CREATE TABLE IF NOT EXISTS reference (
id INTEGER PRIMARY KEY AUTOINCREMENT,
from_id INTEGER REFERENCES blob (id),
to_id INTEGER RE... | def create_table(cur):
cur.execute('\nCREATE TABLE IF NOT EXISTS blob (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n hash TEXT UNIQUE,\n state INTEGER\n)\n')
cur.execute('\nCREATE TABLE IF NOT EXISTS reference (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n from_id INTEGER REFERENCES blob (id),\n to_id INTEGER R... |
_base_ = [
'../_base_/models/retinanet_r50_fpn.py',
'../_base_/datasets/coco_detection.py',
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]
# data
data = dict(samples_per_gpu=8)
# optimizer
model = dict(
backbone=dict(
depth=18,
init_cfg=dict(type='Pretrained', c... | _base_ = ['../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py']
data = dict(samples_per_gpu=8)
model = dict(backbone=dict(depth=18, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet18')), neck=dict(in_channe... |
#to count the number of vowels and consants in a word in a word
s1 = input("enter a string ").lower() #taking string and converting it to lowercase
vc, cc = 0, 0 #vc-vowels cc-consonant
for s in s1:
if (s.isalpha()): #to check whether letter is alpshabet or not
if (s=='a' or s=='e' or s=='i' or s=='o' or s... | s1 = input('enter a string ').lower()
(vc, cc) = (0, 0)
for s in s1:
if s.isalpha():
if s == 'a' or s == 'e' or s == 'i' or (s == 'o') or (s == 'u'):
vc = vc + 1
else:
cc = cc + 1
print('vowel count = ', vc, ' consonant count = ', cc) |
class Pet:
def __init__(self, name, age) -> None:
self.name = name
self.age = age
def show(self):
print(f"I'm {self.name} and I'm {self.age} years old!")
def speak(self):
print("Uhh?")
class Cat(Pet):
def __init__(self, name, age, color) -> None:
super(... | class Pet:
def __init__(self, name, age) -> None:
self.name = name
self.age = age
def show(self):
print(f"I'm {self.name} and I'm {self.age} years old!")
def speak(self):
print('Uhh?')
class Cat(Pet):
def __init__(self, name, age, color) -> None:
super().__in... |
with open("package-list.txt", "rt") as f:
lines = f.readlines()
lines = [l for l in lines if 'automatic]' not in l]
lines = [l for l in lines if '[installed' in l]
lines = [l.split(',',2)[0] for l in lines]
lines = [l.split(' ',2)[0] for l in lines]
lines = [l.split('/',2)[0] for l in lines]
lines = list(set(lines... | with open('package-list.txt', 'rt') as f:
lines = f.readlines()
lines = [l for l in lines if 'automatic]' not in l]
lines = [l for l in lines if '[installed' in l]
lines = [l.split(',', 2)[0] for l in lines]
lines = [l.split(' ', 2)[0] for l in lines]
lines = [l.split('/', 2)[0] for l in lines]
lines = list(set(lin... |
class Novelty:
def __init__(self, knn):
self.knn = knn
# self.novelty_threshold = novelty_threshold
self.archive = []
def get_arch_from_str(self, arch_str, verbose=False):
if verbose: print(f'Input architecture: {arch_str}')
arch = []
for node_ops in arch_str.split('+'):
for eleme... | class Novelty:
def __init__(self, knn):
self.knn = knn
self.archive = []
def get_arch_from_str(self, arch_str, verbose=False):
if verbose:
print(f'Input architecture: {arch_str}')
arch = []
for node_ops in arch_str.split('+'):
for element in node... |
def peel():
print('The first step is to peel the banana.')
def eat():
print('Now you have to eat the banana.') | def peel():
print('The first step is to peel the banana.')
def eat():
print('Now you have to eat the banana.') |
def Solve(N, A):
count = 0
already_checked = set()
for j in range(len(A)):
i = A[j]
if i not in already_checked:
for k in range(j+1, len(A)):
if i % A[k] == 0:
count += 1
already_checked.add(i)
if A[k] not in... | def solve(N, A):
count = 0
already_checked = set()
for j in range(len(A)):
i = A[j]
if i not in already_checked:
for k in range(j + 1, len(A)):
if i % A[k] == 0:
count += 1
already_checked.add(i)
if A[k] not ... |
#!/usr/bin/env python
'''
V2015-05-03
'''
###general Constant
digit_list=["0","1","2","3","4","5","6","7","8","9"]
DIGIT_LIST=["0","1","2","3","4","5","6","7","8","9"]
pure_nt_list = ["A","T","C","G"]
pure_nt_withN_list = ["A","T","C","G","N"]
nt_list=["A","T","C","G","D"]
nt_full_list=["A","T","C","G","a... | """
V2015-05-03
"""
digit_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
digit_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
pure_nt_list = ['A', 'T', 'C', 'G']
pure_nt_with_n_list = ['A', 'T', 'C', 'G', 'N']
nt_list = ['A', 'T', 'C', 'G', 'D']
nt_full_list = ['A', 'T', 'C', 'G', 'a', 't', 'c', '... |
# Homework task for Week 4
# Write program that asks the user to input any positive integer
# and output the successive values of the following calculation
# At each step calculate the next value by taking the current value
# if the current value is even divide it by two
# but if it is odd multiple by three and add ... | x = int(input('Please enter a positive integer: '))
y = 2
while x > 1:
if x % y == 0:
x = int(x / 2)
else:
x = int(x * 3 + 1)
print(x) |
def extend_query_filter(model, args):
if model:
print(f'Extend query filter for {model}')
return args
| def extend_query_filter(model, args):
if model:
print(f'Extend query filter for {model}')
return args |
nterms = int(input('Which element you want: '))
n1 = 0
n2 = 1
count = 2
if nterms <= 0:
print('Enter a integer.')
elif nterms == 1:
print(n1)
else:
print(n1, ',', n2, end=' , ')
while count < nterms:
nth = n1 + n2
print(nth, end=' , ')
n1 = n2
n2 = nth
count += ... | nterms = int(input('Which element you want: '))
n1 = 0
n2 = 1
count = 2
if nterms <= 0:
print('Enter a integer.')
elif nterms == 1:
print(n1)
else:
print(n1, ',', n2, end=' , ')
while count < nterms:
nth = n1 + n2
print(nth, end=' , ')
n1 = n2
n2 = nth
count += 1 |
# Code generated by data_to_py.py.
version = '0.1'
_data =\
b'\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00'\
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x71\x0b\x40\x00'\
b'\x00\x00\x00\x00\x00\x00\x00\x00\x09\xfc\x8b\xa8\x00\x00\x00\x00'\
b'\x00\x00\x00\x00\x00\x04\xbf\x42\xee\x88\x00\x00\x... | version = '0.1'
_data = b'\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01q\x0b@\x00\x00\x00\x00\x00\x00\x00\x00\x00\t\xfc\x8b\xa8\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\xbfB\xee\x88\x00\x00\x00\x00\x80\x00\x00\x18C\xd5o\xb7\xf0\x00\x00\x04[\x1a\x00\x00\x... |
num = float(input())
if num > 0 and num < 25.000:
print('Intervalo [0,25]')
elif num > 25.000 and num < 50.000:
print('Intervalo (25,50]')
elif num > 50.000 and num < 75.000:
print('Intervalo (50,75]')
elif num > 75.000 and num < 100.000:
print('Intervalo (75,100]')
else:
print('Fora de intervalo')
... | num = float(input())
if num > 0 and num < 25.0:
print('Intervalo [0,25]')
elif num > 25.0 and num < 50.0:
print('Intervalo (25,50]')
elif num > 50.0 and num < 75.0:
print('Intervalo (50,75]')
elif num > 75.0 and num < 100.0:
print('Intervalo (75,100]')
else:
print('Fora de intervalo') |
s = 'ABC'
for char in s:
print(char)
it = iter(s)
while True:
try:
print(next(it))
except StopIteration:
del it
break
| s = 'ABC'
for char in s:
print(char)
it = iter(s)
while True:
try:
print(next(it))
except StopIteration:
del it
break |
pole = [1, 2, 5, -1, 3]
print(len(pole))
| pole = [1, 2, 5, -1, 3]
print(len(pole)) |
nrecords_by_dayofweek = survey_data_decoupled["eventDate"].dt.dayofweek.value_counts().sort_index()
fig, ax = plt.subplots(figsize=(6, 6))
nrecords_by_dayofweek.plot(kind="barh", color="#00007f", ax=ax);
# If you want to represent the ticklabels as proper names, uncomment the following line:
# ax.set_yticklabels(["Mon... | nrecords_by_dayofweek = survey_data_decoupled['eventDate'].dt.dayofweek.value_counts().sort_index()
(fig, ax) = plt.subplots(figsize=(6, 6))
nrecords_by_dayofweek.plot(kind='barh', color='#00007f', ax=ax) |
nums = [12, 34, 65, 43, 21, 97, 13, 57, 10, 32]
finalNums = []
moreFinalNums = []
def compareMore(a):
for x in nums:
if x > a:
c = finalNums.append(x)
def compareLess(d):
for x in nums:
if x < d:
c = moreFinalNums.append(x)
get = int(input("To Compare More Than : ")... | nums = [12, 34, 65, 43, 21, 97, 13, 57, 10, 32]
final_nums = []
more_final_nums = []
def compare_more(a):
for x in nums:
if x > a:
c = finalNums.append(x)
def compare_less(d):
for x in nums:
if x < d:
c = moreFinalNums.append(x)
get = int(input('To Compare More Than : '... |
def turnNumberIntoPercent(number):
num = str(number)
num = num.replace('.','')
if number >= 100:
num = num[:1] + '.' + num[1:]
else:
num = '.' + num
return float(num) | def turn_number_into_percent(number):
num = str(number)
num = num.replace('.', '')
if number >= 100:
num = num[:1] + '.' + num[1:]
else:
num = '.' + num
return float(num) |
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
class AVLTree():
def __init__(self, nodes=list()):
self.node = None
self.height = -1
self.balance = 0
for node in nodes:
self.insert(node)
def height(... | class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
class Avltree:
def __init__(self, nodes=list()):
self.node = None
self.height = -1
self.balance = 0
for node in nodes:
self.insert(node)
def height(s... |
# Interface for products
class ProductA:
def do_stuff(self):
pass
class ProductB:
def do_stuff(self):
pass
# Concrete products
class ConcreteProductA1(ProductA):
def do_stuff(self):
print(self, 'do stuff')
class ConcreteProductA2(ProductA):
def do_stuff(self):
print... | class Producta:
def do_stuff(self):
pass
class Productb:
def do_stuff(self):
pass
class Concreteproducta1(ProductA):
def do_stuff(self):
print(self, 'do stuff')
class Concreteproducta2(ProductA):
def do_stuff(self):
print(self, 'do stuff')
class Concreteproductb1(... |
#!/usr/bin/python3
print_sorted_dictionary = __import__('6-print_sorted_dictionary').print_sorted_dictionary
my_dict = { 'language': "C", 'Number': 89, 'track': "Low level", 'ids': [1, 2, 3] }
print_sorted_dictionary(my_dict)
| print_sorted_dictionary = __import__('6-print_sorted_dictionary').print_sorted_dictionary
my_dict = {'language': 'C', 'Number': 89, 'track': 'Low level', 'ids': [1, 2, 3]}
print_sorted_dictionary(my_dict) |
my_list = [element * element for element in range(5)]
my_list_2 = []
for element in range(5):
my_list_2.append(element)
print(my_list)
print(my_list_2)
field = [["." for x in range(10)] for y in range(10)]
[print( "".join(row) ) for row in field]
my_list = [[element, element * element] for element in range(6)... | my_list = [element * element for element in range(5)]
my_list_2 = []
for element in range(5):
my_list_2.append(element)
print(my_list)
print(my_list_2)
field = [['.' for x in range(10)] for y in range(10)]
[print(''.join(row)) for row in field]
my_list = [[element, element * element] for element in range(6)]
print(... |
with open('gutenberg.txt.txt')as object:
contents = object.read()
print(contents.count('the'))
| with open('gutenberg.txt.txt') as object:
contents = object.read()
print(contents.count('the')) |
#
# PySNMP MIB module CISCO-CNO-SWITCH-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-CNO-SWITCH-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:36:15 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, value_size_constraint, constraints_union, constraints_intersection) ... |
PARAMS = {
"ref_left_support_threshold" : 0,
"ref_right_support_threshold" : 0,
"ref_left_junction_threshold" : 0,
"ref_right_junction_threshold" : 0,
"nonref_left_support_threshold" : 0,
"nonref_right_support_threshold" : 0,
"nonref_left_junction_threshold" : 0,
"nonref_right_junction_... | params = {'ref_left_support_threshold': 0, 'ref_right_support_threshold': 0, 'ref_left_junction_threshold': 0, 'ref_right_junction_threshold': 0, 'nonref_left_support_threshold': 0, 'nonref_right_support_threshold': 0, 'nonref_left_junction_threshold': 0, 'nonref_right_junction_threshold': 0} |
{
"targets": [
{
"target_name": "popplonode",
"sources": [
"getTextFromPageAsync.cpp",
"popplonode.cpp",
],
"cflags_cc!": [
"-fno-exceptions",
],
"cflags_cc": [
"-fpermissive",
],
"dependencies": [
"lib/poppler.gyp:libpoppler"... | {'targets': [{'target_name': 'popplonode', 'sources': ['getTextFromPageAsync.cpp', 'popplonode.cpp'], 'cflags_cc!': ['-fno-exceptions'], 'cflags_cc': ['-fpermissive'], 'dependencies': ['lib/poppler.gyp:libpoppler'], 'conditions': [["OS=='win'", {'msvs_settings': {'VCCLCompilerTool': {'ExceptionHandling': 1}}, 'link_set... |
class Solution:
def minCost(self, maxTime: int, edges: List[List[int]], passingFees: List[int]) -> int:
n = len(passingFees)
graph = [[] for _ in range(n)]
minHeap = [] # (cost, time, node)
cost = [math.inf] * n # cost[i] := min cost to reach cities[i]
time = [math.inf] * n # time[i] := min cos... | class Solution:
def min_cost(self, maxTime: int, edges: List[List[int]], passingFees: List[int]) -> int:
n = len(passingFees)
graph = [[] for _ in range(n)]
min_heap = []
cost = [math.inf] * n
time = [math.inf] * n
for (x, y, t) in edges:
graph[x].append(... |
expected_output = {
"mac": {
"access-list": {
"extended": {
"test-2": {
"name": "test-2",
"seqs": {
10: {
"action": "permit",
"dst": "any",
... | expected_output = {'mac': {'access-list': {'extended': {'test-2': {'name': 'test-2', 'seqs': {10: {'action': 'permit', 'dst': 'any', 'ethertype': 'arp', 'seq-id': 10, 'source': 'host', 'srchost': 'e481.84a5.e47e', 'vlan': '10', 'vlan-tag-format': 'single-tagged'}, 11: {'action': 'permit', 'dst': 'any', 'ethertype': 'ip... |
#
# PySNMP MIB module OPENBSD-MEM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OPENBSD-MEM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:35:01 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, value_size_constraint, constraints_intersection, single_value_constraint) ... |
#!/bin/python
def diff(string):
V=filter(lambda x: x == "A" or x=="E" or x=="I" or x=="O" or x=="U",list(string))
C=filter(lambda x: x not in L,list(string))
return V, C
| def diff(string):
v = filter(lambda x: x == 'A' or x == 'E' or x == 'I' or (x == 'O') or (x == 'U'), list(string))
c = filter(lambda x: x not in L, list(string))
return (V, C) |
answer = input("would you like to play (yes/no)\n")
if answer.lower().strip() == "yes":
answer = input("you encounter a dark alleyway, you have 3 options, will you go straight, right or left\n")
if answer =='left':
print('you run into a frog, it turns into a dragon, it kills you, GAME OVER')
elif answer ... | answer = input('would you like to play (yes/no)\n')
if answer.lower().strip() == 'yes':
answer = input('you encounter a dark alleyway, you have 3 options, will you go straight, right or left\n')
if answer == 'left':
print('you run into a frog, it turns into a dragon, it kills you, GAME OVER')
elif a... |
# simple function
def addByTwo(number):
return number + 2
# function with default parameters value
def addNumber(number, addBy=1):
return number + addBy
print(addByTwo(7))
def bubble_sort(numbers):
for i in range(len(numbers)):
for j in range(len(numbers) - i - 1):
# swapping
... | def add_by_two(number):
return number + 2
def add_number(number, addBy=1):
return number + addBy
print(add_by_two(7))
def bubble_sort(numbers):
for i in range(len(numbers)):
for j in range(len(numbers) - i - 1):
if numbers[j] > numbers[j + 1]:
temp = numbers[j]
... |
inputFile = open('./Resources/third/text.txt')
outputFile = open('./Resources/third/words.txt')
text = inputFile.readlines()[0]
word = outputFile.readlines()[0].split(' ')
print(word[0])
count = 0
for i in text:
if word[0] in text:
count += 1
print(count)
inputFile.close()
outputFile.close() | input_file = open('./Resources/third/text.txt')
output_file = open('./Resources/third/words.txt')
text = inputFile.readlines()[0]
word = outputFile.readlines()[0].split(' ')
print(word[0])
count = 0
for i in text:
if word[0] in text:
count += 1
print(count)
inputFile.close()
outputFile.close() |
#
# (c) Peralta Informatics 2007
# $Id: DeployWebsiteConfiguration.py 299 2008-01-19 08:42:05Z andrei $
#
class WebsiteConfiguration(object):
class AuthenticationConfiguration(object):
def __init__(self):
self.Name = None
self.Type = None
class ScriptMap(object):
def _... | class Websiteconfiguration(object):
class Authenticationconfiguration(object):
def __init__(self):
self.Name = None
self.Type = None
class Scriptmap(object):
def __init__(self):
self.Extension = None
self.ScriptProcessor = None
self... |
families = ['thamesc', 'uni-sans', 'verdana']
single = ['impact', 'lobster', 'comic-sans']
def get_font_path(name, bold=False, italic=False):
name = name.lower().replace(' ', '-')
if name in single:
return f'fonts/{name}.ttf'
if name in families:
suffix = ''
if bold:
su... | families = ['thamesc', 'uni-sans', 'verdana']
single = ['impact', 'lobster', 'comic-sans']
def get_font_path(name, bold=False, italic=False):
name = name.lower().replace(' ', '-')
if name in single:
return f'fonts/{name}.ttf'
if name in families:
suffix = ''
if bold:
suf... |
# -*- coding: utf-8 -*-
def hello(name):
suffix = "Hello"
print("%s, %s" % (suffix, name))
x = hello
#print(dir(echo))
print(hello.__name__)
print(x.__name__)
print(hello.__code__.co_varnames)
| def hello(name):
suffix = 'Hello'
print('%s, %s' % (suffix, name))
x = hello
print(hello.__name__)
print(x.__name__)
print(hello.__code__.co_varnames) |
max = -99999999
for i in range(0,10,1):
a = int(input())
if(max < a):
max = a
print(max)
| max = -99999999
for i in range(0, 10, 1):
a = int(input())
if max < a:
max = a
print(max) |
class BackTestingSetup(object):
def __init__(self):
self.capital = 100000.0
#leverage is determined by the account
self.leverage = 2.0
self.data_frequency = 'day'
#maximum history data from the most recent data point
self.look_back = 150
self.cancel_policy =... | class Backtestingsetup(object):
def __init__(self):
self.capital = 100000.0
self.leverage = 2.0
self.data_frequency = 'day'
self.look_back = 150
self.cancel_policy = 'never_cancel'
self.trading_universe = 'us_equities'
def get_universes(self):
pass
... |
def format_name(first_name, last_name):
# code goes here
if first_name != '' and last_name != '':
return ("Name: " + last_name + ", " + first_name)
elif first_name != '' or last_name != '':
return ("Name: " + last_name + first_name)
else:
return ''
return string
print(format_name("Ernest", "Hemingway"))
# ... | def format_name(first_name, last_name):
if first_name != '' and last_name != '':
return 'Name: ' + last_name + ', ' + first_name
elif first_name != '' or last_name != '':
return 'Name: ' + last_name + first_name
else:
return ''
return string
print(format_name('Ernest', 'Hemingway... |
# Copyright 2013 IBM Corp.
#
# 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 t... | def upgrade(migration_engine):
conn = migration_engine.connect()
result = conn.execute('update compute_node_stats set deleted = id, deleted_at = current_timestamp where compute_node_id not in (select id from compute_nodes where deleted <> 0)')
result.close()
conn.close()
def downgrade(migration_engine)... |
#!/usr/bin/env python3
# ----------------------------------------------------------
# LISTS
# List are also ordered sequences
# a list are represented with square brackets
# list are mutables
my_list = ["Michale", "Jackson", 10.4, True, 1455]
for i in range(len(my_list)):
print(i)
print("------------------")
# ... | my_list = ['Michale', 'Jackson', 10.4, True, 1455]
for i in range(len(my_list)):
print(i)
print('------------------')
mix_list = ['Eduardo', 'Rasgado', 10.1212, 1224, [1, 2, 3, 4, 5], ('A', 12), (22, 45)]
for i in range(len(mix_list)):
print(mix_list[i])
print('---------------------')
for i in range(len(mix_lis... |
N, *A = map(int, open(0).read().split())
a = range(2 ** N)
while len(a) != 2:
t = []
for i in range(0, len(a), 2):
if A[a[i]] > A[a[i + 1]]:
t.append(a[i])
else:
t.append(a[i + 1])
a = t
if A[a[0]] > A[a[1]]:
print(a[1] + 1)
else:
print(a[0] + 1)
| (n, *a) = map(int, open(0).read().split())
a = range(2 ** N)
while len(a) != 2:
t = []
for i in range(0, len(a), 2):
if A[a[i]] > A[a[i + 1]]:
t.append(a[i])
else:
t.append(a[i + 1])
a = t
if A[a[0]] > A[a[1]]:
print(a[1] + 1)
else:
print(a[0] + 1) |
#
# PySNMP MIB module TCAv2-MIB (http://pysnmp.sf.net)
# Produced by pysmi-0.0.1 from TCAv2-MIB at Fri May 8 14:22:23 2015
# On host cray platform Linux version 2.6.37.6-smp by user tt
# Using Python version 2.7.2 (default, Apr 2 2012, 20:32:47)
#
( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbol... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, constraints_intersection, value_size_constraint, value_range_constraint) ... |
def configure(context):
context.stage("tests.fixtures.devalidation.A1")
context.stage("tests.fixtures.devalidation.A2")
def execute(context):
a1 = context.stage("tests.fixtures.devalidation.A1")
a2 = context.stage("tests.fixtures.devalidation.A2")
return a1 + a2
| def configure(context):
context.stage('tests.fixtures.devalidation.A1')
context.stage('tests.fixtures.devalidation.A2')
def execute(context):
a1 = context.stage('tests.fixtures.devalidation.A1')
a2 = context.stage('tests.fixtures.devalidation.A2')
return a1 + a2 |
{
'includes': [
'../external/skia/gyp/common.gypi',
],
'variables': {
'glue_dir' : 'output'
},
'targets': [
{
'target_name': 'libxobotos',
'type': 'shared_library',
'mac_bundle' : 1,
'include_dirs' : [
'../external/skia/src/core', # needed to get SkConcaveToTriangl... | {'includes': ['../external/skia/gyp/common.gypi'], 'variables': {'glue_dir': 'output'}, 'targets': [{'target_name': 'libxobotos', 'type': 'shared_library', 'mac_bundle': 1, 'include_dirs': ['../external/skia/src/core', '../external/skia/gm', '../external/skia/include/pipe', 'include', '/usr/include/mono-2.0'], 'cflags'... |
#
# @lc app=leetcode id=567 lang=python3
#
# [567] Permutation in String
#
# @lc code=start
class Solution:
def checkInclusion(self, s1, s2):
# s1: target
# s2: pool
p = 0
win = len(s1)
s1 = sorted(list(s1))
while p + win <= len(s2):
current_str = s2[p : ... | class Solution:
def check_inclusion(self, s1, s2):
p = 0
win = len(s1)
s1 = sorted(list(s1))
while p + win <= len(s2):
current_str = s2[p:p + win]
ls = sorted(list(current_str))
if ls == s1:
return True
p += 1
r... |
# work with these variables
rivers = set(input().split())
states = set(input().split())
print(rivers.difference(states))
| rivers = set(input().split())
states = set(input().split())
print(rivers.difference(states)) |
class Solution:
def oddEvenList(self, head):
if head is None or head.next is None or head.next.next is None:
return head
head_next = head.next
previous_node = head
node = previous_node.next
odd_not_even = True
while node is not None:
odd_not_e... | class Solution:
def odd_even_list(self, head):
if head is None or head.next is None or head.next.next is None:
return head
head_next = head.next
previous_node = head
node = previous_node.next
odd_not_even = True
while node is not None:
odd_not... |
class Solution:
def XXX(self, a: str, b: str) -> str:
a=int(a,2)
b=int(b,2)
sum=a+b
return str(bin(sum))[2:]
| class Solution:
def xxx(self, a: str, b: str) -> str:
a = int(a, 2)
b = int(b, 2)
sum = a + b
return str(bin(sum))[2:] |
N = int(input())
nums = list(input())
res = 0
for i in range(N):
res += int(nums[i])
print(res) | n = int(input())
nums = list(input())
res = 0
for i in range(N):
res += int(nums[i])
print(res) |
def sieve(limit):
prime = [True] * (limit + 1)
prime[0] = prime[1] = False
for i in range(2, int(limit ** 0.5) + 1):
if prime[i]:
for j in range(i * i, limit + 1, i):
prime[j] = False
return [i for i, x in enumerate(prime) if x]
| def sieve(limit):
prime = [True] * (limit + 1)
prime[0] = prime[1] = False
for i in range(2, int(limit ** 0.5) + 1):
if prime[i]:
for j in range(i * i, limit + 1, i):
prime[j] = False
return [i for (i, x) in enumerate(prime) if x] |
'''input
ggppgggpgg
2
gpg
0
'''
# -*- coding: utf-8 -*-
# AtCoder Beginner Contest
# Problem D
if __name__ == '__main__':
s = input()
# See:
# http://arc062.contest.atcoder.jp/data/arc/062/editorial.pdf
print(len(s) // 2 - s.count('p'))
| """input
ggppgggpgg
2
gpg
0
"""
if __name__ == '__main__':
s = input()
print(len(s) // 2 - s.count('p')) |
def mul(i, j):
return i * j
def test_mul():
assert mul(9, 9) == 81
def test_mul2():
assert mul(2, 2) == 4 | def mul(i, j):
return i * j
def test_mul():
assert mul(9, 9) == 81
def test_mul2():
assert mul(2, 2) == 4 |
# Your task is to complete all these function's
# function should append an element on to the stack
def push(arr, ele):
# Code here
arr.append(ele)
# Function should pop an element from stack
def pop(arr):
# Code here
arr.append(len(arr) - 1)
# function should return 1/0 or True/False
def isFull(n, ar... | def push(arr, ele):
arr.append(ele)
def pop(arr):
arr.append(len(arr) - 1)
def is_full(n, arr):
if len(arr) == n:
return True
return False
def is_empty(arr):
if len(arr) == 0:
return True
return False
def get_min(n, arr):
return min(arr) |
#
# PySNMP MIB module ONEACCESS-AAA-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ONEACCESS-AAA-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:24:50 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, value_size_constraint, constraints_union, value_range_constraint) ... |
def stampa(n):
if n > 0:
print("\nIl programma calcola la somma seguente: ")
print("\n7",end="")
for j in range(1,n,1):
print(end=" + 7"+"1"*j) | def stampa(n):
if n > 0:
print('\nIl programma calcola la somma seguente: ')
print('\n7', end='')
for j in range(1, n, 1):
print(end=' + 7' + '1' * j) |
# This time you need to import the randint function from
# random all by yourself.
home = randint(0, 8)
visitors = randint(0, 8)
print('Final score: ', home, ' to ', visitors)
| home = randint(0, 8)
visitors = randint(0, 8)
print('Final score: ', home, ' to ', visitors) |
x = 10
def func():
print(x * 2)
#print(x, x, x) | x = 10
def func():
print(x * 2) |
data,lookup,os=None,None,None
def verify():
return "module"
def init(dataV,lookupV):
global data,lookup,os
data = dataV
lookup = lookupV
os = lookup.get("os")
return "usrmng"
usernames = []
class load():
def users():
f = open(data.files+"data/Users/user info.redi")
f.seek(0)
global usernames... | (data, lookup, os) = (None, None, None)
def verify():
return 'module'
def init(dataV, lookupV):
global data, lookup, os
data = dataV
lookup = lookupV
os = lookup.get('os')
return 'usrmng'
usernames = []
class Load:
def users():
f = open(data.files + 'data/Users/user info.redi')
... |
class Engine:
def __init__(self):
self.mode = 0
self.keyboards = []
def get_keyboard(self):
return self.keyboards[self.mode % len(self.keyboards)]
def add_keyboard(self, keyboard):
self.keyboards.append(keyboard)
def change_mode(self):
self.mode += 1
| class Engine:
def __init__(self):
self.mode = 0
self.keyboards = []
def get_keyboard(self):
return self.keyboards[self.mode % len(self.keyboards)]
def add_keyboard(self, keyboard):
self.keyboards.append(keyboard)
def change_mode(self):
self.mode += 1 |
def get_first_number():
return int(input("What is the first number? "))
def get_second_number():
return int(input("What is the second number? "))
def print_results(first_number, second_number):
fmt_str = "{:d} {} {:d} = {}"
print(fmt_str.format(first_number, "+", second_number, first_number + secon... | def get_first_number():
return int(input('What is the first number? '))
def get_second_number():
return int(input('What is the second number? '))
def print_results(first_number, second_number):
fmt_str = '{:d} {} {:d} = {}'
print(fmt_str.format(first_number, '+', second_number, first_number + second_n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.