content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class A:
def f(s):
return 9
x = property(f)
a = A()
print(a.x)
@property
def x():
return a
print(x) | class A:
def f(s):
return 9
x = property(f)
a = a()
print(a.x)
@property
def x():
return a
print(x) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
n = int(input())
a = list(map(int, input().split()))
ans = 0
a.sort()
for i in range(1, n, 2):
ans += a[i]-a[i-1]
print(ans)
| n = int(input())
a = list(map(int, input().split()))
ans = 0
a.sort()
for i in range(1, n, 2):
ans += a[i] - a[i - 1]
print(ans) |
x,y=map(int,input().split())
r=int(input())
d=[(1,1),(1,-1),(-1,-1),(-1,1)]
for i in range(4):
print(x+r*d[i][0],y+r*d[i][1]) | (x, y) = map(int, input().split())
r = int(input())
d = [(1, 1), (1, -1), (-1, -1), (-1, 1)]
for i in range(4):
print(x + r * d[i][0], y + r * d[i][1]) |
# https://www.codechef.com/problems/STICKS
for T in range(int(input())):
i,a,k,c=int(input())-1,sorted(list(map(int,input().split()))),-1,0
while(i>0):
if(a[i]==a[i-1]):
k,c,i=k*a[i],c+1,i-2
if(c==2): break
else: i-=1
print(abs(k)) if(c==2) else print(-1) | for t in range(int(input())):
(i, a, k, c) = (int(input()) - 1, sorted(list(map(int, input().split()))), -1, 0)
while i > 0:
if a[i] == a[i - 1]:
(k, c, i) = (k * a[i], c + 1, i - 2)
if c == 2:
break
else:
i -= 1
print(abs(k)) if c == 2 els... |
L1=[5, 4,3,5]
b=L1.count(5) # return how many times 5 appear in list
L2 = ["a", "b"];
L1.extend(L2) # extend L1 adding L2
print (L1)
| l1 = [5, 4, 3, 5]
b = L1.count(5)
l2 = ['a', 'b']
L1.extend(L2)
print(L1) |
if __name__ == '__main__':
a = b = x = 0
with open('./input', 'r') as file:
a = int(file.readline())
for line in file:
b = int(line)
if b> a:
x += 1
a = b
print(x)
| if __name__ == '__main__':
a = b = x = 0
with open('./input', 'r') as file:
a = int(file.readline())
for line in file:
b = int(line)
if b > a:
x += 1
a = b
print(x) |
class Page(object):
def __init__(self, experience=False):
self.__coeff = []
self.__power = []
self.__exp = bool(experience)
def addCoefficient(self, value):
self.__coeff.append(value)
self.__power.append(len(self.__coeff))
def addCoefficientAndPower(self, value, powerValue):
self.__coeff.append(v... | class Page(object):
def __init__(self, experience=False):
self.__coeff = []
self.__power = []
self.__exp = bool(experience)
def add_coefficient(self, value):
self.__coeff.append(value)
self.__power.append(len(self.__coeff))
def add_coefficient_and_power(self, value... |
# Read only
# Skip modify last run file and refresh note
readOnly = False
# Open obsidian after file update
# If running on server, usually turn this off
openObsidian = True
| read_only = False
open_obsidian = True |
class User:
def __init__(self, user_id, name, headline, created_at, username, image_url, profile_url):
self.id = user_id
self.name = name
self.headline = headline
self.created_at = created_at
self.username = username
self.image_url = image_url
self.profile_ur... | class User:
def __init__(self, user_id, name, headline, created_at, username, image_url, profile_url):
self.id = user_id
self.name = name
self.headline = headline
self.created_at = created_at
self.username = username
self.image_url = image_url
self.profile_ur... |
class SkillType:
RANGE_BONUS_PASSIVE_1 = 0
RANGE_BONUS_AURA_1 = 1
RANGE_BONUS_PASSIVE_2 = 2
RANGE_BONUS_AURA_2 = 3
ADVANCED_MAGIC_MISSILE = 4
MAGICAL_DAMAGE_BONUS_PASSIVE_1 = 5
MAGICAL_DAMAGE_BONUS_AURA_1 = 6
MAGICAL_DAMAGE_BONUS_PASSIVE_2 = 7
MAGICAL_DAMAGE_BONUS_AURA_2 = 8... | class Skilltype:
range_bonus_passive_1 = 0
range_bonus_aura_1 = 1
range_bonus_passive_2 = 2
range_bonus_aura_2 = 3
advanced_magic_missile = 4
magical_damage_bonus_passive_1 = 5
magical_damage_bonus_aura_1 = 6
magical_damage_bonus_passive_2 = 7
magical_damage_bonus_aura_2 = 8
fros... |
class MJConstants:
class Action:
READY = 0
START = 1
TAKE = 2
CHOW = 3
PONG = 4
KONG = 5
PLAY = 6
TIN = 7
HU = 8
PASS = 9
class round_act_state:
START = 0
CHECK_TAKE = 1
ACT_TAKE = 2
CHECK_CHOW = 3
... | class Mjconstants:
class Action:
ready = 0
start = 1
take = 2
chow = 3
pong = 4
kong = 5
play = 6
tin = 7
hu = 8
pass = 9
class Round_Act_State:
start = 0
check_take = 1
act_take = 2
check_chow = 3
... |
host = 'http://gxhttp.chinacloudapp.cn'
post_data = {"bNode": [], "buPin": "0.0", "duration": "20", "endTime": "", "frombp": "0", "goal": "2.00",
"real": "131622.016746475", "runPageId": "", "speed": "",
"startTime": "", "tNode": [], "totalNum": "0",
"track": [], "trend": [], "type": "",
... | host = 'http://gxhttp.chinacloudapp.cn'
post_data = {'bNode': [], 'buPin': '0.0', 'duration': '20', 'endTime': '', 'frombp': '0', 'goal': '2.00', 'real': '131622.016746475', 'runPageId': '', 'speed': '', 'startTime': '', 'tNode': [], 'totalNum': '0', 'track': [], 'trend': [], 'type': '', 'userid': '157332'}
no_free_dat... |
# works since py39
def return_me()-> tuple[str]:
return "Hallo", "Welt"
print(return_me()) | def return_me() -> tuple[str]:
return ('Hallo', 'Welt')
print(return_me()) |
#!/usr/bin/env python
class SimError(Exception):
pass
#
# State-related errors
#
class SimStateError(SimError):
pass
class SimMergeError(SimStateError):
pass
class SimMemoryError(SimStateError):
pass
class SimRegionMapError(SimMemoryError):
pass
class SimMemoryLimitError(SimMemoryError):
... | class Simerror(Exception):
pass
class Simstateerror(SimError):
pass
class Simmergeerror(SimStateError):
pass
class Simmemoryerror(SimStateError):
pass
class Simregionmaperror(SimMemoryError):
pass
class Simmemorylimiterror(SimMemoryError):
pass
class Simmemoryaddresserror(SimMemoryError):
... |
a = []
d = []
t1 = []
N = int(input())
for i in range(N):
a = list(map(int, input().split(" ")))
d.append(a)
def corners():
for i in range(4):
for i in range(N):
for j in range(N-1):
if i > j:
temp = d[i][j]
d[i][j] = d[j][i]
... | a = []
d = []
t1 = []
n = int(input())
for i in range(N):
a = list(map(int, input().split(' ')))
d.append(a)
def corners():
for i in range(4):
for i in range(N):
for j in range(N - 1):
if i > j:
temp = d[i][j]
d[i][j] = d[j][i]
... |
zahl1 = int(input("Zahl1:"))
zahl2 = int(input("Zahl2:"))
zahl3 = int(input("Zahl3:"))
Summe = zahl1 + zahl2 + zahl3 #summe der 3 Inputs bilden
print("Die Summe der drei Zahlen ist ", Summe)
| zahl1 = int(input('Zahl1:'))
zahl2 = int(input('Zahl2:'))
zahl3 = int(input('Zahl3:'))
summe = zahl1 + zahl2 + zahl3
print('Die Summe der drei Zahlen ist ', Summe) |
class HyundaiInputOutputController:
def __init__(self, send_func):
self.send = send_func
def front_wipers_slow(self, on):
if on:
msg = b"\x04\x2f\xb0\x08\x03"
else:
msg = b"\x04\x2f\xb0\x08\x00\x00"
self.send(0x700, msg)
def front_wipers_fast(self, on):
if on:
msg = b"\x04... | class Hyundaiinputoutputcontroller:
def __init__(self, send_func):
self.send = send_func
def front_wipers_slow(self, on):
if on:
msg = b'\x04/\xb0\x08\x03'
else:
msg = b'\x04/\xb0\x08\x00\x00'
self.send(1792, msg)
def front_wipers_fast(self, on):
... |
def read_in_chunks(filename, chunk_size):
with open(filename, 'rb') as file:
while True:
data = file.read(chunk_size)
if not data:
break
yield data
| def read_in_chunks(filename, chunk_size):
with open(filename, 'rb') as file:
while True:
data = file.read(chunk_size)
if not data:
break
yield data |
command = input()
force_users = {}
def command_line(side, user):
user_found = False
for sides, users in force_users.items():
if user in users:
user_found = True
if not user_found:
if side not in force_users:
force_users[side] = [user]
else:
if us... | command = input()
force_users = {}
def command_line(side, user):
user_found = False
for (sides, users) in force_users.items():
if user in users:
user_found = True
if not user_found:
if side not in force_users:
force_users[side] = [user]
elif user not in force... |
class NotFittedError(ValueError, AttributeError):
pass
class MissingFeatureError(ValueError, AttributeError):
pass | class Notfittederror(ValueError, AttributeError):
pass
class Missingfeatureerror(ValueError, AttributeError):
pass |
used_in_paper = {
(1, 2): {
"creation": {
"sidebands": [0, -1, 0, -1],
"fractions": [0.30122048, 0.40087652, 0.37204349, 0.35533004],
"phases": [0.0, -1.57079633, 0.0, -1.57079633],
},
"mapping": {
"sidebands": [-1, 0, -1, 0, -1],
"... | used_in_paper = {(1, 2): {'creation': {'sidebands': [0, -1, 0, -1], 'fractions': [0.30122048, 0.40087652, 0.37204349, 0.35533004], 'phases': [0.0, -1.57079633, 0.0, -1.57079633]}, 'mapping': {'sidebands': [-1, 0, -1, 0, -1], 'fractions': [0.35355378, 0.22007489, 0.70710786, 0.27091033, 0.70710467], 'phases': [0.0, 4.19... |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... | power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate Leakage': 0.00662954, 'Peak Dynamic': 0.0, 'Runtime Dynamic': 0.0, 'Subthres... |
inf_methods = ['Dionesus', 'Lasso', 'RandomForest']
organisms = [("yeast", "Yeast", "Yeast10"), ("ecoli","Ecoli", "Ecoli10")]
fobj = open("job_params_even_sampling.txt", "w")
intervals = [10,30,50,100,200,333,500]
max_window = 7
test_window = 4
for inf_method in inf_methods:
for organism in organisms:
fo... | inf_methods = ['Dionesus', 'Lasso', 'RandomForest']
organisms = [('yeast', 'Yeast', 'Yeast10'), ('ecoli', 'Ecoli', 'Ecoli10')]
fobj = open('job_params_even_sampling.txt', 'w')
intervals = [10, 30, 50, 100, 200, 333, 500]
max_window = 7
test_window = 4
for inf_method in inf_methods:
for organism in organisms:
... |
class Solution:
def isHappy(self, n: int) -> bool:
while n > 9:
temp = 0
while n > 0:
temp += (n % 10)**2
n //= 10
n = temp
return n in [1, 7]
| class Solution:
def is_happy(self, n: int) -> bool:
while n > 9:
temp = 0
while n > 0:
temp += (n % 10) ** 2
n //= 10
n = temp
return n in [1, 7] |
class Book:
def __init__(self, name, price):
self.name = name
self.price = price
def showbook(self):
print ("Name:", self.name)
print("Price:", self.price)
Va = Book("JavaCompletePet", 480.5)
Va.showbook()
class Reactangle:
def __init__(self, length, breadth):
... | class Book:
def __init__(self, name, price):
self.name = name
self.price = price
def showbook(self):
print('Name:', self.name)
print('Price:', self.price)
va = book('JavaCompletePet', 480.5)
Va.showbook()
class Reactangle:
def __init__(self, length, breadth):
self... |
#!//urs/local/bin/python
# Code Fights Avoid Obstacles Problem
def avoidObstacles(inputArray):
for jump in range(2, 40):
safe = True
for item in inputArray:
if item % jump == 0:
safe = False
break
if safe:
return jump
def main():
... | def avoid_obstacles(inputArray):
for jump in range(2, 40):
safe = True
for item in inputArray:
if item % jump == 0:
safe = False
break
if safe:
return jump
def main():
tests = [[[5, 3, 6, 7, 9], 4], [[2, 3], 4], [[1, 4, 10, 6, 2], ... |
def left_join(map1, map2):
result = []
for key, value in map1.items():
inner = []
inner.extend([key,value])
if key in map2:
inner.append(map2[key])
else:
inner.append(None)
result.append(inner)
return result
| def left_join(map1, map2):
result = []
for (key, value) in map1.items():
inner = []
inner.extend([key, value])
if key in map2:
inner.append(map2[key])
else:
inner.append(None)
result.append(inner)
return result |
def sort(li):
if len(li) > 0:
pivot = li[-1]
left = []
right = []
for i in li[:-1]:
if i > pivot:
right.append(i)
else:
left.append(i)
return sort(left) + [pivot] + sort(right)
else:
return li
... | def sort(li):
if len(li) > 0:
pivot = li[-1]
left = []
right = []
for i in li[:-1]:
if i > pivot:
right.append(i)
else:
left.append(i)
return sort(left) + [pivot] + sort(right)
else:
return li
def sort2(seq)... |
def dataFromResult(input, output):
data = []
for i in range(len(output['ranks'])):
if output['entities'][i] in input['up']:
data.append({
'x': output['ranks'][i],
'y': -(output['ranks'][i]-(len(output['ranks'])/2)) / (len(output['ranks'])/2),
'b': 1
})
elif output['entit... | def data_from_result(input, output):
data = []
for i in range(len(output['ranks'])):
if output['entities'][i] in input['up']:
data.append({'x': output['ranks'][i], 'y': -(output['ranks'][i] - len(output['ranks']) / 2) / (len(output['ranks']) / 2), 'b': 1})
elif output['entities'][i] ... |
google = Runtime.start('google','GoogleSearch')
python.subscribe('google', 'publishResults')
def onResults(data):
print(data)
google.search('what is a goat?')
| google = Runtime.start('google', 'GoogleSearch')
python.subscribe('google', 'publishResults')
def on_results(data):
print(data)
google.search('what is a goat?') |
PLATFORM_PI = False
PRINT_TO_TERMINAL = True
LEDS_USED = True
AUTO_CONTROL_RIGHT = True
class Side:
LEFT = 0
RIGHT = 1
| platform_pi = False
print_to_terminal = True
leds_used = True
auto_control_right = True
class Side:
left = 0
right = 1 |
[
"bar",
"rib",
"act",
"shy",
"spy",
"few",
"gem",
"owe",
"pan",
"aid",
"lid",
"gap",
"age",
"cut",
"sin",
"boy",
"jaw",
"bed",
"tip",
"ash",
]
| ['bar', 'rib', 'act', 'shy', 'spy', 'few', 'gem', 'owe', 'pan', 'aid', 'lid', 'gap', 'age', 'cut', 'sin', 'boy', 'jaw', 'bed', 'tip', 'ash'] |
def can_build(env, platform):
return True
def configure(env):
if (env['platform'] == 'android'):
env.android_add_java_dir("android/src")
env.android_add_dependency("compile 'com.android.support:appcompat-v7:23.1.1'")
| def can_build(env, platform):
return True
def configure(env):
if env['platform'] == 'android':
env.android_add_java_dir('android/src')
env.android_add_dependency("compile 'com.android.support:appcompat-v7:23.1.1'") |
# Space: O(1)
# Time: O(n)
class Solution:
def checkPossibility(self, nums):
length = len(nums)
if length <= 1: return True
slow, fast = -1, 0
while fast < length - 1:
if nums[fast] > nums[fast + 1]:
if slow != -1: return False
slow = fa... | class Solution:
def check_possibility(self, nums):
length = len(nums)
if length <= 1:
return True
(slow, fast) = (-1, 0)
while fast < length - 1:
if nums[fast] > nums[fast + 1]:
if slow != -1:
return False
s... |
expected_output = {
'vpn_id':{
1:{
'originating_ip':{
'1.1.1.1':{
'encap':'SRv6',
'ethertag':0,
'tepid':'0xffffffff',
'pmsi_type':6,
'nexthop':'::',
'sr_te_in... | expected_output = {'vpn_id': {1: {'originating_ip': {'1.1.1.1': {'encap': 'SRv6', 'ethertag': 0, 'tepid': '0xffffffff', 'pmsi_type': 6, 'nexthop': '::', 'sr_te_info': 'N/A', 'sid': 'cafe:0:128:e1aa::', 'source': 'Local', 'e_tree': 'Root'}, '2.2.2.2': {'encap': 'SRv6', 'ethertag': 0, 'tepid': '0x05000001', 'pmsi_type': ... |
def test():
# Here we can either check objects created in the solution code, or the
# string value of the solution, available as __solution__. A helper for
# printing formatted messages is available as __msg__. See the testTemplate
# in the meta.json for details.
# If an assertion fails, the messag... | def test():
assert 'hockey_players' in __solution__, "Make sure you are naming your object 'hockey_players'"
assert 'position_bar' in __solution__, "Make sure you are naming your object 'drawer_length'"
assert hockey_players.shape == (22, 9), "Did you load in 'canucks.csv' correctly?"
assert position_ba... |
class Reptile(object): # Both Pythons
def describe(self):
return "Reptile"
class Snake(Reptile):
def describe(self):
return "Snake"
class Python(Snake):
def describe(self):
return "Python"
print(super(Python, Python()).describe())
print(super(Snake, Snake).describe(Python()))
| class Reptile(object):
def describe(self):
return 'Reptile'
class Snake(Reptile):
def describe(self):
return 'Snake'
class Python(Snake):
def describe(self):
return 'Python'
print(super(Python, python()).describe())
print(super(Snake, Snake).describe(python())) |
AUTHOR = "gmattis"
CLASS = "Settings"
DESCRIPTION = "Settings application"
IMAGE = "settings.png"
NAME = "Settings"
| author = 'gmattis'
class = 'Settings'
description = 'Settings application'
image = 'settings.png'
name = 'Settings' |
class Event:
def __init__(self):
self.cancelled = False
self.is_cancellable = True
self.stopped = False
def cancel(self):
if not self.is_cancellable:
raise Exception("Event is not cancellable")
def stop(self):
self.stopped = True
class EventHandler:
... | class Event:
def __init__(self):
self.cancelled = False
self.is_cancellable = True
self.stopped = False
def cancel(self):
if not self.is_cancellable:
raise exception('Event is not cancellable')
def stop(self):
self.stopped = True
class Eventhandler:
... |
size_of_board = 600
number_of_dots = 6
symbol_size = (size_of_board / 3 - size_of_board / 8) / 2
symbol_thickness = 50
dot_colour = "#7BC043"
player1_colour = "#0492CF"
player1_colour_light = "#67B0CF"
player2_colour = "#EE4035"
player2_colour_light = "#EE7E77"
Green_colour = "#7BC043"
dot_width = 0.25 * size... | size_of_board = 600
number_of_dots = 6
symbol_size = (size_of_board / 3 - size_of_board / 8) / 2
symbol_thickness = 50
dot_colour = '#7BC043'
player1_colour = '#0492CF'
player1_colour_light = '#67B0CF'
player2_colour = '#EE4035'
player2_colour_light = '#EE7E77'
green_colour = '#7BC043'
dot_width = 0.25 * size_of_board ... |
instructions = [line.strip().split(" -> ") for line in open("input_7", "r").readlines()]
# The keys of this dict are the wire-names, and its values will be their signal.
# Looping through the expressions, the dict will gradually fill up as we know
# more and more.
solved_circuit = {}
def solved(key):
return key... | instructions = [line.strip().split(' -> ') for line in open('input_7', 'r').readlines()]
solved_circuit = {}
def solved(key):
return key in solved_circuit
def store(key, value):
if key in solved_circuit:
pass
solved_circuit[key] = value
def get_value(key):
return solved_circuit[key]
def eval... |
class ContaCorrente:
def __init__(self, numero_conta, nome, saldo=0) -> None:
self.numero_conta = numero_conta
self.nome = nome
self.saldo = saldo
def alterar_nome(self, novo_nome):
self.nome = novo_nome
def deposito(self, valor):
self.saldo += valor
def saque(... | class Contacorrente:
def __init__(self, numero_conta, nome, saldo=0) -> None:
self.numero_conta = numero_conta
self.nome = nome
self.saldo = saldo
def alterar_nome(self, novo_nome):
self.nome = novo_nome
def deposito(self, valor):
self.saldo += valor
def saque... |
# from Olivia Ng via https://codepen.io/oliviale/pen/OrxWyK
def write_card(
card_title,
card_subtitle,
squares,
):
card_header = f'''
<html lang="en"><head>
<meta charset="UTF-8">
<title>{card_title}</title>
'''
card_header += '''<link href="https://fonts.googleapi... | def write_card(card_title, card_subtitle, squares):
card_header = f'\n <html lang="en"><head>\n\n <meta charset="UTF-8">\n\n <title>{card_title}</title>\n '
card_header += '<link href="https://fonts.googleapis.com/css?family=Amatic+SC:700|Nunito|Caveat+Brush" rel="stylesheet">\n\n <link rel... |
# Python program to
# demonstrate queue implementation
# using list
# Initializing a queue
queue = []
# Adding elements to the queue
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)
# Removing elements from the queue
print("\nElements dequeued from queue")
print(queue.pop(0)... | queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print('Initial queue')
print(queue)
print('\nElements dequeued from queue')
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
print('\nQueue after removing elements')
print(queue) |
# This is the memoization approach of 0 / 1 Knapsack in Python in simple
# Method : Dynamic Programming
# Author : Neeraj Pratap Hazarika
# Problem Statement : Given a set of items, each with a weight and a value, take items to include in a knapsack such that the total weight is less than or equal to a given limit... | dp = [[]]
def knapsack(wt, val, W, n):
if n == 0 or W == 0:
return 0
if dp[n][W] != -1:
return dp[n][W]
if wt[n - 1] <= W:
dp[n][W] = max(val[n - 1] + knapsack(wt, val, W - wt[n - 1], n - 1), knapsack(wt, val, W, n - 1))
return dp[n][W]
elif wt[n - 1] > W:
dp[n][... |
# -*- coding: utf-8 -*-
class LineStyle:
def inc(self):
raise NotImplementedError()
def p(self):
raise NotImplementedError()
class SolidLineStyle(LineStyle):
def inc(self):
pass
def p(self):
return True
class DashedLineStyle(LineStyle):
def __init__(self):
... | class Linestyle:
def inc(self):
raise not_implemented_error()
def p(self):
raise not_implemented_error()
class Solidlinestyle(LineStyle):
def inc(self):
pass
def p(self):
return True
class Dashedlinestyle(LineStyle):
def __init__(self):
self.tick = 0
... |
# conftest.py
def pytest_addoption(parser):
parser.addoption("--name", action="store", default="test")
| def pytest_addoption(parser):
parser.addoption('--name', action='store', default='test') |
s = "aB:cD"
__author__ = "Mert Erol"
print("Start string = " + s)
a, b = s.split(":", 1)
print("String split at : and assigned to new variables;")
print(a)
print(b)
z = a.lower()
y = b.upper()
print(z + ":" + y) | s = 'aB:cD'
__author__ = 'Mert Erol'
print('Start string = ' + s)
(a, b) = s.split(':', 1)
print('String split at : and assigned to new variables;')
print(a)
print(b)
z = a.lower()
y = b.upper()
print(z + ':' + y) |
# Test: simple test.
def test_simple():
a = 1
assert a == 1
| def test_simple():
a = 1
assert a == 1 |
for _ in range(int(input())):
row,col=map(int,input().split())
in_matrix = list(map(int,input().split()))
index=0
matrix=[]
for i in range(row):
temp_row=[]
for j in range(col):
temp_row.append(in_matrix[index])
index+=1
matrix.append(temp_row)
... | for _ in range(int(input())):
(row, col) = map(int, input().split())
in_matrix = list(map(int, input().split()))
index = 0
matrix = []
for i in range(row):
temp_row = []
for j in range(col):
temp_row.append(in_matrix[index])
index += 1
matrix.append(te... |
class Finding:
def __init__(self, source, name, description=None, address=None, pc=None, severity=None):
self.source = source
self.name = name
self.description = description
self.address = address
self.pc = pc
self.severity = severity | class Finding:
def __init__(self, source, name, description=None, address=None, pc=None, severity=None):
self.source = source
self.name = name
self.description = description
self.address = address
self.pc = pc
self.severity = severity |
__author__ = 'Sergey Khrul'
class NavigationHelper:
def __init__(self, app):
self.app = app
def open_home_page(self):
wd = self.app.wd
# open home_phone page
wd.get(self.app.mainURL)
def ensure_home_opened(self):
wd = self.app.wd
# open home_phone page
... | __author__ = 'Sergey Khrul'
class Navigationhelper:
def __init__(self, app):
self.app = app
def open_home_page(self):
wd = self.app.wd
wd.get(self.app.mainURL)
def ensure_home_opened(self):
wd = self.app.wd
if wd.current_url is not self.app.mainURL:
se... |
my_list = [10, 11, 12, 13, 14, 15]
first_plus_last = my_list[0] + my_list[len(my_list) - 1]
print(first_plus_last)
| my_list = [10, 11, 12, 13, 14, 15]
first_plus_last = my_list[0] + my_list[len(my_list) - 1]
print(first_plus_last) |
#doc 10
nWeights = int(input("Enter how many people's weight-height you'd like to enter: "))
ans= ""
for inputInfo in range (nWeights):
tmp = input().split()
bmi = float(tmp[0]) / float(tmp[1])**2
if bmi > 18.5:
ans+="underweight "
continue
elif bmi <= 25.0:
ans+="healthy"
... | n_weights = int(input("Enter how many people's weight-height you'd like to enter: "))
ans = ''
for input_info in range(nWeights):
tmp = input().split()
bmi = float(tmp[0]) / float(tmp[1]) ** 2
if bmi > 18.5:
ans += 'underweight '
continue
elif bmi <= 25.0:
ans += 'healthy'
... |
def valid_auth_header(api_key, auth_header) -> bool:
if not auth_header:
return False
auth_token = auth_header.split(' ')[1]
if not auth_token or auth_token != api_key:
return False
return True
| def valid_auth_header(api_key, auth_header) -> bool:
if not auth_header:
return False
auth_token = auth_header.split(' ')[1]
if not auth_token or auth_token != api_key:
return False
return True |
# Given a string, find the length of the longest substring without repeating characters.
#
#
# Examples:
#
# Given "abcabcbb", the answer is "abc", which the length is 3.
#
# Given "bbbbb", the answer is "b", with the length of 1.
#
# Given "pwwkew", the answer is "wke", with the length of 3.
#
# Note that the answer m... | class Solution:
def length_of_longest_substr(self, s: str) -> int:
pos = 0
long = 0
map_appearances = [False] * 256
for (i, c) in enumerate(s):
if map_appearances[ord(c)]:
long = max(long, i - pos)
while c != s[pos]:
ma... |
class ModifierExample:
def __init__(self):
self.someVariable = 10
#Constructors
def someFunction(self, x):
self.__anotherVariable = x
if __name__ == '__main__':
obj1 = ModifierExample()
obj1.someFunction(50)
print(obj1.someVariable)
print(obj1.__dict__.clear())
#... | class Modifierexample:
def __init__(self):
self.someVariable = 10
def some_function(self, x):
self.__anotherVariable = x
if __name__ == '__main__':
obj1 = modifier_example()
obj1.someFunction(50)
print(obj1.someVariable)
print(obj1.__dict__.clear())
obj2 = modifier_example(... |
HEADERS = [{
'User-Agent':
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0',
'Accept': '*/*',
'Connection': 'keep-alive',
'Accept-Language': 'zh-CN,zh;q=0.8'
}]
SITE_INFO = {}
| headers = [{'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0', 'Accept': '*/*', 'Connection': 'keep-alive', 'Accept-Language': 'zh-CN,zh;q=0.8'}]
site_info = {} |
# Copyright B. Soares
#
# Released under the MIT License
# https://github.com/basoares/google-code-jam/blob/master/LICENSE
#
num_tests = int(input())
for i in range(num_tests):
number = input()
a = number.replace('4', '3')
b = ''.join('1' if d == '4' else '0' for d in number).lstrip('0')
print('Case #{... | num_tests = int(input())
for i in range(num_tests):
number = input()
a = number.replace('4', '3')
b = ''.join(('1' if d == '4' else '0' for d in number)).lstrip('0')
print('Case #{}: {} {}'.format(i + 1, a, b)) |
class LRUCache:
def __init__(self, capacity: int):
self.length = capacity
self.cache = collections.OrderedDict()
def get(self, key: int) -> int:
if key in self.cache:
value = self.cache[key]
self.cache.pop(key)
self.cache[key] = value
retu... | class Lrucache:
def __init__(self, capacity: int):
self.length = capacity
self.cache = collections.OrderedDict()
def get(self, key: int) -> int:
if key in self.cache:
value = self.cache[key]
self.cache.pop(key)
self.cache[key] = value
ret... |
def longestPalindrome(s: str) -> str:
n = len(s)
res = s[0]
for i in range(n):
# Check once for even palindrome size
mid = i
left = i - 1
while mid < n and left >= 0 and s[mid] == s[left]:
left -= 1
mid += 1
res = max(res, s[left+1:mid], key=l... | def longest_palindrome(s: str) -> str:
n = len(s)
res = s[0]
for i in range(n):
mid = i
left = i - 1
while mid < n and left >= 0 and (s[mid] == s[left]):
left -= 1
mid += 1
res = max(res, s[left + 1:mid], key=lambda x: len(x))
left = i - 1
... |
# Program to demmonstrate dictionary
# To create dictionary use {}
person_info = {"first_name": "Anand", "last_name": "Dasani",
"DOY": 2001, "country": "India"}
print(type(person_info))
print(person_info)
print("First name :: ", person_info["first_name"])
print("\n")
# dict are mutable, we can chang... | person_info = {'first_name': 'Anand', 'last_name': 'Dasani', 'DOY': 2001, 'country': 'India'}
print(type(person_info))
print(person_info)
print('First name :: ', person_info['first_name'])
print('\n')
person_info['DOY'] = 2000
print(person_info)
print('\n')
person_info['marital_status'] = 'Not married'
print(person_inf... |
#!/usr/bin/env python3
# O(sqrt(n))
if __name__ == '__main__':
num = 600851475143
s = set()
cur = 2
while True:
if cur * cur > num:
print(int(num))
break
while num % cur == 0:
num /= cur
if num == 1:
print(cur)
br... | if __name__ == '__main__':
num = 600851475143
s = set()
cur = 2
while True:
if cur * cur > num:
print(int(num))
break
while num % cur == 0:
num /= cur
if num == 1:
print(cur)
break
if cur == 2:
cur +=... |
__all__ = [
'q1_introduction_to_regex',
'q2_re_split',
'q3_re_group_groups',
'q4_re_findall_re_finditer',
'q5_re_start_re_end',
'q6_re_sub_regex_substitution',
'q7_validate_a_roman_number',
'q8_validating_the_phone_number',
'q9_validating_named_email_addresses',
'q10_hex_color_co... | __all__ = ['q1_introduction_to_regex', 'q2_re_split', 'q3_re_group_groups', 'q4_re_findall_re_finditer', 'q5_re_start_re_end', 'q6_re_sub_regex_substitution', 'q7_validate_a_roman_number', 'q8_validating_the_phone_number', 'q9_validating_named_email_addresses', 'q10_hex_color_code', 'q11_html_parser_part_1', 'q12_html_... |
line = input()
happy = line.count(':-)')
sad = line.count(':-(')
if happy == 0 and sad == 0:
print('none')
elif happy == sad:
print('unsure')
elif happy > sad:
print('happy')
else:
print('sad') | line = input()
happy = line.count(':-)')
sad = line.count(':-(')
if happy == 0 and sad == 0:
print('none')
elif happy == sad:
print('unsure')
elif happy > sad:
print('happy')
else:
print('sad') |
x,y = map(int,input().split())
if x == y:
print(2*x)
else:
print(2*max(x,y)-1) | (x, y) = map(int, input().split())
if x == y:
print(2 * x)
else:
print(2 * max(x, y) - 1) |
num_one = int(input())
num_two = int(input())
num_three = int(input())
if num_one == num_two and num_two == num_three:
print("yes")
else:
print("no")
| num_one = int(input())
num_two = int(input())
num_three = int(input())
if num_one == num_two and num_two == num_three:
print('yes')
else:
print('no') |
print('Hi,Hello?')
print('Hello,Have a nice day!')
print('Gundamuaaaaa')
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
| print('Hi,Hello?')
print('Hello,Have a nice day!')
print('Gundamuaaaaa')
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa |
def radix_sort(to_be_sorted):
max_exponent = len(str(max(to_be_sorted)))
being_sorted = to_be_sorted[:] # create a copy of the list
# loop through each digit based on largest exponent
for exponent in range(max_exponent):
digits = [[] for i in range(10)] # create buckets for each digit
... | def radix_sort(to_be_sorted):
max_exponent = len(str(max(to_be_sorted)))
being_sorted = to_be_sorted[:]
for exponent in range(max_exponent):
digits = [[] for i in range(10)]
index = -(exponent + 1)
for number in being_sorted:
number_as_a_string = str(number)
t... |
def do_stuff(l):
print(l(1))
print(l(2))
print(l(4))
do_stuff(lambda x: x**2)
do_stuff(lambda x: print("This is probably a really bad idea: %d" % x))
do_stuff(lambda groot: do_stuff(lambda groot_: do_stuff(lambda groot__: do_stuff(lambda groot___: print(groot___)))))
| def do_stuff(l):
print(l(1))
print(l(2))
print(l(4))
do_stuff(lambda x: x ** 2)
do_stuff(lambda x: print('This is probably a really bad idea: %d' % x))
do_stuff(lambda groot: do_stuff(lambda groot_: do_stuff(lambda groot__: do_stuff(lambda groot___: print(groot___))))) |
# lc572.py
# LeetCode 572. Subtree of Another Tree `E`
# acc | 93% | 33'
# A~0g01
# 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 isSubtree(self, s:... | class Solution:
def is_subtree(self, s: TreeNode, t: TreeNode) -> bool:
ss = self.traverse(s)
st = self.traverse(t)
return st in ss
def traverse(self, t):
if not t:
return None
return f'# {self.traverse(t.left)} {t.val} {self.traverse(t.right)}' |
#
# PySNMP MIB module DISMAN-EXPRESSION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DISMAN-EXPRESSION-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:32:13 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_size_constraint, single_value_constraint, value_range_constraint) ... |
''' Python program to find the
multiplication table (from 1 to 10)'''
num = 12
# To take input from the user
# num = int(input("Display multiplication table of? "))
# use for loop to iterate 10 times
for i in range(1, 11):
print(num,'x',i,'=',num*i)
| """ Python program to find the
multiplication table (from 1 to 10)"""
num = 12
for i in range(1, 11):
print(num, 'x', i, '=', num * i) |
number_to_check = int(input("Number : "))
till_where = int(input("Till where to check : "))
list_of_non_multiples = []
for num in range(0, till_where + 1):
if num % number_to_check != 0:
list_of_non_multiples.append(num)
print(list_of_non_multiples)
# or you can do
# this
print(" ")
for element in list_of_... | number_to_check = int(input('Number : '))
till_where = int(input('Till where to check : '))
list_of_non_multiples = []
for num in range(0, till_where + 1):
if num % number_to_check != 0:
list_of_non_multiples.append(num)
print(list_of_non_multiples)
print(' ')
for element in list_of_non_multiples:
print... |
fibonacci = [0]
terms = input("Enter number of required terms: ")
terms = int(terms)
for i in range(0, terms):
if len(fibonacci) == 1:
fibonacci.append(1)
a = len(fibonacci) - 1
if len(fibonacci) > 1:
fibonacci.append(fibonacci[a] + fibonacci[a -1])
print(fibonacci)
| fibonacci = [0]
terms = input('Enter number of required terms: ')
terms = int(terms)
for i in range(0, terms):
if len(fibonacci) == 1:
fibonacci.append(1)
a = len(fibonacci) - 1
if len(fibonacci) > 1:
fibonacci.append(fibonacci[a] + fibonacci[a - 1])
print(fibonacci) |
# This file has two Solutions: 1st is when the duplicate sets are allowed and second is when they aren't.
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
ans = []
for i in range(len(nums)):
curr = nums[i]
low = i+1
high... | class Solution:
def three_sum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
ans = []
for i in range(len(nums)):
curr = nums[i]
low = i + 1
high = len(nums) - 1
while low < high:
sum = nums[i] + nums[low] + nums[high]
... |
# Copyright 2021 Google Inc. All Rights Reserved.
# 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 ... | class Logger:
def __new__(cls):
if cls._instance is None:
cls._instance = super(Logger, cls).__new__(cls)
cls._lines = []
return cls._instance
_instance = None
_log_level = 2
def log(self, message, level=2):
if level > self._log_level:
return... |
# Data types
STRING = 'STRING'
NUMBER = 'NUMBER'
BOOL = 'BOOLEAN'
ID = 'IDENTIFIER'
LIST = 'LIST'
# Keywords
IF = 'IF'
ELSE = 'ELSE'
FOR = 'FOR'
WHILE = 'WHILE'
FUNC = 'FUNCTION'
CLASS = 'CLASS'
END = 'END'
RETURN = 'RETURN'
# Other
OP = 'OP'
CPP = 'C++ CODE'
# Expect function
# Checks if there is a match. Else, raise... | string = 'STRING'
number = 'NUMBER'
bool = 'BOOLEAN'
id = 'IDENTIFIER'
list = 'LIST'
if = 'IF'
else = 'ELSE'
for = 'FOR'
while = 'WHILE'
func = 'FUNCTION'
class = 'CLASS'
end = 'END'
return = 'RETURN'
op = 'OP'
cpp = 'C++ CODE'
def expect(stream: list, token: str):
try:
if stream[0][1] == token:
... |
class Solution:
def readBinaryWatch(self, num: int) -> list:
res = []
for i in range(0, 12):
for j in range(0, 60):
if (bin(i).count('1') + bin(j).count('1')) == num:
res.append('%d:%02d' % (i, j))
return res
n = 1
s = Solution()
print(s.read... | class Solution:
def read_binary_watch(self, num: int) -> list:
res = []
for i in range(0, 12):
for j in range(0, 60):
if bin(i).count('1') + bin(j).count('1') == num:
res.append('%d:%02d' % (i, j))
return res
n = 1
s = solution()
print(s.readB... |
class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
if not root:
return
res = []
self.dfs(root, targetSum, [], res)
return res
def dfs(self, node, sum, path, res):
if not node:
ret... | class Solution:
def path_sum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
if not root:
return
res = []
self.dfs(root, targetSum, [], res)
return res
def dfs(self, node, sum, path, res):
if not node:
return
if not no... |
class RoutorException(Exception):
pass
class GraphException(RoutorException):
pass
class NodeDoesNotExist(GraphException):
pass
class EdgeDoesNotExist(GraphException):
pass
| class Routorexception(Exception):
pass
class Graphexception(RoutorException):
pass
class Nodedoesnotexist(GraphException):
pass
class Edgedoesnotexist(GraphException):
pass |
class InvalidConversionException(Exception):
def __init__(self, unit_from, unit_to, reason, *args) -> None:
self.unit_from = unit_from
self.unit_to = unit_to
self.message = reason
super().__init__(self,*args)
def __str__(self) -> str:
return 'Invalid conversion: {unit_... | class Invalidconversionexception(Exception):
def __init__(self, unit_from, unit_to, reason, *args) -> None:
self.unit_from = unit_from
self.unit_to = unit_to
self.message = reason
super().__init__(self, *args)
def __str__(self) -> str:
return 'Invalid conversion: {unit_... |
# Copyright (C) 2020 NextERP Romania
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Projects Portal Access Rights",
"summary": "Add portal access rights to all project types",
"version": "13.0.1.0.0",
"development_status": "Mature",
"category": "Security",
"website":... | {'name': 'Projects Portal Access Rights', 'summary': 'Add portal access rights to all project types', 'version': '13.0.1.0.0', 'development_status': 'Mature', 'category': 'Security', 'website': 'https://nexterp.ro', 'author': 'NextERP Romania SRL', 'maintainers': ['feketemihai'], 'license': 'AGPL-3', 'installable': Tru... |
def setup():
size(800, 800)
background(255,229,180, 0.54)
smooth()
fill(100)
rect(250, 250, 400, 400)
filter( BLUR, 35 )
smooth()
rect(30, 450, 80, 250)
filter(BLUR, 20)
# Main pointillism background
for i in range(50, 750):
for j in range(50, 750):
... | def setup():
size(800, 800)
background(255, 229, 180, 0.54)
smooth()
fill(100)
rect(250, 250, 400, 400)
filter(BLUR, 35)
smooth()
rect(30, 450, 80, 250)
filter(BLUR, 20)
for i in range(50, 750):
for j in range(50, 750):
smooth()
stroke(0)
... |
print("How old are you?", end=' ')
age= input()
print("How tall are you?", end=' ')
heigh = input()
print("How much do you weigh?", end=' ')
weigh = input()
print(f"So, you're {age} old, {heigh} tall and {weigh} heavy.")
| print('How old are you?', end=' ')
age = input()
print('How tall are you?', end=' ')
heigh = input()
print('How much do you weigh?', end=' ')
weigh = input()
print(f"So, you're {age} old, {heigh} tall and {weigh} heavy.") |
class Solution0669:
def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
if not root:
return root
if root.val < low:
return self.trimBST(root.right, low, high)
if root.val > high:
return self.trimBST(root.left, low, hi... | class Solution0669:
def trim_bst(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
if not root:
return root
if root.val < low:
return self.trimBST(root.right, low, high)
if root.val > high:
return self.trimBST(root.left, low, hig... |
# db_utils.py
def execute_query_for_single_value(cursor, query):
'''
query is a string containing a well-formed query that is executed
against the specified cursor.
RETURNS: the following tripe: (results_flag, err_msg, value)
'''
try:
# Execute the query
cursor.exe... | def execute_query_for_single_value(cursor, query):
"""
query is a string containing a well-formed query that is executed
against the specified cursor.
RETURNS: the following tripe: (results_flag, err_msg, value)
"""
try:
cursor.execute(query)
except Exception as e:
msg = 'Exc... |
# Copyright 2017 Quantum Information Science, University of Parma, Italy. All Rights Reserved.
#
# 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... | __author__ = 'Davide Ferrari'
__copyright__ = 'Copyright 2017, Quantum Information Science, University of Parma, Italy'
__license__ = 'Apache'
__version__ = '2.0'
__email__ = 'davide.ferrari8@studenti.unipr.it'
ap_itoken = None
url = 'https://quantumexperience.ng.bluemix.net/api'
if 'APItoken' not in locals():
rais... |
#
# PySNMP MIB module Wellfleet-LOADER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-LOADER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:34:12 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, value_range_constraint, value_size_constraint, constraints_union) ... |
with open('prefix.txt', 'r') as file:
lines = file.readlines()
prefix_set = {x.strip() for x in lines}
def is_real(mac):
check = mac[0:6].upper()
return check in prefix_set
if __name__ == '__main__':
print(is_real('482CA04A7D89'))
print(is_real('000000000000'))
| with open('prefix.txt', 'r') as file:
lines = file.readlines()
prefix_set = {x.strip() for x in lines}
def is_real(mac):
check = mac[0:6].upper()
return check in prefix_set
if __name__ == '__main__':
print(is_real('482CA04A7D89'))
print(is_real('000000000000')) |
# Problem code
def subsets(nums):
result = []
backtrack(nums, 0, result, [])
return result
def backtrack(nums, index, result, temp):
result.append(temp.copy())
for i in range(index, len(nums)):
# use it
temp.append(nums[i])
# backtrack
backtrack(nums, i + 1, resu... | def subsets(nums):
result = []
backtrack(nums, 0, result, [])
return result
def backtrack(nums, index, result, temp):
result.append(temp.copy())
for i in range(index, len(nums)):
temp.append(nums[i])
backtrack(nums, i + 1, result, temp)
temp.pop() |
class powerSystem:
# input parameters:
# powerModelFilepath: file path of power model
# opIDs: a dict that maps the name of an option to its numerical ID, an iteger from 0 to n-1. n is the total number of options
def __init__(self, powerModelFilepath, opIDs):
self.numOfOptions = le... | class Powersystem:
def __init__(self, powerModelFilepath, opIDs):
self.numOfOptions = len(opIDs)
self.opIDs = opIDs
self.pmfp = powerModelFilepath
self.powerModel = self.loadPowerModel()
def load_power_model(self):
try:
model = {tuple([-1]): 0}
w... |
# %% [1266. Minimum Time Visiting All Points](https://leetcode.com/problems/minimum-time-visiting-all-points/)
class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
return sum(
max(abs(pt2[0] - pt1[0]), abs(pt2[1] - pt1[1]))
for pt1, pt2 in zip(points, po... | class Solution:
def min_time_to_visit_all_points(self, points: List[List[int]]) -> int:
return sum((max(abs(pt2[0] - pt1[0]), abs(pt2[1] - pt1[1])) for (pt1, pt2) in zip(points, points[1:]))) |
class Linked_List():
def __init__(self, head):
self.head = head
class Node():
def __init__(self, data):
self.data = data
self.next = None
# O(n + m) time and O(1) space.
def find_intersect(linked_list1, linked_list2):
length_1 = 0
length_2 = 0
next_one_1 = linked_list1.head... | class Linked_List:
def __init__(self, head):
self.head = head
class Node:
def __init__(self, data):
self.data = data
self.next = None
def find_intersect(linked_list1, linked_list2):
length_1 = 0
length_2 = 0
next_one_1 = linked_list1.head
next_one_2 = linked_list2.hea... |
def printList(list):
for key in list:
print(key)
wangziRange = range(1, 10)
tongziRange = range(11, 20)
tiaoziRange = range(21, 30)
zipaiRange = range(31, 38)
printList(wangziRange)
printList(tongziRange)
printList(tiaoziRange)
printList(zipaiRange) | def print_list(list):
for key in list:
print(key)
wangzi_range = range(1, 10)
tongzi_range = range(11, 20)
tiaozi_range = range(21, 30)
zipai_range = range(31, 38)
print_list(wangziRange)
print_list(tongziRange)
print_list(tiaoziRange)
print_list(zipaiRange) |
class Preposition:
'''Data model for prepositions.'''
def __init__(self, index):
'''
Attributes:
- self.index: identifies a preposition;
- self.contractions: defines eventual contractions with
following words.
'''
self.index = index
self.contra... | class Preposition:
"""Data model for prepositions."""
def __init__(self, index):
"""
Attributes:
- self.index: identifies a preposition;
- self.contractions: defines eventual contractions with
following words.
"""
self.index = index
self.contrac... |
class Heater:
def __init__(self, max_power: int):
self.max_power = max_power
self.power = 0
self.is_heating = False
def __repr__(self):
return f'Heater with power of: {self.max_power}W'
| class Heater:
def __init__(self, max_power: int):
self.max_power = max_power
self.power = 0
self.is_heating = False
def __repr__(self):
return f'Heater with power of: {self.max_power}W' |
def main():
input_data = read_input()
# Part 1
fabric_size = 1000
fabric = [[[] for y in range(fabric_size)] for x in range(fabric_size)]
non_overlapping_ids = set()
for claim in input_data:
id, claim = claim.split(' @ ')
position, claim = claim.split(": ")
x, y = ma... | def main():
input_data = read_input()
fabric_size = 1000
fabric = [[[] for y in range(fabric_size)] for x in range(fabric_size)]
non_overlapping_ids = set()
for claim in input_data:
(id, claim) = claim.split(' @ ')
(position, claim) = claim.split(': ')
(x, y) = map(int, posit... |
print('Enter Your Name : ')
name = input()
filename = 'guest.txt'
with open (filename,'w') as object:
(object.write(name))
| print('Enter Your Name : ')
name = input()
filename = 'guest.txt'
with open(filename, 'w') as object:
object.write(name) |
class Params:
# If pickle file has been generated, glove is not neccessary.
glove_word = "glove.840B.300d.txt"
vocab_size = 91605
word_emb_size = 300
glove_char = "glove.840B.300d.char.txt"
char_size = 95
char_emb_size = 300
emb_pickle = "embeddings.pickle"
# data directory
trai... | class Params:
glove_word = 'glove.840B.300d.txt'
vocab_size = 91605
word_emb_size = 300
glove_char = 'glove.840B.300d.char.txt'
char_size = 95
char_emb_size = 300
emb_pickle = 'embeddings.pickle'
train_path = 'dev.json'
dev_path = 'dev.json'
test_path = 'test.json'
max_passag... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.