content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
while True:
a, b = map(int, input().split(" "))
if not a and not b:
break
print(a + b) | while True:
(a, b) = map(int, input().split(' '))
if not a and (not b):
break
print(a + b) |
class LetterFrequencyPair:
def __init__(self, letter: str, frequency: int):
self.letter: str = letter
self.frequency: int = frequency
def __str__(self):
return '{}:{}'.format(self.letter, self.frequency)
class HTreeNode:
pass
print(LetterFrequencyPair('A', 23))
| class Letterfrequencypair:
def __init__(self, letter: str, frequency: int):
self.letter: str = letter
self.frequency: int = frequency
def __str__(self):
return '{}:{}'.format(self.letter, self.frequency)
class Htreenode:
pass
print(letter_frequency_pair('A', 23)) |
class HashMap:
def __init__(self, size):
self.array_size = size
self.array = [None] * size
def hash(self, key, count_collisions = 0):
return sum(key.encode()) + count_collisions
def compressor(self, hash_code):
return hash_code % self.array_size
def ass... | class Hashmap:
def __init__(self, size):
self.array_size = size
self.array = [None] * size
def hash(self, key, count_collisions=0):
return sum(key.encode()) + count_collisions
def compressor(self, hash_code):
return hash_code % self.array_size
def assign(self, key, va... |
def solution(n):
n = str(n)
if len(n) % 2 != 0: return False
n = list(n)
a,b = n[:len(n)//2], n[len(n)//2:]
a,b = list(map(int, a)), list(map(int, b))
return sum(a) == sum(b)
| def solution(n):
n = str(n)
if len(n) % 2 != 0:
return False
n = list(n)
(a, b) = (n[:len(n) // 2], n[len(n) // 2:])
(a, b) = (list(map(int, a)), list(map(int, b)))
return sum(a) == sum(b) |
def main():
while True:
userinput = input("Write something (quit ends): ")
if(userinput == "quit"):
break
else:
tester(userinput)
def tester(givenstring="Too short"):
if(len(givenstring) < 10):
print("Too short")
else:
print(givenstring)
if ... | def main():
while True:
userinput = input('Write something (quit ends): ')
if userinput == 'quit':
break
else:
tester(userinput)
def tester(givenstring='Too short'):
if len(givenstring) < 10:
print('Too short')
else:
print(givenstring)
if __na... |
df = pd.read_csv(DATA, delimiter=';')
df[['EV1', 'EV2', 'EV3']] = df['Participants'].str.split(', ', expand=True)
df['Duration'] = pd.to_timedelta(df['Duration'])
result = (pd.concat([
df[['EV1', 'Duration']].rename(columns={'EV1': 'Astronaut'}),
df[['EV2', 'Duration']].rename(columns={'EV2': 'A... | df = pd.read_csv(DATA, delimiter=';')
df[['EV1', 'EV2', 'EV3']] = df['Participants'].str.split(', ', expand=True)
df['Duration'] = pd.to_timedelta(df['Duration'])
result = pd.concat([df[['EV1', 'Duration']].rename(columns={'EV1': 'Astronaut'}), df[['EV2', 'Duration']].rename(columns={'EV2': 'Astronaut'}), df[['EV3', 'D... |
class Solution:
def hasValidPath(self, grid):
def dfs(x, y, d):
if x == m or y == n:
return True
if grid[x][y] == 1:
if d == 1:
return dfs(x, y + 1, d)
elif d == 3:
return dfs(x, y - 1, d)
... | class Solution:
def has_valid_path(self, grid):
def dfs(x, y, d):
if x == m or y == n:
return True
if grid[x][y] == 1:
if d == 1:
return dfs(x, y + 1, d)
elif d == 3:
return dfs(x, y - 1, d)
... |
class fabrica:
def __init__(self, tiempo, nombre, ruedas):
self.tiempo = tiempo
self.nombre = nombre
self.ruedas = ruedas
print("se creo el auto", self.nombre)
def __str__(self):
return "{}({})".format(self.nombre, self.tiempo)
class listado: #
autos = []# lista q... | class Fabrica:
def __init__(self, tiempo, nombre, ruedas):
self.tiempo = tiempo
self.nombre = nombre
self.ruedas = ruedas
print('se creo el auto', self.nombre)
def __str__(self):
return '{}({})'.format(self.nombre, self.tiempo)
class Listado:
autos = []
def __... |
n1 = int(input('digite um valor: '))
n2 = int(input('digite outro valor: '))
s = n1 + n2
m = n1 * n2
p = n1 ** n2
print(f'a soma vale {s}, a mult vale {m}, e a potencia vale {p}', end=', ')
print('testando end')
| n1 = int(input('digite um valor: '))
n2 = int(input('digite outro valor: '))
s = n1 + n2
m = n1 * n2
p = n1 ** n2
print(f'a soma vale {s}, a mult vale {m}, e a potencia vale {p}', end=', ')
print('testando end') |
file_name = 'data/PacMan.png'
reader = itk.ImageFileReader.New(FileName=file_name)
smoother = itk.RecursiveGaussianImageFilter.New(Input=reader.GetOutput())
smoother.SetSigma(5.0)
smoother.Update()
view(smoother.GetOutput(), ui_collapsed=True)
| file_name = 'data/PacMan.png'
reader = itk.ImageFileReader.New(FileName=file_name)
smoother = itk.RecursiveGaussianImageFilter.New(Input=reader.GetOutput())
smoother.SetSigma(5.0)
smoother.Update()
view(smoother.GetOutput(), ui_collapsed=True) |
# -*- coding: utf-8 -*-
__all__ = ['Microblog', 'MICROBLOG_SESSION_PROFILE']
MICROBLOG_SESSION_PROFILE = 'mic_profile_session'
class Microblog(object):
def __init__(self):
self.profile = None
| __all__ = ['Microblog', 'MICROBLOG_SESSION_PROFILE']
microblog_session_profile = 'mic_profile_session'
class Microblog(object):
def __init__(self):
self.profile = None |
# https://leetcode.com/problems/binary-tree-postorder-traversal/
# 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:
# DFS
def postorderTraversal(self, root... | class Solution:
def postorder_traversal(self, root: TreeNode) -> List[int]:
(stack, res) = ([root], [])
while stack:
node = stack.pop()
if node:
res.append(node.val)
stack.append(node.left)
stack.append(node.right)
retu... |
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
def push(head, data):
node = Node(data)
node.next = head
return node
def build_one_two_three():
return push(push(Node(3), 2), 1)
| class Node(object):
def __init__(self, data):
self.data = data
self.next = None
def push(head, data):
node = node(data)
node.next = head
return node
def build_one_two_three():
return push(push(node(3), 2), 1) |
string = "a" * ITERATIONS
# ---
for char in string:
pass
| string = 'a' * ITERATIONS
for char in string:
pass |
# Tool Types
BRACKEN = 'bracken_abundance_estimation'
KRAKEN = 'kraken_taxonomy_profiling'
KRAKENHLL = 'krakenhll_taxonomy_profiling'
METAPHLAN2 = 'metaphlan2_taxonomy_profiling'
HMP_SITES = 'hmp_site_dists'
MICROBE_CENSUS = 'microbe_census'
AMR_GENES = 'align_to_amr_genes'
RESISTOME_AMRS = 'resistome_amrs'
READ_CLASS_... | bracken = 'bracken_abundance_estimation'
kraken = 'kraken_taxonomy_profiling'
krakenhll = 'krakenhll_taxonomy_profiling'
metaphlan2 = 'metaphlan2_taxonomy_profiling'
hmp_sites = 'hmp_site_dists'
microbe_census = 'microbe_census'
amr_genes = 'align_to_amr_genes'
resistome_amrs = 'resistome_amrs'
read_class_props = 'read... |
def predict(x_test, model):
# predict
y_pred = model.predict(x_test)
y_pred_scores = model.predict_proba(x_test)
return y_pred, y_pred_scores | def predict(x_test, model):
y_pred = model.predict(x_test)
y_pred_scores = model.predict_proba(x_test)
return (y_pred, y_pred_scores) |
r = [int (r) for r in input().split()]
renas = ['Rudolph','Dasher','Dancer','Prancer','Vixen','Comet','Cupid','Donner','Blitzen']
b = 0
for s in range(len(r)):
b = b + r[s]
resto = b%9
for t in range(0,9):
if resto == t:
print(renas[t])
| r = [int(r) for r in input().split()]
renas = ['Rudolph', 'Dasher', 'Dancer', 'Prancer', 'Vixen', 'Comet', 'Cupid', 'Donner', 'Blitzen']
b = 0
for s in range(len(r)):
b = b + r[s]
resto = b % 9
for t in range(0, 9):
if resto == t:
print(renas[t]) |
# This exercise should be done in Jupyter and in the interpreter
# Print your name
print('My name is Anne.')
| print('My name is Anne.') |
n = input()
while len(n) > 1:
x = 1
for c in n:
if c != '0': x *= int(c)
n = str(x)
print(n) | n = input()
while len(n) > 1:
x = 1
for c in n:
if c != '0':
x *= int(c)
n = str(x)
print(n) |
# from the paper `using cython to speedup numerical python programs'
#pythran export timeloop(float, float, float, float, float, float list list, float list list, float list list)
#pythran export timeloop(float, float, float, float, float, int list list, int list list, int list list)
#bench A=[list(range(70)) for i in ... | def timeloop(t, t_stop, dt, dx, dy, u, um, k):
while t <= t_stop:
t += dt
new_u = calculate_u(dt, dx, dy, u, um, k)
um = u
u = new_u
return u
def calculate_u(dt, dx, dy, u, um, k):
up = [[0.0] * len(u[0]) for i in range(len(u))]
'omp parallel for'
for i in range(1, l... |
#Python task list example
taskList = []
def commander():
print("\na to add, s to show list, q to quit")
commandOrder = input("Command --> ")
if commandOrder == "a":
addTasks()
if commandOrder == "s":
printTasklist()
if commandOrder == "q":
print("Bye Bye Friend....")
... | task_list = []
def commander():
print('\na to add, s to show list, q to quit')
command_order = input('Command --> ')
if commandOrder == 'a':
add_tasks()
if commandOrder == 's':
print_tasklist()
if commandOrder == 'q':
print('Bye Bye Friend....')
def add_tasks():
print('... |
class C:
def m1(self):
pass
# <editor-fold desc="Description">
def m2(self):
pass
def m3(self):
pass
# </editor-fold> | class C:
def m1(self):
pass
def m2(self):
pass
def m3(self):
pass |
'''
Created on Aug 14, 2016
@author: rafacarv
'''
| """
Created on Aug 14, 2016
@author: rafacarv
""" |
class CBWGroup(object):
def __init__(self,
id="",
name="",
created_at="",
updated_at=""):
self.group_id = id
self.name = name
self.created_at = created_at
self.updated_at = updated_at
| class Cbwgroup(object):
def __init__(self, id='', name='', created_at='', updated_at=''):
self.group_id = id
self.name = name
self.created_at = created_at
self.updated_at = updated_at |
def print_board(data, board):
snake_index = 0
for snake in board['snakes']:
if (snake['id'] == data['you']['id']):
break
snake_index += 1
print("My snake: " + str(snake_index))
for i in range(board['height'] - 1, -1, -1):
for j in range(0, board['wid... | def print_board(data, board):
snake_index = 0
for snake in board['snakes']:
if snake['id'] == data['you']['id']:
break
snake_index += 1
print('My snake: ' + str(snake_index))
for i in range(board['height'] - 1, -1, -1):
for j in range(0, board['width'], 1):
... |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace:
class Value(object):
NONE = 0
boolean = 1
i8 = 2
u8 = 3
i16 = 4
u16 = 5
i32 = 6
u32 = 7
i64 = 8
u64 = 9
f32 = 10
f64 = 11
str = 12
str_list = 13
int32_list = 14
float_list... | class Value(object):
none = 0
boolean = 1
i8 = 2
u8 = 3
i16 = 4
u16 = 5
i32 = 6
u32 = 7
i64 = 8
u64 = 9
f32 = 10
f64 = 11
str = 12
str_list = 13
int32_list = 14
float_list = 15
bin = 16 |
l = [1,2,3]
assert 1 in l
assert 5 not in l
d = {1:2}
assert 1 in d
assert 2 not in d
d[2] = d
assert 2 in d
print("ok")
| l = [1, 2, 3]
assert 1 in l
assert 5 not in l
d = {1: 2}
assert 1 in d
assert 2 not in d
d[2] = d
assert 2 in d
print('ok') |
def encode(message, rails):
period = 2 * rails - 2
rows = [[] for _ in range(rails)]
for i, c in enumerate(message):
rows[min(i % period, period - i % period)].append(c)
return ''.join(''.join(row) for row in rows)
def decode(encoded_message, rails):
period = 2 * rails - 2
rows_size ... | def encode(message, rails):
period = 2 * rails - 2
rows = [[] for _ in range(rails)]
for (i, c) in enumerate(message):
rows[min(i % period, period - i % period)].append(c)
return ''.join((''.join(row) for row in rows))
def decode(encoded_message, rails):
period = 2 * rails - 2
rows_size... |
__author__ = 'Kalyan'
notes = '''
1. Read instructions for each function carefully.
2. Feel free to create new functions if needed. Give good names!
3. Use builtins and datatypes that we have seen so far.
4. If something about the function spec is not clear, use the corresponding test
for clarification.
5. ... | __author__ = 'Kalyan'
notes = '\n1. Read instructions for each function carefully.\n2. Feel free to create new functions if needed. Give good names!\n3. Use builtins and datatypes that we have seen so far.\n4. If something about the function spec is not clear, use the corresponding test\n for clarification.\n5. Many ... |
a1 = b'\x02'
b1 = 'AB'
c1 = 'EF'
c2 = None
d1 = b'\x03'
bb = a1 + bytes(b1.encode()) + bytes(c1.encode()) + d1
bb2 = a1 + bytes(b1.encode()) + bytes(c2.encode()) + d1
print(type(bb), bb) | a1 = b'\x02'
b1 = 'AB'
c1 = 'EF'
c2 = None
d1 = b'\x03'
bb = a1 + bytes(b1.encode()) + bytes(c1.encode()) + d1
bb2 = a1 + bytes(b1.encode()) + bytes(c2.encode()) + d1
print(type(bb), bb) |
class Solution:
def reverseBits(self, n: int) -> int:
# we can take the last bit of "n" by doing "n % 2"
# and shift the "n" to the right
# then we paste the last bit to the first bit of "res"
# by using `|` operation
# Take 0101 as an example:
# 00... | class Solution:
def reverse_bits(self, n: int) -> int:
res = 0
for i in range(32):
bit = n % 2
n >>= 1
res |= bit << 31 - i
return res |
"Create maps with OpenStreetMap layers in a minute and embed them in your site."
VERSION = (1, 0, 0)
__author__ = 'Yohan Boniface'
__contact__ = "ybon@openstreetmap.fr"
__homepage__ = "https://github.com/umap-project/umap"
__version__ = ".".join(map(str, VERSION))
| """Create maps with OpenStreetMap layers in a minute and embed them in your site."""
version = (1, 0, 0)
__author__ = 'Yohan Boniface'
__contact__ = 'ybon@openstreetmap.fr'
__homepage__ = 'https://github.com/umap-project/umap'
__version__ = '.'.join(map(str, VERSION)) |
#!/user/bin/env python
'''structureToPolymerSequences.py:
This mapper maps a structure to it's polypeptides, polynucleotide chain sequences.
For a multi-model structure, only the first model is considered.
'''
__author__ = "Mars (Shih-Cheng) Huang"
__maintainer__ = "Mars (Shih-Cheng) Huang"
__email__ = "marshuang80@g... | """structureToPolymerSequences.py:
This mapper maps a structure to it's polypeptides, polynucleotide chain sequences.
For a multi-model structure, only the first model is considered.
"""
__author__ = 'Mars (Shih-Cheng) Huang'
__maintainer__ = 'Mars (Shih-Cheng) Huang'
__email__ = 'marshuang80@gmail.com'
__version__ =... |
class ChooserStatistician:
def __init__(self, m_iterations):
self.m_iterations = m_iterations
@property
def m_iterations(self):
return self._m_iterations
@m_iterations.setter
def m_iterations(self, m_iterations):
if not m_iterations > 1:
raise ValueError("Number... | class Chooserstatistician:
def __init__(self, m_iterations):
self.m_iterations = m_iterations
@property
def m_iterations(self):
return self._m_iterations
@m_iterations.setter
def m_iterations(self, m_iterations):
if not m_iterations > 1:
raise value_error('Numb... |
# a = '42'
# print(type(a))
# a = int(a)
# print(type(a))
# b = 'a2'
# print(type(b))
# b = int(b) ERROR ->>>> this cause error!!! because of 'a' in 'a2'
# c = 3.141592
# print(type(c))
# c = int(c)
# print(c, type(c))
d = '3.141592'
print(type(d))
d = int(float(d))
print(d, type(d))
| d = '3.141592'
print(type(d))
d = int(float(d))
print(d, type(d)) |
class MultiStack:
def __init__(self, stacksize):
self.numstacks = 3
self.array = [0] * (stacksize * self.numstacks)
self.sizes = [0] * self.numstacks
self.stacksize = stacksize
def Push(self, item, stacknum):
if self.IsFull(stacknum):
raise Exception("Stack i... | class Multistack:
def __init__(self, stacksize):
self.numstacks = 3
self.array = [0] * (stacksize * self.numstacks)
self.sizes = [0] * self.numstacks
self.stacksize = stacksize
def push(self, item, stacknum):
if self.IsFull(stacknum):
raise exception('Stack ... |
# Confidence Interval using Stats Model Summary
thresh = 0.05
intervals = results.conf_int(alpha=thresh)
# Renaming column names
first_col = str(thresh/2*100)+"%"
second_col = str((1-thresh/2)*100)+"%"
intervals = intervals.rename(columns={0:first_col,1:second_col})
display(intervals) | thresh = 0.05
intervals = results.conf_int(alpha=thresh)
first_col = str(thresh / 2 * 100) + '%'
second_col = str((1 - thresh / 2) * 100) + '%'
intervals = intervals.rename(columns={0: first_col, 1: second_col})
display(intervals) |
def loadfile(name):
lines = []
f = open(name, "r")
for x in f:
if x.endswith('\n'):
x = x[:-1]
line = []
for character in x:
line.append(int(character))
lines.append(line)
return lines
def add1ToAll(lines):
for i in range (0, len(lines)):
... | def loadfile(name):
lines = []
f = open(name, 'r')
for x in f:
if x.endswith('\n'):
x = x[:-1]
line = []
for character in x:
line.append(int(character))
lines.append(line)
return lines
def add1_to_all(lines):
for i in range(0, len(lines)):
... |
class BuildingSpecification(object):
def __init__(self,building_type, display_string, other_buildings_available, codes_available):
self.building_type = building_type
self.display_string = display_string
self.other_buildings_available = other_buildings_available # list of building names
... | class Buildingspecification(object):
def __init__(self, building_type, display_string, other_buildings_available, codes_available):
self.building_type = building_type
self.display_string = display_string
self.other_buildings_available = other_buildings_available
self.codes_available... |
################################################################################
level_number = 6
dungeon_name = 'Catacombs'
wall_style = 'Catacombs'
monster_difficulty = 3
goes_down = True
entry_position = (0, 0)
phase_door = False
level_teleport = [
(4, True),
(5, True),
(6, False),
]
stairs_previou... | level_number = 6
dungeon_name = 'Catacombs'
wall_style = 'Catacombs'
monster_difficulty = 3
goes_down = True
entry_position = (0, 0)
phase_door = False
level_teleport = [(4, True), (5, True), (6, False)]
stairs_previous = [(13, 11)]
stairs_next = []
portal_down = []
portal_up = []
teleports = [((0, 21), (10, 7)), ((21,... |
class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
d = [0] *(max(nums)+1)
for i in nums:
d[i] += i
prev,prever = 0,0
for i in d:
cur = max(prev,prever+i)
prever = prev
prev = cur
return max(cur,prever)
| class Solution:
def delete_and_earn(self, nums: List[int]) -> int:
d = [0] * (max(nums) + 1)
for i in nums:
d[i] += i
(prev, prever) = (0, 0)
for i in d:
cur = max(prev, prever + i)
prever = prev
prev = cur
return max(cur, prev... |
keywords = ['program', 'label', 'type', 'array', 'of', 'var', 'procedure'
,'function', 'begin', 'end', 'if', 'then', 'else', 'while', 'do'
, 'or', 'and', 'div', 'not']
symbols = ['.', ';', ',', '(', ')', ':', '=',
'<', '>', '+', '-', '*', '[', ':=', '..']
def ... | keywords = ['program', 'label', 'type', 'array', 'of', 'var', 'procedure', 'function', 'begin', 'end', 'if', 'then', 'else', 'while', 'do', 'or', 'and', 'div', 'not']
symbols = ['.', ';', ',', '(', ')', ':', '=', '<', '>', '+', '-', '*', '[', ':=', '..']
def get_tokens(code):
label = ''
tokens = []
for str... |
# Problem Link : https://codeforces.com/problemset/problem/339/A#
s = input()
nums = list(s[0:len(s):2])
nums.sort()
j = 0
for i in range(len(s)):
if i%2 == 0:
print(nums[j], end="")
j += 1
else:
print("+", end="")
| s = input()
nums = list(s[0:len(s):2])
nums.sort()
j = 0
for i in range(len(s)):
if i % 2 == 0:
print(nums[j], end='')
j += 1
else:
print('+', end='') |
#
# PySNMP MIB module CISCO-SNMPv2-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-SNMPv2-CAPABILITY
# Produced by pysmi-0.3.4 at Wed May 1 12:12:36 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, constraints_intersection, single_value_constraint, constraints_union) ... |
description = 'Asyn serial controllers in the SINQ AMOR.'
group='lowlevel'
pvprefix = 'SQ:AMOR:serial'
devices = dict(
serial1=device(
'nicos_ess.devices.epics.extensions.EpicsCommandReply',
epicstimeout=3.0,
description='Controller of the devices connected to serial 1',
commandpv... | description = 'Asyn serial controllers in the SINQ AMOR.'
group = 'lowlevel'
pvprefix = 'SQ:AMOR:serial'
devices = dict(serial1=device('nicos_ess.devices.epics.extensions.EpicsCommandReply', epicstimeout=3.0, description='Controller of the devices connected to serial 1', commandpv=pvprefix + '1.AOUT', replypv=pvprefix ... |
#!/usr/bin/python3
def NativeZeros(nRows, nCols):
return [range(nRows) for col in range(nCols)]
matrix = NativeZeros(4, 4)
print(matrix)
print(sum([sum(row) for row in matrix]))
| def native_zeros(nRows, nCols):
return [range(nRows) for col in range(nCols)]
matrix = native_zeros(4, 4)
print(matrix)
print(sum([sum(row) for row in matrix])) |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'chromium_code': 1,
},
'includes': [
'../build/win_precompile.gypi',
'../chrome/version.gypi',
'blacklist.gypi',
],
... | {'variables': {'chromium_code': 1}, 'includes': ['../build/win_precompile.gypi', '../chrome/version.gypi', 'blacklist.gypi'], 'targets': [{'target_name': 'chrome_elf', 'type': 'shared_library', 'include_dirs': ['..'], 'sources': ['chrome_elf.def', 'chrome_elf_main.cc', 'chrome_elf_main.h'], 'dependencies': ['blacklist'... |
elem = lambda value, next: {'value': value, 'next': next}
to_str = lambda head: '' if head is None \
else str(head['value']) + ' ' + to_str(head['next'])
values = elem(1, elem(2, elem(3, None)))
# print(to_str(values))
def make_powers(count):
powers = []
for i in range(count):
... | elem = lambda value, next: {'value': value, 'next': next}
to_str = lambda head: '' if head is None else str(head['value']) + ' ' + to_str(head['next'])
values = elem(1, elem(2, elem(3, None)))
def make_powers(count):
powers = []
for i in range(count):
powers.append((lambda p: lambda x: x ** p)(i))
... |
class Allergies(object):
def __init__(self, score):
self.score = [allergen for num, allergen in list(enumerate([
'eggs',
'peanuts',
'shellfish',
'strawberries',
'tomatoes',
'chocolate',
'pollen',
'cats'
... | class Allergies(object):
def __init__(self, score):
self.score = [allergen for (num, allergen) in list(enumerate(['eggs', 'peanuts', 'shellfish', 'strawberries', 'tomatoes', 'chocolate', 'pollen', 'cats'])) if 0 < score & 1 << num]
def is_allergic_to(self, item):
return item in self.score
... |
# 1. Sort the 'people' list of dictionaries alphabetically based on the
# 'name' key from each dictionary using the 'sorted' function and store
# the new list as 'sorted_by_name'
people = [
{'name': 'Kevin Bacon', 'age': 61},
{'name': 'Fred Ward', 'age': 77},
{'name': 'finn Carter', 'age': 59},
{'name... | people = [{'name': 'Kevin Bacon', 'age': 61}, {'name': 'Fred Ward', 'age': 77}, {'name': 'finn Carter', 'age': 59}, {'name': 'Ariana Richards', 'age': 40}, {'name': 'Vicotor Wong', 'age': 74}]
sorted_by_name = sorted(people, key=lambda d: d['name'].lower())
assert sorted_by_name == [{'name': 'Ariana Richards', 'age': 4... |
# Copyright 2017 Pedro M. Baeza <pedro.baeza@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Weights in the invoices analysis view",
"version": "13.0.1.0.0",
"author": "Tecnativa," "Odoo Community Association (OCA)",
"category": "Inventory, Logistics, Warehousi... | {'name': 'Weights in the invoices analysis view', 'version': '13.0.1.0.0', 'author': 'Tecnativa,Odoo Community Association (OCA)', 'category': 'Inventory, Logistics, Warehousing', 'development_status': 'Production/Stable', 'license': 'AGPL-3', 'website': 'https://www.github.com/account_reporting_weight', 'depends': ['s... |
# Theory: List
# In your programs, you often need to group several elements in
# order to process them as a single object. For this, you will need
# to use different collections. One of the most useful collections
# in Python is a list. It is one of the most important things in
# Python.
# 1. Creating and printing li... | dog_breeds = ['corgi', 'labrador', 'poodle', 'jack russel']
print(dog_breeds)
numbers = [1, 2, 3, 4, 5]
print(numbers)
list_out_of_string = list('danger!')
print(list_out_of_string)
multi_element_list = list('danger!')
print(multi_element_list)
singe_element_list = ['danger!']
print(singe_element_list)
empty_list_1 = l... |
# -*- python -*-
# This software was produced by NIST, an agency of the U.S. government,
# and by statute is not subject to copyright in the United States.
# Recipients of this software assume all responsibilities associated
# with its operation, modification and maintenance. However, to
# facilitate maintenance we as... | delay = 2000
period = 200
def set_delay(menuitem, milliseconds):
global delay
delay = milliseconds |
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
m = len(image)
n = len(image[0])
oldColor = image[sr][sc]
if oldColor == newColor:
return image
def dfs(r, c):
nonlocal image, new... | class Solution:
def flood_fill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
m = len(image)
n = len(image[0])
old_color = image[sr][sc]
if oldColor == newColor:
return image
def dfs(r, c):
nonlocal image, newColor... |
#### digonal sum
digonal=[[1,2,3,5],
[4,5,6,4],
[7,8,9,3]
]
def digonaldiffernce(arr):
SUM1=0
SUM2=0
j=0
for i in arr:
SUM1+=i[j]
SUM2+=i[(len(i)-1)-j]
j+=1
return abs(SUM1-SUM2)
print(digonaldiffernce(digonal))
| digonal = [[1, 2, 3, 5], [4, 5, 6, 4], [7, 8, 9, 3]]
def digonaldiffernce(arr):
sum1 = 0
sum2 = 0
j = 0
for i in arr:
sum1 += i[j]
sum2 += i[len(i) - 1 - j]
j += 1
return abs(SUM1 - SUM2)
print(digonaldiffernce(digonal)) |
class Main:
class featured:
it = {'css': '#content > div.row'}
products = {'css': it['css'] + ' .product-layout'}
names = {'css': products['css'] + ' .caption h4 a'}
| class Main:
class Featured:
it = {'css': '#content > div.row'}
products = {'css': it['css'] + ' .product-layout'}
names = {'css': products['css'] + ' .caption h4 a'} |
def foo(x):
print(x)
foo([x for x in range(10)])
| def foo(x):
print(x)
foo([x for x in range(10)]) |
def dogleg(value, units):
return_dict = {}
if units == 'deg/100ft':
return_dict['deg/100ft'] = value
return_dict['deg/30m'] = value * 0.9843004
elif units == 'deg/30m':
return_dict['deg/100ft'] = value * 1.01595
return_dict['deg/30m'] = value
return return_dict
def axia... | def dogleg(value, units):
return_dict = {}
if units == 'deg/100ft':
return_dict['deg/100ft'] = value
return_dict['deg/30m'] = value * 0.9843004
elif units == 'deg/30m':
return_dict['deg/100ft'] = value * 1.01595
return_dict['deg/30m'] = value
return return_dict
def axial... |
DYNAMIC_API_URL = 'https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/space_history'
GET_DYNAMIC_DETAIL_API_URL = 'https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/get_dynamic_detail'
USER_INFO_API_URL = 'https://api.bilibili.com/x/space/acc/info'
DYNAMIC_URL = 'https://t.bilibili.com/'
| dynamic_api_url = 'https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/space_history'
get_dynamic_detail_api_url = 'https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/get_dynamic_detail'
user_info_api_url = 'https://api.bilibili.com/x/space/acc/info'
dynamic_url = 'https://t.bilibili.com/' |
def readDiary():
day = input("What day do you want to read? ")
file = open(day, "r")
line = file.read()
print(line)
file.close()
def writeDiary():
day = input("What day is your diary for? ")
file = open(day, "w")
line = input("Enter entry: ")
file.write(line)
file.close()
... | def read_diary():
day = input('What day do you want to read? ')
file = open(day, 'r')
line = file.read()
print(line)
file.close()
def write_diary():
day = input('What day is your diary for? ')
file = open(day, 'w')
line = input('Enter entry: ')
file.write(line)
file.close()
oper... |
T = int(input())
for c in range(T):
N = int(input())
sum = N * (N + 1) // 2
sqs = N * (N + 1) * (2 * N + 1) // 6
d = sum * sum - sqs
print(abs(d))
| t = int(input())
for c in range(T):
n = int(input())
sum = N * (N + 1) // 2
sqs = N * (N + 1) * (2 * N + 1) // 6
d = sum * sum - sqs
print(abs(d)) |
# @Vipin Chaudhari
host='192.168.1.15'
meetup_rsvp_stream_api_url = "http://stream.meetup.com/2/rsvps"
# Kafka info
kafka_topic = "meetup-rsvp-topic"
kafka_server = host+':9092'
# MySQL info
mysql_user = "python"
mysql_pwd = "python"
mysql_db = "meetup"
mysql_driver = "com.mysql.cj.jdbc.Driver"
mys... | host = '192.168.1.15'
meetup_rsvp_stream_api_url = 'http://stream.meetup.com/2/rsvps'
kafka_topic = 'meetup-rsvp-topic'
kafka_server = host + ':9092'
mysql_user = 'python'
mysql_pwd = 'python'
mysql_db = 'meetup'
mysql_driver = 'com.mysql.cj.jdbc.Driver'
mysql_tbl = 'MeetupRSVP'
mysql_jdbc_url = 'jdbc:mysql://' + host ... |
class Layer:
def __init__(self):
self.input = None
self.output = None
def forward_propagation(self,input):
raise NotImplementedError
def backward_propagation(self, output_error,learning_rate):
raise NotImplementedError | class Layer:
def __init__(self):
self.input = None
self.output = None
def forward_propagation(self, input):
raise NotImplementedError
def backward_propagation(self, output_error, learning_rate):
raise NotImplementedError |
def to_fp_name(path, prefix='fp'):
if path == 'stdout':
return 'stdout'
if path == 'stderr':
return 'stderr'
if path == 'stdin':
return 'stdin'
# For now, just construct a fd variable name by taking objectionable chars out of the path
cleaned = path.replace('.', '_').replac... | def to_fp_name(path, prefix='fp'):
if path == 'stdout':
return 'stdout'
if path == 'stderr':
return 'stderr'
if path == 'stdin':
return 'stdin'
cleaned = path.replace('.', '_').replace('/', '_').replace('-', '_').replace('+', 'x')
return '{}_{}'.format(prefix, cleaned)
def d... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
if root is None:
return None
left = self.lo... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def lowest_common_ancestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
if root is None:
return None
left = self.lowestCommonAncestor(root... |
class MarginGetError(Exception):
pass
class PositionGetError(Exception):
pass
class TickGetError(Exception):
pass
class TradeGetError(Exception):
pass
class BarGetError(Exception):
pass
class FillGetError(Exception):
pass
class OrderPostError(Exception):
pass
class OrderGetErro... | class Margingeterror(Exception):
pass
class Positiongeterror(Exception):
pass
class Tickgeterror(Exception):
pass
class Tradegeterror(Exception):
pass
class Bargeterror(Exception):
pass
class Fillgeterror(Exception):
pass
class Orderposterror(Exception):
pass
class Ordergeterror(Excep... |
class MyStuff(object):
def __init__(self):
self.stark = "I am classy Iron Man."
def groot(self):
print("I am classy groot!")
thing = MyStuff()
thing.groot()
print(thing.stark)
| class Mystuff(object):
def __init__(self):
self.stark = 'I am classy Iron Man.'
def groot(self):
print('I am classy groot!')
thing = my_stuff()
thing.groot()
print(thing.stark) |
expected_output = {
"GigabitEthernet0/1/1": {
"service_policy": {
"output": {
"policy_name": {
"shape-out": {
"class_map": {
"class-default": {
"bytes": 0,
... | expected_output = {'GigabitEthernet0/1/1': {'service_policy': {'output': {'policy_name': {'shape-out': {'class_map': {'class-default': {'bytes': 0, 'bytes_output': 0, 'match': ['any'], 'match_evaluation': 'match-any', 'no_buffer_drops': 0, 'packets': 0, 'pkts_output': 0, 'queue_depth': 0, 'queue_limit_packets': '64', '... |
TOKEN = '668308467:AAETX4hdMRnVvYVBP4bK5WDgvL8zIXoHq5g'
main_url = 'https://schedule.vekclub.com/api/v1/'
list_group = 'handbook/groups-by-institution?institutionId=4'
shedule_group ='schedule/group?groupId=' | token = '668308467:AAETX4hdMRnVvYVBP4bK5WDgvL8zIXoHq5g'
main_url = 'https://schedule.vekclub.com/api/v1/'
list_group = 'handbook/groups-by-institution?institutionId=4'
shedule_group = 'schedule/group?groupId=' |
# SOME BASIC CONSTANT AND MASS FUNCTION OF POISSION DISTRIBUTION
# e is Euler's number (e = 2.71828...)
# f(k, lambda) = lambda^k * e^-lambda / k!
# Task:
# A random variable, X , follows Poisson distribution with mean of 2.5. Find the probability with which the random variable X is equal to 5.
# Define functions
d... | def factorial(n):
if n == 1 or n == 0:
return 1
if n > 1:
return factorial(n - 1) * n
lam = float(input())
k = float(input())
e = 2.71828
result = lam ** k * e ** (-lam) / factorial(k)
print(round(result, 3)) |
s1 = {'ab', 3,4, (5,6)}
s2 = {'ab', 7, (7,6)}
print(s1-s2)
# Returns all the items in both s1 and s2
print(s1.intersection(s2))
# Returns all the items in a set
print(s1.union(s2))
print('ab' in s1) # Testing for a member's presence in the set
# Lopping through elements in a set
for element in s1:
print(elemen... | s1 = {'ab', 3, 4, (5, 6)}
s2 = {'ab', 7, (7, 6)}
print(s1 - s2)
print(s1.intersection(s2))
print(s1.union(s2))
print('ab' in s1)
for element in s1:
print(element)
s1.add(frozenset(s2))
print(s1)
fs1 = frozenset(s1)
fs2 = frozenset(s2)
{fs1: 'fs1', fs2: 'fs2'} |
# -*- coding: utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def tree2str(self, t):
if t is None:
return ''
result = [str(t.val)]
if t.left is not None or t.right is not None:
... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def tree2str(self, t):
if t is None:
return ''
result = [str(t.val)]
if t.left is not None or t.right is not None:
result.extend(['(',... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Simulation : https://framagit.org/kepon/PvMonit/issues/8
# ~ print("PID:0x203");
# ~ print("FW:146");
# ~ print("SER#:HQ18523ZGZI");
# ~ print("V:25260");
# ~ print("I:100");
# ~ print("VPV:28600");
# ~ print("PPV:6");
# ~ print("CS:3");
# ~ print("MPPT:2");
# ~ print("OR:0... | print('AR:0')
print('Alarm:OFF')
print('BMV:700')
print('CE:-36228')
print('FW: 0308')
print('H1:-102738')
print('H10:121')
print('H11:0')
print('H12:0')
print('H17:59983')
print('H18:70519')
print('H2:-36228')
print('H3:-102738')
print('H4:1')
print('H5:0')
print('H6:-24205923')
print('H7:21238')
print('H8:29442')
pri... |
def check_prime(n):
f = 0
for i in range (2, n//2 +1):
if n%i==0 :
f= 1
break
return f
def min_range(d):
a = (10**(d-1))
return a
def max_range(d):
b = (10**d)
return b
d=int(input("Enter d"))
twin_prime_list = []
for i in range ( min_range(... | def check_prime(n):
f = 0
for i in range(2, n // 2 + 1):
if n % i == 0:
f = 1
break
return f
def min_range(d):
a = 10 ** (d - 1)
return a
def max_range(d):
b = 10 ** d
return b
d = int(input('Enter d'))
twin_prime_list = []
for i in range(min_range(d), max_r... |
# 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
# DFS
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
self.ans = []
self.dfs(root, 0)
... | class Treenode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def level_order(self, root: TreeNode) -> List[List[int]]:
self.ans = []
self.dfs(root, 0)
return self.ans
def dfs(self, nod... |
numbers = (input("enter the value of a number"))
def divisors(numbers):
array = []
for item in range(1, numbers):
if(numbers % item == 0):
print("divisors items", item)
array.append(item)
print(array)
# print("all items",item)
divisors(numbers)
| numbers = input('enter the value of a number')
def divisors(numbers):
array = []
for item in range(1, numbers):
if numbers % item == 0:
print('divisors items', item)
array.append(item)
print(array)
divisors(numbers) |
# Space : O(n)
# Time : O(n**2)
class Solution:
def jump(self, nums: List[int]) -> int:
n = len(nums)
dp = [10**5] * n
dp[0] = 0
if n == 1:
return 0
for i in range(n):
for j in range(nums[i]):
dp[j+i+1] = min(dp[j+i+... | class Solution:
def jump(self, nums: List[int]) -> int:
n = len(nums)
dp = [10 ** 5] * n
dp[0] = 0
if n == 1:
return 0
for i in range(n):
for j in range(nums[i]):
dp[j + i + 1] = min(dp[j + i + 1], dp[i] + 1)
if j + i +... |
while True:
a = input()
if int(a) == 42:
break;
print(int(a))
| while True:
a = input()
if int(a) == 42:
break
print(int(a)) |
__version__ = '0.0.7'
def get_version():
return __version__
| __version__ = '0.0.7'
def get_version():
return __version__ |
#Question:1
# Initializing matrix
matrix = []
# Taking input from user of rows and column
row = int(input("Enter the number of rows:"))
column = int(input("Enter the number of columns:"))
print("Enter the elements row wise:")
# Getting elements of matrix from user
for i in range(row):
a =[]
... | matrix = []
row = int(input('Enter the number of rows:'))
column = int(input('Enter the number of columns:'))
print('Enter the elements row wise:')
for i in range(row):
a = []
for j in range(column):
a.append(int(input()))
matrix.append(a)
print()
print('Entered Matrix is: ')
for i in range(row):
... |
devices = \
{
# -------------------------------------------------------------------------
# NXP ARM7TDMI devices Series LPC21xx, LPC22xx, LPC23xx, LPC24xx
"lpc2129":
{
"defines": ["__ARM_LPC2000__"],
"linkerscript": "arm7/lpc/linker/lpc2129.ld",
"size": { "flash": 262144, "ram": 16384 },
},
"lpc2368":
{... | devices = {'lpc2129': {'defines': ['__ARM_LPC2000__'], 'linkerscript': 'arm7/lpc/linker/lpc2129.ld', 'size': {'flash': 262144, 'ram': 16384}}, 'lpc2368': {'defines': ['__ARM_LPC2000__', '__ARM_LPC23_24__'], 'linkerscript': 'arm7/lpc/linker/lpc2368.ld', 'size': {'flash': 524288, 'ram': 32768}}, 'lpc2468': {'defines': ['... |
WALK_UP = 4
WALK_DOWN = 3
WALK_RIGHT = 2
WALK_LEFT = 1
NO_OP = 0
SHOOT = 5
WALK_ACTIONS = [WALK_UP, WALK_DOWN, WALK_RIGHT, WALK_LEFT]
ACTIONS = [NO_OP, WALK_LEFT, WALK_RIGHT, WALK_DOWN, WALK_UP, SHOOT]
| walk_up = 4
walk_down = 3
walk_right = 2
walk_left = 1
no_op = 0
shoot = 5
walk_actions = [WALK_UP, WALK_DOWN, WALK_RIGHT, WALK_LEFT]
actions = [NO_OP, WALK_LEFT, WALK_RIGHT, WALK_DOWN, WALK_UP, SHOOT] |
# Day Six: Lanternfish
file = open("input/06.txt").readlines()
ages = []
for num in file[0].split(","):
ages.append(int(num))
for day in range(80):
for i, fish in enumerate(ages):
if fish == 0:
ages[i] = 6
ages.append(9)
else:
ages[i] = fish-1
print(len(age... | file = open('input/06.txt').readlines()
ages = []
for num in file[0].split(','):
ages.append(int(num))
for day in range(80):
for (i, fish) in enumerate(ages):
if fish == 0:
ages[i] = 6
ages.append(9)
else:
ages[i] = fish - 1
print(len(ages))
ages = [0, 0, 0, 0... |
#Horas-minutos e Segundos
valor = int(input())
horas = 0
minutos = 0
segundos = 0
valorA = valor
contador = segundos
while(contador <= valorA):
if contador > 0:
segundos += 1
if segundos >= 60:
minutos += 1
segundos = 0
if minutos >= 60:
horas += 1
minutos = 0
c... | valor = int(input())
horas = 0
minutos = 0
segundos = 0
valor_a = valor
contador = segundos
while contador <= valorA:
if contador > 0:
segundos += 1
if segundos >= 60:
minutos += 1
segundos = 0
if minutos >= 60:
horas += 1
minutos = 0
contador += 1
print('{}:{}:{}... |
#!/usr/bin/env python
# Author: Omid Mashayekhi <omidm@stanford.edu>
# ssh -i ~/.ssh/omidm-sing-key-pair-us-west-2.pem -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no ubuntu@<ip>
# US West (Northern California) Region
# EC2_LOCATION = 'us-west-1'
# NIMBUS_AMI = 'ami-50201815'
# UBUNTU_AMI = 'ami-660c3023... | ec2_location = 'us-west-2'
ubuntu_ami = 'ami-fa9cf1ca'
nimbus_ami = 'ami-4f5c392f'
controller_instance_type = 'c3.4xlarge'
worker_instance_type = 'c3.2xlarge'
placement = 'us-west-2a'
placement_group = 'nimbus-cluster'
security_group = 'nimbus_sg_uswest2'
key_name = 'sing-key-pair-us-west-2'
private_key = '/home/omidm/... |
# Copyright: 2006 Marien Zwart <marienz@gentoo.org>
# License: BSD/GPL2
#base class
__all__ = ("PackageError", "InvalidPackageName", "MetadataException", "InvalidDependency",
"ChksumBase", "MissingChksum", "ParseChksumError")
class PackageError(ValueError):
pass
class InvalidPackageName(PackageError):
p... | __all__ = ('PackageError', 'InvalidPackageName', 'MetadataException', 'InvalidDependency', 'ChksumBase', 'MissingChksum', 'ParseChksumError')
class Packageerror(ValueError):
pass
class Invalidpackagename(PackageError):
pass
class Metadataexception(PackageError):
def __init__(self, pkg, attr, error):
... |
#
# PySNMP MIB module CISCO-ENTITY-ASSET-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ENTITY-ASSET-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:56:50 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, constraints_union, value_range_constraint, single_value_constraint) ... |
def egcd(a, b):
if a==0:
return b, 0, 1
else:
gcd, x, y = egcd(b%a, a)
return gcd, y-(b//a)*x, x
if __name__ == '__main__':
a = int(input('Enter a: '))
b = int(input('Enter b: '))
gcd, x, y = egcd(a, b)
print(egcd(a,b))
if gcd!=1:
print("M.I. doe... | def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
(gcd, x, y) = egcd(b % a, a)
return (gcd, y - b // a * x, x)
if __name__ == '__main__':
a = int(input('Enter a: '))
b = int(input('Enter b: '))
(gcd, x, y) = egcd(a, b)
print(egcd(a, b))
if gcd != 1:
print("M.I... |
def app(environ, start_response):
s = ""
for i in environ['QUERY_STRING'].split("&"):
s = s + i + "\r\n"
start_response("200 OK", [
("Content-Type", "text/plain"),
("Content-Length", str(len(s)))
])
return [bytes(s, 'utf-8')]
| def app(environ, start_response):
s = ''
for i in environ['QUERY_STRING'].split('&'):
s = s + i + '\r\n'
start_response('200 OK', [('Content-Type', 'text/plain'), ('Content-Length', str(len(s)))])
return [bytes(s, 'utf-8')] |
deck_test = {
"kategori 1": ["kartuA", "kartuB", "kartuC", "kartuD"],
"kategori 2": ["kartuE", "kartuF", "kartuG", "kartuH"],
"kategori 3": ["kartuI", "kartuJ", "kartuK", "kartuL"],
# "kategori 4": ["kartuM", "kartuN", "kartuO", "kartuP"],
# "kategori 5": ["kartuQ", "kartuR", "kartuS", "kartuT"],
}
... | deck_test = {'kategori 1': ['kartuA', 'kartuB', 'kartuC', 'kartuD'], 'kategori 2': ['kartuE', 'kartuF', 'kartuG', 'kartuH'], 'kategori 3': ['kartuI', 'kartuJ', 'kartuK', 'kartuL']}
deck_used = {'nasi': ['nasi goreng', 'nasi uduk', 'nasi kuning', 'nasi kucing'], 'air': ['air putih', 'air santan', 'air susu', 'air tajin'... |
data = [int(input()), input()]
if 10 <= data[0] <= 15 and data[1] == "f":
print("YES")
else:
print("NO")
| data = [int(input()), input()]
if 10 <= data[0] <= 15 and data[1] == 'f':
print('YES')
else:
print('NO') |
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
res = cnt = 0
for i in nums:
if i:
cnt += 1
else:
if cnt:
res = max(res, cnt)
cnt = 0
return max(res, cnt) | class Solution:
def find_max_consecutive_ones(self, nums: List[int]) -> int:
res = cnt = 0
for i in nums:
if i:
cnt += 1
elif cnt:
res = max(res, cnt)
cnt = 0
return max(res, cnt) |
n = int(input())
while True:
s,z =0,n
while z>0:
s+=z%10
z//=10
if n%s==0:
print(n)
break
n+=1 | n = int(input())
while True:
(s, z) = (0, n)
while z > 0:
s += z % 10
z //= 10
if n % s == 0:
print(n)
break
n += 1 |
n = int(input())
k = n >> 1
ans = 1
for i in range(n-k+1,n+1):
ans *= i
for i in range(1,k+1):
ans //= i
print (ans)
| n = int(input())
k = n >> 1
ans = 1
for i in range(n - k + 1, n + 1):
ans *= i
for i in range(1, k + 1):
ans //= i
print(ans) |
#
# PySNMP MIB module DVMRP-STD-MIB-UNI (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DVMRP-STD-MIB-UNI
# Produced by pysmi-0.3.4 at Mon Apr 29 18:40:19 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_union, constraints_intersection, value_range_constraint) ... |
mesh_meshes_begin = 0
mesh_mp_score_a = 1
mesh_mp_score_b = 2
mesh_load_window = 3
mesh_checkbox_off = 4
mesh_checkbox_on = 5
mesh_white_plane = 6
mesh_white_dot = 7
mesh_player_dot = 8
mesh_flag_infantry = 9
mesh_flag_archers = 10
mesh_flag_cavalry = 11
mesh_inv_slot = 12
mesh_mp_ingame_menu = 13
mesh_mp_inventory_lef... | mesh_meshes_begin = 0
mesh_mp_score_a = 1
mesh_mp_score_b = 2
mesh_load_window = 3
mesh_checkbox_off = 4
mesh_checkbox_on = 5
mesh_white_plane = 6
mesh_white_dot = 7
mesh_player_dot = 8
mesh_flag_infantry = 9
mesh_flag_archers = 10
mesh_flag_cavalry = 11
mesh_inv_slot = 12
mesh_mp_ingame_menu = 13
mesh_mp_inventory_lef... |
# hanoi: int -> int
# calcula el numero de movimientos necesarios aara mover
# una torre de n discos de una vara a otra
# usando 3 varas y siguiendo las restricciones del puzzle hanoi
# ejemplo: hanoi(0) debe dar 0, hanoi(1) debe dar 1, hanoi(2) debe dar 3
def hanoi(n):
if n < 2:
return n
else:
... | def hanoi(n):
if n < 2:
return n
else:
return 1 + 2 * hanoi(n - 1)
assert hanoi(0) == 0
assert hanoi(1) == 1
assert hanoi(4) == 15
assert hanoi(5) == 31 |
date = input("enter the date: ").split()
dd = int(date[0])
yyyy = int(date[2])
mm = date[1]
l = []
l.append(yyyy)
l.append(mm)
l.append(dd)
t = tuple(l)
print(t)
| date = input('enter the date: ').split()
dd = int(date[0])
yyyy = int(date[2])
mm = date[1]
l = []
l.append(yyyy)
l.append(mm)
l.append(dd)
t = tuple(l)
print(t) |
a, b = input().split()
a = int(a)
b = int(b)
if a > b:
print(">")
elif a < b:
print("<")
else:
print("==")
| (a, b) = input().split()
a = int(a)
b = int(b)
if a > b:
print('>')
elif a < b:
print('<')
else:
print('==') |
n = int(input("Enter a number: "))
for i in range(1, n+1):
count = 0
for j in range(1, n+1):
if i%j==0:
count= count+1
if count==2:
print(i)
| n = int(input('Enter a number: '))
for i in range(1, n + 1):
count = 0
for j in range(1, n + 1):
if i % j == 0:
count = count + 1
if count == 2:
print(i) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.