content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#show function logs all attempts on console and in out.txt file
out = open("out.txt", 'w+')
def show(line):
li = ""
for i in line:
for j in i:
li += str(j) + " "
li += "\n"
print(li)
out.write(li)
out.write("\n")
| out = open('out.txt', 'w+')
def show(line):
li = ''
for i in line:
for j in i:
li += str(j) + ' '
li += '\n'
print(li)
out.write(li)
out.write('\n') |
print()
print("-- RELATIONS ------------------------------")
print()
print("GRAPH 1:\n0 0 0\n0 0 0\n0 0 0")
g1 = Graph(3)
print("REFLEXIVITA: " + str(is_reflexive(g1)) + " -> spravna odpoved: False")
print("SYMETRIE: " + str(is_symmetric(g1)) + " -> spravna odpoved: True")
print("ANTISYMETRIE: " + str(is... | print()
print('-- RELATIONS ------------------------------')
print()
print('GRAPH 1:\n0 0 0\n0 0 0\n0 0 0')
g1 = graph(3)
print('REFLEXIVITA: ' + str(is_reflexive(g1)) + ' -> spravna odpoved: False')
print('SYMETRIE: ' + str(is_symmetric(g1)) + ' -> spravna odpoved: True')
print('ANTISYMETRIE: ' + str(is_... |
# Task 03. Statistics
def add_to_dict(product: str, quantity: int):
if product not in stock:
stock[product] = quantity
else:
stock[product] += quantity
cmd = input()
stock = {}
while not cmd == "statistics":
key = cmd.split(': ')[0]
value = cmd.split(': ')[1]
add_to_dict(key, int(... | def add_to_dict(product: str, quantity: int):
if product not in stock:
stock[product] = quantity
else:
stock[product] += quantity
cmd = input()
stock = {}
while not cmd == 'statistics':
key = cmd.split(': ')[0]
value = cmd.split(': ')[1]
add_to_dict(key, int(value))
cmd = input()... |
'''
This problem was asked by Stripe.
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the input [3, 4, -1... | """
This problem was asked by Stripe.
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the input [3, 4, -1... |
#Main class
class Characters:
def __init__(self,
name,
lastname,
age,
hp,
title,
language,
race,
weakness
):
# instance variable unique to each instance
... | class Characters:
def __init__(self, name, lastname, age, hp, title, language, race, weakness):
self.__name = name
self.__lastname = lastname
self.__age = age
self.__hp = hp
self.__title = title
self.__race = race
self.__weakness = weakness
self.__lan... |
n = int(input())
b = list(map(int, input().split(' ')))
x = [0]
a = []
a.append(b[0])
x.append(a[0])
i = 1
while i < n:
a.append(b[i]+x[i])
if a[i] > x[i]:
x.append(a[i])
else:
x.append(x[i])
i += 1
str_a = [str(ele) for ele in a]
print(' '.join(str_a)) | n = int(input())
b = list(map(int, input().split(' ')))
x = [0]
a = []
a.append(b[0])
x.append(a[0])
i = 1
while i < n:
a.append(b[i] + x[i])
if a[i] > x[i]:
x.append(a[i])
else:
x.append(x[i])
i += 1
str_a = [str(ele) for ele in a]
print(' '.join(str_a)) |
def valida(digitos):
# digitos = [4,5,7,5,0,8,0,0,0]
# digitos = [11] * 9
i = 1
soma = 0
for x in digitos:
soma = soma +(i * x)
i += 1
return bool( soma % 11 == 0)
print(valida(1)) | def valida(digitos):
i = 1
soma = 0
for x in digitos:
soma = soma + i * x
i += 1
return bool(soma % 11 == 0)
print(valida(1)) |
{
"targets": [{
"target_name": "OpenSSL_EVP_BytesToKey",
"sources": [
"./test/main.cc",
],
"cflags": [
"-Wall",
"-Wno-maybe-uninitialized",
"-Wno-uninitialized",
"-Wno-unused-function",
"-Wextra"
],
"cflags_cc+": [
"-std=c++0x"
],
"include_dirs... | {'targets': [{'target_name': 'OpenSSL_EVP_BytesToKey', 'sources': ['./test/main.cc'], 'cflags': ['-Wall', '-Wno-maybe-uninitialized', '-Wno-uninitialized', '-Wno-unused-function', '-Wextra'], 'cflags_cc+': ['-std=c++0x'], 'include_dirs': ['/usr/local/include', '<!(node -e "require(\'nan\')")'], 'conditions': [["OS=='ma... |
def catalan_number(n):
nm = dm = 1
for k in range(2, n+1):
nm, dm = ( nm*(n+k), dm*k )
return nm/dm
print([catalan_number(n) for n in range(1, 16)])
[1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845]
| def catalan_number(n):
nm = dm = 1
for k in range(2, n + 1):
(nm, dm) = (nm * (n + k), dm * k)
return nm / dm
print([catalan_number(n) for n in range(1, 16)])
[1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845] |
NAME = 'weather.py'
ORIGINAL_AUTHORS = [
'Gabriele Ron'
]
ABOUT = '''
A plugin to get the weather of a location
'''
COMMANDS = '''
>>> .weather <city> <country code>
returns the weather
'''
WEBSITE = ''
| name = 'weather.py'
original_authors = ['Gabriele Ron']
about = '\nA plugin to get the weather of a location\n'
commands = '\n>>> .weather <city> <country code>\nreturns the weather\n'
website = '' |
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkList:
def __init__(self, value):
node = Node(value)
self.head = node
self.tail = node
self.length = 1
def append(self, value):
node = Node(value)
if self.le... | class Node:
def __init__(self, value):
self.value = value
self.next = None
class Linklist:
def __init__(self, value):
node = node(value)
self.head = node
self.tail = node
self.length = 1
def append(self, value):
node = node(value)
if self.l... |
class node:
def __init__(self,val):
self.val = val
self.next = None
self.prev = None
class mylinkedlist:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def get(self,index):
if index < 0 or index >= self.size:
... | class Node:
def __init__(self, val):
self.val = val
self.next = None
self.prev = None
class Mylinkedlist:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def get(self, index):
if index < 0 or index >= self.size:
retu... |
#declaring variable as string
phrase = str(input('Type a phrase: '))
#saving the phrase in lowercase
phrase = phrase.lower()
#presenting amount of lettters 'a'
print('Amount of letters "a": ', phrase.count('a'))
#presenting the position of firt 'a'
print('Firt "A" in position: ', phrase.find('a'))
#presenting the posi... | phrase = str(input('Type a phrase: '))
phrase = phrase.lower()
print('Amount of letters "a": ', phrase.count('a'))
print('Firt "A" in position: ', phrase.find('a'))
print('Last "A" in postion: ', phrase.rfind('a')) |
{
"targets": [
{
"target_name": "json",
"product_name": "json",
"variables": {
"json_dir%": "../"
},
'cflags!': [ '-fno-exceptions' ],
'cflags_cc!': [ '-fno-exceptions' ],
'conditions': [
['OS=="m... | {'targets': [{'target_name': 'json', 'product_name': 'json', 'variables': {'json_dir%': '../'}, 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exceptions'], 'conditions': [['OS=="mac"', {'xcode_settings': {'GCC_ENABLE_CPP_EXCEPTIONS': 'YES'}}]], 'type': 'static_library', 'include_dirs': ['<(json_dir)/', '<(json_d... |
todos = []
impar = []
par = []
while True:
todos.append(int(input('Digite um valor: ')))
soun = str(input('Quer adicionar mais ? [S/N] ')).strip()[0]
if soun in 'Nn':
break
for n in todos:
if n % 2 == 0:
par.append(n)
for v in todos:
if v % 2 != 0:
impar.append(v)
print('=' *... | todos = []
impar = []
par = []
while True:
todos.append(int(input('Digite um valor: ')))
soun = str(input('Quer adicionar mais ? [S/N] ')).strip()[0]
if soun in 'Nn':
break
for n in todos:
if n % 2 == 0:
par.append(n)
for v in todos:
if v % 2 != 0:
impar.append(v)
print('=' *... |
def print_formatted(N):
width = len(bin(N)[2:])
for i in range(1, N + 1):
print(' '.join(map(lambda x: x.rjust(width), [str(i), oct(i)[2:], hex(i)[2:].upper(), bin(i)[2:]])))
if __name__ == '__main__':
n = int(input())
print_formatted(n) | def print_formatted(N):
width = len(bin(N)[2:])
for i in range(1, N + 1):
print(' '.join(map(lambda x: x.rjust(width), [str(i), oct(i)[2:], hex(i)[2:].upper(), bin(i)[2:]])))
if __name__ == '__main__':
n = int(input())
print_formatted(n) |
class File:
def __init__(self, hash, realName, extension, url):
self.hash = hash
self.realName = realName
self.extension = extension
self.url = url
@staticmethod
def from_DB(record):
return File(record[0], record[1], record[2], record[3])
| class File:
def __init__(self, hash, realName, extension, url):
self.hash = hash
self.realName = realName
self.extension = extension
self.url = url
@staticmethod
def from_db(record):
return file(record[0], record[1], record[2], record[3]) |
class Vertex:
def __init__(self, id):
self.id = id
self.edges = set()
def outgoing_edges(self):
for edge in self.edges:
successor = edge.get_successor(self)
if successor is not None:
yield edge
| class Vertex:
def __init__(self, id):
self.id = id
self.edges = set()
def outgoing_edges(self):
for edge in self.edges:
successor = edge.get_successor(self)
if successor is not None:
yield edge |
# -*- coding: UTF-8 -*-
light = input('input a light')
if light == 'red':
print('GoGoGO')
elif light == 'green':
print('stop')
| light = input('input a light')
if light == 'red':
print('GoGoGO')
elif light == 'green':
print('stop') |
'''
Resources/other/contact
_______________________
Contact information for XL Discoverer.
:copyright: (c) 2015 The Regents of the University of California.
:license: GNU GPL, see licenses/GNU GPLv3.txt for more details.
'''
__all__ = [
'AUTHOR',
'AUTHOR_EMAIL',
'MAINTAINER',
'MAI... | """
Resources/other/contact
_______________________
Contact information for XL Discoverer.
:copyright: (c) 2015 The Regents of the University of California.
:license: GNU GPL, see licenses/GNU GPLv3.txt for more details.
"""
__all__ = ['AUTHOR', 'AUTHOR_EMAIL', 'MAINTAINER', 'MAINTAINER_EMAIL']
au... |
# Binary Tree Level Order Traversal - Breadth First Search 1
# Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
... | class Treenode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def level_traverse(self, node, level):
if level == len(self.levels):
self.levels.append([])
self.levels[level].append(node.v... |
# Seasons.py -- Hass helper python_script to turn a Climate entity into a smart
# thermostat, with support for multiple thermostats each having their own
# schedule.
#
# INPUTS:
# * climate_unit (required): The Climate entity to be controlled
# * global_mode (required): an entity whose state is the desired global clima... | seasons = {('Cold Winter', 'climate.first_floor_heat'): [{'title': 'Ecobee schedule', 'operation': 'heat'}], ('Cold Winter', 'climate.second_floor'): [{'title': 'Ecobee schedule', 'operation': 'heat'}], ('Cold Winter', 'climate.loft_heat'): [{'title': 'Ecobee schedule', 'operation': 'heat'}], ('Winter', 'climate.first_... |
# --------------
# Code starts here
class_1=['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio']
class_2=['Hilary Mason','Carla Gentry','Corinna Cortes']
new_class= class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Carla Gentry')
print(new_class)
# ... | class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio']
class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Carla Gentry')
print(new_class)
courses = {'Math': 65, 'English... |
def cria(linhas, colunas):
return {'linhas': linhas, 'colunas': colunas, 'dados': {}}
#[[0,3],[1,2]]
def criaLst(matriz_lst):
linhas = len(matriz_lst) #2
colunas = len(matriz_lst[0]) #2
dados = {} #{(0,1): 3, (1,0):1, (1,1):2}
for i in range(linhas):
for j in range(colunas):
if... | def cria(linhas, colunas):
return {'linhas': linhas, 'colunas': colunas, 'dados': {}}
def cria_lst(matriz_lst):
linhas = len(matriz_lst)
colunas = len(matriz_lst[0])
dados = {}
for i in range(linhas):
for j in range(colunas):
if matriz_lst[i][j] != 0:
dados[i, j]... |
# -*- coding: utf-8 -*-
def main():
n, l = list(map(int, input().split()))
s = input()
tab_count = 1
crash_count = 0
for si in s:
if si == '+':
tab_count += 1
else:
tab_count -= 1
if tab_count > l:
crash_count += 1
... | def main():
(n, l) = list(map(int, input().split()))
s = input()
tab_count = 1
crash_count = 0
for si in s:
if si == '+':
tab_count += 1
else:
tab_count -= 1
if tab_count > l:
crash_count += 1
tab_count = 1
print(crash_count... |
#Autor Manuela Garcia Monsalve
# 28 septiembre 2018
#Esta es la super clase Vehiculo donde se encuentran los atributos de marca, modelo y color que seran
#heredados para las subclases
class Vehiculo():
def __init__(self,marca,color, modelo): #Se generan los atributos para poder ser heredados
self.marca = ... | class Vehiculo:
def __init__(self, marca, color, modelo):
self.marca = marca
self.color = color
self.modelo = modelo
def prender(self):
pass
def arrancar(self):
pass
def apagar(self):
pass |
def cookie(x):
if isinstance(x, str):
cookie_eater = "Zach"
elif isinstance(x, int) or isinstance(x, float):
cookie_eater = "Monica"
else:
cookie_eater = "the dog"
if x == True or x == False:
cookie_eater = "the dog"
return "Who ate the last cookie? It was %s!" % cookie_eater
print(cookie("Ryan... | def cookie(x):
if isinstance(x, str):
cookie_eater = 'Zach'
elif isinstance(x, int) or isinstance(x, float):
cookie_eater = 'Monica'
else:
cookie_eater = 'the dog'
if x == True or x == False:
cookie_eater = 'the dog'
return 'Who ate the last cookie? It was %s!' % cook... |
result = ''
for line in DATA:
result += line + '\n'
| result = ''
for line in DATA:
result += line + '\n' |
class Solution:
def maximalRectangle(self, matrix: List[List[str]]) -> int:
dp = [[0] * len(matrix[0]) for i in range(len(matrix))]
for row_i, row in enumerate(matrix):
for col_i, col in enumerate(row):
if col == "0":
dp[row_i][col_i] = 0
... | class Solution:
def maximal_rectangle(self, matrix: List[List[str]]) -> int:
dp = [[0] * len(matrix[0]) for i in range(len(matrix))]
for (row_i, row) in enumerate(matrix):
for (col_i, col) in enumerate(row):
if col == '0':
dp[row_i][col_i] = 0
... |
# variables 4
a = "abc"
b = 1
c = 1.5
d = True
e = 3 + 5j
print("a:", type(a), "b", type(b), "c:", type(c),
"d:", type(d), "e:", type(e))
| a = 'abc'
b = 1
c = 1.5
d = True
e = 3 + 5j
print('a:', type(a), 'b', type(b), 'c:', type(c), 'd:', type(d), 'e:', type(e)) |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold(x1, y1, x2, y2, r1, r2):
distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)
radSumSq = (r1 + r2) * (r1 + ... | def f_gold(x1, y1, x2, y2, r1, r2):
dist_sq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)
rad_sum_sq = (r1 + r2) * (r1 + r2)
if distSq == radSumSq:
return 1
elif distSq > radSumSq:
return -1
else:
return 0
if __name__ == '__main__':
param = [(11, 36, 62, 64, 50, 4), (87... |
#!/usr/bin/env python
# Task 1
instructions = list()
with open("./dec_2/dec2_input.txt") as f:
instructions = [x for x in f.read().split('\n')]
start_position = [0, 0]
for direction in instructions:
info = direction.split(' ')
vector, length = info[0], int(info[1])
if vector == "forward":
star... | instructions = list()
with open('./dec_2/dec2_input.txt') as f:
instructions = [x for x in f.read().split('\n')]
start_position = [0, 0]
for direction in instructions:
info = direction.split(' ')
(vector, length) = (info[0], int(info[1]))
if vector == 'forward':
start_position[0] += length
e... |
a = input()
s = [int(x) for x in input().split()]
buff = 0
load = False
for num in s:
if num - buff < 0:
load = True
if num - buff >= 30:
print(buff+30)
break
else:
if load:
buff += 5
load = False
else:
buff = num + 5
else:
prin... | a = input()
s = [int(x) for x in input().split()]
buff = 0
load = False
for num in s:
if num - buff < 0:
load = True
if num - buff >= 30:
print(buff + 30)
break
elif load:
buff += 5
load = False
else:
buff = num + 5
else:
print(buff + 30) |
class OmnipyConfiguration(object):
def __init__(self):
self.mqtt_host = ""
self.mqtt_port = 1883
self.mqtt_clientid = ""
self.mqtt_command_topic = ""
self.mqtt_response_topic = ""
self.mqtt_rate_topic = ""
| class Omnipyconfiguration(object):
def __init__(self):
self.mqtt_host = ''
self.mqtt_port = 1883
self.mqtt_clientid = ''
self.mqtt_command_topic = ''
self.mqtt_response_topic = ''
self.mqtt_rate_topic = '' |
def solution(N):
num = bin(N)[2:].split('1')
if len(num[1:-1]) == 0:
return 0
return len(max(num[1:-1], key=lambda x: len(x)))
| def solution(N):
num = bin(N)[2:].split('1')
if len(num[1:-1]) == 0:
return 0
return len(max(num[1:-1], key=lambda x: len(x))) |
a = int(input())
b = int ( input ( ) )
a = int(input())
| a = int(input())
b = int(input())
a = int(input()) |
word = 'Python'
word[0] = 'M'
| word = 'Python'
word[0] = 'M' |
#Operator Name Example
# > Greater than x > y
x = 5
y = 3
print(x > y) # true
| x = 5
y = 3
print(x > y) |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( x , y , z ) :
c = 0
while ( x and y and z ) :
x = x - 1
y = y - 1
z = z - 1
... | def f_gold(x, y, z):
c = 0
while x and y and z:
x = x - 1
y = y - 1
z = z - 1
c = c + 1
return c
if __name__ == '__main__':
param = [(23, 98, 25), (87, 55, 94), (35, 90, 29), (25, 9, 41), (93, 22, 39), (52, 42, 96), (95, 88, 26), (91, 64, 51), (75, 1, 6), (96, 44, 76)]
... |
# Voting with delegation.
# Information about voters
voters: public({
# weight is accumulated by delegation
weight: num,
# if true, that person already voted
voted: bool,
# person delegated to
delegate: address,
# index of the voted proposal
vote: num
}[address])
# This is a type for a... | voters: public({weight: num, voted: bool, delegate: address, vote: num}[address])
proposals: public({name: bytes32, vote_count: num}[num])
voter_count: public(num)
chairperson: public(address)
def __init__(_proposalNames: bytes32[5]):
self.chairperson = msg.sender
self.voter_count = 0
for i in range(5):
... |
load(
"@com_googlesource_gerrit_bazlets//tools:junit.bzl",
"junit_tests",
)
def tests(tests):
for src in tests:
name = src[len("tst/"):len(src) - len(".java")].replace("/", "_")
labels = []
timeout = "moderate"
if name.startswith("org_eclipse_jgit_"):
package = n... | load('@com_googlesource_gerrit_bazlets//tools:junit.bzl', 'junit_tests')
def tests(tests):
for src in tests:
name = src[len('tst/'):len(src) - len('.java')].replace('/', '_')
labels = []
timeout = 'moderate'
if name.startswith('org_eclipse_jgit_'):
package = name[len('or... |
#Exam
def solution(N):
if (N > 0) and (N < 1000): #Assume that N is an integer within 1 to 1000
list_of_coded_numbers = [] #List will contain the coded numbers in descending order
while N > 0:
if (N % 2 == 0) and (N % 3 == 0) and (N % 5 == 0):
list_of_coded_numbers.append... | def solution(N):
if N > 0 and N < 1000:
list_of_coded_numbers = []
while N > 0:
if N % 2 == 0 and N % 3 == 0 and (N % 5 == 0):
list_of_coded_numbers.append('CodilityTestCoders')
elif N % 3 == 0 and N % 5 == 0:
list_of_coded_numbers.append('Test... |
#
# This file is part of stac2odc
# Copyright (C) 2020 INPE.
#
# stac2odc is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
#
__version__ = '0.0.1'
| __version__ = '0.0.1' |
str = 'X-DSPAM-Confidence:0.8475'
print(str)
colon = str.find(":")
fnum = float(str[colon+1:])
print("Number from string equals:", fnum)
| str = 'X-DSPAM-Confidence:0.8475'
print(str)
colon = str.find(':')
fnum = float(str[colon + 1:])
print('Number from string equals:', fnum) |
# Python > Strings > String Validators
# Identify the presence of alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters in a string.
#
# https://www.hackerrank.com/challenges/string-validators/problem
#
if __name__ == '__main__':
s = input()
# any alphanumeric characters... | if __name__ == '__main__':
s = input()
print(any((c.isalnum() for c in s)))
print(any((c.isalpha() for c in s)))
print(any((c.isdigit() for c in s)))
print(any((c.islower() for c in s)))
print(any((c.isupper() for c in s))) |
DOMAIN = "airthings"
KEY_API = "api"
PLATFORMS = ("sensor",)
ERROR_LOGIN_FAILED = "login_failed"
| domain = 'airthings'
key_api = 'api'
platforms = ('sensor',)
error_login_failed = 'login_failed' |
def updatePars():
if not parent().par.Lockbuffermenu:
return
op('output_table_path').cook(force=True)
dat = op('output_table')
if dat.numRows < 2:
return
p = parent().par.Outputbuffer
p.menuNames = dat.col('name')[1:]
p.menuLabels = dat.col('label')[1:]
def onTableChange(dat):
updatePars()
def onValueChang... | def update_pars():
if not parent().par.Lockbuffermenu:
return
op('output_table_path').cook(force=True)
dat = op('output_table')
if dat.numRows < 2:
return
p = parent().par.Outputbuffer
p.menuNames = dat.col('name')[1:]
p.menuLabels = dat.col('label')[1:]
def on_table_change(... |
def error_Check(inputX, inputY, nSamples, initVector, minCost, alpha,
training_epochs, silent, overlap, objFunc,
keepPercent, batchSize, batching):
acceptedObjFuncs = ["", "QUAD"]
if inputX.shape[0] != inputY.shape[0]:
print("Must have the same number of labels... | def error__check(inputX, inputY, nSamples, initVector, minCost, alpha, training_epochs, silent, overlap, objFunc, keepPercent, batchSize, batching):
accepted_obj_funcs = ['', 'QUAD']
if inputX.shape[0] != inputY.shape[0]:
print('Must have the same number of labels and training samples')
return -... |
'''
Kattis - oddgnome
theres probably a smarter way, but i really can't be bothered
Time: O(n^2 log n), Space: O(n)
'''
num_tc = int(input())
for _ in range(num_tc):
arr = list(map(int, input().split()))
n = arr.pop(0)
for i in range(1, n):
new_arr = arr[:i] + arr[i+1:]
if new_arr == s... | """
Kattis - oddgnome
theres probably a smarter way, but i really can't be bothered
Time: O(n^2 log n), Space: O(n)
"""
num_tc = int(input())
for _ in range(num_tc):
arr = list(map(int, input().split()))
n = arr.pop(0)
for i in range(1, n):
new_arr = arr[:i] + arr[i + 1:]
if new_arr == sort... |
def force_bytes(value):
if isinstance(value, bytes):
return value
return str(value).encode('utf-8')
| def force_bytes(value):
if isinstance(value, bytes):
return value
return str(value).encode('utf-8') |
coords = []
for ry in range(-2, 3):
for rx in range(2, -3, -1):
x = rx / 4
y = ry / 4
coords.append((x,y))
for p in range(16):
y, x = divmod(p, 4)
top_right = coords[(y+1)*5 + x]
top_left = coords[(y+1)*5 + x + 1]
bottom_left = coords[y*5 + x + 1]
bottom_right = coords[y... | coords = []
for ry in range(-2, 3):
for rx in range(2, -3, -1):
x = rx / 4
y = ry / 4
coords.append((x, y))
for p in range(16):
(y, x) = divmod(p, 4)
top_right = coords[(y + 1) * 5 + x]
top_left = coords[(y + 1) * 5 + x + 1]
bottom_left = coords[y * 5 + x + 1]
bottom_righ... |
# -*- coding: utf-8 -*-
__author__ = 'Bruno Paes'
__email__ = 'brunopaes05@gmail.com'
__github__ = 'https://www.github.com/Brunopaes'
__status__ = 'Finalised'
class Viginere(object):
@staticmethod
def encrypt(plaintext, key):
key_length = len(key)
key_as_int = [ord(i) for i in key]
pla... | __author__ = 'Bruno Paes'
__email__ = 'brunopaes05@gmail.com'
__github__ = 'https://www.github.com/Brunopaes'
__status__ = 'Finalised'
class Viginere(object):
@staticmethod
def encrypt(plaintext, key):
key_length = len(key)
key_as_int = [ord(i) for i in key]
plaintext_int = [ord(i) for... |
predictor_url = 'http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2'
predictor_file = '../weights/shape_predictor_68_face_landmarks.dat'
p2v_model_gdrive_id = '1op5_zyH4CWm_JFDdCUPZM4X-A045ETex'
sample_image = '../examples/sample.jpg'
| predictor_url = 'http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2'
predictor_file = '../weights/shape_predictor_68_face_landmarks.dat'
p2v_model_gdrive_id = '1op5_zyH4CWm_JFDdCUPZM4X-A045ETex'
sample_image = '../examples/sample.jpg' |
def main(request, response):
name = request.GET.first(b"name")
value = request.GET.first(b"value")
source_origin = request.headers.get(b"origin", None)
response_headers = [(b"Set-Cookie", name + b"=" + value),
(b"Access-Control-Allow-Origin", source_origin),
... | def main(request, response):
name = request.GET.first(b'name')
value = request.GET.first(b'value')
source_origin = request.headers.get(b'origin', None)
response_headers = [(b'Set-Cookie', name + b'=' + value), (b'Access-Control-Allow-Origin', source_origin), (b'Access-Control-Allow-Credentials', b'true'... |
# Leetcode 435. Non-overlapping Intervals
#
# Link: https://leetcode.com/problems/non-overlapping-intervals/
# Difficulty: Medium
# Solution using sorting.
# Complexity:
# O(NlogN) time | where N represent the number of intervals
# O(1) space
class Solution:
def eraseOverlapIntervals(self, intervals: List[List... | class Solution:
def erase_overlap_intervals(self, intervals: List[List[int]]) -> int:
intervals.sort(key=lambda pair: pair[0])
result = 0
prev_end = intervals[0][1]
for (start, end) in intervals[1:]:
if start >= prevEnd:
prev_end = end
else:
... |
BOARD_TILE_SIZE = 56 # the size of each board tile
BOARD_PLAYER_SIZE = 20 # the size of each player icon
BOARD_MARGIN = (10, 0) # margins, in pixels (for player icons)
PLAYER_ICON_IMAGE_SIZE = 32 # the size of the image to download, should a power of 2 and higher than BOARD_PLAYER_SIZE
MAX_PLAYERS ... | board_tile_size = 56
board_player_size = 20
board_margin = (10, 0)
player_icon_image_size = 32
max_players = 4
board = {2: 38, 7: 14, 8: 31, 15: 26, 21: 42, 28: 84, 36: 44, 51: 67, 71: 91, 78: 98, 87: 94, 99: 80, 95: 75, 92: 88, 89: 68, 74: 53, 64: 60, 62: 19, 49: 11, 46: 25, 16: 6} |
def truncate(string, length):
"Ensure a string is no longer than a given length."
if len(string) <= length:
return string
else:
return string[:length]
| def truncate(string, length):
"""Ensure a string is no longer than a given length."""
if len(string) <= length:
return string
else:
return string[:length] |
def insertionSort(arr, size):
for i in range(1, size):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
def shakerSort(arr, size):
left = 0
right = size - 1
lastSwap = 0
... | def insertion_sort(arr, size):
for i in range(1, size):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
def shaker_sort(arr, size):
left = 0
right = size - 1
last_swap = 0
while ... |
def mergeOverlappingIntervals(intervals):
sortedIntervals = sorted(intervals, key=lambda x: x[0])
overlappingIntervals = []
left = sortedIntervals[0][0]
right = sortedIntervals[0][1]
for i in range(1, len(sortedIntervals)):
if right >= sortedIntervals[i][0]:
right = max(right, so... | def merge_overlapping_intervals(intervals):
sorted_intervals = sorted(intervals, key=lambda x: x[0])
overlapping_intervals = []
left = sortedIntervals[0][0]
right = sortedIntervals[0][1]
for i in range(1, len(sortedIntervals)):
if right >= sortedIntervals[i][0]:
right = max(right... |
class GameLogic:
def __int__(self):
self
def add_lander(self, lander):
self.lander = lander
def update(self, delta_time):
self.lander.update_lander(delta_time) | class Gamelogic:
def __int__(self):
self
def add_lander(self, lander):
self.lander = lander
def update(self, delta_time):
self.lander.update_lander(delta_time) |
data = []
with open("data.txt") as file:
data = [int(x) for x in file.read().split(",")]
def part_one(data, noun, verb):
opcode = 0
data_c = data[:]
data_c[1] = noun
data_c[2] = verb
while True:
if data_c[opcode] == 1:
data_c[data_c[opcode + 3]] = data_c[data_c[... | data = []
with open('data.txt') as file:
data = [int(x) for x in file.read().split(',')]
def part_one(data, noun, verb):
opcode = 0
data_c = data[:]
data_c[1] = noun
data_c[2] = verb
while True:
if data_c[opcode] == 1:
data_c[data_c[opcode + 3]] = data_c[data_c[opcode + 1]] ... |
var = 'foo'
def ex2():
var = 'bar'
print ('inside the function var is ', var)
ex2()
def ex3():
global var
var = 'bar'
print ('inside the function var is ', var)
ex3()
print ('outside the function var is ', var)
| var = 'foo'
def ex2():
var = 'bar'
print('inside the function var is ', var)
ex2()
def ex3():
global var
var = 'bar'
print('inside the function var is ', var)
ex3()
print('outside the function var is ', var) |
code = bytearray([
0xa9, 0xff,
0x8d, 0x02, 0x60,
0xa9, 0x55, # lda #$55
0x8d, 0x00, 0x60, #sta $6000
0xa9, 0x00, # lda #00
0x8d, 0x00, 0x60, #sta $6000
0x4c, 0x05, 0x80 #jmp 8005 (#lda $55)
])
rom = code + bytearray([0xea] * (32768 - len(code)) )
rom[0x7ffc] = 0x00
rom[0x7ffd] = 0x... | code = bytearray([169, 255, 141, 2, 96, 169, 85, 141, 0, 96, 169, 0, 141, 0, 96, 76, 5, 128])
rom = code + bytearray([234] * (32768 - len(code)))
rom[32764] = 0
rom[32765] = 128
with open('rom.bin', 'wb') as out_file:
out_file.write(rom) |
_sampler = None
def get_sampler():
return _sampler
def set_sampler(sampler):
global _sampler
_sampler = sampler
| _sampler = None
def get_sampler():
return _sampler
def set_sampler(sampler):
global _sampler
_sampler = sampler |
class Node:
def __init__(self,id,parent,val):
self.id=id
self.parent=parent
self.ch1,self.ch2=0,0
self.val=val
self.leaf=True
n=int(input())
orix=[*map(int,input().split())]
x=sorted(orix)
node=dict()
node[1]=Node(1,0,-1)
cnt=1
li=[]
for i in x:
li2=[]
root=node[1]
... | class Node:
def __init__(self, id, parent, val):
self.id = id
self.parent = parent
(self.ch1, self.ch2) = (0, 0)
self.val = val
self.leaf = True
n = int(input())
orix = [*map(int, input().split())]
x = sorted(orix)
node = dict()
node[1] = node(1, 0, -1)
cnt = 1
li = []
for i... |
#!/usr/bin/env python
# coding=utf-8
'''
@Author: John
@Email: johnjim0816@gmail.com
@Date: 2019-11-15 13:46:12
@LastEditor: John
@LastEditTime: 2020-07-29 22:43:12
@Discription:
@Environment:
'''
class Solution:
def singleNumber(self, nums: List[int]) -> int:
seen_once = seen_twice = 0
for num in... | """
@Author: John
@Email: johnjim0816@gmail.com
@Date: 2019-11-15 13:46:12
@LastEditor: John
@LastEditTime: 2020-07-29 22:43:12
@Discription:
@Environment:
"""
class Solution:
def single_number(self, nums: List[int]) -> int:
seen_once = seen_twice = 0
for num in nums:
seen_once = ~se... |
res = 0
i = 0
nb = int(input())
if nb == -1:
while i != 'F':
i = input()
if i != 'F':
res += int(i)
else:
for x in range(nb):
i = int(input())
res += i
print(res) | res = 0
i = 0
nb = int(input())
if nb == -1:
while i != 'F':
i = input()
if i != 'F':
res += int(i)
else:
for x in range(nb):
i = int(input())
res += i
print(res) |
#
# Example file for working with conditional statements
#
def main():
x, y = 10, 100
# conditional flow uses if, elif, else
if x < y:
print("x is smaller than y")
elif x == y:
print("x has same value as y")
else:
print("x is larger than y")
# conditional statements let you use "a if C e... | def main():
(x, y) = (10, 100)
if x < y:
print('x is smaller than y')
elif x == y:
print('x has same value as y')
else:
print('x is larger than y')
result = 'x is less than y' if x < y else 'x is same as or larger than y'
print(result)
if __name__ == '__main__':
main(... |
class AreaLight:
def __init__(self, shape_id, intensity, two_sided = False):
assert(intensity.device.type == 'cpu')
self.shape_id = shape_id
self.intensity = intensity
self.two_sided = two_sided
def state_dict(self):
return {
'shape_id': self.shape_id,
... | class Arealight:
def __init__(self, shape_id, intensity, two_sided=False):
assert intensity.device.type == 'cpu'
self.shape_id = shape_id
self.intensity = intensity
self.two_sided = two_sided
def state_dict(self):
return {'shape_id': self.shape_id, 'intensity': self.int... |
#
# PySNMP MIB module CISCO-VOICE-CAS-MODULE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VOICE-CAS-MODULE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:02:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, single_value_constraint, value_range_constraint, constraints_union) ... |
#
# PySNMP MIB module CISCOSB-rlInterfaces (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-rlInterfaces
# Produced by pysmi-0.3.4 at Wed May 1 12:24:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_size_constraint, constraints_union, value_range_constraint) ... |
def solveQuestion(inputPath):
fileP = open(inputPath, 'r')
fileLines = fileP.readlines()
fileP.close()
newPosition = []
numRows = len(fileLines)
numCols = len(fileLines[0].strip('\n'))
for line in fileLines:
currentLine = []
for grid in line.strip('\n'):
... | def solve_question(inputPath):
file_p = open(inputPath, 'r')
file_lines = fileP.readlines()
fileP.close()
new_position = []
num_rows = len(fileLines)
num_cols = len(fileLines[0].strip('\n'))
for line in fileLines:
current_line = []
for grid in line.strip('\n'):
cu... |
n = int(input())
if n%2 != 0:
print('Weird')
else:
if n in range(2, 6):
print('Not Weird')
if n in range(6, 21):
print('Weird')
if n > 20:
print('Not Weird')
| n = int(input())
if n % 2 != 0:
print('Weird')
else:
if n in range(2, 6):
print('Not Weird')
if n in range(6, 21):
print('Weird')
if n > 20:
print('Not Weird') |
def add_numbers(start, end):
total=0
for i in range(start,end+1):
total=total+i
return total
test1 = add_numbers(333, 777)
print(test1)
| def add_numbers(start, end):
total = 0
for i in range(start, end + 1):
total = total + i
return total
test1 = add_numbers(333, 777)
print(test1) |
MOD = 10 ** 9 + 7
n, k = map(int, input().split())
dp = [0] * (k + 1)
ans = 0
for x in range(k, 0, -1):
dp[x] = pow(k // x, n, MOD)
for i in range(2 * x, k + 1, x):
dp[x] -= dp[i]
ans += dp[x] * x
ans %= MOD
print(ans) | mod = 10 ** 9 + 7
(n, k) = map(int, input().split())
dp = [0] * (k + 1)
ans = 0
for x in range(k, 0, -1):
dp[x] = pow(k // x, n, MOD)
for i in range(2 * x, k + 1, x):
dp[x] -= dp[i]
ans += dp[x] * x
ans %= MOD
print(ans) |
# Bidirectional BFS
class Solution(object):
def minKnightMoves(self, x, y):
offsets = [(1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)]
q1 = collections.deque([(0, 0)])
q2 = collections.deque([(x, y)])
steps1 = {(0, 0): 0} #steps needed starting from (0, 0)
... | class Solution(object):
def min_knight_moves(self, x, y):
offsets = [(1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)]
q1 = collections.deque([(0, 0)])
q2 = collections.deque([(x, y)])
steps1 = {(0, 0): 0}
steps2 = {(x, y): 0}
while q1 and q2:
... |
class School:
def __init__(self):
self.list_students = list()
self.list_data = list()
def add_student(self, name, grade):
self.list_students.append({"name": name, "grade": grade})
def roster(self):
return self.sort_student_list_by_name_and_grade()
def grade(self, grad... | class School:
def __init__(self):
self.list_students = list()
self.list_data = list()
def add_student(self, name, grade):
self.list_students.append({'name': name, 'grade': grade})
def roster(self):
return self.sort_student_list_by_name_and_grade()
def grade(self, grad... |
#!/usr/bin/python3
# * Copyright (c) 2020-2021, Happiest Minds Technologies Limited Intellectual Property. All rights reserved.
# *
# * SPDX-License-Identifier: LGPL-2.1-only
PE1_binding_chk = 'ipv4 PE1ID/32 P1ID imp-null'
P1_binding_chk1 = 'ipv4 P1ID/32 PE1ID imp-null'
P1_binding_c... | pe1_binding_chk = 'ipv4 PE1ID/32 P1ID imp-null'
p1_binding_chk1 = 'ipv4 P1ID/32 PE1ID imp-null'
p1_binding_chk2 = 'ipv4 P1ID/32 PE2ID imp-null'
pe2_binding_chk = 'ipv4 PE2ID/32 P1ID imp-null' |
# Url source:
# https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list
numbers = list(range(1, 50))
for i in numbers:
if i < 20:
numbers.remove(i)
print(numbers)
| numbers = list(range(1, 50))
for i in numbers:
if i < 20:
numbers.remove(i)
print(numbers) |
class Solution:
def shortestPathLength(self, graph):
def dp(node, mask):
state = (node, mask)
if state in cache:
return cache[state]
if mask & (mask - 1) == 0:
# Base case - mask only has a single "1", which means
# that onl... | class Solution:
def shortest_path_length(self, graph):
def dp(node, mask):
state = (node, mask)
if state in cache:
return cache[state]
if mask & mask - 1 == 0:
return 0
cache[state] = float('inf')
for neighbor in g... |
def format_dict(data, sep_item=", ", sep_key_value="=", brackets=True):
output = ""
delim = ""
for key, value in data.items():
output += f"{delim}{key}{sep_key_value}{value}"
delim = f"{sep_item}"
return f"{{{output}}}" if brackets else f"{output}"
def powerdict(data): # https://stack... | def format_dict(data, sep_item=', ', sep_key_value='=', brackets=True):
output = ''
delim = ''
for (key, value) in data.items():
output += f'{delim}{key}{sep_key_value}{value}'
delim = f'{sep_item}'
return f'{{{output}}}' if brackets else f'{output}'
def powerdict(data):
n = len(dat... |
#!/usr/bin/env python3
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | dir = 'website'
for name in os.listdir(dir):
fullname = os.path.join(dir, name)
if os.path.isdir(fullname):
print('{} is a directory'.format(fullname))
else:
print('{} is a file'.format(fullname))
with open('software.csv') as software:
reader = csv.DictReader(software)
for row in rea... |
class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
if grid[0][0] == 1:
return -1
def neighbor8(i, j):
n = len(grid)
for di in (-1, 0, 1):
for dj in (-1, 0, 1):
if di == dj == 0:
... | class Solution:
def shortest_path_binary_matrix(self, grid: List[List[int]]) -> int:
if grid[0][0] == 1:
return -1
def neighbor8(i, j):
n = len(grid)
for di in (-1, 0, 1):
for dj in (-1, 0, 1):
if di == dj == 0:
... |
first = "Aditya"
last = "Mhambrey"
full = first+" "+last
print(full)
full = f"{first} {last} {2+2} {len(first)}"
print(full)
course = " Python Programming"
print(course.upper())
print(course.lower())
print(course.title()) # First Letter of every Word is capital
print(course.strip()) # Getting rid of white space
prin... | first = 'Aditya'
last = 'Mhambrey'
full = first + ' ' + last
print(full)
full = f'{first} {last} {2 + 2} {len(first)}'
print(full)
course = ' Python Programming'
print(course.upper())
print(course.lower())
print(course.title())
print(course.strip())
print(course.rstrip())
print(course.find('Pro'))
print(course.replace... |
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def has_cycle(head):
slow, fast = head, head
while fast is not None and fast.next is not None:
fast = fast.next.next
slow = slow.next
if slow == fast:
... | class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def has_cycle(head):
(slow, fast) = (head, head)
while fast is not None and fast.next is not None:
fast = fast.next.next
slow = slow.next
if slow == fast:
... |
#Sort an array of 0s, 1s and 2s
#It is a problem from geeksforgeeks and can be solved using python code
#Given an array A of size N containing 0s, 1s, and 2s; you need to sort the array in ascending order.
# Here t is the number of test cases,
# i is an iterative variable,
# n is the number of elements in list,
# x i... | t = int(input())
for i in range(t):
n = int(input())
x = list(map(int, input().split()))
x.sort()
for i in x:
print(i, end=' ')
print() |
# list(map(int, input().split()))
# int(input())
def main():
X = int(input())
if X >= 30:
print('Yes')
else:
print('No')
if __name__ == '__main__':
main()
| def main():
x = int(input())
if X >= 30:
print('Yes')
else:
print('No')
if __name__ == '__main__':
main() |
class ManageCards:
cards = {}
cards["154-98-11-133-118"] = "1"
cards["64-91-169-137-59"] = "2"
cards["46-245-168-137-250"] = "3"
cards["198-241-168-137-22"] = "4"
cards["127-72-227-41-253"] = "5"
cards["78-4-170-137-105"] = "6"
cards["119-174-226-41-18"] = "7"
cards["98-155-250-41-42"] = "8"
cards["1-112-16... | class Managecards:
cards = {}
cards['154-98-11-133-118'] = '1'
cards['64-91-169-137-59'] = '2'
cards['46-245-168-137-250'] = '3'
cards['198-241-168-137-22'] = '4'
cards['127-72-227-41-253'] = '5'
cards['78-4-170-137-105'] = '6'
cards['119-174-226-41-18'] = '7'
cards['98-155-250-41-42... |
'''An e-commerce website wishes to find the lucky customer who will be eligible for full value cash back. For this purpose,a number N is fed to the system. It will return another number that is calculated by an algorithm. In the algorithm, a sequence is generated, in which each number n the sum of the preceding numbers... | """An e-commerce website wishes to find the lucky customer who will be eligible for full value cash back. For this purpose,a number N is fed to the system. It will return another number that is calculated by an algorithm. In the algorithm, a sequence is generated, in which each number n the sum of the preceding numbers... |
class CommonsShared:
# period, step, and episode counter
periods_counter = 1
steps_counter = 1
episode_number = 0
# number of periods considered for calculating short and long term sustainabilities
n_steps_short_term = 1
n_steps_long_term = 4
# number of agents
n_agents = 5
# ... | class Commonsshared:
periods_counter = 1
steps_counter = 1
episode_number = 0
n_steps_short_term = 1
n_steps_long_term = 4
n_agents = 5
max_episode_periods = 10
agents_loop_steps = 20
growing_rate = 0.3
carrying_capacity = 50000
punishment_probability = 1
max_replenishmen... |
def test_ci_placeholder():
# This empty test is used within the CI to
# setup the tox venv without running the test suite
# if we simply skip all test with pytest -k=wrong_pattern
# pytest command would return with exit_code=5 (i.e "no tests run")
# making travis fail
# this empty test is the re... | def test_ci_placeholder():
pass |
if __name__ == '__main__':
x = 1
y = [2]
x, = y
print(x)
| if __name__ == '__main__':
x = 1
y = [2]
(x,) = y
print(x) |
class Decoder:
def __init__(self, alphabet, symbol):
self._alphabet = alphabet
self._symbol = symbol
self._reconstructed_extended_dict = {
int(symbol): letter for letter, symbol in self._alphabet.copy().items()
}
def decode(self, encoded_input):
output = ""
... | class Decoder:
def __init__(self, alphabet, symbol):
self._alphabet = alphabet
self._symbol = symbol
self._reconstructed_extended_dict = {int(symbol): letter for (letter, symbol) in self._alphabet.copy().items()}
def decode(self, encoded_input):
output = ''
last_decoded... |
listanum = [[],[]] #Primeiro colchete numeros pares e segundo colchete numeros impares
valor = 0
for cont in range(1,8):
valor = int(input("Digite um valor: "))
if valor % 2 ==0:
listanum[0].append(valor)
else:
listanum[1].append(valor)
listanum[0].sort()
listanum[1].sort()
print(f"Os numero... | listanum = [[], []]
valor = 0
for cont in range(1, 8):
valor = int(input('Digite um valor: '))
if valor % 2 == 0:
listanum[0].append(valor)
else:
listanum[1].append(valor)
listanum[0].sort()
listanum[1].sort()
print(f'Os numeros pares digitados foram {listanum[0]}')
print(f'Os numeros impare... |
path = "../data/stockfish_norm.csv"
scores = open( path)
last_scores = open( "last_scores.fea", "w")
for row in scores:
last_scores.write( row.rsplit(" ", 1)[1])
scores.close()
last_scores.close() | path = '../data/stockfish_norm.csv'
scores = open(path)
last_scores = open('last_scores.fea', 'w')
for row in scores:
last_scores.write(row.rsplit(' ', 1)[1])
scores.close()
last_scores.close() |
def mutation(word_list):
if all(i in word_list[0].lower() for i in word_list[1].lower()):
return True
return False
print(mutation(["hello", "Hello"]))
print(mutation(["hello", "hey"]))
print(mutation(["Alien", "line"]))
| def mutation(word_list):
if all((i in word_list[0].lower() for i in word_list[1].lower())):
return True
return False
print(mutation(['hello', 'Hello']))
print(mutation(['hello', 'hey']))
print(mutation(['Alien', 'line'])) |
def index(req):
req.content_type = "text/html"
req.add_common_vars()
env_vars = req.subprocess_env.copy()
req.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">')
req.write('<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:l... | def index(req):
req.content_type = 'text/html'
req.add_common_vars()
env_vars = req.subprocess_env.copy()
req.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">')
req.write('<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lan... |
class Vehicle:
name = ""
kind = "car"
color = ""
value = 00.00
def description (self):
desc ="%s is a %s %s worth $%.2f." % (self.name,self.color,self.kind,self.value)
return desc
car1 = Vehicle()
car1.name = "Fuso"
car1.color = "grey"
car1.kind = "lorry"
car1.value = 1000
car2 = Vehicle()
car2.name ... | class Vehicle:
name = ''
kind = 'car'
color = ''
value = 0.0
def description(self):
desc = '%s is a %s %s worth $%.2f.' % (self.name, self.color, self.kind, self.value)
return desc
car1 = vehicle()
car1.name = 'Fuso'
car1.color = 'grey'
car1.kind = 'lorry'
car1.value = 1000
car2 = v... |
class ContactHelper:
def __init__(self, app):
self.app = app
def create(self, contact):
wd = self.app.wd
# init contact creation
wd.find_element_by_link_text("add new").click()
# foll contact form
wd.find_element_by_name("firstname").click()
wd.find_elem... | class Contacthelper:
def __init__(self, app):
self.app = app
def create(self, contact):
wd = self.app.wd
wd.find_element_by_link_text('add new').click()
wd.find_element_by_name('firstname').click()
wd.find_element_by_name('firstname').clear()
wd.find_element_by_... |
#
# Copyright (c) 2017 Amit Green. All rights reserved.
#
@gem('Gem.Codec')
def gem():
require_gem('Gem.Import')
PythonCodec = import_module('codecs')
python_encode_ascii = PythonCodec.getencoder('ascii')
@export
def encode_ascii(s):
return python_encode_ascii(s)[0]
| @gem('Gem.Codec')
def gem():
require_gem('Gem.Import')
python_codec = import_module('codecs')
python_encode_ascii = PythonCodec.getencoder('ascii')
@export
def encode_ascii(s):
return python_encode_ascii(s)[0] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.