content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Non-OOP
# Bank Version 1
# Single account
accountName = 'Joe'
accountBalance = 100
accountPassword = 'soup'
while True:
print()
print('Press b to get the balance')
print('Press d to make a deposit')
print('Press w to make a withdrawal')
print('Press s to show the account')
print('Press q to ... | account_name = 'Joe'
account_balance = 100
account_password = 'soup'
while True:
print()
print('Press b to get the balance')
print('Press d to make a deposit')
print('Press w to make a withdrawal')
print('Press s to show the account')
print('Press q to quit')
print()
action = input('What... |
def getball():
rest()
i01.setHandSpeed("right", 0.85, 0.75, 0.75, 0.75, 0.85, 0.75)
i01.setArmSpeed("right", 1.0, 1.0, 1.0, 0.85)
i01.setHeadSpeed(0.9, 0.9)
i01.setTorsoSpeed(0.75, 0.55, 1.0)
i01.moveHead(45,65)
i01.moveArm("left",5,90,16,15)
i01.moveArm("right",6,85,110,22)
i01.moveHand("left",50,50,... | def getball():
rest()
i01.setHandSpeed('right', 0.85, 0.75, 0.75, 0.75, 0.85, 0.75)
i01.setArmSpeed('right', 1.0, 1.0, 1.0, 0.85)
i01.setHeadSpeed(0.9, 0.9)
i01.setTorsoSpeed(0.75, 0.55, 1.0)
i01.moveHead(45, 65)
i01.moveArm('left', 5, 90, 16, 15)
i01.moveArm('right', 6, 85, 110, 22)
... |
# config.py
cfg = {
'name': 'Retinaface',
'min_sizes': [[16, 32], [64, 128], [256, 512]],
'steps': [8, 16, 32],
'variance': [0.1, 0.2],
'clip': False,
'loc_weight': 2.0,
'gpu_train': True
}
| cfg = {'name': 'Retinaface', 'min_sizes': [[16, 32], [64, 128], [256, 512]], 'steps': [8, 16, 32], 'variance': [0.1, 0.2], 'clip': False, 'loc_weight': 2.0, 'gpu_train': True} |
class Publisher:
def __init__(self):
self.observers = []
def add(self, observer):
if observer not in self.observers:
self.observers.append(observer)
else:
print(f'Failed to add: {observer}')
def remove(self, observer):
... | class Publisher:
def __init__(self):
self.observers = []
def add(self, observer):
if observer not in self.observers:
self.observers.append(observer)
else:
print(f'Failed to add: {observer}')
def remove(self, observer):
try:
self.observer... |
# https://www.acmicpc.net/problem/1110
class PlusCycle(object):
def get_new_number(self, num):
sum_of_each = int(num[0]) + int(num[1])
return str(num[1]) + str(sum_of_each%10)
def get_cycle(self, n):
n = '{:02d}'.format(int(n))
target = n
count = 1
ne... | class Pluscycle(object):
def get_new_number(self, num):
sum_of_each = int(num[0]) + int(num[1])
return str(num[1]) + str(sum_of_each % 10)
def get_cycle(self, n):
n = '{:02d}'.format(int(n))
target = n
count = 1
new_number = self.get_new_number(n)
while ... |
#
# PySNMP MIB module NASUNI-FILER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file://text/NASUNI-FILER-MIB
# Produced by pysmi-0.3.4 at Mon Sep 20 10:57:46 2021
# On host C02YJ1DPJHD2 platform Darwin version 20.4.0 by user mpipaliya
# Using Python version 3.7.4 (default, Oct 12 2019, 18:55:28)
#
Integer, OctetStri... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, constraints_intersection, value_range_constraint, single_value_constraint) ... |
class VersionMixin(object):
def _get_versioned_class(self, attribute):
attribute = getattr(self, attribute)
version = self.request.version
# Return default if version is not specified
if not version:
return attribute["default"]
try:
# Return version
... | class Versionmixin(object):
def _get_versioned_class(self, attribute):
attribute = getattr(self, attribute)
version = self.request.version
if not version:
return attribute['default']
try:
return attribute[version]
except KeyError:
return a... |
def area():
return larg * comp
larg = float(input('informe a largura '))
comp = float(input('informe o comprimento '))
print(area()) | def area():
return larg * comp
larg = float(input('informe a largura '))
comp = float(input('informe o comprimento '))
print(area()) |
def csvReader(file):
''' Reads a csv file creates a dictionary with the first three
comma seperated values of each line key and the fourth as value. '''
fileObject = open(file)
data = fileObject.readlines()
dic = {}
for i in range(0,len(data)):
try:
dic[data[i].strip... | def csv_reader(file):
""" Reads a csv file creates a dictionary with the first three
comma seperated values of each line key and the fourth as value. """
file_object = open(file)
data = fileObject.readlines()
dic = {}
for i in range(0, len(data)):
try:
dic[data[i].strip('\n')... |
# solution 1
a = [1,2,1,3,4,5,5]
a = list(set(a))
print(a)
# solution 2
a = [1,2,1,3,4,5,5]
res = []
for i in a:
if i not in res:
res.append(i)
print(res)
| a = [1, 2, 1, 3, 4, 5, 5]
a = list(set(a))
print(a)
a = [1, 2, 1, 3, 4, 5, 5]
res = []
for i in a:
if i not in res:
res.append(i)
print(res) |
#Creacion de la clase
class Persona:
def __init__(self, nombre, edad):
self.__nombre = nombre
self.__edad = edad
def __str__(self):
return "Nombre: "+self.__nombre+" y edad : "+str(self.__edad)
| class Persona:
def __init__(self, nombre, edad):
self.__nombre = nombre
self.__edad = edad
def __str__(self):
return 'Nombre: ' + self.__nombre + ' y edad : ' + str(self.__edad) |
class Allergies:
def __init__(self, score):
self.score = score
def allergic_to(self, item):
return item in self.lst
@property
def lst(self):
allergieList = ['eggs', 'peanuts', 'shellfish', 'strawberries', 'tomatoes', 'chocolate', 'pollen', 'cats']
allergicTo = list()
... | class Allergies:
def __init__(self, score):
self.score = score
def allergic_to(self, item):
return item in self.lst
@property
def lst(self):
allergie_list = ['eggs', 'peanuts', 'shellfish', 'strawberries', 'tomatoes', 'chocolate', 'pollen', 'cats']
allergic_to = list()... |
'''API END_POINT'''
CENTER_CODE = 'PUT YOUR CENTER CODE HERE!!!!'
API_ENDPOINT = "PUT YOUR URL HERE!!!!"
URL_TIMEOUT = 3
'''QR Scanners config'''
IN_SCANNER = '/dev/ttyUSB0'
OUT_SCANNER = '/dev/ttyUSB1'
WAIT_SECONDS_BLOCK_DOOR = 2.5
NUM_SCANNERS = 2
'''I2C Bus Options'''
DEVICE_BUS = 1
PHY_DOORS_NUMBERS = 1
DEVICE_AD... | """API END_POINT"""
center_code = 'PUT YOUR CENTER CODE HERE!!!!'
api_endpoint = 'PUT YOUR URL HERE!!!!'
url_timeout = 3
'QR Scanners config'
in_scanner = '/dev/ttyUSB0'
out_scanner = '/dev/ttyUSB1'
wait_seconds_block_door = 2.5
num_scanners = 2
'I2C Bus Options'
device_bus = 1
phy_doors_numbers = 1
device_addr_door_1_... |
def bubble_sort(nums):
for i in range(len(nums) - 1):
for j in range(len(nums) - i - 1):
if nums[j] > nums[j + 1]:
nums[j + 1], nums[j] = nums[j], nums[j + 1]
return nums
def quick_sort(nums):
if len(nums) < 1:
return nums
p = nums[0]
l = []
r = []
... | def bubble_sort(nums):
for i in range(len(nums) - 1):
for j in range(len(nums) - i - 1):
if nums[j] > nums[j + 1]:
(nums[j + 1], nums[j]) = (nums[j], nums[j + 1])
return nums
def quick_sort(nums):
if len(nums) < 1:
return nums
p = nums[0]
l = []
r = [... |
XK_ISO_Lock = 0xFE01
XK_ISO_Level2_Latch = 0xFE02
XK_ISO_Level3_Shift = 0xFE03
XK_ISO_Level3_Latch = 0xFE04
XK_ISO_Level3_Lock = 0xFE05
XK_ISO_Group_Shift = 0xFF7E
XK_ISO_Group_Latch = 0xFE06
XK_ISO_Group_Lock = 0xFE07
XK_ISO_Next_Group = 0xFE08
XK_ISO_Next_Group_Lock = 0xFE09
XK_ISO_Prev_Group = 0xFE0A
XK_ISO_Prev_Gro... | xk_iso__lock = 65025
xk_iso__level2__latch = 65026
xk_iso__level3__shift = 65027
xk_iso__level3__latch = 65028
xk_iso__level3__lock = 65029
xk_iso__group__shift = 65406
xk_iso__group__latch = 65030
xk_iso__group__lock = 65031
xk_iso__next__group = 65032
xk_iso__next__group__lock = 65033
xk_iso__prev__group = 65034
xk_i... |
names = {'anonymous','tazri','focasa','troy','farha'};
# can use for loop for access names sets
for name in names :
print("Hello, "+name.title()+"!");
# can check value is exist in sets ?
print("\n'tazri' in names : ",'tazri' in names);
print("'solus' not in names : ",'solus' not in names);
print("'xenon' in name... | names = {'anonymous', 'tazri', 'focasa', 'troy', 'farha'}
for name in names:
print('Hello, ' + name.title() + '!')
print("\n'tazri' in names : ", 'tazri' in names)
print("'solus' not in names : ", 'solus' not in names)
print("'xenon' in names : ", 'xenon' in names) |
def GenerateConfig(context):
resources = []
project = context.env["project"]
zone = context.properties["zone"]
instance_name = "gcp-vm-" + context.env["project"]
machine_type = context.properties["machineType"]
resources.append({
"name": instance_name,
"type": "compute.v1.i... | def generate_config(context):
resources = []
project = context.env['project']
zone = context.properties['zone']
instance_name = 'gcp-vm-' + context.env['project']
machine_type = context.properties['machineType']
resources.append({'name': instance_name, 'type': 'compute.v1.instances', 'properties... |
my_vals = [623, '43', 324.523, '23', '23.23', 234, '342']
def add(values):
'''take a list of values and adds them up
We assume that the contents of the list is either int, float or str
where strings are numbers that can be converted to an int/float
Parameters
----------
values : list (any)
... | my_vals = [623, '43', 324.523, '23', '23.23', 234, '342']
def add(values):
"""take a list of values and adds them up
We assume that the contents of the list is either int, float or str
where strings are numbers that can be converted to an int/float
Parameters
----------
values : list (any)
... |
PPTIK_GRAVITY = 9.77876
class StationKind:
V1 = 'L'
STATIONARY = 'S'
MOBILE = 'M'
class StationState:
ALERT = 'A'
READY = 'R'
ECO = 'E'
HIGH_RATE = 'H'
NORMAL_RATE = 'N'
LOST = 'L' | pptik_gravity = 9.77876
class Stationkind:
v1 = 'L'
stationary = 'S'
mobile = 'M'
class Stationstate:
alert = 'A'
ready = 'R'
eco = 'E'
high_rate = 'H'
normal_rate = 'N'
lost = 'L' |
# 1st solution
class Solution:
def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:
if not firstList or not secondList:
return []
first, second = 0, 0
result = []
while first < len(firstList) and second < len(secondLi... | class Solution:
def interval_intersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:
if not firstList or not secondList:
return []
(first, second) = (0, 0)
result = []
while first < len(firstList) and second < len(secondList):
... |
#
# PySNMP MIB module WWP-VOIP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WWP-VOIP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:32:08 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, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, value_size_constraint, value_range_constraint, constraints_intersection) ... |
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
# List for visited nodes.
visited = []
#Initialize a queue
queue = []
# distance initialization (dict)
dist = {}
#function for BFS
def bfs_shortest_path(visited, graph, start_node, end_node):... | graph = {'5': ['3', '7'], '3': ['2', '4'], '7': ['8'], '2': [], '4': ['8'], '8': []}
visited = []
queue = []
dist = {}
def bfs_shortest_path(visited, graph, start_node, end_node):
global dist
dist[start_node] = 0
visited.append(start_node)
queue.append(start_node)
if start_node == end_node:
... |
def star():
print("How Much Rows You Want")
n = int(input())
print("Enter 1 or Non Zero for True and 0 For False")
n2 = int(input())
n1 = bool((n2))
if n1 is True:
for i in range(n):
i = i+1
print(i*"*")
elif n1 is False:
for i in range(n):
... | def star():
print('How Much Rows You Want')
n = int(input())
print('Enter 1 or Non Zero for True and 0 For False')
n2 = int(input())
n1 = bool(n2)
if n1 is True:
for i in range(n):
i = i + 1
print(i * '*')
elif n1 is False:
for i in range(n):
... |
#!/usr/bin/env python3
with open("input.txt", "r") as f:
num = []
for elem in f.read().split(","):
num.append(int(elem))
positions = set(num)
steps = -1
for position in positions:
current = 0
for elem in num:
current += abs(elem - position)
if steps < 0 or... | with open('input.txt', 'r') as f:
num = []
for elem in f.read().split(','):
num.append(int(elem))
positions = set(num)
steps = -1
for position in positions:
current = 0
for elem in num:
current += abs(elem - position)
if steps < 0 or current < steps:
... |
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
s, res = {}, []
for i in range(len(numbers)):
if numbers[i] in s.keys():
res.append(s[numbers[i]] + 1)
res.append(i + 1)
return res
s[target - numbe... | class Solution:
def two_sum(self, numbers: List[int], target: int) -> List[int]:
(s, res) = ({}, [])
for i in range(len(numbers)):
if numbers[i] in s.keys():
res.append(s[numbers[i]] + 1)
res.append(i + 1)
return res
s[target -... |
# historgram
def histogram(s):
d = dict()
for c in s:
a = d.get(c, 0)
d[c] = 1+a
return sorted(d)
h = histogram("brantosaurus")
print(h)
| def histogram(s):
d = dict()
for c in s:
a = d.get(c, 0)
d[c] = 1 + a
return sorted(d)
h = histogram('brantosaurus')
print(h) |
class FirmwareGPIO:
def __init__(self, scfg):
crtl_inputs = scfg.analog_ctrl_inputs + scfg.digital_ctrl_inputs
ctrl_outputs = scfg.analog_ctrl_outputs + scfg.digital_ctrl_outputs
self.getter_dict = {}
for probe in ctrl_outputs:
if probe.o_addr is not None:
... | class Firmwaregpio:
def __init__(self, scfg):
crtl_inputs = scfg.analog_ctrl_inputs + scfg.digital_ctrl_inputs
ctrl_outputs = scfg.analog_ctrl_outputs + scfg.digital_ctrl_outputs
self.getter_dict = {}
for probe in ctrl_outputs:
if probe.o_addr is not None:
... |
def Articles():
articles = [
{
'id' : 1,
'title' : 'Article one',
'body' : 'Now ParseHub will call this handler every time the status of a run changes. It doesnt matter how long the run takes, or if it queued up on our servers for a while. Itll just work',
'auther': 'Refuge',
'create_date' : ... | def articles():
articles = [{'id': 1, 'title': 'Article one', 'body': 'Now ParseHub will call this handler every time the status of a run changes. It doesnt matter how long the run takes, or if it queued up on our servers for a while. Itll just work', 'auther': 'Refuge', 'create_date': '04-24-2018'}, {'id': 2, 'tit... |
DOMAIN = "ble_mesh"
PLATFORM_LIGHT = "light"
HANDLE_ID = 14
CMD_FUNCTION = 0xFB
CMD_GPIO_CONTROL = 0xE7
CMD_OUT_1 = 0xF1
CMD_ON = 0x01
CMD_OFF = 0x00
| domain = 'ble_mesh'
platform_light = 'light'
handle_id = 14
cmd_function = 251
cmd_gpio_control = 231
cmd_out_1 = 241
cmd_on = 1
cmd_off = 0 |
for _ in range(int(input())):
a, b = [int(i) for i in input().split()]
if a > b: print(">")
elif a < b: print("<")
else: print("=") | for _ in range(int(input())):
(a, b) = [int(i) for i in input().split()]
if a > b:
print('>')
elif a < b:
print('<')
else:
print('=') |
a = list(input())
cnt = 0
x = 0
for i in range(len(a)-1):
if a[i] == a[i+1]:
cnt += 1
if x <= cnt:
x = cnt
elif a[i] != a[i+1]:
cnt = 0
print(x+1) | a = list(input())
cnt = 0
x = 0
for i in range(len(a) - 1):
if a[i] == a[i + 1]:
cnt += 1
if x <= cnt:
x = cnt
elif a[i] != a[i + 1]:
cnt = 0
print(x + 1) |
# Test proper handling of exceptions within generator across yield
def gen():
try:
yield 1
raise ValueError
print("FAIL")
raise SystemExit
except ValueError:
pass
yield 2
for i in gen():
print(i)
# Test throwing exceptions out of generator
def gen2():
yield... | def gen():
try:
yield 1
raise ValueError
print('FAIL')
raise SystemExit
except ValueError:
pass
yield 2
for i in gen():
print(i)
def gen2():
yield 1
raise ValueError
yield 2
yield 3
g = gen2()
print(next(g))
try:
print(next(g))
print('FAIL... |
with open("testfile.txt", "wb") as f1:
for i in range(0, 65536):
a = i//256
b = i%256
f1.write(bytes([a, b]))
| with open('testfile.txt', 'wb') as f1:
for i in range(0, 65536):
a = i // 256
b = i % 256
f1.write(bytes([a, b])) |
# Array (mutable, resizable)
class Array:
# Declare the necessary values used for the Array
_capacity = None
_size = None
_array = None
# Initialize these values with the capacity chosen
def __init__(self, capacity):
self._capacity = capacity
self._size = 0
self._array ... | class Array:
_capacity = None
_size = None
_array = None
def __init__(self, capacity):
self._capacity = capacity
self._size = 0
self._array = [None] * capacity
def get_size(self):
return self._size
def get_capacity(self):
return self._capacity
def ... |
class Solution:
def nextGreaterElements(self, nums: list) -> list:
if not nums:
return []
monotonic_stack = [(nums[0], 0)]
nums = nums + nums
next_greater = {}
for i, num in enumerate(nums[1:], 1):
while monotonic_stack:
... | class Solution:
def next_greater_elements(self, nums: list) -> list:
if not nums:
return []
monotonic_stack = [(nums[0], 0)]
nums = nums + nums
next_greater = {}
for (i, num) in enumerate(nums[1:], 1):
while monotonic_stack:
if num > m... |
# List of rooms, characters, and weapons
room_list = ['Study','Hall','Lounge','Library','Billiard','Dining','Conservatory','Ballroom','Kitchen']
hall_list = ['Hall A','Hall B','Hall C','Hall D','Hall E','Hall F','Hall G','Hall H','Hall I','Hall J','Hall K','Hall L']
character_list = ['Miss Scarlet','Mrs. Peacock','Prof... | room_list = ['Study', 'Hall', 'Lounge', 'Library', 'Billiard', 'Dining', 'Conservatory', 'Ballroom', 'Kitchen']
hall_list = ['Hall A', 'Hall B', 'Hall C', 'Hall D', 'Hall E', 'Hall F', 'Hall G', 'Hall H', 'Hall I', 'Hall J', 'Hall K', 'Hall L']
character_list = ['Miss Scarlet', 'Mrs. Peacock', 'Professor Plum', 'Mr. Bo... |
class MetadataNotFound(Exception):
pass
class MetadataCorruption(Exception):
pass
class NotYetImplemented(Exception):
pass
class SPConfigurationMissing(Exception):
pass
| class Metadatanotfound(Exception):
pass
class Metadatacorruption(Exception):
pass
class Notyetimplemented(Exception):
pass
class Spconfigurationmissing(Exception):
pass |
inp = input()
arr = inp.split(' ')
L = int(arr[0])
N = int(arr[1])
dic = []
for i in range(0,L):
st = input()
stri = st.split(' ')
dic.append(stri)
for i in range(0,N):
inp = input()
tr = False
for j in range(0,L):
temp = dic[j]
if(inp == temp[0]):
print(temp[1])
tr = T... | inp = input()
arr = inp.split(' ')
l = int(arr[0])
n = int(arr[1])
dic = []
for i in range(0, L):
st = input()
stri = st.split(' ')
dic.append(stri)
for i in range(0, N):
inp = input()
tr = False
for j in range(0, L):
temp = dic[j]
if inp == temp[0]:
print(temp[1])
... |
__all__ = (
'decode_int',
'decode_str',
'decode_lst'
)
def decode_int(data, pos):
end = data[pos:].index(b'e')
if data[pos+1] == ord('-'):
return (int(data[pos + 2:pos + end]) * -1, end)
else:
return (int(data[pos + 1:pos + end]), end + pos)
# return data as raw byte... | __all__ = ('decode_int', 'decode_str', 'decode_lst')
def decode_int(data, pos):
end = data[pos:].index(b'e')
if data[pos + 1] == ord('-'):
return (int(data[pos + 2:pos + end]) * -1, end)
else:
return (int(data[pos + 1:pos + end]), end + pos)
def decode_str(data, pos):
index = data[pos:... |
def seat_decode(seat):
row = int(seat[:7].replace("F", "0").replace("B", "1"), 2)
column = int(seat[7:].replace("L", "0").replace("R", "1"), 2)
return row * 8 + column
if __name__ == "__main__":
with open("input.txt", "r") as f:
ids = {seat_decode(line.strip()) for line in f.readlines()}
... | def seat_decode(seat):
row = int(seat[:7].replace('F', '0').replace('B', '1'), 2)
column = int(seat[7:].replace('L', '0').replace('R', '1'), 2)
return row * 8 + column
if __name__ == '__main__':
with open('input.txt', 'r') as f:
ids = {seat_decode(line.strip()) for line in f.readlines()}
... |
dicio = {"Nome": str(input('Nome do jogador: '))}
partidas = int(input(f'Quantas partidas {dicio["Nome"]} jogou? '))
lista = []
for c in range(partidas):
dicio["Gols"] = int((input(f'Quantos gols na partida {c+1}: ')))
lista.append(dicio["Gols"])
dicio["Gols"] = lista
total = int()
for c in lista:
total += ... | dicio = {'Nome': str(input('Nome do jogador: '))}
partidas = int(input(f"Quantas partidas {dicio['Nome']} jogou? "))
lista = []
for c in range(partidas):
dicio['Gols'] = int(input(f'Quantos gols na partida {c + 1}: '))
lista.append(dicio['Gols'])
dicio['Gols'] = lista
total = int()
for c in lista:
total += ... |
def data():
return {
"test": {
"min/layer2/weights": {
"displayName": "min/layer2/weights",
"description": ""
}
},
"train": {
"min/layer2/weights": {
"displayName": "min/layer2/weights",
"desc... | def data():
return {'test': {'min/layer2/weights': {'displayName': 'min/layer2/weights', 'description': ''}}, 'train': {'min/layer2/weights': {'displayName': 'min/layer2/weights', 'description': ''}}} |
#!/usr/bin/env/ python
# encoding: utf-8
__author__ = 'aldur'
| __author__ = 'aldur' |
# Python 3.6.1
with open("input.txt", "r") as f:
puzzle_input = []
for line in f:
puzzle_input.append(line.strip().split(" "))
total = 0
for phrase in puzzle_input:
bad = False
for word in phrase:
if phrase.count(word) > 1:
bad = True
break
if not bad:
... | with open('input.txt', 'r') as f:
puzzle_input = []
for line in f:
puzzle_input.append(line.strip().split(' '))
total = 0
for phrase in puzzle_input:
bad = False
for word in phrase:
if phrase.count(word) > 1:
bad = True
break
if not bad:
total += 1
pri... |
def Select_sort1():
A = [-9, -8, 640, 25, 12, 22, 33, 23, 45, 11, -2, -5, 99, 0]
for i in range(len(A)):
minimum = i
for j in range(i+1, len(A)):
if A[minimum] > A[j]:
minimum = j
A[i], A[minimum] = A[minimum], A[i]
print("After sort:")
print(A)
def ... | def select_sort1():
a = [-9, -8, 640, 25, 12, 22, 33, 23, 45, 11, -2, -5, 99, 0]
for i in range(len(A)):
minimum = i
for j in range(i + 1, len(A)):
if A[minimum] > A[j]:
minimum = j
(A[i], A[minimum]) = (A[minimum], A[i])
print('After sort:')
print(A)
... |
emails = sorted(set([line.strip() for line in open("email_domains.txt")]))
for email in emails:
print("'{email}',".format(email=email))
| emails = sorted(set([line.strip() for line in open('email_domains.txt')]))
for email in emails:
print("'{email}',".format(email=email)) |
for _ in range(int(input())):
string = input()
new_str= ""
new_str += string[0]
for i in range(1, len(string)):
if string[i] == "L":
on = string[i-1]
elif string[i] == "R":
on = string[i+1]
else:
on = string[i]
new_str += on
print(... | for _ in range(int(input())):
string = input()
new_str = ''
new_str += string[0]
for i in range(1, len(string)):
if string[i] == 'L':
on = string[i - 1]
elif string[i] == 'R':
on = string[i + 1]
else:
on = string[i]
new_str += on
pr... |
# https://www.hackerrank.com/challenges/any-or-all/problem
def is_palindrome(number):
return number == number[::-1]
N = int(input())
array = list(input().split())
print(
all(int(element) >= 0 for element in array)
and any(is_palindrome(element) for element in array)
)
| def is_palindrome(number):
return number == number[::-1]
n = int(input())
array = list(input().split())
print(all((int(element) >= 0 for element in array)) and any((is_palindrome(element) for element in array))) |
def flownet_v1_s(input):
pass
| def flownet_v1_s(input):
pass |
prime = [2,3]
i = 4
while len(prime)<10001:
s = True
for j in prime:
if i%j == 0:
s = False
break
if s:
prime.append(i)
i = i + 1
print(prime[-1]) | prime = [2, 3]
i = 4
while len(prime) < 10001:
s = True
for j in prime:
if i % j == 0:
s = False
break
if s:
prime.append(i)
i = i + 1
print(prime[-1]) |
def rotation_string(str):
l = []
#str = ""
for i in str:
l.append(i)
#print(l)
for j in range(len(l) // 2):
a = l[j]
b = l[-(j+1)]
l[j] = b
l[-(j+1)] = a
return l | def rotation_string(str):
l = []
for i in str:
l.append(i)
for j in range(len(l) // 2):
a = l[j]
b = l[-(j + 1)]
l[j] = b
l[-(j + 1)] = a
return l |
def descending(x,n):
t=0
# by selection sorting
for i in range(0,n-1,1):
for j in range(i+1,n,1):
if x[i]<x[j]:
t=x[i]
x[i]=x[j]
x[j]=t
return (x)
# To sort a list in descending order
print("This programme sorts a list in d... | def descending(x, n):
t = 0
for i in range(0, n - 1, 1):
for j in range(i + 1, n, 1):
if x[i] < x[j]:
t = x[i]
x[i] = x[j]
x[j] = t
return x
print('This programme sorts a list in descending order : ')
n = int(input('Enter the number of elem... |
config = {'MAX_BOUND':512.0,
'MIN_BOUND':-1024.0,
'PIXEL_MEAN':0.25,
'NORM_CROP':True
} | config = {'MAX_BOUND': 512.0, 'MIN_BOUND': -1024.0, 'PIXEL_MEAN': 0.25, 'NORM_CROP': True} |
#
# PySNMP MIB module ELTEX-ULD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-ULD-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:48:10 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, constraints_intersection, constraints_union, value_size_constraint) ... |
n = int(input('Enter a Value for N:\n'))
count = 1
while count <= n:
v1 = count
v2 = count + 1
if count +2 < n:
v3 = count + 2
else:
v3 = ' '
print(f'{v1} {v2} {v3}')
count += 3 | n = int(input('Enter a Value for N:\n'))
count = 1
while count <= n:
v1 = count
v2 = count + 1
if count + 2 < n:
v3 = count + 2
else:
v3 = ' '
print(f'{v1} {v2} {v3}')
count += 3 |
# https://www.codewars.com/kata/578553c3a1b8d5c40300037c/python
# Given an array of ones and zeroes, convert the equivalent binary value to an integer.
# Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1.
# Examples:
# Testing: [0, 0, 0, 1] ==> 1
# Testing: [0, 0, 1, 0] ==> 2
# Testing: [0, ... | def binary_array_to_number(arr):
binary = ''.join(map(str, arr))
return int(binary, 2)
print(binary_array_to_number([1, 0, 0, 0, 1])) |
def gap_sort(x):
gap = len(x)
swap= True
while gap > 1 or swap:
gap = max(1, int(gap / 1.3))
swap= False
for i in range(len(x) - gap):
j = i+gap
if x[i] > x[j]:
x[i], x[j] = x[j], x[i]
swap= True
lst = [3,6,4,8,9,0,6,5,2,10,... | def gap_sort(x):
gap = len(x)
swap = True
while gap > 1 or swap:
gap = max(1, int(gap / 1.3))
swap = False
for i in range(len(x) - gap):
j = i + gap
if x[i] > x[j]:
(x[i], x[j]) = (x[j], x[i])
swap = True
lst = [3, 6, 4, 8, 9, 0... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
modelChemistry = "CBS-QB3"
useHinderedRotors = True
useBondCorrections = False
species('CH2CHOOH', 'CH2CHOOH.py')
statmech('CH2CHOOH')
thermo('CH2CHOOH', 'Wilhoit')
| model_chemistry = 'CBS-QB3'
use_hindered_rotors = True
use_bond_corrections = False
species('CH2CHOOH', 'CH2CHOOH.py')
statmech('CH2CHOOH')
thermo('CH2CHOOH', 'Wilhoit') |
#: Module purely exists to test patching things.
thing = True
it = lambda: False
def get_thing():
global thing
return thing
def get_it():
global it
return it
| thing = True
it = lambda : False
def get_thing():
global thing
return thing
def get_it():
global it
return it |
li=[]
n=int(input("Enter Number of Elements in List"))
print("Enter Numbers")
for i in range(n):
ele=int(input())
li.append(ele)
l1=[]
for i in li:
l1.insert(len(l1)-1,i)
print(l1)
| li = []
n = int(input('Enter Number of Elements in List'))
print('Enter Numbers')
for i in range(n):
ele = int(input())
li.append(ele)
l1 = []
for i in li:
l1.insert(len(l1) - 1, i)
print(l1) |
phone_book = dict()
enough = False
while True:
if enough:
break
command = input()
if command == 'stop':
break
elif command == 'search':
while True:
person = input()
if person == 'stop':
enough = True
break
... | phone_book = dict()
enough = False
while True:
if enough:
break
command = input()
if command == 'stop':
break
elif command == 'search':
while True:
person = input()
if person == 'stop':
enough = True
break
if per... |
#In this program we will enter a number and get its factors as the output in a list format.
num = int(input("Enter number: "))
def factors(n):
flist = []
for i in range(1,n+1):
if n%i == 0:
flist.append(i)
return flist
print(factors(num))
| num = int(input('Enter number: '))
def factors(n):
flist = []
for i in range(1, n + 1):
if n % i == 0:
flist.append(i)
return flist
print(factors(num)) |
class initial():
def solution(self, nums):
prefix = [1] * len(nums)
suffix = [1] * len(nums)
for i in range(1, len(nums)):
prefix[i] = prefix[i-1] * nums[i-1]
for j in range(len(nums)-2, -1, -1):
suffix[j] = suffix[j+1] * nums[j+1]
return [prefix[i]... | class Initial:
def solution(self, nums):
prefix = [1] * len(nums)
suffix = [1] * len(nums)
for i in range(1, len(nums)):
prefix[i] = prefix[i - 1] * nums[i - 1]
for j in range(len(nums) - 2, -1, -1):
suffix[j] = suffix[j + 1] * nums[j + 1]
return [pre... |
def parse(filename: str) -> list[int]:
with open(filename) as file:
line = file.read()
return list(map(int, line.split(',')))
def solve(fishes: list[int], days: int) -> int:
for _ in range(days):
for i in range(len(fishes)):
fishes[i] -= 1
if fishes[i] < 0:
... | def parse(filename: str) -> list[int]:
with open(filename) as file:
line = file.read()
return list(map(int, line.split(',')))
def solve(fishes: list[int], days: int) -> int:
for _ in range(days):
for i in range(len(fishes)):
fishes[i] -= 1
if fishes[i] < 0:
... |
#leia o tamanho do lado de um quadrado e
#imprima como resultado a area.
lado=float(input("Informe o lado do quadrado: "))
area=lado*lado
print(f"A area do quadrado eh {area}") | lado = float(input('Informe o lado do quadrado: '))
area = lado * lado
print(f'A area do quadrado eh {area}') |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
maxi = 0
... | class Solution:
def diameter_of_binary_tree(self, root: Optional[TreeNode]) -> int:
maxi = 0
def dfs(node):
nonlocal maxi
if node is None:
return -1
left = dfs(node.left) + 1
right = dfs(node.right) + 1
cur_sum = left + ri... |
class dotHierarchicList_t(object):
# no doc
aObjects = None
ModelFatherObject = None
nObjects = None
ObjectsLeftToGet = None
OperationType = None
| class Dothierarchiclist_T(object):
a_objects = None
model_father_object = None
n_objects = None
objects_left_to_get = None
operation_type = None |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if not head:
return None
if not head.next:
return head
tem... | class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def swap_pairs(self, head: ListNode) -> ListNode:
if not head:
return None
if not head.next:
return head
temp = head.next
head.next = s... |
'''
Factorial (hacker challenge). Write a function factorial() that returns the
factorial of the given number. For example, factorial(5) should return 120.
Do this using recursion; remember that factorial(n) = n * factorial(n-1).
'''
def factorial(n):
if n == 1 or n == 0:
return 1
if n == 2:
... | """
Factorial (hacker challenge). Write a function factorial() that returns the
factorial of the given number. For example, factorial(5) should return 120.
Do this using recursion; remember that factorial(n) = n * factorial(n-1).
"""
def factorial(n):
if n == 1 or n == 0:
return 1
if n == 2:
... |
def infini(y : int) -> int:
x : int = y
while x >= 0:
x = x + 1
return x
def f(x : int) -> int:
return x + 1
| def infini(y: int) -> int:
x: int = y
while x >= 0:
x = x + 1
return x
def f(x: int) -> int:
return x + 1 |
def changeConf(xmin=2., xmax=16., resolution=2, Nxx=1000, Ntt=20000, \
every_scalar_t=10, every_aaray_t=100, \
amplitud=0.1, sigma=1, x0=9., Boundaries=0, Metric=1):
conf = open('input.par','w')
conf.write('¶meters')
conf.write('xmin = ' + str(xmin) + '\n... | def change_conf(xmin=2.0, xmax=16.0, resolution=2, Nxx=1000, Ntt=20000, every_scalar_t=10, every_aaray_t=100, amplitud=0.1, sigma=1, x0=9.0, Boundaries=0, Metric=1):
conf = open('input.par', 'w')
conf.write('¶meters')
conf.write('xmin = ' + str(xmin) + '\n')
conf.write('xmax = ' + str(xmax) + '\n')
... |
class Day3:
def part1(self):
with open(r'C:\Coding\AdventOfCode\AOC2019\Data\Data3.txt') as f:
lines = f.read().splitlines()
firstPath = lines[0].split(',')
secondPath = lines[1].split(',')
firstPathCoordinates = self.wiresPositionsDictionary(firstPath)
secondPa... | class Day3:
def part1(self):
with open('C:\\Coding\\AdventOfCode\\AOC2019\\Data\\Data3.txt') as f:
lines = f.read().splitlines()
first_path = lines[0].split(',')
second_path = lines[1].split(',')
first_path_coordinates = self.wiresPositionsDictionary(firstPath)
s... |
# --------------------------------------
#! /usr/bin/python
# File: 283. Move Zeros.py
# Author: Kimberly Gao
class Solution:
def _init_(self,name):
self.name = name
# My 1st solution: (Run time: 68ms(29.57%)) (2 pointer)
# Memory Usage: 15.4 MB (61.79%)
def moveZeros1(self, nums):
slo... | class Solution:
def _init_(self, name):
self.name = name
def move_zeros1(self, nums):
slow = 0
for fast in range(len(nums)):
if nums[fast] != 0:
nums[slow] = nums[fast]
slow += 1
for fast in range(slow, len(nums)):
nums[fa... |
'''
Created on Nov 3, 2018
@author: nilson.nieto
'''
list_numeros =input("Ingrese varios numeros separados por espacio : ").split(" , ")
for i in list_numeros:
print(i) | """
Created on Nov 3, 2018
@author: nilson.nieto
"""
list_numeros = input('Ingrese varios numeros separados por espacio : ').split(' , ')
for i in list_numeros:
print(i) |
def get_fuel(mass):
return int(mass / 3) - 2
def get_fuel_including_fuel(mass):
total = 0
while True:
fuel = get_fuel(mass)
if fuel <= 0:
break
total += fuel
mass = fuel
return total
# Part one
with open('input') as f:
print(sum(
get_fuel(
... | def get_fuel(mass):
return int(mass / 3) - 2
def get_fuel_including_fuel(mass):
total = 0
while True:
fuel = get_fuel(mass)
if fuel <= 0:
break
total += fuel
mass = fuel
return total
with open('input') as f:
print(sum((get_fuel(int(line)) for line in f)))... |
class Manager:
def __init__(self):
self.worker = None
def set_worker(self, worker):
assert "Worker" in [el.__name__ for el in worker.__class__.__mro__], "'worker' must be of type Worker"
self.worker = worker
def manage(self):
if self.worker is not None:
self.wo... | class Manager:
def __init__(self):
self.worker = None
def set_worker(self, worker):
assert 'Worker' in [el.__name__ for el in worker.__class__.__mro__], "'worker' must be of type Worker"
self.worker = worker
def manage(self):
if self.worker is not None:
self.wo... |
N, K = map(int, input().split())
A = [0]
total = 0
a = list(map(int, input().split()))
ans = 0
m = {0: 1}
for x in a:
total += x
count = m.get(total - K, 0)
ans += count
m[total] = m.get(total, 0) + 1
A.append(total)
print(ans) | (n, k) = map(int, input().split())
a = [0]
total = 0
a = list(map(int, input().split()))
ans = 0
m = {0: 1}
for x in a:
total += x
count = m.get(total - K, 0)
ans += count
m[total] = m.get(total, 0) + 1
A.append(total)
print(ans) |
class Solution:
def findMaxAverage(self, nums: List[int], k: int) -> float:
# sliding window, O(N) time, O(1) space
globMax = tempMax = sum(nums[:k])
for i in range(k, len(nums)):
tempMax += (nums[i] - nums[i-k])
globMax = max(tempMax, globMax)
return globMax ... | class Solution:
def find_max_average(self, nums: List[int], k: int) -> float:
glob_max = temp_max = sum(nums[:k])
for i in range(k, len(nums)):
temp_max += nums[i] - nums[i - k]
glob_max = max(tempMax, globMax)
return globMax / k |
#Task 4: Login functionality
# In its parameter list, define three parameters: database, username, and password.
def login(database, username, password):
if username in dict.keys(database) and database[username] == password:
print("Welcome back: ", username)
elif username in dict.keys(database) or pass... | def login(database, username, password):
if username in dict.keys(database) and database[username] == password:
print('Welcome back: ', username)
elif username in dict.keys(database) or password in dict.values(database):
print('Check your credentials again!')
else:
print('Something w... |
H, W = map(int, input().split())
N = 0
a_map = []
for i in range(H):
a = list(map(int, input().split()))
a_map.append(a)
result = []
for i in range(H):
for j in range(W):
if a_map[i][j]%2==1:
if j < W - 1:
N += 1
result.append([i + 1, j + 1, i + 1, j + 2])... | (h, w) = map(int, input().split())
n = 0
a_map = []
for i in range(H):
a = list(map(int, input().split()))
a_map.append(a)
result = []
for i in range(H):
for j in range(W):
if a_map[i][j] % 2 == 1:
if j < W - 1:
n += 1
result.append([i + 1, j + 1, i + 1, j... |
class Stairs:
def designs(self, maxHeight, minWidth, totalHeight, totalWidth):
c = 0
for r in xrange(1, maxHeight + 1):
if totalHeight % r == 0:
n = totalHeight / r
if (
n > 1
and totalWidth % (n - 1) == 0
... | class Stairs:
def designs(self, maxHeight, minWidth, totalHeight, totalWidth):
c = 0
for r in xrange(1, maxHeight + 1):
if totalHeight % r == 0:
n = totalHeight / r
if n > 1 and totalWidth % (n - 1) == 0 and (totalWidth / (n - 1) >= minWidth):
... |
length = int(raw_input())
s = raw_input()
n = length / 4
A = T = G = C = 0
for i in s:
if i == 'A':
A += 1
elif i == 'T':
T += 1
elif i == 'G':
G += 1
else:
C += 1
res = 0
if A != n or C != n or G != n or T != n:
res = length
l = 0
for r in xrange(length):
... | length = int(raw_input())
s = raw_input()
n = length / 4
a = t = g = c = 0
for i in s:
if i == 'A':
a += 1
elif i == 'T':
t += 1
elif i == 'G':
g += 1
else:
c += 1
res = 0
if A != n or C != n or G != n or (T != n):
res = length
l = 0
for r in xrange(length):
... |
class JellyBean:
def __init__( self, mass = 0 ):
self.mass = mass
def __add__( self, other ):
other_mass = other.mass
other.mass = 0
return JellyBean( self.mass + other_mass )
def __sub__( self, other ):
self_mass = self.mass
self.mass -= other.mass
def... | class Jellybean:
def __init__(self, mass=0):
self.mass = mass
def __add__(self, other):
other_mass = other.mass
other.mass = 0
return jelly_bean(self.mass + other_mass)
def __sub__(self, other):
self_mass = self.mass
self.mass -= other.mass
def __str__... |
class PlayerAlreadyHasItemError(Exception):
pass
class PlayerNotInitializedError(Exception):
pass
| class Playeralreadyhasitemerror(Exception):
pass
class Playernotinitializederror(Exception):
pass |
# Preferences defaults
PREFERENCES_PATH = "./config/preferences.json"
PREFERENCES_DEFAULTS = {
'on_time': 1200,
'off_time': 300
}
# Bot configureation
DISCORD_TOKEN = "from https://discord.com/developers"
ADMIN_ID = 420
USER_ID = 999
DEV_MODE = True
PREFIX = '!!'
PREFIXES = ('johnsmith ', 'john smith ')
COGS_L... | preferences_path = './config/preferences.json'
preferences_defaults = {'on_time': 1200, 'off_time': 300}
discord_token = 'from https://discord.com/developers'
admin_id = 420
user_id = 999
dev_mode = True
prefix = '!!'
prefixes = ('johnsmith ', 'john smith ')
cogs_list = ['cogs.misc', 'cogs.testing', 'cogs.admin'] |
# has_good_credit = True
# has_criminal_record = True
#
# if has_good_credit and not has_criminal_record:
# print("Eligible for loan")
# temperature = 35
#
# if temperature > 30:
# print("It's a hot day")
# else:
# print("It's not a hot day")
name = "ddddddddddddddddddddddddddddddddddddddddddddddddddddddd... | name = 'dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd'
if len(name) < 3:
print('Name must be at least 3 characters long')
elif len(name) > 50:
print('Name cannot be more than 50 characters long')
else:
print('Name looks good!') |
x = ''
while True:
x = input()
print(x)
if x == 'end':
break
print('end') | x = ''
while True:
x = input()
print(x)
if x == 'end':
break
print('end') |
# -*- coding: utf-8 -*-
def main():
s = sorted([input() for _ in range(15)])
print(s[6])
if __name__ == '__main__':
main()
| def main():
s = sorted([input() for _ in range(15)])
print(s[6])
if __name__ == '__main__':
main() |
# Perulangan pada set dan dictionary
print('\n==========Perulangan Pada Set==========')
set_integer = {10, 20, 30, 40, 50}
# Cara pertama
for item in set_integer:
print(item, end=' ')
print('')
# Cara kedua
for i in range(len(set_integer)):
print(list(set_integer)[i], end=' ')
print('')
# Cara ketiga
i = 0... | print('\n==========Perulangan Pada Set==========')
set_integer = {10, 20, 30, 40, 50}
for item in set_integer:
print(item, end=' ')
print('')
for i in range(len(set_integer)):
print(list(set_integer)[i], end=' ')
print('')
i = 0
while i < len(set_integer):
print(list(set_integer)[i], end=' ')
i = i + 1
... |
def word_time(word, elapsed_time):
return [word, elapsed_time]
p0 = [word_time('START', 0), word_time('What', 0.2), word_time('great', 0.4), word_time('luck', 0.8)]
p1 = [word_time('START', 0), word_time('What', 0.6), word_time('great', 0.8), word_time('luck', 1.19)]
p0
p1 | def word_time(word, elapsed_time):
return [word, elapsed_time]
p0 = [word_time('START', 0), word_time('What', 0.2), word_time('great', 0.4), word_time('luck', 0.8)]
p1 = [word_time('START', 0), word_time('What', 0.6), word_time('great', 0.8), word_time('luck', 1.19)]
p0
p1 |
# Definition for singly-linked list.
# class LinkedListNode:
# def __init__(self, value = 0, next = None):
# self.value = value
# self.next = next
class Solution:
def containsCycle(self, head):
if not head or not head.next:
return False
current = head
... | class Solution:
def contains_cycle(self, head):
if not head or not head.next:
return False
current = head
s = set()
while current:
if id(current) in s:
return True
s.add(id(current))
current = current.next
retur... |
def inf():
while True:
yield
for _ in inf():
input('>')
| def inf():
while True:
yield
for _ in inf():
input('>') |
def grep(pattern):
print("Searching for", pattern)
while True:
line = (yield)
if pattern in line:
print(line)
search = grep('coroutine')
next(search)
search.send("I love you")
search.send("Don't you love me")
search.send("I love coroutines")
| def grep(pattern):
print('Searching for', pattern)
while True:
line = (yield)
if pattern in line:
print(line)
search = grep('coroutine')
next(search)
search.send('I love you')
search.send("Don't you love me")
search.send('I love coroutines') |
def conf():
return {
"id":"discord",
"description":"this is the discord c360 component",
"enabled":False,
} | def conf():
return {'id': 'discord', 'description': 'this is the discord c360 component', 'enabled': False} |
S = input()
l = len(S)
nhug = 0
for i in range(l//2):
if S[i] != S[l-1-i]:
nhug += 1
print(nhug)
| s = input()
l = len(S)
nhug = 0
for i in range(l // 2):
if S[i] != S[l - 1 - i]:
nhug += 1
print(nhug) |
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print("Hi there! I'm {}, {} years old!".format(self.name, self.age))
maria = Person("Maria Popova", 25)
pesho = Person("Pesho", 27)
print(maria)
# name = Maria Popova
# age = 25 | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print("Hi there! I'm {}, {} years old!".format(self.name, self.age))
maria = person('Maria Popova', 25)
pesho = person('Pesho', 27)
print(maria) |
class Solution:
def maxNumber(self, nums1, nums2, k):
def merge(arr1, arr2):
res, i, j = [], 0, 0
while i < len(arr1) and j < len(arr2):
if arr1[i:] >= arr2[j:]:
res.append(arr1[i])
i += 1
else:
... | class Solution:
def max_number(self, nums1, nums2, k):
def merge(arr1, arr2):
(res, i, j) = ([], 0, 0)
while i < len(arr1) and j < len(arr2):
if arr1[i:] >= arr2[j:]:
res.append(arr1[i])
i += 1
else:
... |
def sudoku2(grid):
seen = set()
# Iterate through grid
for i in range(len(grid)):
for j in range(len(grid[i])):
current_value = grid[i][j]
if current_value != ".":
if (
(current_value + " found in row " + str(i)) in seen
... | def sudoku2(grid):
seen = set()
for i in range(len(grid)):
for j in range(len(grid[i])):
current_value = grid[i][j]
if current_value != '.':
if current_value + ' found in row ' + str(i) in seen or current_value + ' found in column ' + str(j) in seen or current_val... |
FEATURES = 'FEATURES'
AUTH_GITHUB = 'AUTH_GITHUB'
AUTH_GITLAB = 'AUTH_GITLAB'
AUTH_BITBUCKET = 'AUTH_BITBUCKET'
AUTH_AZURE = 'AUTH_AZURE'
AFFINITIES = 'AFFINITIES'
ARCHIVES_ROOT = 'ARCHIVES_ROOT'
DOWNLOADS_ROOT = 'DOWNLOADS_ROOT'
ADMIN = 'ADMIN'
NODE_SELECTORS = 'NODE_SELECTORS'
TOLERATIONS = 'TOLERATIONS'
ANNOTATIONS ... | features = 'FEATURES'
auth_github = 'AUTH_GITHUB'
auth_gitlab = 'AUTH_GITLAB'
auth_bitbucket = 'AUTH_BITBUCKET'
auth_azure = 'AUTH_AZURE'
affinities = 'AFFINITIES'
archives_root = 'ARCHIVES_ROOT'
downloads_root = 'DOWNLOADS_ROOT'
admin = 'ADMIN'
node_selectors = 'NODE_SELECTORS'
tolerations = 'TOLERATIONS'
annotations ... |
# Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus or . She must avoid the thunderheads. Determine the minimum number of j... | def jumping_on_clouds(c):
if len(c) == 1:
return 0
if len(c) == 2:
return 0 if c[1] == 1 else 1
if c[2] == 1:
return 1 + jumping_on_clouds(c[1:])
if c[2] == 0:
return 1 + jumping_on_clouds(c[2:])
print(jumping_on_clouds([0, 0, 0, 0, 1, 0]))
array = [0, 0, 0, 0, 1, 0]
prin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.