content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# title here
print("="*100)
title = "Smart Calculator"
print('It is me, ', title)
print("-" * 100)
op = input("Please, enter operation:")
a = int(input('a = '))
b = int(input('b = '))
if op == '+':
print('a + b =', a + b)
elif op == '-':
print('a - b =', a - b)
elif op == '*':
print('a * b =', a * b)
elif... | print('=' * 100)
title = 'Smart Calculator'
print('It is me, ', title)
print('-' * 100)
op = input('Please, enter operation:')
a = int(input('a = '))
b = int(input('b = '))
if op == '+':
print('a + b =', a + b)
elif op == '-':
print('a - b =', a - b)
elif op == '*':
print('a * b =', a * b)
elif op == '/':
... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
input()
s1=set(map(int, ((input().split()))))
input()
s2=set(map(int, ((input().split()))))
set1 = s1.difference(s2)
set2 = s2.difference(s1)
set3 = set1.union(set2)
output = sorted(set3)
for i in output:
print(i) | input()
s1 = set(map(int, input().split()))
input()
s2 = set(map(int, input().split()))
set1 = s1.difference(s2)
set2 = s2.difference(s1)
set3 = set1.union(set2)
output = sorted(set3)
for i in output:
print(i) |
s = input()
L = []
z = s[0]
for i in s[1:]:
if z[-1] == i:
z += i
else:
L.append(z)
z = i
L.append(z)
ans = 1
for i in L:
c = 1
if i[0] == 'c':
c*=26
for j in range(1,len(i)):
c*=25
else:
c*=10
for j in range(1,len(i)):
... | s = input()
l = []
z = s[0]
for i in s[1:]:
if z[-1] == i:
z += i
else:
L.append(z)
z = i
L.append(z)
ans = 1
for i in L:
c = 1
if i[0] == 'c':
c *= 26
for j in range(1, len(i)):
c *= 25
else:
c *= 10
for j in range(1, len(i)):
... |
def encryptOne(char, rot):
return chr(ord(char) + rot)
def decryptOne(char, rot):
return chr(ord(char) - rot)
def encrypt(str, rot):
encoded = ""
for char in str:
encoded += encryptOne(char, rot)
return encoded
def decrypt(str, rot):
decoded = ""
for char in str:
de... | def encrypt_one(char, rot):
return chr(ord(char) + rot)
def decrypt_one(char, rot):
return chr(ord(char) - rot)
def encrypt(str, rot):
encoded = ''
for char in str:
encoded += encrypt_one(char, rot)
return encoded
def decrypt(str, rot):
decoded = ''
for char in str:
decode... |
dy_import_module_symbols("testchunk_helper")
SERVER_IP = getmyip()
SERVER_PORT = 60606
DATA_RECV = 1024
CHUNK_SIZE_SEND = 2**9 # 512KB chunk size
CHUNK_SIZE_RECV = 2**9
DATA_TO_SEND = "Hello" * 1024 * 1024 # 5MB of data
launch_test()
| dy_import_module_symbols('testchunk_helper')
server_ip = getmyip()
server_port = 60606
data_recv = 1024
chunk_size_send = 2 ** 9
chunk_size_recv = 2 ** 9
data_to_send = 'Hello' * 1024 * 1024
launch_test() |
def solution(distance, rocks, n):
rocks.sort(); rocks.append(distance)
left, right = 0, distance
while left <= right:
mid = (left + right) // 2
removeCnt = 0; current = 0; dist = distance
for i in range(len(rocks)):
if rocks[i] - current < mid:
removeCnt +... | def solution(distance, rocks, n):
rocks.sort()
rocks.append(distance)
(left, right) = (0, distance)
while left <= right:
mid = (left + right) // 2
remove_cnt = 0
current = 0
dist = distance
for i in range(len(rocks)):
if rocks[i] - current < mid:
... |
# 227. Basic Calculator II
# https://leetcode.com/problems/basic-calculator-ii/
MULTIPLICATION = "*"
SUBSTRACTION = "-"
DIVISION = "/"
SUM = "+"
OPERANDS = [MULTIPLICATION, SUM, SUBSTRACTION, DIVISION]
INVALID = OPERANDS + [" "]
class Solution:
def calculate(self, s: str) -> int:
n = len(s)
... | multiplication = '*'
substraction = '-'
division = '/'
sum = '+'
operands = [MULTIPLICATION, SUM, SUBSTRACTION, DIVISION]
invalid = OPERANDS + [' ']
class Solution:
def calculate(self, s: str) -> int:
n = len(s)
(left, i) = self.number_at(s, 0)
while i < n and s[i] in INVALID:
... |
class DottedDict(dict):
def __getattr__(self, attr):
try:
return self[attr]
except KeyError:
raise AttributeError("'{}'".format(attr))
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__ | class Dotteddict(dict):
def __getattr__(self, attr):
try:
return self[attr]
except KeyError:
raise attribute_error("'{}'".format(attr))
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__ |
class Paypal(object):
def __init__(self,
country_code,
email,
id,
payer,
username,
amount,
create_time,
update_time
):
self.contry_code = country_code
self.email = email
self.id = id
self.payer = payer
self.u... | class Paypal(object):
def __init__(self, country_code, email, id, payer, username, amount, create_time, update_time):
self.contry_code = country_code
self.email = email
self.id = id
self.payer = payer
self.username = username
self.amount = amount
self.create_... |
#
# PySNMP MIB module COMPAQ-AGENT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/COMPAQ-AGENT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:26:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, single_value_constraint, value_size_constraint, value_range_constraint) ... |
# -*- coding: utf-8 -*-
# @Author: Wenwen Yu
# @Created Time: 7/8/2020 9:34 PM
Entities_list = [
"COM",
"ADD",
"DATE",
"TOTAL"
]
# Entities_list = [
# "ticket_num",
# "starting_station",
# "train_num",
# "destination_station",
# "date",
# "ticket_rates",
# "seat_category",
... | entities_list = ['COM', 'ADD', 'DATE', 'TOTAL'] |
def ordinal(n):
return "%d%s" % (
n,
"tsnrhtdd"[(n // 10 % 10 != 1) * (n % 10 < 4) * n % 10 :: 4],
)
| def ordinal(n):
return '%d%s' % (n, 'tsnrhtdd'[(n // 10 % 10 != 1) * (n % 10 < 4) * n % 10::4]) |
class User:
'''
class that generates new instance of users
'''
user_list = []
def __init__(self,name,password):
self.name = name
self.password = password
def save_user(self):
User.user_list.append(self)
def delete_user(self):
'''
delete user a... | class User:
"""
class that generates new instance of users
"""
user_list = []
def __init__(self, name, password):
self.name = name
self.password = password
def save_user(self):
User.user_list.append(self)
def delete_user(self):
"""
delete user accou... |
# Copyright 2016 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.
{
'targets': [
{
'target_name': 'cr_slider',
'dependencies': [
'<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert',
... | {'targets': [{'target_name': 'cr_slider', 'dependencies': ['<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', '<(DEPTH)/third_party/polymer/v1_0/components-chromium/paper-slider/compiled_resources2.gyp:paper-slider-extracted'], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi']}]... |
#!/usr/bin/env python3
def consumer():
response = ''
while True:
message = yield response
if not message:
return
print('[CONSUMER] Consumer <%s>...' % ( message ))
response = '{CONSUMER OK}'
def product(consumer):
r = consumer.send(None)# next(... | def consumer():
response = ''
while True:
message = (yield response)
if not message:
return
print('[CONSUMER] Consumer <%s>...' % message)
response = '{CONSUMER OK}'
def product(consumer):
r = consumer.send(None)
assert (r == '', 'never')
for require in r... |
set_a = set(input().split())
num_sets = int(input())
i = 0
resp = []
while i < num_sets:
set_b = set(input().split())
resp.append(
len(set_b.intersection(set_a)) == len(set_b) and len(set_a) > len(set_b)
)
i += 1
print(all(resp))
| set_a = set(input().split())
num_sets = int(input())
i = 0
resp = []
while i < num_sets:
set_b = set(input().split())
resp.append(len(set_b.intersection(set_a)) == len(set_b) and len(set_a) > len(set_b))
i += 1
print(all(resp)) |
#https://codeforces.com/problemset/problem/266/A
p,s = input(),input()
c=0
for i in range(int(p)-1):
if(s[i]==s[i+1]):
c+=1
print(c) | (p, s) = (input(), input())
c = 0
for i in range(int(p) - 1):
if s[i] == s[i + 1]:
c += 1
print(c) |
def intersect(seq1:str,seq2:str)->list:
res=[]
for i in seq1:
if i in seq2:
res.append(i)
return res
print(intersect("SPAM","SAM")) | def intersect(seq1: str, seq2: str) -> list:
res = []
for i in seq1:
if i in seq2:
res.append(i)
return res
print(intersect('SPAM', 'SAM')) |
# Too slow
# def backtrack(n: str) -> int:
# if '?' not in n:
# # base case
# return
# # resolve first instance of ?
# index = n.index('?')
# n1 = n
# n2 = n
# n1[index] = '0'
# n2[index] = '0'
# return (int(backtrack(n1)) % 1000000007 + int(backtrack(n2)) % 1000000007) ... | mod = 1000000007
cache = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]
def sq_mod(n: int):
"""
gets how many it takes for inversion on n
"""
while len(cache) <= n:
cache.append(cache[-1] * 2 % mod)
return cache[n]
def inversions(n: str):
zeros = 0
questions = 0
tota... |
src = []
if aos_global_config.get('vcall') != 'posix':
src.append('cpu_impl.c')
if aos_global_config.board == 'linuxhost':
src.append('swap.S')
aos_component('linux', src)
| src = []
if aos_global_config.get('vcall') != 'posix':
src.append('cpu_impl.c')
if aos_global_config.board == 'linuxhost':
src.append('swap.S')
aos_component('linux', src) |
__all__ = ['ExternalGreeter']
class ExternalGreeter:
def __init__(self, name: str):
self._name = name
def say_hello(self):
print(f'Hello from GreetTheWorld: {self._name}')
| __all__ = ['ExternalGreeter']
class Externalgreeter:
def __init__(self, name: str):
self._name = name
def say_hello(self):
print(f'Hello from GreetTheWorld: {self._name}') |
# My approach
# def bin(n):
# l = []
# while n:
# l.append(str(n & 1))
# n>>=1
# return (''.join(l[::-1]))
# n = 12
# print("Binary representation of given number is",bin(12))
# # Iterative approach
# def bin(n) :
# i = 1 << 31
# while(i > 0) :
# ... | def binary(num):
return int(bin(num).split('0b')[1])
if __name__ == '__main__':
x = 10
binary_x = binary(x)
print(binary_x) |
def sequencia_logica():
n = int(input())
for i in range(1, n+1):
quadrado = i ** 2
cubo = i ** 3
print(f'{i} {quadrado} {cubo}')
print(f'{i} {quadrado+1} {cubo+1}')
sequencia_logica()
| def sequencia_logica():
n = int(input())
for i in range(1, n + 1):
quadrado = i ** 2
cubo = i ** 3
print(f'{i} {quadrado} {cubo}')
print(f'{i} {quadrado + 1} {cubo + 1}')
sequencia_logica() |
# 4. Write a for loop that prints all elements of a list and their position in the list.
a = [4, 7, 3, 2, 5, 9]
for ele in a:
print(f"{ele} - {a.index(ele) + 1}")
| a = [4, 7, 3, 2, 5, 9]
for ele in a:
print(f'{ele} - {a.index(ele) + 1}') |
WARNING = "Warning"
ERROR = "Error"
OK = "Ok"
SUCCESS = "Success"
ANSWER = "Answer"
SESSION = 'session'
DESCRIPTION = "description"
DATA = "data"
COMPANY = "Company"
LOGIN = "login"
PASSWORD = "password"
TYPE = "type"
QUERY = "query"
FIELD = "field"
ID_NAME = "id_nom"
ID_USER = "id_user"
NAME = "name"
SURNAME = "surna... | warning = 'Warning'
error = 'Error'
ok = 'Ok'
success = 'Success'
answer = 'Answer'
session = 'session'
description = 'description'
data = 'data'
company = 'Company'
login = 'login'
password = 'password'
type = 'type'
query = 'query'
field = 'field'
id_name = 'id_nom'
id_user = 'id_user'
name = 'name'
surname = 'surnam... |
def isSubclassOfAny(obj, types):
otype = type(obj)
isotype = lambda base: issubclass(otype, base)
return any(map(isotype, types))
| def is_subclass_of_any(obj, types):
otype = type(obj)
isotype = lambda base: issubclass(otype, base)
return any(map(isotype, types)) |
class Constants(object):
#
# * Constants for the program. Kind of crude, but if you need to change anything do it here. For the most part,
# * you shouldn't need to change anything.
#
ROOT = "<root>"
DISCOUNT=0.1
UNK = "UNK"
NUM_PAD = 1
STOP = "</s>"
START = "<s>"
NE... | class Constants(object):
root = '<root>'
discount = 0.1
unk = 'UNK'
num_pad = 1
stop = '</s>'
start = '<s>'
newline = '\n'
dash = '-'
dot = '.'
lm = 'lm'
text = 'text'
perp = 'perp'
order = 'order'
long_branches = 'long'
port = 'port'
test = 'test'
uni... |
class Solution:
def totalFruit(self, tree: List[int]) -> int:
result = i = 0
counter = defaultdict(int)
for j, x in enumerate(tree):
counter[x] += 1
while len(counter) > 2:
counter[tree[i]] -= 1
if counter[tree[i]] == 0:
... | class Solution:
def total_fruit(self, tree: List[int]) -> int:
result = i = 0
counter = defaultdict(int)
for (j, x) in enumerate(tree):
counter[x] += 1
while len(counter) > 2:
counter[tree[i]] -= 1
if counter[tree[i]] == 0:
... |
with open('cache/kyonh.txt') as f:
kyonh2descr = dict(line.rstrip('\n').split('\t')[::-1] for line in f)
with open('cache/tshet.txt') as f:
descr2tshet = dict(line.rstrip('\n').split('\t') for line in f)
def do(fin, fout, ferr):
# header
for line in fin:
line = line.rstrip('\n')
if li... | with open('cache/kyonh.txt') as f:
kyonh2descr = dict((line.rstrip('\n').split('\t')[::-1] for line in f))
with open('cache/tshet.txt') as f:
descr2tshet = dict((line.rstrip('\n').split('\t') for line in f))
def do(fin, fout, ferr):
for line in fin:
line = line.rstrip('\n')
if line == '...'... |
# from secret import FLAG
FLAG = "CSR{fuckingIdiotShitStupid}"
def hashfun(msg):
digest = []
for i in range(len(msg) - 4):
digest.append(ord(msg[i]) ^ ord(msg[i + 4]))
return digest
def revhash(cipher):
msg_len = len(c) + 4
msg = ["."] * (msg_len + 1)
msg[0:5] = "CSR{"
for i in... | flag = 'CSR{fuckingIdiotShitStupid}'
def hashfun(msg):
digest = []
for i in range(len(msg) - 4):
digest.append(ord(msg[i]) ^ ord(msg[i + 4]))
return digest
def revhash(cipher):
msg_len = len(c) + 4
msg = ['.'] * (msg_len + 1)
msg[0:5] = 'CSR{'
for i in range(4, msg_len):
pr... |
def _impl(ctx):
tree = ctx.actions.declare_directory(ctx.attr.name)
ctx.actions.run(
inputs = [],
outputs = [ tree ],
arguments = ['-o', tree.path, '-n', str(ctx.attr.n) ],
progress_message = "Generating cc files into '%s'" % tree.path,
executable = ctx.executable._tool,
)
return [ DefaultI... | def _impl(ctx):
tree = ctx.actions.declare_directory(ctx.attr.name)
ctx.actions.run(inputs=[], outputs=[tree], arguments=['-o', tree.path, '-n', str(ctx.attr.n)], progress_message="Generating cc files into '%s'" % tree.path, executable=ctx.executable._tool)
return [default_info(files=depset([tree]))]
genccs... |
class RegexHelper:
SWEDISH_PRIVATE_PERSON = "^(19|20)[0-9]{2}((0[1-9])|(1[0-2]))(([06][1-9])|([1278][0-9])|([39][0-1]))[0-9]{4}$"
EMAIL_ADDRESS = "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$"
MOBILE_PHONE = "^\+(\d+)$... | class Regexhelper:
swedish_private_person = '^(19|20)[0-9]{2}((0[1-9])|(1[0-2]))(([06][1-9])|([1278][0-9])|([39][0-1]))[0-9]{4}$'
email_address = "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$"
mobile_phone = '^\\+(\\... |
def additionWithoutCarrying(param1, param2):
# Convert numbers to strings
str1 = str(param1)
str2 = str(param2)
# Pad both to the same length with zeroes (to the left of the numbers)
length = max(len(str2), len(str1))
str1 = str1.rjust(length, "0")
str2 = str2.rjust(length, "0")
output =... | def addition_without_carrying(param1, param2):
str1 = str(param1)
str2 = str(param2)
length = max(len(str2), len(str1))
str1 = str1.rjust(length, '0')
str2 = str2.rjust(length, '0')
output = []
for (num1, num2) in zip(str1, str2):
result = str(int(num1) + int(num2))[-1]
outpu... |
def strength(A, theta = 0.0):
A = A.tocsr()
Sp = np.empty_like(A.indptr)
Sj = np.empty_like(A.indices)
Sx = np.empty_like(A.data)
nnz = 0
n = A.shape[0]
Sp[0] = 0
for i in range(0, n):
diag = 0
for j in range(A.indptr[i], A.indptr[i+1]):
if (A.i... | def strength(A, theta=0.0):
a = A.tocsr()
sp = np.empty_like(A.indptr)
sj = np.empty_like(A.indices)
sx = np.empty_like(A.data)
nnz = 0
n = A.shape[0]
Sp[0] = 0
for i in range(0, n):
diag = 0
for j in range(A.indptr[i], A.indptr[i + 1]):
if A.indices[j] == i:
... |
class Solution:
def isMatch(self, s: str, p: str) -> bool:
matched = [[False for _ in range(len(p)+1)] for _ in range(len(s)+1)]
matched[0][0] = True
for i in range(len(s)+1):
for j in range(1, len(p)+1):
pattern = p[j-1]
... | class Solution:
def is_match(self, s: str, p: str) -> bool:
matched = [[False for _ in range(len(p) + 1)] for _ in range(len(s) + 1)]
matched[0][0] = True
for i in range(len(s) + 1):
for j in range(1, len(p) + 1):
pattern = p[j - 1]
if pattern == ... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def getIntersect(self, head: ListNode):
hare = head
tortoise = head
while hare and hare.next:
hare = hare.next.next
tortoise... | class Listnode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def get_intersect(self, head: ListNode):
hare = head
tortoise = head
while hare and hare.next:
hare = hare.next.next
tortoise = tortoise.next
if har... |
'''# Problem: https://www.hackerrank.com/challenges/tutorial-intro/problem
# Score: 30
About Tutorial Challenges
Many of the challenges on HackerRank are difficult and assume that you already know the relevant algorithms. These tutorial challenges are different. They break down algorithmic concepts into smaller challen... | """# Problem: https://www.hackerrank.com/challenges/tutorial-intro/problem
# Score: 30
About Tutorial Challenges
Many of the challenges on HackerRank are difficult and assume that you already know the relevant algorithms. These tutorial challenges are different. They break down algorithmic concepts into smaller challen... |
#create node
class Node(object):
def __init__(self, data=None, next=None): #initialise node
self.data = data
self.next = next
def get_data(self): #retrieve node data
return self.data
def set_data(self, new_data): #set node data
self.data = new_data
... | class Node(object):
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def get_data(self):
return self.data
def set_data(self, new_data):
self.data = new_data
def get_next(self):
return self.next
def set_next(self, next_node):
... |
class Di(object):
_env = None
_args = None
def getEnv(self):
return self._env
def setEnv(self, env):
self._env = env
def setArgs(self, args):
self._args = args
def getArgs(self):
return self._args
def __init__(self, env, args):
... | class Di(object):
_env = None
_args = None
def get_env(self):
return self._env
def set_env(self, env):
self._env = env
def set_args(self, args):
self._args = args
def get_args(self):
return self._args
def __init__(self, env, args):
self._env = env... |
#
# PySNMP MIB module HHMSSMALL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HHMSSMALL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:30:39 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, value_range_constraint, constraints_union, single_value_constraint) ... |
class FunctionPrototype:
def __init__(self, name, return_type, parameters):
self.name = name
self.return_type = return_type
self.parameters = parameters
class Function:
def __init__(self, name, return_type, parameters, block):
self.name = name
self.return_type = return_... | class Functionprototype:
def __init__(self, name, return_type, parameters):
self.name = name
self.return_type = return_type
self.parameters = parameters
class Function:
def __init__(self, name, return_type, parameters, block):
self.name = name
self.return_type = return... |
def exist_sum(arr, target):
if target==0:
return True
if len(arr)==1:
return arr[0] == target
else:
for i in range(len(arr)):
new_arr = arr[:i]+arr[i+1:]
if exist_sum(new_arr, target-arr[i]):
return True
return False
while True:
tr... | def exist_sum(arr, target):
if target == 0:
return True
if len(arr) == 1:
return arr[0] == target
else:
for i in range(len(arr)):
new_arr = arr[:i] + arr[i + 1:]
if exist_sum(new_arr, target - arr[i]):
return True
return False
while Tru... |
# This sample is imported by import6.py.
foo = 3
__foo = 4
bar = 5
_bar = 6
| foo = 3
__foo = 4
bar = 5
_bar = 6 |
class Solution:
def longestRepeatingSubstring(self, S: str) -> int:
def search(L):
visited = set()
for i in range(len(S) - L + 1):
s = S[i: i + L]
if s in visited:
return i
visited.add(s)
return -1
... | class Solution:
def longest_repeating_substring(self, S: str) -> int:
def search(L):
visited = set()
for i in range(len(S) - L + 1):
s = S[i:i + L]
if s in visited:
return i
visited.add(s)
return -1
... |
def isPrime(n) :
if (n <= 1) :
return False
if (n <= 3) :
return True
# we are doing this to decrease the time complexity
if (n % 2 == 0 or n % 3 == 0 ) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return F... | def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i = i + 6
return True
total = 2
for i in range(3, 2000000, 2):
... |
Settings.MoveMouseDelay = 0
running = True
def runHotkey(event):
global running
running = False
Env.addHotkey(Key.F1, KeyModifier.ALT, runHotkey)
while(running):
if (exists("1507485878000.png", .005) or (exists("1509668195740.png", .005))):
#If tip window shows up, wait
wait(2)
#F... | Settings.MoveMouseDelay = 0
running = True
def run_hotkey(event):
global running
running = False
Env.addHotkey(Key.F1, KeyModifier.ALT, runHotkey)
while running:
if exists('1507485878000.png', 0.005) or exists('1509668195740.png', 0.005):
wait(2)
click('1511398531290.png')
wait(0.5)... |
# -*- coding: utf-8 -*-
'''
Author: Hannibal
Data:
Desc: local data config
NOTE: Don't modify this file, it's build by xml-to-python!!!
'''
partnerskill2_map = {};
partnerskill2_map[1] = {"lv":1,"reqlv":1,"gold":20,"goldrate":1,};
partnerskill2_map[2] = {"lv":2,"reqlv":2,"gold":100,"goldrate":4,};
partnerskill2_map... | """
Author: Hannibal
Data:
Desc: local data config
NOTE: Don't modify this file, it's build by xml-to-python!!!
"""
partnerskill2_map = {}
partnerskill2_map[1] = {'lv': 1, 'reqlv': 1, 'gold': 20, 'goldrate': 1}
partnerskill2_map[2] = {'lv': 2, 'reqlv': 2, 'gold': 100, 'goldrate': 4}
partnerskill2_map[3] = {'lv': 3, 'r... |
#
# PySNMP MIB module TIME-AGGREGATE-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/TIME-AGGREGATE-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:31:27 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, constraints_intersection, value_range_constraint, value_size_constraint) ... |
color=["blue","red","green","pink"]
a,b,c,d=color
print(a)
print(b)
print(c)
print(d) | color = ['blue', 'red', 'green', 'pink']
(a, b, c, d) = color
print(a)
print(b)
print(c)
print(d) |
true=True
false=False
beaconBaseBlock={
"format_version": "1.16.100",
"minecraft:block": {
"description": {
"identifier": "spb:beacon_base.block",
"is_experimental": false,
"properties": {
"spb:range_level": [
0,
1,
2,
3
]
}
},
"permutations": [
{
"condition": "que... | true = True
false = False
beacon_base_block = {'format_version': '1.16.100', 'minecraft:block': {'description': {'identifier': 'spb:beacon_base.block', 'is_experimental': false, 'properties': {'spb:range_level': [0, 1, 2, 3]}}, 'permutations': [{'condition': "query.block_property('spb:range_level')==0", 'components': {... |
class Flight:
def __init__(self, data):
self.data = data
def __repr__(self):
return (
f"Flight {self.callsign} with aircraft {self.icao24} "
f"on {self.min('timestamp'):%Y-%m-%d} "
)
def __lt__(self, other):
return self.min("timestamp") <= other.min(... | class Flight:
def __init__(self, data):
self.data = data
def __repr__(self):
return f"Flight {self.callsign} with aircraft {self.icao24} on {self.min('timestamp'):%Y-%m-%d} "
def __lt__(self, other):
return self.min('timestamp') <= other.min('timestamp')
def max(self, feature... |
# Copyright 2017 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.
DEPS = [
'goma',
]
def RunSteps(api):
jobs = api.goma.recommended_goma_jobs
# Test caching.
jobs2 = api.goma.recommended_goma_jobs
assert jobs =... | deps = ['goma']
def run_steps(api):
jobs = api.goma.recommended_goma_jobs
jobs2 = api.goma.recommended_goma_jobs
assert jobs == jobs2
def gen_tests(api):
yield api.test('basic') |
def setStyle_CSS():
CSS_dict = \
{
'QWidget':
{
'background-color': '#dddddd',
},
'QLabel#label':
{
'color': '#888888',
'background-color': '#444444',
'font-weight': 'bold',
},
'QLabel#label:active':
... | def set_style_css():
css_dict = {'QWidget': {'background-color': '#dddddd'}, 'QLabel#label': {'color': '#888888', 'background-color': '#444444', 'font-weight': 'bold'}, 'QLabel#label:active': {'color': '#1d90cd'}, 'QPushButton#button': {'color': '#888888', 'background-color': '#444444', 'font-weight': 'bold', 'bord... |
def sum_of_nsqr(n):
return n * (n+1) * (2*n+1) // 6
print(sum_of_nsqr(10))
print(sum_of_nsqr(50))
| def sum_of_nsqr(n):
return n * (n + 1) * (2 * n + 1) // 6
print(sum_of_nsqr(10))
print(sum_of_nsqr(50)) |
class Solution:
def minFlips(self, target: str) -> int:
flips = 0
i0 = target.find('1')
if i0 ==-1:
return flips
flips = 1
for i in range(i0 + 1, len(target)):
if target[i] != target[i-1]:
flips += 1
return flips
... | class Solution:
def min_flips(self, target: str) -> int:
flips = 0
i0 = target.find('1')
if i0 == -1:
return flips
flips = 1
for i in range(i0 + 1, len(target)):
if target[i] != target[i - 1]:
flips += 1
return flips
target = '... |
#M
row=0
while row<7:
col =0
while col<11:
if (col==0 )or (row==3 and col==7)or (row==2 and col==8)or (row==1 and col==9)or (col==10)or(row==4 and col==6)or(row==1 and col==1)or(row==2 and col==2)or(row==3 and col==3)or(row==4 and col==4)or (row==5 and col==5):
print("*",end=" ")
... | row = 0
while row < 7:
col = 0
while col < 11:
if col == 0 or (row == 3 and col == 7) or (row == 2 and col == 8) or (row == 1 and col == 9) or (col == 10) or (row == 4 and col == 6) or (row == 1 and col == 1) or (row == 2 and col == 2) or (row == 3 and col == 3) or (row == 4 and col == 4) or (row == 5 a... |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... | power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate Leakage': 0.00662954, 'Peak Dynamic': 0.0, 'Runtime Dynamic': 0.0, 'Subthres... |
# URI Online Judge 3161
entrada = [int(i) for i in input().split()]
N, M = entrada[0], entrada[1]
frutas = [input().lower() for i in range(N)]
codigos = [input().lower() for i in range(M)]
codigo = ''.join(codigos)
gosta = []
for fruta in frutas:
if fruta in codigo or fruta in codigo[::-1] :
print("Shel... | entrada = [int(i) for i in input().split()]
(n, m) = (entrada[0], entrada[1])
frutas = [input().lower() for i in range(N)]
codigos = [input().lower() for i in range(M)]
codigo = ''.join(codigos)
gosta = []
for fruta in frutas:
if fruta in codigo or fruta in codigo[::-1]:
print('Sheldon come a fruta {}'.form... |
# Lets see Casting value to float (Number)
ix = 2
sx = "299"
pi = "3.14"
x = float(ix) # Casting from int to float
print(f"Casted from int {x}")
y = float(sx) # Casting from str to float
print(f"Casted from Text (str) {y}")
z = float(pi) # Casting from str to float
print(f"Casted from Text (str) {z}")
print(ty... | ix = 2
sx = '299'
pi = '3.14'
x = float(ix)
print(f'Casted from int {x}')
y = float(sx)
print(f'Casted from Text (str) {y}')
z = float(pi)
print(f'Casted from Text (str) {z}')
print(type(z)) |
def round(pt_1, pt_2, key_round, n, c):
# plaintext = t1[0:n-1]t2[0:n-1]
# print(type(pt_1))
t1 = pt_1
t2 = pt_2
# print ("before texts 01 in hex",format(t1, '04x'), format(t2, "04X"))
# print(key_0_list[i])
crol_1 = (t1 << 1) + (t1 >> (n - 1)) & c
crol_5 = (t1 << 5) + (t1 >> (n - 5)) &... | def round(pt_1, pt_2, key_round, n, c):
t1 = pt_1
t2 = pt_2
crol_1 = (t1 << 1) + (t1 >> n - 1) & c
crol_5 = (t1 << 5) + (t1 >> n - 5) & c
tmp1 = t1 & crol_5
tmp2 = t2 ^ tmp1
tmp3 = tmp2 ^ crol_1
tmp4 = tmp3 ^ key_round
t2 = t1
t1 = tmp4
return (t1, t2) |
class Athlete:
def __init__(self, value='Jane'):
self.inner_value = value
print(self.inner_value)
def getInnerValue(self):
return self.inner_value
class Temp(Athlete):
def __init__(self):
super()
athlete = Athlete(value='fonslucens') # == Athlete.__init__()
print(athlet... | class Athlete:
def __init__(self, value='Jane'):
self.inner_value = value
print(self.inner_value)
def get_inner_value(self):
return self.inner_value
class Temp(Athlete):
def __init__(self):
super()
athlete = athlete(value='fonslucens')
print(athlete.getInnerValue()) |
__author__ = 'jbowman'
# string length
s = 'Hello World'
print(len(s))
# case conversion
s = 'Python'
s = s.upper()
print(s)
# concatenation
str1 = 'Python'
str2 = 'This is my favorite language'
str3 = str1 + ' ' + str2
print(str3)
# newlines
str4 = str1 + "\n" + str2
print(str4)
# quotes (\ escape character)
str1... | __author__ = 'jbowman'
s = 'Hello World'
print(len(s))
s = 'Python'
s = s.upper()
print(s)
str1 = 'Python'
str2 = 'This is my favorite language'
str3 = str1 + ' ' + str2
print(str3)
str4 = str1 + '\n' + str2
print(str4)
str1 = 'The word "computer" will be in quotes.'
print(str1) |
class NoOpDeviceNameCalculator:
def __init__(self):
pass
def name(self):
return ""
| class Noopdevicenamecalculator:
def __init__(self):
pass
def name(self):
return '' |
N = int(input())
at = [list(map, int, input().split()) for _ in range(N)]
Q = int(input())
x = list(map, int, input().split())
# for _ in range(s | n = int(input())
at = [list(map, int, input().split()) for _ in range(N)]
q = int(input())
x = list(map, int, input().split()) |
N, L = map(int, input().split())
A = []
for i in range(N):
A.append(L + (i + 1) - 1)
apple = 1000
for a in A:
if abs(a) < abs(apple):
apple = a
print(sum(A) - apple) | (n, l) = map(int, input().split())
a = []
for i in range(N):
A.append(L + (i + 1) - 1)
apple = 1000
for a in A:
if abs(a) < abs(apple):
apple = a
print(sum(A) - apple) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
# Using memoization as decorator (decorator-function)
def memoize_func(f):
memo = dict()
def func(*args):
if args not in memo:
memo[args] = f(*args)
return memo[args]
return func
@memoize_func
def fib(n... | __author__ = 'ipetrash'
def memoize_func(f):
memo = dict()
def func(*args):
if args not in memo:
memo[args] = f(*args)
return memo[args]
return func
@memoize_func
def fib(n):
(a, b) = (1, 1)
for i in range(n - 1):
(a, b) = (b, a + b)
return a
print(fib(1000... |
#LeetCode problem 94: Binary Tree Inorder 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:
def inorderTraversal(self, root: TreeNode) -> List[int]:... | class Solution:
def inorder_traversal(self, root: TreeNode) -> List[int]:
a = []
self.returnOrder(root, a)
return a
def return_order(self, root: TreeNode, a: List):
if root is None:
return
if root:
self.returnOrder(root.left, a)
a.app... |
N, K, *a = map(int, open(0).read().split())
result = [K // N] * N
for i, _ in sorted(enumerate(a), key=lambda x: x[1])[:K % N]:
result[i] += 1
print(*result, sep='\n')
| (n, k, *a) = map(int, open(0).read().split())
result = [K // N] * N
for (i, _) in sorted(enumerate(a), key=lambda x: x[1])[:K % N]:
result[i] += 1
print(*result, sep='\n') |
if __name__ == "__main__":
l = [int(x) for x in input().split()]
def isValidMaxHeap(l, n):
for i in range(((n-2)//2)+1):
if l[2*i+1] < l[i]:
return False
if 2*i+2 < n and l[2*i+2] < l[i]:
return False
return True
print(isValidMaxHeap(l, len(l))) | if __name__ == '__main__':
l = [int(x) for x in input().split()]
def is_valid_max_heap(l, n):
for i in range((n - 2) // 2 + 1):
if l[2 * i + 1] < l[i]:
return False
if 2 * i + 2 < n and l[2 * i + 2] < l[i]:
return False
return True
pri... |
# searching for an item in an ordered list
# this technique uses a binary search
items = [6, 8, 19, 20, 23, 42, 53, 87]
def binary_search(item, dataset):
# start at the two ends of the list
lower = 0
upper = len(dataset) - 1
while lower <= upper:
# TODO: calculate the middle point
... | items = [6, 8, 19, 20, 23, 42, 53, 87]
def binary_search(item, dataset):
lower = 0
upper = len(dataset) - 1
while lower <= upper:
mid = (lower + upper) // 2
if dataset[mid] == item:
return mid
if dataset[mid] < item:
lower = mid + 1
else:
... |
#
# PySNMP MIB module ALCATEL-IND1-IPM-VLAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALCATEL-IND1-IPM-VLAN-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:02:21 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... | (softent_ind1_ipm_vlan_mgt,) = mibBuilder.importSymbols('ALCATEL-IND1-BASE', 'softentIND1IPMVlanMgt')
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_cons... |
def sort(arr):
sorted = False
unsorted_until_index = len(arr) - 1
while not sorted:
sorted = True
for i in range(unsorted_until_index):
if arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
sorted = False
unsorted_until_index = unsorted_unt... | def sort(arr):
sorted = False
unsorted_until_index = len(arr) - 1
while not sorted:
sorted = True
for i in range(unsorted_until_index):
if arr[i] > arr[i + 1]:
(arr[i], arr[i + 1]) = (arr[i + 1], arr[i])
sorted = False
unsorted_until_index = un... |
class Functions:
@staticmethod
def ranges(data, X):
featureRanges = []
for i in range(len(X[0])):
lst = [f[i] for f in data]
featureRanges.append(max(max(lst), X[0][i]) - min(min(lst), X[0][i]))
return featureRanges
| class Functions:
@staticmethod
def ranges(data, X):
feature_ranges = []
for i in range(len(X[0])):
lst = [f[i] for f in data]
featureRanges.append(max(max(lst), X[0][i]) - min(min(lst), X[0][i]))
return featureRanges |
def permute(a,l,r):
n = len(a)
if l ==r:
# return a
print(''.join(a))
else:
for j in range(l,r+1):
a[j],a[l] = a[l], a[j]
# print(a,l,j)
permute(a,l+1,r)
a[j],a[l] = a[l], a[j]
# print('after',a,l,j)
# print(... | def permute(a, l, r):
n = len(a)
if l == r:
print(''.join(a))
else:
for j in range(l, r + 1):
(a[j], a[l]) = (a[l], a[j])
permute(a, l + 1, r)
(a[j], a[l]) = (a[l], a[j])
a = 'abc'
a = list(a)
def nested_fors(n, firstfor, x):
store = []
if firstfo... |
s=input()
a=int(input())
leng=len(s)
if(leng>a):
print('True')
else:
print('False')
if(leng>=a):
print('True')
else:
print('False')
if(leng==a):
print('True')
else:
print('False')
if(leng!=a):
print('True')
else:
print('False') | s = input()
a = int(input())
leng = len(s)
if leng > a:
print('True')
else:
print('False')
if leng >= a:
print('True')
else:
print('False')
if leng == a:
print('True')
else:
print('False')
if leng != a:
print('True')
else:
print('False') |
i=0
while (i<=10):
print (i*99)
i+=1
| i = 0
while i <= 10:
print(i * 99)
i += 1 |
a : int = 10
def foo(x : int) -> int:
b : int = 0
def aux(i : int) -> int:
return b + i
def bar(y : int) -> int:
c : int = 0
def baz(z : int) -> int:
d : int = 0
d = aux(c + 1)
return a + x + y + z
return baz(a + b + x)
b = aux(x)
return bar(b + 10)
print(foo(a)) | a: int = 10
def foo(x: int) -> int:
b: int = 0
def aux(i: int) -> int:
return b + i
def bar(y: int) -> int:
c: int = 0
def baz(z: int) -> int:
d: int = 0
d = aux(c + 1)
return a + x + y + z
return baz(a + b + x)
b = aux(x)
retur... |
def removeDuplicates(nums):
dict = {}
arr = []
for item in nums:
if dict[item] != 1:
dict[item] = 1
arr.append(item)
return arr
arr = [1,3,4,5,4,2,2,2,74,23]
arr = removeDuplicates(arr)
print(arr)
| def remove_duplicates(nums):
dict = {}
arr = []
for item in nums:
if dict[item] != 1:
dict[item] = 1
arr.append(item)
return arr
arr = [1, 3, 4, 5, 4, 2, 2, 2, 74, 23]
arr = remove_duplicates(arr)
print(arr) |
class Inventory:
def_weapon_supplier=lambda _: Weapon("Fists", 1, 10)
def __init__(self, armor=list(), weapons=list(), other_items=list()):
self.armor=armor
self.weapons=weapons
self.other_items=other_items
def all_items():
for piece in armor:
yield piece
... | class Inventory:
def_weapon_supplier = lambda _: weapon('Fists', 1, 10)
def __init__(self, armor=list(), weapons=list(), other_items=list()):
self.armor = armor
self.weapons = weapons
self.other_items = other_items
def all_items():
for piece in armor:
yield piec... |
# we can also compute the stats individually
# *challenge* modify this cell so that all of these stats print out
surveys_df['weight'].min()
surveys_df['weight'].max()
surveys_df['weight'].mean()
surveys_df['weight'].std()
surveys_df['weight'].count() | surveys_df['weight'].min()
surveys_df['weight'].max()
surveys_df['weight'].mean()
surveys_df['weight'].std()
surveys_df['weight'].count() |
class ModelType:
KEY_CREATOR = 'creator'
SHIP_MODEL = 'ship'
ASTEROID_MODEL = 'asteroid'
BOLT_MODEL = 'bolt'
KEY_POSITION = 'k_xy'
KEY_SPEED = 'k_v_xy'
KEY_DIRECTION = 'k_dir_xy'
KEY_TYPE = 'k_type'
KEY_RADIUS = 'k_rad'
KEY_LIFE = 'k_life'
KEY_COLOR = 'k_color'
KEY_NAME... | class Modeltype:
key_creator = 'creator'
ship_model = 'ship'
asteroid_model = 'asteroid'
bolt_model = 'bolt'
key_position = 'k_xy'
key_speed = 'k_v_xy'
key_direction = 'k_dir_xy'
key_type = 'k_type'
key_radius = 'k_rad'
key_life = 'k_life'
key_color = 'k_color'
key_name =... |
def n_esimo_fibonacci(n):
seq = [0, 1]
while len(seq) <= n:
seq.append(seq[-1]+seq[-2])
return seq[n]
print(n_esimo_fibonacci(7)) | def n_esimo_fibonacci(n):
seq = [0, 1]
while len(seq) <= n:
seq.append(seq[-1] + seq[-2])
return seq[n]
print(n_esimo_fibonacci(7)) |
class Messages:
def __init__(self, message):
self.message = message
def __str__(self):
return '[%s]: %s' % (self.__class__.__name__, self.message)
class Info(Messages):
pass
| class Messages:
def __init__(self, message):
self.message = message
def __str__(self):
return '[%s]: %s' % (self.__class__.__name__, self.message)
class Info(Messages):
pass |
class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower()
'''
arr = list(s)
for idx,letter in enumerate(arr):
arr[idx] = letter.lower()
out = ""
return out.join(arr)
''' | class Solution:
def to_lower_case(self, s: str) -> str:
return s.lower()
'\n arr = list(s)\n \n for idx,letter in enumerate(arr):\n arr[idx] = letter.lower()\n \n out = ""\n return out.join(arr)\n ' |
__all__ = [
"saved_acquisition_schemes",
"saved_data"
]
| __all__ = ['saved_acquisition_schemes', 'saved_data'] |
class Rectangle:
width: int
height: int
def __init__(self, width: int, height: int) -> None:
self.width = width
self.height = height
def fill(self):
return [[1] * self.width for _ in range(self.height)]
| class Rectangle:
width: int
height: int
def __init__(self, width: int, height: int) -> None:
self.width = width
self.height = height
def fill(self):
return [[1] * self.width for _ in range(self.height)] |
list1 = []
list2 = []
listNew = []
print("Please enter 3 numbers for each list.")
print("List 1")
for i in range (0,3):
listItem = float(input(str(i + 1) + ": "))
list1.append(listItem)
print("List 2")
for i in range (0,3):
listItem = float(input(str(i + 1) + ": "))
list2.append(listItem)
listNew = ... | list1 = []
list2 = []
list_new = []
print('Please enter 3 numbers for each list.')
print('List 1')
for i in range(0, 3):
list_item = float(input(str(i + 1) + ': '))
list1.append(listItem)
print('List 2')
for i in range(0, 3):
list_item = float(input(str(i + 1) + ': '))
list2.append(listItem)
list_new = ... |
def average(array):
#your code here and if you use a loop you are lame and inefficient!
return round(sum(array) / len(array))
| def average(array):
return round(sum(array) / len(array)) |
# ---
# jupyter:
# jupytext:
# cell_markers: '{{{,}}}'
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
1+2+3
# {{{ active=""
# This is a raw cell
# }}}
# This is a markdown cell
| 1 + 2 + 3 |
#!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
words = ['one', 'two', 'three', 'four', 'five']
for index in words:
print(index)
| words = ['one', 'two', 'three', 'four', 'five']
for index in words:
print(index) |
filename="/etc/passwd"
k=1
with open(filename, 'r') as fp:
for line in fp:
print(f'{str(k).zfill(3):5}{line[:35]}'.rstrip("\n"))
k+=1
| filename = '/etc/passwd'
k = 1
with open(filename, 'r') as fp:
for line in fp:
print(f'{str(k).zfill(3):5}{line[:35]}'.rstrip('\n'))
k += 1 |
print(5/8)
print(7+10)
print(2*6)
print(23-10)
#modulo
print(18%7)
#this allows dev to raise a number to power
print(2**4)
| print(5 / 8)
print(7 + 10)
print(2 * 6)
print(23 - 10)
print(18 % 7)
print(2 ** 4) |
'''
Copyright (C) 2020 Link Shortener Authors (see AUTHORS in Documentation).
Licensed under the MIT (Expat) License (see LICENSE in Documentation).
'''
class AccessDeniedException(Exception):
'''
Used for API token checking. Raised when headers are missing a token
or the token is incorrect.
'''
p... | """
Copyright (C) 2020 Link Shortener Authors (see AUTHORS in Documentation).
Licensed under the MIT (Expat) License (see LICENSE in Documentation).
"""
class Accessdeniedexception(Exception):
"""
Used for API token checking. Raised when headers are missing a token
or the token is incorrect.
"""
pa... |
#
# PySNMP MIB module UCD-IPFWACC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/UCD-IPFWACC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:21:11 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, constraints_union, value_size_constraint, value_range_constraint) ... |
s="this is string example"
# Reverse the string :
a = s.split()
a = list(reversed(a))
print(" ".join(a))
# Word wise reversing the String :
stringlength=len(s)
slicedString=s[stringlength::-1]
print (slicedString)
# Two characters interchange :
def solve(b):
b = list(s)
for i in range(0, len(b)-1, 2):
b[... | s = 'this is string example'
a = s.split()
a = list(reversed(a))
print(' '.join(a))
stringlength = len(s)
sliced_string = s[stringlength::-1]
print(slicedString)
def solve(b):
b = list(s)
for i in range(0, len(b) - 1, 2):
(b[i], b[i + 1]) = (b[i + 1], b[i])
return ''.join(b)
print(solve(s))
c = ['t... |
def apply(variable_a, variable_b, a=0.5, b=0.5):
print(variable_a.shape)
print(variable_b.shape)
return a * variable_a + b * variable_b
| def apply(variable_a, variable_b, a=0.5, b=0.5):
print(variable_a.shape)
print(variable_b.shape)
return a * variable_a + b * variable_b |
# 0 ==> empty block
# 1 ==> piece block
# 2 ==> occupied block
I = [
[ 0, 0, 1, 0,
0, 0, 1, 0,
0, 0, 1, 0,
0, 0, 1, 0,],
[ 0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
1, 1, 1, 1,],
]
O = [
[ 0, 0, 0, 0,
0, 0, 0, 0,
0, 1, 1, 0,
0, 1, 1, 0,... | i = [[0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]]
o = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0]]
l = [[0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 0, 0, 2, 1, 0, 0, 2, 1, 0], [0, 0... |
# Estimated Probabilities
# Perturb Variables based on Assumed Causal Graph
# Drive Alone
long_sim_data_causal.loc[
long_sim_data_causal["mode_id"] == 1, "total_travel_time"
] = reg.lin_reg_pred(
X=long_sim_data_causal.loc[
long_sim_data_causal["mode_id"] == 1, "total_travel_distance"
],
fitted_... | long_sim_data_causal.loc[long_sim_data_causal['mode_id'] == 1, 'total_travel_time'] = reg.lin_reg_pred(X=long_sim_data_causal.loc[long_sim_data_causal['mode_id'] == 1, 'total_travel_distance'], fitted_reg=fitted_reg_da['total_travel_time_on_total_travel_distance'], size=long_sim_data_causal.loc[long_sim_data_causal['mo... |
n = int(input())
s = int((n*(n+1))/2)
if s%2==0:
print("0")
else:
print("1") | n = int(input())
s = int(n * (n + 1) / 2)
if s % 2 == 0:
print('0')
else:
print('1') |
str1="hello"
c=0
for x in str1:
if(x=='e' or x=='o'):
pass
else:
c=c+1
print(c)
#3 | str1 = 'hello'
c = 0
for x in str1:
if x == 'e' or x == 'o':
pass
else:
c = c + 1
print(c) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.