content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Solution:
def twoSum(self, numbers, target):
res = None
left = 0
right = len(numbers) - 1
while left < right:
result = numbers[left] + numbers[right]
if result == target:
res = [left + 1, right + 1]
break
elif ... | class Solution:
def two_sum(self, numbers, target):
res = None
left = 0
right = len(numbers) - 1
while left < right:
result = numbers[left] + numbers[right]
if result == target:
res = [left + 1, right + 1]
break
eli... |
class CaesarShiftCipher:
def __init__(self, shift=1):
self.shift = shift
def encrypt(self, plaintext):
return ''.join(
[self.num_2_char((self.char_2_num(letter) + self.shift) % 26) for letter in plaintext.lower()]
).upper()
def decrypt(self, ciphertext: str) -> str:
... | class Caesarshiftcipher:
def __init__(self, shift=1):
self.shift = shift
def encrypt(self, plaintext):
return ''.join([self.num_2_char((self.char_2_num(letter) + self.shift) % 26) for letter in plaintext.lower()]).upper()
def decrypt(self, ciphertext: str) -> str:
return ''.join([... |
def factorial(n):
if n < 2:
return 1
return n * factorial(n - 1)
def main():
n=6
print(factorial(n))
main()
| def factorial(n):
if n < 2:
return 1
return n * factorial(n - 1)
def main():
n = 6
print(factorial(n))
main() |
numbers = [int(n) for n in input().split(' ')]
n = len(numbers)
for i in range(n):
for j in range(0, n - i - 1):
if numbers[j] > numbers[j + 1]:
numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]
print(' '.join([str(n) for n in numbers])) | numbers = [int(n) for n in input().split(' ')]
n = len(numbers)
for i in range(n):
for j in range(0, n - i - 1):
if numbers[j] > numbers[j + 1]:
(numbers[j], numbers[j + 1]) = (numbers[j + 1], numbers[j])
print(' '.join([str(n) for n in numbers])) |
# coding: utf8
# try something like
def index():
'''main page that allows searching for and displaying audio listings'''
#create search form
formSearch = FORM(INPUT(_id='searchInput', requires=[IS_NOT_EMPTY(error_message='you have to enter something to search for'),
IS_LENGTH(50, error_message='you can\'t have su... | def index():
"""main page that allows searching for and displaying audio listings"""
form_search = form(input(_id='searchInput', requires=[is_not_empty(error_message='you have to enter something to search for'), is_length(50, error_message="you can't have such a long search term, limit is 50 characters")]), inp... |
# Register the HourglassTree report addon
register(REPORT,
id = 'hourglass_chart',
name = _("Hourglass Tree"),
description = _("Produces a graphical report combining an ancestor tree and a descendant tree."),
version = '1.0.0',
gramps_target_version = '5.1',
status = STABLE,
fname = 'hourglasstree.p... | register(REPORT, id='hourglass_chart', name=_('Hourglass Tree'), description=_('Produces a graphical report combining an ancestor tree and a descendant tree.'), version='1.0.0', gramps_target_version='5.1', status=STABLE, fname='hourglasstree.py', authors=['Peter Zingg'], authors_email=['peter.zingg@gmail.com'], catego... |
#
# PySNMP MIB module Nortel-Magellan-Passport-PppMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-PppMIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:18:42 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pytho... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, single_value_constraint, value_range_constraint, constraints_union) ... |
#
# This file contains the Python code from Program 9.8 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm09_08.txt
#
class Tree(Containe... | class Tree(Container):
def accept(self, visitor):
assert isinstance(visitor, Visitor)
self.depthFirstTraversal(pre_order(visitor)) |
x = int(input("Insert some numbers: "))
ev = 0
od = 0
while x > 0:
if x%2 ==0:
ev += 1
else:
od += 1
x = x//10
print("Even numbers = %d, Odd numbers = %d" % (ev,od)) | x = int(input('Insert some numbers: '))
ev = 0
od = 0
while x > 0:
if x % 2 == 0:
ev += 1
else:
od += 1
x = x // 10
print('Even numbers = %d, Odd numbers = %d' % (ev, od)) |
'''A special two digit number is a number such that when the sum of its digits is added to the product of its digits, the result should be equal to the original two-digit number.
Implement a program to accept a two digit number and check whether it is a special two digit number or not.
Input Format
a two digit number... | """A special two digit number is a number such that when the sum of its digits is added to the product of its digits, the result should be equal to the original two-digit number.
Implement a program to accept a two digit number and check whether it is a special two digit number or not.
Input Format
a two digit number... |
def latex_template(name, title):
return '\n'.join((r"\begin{figure}[H]",
r" \centering",
rf" \incfig[0.8]{{{name}}}",
rf" \caption{{{title}}}",
rf" \label{{fig:{name}}}",
r" \vspace{-0.5cm}",... | def latex_template(name, title):
return '\n'.join(('\\begin{figure}[H]', ' \\centering', f' \\incfig[0.8]{{{name}}}', f' \\caption{{{title}}}', f' \\label{{fig:{name}}}', ' \\vspace{-0.5cm}', '\\end{figure}')) |
houses = {(0, 0)}
with open('Day 3 - input', 'r') as f:
directions = f.readline()
current_location = [0, 0]
for direction in directions[::2]:
if direction == '^':
current_location[1] += 1
houses.add(tuple(current_location))
elif direction == '>':
current_... | houses = {(0, 0)}
with open('Day 3 - input', 'r') as f:
directions = f.readline()
current_location = [0, 0]
for direction in directions[::2]:
if direction == '^':
current_location[1] += 1
houses.add(tuple(current_location))
elif direction == '>':
current_l... |
class Profile:
def __init__(self, id, username, email, allowed_buy,
first_name, last_name, is_staff, is_current, **kwargs):
self.id = id
self.user_name = username
self.email = email
self.allowed_buy = allowed_buy
self.first_name = first_name
self.last... | class Profile:
def __init__(self, id, username, email, allowed_buy, first_name, last_name, is_staff, is_current, **kwargs):
self.id = id
self.user_name = username
self.email = email
self.allowed_buy = allowed_buy
self.first_name = first_name
self.last_name = last_nam... |
#!/usr/bin/env python
class Graph:
def __init__(self, n, edges):
# n is the number of vertices
# edges is a list of tuples which represents one edge
self.n = n
self.V = set(list(range(n)))
self.E = [set() for i in range(n)]
for e in edges:
v, w = e
... | class Graph:
def __init__(self, n, edges):
self.n = n
self.V = set(list(range(n)))
self.E = [set() for i in range(n)]
for e in edges:
(v, w) = e
self.E[v].add(w)
self.E[w].add(v)
def __str__(self):
ret = ''
ret += 'There are %... |
'''
Adapt the code from one of the functions above to create a new function called 'multiplier'.
The user should be able to input two numbers that are stored in variables.
The function should multiply the two variables together and return the result to a variable in the main program.
The main program should output the ... | """
Adapt the code from one of the functions above to create a new function called 'multiplier'.
The user should be able to input two numbers that are stored in variables.
The function should multiply the two variables together and return the result to a variable in the main program.
The main program should output the ... |
my_dictionary={
'nama': 'Elyas',
'usia': 19,
'status': 'mahasiswa'
}
my_dictionary["usia"]=20
print(my_dictionary) | my_dictionary = {'nama': 'Elyas', 'usia': 19, 'status': 'mahasiswa'}
my_dictionary['usia'] = 20
print(my_dictionary) |
#!/usr/bin/env python3
#encoding=utf-8
#------------------------------------------------
# Usage: python3 3-decorator2.py
# Description: Tracer call with key-word only
#------------------------------------------------
class Tracer: # state via instance attributes
def __init__(self, func): # ... | class Tracer:
def __init__(self, func):
self.func = func
self.calls = 0
def __call__(self, *args, **kwargs):
self.calls += 1
print('call %s to %s' % (self.calls, self.func.__name__))
return self.func(*args, **kwargs)
@Tracer
def spam(a, b, c):
print(a + b + c)
@Tr... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
class TwoStackQueue:
def __init__(self):
self.forward_stack = []
self.reverse_stack = []
def dequeue(self):
if not self.reverse_stack:
while self.forward_stack:
self.reverse_stac... | class Twostackqueue:
def __init__(self):
self.forward_stack = []
self.reverse_stack = []
def dequeue(self):
if not self.reverse_stack:
while self.forward_stack:
self.reverse_stack.append(self.forward_stack.pop())
return self.reverse_stack.pop()
... |
N, K = map(int, input().split())
result = 0
while N != 0:
result += 1
N //= K
print(result)
| (n, k) = map(int, input().split())
result = 0
while N != 0:
result += 1
n //= K
print(result) |
EXPECTED_SECRETS = [
"EQ_SERVER_SIDE_STORAGE_USER_ID_SALT",
"EQ_SERVER_SIDE_STORAGE_USER_IK_SALT",
"EQ_SERVER_SIDE_STORAGE_ENCRYPTION_USER_PEPPER",
"EQ_SECRET_KEY",
"EQ_RABBITMQ_USERNAME",
"EQ_RABBITMQ_PASSWORD",
]
def validate_required_secrets(secrets):
for required_secret in EXPECTED_SEC... | expected_secrets = ['EQ_SERVER_SIDE_STORAGE_USER_ID_SALT', 'EQ_SERVER_SIDE_STORAGE_USER_IK_SALT', 'EQ_SERVER_SIDE_STORAGE_ENCRYPTION_USER_PEPPER', 'EQ_SECRET_KEY', 'EQ_RABBITMQ_USERNAME', 'EQ_RABBITMQ_PASSWORD']
def validate_required_secrets(secrets):
for required_secret in EXPECTED_SECRETS:
if required_se... |
{
"targets": [{
"target_name": "fuse",
"include_dirs": [
"<!(node -e \"require('napi-macros')\")",
"<!(node -e \"require('fuse-shared-library/include')\")",
],
"libraries": [
"<!(node -e \"require('fuse-shared-library/lib')\")",
],
"sources": [
"fuse-native.c"
],
... | {'targets': [{'target_name': 'fuse', 'include_dirs': ['<!(node -e "require(\'napi-macros\')")', '<!(node -e "require(\'fuse-shared-library/include\')")'], 'libraries': ['<!(node -e "require(\'fuse-shared-library/lib\')")'], 'sources': ['fuse-native.c'], 'xcode_settings': {'OTHER_CFLAGS': ['-g', '-O3', '-Wall']}, 'cflag... |
def split_list(list, n):
target_list = []
cut = int(len(list) / n)
if cut == 0:
list = [[x] for x in list]
none_array = [[] for i in range(0, n - len(list))]
return list + none_array
for i in range(0, n - 1):
target_list.append(list[cut * i:cut * (1 + i)])
target_list... | def split_list(list, n):
target_list = []
cut = int(len(list) / n)
if cut == 0:
list = [[x] for x in list]
none_array = [[] for i in range(0, n - len(list))]
return list + none_array
for i in range(0, n - 1):
target_list.append(list[cut * i:cut * (1 + i)])
target_list... |
#
# This file contains the Python code from Program 15.18 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm15_18.txt
#
class RadixSorter... | class Radixsorter(Sorter):
r = 8
r = 1 << r
p = (32 + r - 1) / r
def __init__(self):
self._count = array(self.R)
self._tempArray = None |
somthing = 'F5fjDxitafeZwPdwsmBL-Q'
key_api = 'MiT75-jn5D_6MENzkehT5EReeVdYhp_86hQKYQp-3o10wIVXAbOakIT6khg8Y-_PBiy2fKPuAQFp9x7W80Ubn3xdiS8eCfy-nc7qtLNvs6oyAzdU2CsCRHEniyJUYHYx' | somthing = 'F5fjDxitafeZwPdwsmBL-Q'
key_api = 'MiT75-jn5D_6MENzkehT5EReeVdYhp_86hQKYQp-3o10wIVXAbOakIT6khg8Y-_PBiy2fKPuAQFp9x7W80Ubn3xdiS8eCfy-nc7qtLNvs6oyAzdU2CsCRHEniyJUYHYx' |
# -*- coding: utf-8 -*-
## courses table
Course = db.define_table("courses",
Field("title", label=T('Title')),
Field("short_description", "text", label=T('Short Description')),
Field("description", "text", widget=ckeditor.widget, label=T('Description')),
Fiel... | course = db.define_table('courses', field('title', label=t('Title')), field('short_description', 'text', label=t('Short Description')), field('description', 'text', widget=ckeditor.widget, label=t('Description')), field('price', 'float', default=0, label=t('Price')), field('discount', 'float', default=0, label=t('Disco... |
def get_encoder_decoder_hp(model='gin', decoder=None):
if model == 'gin':
model_hp = {
"num_layers": 5,
"hidden": [64,64,64,64],
"dropout": 0.5,
"act": "relu",
"eps": "False",
"mlp_layers": 2,
"neighbor_pooling_type": "sum"... | def get_encoder_decoder_hp(model='gin', decoder=None):
if model == 'gin':
model_hp = {'num_layers': 5, 'hidden': [64, 64, 64, 64], 'dropout': 0.5, 'act': 'relu', 'eps': 'False', 'mlp_layers': 2, 'neighbor_pooling_type': 'sum'}
elif model == 'gat':
model_hp = {'num_layers': 2, 'hidden': [8], 'hea... |
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
count_r={}
for c in ransomNote:
if c not in count_r:
count_r[c]=1
else:
count_r[c]+=1
print(count_r)
for cr in magazine:
if cr n... | class Solution:
def can_construct(self, ransomNote: str, magazine: str) -> bool:
count_r = {}
for c in ransomNote:
if c not in count_r:
count_r[c] = 1
else:
count_r[c] += 1
print(count_r)
for cr in magazine:
if cr n... |
BOTTLE_CONTENT_MANAGER_API_PORT = 8081
BOTTLE_DEORATOR_PORTFOLIOS_API_PORT = 8082
BOTTLE_DEORATOR_TAGS_API_PORT = 8083
BOTTLE_DEORATOR_VOTES_API_PORT = 8084
USE_SOLR_AS_PERSISTENCE = True
SOLR_URL = 'http://localhost:8983/solr'
DECORATION_SOLR_FIELD_0 = 'portfolios'
DECORATION_SOLR_FIELD_1 = 'tags'
| bottle_content_manager_api_port = 8081
bottle_deorator_portfolios_api_port = 8082
bottle_deorator_tags_api_port = 8083
bottle_deorator_votes_api_port = 8084
use_solr_as_persistence = True
solr_url = 'http://localhost:8983/solr'
decoration_solr_field_0 = 'portfolios'
decoration_solr_field_1 = 'tags' |
# keep a list of the N best things we have seen, discard anything else
class nbest(object):
def __init__(self,N=1000):
self.store = []
self.N = N
def add(self,item):
self.store.append(item)
self.store.sort(reverse=True)
self.store = self.store[:self.N]
d... | class Nbest(object):
def __init__(self, N=1000):
self.store = []
self.N = N
def add(self, item):
self.store.append(item)
self.store.sort(reverse=True)
self.store = self.store[:self.N]
def __getitem__(self, k):
return self.store[k]
def __len__(self):
... |
#f = open("datum/iris.csv")
#print (f.read())
#f.close()
#closing file is good practice
#Using ff code will make closing file unnecessary
with open("datum/iris.csv") as f:
contents = (f.read())
print(contents) | with open('datum/iris.csv') as f:
contents = f.read()
print(contents) |
def main(j, args, params, tags, tasklet):
page = args.page
logpath = args.requestContext.params.get('logpath')
templatepath = args.requestContext.params.get('templatepath')
installedpath = args.requestContext.params.get('installedpath')
metapath = args.requestContext.params.get('metapath')
dom... | def main(j, args, params, tags, tasklet):
page = args.page
logpath = args.requestContext.params.get('logpath')
templatepath = args.requestContext.params.get('templatepath')
installedpath = args.requestContext.params.get('installedpath')
metapath = args.requestContext.params.get('metapath')
domai... |
def cargarListas(nombrearchivo,lista):
try:
archivo = open(nombrearchivo, "rt")
while True:
linea = archivo.readline()
if not linea:
break
linea = linea[:-1]
listaNombre, Articulos = linea.split("=")
if Articulos.stri... | def cargar_listas(nombrearchivo, lista):
try:
archivo = open(nombrearchivo, 'rt')
while True:
linea = archivo.readline()
if not linea:
break
linea = linea[:-1]
(lista_nombre, articulos) = linea.split('=')
if Articulos.strip(... |
first_number = int(input())
prime_count = 0
while True:
if 1>= first_number:
break
running_number = first_number
divider = first_number // 2 if ( 0 == first_number % 2 ) else ( first_number // 2 ) + 1;
count = 0
while divider != 1:
if 0 == running_number % divider:
c... | first_number = int(input())
prime_count = 0
while True:
if 1 >= first_number:
break
running_number = first_number
divider = first_number // 2 if 0 == first_number % 2 else first_number // 2 + 1
count = 0
while divider != 1:
if 0 == running_number % divider:
count += 1
... |
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | allowed_param_merge_strategies = (overwrite, merge, deep_merge) = ('overwrite', 'merge', 'deep_merge')
def get_param_merge_strategy(merge_strategies, param_key):
if merge_strategies is None:
return OVERWRITE
env_default = merge_strategies.get('default', OVERWRITE)
merge_strategy = merge_strategies.... |
# for item in ["mash","john","sera"]:
# print(item)
# for item in range(5,10,2):
# print(item)
# for x in range(4):
# for y in range(3):
# print(f"({x}, {y})")
numbers = [5, 2 , 5 ,2 ,2]
for item in numbers:
output = ""
for count in range(item):
output += "X"
print(output) | numbers = [5, 2, 5, 2, 2]
for item in numbers:
output = ''
for count in range(item):
output += 'X'
print(output) |
# Problem: https://www.hackerrank.com/challenges/30-data-types/problem
# Score: 30.0
i = 4
d = 4.0
s = 'HackerRank '
x = int(input())
y = float(input())
z = input()
print(i+x, d+y, s+z, sep='\n')
| i = 4
d = 4.0
s = 'HackerRank '
x = int(input())
y = float(input())
z = input()
print(i + x, d + y, s + z, sep='\n') |
class ConsumerRegister:
all_consumers = {}
def __init__(self, name):
self.name = name
self.consumer_class = None
def consumer(self):
def decorator(plugin_cls):
self.consumer_class = plugin_cls
self.all_consumers[self.name] = {
'consumer_cls':... | class Consumerregister:
all_consumers = {}
def __init__(self, name):
self.name = name
self.consumer_class = None
def consumer(self):
def decorator(plugin_cls):
self.consumer_class = plugin_cls
self.all_consumers[self.name] = {'consumer_cls': self.consumer_c... |
class ConfigBase:
def __init__(self,**kwargs):
for k,v in kwargs.items():
setattr(self,k,v)
@classmethod
def get_class_config_info_dict(cls):
if issubclass(cls.__base__, ConfigBase):
dic=cls.__base__.get_class_config_info_dict()
else:
dic = {}
... | class Configbase:
def __init__(self, **kwargs):
for (k, v) in kwargs.items():
setattr(self, k, v)
@classmethod
def get_class_config_info_dict(cls):
if issubclass(cls.__base__, ConfigBase):
dic = cls.__base__.get_class_config_info_dict()
else:
dic... |
def mergeSort(arr):
if len(arr) >1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
mergeSort(L)
mergeSort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i+= 1
els... | def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
l = arr[:mid]
r = arr[mid:]
merge_sort(L)
merge_sort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
... |
#python 3.5.2
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[l... | class Stack:
def __init__(self):
self.items = []
def is_empty(self):
self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
... |
class TextManipulation:
def formatText(text):
newText = text.replace("&", "\n")
return newText | class Textmanipulation:
def format_text(text):
new_text = text.replace('&', '\n')
return newText |
# Map query config
QUERY_RADIUS = 3000 # mts. Radius to use on OSM data queries.
MIN_DISTANCE_FOR_NEW_QUERY = 1000 # mts. Minimum distance to query area edge before issuing a new query.
FULL_STOP_MAX_SPEED = 1.39 # m/s Max speed for considering car is stopped.
| query_radius = 3000
min_distance_for_new_query = 1000
full_stop_max_speed = 1.39 |
# THIS FILE IS GENERATED FROM PYWAVELETS SETUP.PY
short_version = '0.3.0'
version = '0.3.0'
full_version = '0.3.0.dev-7ea3e91'
git_revision = '7ea3e919b1d7bbf4d7685c47d3d10c16c599cd06'
release = False
if not release:
version = full_version
| short_version = '0.3.0'
version = '0.3.0'
full_version = '0.3.0.dev-7ea3e91'
git_revision = '7ea3e919b1d7bbf4d7685c47d3d10c16c599cd06'
release = False
if not release:
version = full_version |
'''
Create a function that sums two arguments together. If only one argument is provided, then return a function that expects one argument and returns the sum.
For example, addTogether(2, 3) should return 5, and addTogether(2) should return a function.
Calling this returned function with a single argument will the... | """
Create a function that sums two arguments together. If only one argument is provided, then return a function that expects one argument and returns the sum.
For example, addTogether(2, 3) should return 5, and addTogether(2) should return a function.
Calling this returned function with a single argument will then ... |
exp_name = 'prenet_c32s6d5_lstm'
work_dir = f'./work_dirs/{exp_name}'
# model settings
model = dict(
type='MultiStageRestorer',
generator=dict(
type='PReNet',
in_channels=3,
out_channels=3,
mid_channels=32,
recurrent_unit='LSTM',
num_stages=6,
num_resbloc... | exp_name = 'prenet_c32s6d5_lstm'
work_dir = f'./work_dirs/{exp_name}'
model = dict(type='MultiStageRestorer', generator=dict(type='PReNet', in_channels=3, out_channels=3, mid_channels=32, recurrent_unit='LSTM', num_stages=6, num_resblocks=5, recursive_resblock=False), losses=[dict(type='SSIMLoss', loss_weight=1.0, redu... |
def findDecision(obj): #obj[0]: Coupon, obj[1]: Education, obj[2]: Occupation, obj[3]: Restaurant20to50, obj[4]: Distance
# {"feature": "Coupon", "instances": 127, "metric_value": 0.9671, "depth": 1}
if obj[0]>0:
# {"feature": "Occupation", "instances": 111, "metric_value": 0.9353, "depth": 2}
if obj[2]<=7.990990... | def find_decision(obj):
if obj[0] > 0:
if obj[2] <= 7.990990990990991:
if obj[3] <= 2.0:
if obj[4] > 1:
if obj[1] <= 2:
return 'True'
elif obj[1] > 2:
return 'True'
else:
... |
a = 1
a = a + 2
print(a)
a += 2
print(a)
word = "race"
word += " car"
print(word)
| a = 1
a = a + 2
print(a)
a += 2
print(a)
word = 'race'
word += ' car'
print(word) |
# compare_versions.py
# software library for question B
def compare_versions(string1, string2):
seperator = "."
# first load the strings and then seperate the individual numbers into a list by
# using the split function
string1 = string1.split(seperator)
string2 = string2.split(seperator)
# l... | def compare_versions(string1, string2):
seperator = '.'
string1 = string1.split(seperator)
string2 = string2.split(seperator)
for level in range(0, len(string1)):
if string1[level] == string2[level]:
continue
return print('Version %s is equal to version %s. ' % (seperator... |
class BaseSubmission:
def __init__(self, team_name, player_names):
self.team_name = team_name
self.player_names = player_names
def get_actions(self, obs):
'''
Overview:
You must implement this function.
'''
raise NotImplementedError
| class Basesubmission:
def __init__(self, team_name, player_names):
self.team_name = team_name
self.player_names = player_names
def get_actions(self, obs):
"""
Overview:
You must implement this function.
"""
raise NotImplementedError |
class R1DataCheckSpecificDto:
def __init__(self, id_r1_data_check_specific=None, init_event=None, end_event=None, init_pixel=None, end_pixel=None,
init_sample=None, end_sample=None,
init_subrun=None, end_subrun=None, type_of_gap_calc=None, list_of_module_in_detail=None):
s... | class R1Datacheckspecificdto:
def __init__(self, id_r1_data_check_specific=None, init_event=None, end_event=None, init_pixel=None, end_pixel=None, init_sample=None, end_sample=None, init_subrun=None, end_subrun=None, type_of_gap_calc=None, list_of_module_in_detail=None):
self.__id_r1_data_check_specific = ... |
def takethis():
fullspeed()
i01.moveHead(14,90)
i01.moveArm("left",13,45,95,10)
i01.moveArm("right",5,90,30,10)
i01.moveHand("left",2,2,2,2,2,60)
i01.moveHand("right",81,66,82,60,105,113)
i01.moveTorso(85,76,90)
sleep(3)
closelefthand()
i01.moveTorso(110,90,90)
sleep(2)
isitaball()
i01.mouth.s... | def takethis():
fullspeed()
i01.moveHead(14, 90)
i01.moveArm('left', 13, 45, 95, 10)
i01.moveArm('right', 5, 90, 30, 10)
i01.moveHand('left', 2, 2, 2, 2, 2, 60)
i01.moveHand('right', 81, 66, 82, 60, 105, 113)
i01.moveTorso(85, 76, 90)
sleep(3)
closelefthand()
i01.moveTorso(110, 9... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2019-05-18 23:29:05
# @Author : Ivy Mong (davy0328meng@gmail.com)
arr1 = [1, 3, 4, 6, 10]
arr2 = [2, 5, 8, 11]
ind = 0
ans = arr1.copy()
for i in range(len(arr2)):
while ind < len(arr1):
if arr2[i] <= arr1[ind]:
ans.insert(ind+i, ar... | arr1 = [1, 3, 4, 6, 10]
arr2 = [2, 5, 8, 11]
ind = 0
ans = arr1.copy()
for i in range(len(arr2)):
while ind < len(arr1):
if arr2[i] <= arr1[ind]:
ans.insert(ind + i, arr2[i])
break
else:
ind += 1
else:
ans = ans + arr2[i:]
print(ans) |
print('Dratuti!')
print('Hello!')
print('Hello, Georgios!')
print('Hello, Pupa!')
| print('Dratuti!')
print('Hello!')
print('Hello, Georgios!')
print('Hello, Pupa!') |
# Copyright (C) 2018 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | _base = 'https://chromium.googlesource.com/breakpad/breakpad'
def _breakpad_impl(repository_ctx):
repository_ctx.download_and_extract(url=_BASE + '/+archive/' + repository_ctx.attr.commit + '.tar.gz', output='.')
repository_ctx.symlink(label('@gapid//tools/build/third_party/breakpad:breakpad.BUILD'), 'BUILD')
... |
DEBUG = True
SECRET_KEY = "iECgbYWReMNxkRprrzMo5KAQYnb2UeZ3bwvReTSt+VSESW0OB8zbglT+6rEcDW9X"
SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:999999@127.0.0.1:3306/fisher"
| debug = True
secret_key = 'iECgbYWReMNxkRprrzMo5KAQYnb2UeZ3bwvReTSt+VSESW0OB8zbglT+6rEcDW9X'
sqlalchemy_database_uri = 'mysql+pymysql://root:999999@127.0.0.1:3306/fisher' |
def test_shib_redirect(client, app):
r = client.get("/login/shib")
assert r.status_code == 302
def test_shib_login(app, client):
r = client.get(
"/login/shib/login", headers={app.config["SHIBBOLETH_HEADER"]: "test"}
)
assert r.status_code == 200
def test_shib_login_redirect(app, client):... | def test_shib_redirect(client, app):
r = client.get('/login/shib')
assert r.status_code == 302
def test_shib_login(app, client):
r = client.get('/login/shib/login', headers={app.config['SHIBBOLETH_HEADER']: 'test'})
assert r.status_code == 200
def test_shib_login_redirect(app, client):
r = client.... |
siblings = int(input())
popsicles = int(input())
#your code goes here
if((popsicles % siblings)==0):
print("give away")
else:
print("eat them yourself")
| siblings = int(input())
popsicles = int(input())
if popsicles % siblings == 0:
print('give away')
else:
print('eat them yourself') |
class Solution:
def minMeetingRooms(self, intervals: List[List[int]]) -> int:
minHeap = [] # store end times of each room
for start, end in sorted(intervals):
if minHeap and start >= minHeap[0]:
heapq.heappop(minHeap)
heapq.heappush(minHeap, end)
return len(minHeap)
| class Solution:
def min_meeting_rooms(self, intervals: List[List[int]]) -> int:
min_heap = []
for (start, end) in sorted(intervals):
if minHeap and start >= minHeap[0]:
heapq.heappop(minHeap)
heapq.heappush(minHeap, end)
return len(minHeap) |
class custom_range:
def __init__(self, start, end, step=1):
self.start = start
self.end = end
self.step = step
self.increment = 1
if self.step < 0:
self.start, self.end = self.end, self.start
self.increment = -1
def __iter__(self):
return... | class Custom_Range:
def __init__(self, start, end, step=1):
self.start = start
self.end = end
self.step = step
self.increment = 1
if self.step < 0:
(self.start, self.end) = (self.end, self.start)
self.increment = -1
def __iter__(self):
re... |
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
def baseN(num,b):
return (((num == 0) and "0" )
or ( baseN(num // b, b).lstrip("0")
+ digits[num % b]))
# alternatively:
def baseN(num,b):
if num == 0: return "0"
result = ""
while num != 0:
num, d = divmod(num, b)
result += d... | digits = '0123456789abcdefghijklmnopqrstuvwxyz'
def base_n(num, b):
return num == 0 and '0' or base_n(num // b, b).lstrip('0') + digits[num % b]
def base_n(num, b):
if num == 0:
return '0'
result = ''
while num != 0:
(num, d) = divmod(num, b)
result += digits[d]
return resu... |
class Counter:
"This is a counter class"
def __init__(self):
self.value = 0
def increment(self):
"Increments the counter"
self.value = self.value + 1
def decrement(self):
"Decrements the counter"
self.value = self.value - 1 | class Counter:
"""This is a counter class"""
def __init__(self):
self.value = 0
def increment(self):
"""Increments the counter"""
self.value = self.value + 1
def decrement(self):
"""Decrements the counter"""
self.value = self.value - 1 |
# Find Fractional Number
# https://www.acmicpc.net/problem/1193
n = int(input())
i = 1
while True:
sums = int((1 + i) * i * 0.5)
if sums >= n:
if (i%2) == 0:
x = i - (sums - n)
y = (sums - n) + 1
else:
x = (sums - n) + 1
y = i - (sums - n)
... | n = int(input())
i = 1
while True:
sums = int((1 + i) * i * 0.5)
if sums >= n:
if i % 2 == 0:
x = i - (sums - n)
y = sums - n + 1
else:
x = sums - n + 1
y = i - (sums - n)
print(str(x) + '/' + str(y))
break
i = i + 1 |
def for_l():
for row in range(6):
for col in range(4):
if col==1 and row<5or (row==5 and (col==0 or col==2 or col==3)) :
print("*",end=" ")
else:
print(" ",end=" ")
print()
def while_l():
row=0
while row<6:
col=0
... | def for_l():
for row in range(6):
for col in range(4):
if col == 1 and row < 5 or (row == 5 and (col == 0 or col == 2 or col == 3)):
print('*', end=' ')
else:
print(' ', end=' ')
print()
def while_l():
row = 0
while row < 6:
co... |
#
# 120. Triangle
#
# Q: https://leetcode.com/problems/triangle/
# A: https://leetcode.com/problems/triangle/discuss/38726/Kt-Js-Py3-Cpp-The-ART-of-Dynamic-Programming
#
# TopDown
class Solution:
def minimumTotal(self, A: List[List[int]]) -> int:
N = len(A)
def go(i = 0, j = 0):
if i ==... | class Solution:
def minimum_total(self, A: List[List[int]]) -> int:
n = len(A)
def go(i=0, j=0):
if i == N:
return 0
return A[i][j] + min(go(i + 1, j), go(i + 1, j + 1))
return go()
class Solution:
def minimum_total(self, A: List[List[int]]) ->... |
def remove_duplicates_v2(arr):
dedupe_arr = []
for i in arr:
if i not in dedupe_arr:
dedupe_arr.append(i)
return dedupe_arr
result = remove_duplicates([0,0,0,1,1,2,2,3,4,5])
print(result)
| def remove_duplicates_v2(arr):
dedupe_arr = []
for i in arr:
if i not in dedupe_arr:
dedupe_arr.append(i)
return dedupe_arr
result = remove_duplicates([0, 0, 0, 1, 1, 2, 2, 3, 4, 5])
print(result) |
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
for dimension in dimensions:
print(dimension)
| dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
for dimension in dimensions:
print(dimension) |
class Config():
def __init__(self):
pass
def to_dict(self):
res_dict = dict()
for key, value in self.__dict__.items():
if isinstance(value, Config):
res_dict.update(value.to_dict())
else:
res_dict[key] = value
return res_di... | class Config:
def __init__(self):
pass
def to_dict(self):
res_dict = dict()
for (key, value) in self.__dict__.items():
if isinstance(value, Config):
res_dict.update(value.to_dict())
else:
res_dict[key] = value
return res_d... |
def lazy(func):
fnattr = "__lazy_" + func.__name__
@property
def wrapper(*args, **kwargs):
if not hasattr(func, fnattr):
setattr(func, fnattr, func(*args, **kwargs))
return getattr(func, fnattr)
return wrapper
| def lazy(func):
fnattr = '__lazy_' + func.__name__
@property
def wrapper(*args, **kwargs):
if not hasattr(func, fnattr):
setattr(func, fnattr, func(*args, **kwargs))
return getattr(func, fnattr)
return wrapper |
#
# PySNMP MIB module CXFrameRelay-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXFrameRelay-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:17:11 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_intersection, constraints_union, single_value_constraint) ... |
# Note that this file is multi-lingual and can be used in both Python
# and POSIX shell.
# This file should define a variable VERSION which we use as the
# debugger version number.
VERSION = '2.9.0'
| version = '2.9.0' |
def reverse(input):
#reverse as string
return input[::-1]
#An alternative approach I wass using - string to list
'''myinput = input
mylist = list(myinput)
#print (mylist)
mylist.reverse()
return (mylist)'''
'''while True:
if input == None:
print (None)
... | def reverse(input):
return input[::-1]
'myinput = input\n mylist = list(myinput)\n #print (mylist)\n mylist.reverse()\n return (mylist)'
"while True:\n if input == None:\n print (None)\n break\n else:\n #find length of list\n l=len(mylist)-1\n #while ... |
# Similar to longest substring with k different characters, with k = 2
class Solution:
def totalFruit(self, tree: List[int]) -> int:
if not tree or len(tree) == 0:
return 0
left = 0
ans = 0
baskets = {}
# Use the dictionary to store the last index all fruits/lette... | class Solution:
def total_fruit(self, tree: List[int]) -> int:
if not tree or len(tree) == 0:
return 0
left = 0
ans = 0
baskets = {}
for (t, fruit) in enumerate(tree):
baskets[fruit] = t
if len(baskets) > 2:
left = min(bask... |
'''
Return Permutations of a String
Given a string, find and return all the possible permutations of the input string.
Note : The order of permutations are not important.
Sample Input :
abc
Sample Output :
abc
acb
bac
bca
cab
cba
'''
def permutations(string):
#Implement Your Code Here
if len(string) == 1:
... | """
Return Permutations of a String
Given a string, find and return all the possible permutations of the input string.
Note : The order of permutations are not important.
Sample Input :
abc
Sample Output :
abc
acb
bac
bca
cab
cba
"""
def permutations(string):
if len(string) == 1:
return [string]
te... |
def get_hours_since_midnight(seconds):
'''
Type the code to calculate total hours given n(number) of seconds
For example, given 3800 seconds the total hours is 1
'''
return (seconds//3600)
'''
IF YOU ARE OK WITH A GRADE OF 70 FOR THIS ASSIGNMENT STOP HERE.
'''
def get_minutes(seconds):
'''
... | def get_hours_since_midnight(seconds):
"""
Type the code to calculate total hours given n(number) of seconds
For example, given 3800 seconds the total hours is 1
"""
return seconds // 3600
'\nIF YOU ARE OK WITH A GRADE OF 70 FOR THIS ASSIGNMENT STOP HERE.\n'
def get_minutes(seconds):
"""
Ty... |
class BingoBoard:
def __init__(self) -> None:
self.board = []
self.markedNums = 0
def __repr__(self) -> str:
ret = ''
for line in self.board:
for num in line:
ret += num + ' '
ret += '\n'
return ret
def check_value(self, val:... | class Bingoboard:
def __init__(self) -> None:
self.board = []
self.markedNums = 0
def __repr__(self) -> str:
ret = ''
for line in self.board:
for num in line:
ret += num + ' '
ret += '\n'
return ret
def check_value(self, val:... |
#! /usr/bin/env python3
# coding: utf-8
def main():
with open('sample1.txt','r') as f:
content = f.read()
content = content.upper()
with open('sample2.txt','w') as f:
f.write(content)
if __name__ =='__main__':
main()
| def main():
with open('sample1.txt', 'r') as f:
content = f.read()
content = content.upper()
with open('sample2.txt', 'w') as f:
f.write(content)
if __name__ == '__main__':
main() |
f_chr6 = open("/hwfssz1/ST_BIOCHEM/P18Z10200N0032/liyiyan/SV_Caller/HG002/chr6_reads.fastq")
liness = f_chr6.readlines()
reads_list = []
for i in range(1,len(liness),4):
reads_list.append(liness[i])
res = min(reads_list, key=len,default='')
print(len(res)-1)
| f_chr6 = open('/hwfssz1/ST_BIOCHEM/P18Z10200N0032/liyiyan/SV_Caller/HG002/chr6_reads.fastq')
liness = f_chr6.readlines()
reads_list = []
for i in range(1, len(liness), 4):
reads_list.append(liness[i])
res = min(reads_list, key=len, default='')
print(len(res) - 1) |
qtd = 0
soma = 0
for i in range(1, 101, 1):
if i % 2 == 0:
qtd += 1
soma += i
media = soma / qtd
print('A media dos pares de 1 ate 100 e de {} '.format(media))
| qtd = 0
soma = 0
for i in range(1, 101, 1):
if i % 2 == 0:
qtd += 1
soma += i
media = soma / qtd
print('A media dos pares de 1 ate 100 e de {} '.format(media)) |
names = ["Adam", "Alex", "Mariah", "Martine", "Columbus"]
for word in names:
print(word)
| names = ['Adam', 'Alex', 'Mariah', 'Martine', 'Columbus']
for word in names:
print(word) |
#
# PySNMP MIB module HPNSAECC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPNSAECC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:42: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 2019,... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, constraints_intersection, value_size_constraint, value_range_constraint) ... |
# status: testado com exemplos da prova
if __name__ == '__main__':
n = int(input())
cubes = [int(x) for x in input().split()]
ways = 0
for x in range(0, n):
x_sum = cubes[x]
for y in range(x, n):
if x == y:
if cubes[y] % 8 == 0:
ways += ... | if __name__ == '__main__':
n = int(input())
cubes = [int(x) for x in input().split()]
ways = 0
for x in range(0, n):
x_sum = cubes[x]
for y in range(x, n):
if x == y:
if cubes[y] % 8 == 0:
ways += 1
else:
x_sum +... |
def albumFromID(id:int):
return f'https://www.jiosaavn.com/api.php?__call=content.getAlbumDetails&_format=json&cc=in&_marker=0%3F_marker=0&albumid={id}'
def albumsearchFromSTRING(query:str):
return f'https://www.jiosaavn.com/api.php?__call=autocomplete.get&_format=json&_marker=0&cc=in&includeMetaTags=1&query... | def album_from_id(id: int):
return f'https://www.jiosaavn.com/api.php?__call=content.getAlbumDetails&_format=json&cc=in&_marker=0%3F_marker=0&albumid={id}'
def albumsearch_from_string(query: str):
return f"https://www.jiosaavn.com/api.php?__call=autocomplete.get&_format=json&_marker=0&cc=in&includeMetaTags=1&q... |
def samesign(a, b):
return a * b > 0
def bisect(func, low, high):
'Find root of continuous function where f(low) and f(high) have opposite signs'
assert not samesign(func(low), func(high))
for i in range(54):
midpoint = (low + high) / 2.0
if samesign(func(low), func(midpoint... | def samesign(a, b):
return a * b > 0
def bisect(func, low, high):
"""Find root of continuous function where f(low) and f(high) have opposite signs"""
assert not samesign(func(low), func(high))
for i in range(54):
midpoint = (low + high) / 2.0
if samesign(func(low), func(midpoint)):
... |
i = 1
while i <= 9:
j = 1
while j <= i:
print("{}x{}={}\t".format(j, i, i * j), end='')
j += 1
print()
i += 1 | i = 1
while i <= 9:
j = 1
while j <= i:
print('{}x{}={}\t'.format(j, i, i * j), end='')
j += 1
print()
i += 1 |
print('Hello my dear') #comments are essential but I am always to lazy
print ('what is your name?')
myName = input()
print('it is nice to meet you,' + myName)
print('the length of you name is :')
print(len(myName))
print ('what is your age?')
myAge = input ()
print('you will be ' + str(int(myAge) +1) +' in a year')
| print('Hello my dear')
print('what is your name?')
my_name = input()
print('it is nice to meet you,' + myName)
print('the length of you name is :')
print(len(myName))
print('what is your age?')
my_age = input()
print('you will be ' + str(int(myAge) + 1) + ' in a year') |
#encoding:utf-8
subreddit = 'HermitCraft'
t_channel = '@r_HermitCraft'
def send_post(submission, r2t):
return r2t.send_simple(submission, min_upvotes_limit=100)
| subreddit = 'HermitCraft'
t_channel = '@r_HermitCraft'
def send_post(submission, r2t):
return r2t.send_simple(submission, min_upvotes_limit=100) |
# exc. 7.1.4
def squared_numbers(start, stop):
while start <= stop:
print(start**2)
start += 1
def main():
start = -3
stop = 3
squared_numbers(start, stop)
if __name__ == "__main__":
main() | def squared_numbers(start, stop):
while start <= stop:
print(start ** 2)
start += 1
def main():
start = -3
stop = 3
squared_numbers(start, stop)
if __name__ == '__main__':
main() |
lado = float(input())
altura = float(input())
numero = int(input())
area_1 = lado * altura
area_2 = 0
erro_max = 0
# Fazer o somatorio porposto pelo exercicio
for x in range(-50,51):
atual = numero + x
for j in range (0,atual):
area_2 += lado * (altura/(atual))
modulo_dif = abs(area_1 - area_2)
... | lado = float(input())
altura = float(input())
numero = int(input())
area_1 = lado * altura
area_2 = 0
erro_max = 0
for x in range(-50, 51):
atual = numero + x
for j in range(0, atual):
area_2 += lado * (altura / atual)
modulo_dif = abs(area_1 - area_2)
if erro_max < modulo_dif:
erro_max ... |
# Important class
class ImportantClass:
def __init__(self, var):
# Instance variable
self.var = var
# Important function
def importantFunction(self, old_var, new_var):
return old_var + new_var
# Make users happy
def makeUsersHappy(self, users):
... | class Importantclass:
def __init__(self, var):
self.var = var
def important_function(self, old_var, new_var):
return old_var + new_var
def make_users_happy(self, users):
print('Success!') |
def en_even(r):
return r[0] == "en" and len(r[1]) % 2 == 0
def en_odd(r):
return r[0] == "en" and len(r[1]) % 2 == 1
def predict(w):
def result(r):
return (r[0],r[1], np.dot(w.T, r[2])[0][0], r[3])
return result
train = rdd.filter(en_even)
test = rdd.filter(en_odd)
nxxt = train.map(x_xtransp... | def en_even(r):
return r[0] == 'en' and len(r[1]) % 2 == 0
def en_odd(r):
return r[0] == 'en' and len(r[1]) % 2 == 1
def predict(w):
def result(r):
return (r[0], r[1], np.dot(w.T, r[2])[0][0], r[3])
return result
train = rdd.filter(en_even)
test = rdd.filter(en_odd)
nxxt = train.map(x_xtransp... |
rsa_key_data = [
"9cf7192b51a574d1ad3ccb08ba09b87f228573893eee355529ff243e90fd4b86f79a82097cc7922c0485bed1616b1656a9b0b19ef78ea8ec34c384019adc5d5bf4db2d2a0a2d9cf14277bdcb7056f48b81214e3f7f7742231e29673966f9b1106862112cc798dba8d4a138bb5abfc6d4c12d53a5d39b2f783da916da20852ee139bbafda61d429caf2a4f30847ce7e7ae32ab4061e... | rsa_key_data = ['9cf7192b51a574d1ad3ccb08ba09b87f228573893eee355529ff243e90fd4b86f79a82097cc7922c0485bed1616b1656a9b0b19ef78ea8ec34c384019adc5d5bf4db2d2a0a2d9cf14277bdcb7056f48b81214e3f7f7742231e29673966f9b1106862112cc798dba8d4a138bb5abfc6d4c12d53a5d39b2f783da916da20852ee139bbafda61d429caf2a4f30847ce7e7ae32ab4061e27dd9... |
def main():
data = open("day3/input.txt", "r")
data = [line.strip() for line in data.readlines()]
tree_counter = 0
x = 0
for line in data:
if x >= len(line):
x = x % (len(line))
if line[x] == "#":
tree_counter += 1
x += 3
print(tree_counter)
if ... | def main():
data = open('day3/input.txt', 'r')
data = [line.strip() for line in data.readlines()]
tree_counter = 0
x = 0
for line in data:
if x >= len(line):
x = x % len(line)
if line[x] == '#':
tree_counter += 1
x += 3
print(tree_counter)
if __nam... |
iterations = 1
generations_list = [500]
populations_list = [30]
elitism_list = [0.2, 0.8]
mutables_list = [1] | iterations = 1
generations_list = [500]
populations_list = [30]
elitism_list = [0.2, 0.8]
mutables_list = [1] |
{
'variables': { 'target_arch%': 'ia32', 'naclversion': '0.4.5' },
'targets': [
{
'target_name': 'sodium',
'sources': [
'sodium.cc',
],
"dependencies": [
"<(module_root_dir)/dep... | {'variables': {'target_arch%': 'ia32', 'naclversion': '0.4.5'}, 'targets': [{'target_name': 'sodium', 'sources': ['sodium.cc'], 'dependencies': ['<(module_root_dir)/deps/libsodium.gyp:libsodium'], 'include_dirs': ['./deps/libsodium-<(naclversion)/src/libsodium/include'], 'cflags!': ['-fno-exceptions']}]} |
l, r = int(input()), int(input()) / 100
count = 1
result = 0
while True:
l = int(l*r)
if l <= 5:
break
result += (2**count)*l
count += 1
print(result)
| (l, r) = (int(input()), int(input()) / 100)
count = 1
result = 0
while True:
l = int(l * r)
if l <= 5:
break
result += 2 ** count * l
count += 1
print(result) |
# Given a collection of numbers that might contain duplicates, return all possible unique permutations.
# For example,
# [1,1,2] have the following unique permutations:
# [1,1,2], [1,2,1], and [2,1,1].
class Solution:
# @param {integer[]} nums
# @return {integer[][]}
def permuteUnique(self, nums):
... | class Solution:
def permute_unique(self, nums):
if not nums:
return nums
res = {(nums[0],)}
for i in range(1, len(nums)):
tmp = set()
while res:
base = res.pop()
for j in range(len(base) + 1):
tmp.add(tu... |
class Person:
'''
This class represents a person
'''
def __init__(self, id, firstname, lastname, dob):
self.id = id
self.firstname = firstname
self.lastname = lastname
self.dob = dob
def __str__(self):
return "University ID Number: " + self.id + "\nName: " +... | class Person:
"""
This class represents a person
"""
def __init__(self, id, firstname, lastname, dob):
self.id = id
self.firstname = firstname
self.lastname = lastname
self.dob = dob
def __str__(self):
return 'University ID Number: ' + self.id + '\nName: ' +... |
## CamelCase Method
## 6 kyu
## https://www.codewars.com//kata/587731fda577b3d1b0001196
def camel_case(string):
return ''.join([word.title() for word in string.split()]) | def camel_case(string):
return ''.join([word.title() for word in string.split()]) |
#
# PySNMP MIB module Juniper-E2-Registry (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-E2-Registry
# Produced by pysmi-0.3.4 at Mon Apr 29 19:51:41 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, value_size_constraint, constraints_intersection, single_value_constraint) ... |
class Solution:
def XXX(self, height: List[int]) -> int:
left = 0
right = len(height)-1
temp = 0
while left<right:
temp = max(temp,min(height[left],height[right])*(right-left))
if height[left] < height[right]:
left+=1
else:
... | class Solution:
def xxx(self, height: List[int]) -> int:
left = 0
right = len(height) - 1
temp = 0
while left < right:
temp = max(temp, min(height[left], height[right]) * (right - left))
if height[left] < height[right]:
left += 1
e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.