content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Write your solution here
def double_items(numbers):
double_numbers = []
for item in numbers:
double_numbers.append(item*2)
return double_numbers
if __name__ == "__main__":
numbers = [2, 4, 5, 3, 11, -4]
numbers_doubled = double_items(numbers)
print("original:", numbers)
print("dou... | def double_items(numbers):
double_numbers = []
for item in numbers:
double_numbers.append(item * 2)
return double_numbers
if __name__ == '__main__':
numbers = [2, 4, 5, 3, 11, -4]
numbers_doubled = double_items(numbers)
print('original:', numbers)
print('doubled:', numbers_doubled) |
# -*- coding: utf-8 -*-
TOILET_CHOICES = (
('F', 'Flush'),
('PT', 'Pit toilet'),
('TPT', 'Traditional Pit toilet'),
('L', 'Latrine'),
('BF', 'Bush /Field'),
('R', 'River'),
('O', 'Others'),
)
COOKING_FACILITIES = (
('Electricity', 'Electricity'),
('Gas'... | toilet_choices = (('F', 'Flush'), ('PT', 'Pit toilet'), ('TPT', 'Traditional Pit toilet'), ('L', 'Latrine'), ('BF', 'Bush /Field'), ('R', 'River'), ('O', 'Others'))
cooking_facilities = (('Electricity', 'Electricity'), ('Gas', 'Gas'), ('Biomass', 'Biomass'), ('Kerosene', 'Kerosene'), ('Coal', 'Coal'), ('Charcoal', 'Cha... |
#
# PySNMP MIB module ZHONE-COM-IP-ZEDGE-NAT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHONE-COM-IP-ZEDGE-NAT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:41:01 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, value_range_constraint, single_value_constraint, value_size_constraint) ... |
# Data paths
DATA_BACKGROUND_FOLDER = "../data/background/"
DATA_GENERATED_FOLDER = "../data/generated_data/"
# General settings
IMAGES_TO_GENERATE = 500
COIN_RESIZE_RATIO_MIN = 0.4
COIN_RESIZE_RATIO_MAX = 0.6
# Background settings
BACKGROUND_RESIZE_RATIO = 400
BACKGROUND_MAX_N_COINS = 25
# Coin crop settings
MAX_CO... | data_background_folder = '../data/background/'
data_generated_folder = '../data/generated_data/'
images_to_generate = 500
coin_resize_ratio_min = 0.4
coin_resize_ratio_max = 0.6
background_resize_ratio = 400
background_max_n_coins = 25
max_coin_overlap_percentage = 0.33
individual_coin_crop_noise = 0.05 |
# Test values must be in the form [(text_input, expected_output), (text_input, expected_output), ...]
test_values = [
(
"president",
{
"n": {
"president",
"presidentship",
"presidencies",
"presidency",
"presi... | test_values = [('president', {'n': {'president', 'presidentship', 'presidencies', 'presidency', 'presidentships', 'presidents'}, 'r': {'presidentially'}, 'a': {'presidential'}, 'v': {'presiding', 'presides', 'preside', 'presided'}}), ('elect', {'n': {'elector', 'elects', 'electors', 'elective', 'electorates', 'elect', ... |
def myfunc(str):
print(str)
nstr = str.lower()
for i in range(len(str)):
nstr[i+1].upper()
return nstr
print(myfunc("SlseJbKWdOEuhB")) | def myfunc(str):
print(str)
nstr = str.lower()
for i in range(len(str)):
nstr[i + 1].upper()
return nstr
print(myfunc('SlseJbKWdOEuhB')) |
'''
@Coded by TSG, 2021
Problem:
FizzBuzz is a well known programming assignment, asked during interviews.
The given code solves the FizzBuzz problem and uses the words "Solo" and "Learn" instead of "Fizz" and "Buzz".
It takes an input n and outputs the numbers from 1 to n.
For each multiple of 3, print "Solo" inst... | """
@Coded by TSG, 2021
Problem:
FizzBuzz is a well known programming assignment, asked during interviews.
The given code solves the FizzBuzz problem and uses the words "Solo" and "Learn" instead of "Fizz" and "Buzz".
It takes an input n and outputs the numbers from 1 to n.
For each multiple of 3, print "Solo" inst... |
#
# PySNMP MIB module HP-ICF-MLD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-MLD-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:22:09 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, single_value_constraint, value_size_constraint, value_range_constraint) ... |
# Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of Sick Beard.
#
# Sick Beard is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of t... | __all__ = ['mainDB', 'cache'] |
def read_passphrases():
with open("day_04/input.txt", "r") as f:
return [line.split() for line in f.readlines()]
def part1():
return sum(len(phrase) == len(set(phrase)) for phrase in read_passphrases())
print(part1())
def anagram(passphrase):
return len(passphrase) == len(set("".join(sorted(ph... | def read_passphrases():
with open('day_04/input.txt', 'r') as f:
return [line.split() for line in f.readlines()]
def part1():
return sum((len(phrase) == len(set(phrase)) for phrase in read_passphrases()))
print(part1())
def anagram(passphrase):
return len(passphrase) == len(set((''.join(sorted(phr... |
n = int(input())
a = sorted(list(map(int, input().split())))
if n % 2 == 1 and a[0] != 0:
print(0)
exit()
for i in range(n % 2, n, 2):
if a[i] != a[i + 1] or a[i] != i + 1:
print(0)
exit()
print(2 ** (n // 2) % (10 ** 9 + 7))
| n = int(input())
a = sorted(list(map(int, input().split())))
if n % 2 == 1 and a[0] != 0:
print(0)
exit()
for i in range(n % 2, n, 2):
if a[i] != a[i + 1] or a[i] != i + 1:
print(0)
exit()
print(2 ** (n // 2) % (10 ** 9 + 7)) |
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
#--------------------------------------------------------------------------
# This is a placeholder file. It is deployed with inference only wheel.
pr... | print('An inference only version of ONNX Runtime is installed. Training functionalities are unavailable.') |
'''
Basic Info
'''
__version__ = '0.1'
| """
Basic Info
"""
__version__ = '0.1' |
def maprange( a, b, s):
(a1, a2), (b1, b2) = a, b
return b1 + ((s - a1) * (b2 - b1) / (a2 - a1))
for s in range(11):
print("%2g maps to %g" % (s, maprange( (0, 10), (-1, 0), s)))
| def maprange(a, b, s):
((a1, a2), (b1, b2)) = (a, b)
return b1 + (s - a1) * (b2 - b1) / (a2 - a1)
for s in range(11):
print('%2g maps to %g' % (s, maprange((0, 10), (-1, 0), s))) |
strings = {
'str NaN': 'NaN',
'str none': 'None',
'str true': 'True',
'str false': 'False',
'str 0': '0',
'str -1': '-1',
'str -1.5': '-1.5',
'str 0.42': '0.42',
'str .42': '.42',
'str 1.2E+9': '1.2E+9',
'str 1.2e8': '1.2e8',
'str 0xFF': '0xFF',
'str Inf..': 'Infinity... | strings = {'str NaN': 'NaN', 'str none': 'None', 'str true': 'True', 'str false': 'False', 'str 0': '0', 'str -1': '-1', 'str -1.5': '-1.5', 'str 0.42': '0.42', 'str .42': '.42', 'str 1.2E+9': '1.2E+9', 'str 1.2e8': '1.2e8', 'str 0xFF': '0xFF', 'str Inf..': 'Infinity', 'str empty': '', 'str space': ' ', 'str [Ob]': '[o... |
# coding: utf8
#!/usr/bin/python2
def directorymaker():
pass
| def directorymaker():
pass |
ZALORA_URLS = ['https://www.zalora.co.id/women/pakaian/atasan/?from=header']
def get_start_urls():
return ZALORA_URLS
| zalora_urls = ['https://www.zalora.co.id/women/pakaian/atasan/?from=header']
def get_start_urls():
return ZALORA_URLS |
name0_0_0_1_0_1_0 = None
name0_0_0_1_0_1_1 = None
name0_0_0_1_0_1_2 = None
name0_0_0_1_0_1_3 = None
name0_0_0_1_0_1_4 = None | name0_0_0_1_0_1_0 = None
name0_0_0_1_0_1_1 = None
name0_0_0_1_0_1_2 = None
name0_0_0_1_0_1_3 = None
name0_0_0_1_0_1_4 = None |
email_info = { 'recepient' : 'a.b@c.com',
'messages' : {'TOO_LOW' : 'Hi, the temperature is too low',
'TOO_HIGH' : 'Hi, the temperature is too high'
}
}
def DefineCoolingtype_limits(coolingType):
coolingtype_limits = { 'P... | email_info = {'recepient': 'a.b@c.com', 'messages': {'TOO_LOW': 'Hi, the temperature is too low', 'TOO_HIGH': 'Hi, the temperature is too high'}}
def define_coolingtype_limits(coolingType):
coolingtype_limits = {'PASSIVE_COOLING': {'lowerLimit': 0, 'upperLimit': 35}, 'HI_ACTIVE_COOLING': {'lowerLimit': 0, 'upperLi... |
# -*- coding: utf-8 -*-
# vim: set sw=4 ts=4 expandtab :
class ArgError(Exception):
def __init__(self, message):
if message == None:
self.message = 'node error'
else:
self.message = message
| class Argerror(Exception):
def __init__(self, message):
if message == None:
self.message = 'node error'
else:
self.message = message |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if head is None:
return head
l = 1
tail = head
while tail.next:
... | class Listnode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def rotate_right(self, head: ListNode, k: int) -> ListNode:
if head is None:
return head
l = 1
tail = head
while tail.next:
tail = tail.next
... |
class ApiException(Exception):
def __init__(self, response):
if response.status_code == 404:
self._rollbar_ignore = True
message = response.text
super(ApiException, self).__init__(message)
| class Apiexception(Exception):
def __init__(self, response):
if response.status_code == 404:
self._rollbar_ignore = True
message = response.text
super(ApiException, self).__init__(message) |
__author__ = 'Chirag'
x = {"Tom", 2.71, 36, 36} # is a set. REPETITION NOT ALLOWED
y = ["Tom", 2.71, 36, 36] # is a list. MUTABLE
print("x is a SET : ", x)
print("y is a LIST : ", y)
print()
#===========================================
# CREATE sets
s = {1,2,3,4,5} # direct declare
print(s)
s = set()
for i i... | __author__ = 'Chirag'
x = {'Tom', 2.71, 36, 36}
y = ['Tom', 2.71, 36, 36]
print('x is a SET : ', x)
print('y is a LIST : ', y)
print()
s = {1, 2, 3, 4, 5}
print(s)
s = set()
for i in range(1, 6):
s.add(i)
print(s)
s = set([x for x in range(1, 6)])
print(s)
print()
list1 = [1, 1, 2, 2, 3, 4, 5, 6, 1, 1]
print(f'l... |
# Python3 program to Merge Two Binary Trees
# Helper class that allocates a new node
# with the given data and None left and
# right pointers.
class newNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
# Given a binary tree, prints nodes
# in inorder
def inorder(node)... | class Newnode:
def __init__(self, data):
self.data = data
self.left = self.right = None
def inorder(node):
if not node:
return
inorder(node.left)
print(node.data, end=' ')
inorder(node.right)
def merge_trees(t1, t2):
if not t1:
return t2
if not t2:
... |
def find_lis(a):
T = [None]*len(a)
prev = [None]*len(a)
for i in range(len(a)):
T[i] = 1
prev[i] = -1
for j in range(i):
if a[j] <= a[i] and T[i]< T[j]+1:
T[i] = T[j]+1
prev[i] = j
longest =max(T)
i = 0
for i in range( ... | def find_lis(a):
t = [None] * len(a)
prev = [None] * len(a)
for i in range(len(a)):
T[i] = 1
prev[i] = -1
for j in range(i):
if a[j] <= a[i] and T[i] < T[j] + 1:
T[i] = T[j] + 1
prev[i] = j
longest = max(T)
i = 0
for i in range(... |
# Problem 3
# Largest prime factor
# The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143 ?
def is_prime(num):
if num == 1:
return False
i = 2
while i*i <= num:
if num % i == 0:
return False
i += 1
return True... | def is_prime(num):
if num == 1:
return False
i = 2
while i * i <= num:
if num % i == 0:
return False
i += 1
return True
huge = 600851475143
for x in reversed(range(1, 10000)):
if is_prime(x):
if huge % x == 0:
print(x) |
# defines a mutable class
class Mutable():
def __init__(self):
self.layers = []
def getGen(self):
gen = []
for layer in self.layers:
gen += layer.getWeights()
return gen
def mutateWith(self, lover):
genSelf = self.getGen()
genLover = lover.getG... | class Mutable:
def __init__(self):
self.layers = []
def get_gen(self):
gen = []
for layer in self.layers:
gen += layer.getWeights()
return gen
def mutate_with(self, lover):
gen_self = self.getGen()
gen_lover = lover.getGen()
self.setGen(... |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
__author__ = 'Florents Tselai'
REDIS_URI = '127.0.0.1'
REDIS_CAR_KEYSPACE = 'pycargr:car:{}'
SEARCH_BASE_URL = 'https://www.car.gr/classifieds/cars/'
CACHE_EXPIRE_IN = 24 * 3600
| __author__ = 'Florents Tselai'
redis_uri = '127.0.0.1'
redis_car_keyspace = 'pycargr:car:{}'
search_base_url = 'https://www.car.gr/classifieds/cars/'
cache_expire_in = 24 * 3600 |
a = 28
b = 1.5
c = 'hello'
d = True
e = None
print(a,b,c,d,e) | a = 28
b = 1.5
c = 'hello'
d = True
e = None
print(a, b, c, d, e) |
# -*- coding: utf-8 -*-
class Fila:
def __init__(self):
self.element = list()
def inserir(self,name):
self.element.append(name)
print(f'Inserindo o elemento {name}: ' + ' '.join(self.element))
def remover(self):
self.element.pop(0)
print(f'Removendo o primeiro elemento: ' + ' '.join(... | class Fila:
def __init__(self):
self.element = list()
def inserir(self, name):
self.element.append(name)
print(f'Inserindo o elemento {name}: ' + ' '.join(self.element))
def remover(self):
self.element.pop(0)
print(f'Removendo o primeiro elemento: ' + ' '.join(self... |
load("@bazel_skylib//lib:shell.bzl", "shell")
load("@bazel_skylib//lib:paths.bzl", "paths")
AsciidocInfo = provider(
doc = "Information about the asciidoc-generated files.",
fields = {
"primary_output_path": "Path of the primary output file beneath {resource_dir}.",
"resource_dir": "File for th... | load('@bazel_skylib//lib:shell.bzl', 'shell')
load('@bazel_skylib//lib:paths.bzl', 'paths')
asciidoc_info = provider(doc='Information about the asciidoc-generated files.', fields={'primary_output_path': 'Path of the primary output file beneath {resource_dir}.', 'resource_dir': 'File for the directory containing all of ... |
# return the keys of a dictionary
def keys(dictionary):
return dictionary.keys()
# return the values of a dictionary
def values(dictionary):
return dictionary.values()
# return the string representation of a dictionary
def dict_to_string(d):
return str(d)
# merge two dictionaries
def merge(d1, d2):
... | def keys(dictionary):
return dictionary.keys()
def values(dictionary):
return dictionary.values()
def dict_to_string(d):
return str(d)
def merge(d1, d2):
for (k, v) in d2.iteritems():
if k in d1.keys():
if type(v) is dict:
if type(d1[k]) is dict:
... |
class Data:
def __init__(self):
self.__dia = 0
self.__mes = 0
self.__ano = 0
def le_data(self):
self.dia = int(input('Digite o dia: '))
self.mes = int(input('Digite o mes: '))
self.ano = int(input('Digite o ano: '))
def formatada(self):
print(f'{self... | class Data:
def __init__(self):
self.__dia = 0
self.__mes = 0
self.__ano = 0
def le_data(self):
self.dia = int(input('Digite o dia: '))
self.mes = int(input('Digite o mes: '))
self.ano = int(input('Digite o ano: '))
def formatada(self):
print(f'{sel... |
#este es el ejercicio 3.1
def ejercicio01():
print ("Como saber si puedes votar por tu edad")
mensaje=""
#Ingreso de datos
edadP=int(input("ingrese la edad que tiene:"))
#Proceso
if edadP>=18:
mensaje="Usted tiene la edad necesaria para votar"
else:
mensaje="Usted no cumple con la edad minima para... | def ejercicio01():
print('Como saber si puedes votar por tu edad')
mensaje = ''
edad_p = int(input('ingrese la edad que tiene:'))
if edadP >= 18:
mensaje = 'Usted tiene la edad necesaria para votar'
else:
mensaje = 'Usted no cumple con la edad minima para votar'
print(mensaje)
ej... |
spam = {'name': 'Pooka', 'age': 5}
print("Before:")
print(spam)
#Traditional
if 'color' not in spam:
spam['color'] = 'black'
print("After:")
print(spam)
#With setDefault()
spam.setdefault("color", "white")
print(spam)
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count... | spam = {'name': 'Pooka', 'age': 5}
print('Before:')
print(spam)
if 'color' not in spam:
spam['color'] = 'black'
print('After:')
print(spam)
spam.setdefault('color', 'white')
print(spam)
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
cou... |
# Problem 2.
# Write the function subStringMatchExact. This function takes two arguments: a target string,
# and a key string. It should return a tuple of the starting points of matches of the key
# string in the target string, when indexing starts at 0. Complete the definition for
#
# def subStringMatchExact(target,ke... | def sub_string_match_exact(target, key):
position_list = []
begin_point = 0
temp_position = 0
while temp_position >= 0:
temp_position = target.find(key, begin_point)
if temp_position >= 0:
begin_point = temp_position + 1
position_list.append(temp_position)
pos... |
'''
Palindrome checker by python
'''
#Palindrome check for String inputs.
def palindrome (s):
r=s[::-1]
if(r==s):
print("Yes It is a palindrome")
else:
print("No It is not a palindrome")
s = input("Enter a String to check whether it is palindrome or not")
palin... | """
Palindrome checker by python
"""
def palindrome(s):
r = s[::-1]
if r == s:
print('Yes It is a palindrome')
else:
print('No It is not a palindrome')
s = input('Enter a String to check whether it is palindrome or not')
palindrome(s)
num = int(input('Enter a n... |
class BaseError(Exception):
...
class InternalError(BaseError):
_default = "An internal error has occurred."
def __init__(self):
super().__init__(self._default)
| class Baseerror(Exception):
...
class Internalerror(BaseError):
_default = 'An internal error has occurred.'
def __init__(self):
super().__init__(self._default) |
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
dis = 0
while x != 0 or y !=0:
x,resx = x //2, x%2
y,resy = y//2, y%2
if resx!= resy:
dis +=1
return dis
class Solution:
def hammingDistance(self, x: int, y: int) -> int... | class Solution:
def hamming_distance(self, x: int, y: int) -> int:
dis = 0
while x != 0 or y != 0:
(x, resx) = (x // 2, x % 2)
(y, resy) = (y // 2, y % 2)
if resx != resy:
dis += 1
return dis
class Solution:
def hamming_distance(self... |
QUERIES = {
'average_movies_per_user': (
'select avg(movies_watched) '
'from ( '
'select count(movie_id) as movies_watched '
'from views '
'group by user_id '
' ) as movies_count;'
),
'average_view_times': 'select avg(viewed_frame) from views;',
'top_20_... | queries = {'average_movies_per_user': 'select avg(movies_watched) from ( select count(movie_id) as movies_watched from views group by user_id ) as movies_count;', 'average_view_times': 'select avg(viewed_frame) from views;', 'top_20_users_by_total_view_time': 'select user_id, sum(viewed_frame) as view_time from view... |
# Logic: Write a program that find the maximum positive integer from user input.
# Algorithm: append all the numbers to a list and use the built-in method 'max()' to get the highest number in the list.
num_int = int(input("Input a number: "))
num_list = []
while num_int >= 0:
num_int = int(input("Input a number: ... | num_int = int(input('Input a number: '))
num_list = []
while num_int >= 0:
num_int = int(input('Input a number: '))
num_list.append(num_int)
print('The maximum is', max(num_list)) |
def _print_aspect_impl(target, ctx):
# Make sure the rule has a srcs attribute.
if hasattr(ctx.rule.attr, 'srcs'):
# Iterate through the files that make up the sources and
# print their paths.
for src in ctx.rule.attr.srcs:
for f in src.files.to_list():
print... | def _print_aspect_impl(target, ctx):
if hasattr(ctx.rule.attr, 'srcs'):
for src in ctx.rule.attr.srcs:
for f in src.files.to_list():
print(f.path)
return []
print_aspect = aspect(implementation=_print_aspect_impl, attr_aspects=['deps']) |
for t in range(int(input())):
n=int(input())
k = 3 + 5**(1/2)
s = str(int(k**n))
if len(s) <3:
s = "0"*(3-len(s)) +s
print("Case #{}: {}".format(t+1,s[-3:])) | for t in range(int(input())):
n = int(input())
k = 3 + 5 ** (1 / 2)
s = str(int(k ** n))
if len(s) < 3:
s = '0' * (3 - len(s)) + s
print('Case #{}: {}'.format(t + 1, s[-3:])) |
load(
"@rules_scala3//rules:providers.bzl",
_ScalaConfiguration = "ScalaConfiguration",
_ScalaRulePhase = "ScalaRulePhase",
)
def run_phases(ctx, phases):
phase_providers = [
p[_ScalaRulePhase]
for p in [ctx.attr.scala] + ctx.attr.plugins + ctx.attr._phase_providers
if _ScalaRul... | load('@rules_scala3//rules:providers.bzl', _ScalaConfiguration='ScalaConfiguration', _ScalaRulePhase='ScalaRulePhase')
def run_phases(ctx, phases):
phase_providers = [p[_ScalaRulePhase] for p in [ctx.attr.scala] + ctx.attr.plugins + ctx.attr._phase_providers if _ScalaRulePhase in p]
if phase_providers != []:
... |
# Copyright 2017-2020 EPAM Systems, Inc. (https://www.epam.com/)
#
# 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 appli... | class Sharemountmodel(object):
def __init__(self):
self.identifier = None
self.region_id = None
self.mount_root = None
self.mount_type = None
self.mount_options = None
@classmethod
def load(cls, json):
instance = share_mount_model()
if not json:
... |
X, Y, N = map(int, input().split())
grid = []
win = ''
for i in range(X):
grid.append([])
for j, val in enumerate(input().split()):
grid[i].append({'R':0,'B':0, 'dir':'none'})
if val != 'O':
grid[i][j][val] = 1
up, left, upleft, upright = 0, 0, 0, 0
... | (x, y, n) = map(int, input().split())
grid = []
win = ''
for i in range(X):
grid.append([])
for (j, val) in enumerate(input().split()):
grid[i].append({'R': 0, 'B': 0, 'dir': 'none'})
if val != 'O':
grid[i][j][val] = 1
(up, left, upleft, upright) = (0, 0, 0, 0)
... |
# Copied from https://rosettacode.org/wiki/Shortest_common_supersequence#Python
# Use the Longest Common Subsequence algorithm
def shortest_common_supersequence(a, b):
lcs = longest_common_subsequence(a, b)
scs = ""
# Consume lcs
while len(lcs) > 0:
if a[0]==lcs[0] and b[0]==lcs[0]:
# ... | def shortest_common_supersequence(a, b):
lcs = longest_common_subsequence(a, b)
scs = ''
while len(lcs) > 0:
if a[0] == lcs[0] and b[0] == lcs[0]:
scs += lcs[0]
lcs = lcs[1:]
a = a[1:]
b = b[1:]
elif a[0] == lcs[0]:
scs += b[0]
... |
def extract_tib_only(csv_dump):
lines = csv_dump.strip().split('\n') # cut dump in lines
lines = [l.split(',')[1] for l in lines] # only keep the text
lines = [lines[i] for i in range(0, len(lines), 2)] # only keep the tibetan
return ''.join(lines)
def extract_all(csv_dump):
lines = csv_dump.... | def extract_tib_only(csv_dump):
lines = csv_dump.strip().split('\n')
lines = [l.split(',')[1] for l in lines]
lines = [lines[i] for i in range(0, len(lines), 2)]
return ''.join(lines)
def extract_all(csv_dump):
lines = csv_dump.strip().split('\n')
lines = [l.split(',')[1] for l in lines]
re... |
# 26.05.2019
# Tuples vs Lists
# Tuples are read only
# Tuples have ( ) brackets
# Example with a List:
awesomeList= ['hello', 45, 'Marc', 89.4]
awesomeList[3] = 6
# List can be updated
print(awesomeList)
# now a tuple
awesomeTuple = ('MarcTuple', 1, 213.2, 'Hello')
print(awesomeTuple)
print(awesomeTuple[2])
... | awesome_list = ['hello', 45, 'Marc', 89.4]
awesomeList[3] = 6
print(awesomeList)
awesome_tuple = ('MarcTuple', 1, 213.2, 'Hello')
print(awesomeTuple)
print(awesomeTuple[2])
print(awesomeTuple[0][2:5])
var7 = awesomeTuple[0][2:5]
var8 = awesomeTuple[2]
print(var7 * 3)
print(var8 * 3) |
def dfCheckAvailability(df, baseTrackingMap):
#####
# step number -- iStep
bIStep = False if not ("iStep" in df.columns) else True
print("scan step number (iStep) availability: %s \n--" % str(bIStep))
#####
# Unix time -- epoch
bEpoch = False if not ("epoch" in df.columns) else True
... | def df_check_availability(df, baseTrackingMap):
b_i_step = False if not 'iStep' in df.columns else True
print('scan step number (iStep) availability: %s \n--' % str(bIStep))
b_epoch = False if not 'epoch' in df.columns else True
print('Unix time (epoch) availability: %s \n--' % str(bEpoch))
ls_gonio... |
list1 = [1, 7, 16, 11, 14, 19, 20, 18]
list2 = [85, 111, 117, 43, 104, 127, 117, 117, 33, 110, 99, 43, 72, 95, 85, 85, 94, 66, 120, 98, 79, 117, 68, 83, 64, 94, 39, 65, 73, 32, 65, 72, 51]
ans = ''
for i in range(len(list2)):
ans += chr(list2[i] ^ list1[i % len(list1)])
print(ans)
| list1 = [1, 7, 16, 11, 14, 19, 20, 18]
list2 = [85, 111, 117, 43, 104, 127, 117, 117, 33, 110, 99, 43, 72, 95, 85, 85, 94, 66, 120, 98, 79, 117, 68, 83, 64, 94, 39, 65, 73, 32, 65, 72, 51]
ans = ''
for i in range(len(list2)):
ans += chr(list2[i] ^ list1[i % len(list1)])
print(ans) |
f = open("Street_Centrelines.csv",'r')
def tup():
for v in f:
v = v.split(",")
t = (v[2], v[4], v[6], v[7])
print(t)
def maintenance():
h = dict()
for f2 in f:
f2 = f2.split(",")
if f2[12] not in h:
h[f2[12]] = 1
else:
h[f[12]] += 1
print(h)
... | f = open('Street_Centrelines.csv', 'r')
def tup():
for v in f:
v = v.split(',')
t = (v[2], v[4], v[6], v[7])
print(t)
def maintenance():
h = dict()
for f2 in f:
f2 = f2.split(',')
if f2[12] not in h:
h[f2[12]] = 1
else:
h[f[12]] += 1
... |
words = ['one', 'fish', 'two', 'fish', 'red', 'fish', 'blue', 'fish']
words2 = ['have', 'you', 'seen', 'a', 'blue', 'fish']
# what if we did the first example as a generator?
def get_word_lengths(word_list):
for word in word_list:
yield len(word)
for length in get_word_lengths(words):
print(length)
... | words = ['one', 'fish', 'two', 'fish', 'red', 'fish', 'blue', 'fish']
words2 = ['have', 'you', 'seen', 'a', 'blue', 'fish']
def get_word_lengths(word_list):
for word in word_list:
yield len(word)
for length in get_word_lengths(words):
print(length)
print('--------------------')
for length in (len(word)... |
# Data processing
with open('input') as f:
in_data = [line.rstrip() for line in f]
for i in range(25, len(in_data)):
pre_i = in_data[i-25:i]
summed_pair_found = False
for a in pre_i:
for b in pre_i:
if a != b:
if int(a)+int(b) == int(in_data[i]):
... | with open('input') as f:
in_data = [line.rstrip() for line in f]
for i in range(25, len(in_data)):
pre_i = in_data[i - 25:i]
summed_pair_found = False
for a in pre_i:
for b in pre_i:
if a != b:
if int(a) + int(b) == int(in_data[i]):
summed_pair_fou... |
#! python3
pessoas = [
{'nome': 'Pedro', 'idade': 11},
{'nome': 'Mariana', 'idade': 18},
{'nome': 'Arthur', 'idade': 26},
{'nome': 'Rebeca', 'idade': 6},
{'nome': 'Tiago', 'idade': 19},
{'nome': 'Gabriela', 'idade': 17},
]
menores = filter(lambda p: p['idade'] < 18, pessoas)
print(list(menores... | pessoas = [{'nome': 'Pedro', 'idade': 11}, {'nome': 'Mariana', 'idade': 18}, {'nome': 'Arthur', 'idade': 26}, {'nome': 'Rebeca', 'idade': 6}, {'nome': 'Tiago', 'idade': 19}, {'nome': 'Gabriela', 'idade': 17}]
menores = filter(lambda p: p['idade'] < 18, pessoas)
print(list(menores))
nome_maiorede6caracteres = filter(lam... |
line = input()
a, b = line.split()
a = int(a)
b = int(b)
print(a + b)
| line = input()
(a, b) = line.split()
a = int(a)
b = int(b)
print(a + b) |
employees_happiness = [int(happiness) for happiness in input().split()]
factor = int(input())
factored_employees_happiness = list(map(lambda h: h * factor, employees_happiness))
find_average_happiness = sum(factored_employees_happiness) / len(factored_employees_happiness)
happy_employees = [e for e in factored_employe... | employees_happiness = [int(happiness) for happiness in input().split()]
factor = int(input())
factored_employees_happiness = list(map(lambda h: h * factor, employees_happiness))
find_average_happiness = sum(factored_employees_happiness) / len(factored_employees_happiness)
happy_employees = [e for e in factored_employee... |
db_config = {
'user': 'user',
'password': 'password',
'host': 'host.com',
'port': 12345,
'database': 'db-name',
"autocommit": True
} | db_config = {'user': 'user', 'password': 'password', 'host': 'host.com', 'port': 12345, 'database': 'db-name', 'autocommit': True} |
VALUE_TYPES = {
'short', 'int', 'long',
'uchar', 'ushort', 'uint', 'ulong',
'bool', 'float', 'double', 'size_t',
'uint8', 'int8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64',
}
VALA_TYPES = VALUE_TYPES | {
'char', 'string', 'void*', 'void**', 'time_t',
}
VALA_ALIASES = {
'unsigne... | value_types = {'short', 'int', 'long', 'uchar', 'ushort', 'uint', 'ulong', 'bool', 'float', 'double', 'size_t', 'uint8', 'int8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64'}
vala_types = VALUE_TYPES | {'char', 'string', 'void*', 'void**', 'time_t'}
vala_aliases = {'unsigned int': 'uint', 'short unsigned int... |
num = float(input("Enter a Number: "))
if num > 0:
print("This is a Positive Number")
elif num == 0:
print("Zero")
else:
print("This is a Negative Number")
| num = float(input('Enter a Number: '))
if num > 0:
print('This is a Positive Number')
elif num == 0:
print('Zero')
else:
print('This is a Negative Number') |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class ContentType:
O365_CONNECTOR_CARD = "application/vnd.microsoft.teams.card.o365connector"
FILE_CONSENT_CARD = "application/vnd.microsoft.teams.card.file.consent"
FILE_DOWNLOAD_INFO = "application/vnd.microsof... | class Contenttype:
o365_connector_card = 'application/vnd.microsoft.teams.card.o365connector'
file_consent_card = 'application/vnd.microsoft.teams.card.file.consent'
file_download_info = 'application/vnd.microsoft.teams.file.download.info'
file_info_card = 'application/vnd.microsoft.teams.card.file.info... |
class Log:
lines = []
def __init__(self):
self.lines = []
def add(self, line):
self.lines.append(line)
def flush(self):
for line in self.lines:
print(line)
self.lines = []
battle_log = Log()
general_log = Log() | class Log:
lines = []
def __init__(self):
self.lines = []
def add(self, line):
self.lines.append(line)
def flush(self):
for line in self.lines:
print(line)
self.lines = []
battle_log = log()
general_log = log() |
num1 = 111
num2 = 222
num3 = 333333
num3 = 333
num4 = 4444
| num1 = 111
num2 = 222
num3 = 333333
num3 = 333
num4 = 4444 |
class MaterialPropertyMap:
def __init__(self):
self._lowCutoffs = []
self._highCutoffs = []
self._properties = []
def error_check(self, cutoff, conductivity):
if not isinstance(cutoff, tuple) or len(cutoff) != 2:
raise Exception("Cutoff has to be a tuple(int,int) spe... | class Materialpropertymap:
def __init__(self):
self._lowCutoffs = []
self._highCutoffs = []
self._properties = []
def error_check(self, cutoff, conductivity):
if not isinstance(cutoff, tuple) or len(cutoff) != 2:
raise exception('Cutoff has to be a tuple(int,int) sp... |
class EncodingApiCommunicator(object):
def __init__(self, inner):
self.inner = inner
def call(self, path, command, arguments=None, queries=None,
additional_queries=()):
path = path.encode()
command = command.encode()
arguments = self.transform_dictionary(argum... | class Encodingapicommunicator(object):
def __init__(self, inner):
self.inner = inner
def call(self, path, command, arguments=None, queries=None, additional_queries=()):
path = path.encode()
command = command.encode()
arguments = self.transform_dictionary(arguments or {})
... |
class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.age = 0
def full_name(self):
return self.first_name + " " + self.last_name
def record_info(self):
return self.last_name + ", " + self.first_name
perso... | class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.age = 0
def full_name(self):
return self.first_name + ' ' + self.last_name
def record_info(self):
return self.last_name + ', ' + self.first_name
person = p... |
class Node:
def __init__(self, data) -> None:
self.data = data
self.nextNode = None
class LinkedList:
def __init__(self):
self.head = None
self.numOfNodes = 0
def insert_new(self, data):
self.numOfNodes += 1
new_node = Node(data)
if not self.head:
... | class Node:
def __init__(self, data) -> None:
self.data = data
self.nextNode = None
class Linkedlist:
def __init__(self):
self.head = None
self.numOfNodes = 0
def insert_new(self, data):
self.numOfNodes += 1
new_node = node(data)
if not self.head:
... |
adventures = [
{"id": 1, "name": "Test Location"},
{"id": 12, "name": "The Sewer"},
{"id": 15, "name": "The Spooky Forest"},
{"id": 16, "name": "The Haiku Dungeon"},
{"id": 17, "name": "The Hidden Temple"},
{"id": 18, "name": "Degrassi Knoll"},
{"id": 19, "name": "The Limerick Dungeon"},
... | adventures = [{'id': 1, 'name': 'Test Location'}, {'id': 12, 'name': 'The Sewer'}, {'id': 15, 'name': 'The Spooky Forest'}, {'id': 16, 'name': 'The Haiku Dungeon'}, {'id': 17, 'name': 'The Hidden Temple'}, {'id': 18, 'name': 'Degrassi Knoll'}, {'id': 19, 'name': 'The Limerick Dungeon'}, {'id': 20, 'name': 'The "Fun" Ho... |
class Solution:
def amendSentence(self, s):
# code here
ans = ""
string = ""
for i in range(len(s)):
if 97 <= ord(s[i]) <= 122:
string += s[i]
else:
if string:
ans += string
ans += "... | class Solution:
def amend_sentence(self, s):
ans = ''
string = ''
for i in range(len(s)):
if 97 <= ord(s[i]) <= 122:
string += s[i]
else:
if string:
ans += string
ans += ' '
strin... |
# Copyright (c) 2021 Qualcomm Technologies, Inc.
# All Rights Reserved.
def _tb_advance_global_step(module):
if hasattr(module, 'global_step'):
module.global_step += 1
return module
def _tb_advance_token_counters(module, tensor, verbose=False):
token_count = getattr(module, 'tb_token_count', Non... | def _tb_advance_global_step(module):
if hasattr(module, 'global_step'):
module.global_step += 1
return module
def _tb_advance_token_counters(module, tensor, verbose=False):
token_count = getattr(module, 'tb_token_count', None)
if token_count is not None:
t = tensor.size(1)
if to... |
class ExpressionReader:
priorityComparision = ['=']
andOrComparision = ['OR']
operations = []
operations.extend(priorityComparision)
operations.extend(andOrComparision)
def read(expression):
lst = ExpressionReader.__split(expression)
#lst = ExpressionReader.__parsePriorityExpre... | class Expressionreader:
priority_comparision = ['=']
and_or_comparision = ['OR']
operations = []
operations.extend(priorityComparision)
operations.extend(andOrComparision)
def read(expression):
lst = ExpressionReader.__split(expression)
return lst
def __split(expression):
... |
'''A large FizzBuzz as an output using small FizzBuzz numbers.(FizzBuzz=FizBuz for better alignment
and make sure your output terminal covers the entire length of the screen to avoid automatic newlines)'''
# Author: @AmanMatrix
def iCheck(i):
if i%15==0:
i='FizBuz'
elif i%3==0:
i='Fizz'
eli... | """A large FizzBuzz as an output using small FizzBuzz numbers.(FizzBuzz=FizBuz for better alignment
and make sure your output terminal covers the entire length of the screen to avoid automatic newlines)"""
def i_check(i):
if i % 15 == 0:
i = 'FizBuz'
elif i % 3 == 0:
i = 'Fizz'
elif i % 5 ... |
i = 1.0
print(i)
print("Hello world!")
print(type(i))
a = "Hello"
print(type(a))
# print(a+i) <-Error!
a += "world!"
print(a)
print("this is string: {}, {}".format(3, "ala bala"))
print("pi = %f" % 3.14)
| i = 1.0
print(i)
print('Hello world!')
print(type(i))
a = 'Hello'
print(type(a))
a += 'world!'
print(a)
print('this is string: {}, {}'.format(3, 'ala bala'))
print('pi = %f' % 3.14) |
MACHINE_A = 'MachineA'
MACHINE_B = 'MachineB'
INIT = 'Init'
E_STOP = 'stop'
E_INCREASE = 'increase'
E_DECREASE = 'decrease'
| machine_a = 'MachineA'
machine_b = 'MachineB'
init = 'Init'
e_stop = 'stop'
e_increase = 'increase'
e_decrease = 'decrease' |
#=============================================================================
## Automatic Repository Version Generation Utility
## Author: Zhenyu Wu
## Revision 1: Apr 28. 2016 - Initial Implementation
#=============================================================================
__all__ = [ 'VersionLint' ]
| __all__ = ['VersionLint'] |
def fun(f): #string
# Some functions need zero or more
# arguements then we have to use
# *args & **kwargs
def wrapper(*args, **kwargs):
print("Start")
#print(string)
# to return the values that are passed
values = f(*args, **kwargs)
print("End")
return va... | def fun(f):
def wrapper(*args, **kwargs):
print('Start')
values = f(*args, **kwargs)
print('End')
return values
return wrapper
@fun
def fun2(x):
print('Funtion 2')
return x
@fun
def fun3():
print('Function 3')
a = fun2('a')
print()
print(A)
print()
fun3() |
symbols = [
'TSLA',
'GOOG',
'FB',
'NFLX',
'PFE',
'KO',
'AAPL',
'MSFT',
'DIS',
'UBER',
'AMZN',
'TWTR',
'SBUX',
'F',
'XOM',
'GFINBURO.MX',
'BIMBOA.MX',
'GFNORTEO.MX',
'TLEVISACPO.MX',
'AZTECACPO.MX',
'ALSEA.MX',
'ORBIA.MX',
'POSA... | symbols = ['TSLA', 'GOOG', 'FB', 'NFLX', 'PFE', 'KO', 'AAPL', 'MSFT', 'DIS', 'UBER', 'AMZN', 'TWTR', 'SBUX', 'F', 'XOM', 'GFINBURO.MX', 'BIMBOA.MX', 'GFNORTEO.MX', 'TLEVISACPO.MX', 'AZTECACPO.MX', 'ALSEA.MX', 'ORBIA.MX', 'POSADASA.MX', 'VOLARA.MX', 'LIVEPOLC-1.MX', 'AEROMEX.MX', 'WALMEX.MX', 'PE&OLES.MX', 'BBVA.MX', 'G... |
# ADD BINARY LEETCODE SOLUTION:
# creating a class.
class Solution(object):
# creating a function to solve the problem.
def addBinary(self, a, b):
# using the 'bin' function to convert each integer into its binary format.
sum = bin(int(a, 2) + int(b, 2))
# returning the va... | class Solution(object):
def add_binary(self, a, b):
sum = bin(int(a, 2) + int(b, 2))
return sum[2:] |
mywords = ['Krishna', 'Rameshwar Dass', 'Usha', 'Ramesh']
for w in mywords:
print(w, end='')
#Krishna Rameshwar Dass Usha Ramesh | mywords = ['Krishna', 'Rameshwar Dass', 'Usha', 'Ramesh']
for w in mywords:
print(w, end='') |
#!/usr/bin/env python3
SQL92_reserved = [
"ABSOLUTE", "ACTION", "ADD", "ALL", "ALLOCATE", "ALTER", "AND", "ANY", "ARE", "AS", "ASC", "ASSERTION", "AT", "AUTHORIZATION", "AVG",
"BEGIN", "BETWEEN", "BIT", "BIT_LENGTH", "BOTH", "BY",
"CASCADE", "CASCADED", "CASE", "CAST", "CATALOG", "CHAR", "CHARACTER", "CHAR... | sql92_reserved = ['ABSOLUTE', 'ACTION', 'ADD', 'ALL', 'ALLOCATE', 'ALTER', 'AND', 'ANY', 'ARE', 'AS', 'ASC', 'ASSERTION', 'AT', 'AUTHORIZATION', 'AVG', 'BEGIN', 'BETWEEN', 'BIT', 'BIT_LENGTH', 'BOTH', 'BY', 'CASCADE', 'CASCADED', 'CASE', 'CAST', 'CATALOG', 'CHAR', 'CHARACTER', 'CHAR_LENGTH', 'CHARACTER_LENGTH', 'CHECK'... |
def can_build(env, platform):
return True
def configure(env):
pass
def is_enabled():
# Disabled by default being experimental at the moment.
# Enable manually with `module_gdscript_transpiler_enabled=yes` option.
return False
| def can_build(env, platform):
return True
def configure(env):
pass
def is_enabled():
return False |
class PERIOD:
DAILY = "daily"
WEEKLY = "weekly"
MONTHLY = "monthly"
# Converting BYTES to KB, MB, GB
BYTES_TO_KBYTES = 1024
BYTES_TO_MBYTES = 1048576
BYTES_TO_GBYTES = 1073741824
| class Period:
daily = 'daily'
weekly = 'weekly'
monthly = 'monthly'
bytes_to_kbytes = 1024
bytes_to_mbytes = 1048576
bytes_to_gbytes = 1073741824 |
class MyClass:
'''This is the docstring for this class'''
def __init__(self):
# setup per-instance variables
self.x = 1
self.y = 2
self.z = 3
class MySecondClass:
'''This is the docstring for this second class'''
def __init__(self):
# setup per-instance varia... | class Myclass:
"""This is the docstring for this class"""
def __init__(self):
self.x = 1
self.y = 2
self.z = 3
class Mysecondclass:
"""This is the docstring for this second class"""
def __init__(self):
self.p = 1
self.d = 2
self.q = 3 |
# coding: utf8
class InvalidUnitToDXAException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Unit(object):
@classmethod
def to_dxa(cls, val):
if len(val) < 2:
return 0
else:
unit = ... | class Invalidunittodxaexception(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Unit(object):
@classmethod
def to_dxa(cls, val):
if len(val) < 2:
return 0
else:
unit = val[-2:]
... |
def count(word, letter):
count = 0
for i in word:
if i == letter:
count = count + 1
return count
word = input('Enter a word:')
letter = input('Enter a letter to count in word:')
print("There are {} {}'s in your word".format(count(word,letter), letter))
| def count(word, letter):
count = 0
for i in word:
if i == letter:
count = count + 1
return count
word = input('Enter a word:')
letter = input('Enter a letter to count in word:')
print("There are {} {}'s in your word".format(count(word, letter), letter)) |
class Square:
def __init__(self, side):
self.side = side
def perimeter(self):
return self.side * 4
def area(self):
return self.side ** 2
pass
class Rectangle:
def __init__(self, width, height):
self.width, self.height = width, height
def perimeter(self):
... | class Square:
def __init__(self, side):
self.side = side
def perimeter(self):
return self.side * 4
def area(self):
return self.side ** 2
pass
class Rectangle:
def __init__(self, width, height):
(self.width, self.height) = (width, height)
def perimeter(self):... |
def first_function(values):
''' (list of int) -> NoneType
'''
for i in range(len(values)):
if values[i] % 2 == 1:
values[i] += 1
def second_function(value):
''' (int) -> int
'''
if value % 2 == 1:
value += 1
return value
def snippet_1():
a = [1, 2,... | def first_function(values):
""" (list of int) -> NoneType
"""
for i in range(len(values)):
if values[i] % 2 == 1:
values[i] += 1
def second_function(value):
""" (int) -> int
"""
if value % 2 == 1:
value += 1
return value
def snippet_1():
a = [1, 2, 3]
b ... |
# -*- coding: utf-8 -*-
vagrant = 'vagrant'
def up():
return '{} up'.format(vagrant)
def ssh():
return '{} ssh'.format(vagrant)
def suspend():
return '{} suspend'.format(vagrant)
def status():
return '{} status'.format(vagrant)
def halt():
return '{} halt'.format(vagrant)
def destroy(fo... | vagrant = 'vagrant'
def up():
return '{} up'.format(vagrant)
def ssh():
return '{} ssh'.format(vagrant)
def suspend():
return '{} suspend'.format(vagrant)
def status():
return '{} status'.format(vagrant)
def halt():
return '{} halt'.format(vagrant)
def destroy(force=False):
options = ''
... |
def split_block (string:str, seps:(str, str)) -> str:
_, content = string.split (seps[0])
block, _ = content.split (seps[1])
return block
def is_not_empty (value):
return value != ''
def contens_colons (value:str) -> bool:
return value.count(":") == 0
content = ""
with open ("examples/add.asm") ... | def split_block(string: str, seps: (str, str)) -> str:
(_, content) = string.split(seps[0])
(block, _) = content.split(seps[1])
return block
def is_not_empty(value):
return value != ''
def contens_colons(value: str) -> bool:
return value.count(':') == 0
content = ''
with open('examples/add.asm') a... |
class Solution:
# @return an integer
def threeSumClosest(self, num, target):
num.sort()
res = sum(num[:3])
if res > target:
diff = res-target
elif res < target:
diff = target-res
else:
return res
n = len(num)
for i in x... | class Solution:
def three_sum_closest(self, num, target):
num.sort()
res = sum(num[:3])
if res > target:
diff = res - target
elif res < target:
diff = target - res
else:
return res
n = len(num)
for i in xrange(n):
... |
'''
Prompt:
Given two strings, s1 and s2, write code to check if s2 is a rotation of s1.
(e.g., "waterbottle" is a rotation of "erbottlewat").
Follow up:
What if you could use one call of a helper method isSubstring?
'''
# Time: O(n), Space: O(n)
def isStringRotation(s1, s2):
if len(s1) != len(s2):
return False... | """
Prompt:
Given two strings, s1 and s2, write code to check if s2 is a rotation of s1.
(e.g., "waterbottle" is a rotation of "erbottlewat").
Follow up:
What if you could use one call of a helper method isSubstring?
"""
def is_string_rotation(s1, s2):
if len(s1) != len(s2):
return False
str_length = ... |
# Instantiate Cache information
n = 10
cache = [None] * (n + 1)
def fib_dyn(n):
# Base Case
if n == 0 or n == 1:
return n
# Check cache
if cache[n] != None:
return cache[n]
# Keep setting cache
cache[n] = fib_dyn(n-1) + fib_dyn(n-2)
ret... | n = 10
cache = [None] * (n + 1)
def fib_dyn(n):
if n == 0 or n == 1:
return n
if cache[n] != None:
return cache[n]
cache[n] = fib_dyn(n - 1) + fib_dyn(n - 2)
return cache[n]
fib_dyn(10) |
# -*- coding: utf-8 -*-
# TODO: datetime support
###
### DO NOT CHANGE THIS FILE
###
### The code is auto generated, your change will be overwritten by
### code generating.
###
DefinitionsNewrun = {'required': ['name'], 'type': 'object', 'properties': {'count': {'type': 'boolean'}, 'prePro': {'type': 'boolean'}, ... | definitions_newrun = {'required': ['name'], 'type': 'object', 'properties': {'count': {'type': 'boolean'}, 'prePro': {'type': 'boolean'}, 'fqRegex': {'type': 'string'}, 'star': {'type': 'boolean'}, 'name': {'type': 'string'}, 'fastqc': {'type': 'boolean'}, 'genomeInddex': {'type': 'string'}, 'gtfFile': {'type': 'string... |
class Callback(object):
def __init__(self, fire_rate=1.0, fire_interval=None):
self.FireRate = fire_rate
self.NextFire = self.FireInterval = fire_interval
self.FireLevel = 0.0
self.FireCount = 0
def __call__(self, event, *params, **args):
self.FireCount += 1... | class Callback(object):
def __init__(self, fire_rate=1.0, fire_interval=None):
self.FireRate = fire_rate
self.NextFire = self.FireInterval = fire_interval
self.FireLevel = 0.0
self.FireCount = 0
def __call__(self, event, *params, **args):
self.FireCount += 1
sel... |
class A(Exception):
def __init__(s, err, *args):
s.err = err
s.d = 2323
@property
def message(s):
return 'kawabunga'
def __str__(s):
return s.message
class B(A):
pass
try:
raise A('hh', 89)
except B as e:
print(1) | class A(Exception):
def __init__(s, err, *args):
s.err = err
s.d = 2323
@property
def message(s):
return 'kawabunga'
def __str__(s):
return s.message
class B(A):
pass
try:
raise a('hh', 89)
except B as e:
print(1) |
string = input()
for i in range(len(string)):
emoticon = ''
if string[i] == ':':
emoticon += string[i] + string[i + 1]
print(emoticon)
| string = input()
for i in range(len(string)):
emoticon = ''
if string[i] == ':':
emoticon += string[i] + string[i + 1]
print(emoticon) |
# -*- encoding: utf-8 -*-
#######################################################################################################################
# DESCRIPTION:
#######################################################################################################################
# TODO
#############################... | class Cnf:
def __init__(self):
self.clauses = []
self.variables = []
self.map = {}
def add(self, clause):
for term in clause.terms:
name = term.name
if not name in self.map:
self.map[name] = len(self.variables)
self.variab... |
'''
For a string sequence, a string word is k-repeating if word
concatenated k times is a substring of sequence. The word's
maximum k-repeating value is the highest value k where word
is k-repeating in sequence. If word is not a substring of
sequence, word's maximum k-repeating value is 0.
... | """
For a string sequence, a string word is k-repeating if word
concatenated k times is a substring of sequence. The word's
maximum k-repeating value is the highest value k where word
is k-repeating in sequence. If word is not a substring of
sequence, word's maximum k-repeating value is 0.
... |
altPulo, qntdCano = map(int, input().split())
canos = list(map(int, input().split()))
atual = canos.pop(0)
for cano in canos:
if max([cano, atual]) - min([cano, atual]) > altPulo:
print('GAME OVER')
quit()
atual = cano
print('YOU WIN')
| (alt_pulo, qntd_cano) = map(int, input().split())
canos = list(map(int, input().split()))
atual = canos.pop(0)
for cano in canos:
if max([cano, atual]) - min([cano, atual]) > altPulo:
print('GAME OVER')
quit()
atual = cano
print('YOU WIN') |
# this graph to check the algorithm
graph={
'S':['B','D','A'],
'A':['C'],
'B':['D'],
'C':['G','D'],
'S':['G'],
}
#function of BFS
def BFS(graph,start,goal):
Visited=[]
queue=[[start]]
while queue:
path=queue.pop(0)
node=path[-1]
if node in Visited:
... | graph = {'S': ['B', 'D', 'A'], 'A': ['C'], 'B': ['D'], 'C': ['G', 'D'], 'S': ['G']}
def bfs(graph, start, goal):
visited = []
queue = [[start]]
while queue:
path = queue.pop(0)
node = path[-1]
if node in Visited:
continue
Visited.append(node)
if node == g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.