content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Heaviside step function
x = 3
theta = None
if x < 0:
theta = 0.
elif x == 0:
theta = 0.5
else:
theta = 1.
print("Theta(" + str(x) + ") = " + str(theta))
| x = 3
theta = None
if x < 0:
theta = 0.0
elif x == 0:
theta = 0.5
else:
theta = 1.0
print('Theta(' + str(x) + ') = ' + str(theta)) |
#
# PySNMP MIB module COLUBRIS-DEVICE-WDS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/COLUBRIS-DEVICE-WDS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:25:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, value_size_constraint, value_range_constraint, constraints_intersection) ... |
age = int(input())
def drinks(drink):
print(f"drink {drink}")
if age <= 14:
drinks("toddy")
elif age <= 18:
drinks("coke")
elif age <= 21:
drinks("beer")
else:
drinks("whisky")
| age = int(input())
def drinks(drink):
print(f'drink {drink}')
if age <= 14:
drinks('toddy')
elif age <= 18:
drinks('coke')
elif age <= 21:
drinks('beer')
else:
drinks('whisky') |
SECTION_SEPARATOR = "%" * 30
def get_required_node_edges(qualified_node_id, required_node_ids):
node_requires = [
f"{required_node_id}-->{qualified_node_id}"
for required_node_id in required_node_ids
]
return "\n".join(node_requires)
def get_icon(dict_value):
icon = ""
if "icon" i... | section_separator = '%' * 30
def get_required_node_edges(qualified_node_id, required_node_ids):
node_requires = [f'{required_node_id}-->{qualified_node_id}' for required_node_id in required_node_ids]
return '\n'.join(node_requires)
def get_icon(dict_value):
icon = ''
if 'icon' in dict_value:
i... |
total_food = int(input())
total_food_grams = total_food * 1000
is_food_over = False
command = input()
while command != 'Adopted':
eaten_food = int(command)
total_food_grams -= eaten_food
if total_food_grams < 0:
is_food_over = True
command = input()
if is_food_over:
print(f'Food is not ... | total_food = int(input())
total_food_grams = total_food * 1000
is_food_over = False
command = input()
while command != 'Adopted':
eaten_food = int(command)
total_food_grams -= eaten_food
if total_food_grams < 0:
is_food_over = True
command = input()
if is_food_over:
print(f'Food is not enoug... |
# to get a string like this run:
# openssl rand -hex 32
SECRET_KEY = "de45991397da83e674149beb168b17fde74ebd4a8d6ca65310aedc7a082d5309"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
| secret_key = 'de45991397da83e674149beb168b17fde74ebd4a8d6ca65310aedc7a082d5309'
algorithm = 'HS256'
access_token_expire_minutes = 30 |
#!/usr/bin/env python3
#ccpc20qhda
gcd = lambda a,b: b if a==0 else gcd(b%a,a)
t = int(input())
for i in range(t):
m,n = list(map(int,input().split()))
aa = m*(m-1)
bb = (m+n)*(m+n-1)
c = gcd(aa,bb)
print('Case #%d: %d/%d'%(i+1,aa//c,bb//c))
| gcd = lambda a, b: b if a == 0 else gcd(b % a, a)
t = int(input())
for i in range(t):
(m, n) = list(map(int, input().split()))
aa = m * (m - 1)
bb = (m + n) * (m + n - 1)
c = gcd(aa, bb)
print('Case #%d: %d/%d' % (i + 1, aa // c, bb // c)) |
class Room:
def __init__(self, lw, rw, name=""):
self.id = id(self)
self.name = name
self.leftWall = lw
self.rightWall = rw
self.P = 0
self.S = 0
self.W = 0
self.C = 0
self.parseFinish = False
def getId(self):
return self.id
d... | class Room:
def __init__(self, lw, rw, name=''):
self.id = id(self)
self.name = name
self.leftWall = lw
self.rightWall = rw
self.P = 0
self.S = 0
self.W = 0
self.C = 0
self.parseFinish = False
def get_id(self):
return self.id
... |
'''
@description: Some training parameters
@author: liutaiting
@lastEditors: liutaiting
@Date: 2020-04-01 23:49:35
@LastEditTime: 2020-04-04 23:41:21
'''
EPOCHS = 5
BATCH_SIZE = 32
NUM_CLASSES = 7
image_width = 48
image_height = 48
channels = 1
model_dir = "image_classification_model.h5"
train_dir = "dataset/train"
va... | """
@description: Some training parameters
@author: liutaiting
@lastEditors: liutaiting
@Date: 2020-04-01 23:49:35
@LastEditTime: 2020-04-04 23:41:21
"""
epochs = 5
batch_size = 32
num_classes = 7
image_width = 48
image_height = 48
channels = 1
model_dir = 'image_classification_model.h5'
train_dir = 'dataset/train'
val... |
# Node 'Class'
#
# written by John C. Lusth, copyright 2012
#
# not really an object, a node is an abstraction of
# a two-element array the first slot holds the value
# the second slot holds the next pointer
#
# VERSION 1.0
def NodeCreate(value,next): return [value,next]
def NodeValue(n): return n[0]
def NodeNext(n): ... | def node_create(value, next):
return [value, next]
def node_value(n):
return n[0]
def node_next(n):
return n[1]
def node_set_value(n, value):
n[0] = value
return value
def node_set_next(n, next):
n[1] = next
return next
def list_create(*args):
items = None
for i in range(len(arg... |
# 01234567890123456789012345
letters = "abcdefghijklmnopqrstuvwxyz"
backwards = letters[25:0:-1]
# if I want to print z...a then in line 4 I should write : backwards = letters[25::-1], so the slicing starts printing from 25 backwards to the start INCLUDING the start
# create a slice that produces the charact... | letters = 'abcdefghijklmnopqrstuvwxyz'
backwards = letters[25:0:-1]
print(letters[16:13:-1])
print(letters[4::-1])
print(letters[25:17:-1])
print(backwards)
print(letters[-4:])
print(letters[-1:])
print(letters[:1])
print(letters[0]) |
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
def dfs(course,prerequisite,used):
used.add(course)
if prerequisites[1] not in used:
dfs(prerequisites,prerequisites[1],used)
used = set()
used_1 = s... | class Solution:
def can_finish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
def dfs(course, prerequisite, used):
used.add(course)
if prerequisites[1] not in used:
dfs(prerequisites, prerequisites[1], used)
used = set()
used_1 = set... |
class Plugin(object):
name = "base"
description = "base plugin"
def add_arguments(self, parser):
pass
| class Plugin(object):
name = 'base'
description = 'base plugin'
def add_arguments(self, parser):
pass |
v, n = [int(x) for x in input().split()]
total = v*n
for i in range(1, 10):
if i>=2:
print(" ", end="")
print((total*i+9)// 10, end="")
print()
| (v, n) = [int(x) for x in input().split()]
total = v * n
for i in range(1, 10):
if i >= 2:
print(' ', end='')
print((total * i + 9) // 10, end='')
print() |
'''write a simple function to add two integers,
demonstrate how to call the function with various
inputs'''
# call the function add, 2 and 3, print the result to the terminal
# call the function add, 2 and 3, save the result as a variable | """write a simple function to add two integers,
demonstrate how to call the function with various
inputs""" |
l1= []
l2 = []
i = int(input())
for a in range (0,i):
a = input()
if (a[0]=='1'):
l1.append(a[-1])
elif (a[0]=='2'):
l2.append(a[-1])
elif (a[0] == '5'):
for b in range (0,len(l1)):
print (l1[b], end = " ")
print()
elif (a[0] == '6'):
for b in rang... | l1 = []
l2 = []
i = int(input())
for a in range(0, i):
a = input()
if a[0] == '1':
l1.append(a[-1])
elif a[0] == '2':
l2.append(a[-1])
elif a[0] == '5':
for b in range(0, len(l1)):
print(l1[b], end=' ')
print()
elif a[0] == '6':
for b in range(0, l... |
# Write a function to rotate an array. You are given the array arr,
# n, the size of an array, and d, the number of elements to pivot on
# [1,2,3,4,5,6,7], n = 7, d = 2
# [3,4,5,6,7,1,2]
def rotate_array(arr, n, d):
if n == 0:
return None
elif n == 1:
return arr
return arr[d:] + arr[:d... | def rotate_array(arr, n, d):
if n == 0:
return None
elif n == 1:
return arr
return arr[d:] + arr[:d]
if __name__ == '__main__':
arr = [1, 2, 3, 4, 5, 6, 7]
arr2 = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
n = 10
d = 3
print(rotate_array(arr2, n, d)) |
class Solution:
def checkIfPrerequisite(self, n: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:
graph = collections.defaultdict(list)
innodes = collections.defaultdict(list)
indegrees = [0] * n
for u, v in prerequisites:
indegrees[v] += 1
... | class Solution:
def check_if_prerequisite(self, n: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:
graph = collections.defaultdict(list)
innodes = collections.defaultdict(list)
indegrees = [0] * n
for (u, v) in prerequisites:
indegrees[v] +=... |
# Rotting Oranges
# https://leetcode.com/problems/rotting-oranges/
# In a given grid, each cell can have one of three values:
# the value 0 representing an empty cell;
# the value 1 representing a fresh orange;
# the value 2 representing a rotten orange.
# Every minute, any fresh orange that is adjacent (4-direction... | def oranges_rotting(grid):
minute_count = 0
def create_set(grid, target_value):
result = set()
for y in range(len(grid)):
for x in range(len(grid[0])):
if grid[y][x] == target_value:
result.add((x, y))
return result
rotten_os = create_... |
def travel(n,I,O):
l1=[]
#print(I,O)
for i in range(n):
l4=[]
for j in range(n):
if i==j:
l4.append(1)
else:
l4.append(0)
l1.append(l4)
#print(l1)
#print(l1[0].index(1))
for out in range(n):
incoming=out
... | def travel(n, I, O):
l1 = []
for i in range(n):
l4 = []
for j in range(n):
if i == j:
l4.append(1)
else:
l4.append(0)
l1.append(l4)
for out in range(n):
incoming = out
outgoing = out
while incoming != 0:
... |
# Here 'n' is the number of rows and columns
def pattern(n):
for a in range(n):
print("* "*n,end="\n")
pattern(5)
'''
this will return
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
'''
| def pattern(n):
for a in range(n):
print('* ' * n, end='\n')
pattern(5)
'\n\nthis will return \n\n* * * * *\n* * * * *\n* * * * *\n* * * * *\n* * * * *\n\n' |
# ... client initialization left out
data_client = client.data
file_path = "characterizations/CdTe1.json"
dataset_id = 1
data_client.upload(dataset_id, file_path) | data_client = client.data
file_path = 'characterizations/CdTe1.json'
dataset_id = 1
data_client.upload(dataset_id, file_path) |
# Python Loops
# for [iterator] in [sequence]
# [sequence] = range(start, end, step)
print ("\nLoop with range")
evenodd = lambda n : "even" if n % 2 == 0 else "odd"
for i in range(1, 11):
print (i, "is " + str(evenodd(i)))
print ("\nLoop in range with step")
for i in range(1, 11, 2):
print (i, "is " + str(ev... | print('\nLoop with range')
evenodd = lambda n: 'even' if n % 2 == 0 else 'odd'
for i in range(1, 11):
print(i, 'is ' + str(evenodd(i)))
print('\nLoop in range with step')
for i in range(1, 11, 2):
print(i, 'is ' + str(evenodd(i)))
print('\nLoop through list')
flist = [0.1, 1.1, 2.1, 3.1, 4.1, 5.1]
for i in flis... |
path = "input.txt"
file = open(path)
input = file.readlines()
file.close()
all_fish = [[int(x) for x in line.split(",")] for line in input][0]
for i in range(80):
new = 0
for idx in range(len(all_fish)):
if all_fish[idx] == 0:
all_fish[idx] = 6
new += 1
else:
... | path = 'input.txt'
file = open(path)
input = file.readlines()
file.close()
all_fish = [[int(x) for x in line.split(',')] for line in input][0]
for i in range(80):
new = 0
for idx in range(len(all_fish)):
if all_fish[idx] == 0:
all_fish[idx] = 6
new += 1
else:
... |
def test1_3():
n = 1
while True:
time1 = 100*n**2
time2 = 2**n
if time1 >= time2:
n += 1
else:
break
print(n, time1, time2)
test1_3()
| def test1_3():
n = 1
while True:
time1 = 100 * n ** 2
time2 = 2 ** n
if time1 >= time2:
n += 1
else:
break
print(n, time1, time2)
test1_3() |
def numDepthIncreases():
'''
Problem: https://adventofcode.com/2021/day/1/
'''
with open("data.txt") as f:
data = f.readlines()
num_depth_increases = 0
for i, line in enumerate(data):
if i > 0 and i <= len(data):
if int(line.strip('\n')) > int(data[i-1].str... | def num_depth_increases():
"""
Problem: https://adventofcode.com/2021/day/1/
"""
with open('data.txt') as f:
data = f.readlines()
num_depth_increases = 0
for (i, line) in enumerate(data):
if i > 0 and i <= len(data):
if int(line.strip('\n')) > int(data[i - 1].strip('\... |
class ServiceReviewHistory:
def __init__(self, org_uuid, service_uuid, service_metadata, state, reviewed_by, reviewed_on, created_on,
updated_on):
self._org_uuid = org_uuid
self._service_uuid = service_uuid
self._service_metadata = service_metadata
self._state = stat... | class Servicereviewhistory:
def __init__(self, org_uuid, service_uuid, service_metadata, state, reviewed_by, reviewed_on, created_on, updated_on):
self._org_uuid = org_uuid
self._service_uuid = service_uuid
self._service_metadata = service_metadata
self._state = state
self._... |
class Solution:
def XXX(self, n: int) -> str:
dp = '1'
for i in range(n-1):
s, cur_char, cnt, dp = dp, dp[0], 0, ''
for index in range(len(s)):
if s[index] == cur_char: cnt += 1
else:
dp += str(cnt) + cur_char
... | class Solution:
def xxx(self, n: int) -> str:
dp = '1'
for i in range(n - 1):
(s, cur_char, cnt, dp) = (dp, dp[0], 0, '')
for index in range(len(s)):
if s[index] == cur_char:
cnt += 1
else:
dp += str(cnt... |
def starts_with_vowel(word: str) -> bool:
return word[0].lower() in "aeiou"
def translate_word(word: str) -> str:
if starts_with_vowel(word):
return word + "yay"
vowel_index = 0
for index, letter in enumerate(word):
if starts_with_vowel(letter):
vowel_index = index
... | def starts_with_vowel(word: str) -> bool:
return word[0].lower() in 'aeiou'
def translate_word(word: str) -> str:
if starts_with_vowel(word):
return word + 'yay'
vowel_index = 0
for (index, letter) in enumerate(word):
if starts_with_vowel(letter):
vowel_index = index
... |
BuildSettingInfo = provider()
def _string_imp(ctx):
value = ctx.build_setting_value
label = ctx.label.name
print("evaluated value for " + label + ": " + value)
return BuildSettingInfo(value = value)
string_flag = rule(
implementation = _string_imp,
# https://docs.bazel.build/versions/main/skyl... | build_setting_info = provider()
def _string_imp(ctx):
value = ctx.build_setting_value
label = ctx.label.name
print('evaluated value for ' + label + ': ' + value)
return build_setting_info(value=value)
string_flag = rule(implementation=_string_imp, build_setting=config.string(flag=True)) |
for _ in range(int(input())):
tot = 0
lst = list(map(int, input().split()))
for i in range(1, len(lst)):
if lst[i] > lst[i - 1] * 2:
tot += (lst[i] - 2 * lst[i - 1])
print(tot)
| for _ in range(int(input())):
tot = 0
lst = list(map(int, input().split()))
for i in range(1, len(lst)):
if lst[i] > lst[i - 1] * 2:
tot += lst[i] - 2 * lst[i - 1]
print(tot) |
class ModuleAggregator:
def __init__(self, registry_name) -> None:
self.registry_name = registry_name
self._registry = {}
def __getitem__(self, key):
if isinstance(key, str):
return self._registry[key]
return key
def register(self, name=None):
def wrappe... | class Moduleaggregator:
def __init__(self, registry_name) -> None:
self.registry_name = registry_name
self._registry = {}
def __getitem__(self, key):
if isinstance(key, str):
return self._registry[key]
return key
def register(self, name=None):
def wrap... |
parrot = 'NORWEGIAN BLUE'
print(parrot)
print(parrot[3])
print(parrot[4])
print()
print(parrot[3])
print(parrot[6])
print(parrot[8])
print()
print(parrot[-4:])
print()
number = '9,243;365:248 978;269'
separators = number[1::4]
print(separators) | parrot = 'NORWEGIAN BLUE'
print(parrot)
print(parrot[3])
print(parrot[4])
print()
print(parrot[3])
print(parrot[6])
print(parrot[8])
print()
print(parrot[-4:])
print()
number = '9,243;365:248 978;269'
separators = number[1::4]
print(separators) |
class User:
'''
class that generates new instances of users
'''
user_list = [] #empty user list
def __init__(self,username,password):
self.username = username
self.password = password
def registration(self):
'''
registration method adds users to the system
... | class User:
"""
class that generates new instances of users
"""
user_list = []
def __init__(self, username, password):
self.username = username
self.password = password
def registration(self):
"""
registration method adds users to the system
"""
... |
app_name = 'price_analysis'
urlpatterns = []
| app_name = 'price_analysis'
urlpatterns = [] |
# -*- coding: utf-8 -*-
class Model(object):
pass
class NullModel(Model):
def __init__(self):
pass
@property
def name(self):
return ''
| class Model(object):
pass
class Nullmodel(Model):
def __init__(self):
pass
@property
def name(self):
return '' |
#
# PySNMP MIB module HUAWEI-PWE3-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-PWE3-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:45:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, constraints_union, value_size_constraint, value_range_constraint) ... |
#**kwagrs use for complex agrument like dictionary store string values
def func(**kwargs):
for key, value in kwargs.items():
print("{} : {} ".format(key,value))
dict = {"Manish":"Male","Rashmi":"Female"}
func(**dict)
| def func(**kwargs):
for (key, value) in kwargs.items():
print('{} : {} '.format(key, value))
dict = {'Manish': 'Male', 'Rashmi': 'Female'}
func(**dict) |
nome1 = 'Felipe'
nome2 = 'Schmaedecke'
for n in nome1:
if n not in nome2:
print(n, end=' ')
for n in nome2:
if n not in nome1:
print(n, end=' ')
| nome1 = 'Felipe'
nome2 = 'Schmaedecke'
for n in nome1:
if n not in nome2:
print(n, end=' ')
for n in nome2:
if n not in nome1:
print(n, end=' ') |
#The code is to take in numbers which are even and odd in the provided set
even_numbers = []
odd_numbers = []
for number in range(0,1001):
if number % 2 == 0:
even_numbers.append(number)
else:
odd_numbers.append(number)
print(even_numbers)
print("\n")
print("\n")
print(odd_numbers) | even_numbers = []
odd_numbers = []
for number in range(0, 1001):
if number % 2 == 0:
even_numbers.append(number)
else:
odd_numbers.append(number)
print(even_numbers)
print('\n')
print('\n')
print(odd_numbers) |
#
# PySNMP MIB module AC-ANALOG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AC-ANALOG-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:54:29 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... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, single_value_constraint, constraints_union, constraints_intersection) ... |
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f"You have {cheese_count} cheeses")
print(f"You have {boxes_of_crackers} boxes of crackers")
print("That's a lot")
print("Get a blanket\n")
print("We can just give the function numbers directly")
cheese_and_crackers(20, 30)
print("Or, we can use ... | def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f'You have {cheese_count} cheeses')
print(f'You have {boxes_of_crackers} boxes of crackers')
print("That's a lot")
print('Get a blanket\n')
print('We can just give the function numbers directly')
cheese_and_crackers(20, 30)
print('Or, we ca... |
class Solution:
def rob(self, nums):
n = len(nums)
if n == 1:
return nums[0]
dpa = [0] * (n + 1)
dpb = [0] * (n + 1)
for i in range(2, n + 1):
dpa[i] = max(dpa[i - 1], dpa[i - 2] + nums[i - 2])
dpb[i] = max(dpb[i - 1], dpb[i - 2] + nums[i ... | class Solution:
def rob(self, nums):
n = len(nums)
if n == 1:
return nums[0]
dpa = [0] * (n + 1)
dpb = [0] * (n + 1)
for i in range(2, n + 1):
dpa[i] = max(dpa[i - 1], dpa[i - 2] + nums[i - 2])
dpb[i] = max(dpb[i - 1], dpb[i - 2] + nums[i ... |
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
__author__ = 'Zhiquan Wang'
__date__ = '2018/8/15 10:44'
class MessageType(object):
login_request = u'LoginRequest'
login_reply = u'LoginReply'
attack_request = u'AttackRequest'
attack_reply = u'AttackReply'
game_info = u'GameInfo'
class JsonAttribu... | __author__ = 'Zhiquan Wang'
__date__ = '2018/8/15 10:44'
class Messagetype(object):
login_request = u'LoginRequest'
login_reply = u'LoginReply'
attack_request = u'AttackRequest'
attack_reply = u'AttackReply'
game_info = u'GameInfo'
class Jsonattribute(object):
msg_type = u'msg_type'
lr_usr... |
#!/usr/bin/python3
# Because I decided to use the ThreadingMixIn in the HTTPServer
# we will need to persist the data on disk...
# DB_FILE = ':memory:'
DB_FILE = 'db.sqlite3'
| db_file = 'db.sqlite3' |
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
d = {}
def dfs(node, level):
if level not in d:
d[level] = []
d[level].append(node.val)
if node.left:
dfs(node.left, level + 1)... | class Solution:
def zigzag_level_order(self, root: TreeNode) -> List[List[int]]:
d = {}
def dfs(node, level):
if level not in d:
d[level] = []
d[level].append(node.val)
if node.left:
dfs(node.left, level + 1)
if node.r... |
# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
# Find the sum of all the primes below two million.
# Primes are hard....recycle code from problem 7...
n = 2
limit = 1000
primes = []
prime = 0
primeSum = 0
while prime <= limit:
for i in range(2,n):
if (n % i) == 0:
break
else:
... | n = 2
limit = 1000
primes = []
prime = 0
prime_sum = 0
while prime <= limit:
for i in range(2, n):
if n % i == 0:
break
else:
primes.append(n)
prime = n
prime_sum += n
n += 1
print('THE LAST PRIME ADDED WAS: ' + str(prime))
print("SO I'LL JUST GO AHEAD AND SUBTRAC... |
# String Literals
hello_world = "Hello, World"
hello_world_two = " Hello World "
print(hello_world[1])
print(hello_world[0:5])
# Length of the string
print(len(hello_world))
# Strip
print(hello_world_two)
print(hello_world_two.strip())
# Lower
print(hello_world.lower())
# Upper
print(hello_world.upper())
# Replace... | hello_world = 'Hello, World'
hello_world_two = ' Hello World '
print(hello_world[1])
print(hello_world[0:5])
print(len(hello_world))
print(hello_world_two)
print(hello_world_two.strip())
print(hello_world.lower())
print(hello_world.upper())
print(hello_world.replace('H', 'J'))
print(hello_world.split(',')) |
#Needs more comments
#Node class
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
def getData(self):
return self.data
#Adjanceny List graph implementation
class ALGraph:
#initialize list
def __init__(self):
self.table = []
#ad... | class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
def get_data(self):
return self.data
class Algraph:
def __init__(self):
self.table = []
def insert_vertex(self, data):
temp = node(data)
self.table.append(temp)
de... |
s = float(input('Digite o salario do funcionario: R$ '))
if s>1250:
print('Quem ganhava R${} passa a ganhar R${:.2f} agora.'.format(s,s+(s*10/100)))
else:
print('Quem ganhava R${} passa a ganhar R${:.2f} agora'.format(s,s+(s*15/100)))
| s = float(input('Digite o salario do funcionario: R$ '))
if s > 1250:
print('Quem ganhava R${} passa a ganhar R${:.2f} agora.'.format(s, s + s * 10 / 100))
else:
print('Quem ganhava R${} passa a ganhar R${:.2f} agora'.format(s, s + s * 15 / 100)) |
# Data Type in Python is an attribute of data which tells the interpreter how the programmer intends to use the data
# There are three numeric data types in Python:
# Integers
# Integers (e.g. 2, 4, 20)
# - Boolean (e.g. False and True, acting like 0 and 1)
# Floating Point Numbers (e.g. 3.0, 5.2)
# Complex Number... | positive_integer = 34
negative_integer = -3237937
big_integer = 62733287329879274032843048
print(positive_integer)
print(negative_integer)
print(big_integer)
print('**********************************************************')
my_boolean_value1 = True
my_boolean_value2 = False
print(myBooleanValue1)
print(myBooleanValue... |
class Quadrilatero:
def __init__(self, lado1, lado2):
self.__lado1 = lado1
self.__lado2 = lado2
def retangulo():
pass
def retangulo():
pass
def retangulo():
pass | class Quadrilatero:
def __init__(self, lado1, lado2):
self.__lado1 = lado1
self.__lado2 = lado2
def retangulo():
pass
def retangulo():
pass
def retangulo():
pass |
#creating a node
class Node:
def __init__(self,data):
self.value=data
self.left=None
self.right=None
#function to check if the tree is a mirror image of another tree
def isMirror(troot1, troot2):
if troot1 == None and troot2 == None:
return True;
if (troot1 != None and t... | class Node:
def __init__(self, data):
self.value = data
self.left = None
self.right = None
def is_mirror(troot1, troot2):
if troot1 == None and troot2 == None:
return True
if troot1 != None and troot2 != None:
if troot1.value == troot2.value:
return is_m... |
# pylint: skip-file
# pylint: disable=too-many-instance-attributes
class GcloudResourceBuilder(object):
''' Class to wrap the gcloud deployment manager '''
# pylint allows 5
# pylint: disable=too-many-arguments
def __init__(self,
clusterid,
project,
r... | class Gcloudresourcebuilder(object):
""" Class to wrap the gcloud deployment manager """
def __init__(self, clusterid, project, region, zone, verbose=False):
""" Constructor for gcloud resource """
self.clusterid = clusterid
self.project = project
self.region = region
se... |
# Outputs strings with inverted commas
# Author: Isabella Doyle
message = 'John said "hi", I said "bye.'
print(message) | message = 'John said "hi", I said "bye.'
print(message) |
# 000758_02_02_ifStatements.py
print("000758_02_02_ifStatements:01")
if 10 > 5:
print("10 greater than 5")
print("Program ended")
print("")
print("000758_02_02_ifStatements:02:nested")
num = 12
if num > 5:
print("Bigger than 5")
if num <= 47:
print("Between 5 and 47")
print("")
print("000758_02_02_... | print('000758_02_02_ifStatements:01')
if 10 > 5:
print('10 greater than 5')
print('Program ended')
print('')
print('000758_02_02_ifStatements:02:nested')
num = 12
if num > 5:
print('Bigger than 5')
if num <= 47:
print('Between 5 and 47')
print('')
print('000758_02_02_ifStatements:q.03:nested')
num =... |
PREFIX = "/api"
CORS_POLICY = {"origins": ("*",), "max_age": 3600}
class Base:
def __init__(self, request, context=None):
self.request = request
@property
def _index(self):
return self.request.registry.settings["pyfapi.es.index"]
def _result(self, result):
return {"result": ... | prefix = '/api'
cors_policy = {'origins': ('*',), 'max_age': 3600}
class Base:
def __init__(self, request, context=None):
self.request = request
@property
def _index(self):
return self.request.registry.settings['pyfapi.es.index']
def _result(self, result):
return {'result': r... |
# Exer 8
# # Creating a list of nice places to visit
places_to_visit = ['island', 'australia', 'cananda', 'thailand']
print(places_to_visit)
# putting the list into alphabetic order
print(sorted(places_to_visit))
# putting the list back to its original order
print(places_to_visit)
# putting the list backwards
place... | places_to_visit = ['island', 'australia', 'cananda', 'thailand']
print(places_to_visit)
print(sorted(places_to_visit))
print(places_to_visit)
places_to_visit.reverse()
print(places_to_visit)
places_to_visit.sort()
print(len(places_to_visit)) |
def print_matrix(matrix):
for row in matrix:
for elem in row:
print(elem, end='\t')
print()
print(__name__)
if __name__ == "__main__":
print("Something to run as stand alone script")
| def print_matrix(matrix):
for row in matrix:
for elem in row:
print(elem, end='\t')
print()
print(__name__)
if __name__ == '__main__':
print('Something to run as stand alone script') |
#!/usr/bin/env python3
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
__all__ = [
'datastructures',
'exception',
'funcs',
'info',
'kprobe',
'... | __all__ = ['datastructures', 'exception', 'funcs', 'info', 'kprobe', 'prog', 'socket_filter', 'tc', 'util'] |
l=[]
print(l)
l.append(10)
print(l)
l.append(11)
print(l) | l = []
print(l)
l.append(10)
print(l)
l.append(11)
print(l) |
# coding = utf-8
# @time : 2019/6/30 6:41 PM
# @author : alchemistlee
# @fileName: filter_long_tk.py
# @abstract:
if __name__ == '__main__':
input_zh = '/root/workspace/translate_data/my_corpus_v6.zh-cut.processed6-bpe-v6-2-.test'
input_en = '/root/workspace/translate_data/my_corpus_v6.en.tok.processed6-... | if __name__ == '__main__':
input_zh = '/root/workspace/translate_data/my_corpus_v6.zh-cut.processed6-bpe-v6-2-.test'
input_en = '/root/workspace/translate_data/my_corpus_v6.en.tok.processed6-bpe-v6-2-.test'
out_zh = '/root/workspace/translate_data/my_corpus_v6.zh-cut.processed6-bpe-v6-2-filter3.test'
ou... |
#
# PySNMP MIB module Fore-frs-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Fore-frs-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:04:09 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, single_value_constraint, value_size_constraint, value_range_constraint) ... |
## pure function: has no side effect and returns a value based on their arguments
def pure_function(x,y):
temp = x + 2*y
return temp / y + 2*x
##impure function
some_list = []
def impure(arg):
some_list.append(arg) | def pure_function(x, y):
temp = x + 2 * y
return temp / y + 2 * x
some_list = []
def impure(arg):
some_list.append(arg) |
class Solution(object):
def brokenCalc(self, X, Y):
res = 0
while Y > X:
res += Y % 2 + 1
Y = Y // 2 if Y % 2 == 0 else (Y + 1)//2
return res + X - Y
def main():
startValue = 2
target = 3
startValue = 5
target = 8
startValue = 3
target = 10
startValue ... | class Solution(object):
def broken_calc(self, X, Y):
res = 0
while Y > X:
res += Y % 2 + 1
y = Y // 2 if Y % 2 == 0 else (Y + 1) // 2
return res + X - Y
def main():
start_value = 2
target = 3
start_value = 5
target = 8
start_value = 3
target ... |
'''
Created on Nov 22, 2010
@author: johantenbroeke
'''
| """
Created on Nov 22, 2010
@author: johantenbroeke
""" |
# First we'll start an undo action, then Ctrl-Z will undo the actions of the whole script
editor.beginUndoAction()
# Do a Python regular expression replace, full support of Python regular expressions
# This replaces any three uppercase letters that are repeated,
# so ABDABD, DEFDEF or DGBDGB etc. the first 3 char... | editor.beginUndoAction()
editor.rereplace('([A-Z]{3})\\1', '\\1')
editor.rereplace('<br/>\\s*\\r\\n\\s*<br/>', '<br/>\r\n')
editor.endUndoAction() |
class Product(object):
def __init__(self, product_name:str, global_id, price, description="") -> None:
self.product_id = global_id
self.product_name = product_name
self.description = description
self.price = price
print("created product {0.product_name}".format(se... | class Product(object):
def __init__(self, product_name: str, global_id, price, description='') -> None:
self.product_id = global_id
self.product_name = product_name
self.description = description
self.price = price
print('created product {0.product_name}'.format(self))
... |
# Modify the previous program such that only multiples of three or five are considered in the sum, e.g. 3, 5, 6, 9, 10, 12, 15 for n=17
num = int(input("Enter number: "))
def bubbles_sum(num):
sum = 0
for a in range(1, num + 1):
sum = sum + a
if (a % 3 == 0 or a % 5 == 0) :
sum = s... | num = int(input('Enter number: '))
def bubbles_sum(num):
sum = 0
for a in range(1, num + 1):
sum = sum + a
if a % 3 == 0 or a % 5 == 0:
sum = sum + a
print(sum) |
# The channel to send the log messages to
CHANNEL_NAME = "voice-log"
# The bot token
BOT_TOKEN = "NDI3NTIyNzMxNjgxsasdsagsadshvbn,.fgsfgjfkLHEGROoAxA"
| channel_name = 'voice-log'
bot_token = 'NDI3NTIyNzMxNjgxsasdsagsadshvbn,.fgsfgjfkLHEGROoAxA' |
# use the function blackbox(lst) that is already defined
lst = ["a", "b", "c"]
blackbox_lst = blackbox(lst)
print("modifies" if id(lst) == id(blackbox_lst) else "new")
| lst = ['a', 'b', 'c']
blackbox_lst = blackbox(lst)
print('modifies' if id(lst) == id(blackbox_lst) else 'new') |
expected_output = {
"instance": {
"default": {
"vrf": {
"EVPN-BGP-Table": {
"address_family": {
"l2vpn evpn": {
"prefixes": {
"[3][40.0.0.3:164][0][32][40.0.0.7]/17": {
... | expected_output = {'instance': {'default': {'vrf': {'EVPN-BGP-Table': {'address_family': {'l2vpn evpn': {'prefixes': {'[3][40.0.0.3:164][0][32][40.0.0.7]/17': {'table_version': '234', 'nlri_data': {'route-type': '3', 'rd': '40.0.0.3:164', 'eti': '0', 'ip_len': '32', 'orig_rtr_id': '40.0.0.7', 'subnet': '17'}, 'availabl... |
def get_colnames(score: str):
colnames = {
"charlson": {
"aids": "AIDS or HIV",
"ami": "acute myocardial infarction",
"canc": "cancer any malignancy",
"cevd": "cerebrovascular disease",
"chf": "congestive heart failure",
"copd": "chron... | def get_colnames(score: str):
colnames = {'charlson': {'aids': 'AIDS or HIV', 'ami': 'acute myocardial infarction', 'canc': 'cancer any malignancy', 'cevd': 'cerebrovascular disease', 'chf': 'congestive heart failure', 'copd': 'chronic obstructive pulmonary disease', 'dementia': 'dementia', 'diab': 'diabetes withou... |
#!/usr/bin/env python
'''
Test Templates
'''
regList = ["A", "B", "C", "D", "E", "F", "H", "L", "HL", "PC", "SP"]
cpuTestFile = '''
namespace GameBoyEmulator.Desktop.Tests {
[TestFixture]
public class CPUTest {
private const int RUN_CYCLES = 10;
{TESTS}
}
}
'''
baseTestTemplate = '''
... | """
Test Templates
"""
reg_list = ['A', 'B', 'C', 'D', 'E', 'F', 'H', 'L', 'HL', 'PC', 'SP']
cpu_test_file = '\nnamespace GameBoyEmulator.Desktop.Tests {\n [TestFixture]\n public class CPUTest {\n private const int RUN_CYCLES = 10;\n\n {TESTS}\n }\n}\n'
base_test_template = '\n [Test]\n ... |
#Start of code
x=['a','e','i','o','u','A','E','I','O','U']
y=input("Enter an Alphabet: ")
if y in x:
print(y,"is a vowel")
else:
print(y,"is not a vowel")
#End of code
| x = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
y = input('Enter an Alphabet: ')
if y in x:
print(y, 'is a vowel')
else:
print(y, 'is not a vowel') |
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'utils.authenticate.GoogleBackend',
]
| authentication_backends = ['django.contrib.auth.backends.ModelBackend', 'utils.authenticate.GoogleBackend'] |
N, M = map(int, input().split())
A = []
B = []
for i in range(N):
A.append(list(map(int, input().split())))
for i in range(N):
B.append(list(map(int, input().split())))
C = []
for i in range(N):
tmp = []
for j in range(M):
a = A[i][j]
b = B[i][j]
tmp.append(a ^ b)
C.append(... | (n, m) = map(int, input().split())
a = []
b = []
for i in range(N):
A.append(list(map(int, input().split())))
for i in range(N):
B.append(list(map(int, input().split())))
c = []
for i in range(N):
tmp = []
for j in range(M):
a = A[i][j]
b = B[i][j]
tmp.append(a ^ b)
C.append(... |
contacts = {}
running = True;
while running:
command = input('enter A(dd) D(elete) F(ind) Q(uit)')
if command == 'A' or command == 'a':
name = input('enter a new name');
print('enter a phone number for', name, end=':')
number=input()
contacts[name] = number
elif command == ... | contacts = {}
running = True
while running:
command = input('enter A(dd) D(elete) F(ind) Q(uit)')
if command == 'A' or command == 'a':
name = input('enter a new name')
print('enter a phone number for', name, end=':')
number = input()
contacts[name] = number
elif command == 'D... |
class Atom:
def __init__(self, symbol, atoms, neutr):
self.symbol = str(symbol)
self.atoms = int(atoms)
self.neutrons = int(neutr)
self.protons = int(0)
self.mass = int(0)
def proton_number(self):
self.protons = self.atoms - self.neutrons
return self.prot... | class Atom:
def __init__(self, symbol, atoms, neutr):
self.symbol = str(symbol)
self.atoms = int(atoms)
self.neutrons = int(neutr)
self.protons = int(0)
self.mass = int(0)
def proton_number(self):
self.protons = self.atoms - self.neutrons
return self.pro... |
#!/usr/bin/env python3
xList = [ int( x ) for x in input().split() ]
xList = sorted( xList )
medianIndex = len( xList ) // 2
if len( xList ) % 2 == 0:
print( ( xList[medianIndex-1] + xList[medianIndex] ) / 2. )
else:
print( float( xList[ medianIndex ] ) )
| x_list = [int(x) for x in input().split()]
x_list = sorted(xList)
median_index = len(xList) // 2
if len(xList) % 2 == 0:
print((xList[medianIndex - 1] + xList[medianIndex]) / 2.0)
else:
print(float(xList[medianIndex])) |
class Box(object):
def __init__(self, side, height):
self._side = side
self._height = height
def volume(self):
return self._side * self._side * self._height
def __lt__(self, other):
return self.volume() < other
def __eq__(self, other):
return self.volume() == o... | class Box(object):
def __init__(self, side, height):
self._side = side
self._height = height
def volume(self):
return self._side * self._side * self._height
def __lt__(self, other):
return self.volume() < other
def __eq__(self, other):
return self.volume() == ... |
class Card():
ranks = [str(n) for n in range(2, 10)] + list('TJQKA')
rank_tran = {rank: n for n, rank in enumerate(ranks, 2)}
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
self._numrank = self.rank_tran[rank]
def __eq__(self, other):
return self._num... | class Card:
ranks = [str(n) for n in range(2, 10)] + list('TJQKA')
rank_tran = {rank: n for (n, rank) in enumerate(ranks, 2)}
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
self._numrank = self.rank_tran[rank]
def __eq__(self, other):
return self._num... |
class Solution:
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
# def helper(countA, countB, idx, cur_cost):
# if idx == len(costs):
# return cur_cost
# if countA < len(costs) // 2 and countB < len(costs) // 2:
# return min(helper(countA + 1... | class Solution:
def two_city_sched_cost(self, costs: List[List[int]]) -> int:
a_minus_b = sorted([(a - b, a, b) for (a, b) in costs])
return sum([cost[1] for cost in a_minus_b[:len(costs) // 2]] + [cost[2] for cost in a_minus_b[len(costs) // 2:]]) |
enum_ = '''
[COMMENT_LINE_IMPORTS]
# System
from enum import Enum
[COMMENT_LINE]
[COMMENT_LINE_CLASS_NAME]
class [CLASS_NAME](Enum):
[TAB]Template = 0
[COMMENT_LINE]
'''.strip() | enum_ = '\n[COMMENT_LINE_IMPORTS]\n\n# System\nfrom enum import Enum\n\n[COMMENT_LINE]\n\n\n\n[COMMENT_LINE_CLASS_NAME]\n\nclass [CLASS_NAME](Enum):\n[TAB]Template = 0\n\n\n[COMMENT_LINE]\n'.strip() |
phones = [
{"id": 6, "latitude": 40.1011685523957, "longitude": -88.2200390954902},
{"id": 7, "latitude": 40.0963186128832, "longitude": -88.2255865263258},
{"id": 8, "latitude": 40.1153308841568, "longitude": -88.223901994968},
]
def get_phones():
return phones
bad_data = [
{"id": 6, "longitude... | phones = [{'id': 6, 'latitude': 40.1011685523957, 'longitude': -88.2200390954902}, {'id': 7, 'latitude': 40.0963186128832, 'longitude': -88.2255865263258}, {'id': 8, 'latitude': 40.1153308841568, 'longitude': -88.223901994968}]
def get_phones():
return phones
bad_data = [{'id': 6, 'longitude': -88.2200390954902}, ... |
ies = []
ies.append({ "iei" : "2C", "value" : "IMEISV", "type" : "5G mobile identity", "reference" : "9.10.3.4", "presence" : "O", "format" : "TLV", "length" : "11"})
ies.append({ "iei" : "7D", "value" : "NAS message container", "type" : "message container", "reference" : "9.10.3.31", "presence" : "O", "format" : "TLV-... | ies = []
ies.append({'iei': '2C', 'value': 'IMEISV', 'type': '5G mobile identity', 'reference': '9.10.3.4', 'presence': 'O', 'format': 'TLV', 'length': '11'})
ies.append({'iei': '7D', 'value': 'NAS message container', 'type': 'message container', 'reference': '9.10.3.31', 'presence': 'O', 'format': 'TLV-E', 'length': '... |
# Write a program that reads an integer and displays, using asterisks, a filled and hol-
# low square, placed next to each other. For example if the side length is 5, the pro gram
# should display
# ***** *****
# ***** * *
# ***** * *
# ***** * *
# ***** *****
side = int(input("Ente... | side = int(input('Enter side length: '))
line_num = 1
dot_num = 1
for i in range(side):
dot_num = 1
for i in range(side):
print('*', end='')
print(end=' ')
for i in range(side):
if lineNum == 1 or lineNum == side:
print('*', end='')
elif dotNum == 1 or dotNum == side:... |
class Solution:
def countBits(self, num: int) -> List[int]:
result = [0] * (1 + num)
for i in range(1, 1 + num):
result[i] = result[i&(i - 1)] + 1
return result
| class Solution:
def count_bits(self, num: int) -> List[int]:
result = [0] * (1 + num)
for i in range(1, 1 + num):
result[i] = result[i & i - 1] + 1
return result |
# function to check if two strings are
# anagram or not
def anagram(s1, s2):
# the sorted strings are checked
if(sorted(s1)== sorted(s2)):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.")
#commonCharacterCount
def commonC... | def anagram(s1, s2):
if sorted(s1) == sorted(s2):
print('The strings are anagrams.')
else:
print("The strings aren't anagrams.")
def common_character_count(s1, s2):
s = list(set(s1))
sum1 = 0
for i in s:
sum1 += min(s1.count(i), s2.count(i))
return sum1
def is_bananagra... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Back of envelope calculations for a precious metals mining company
try:
oz_per_yr = int(input("How many ounces will be produced annually?: "))
price_per_oz = int(input("What is the estimated USD price per ounce for the year?: "))
aisc = int(input("What is t... | try:
oz_per_yr = int(input('How many ounces will be produced annually?: '))
price_per_oz = int(input('What is the estimated USD price per ounce for the year?: '))
aisc = int(input('What is the USD AISC?: '))
exchange_rate = float(input('What is the USD/CAD exchange rate?: '))
shrs_out = int(input('H... |
class MergeSort:
def __init__(self,array):
self.array = array
def result(self):
self.sort(0,len(self.array)-1)
return self.array
def sort(self,front,rear):
if front>rear or front == rear:
return
mid = int((front+rear)/2)
self.sort(front,mid)
... | class Mergesort:
def __init__(self, array):
self.array = array
def result(self):
self.sort(0, len(self.array) - 1)
return self.array
def sort(self, front, rear):
if front > rear or front == rear:
return
mid = int((front + rear) / 2)
self.sort(fr... |
#!/usr/bin/python
def find_max_palindrome(min=100,max=999):
max_palindrome = 0
a = 999
while a > 99:
b = 999
while b >= a:
prod = a*b
if prod > max_palindrome and str(prod)==(str(prod)[::-1]):
max_palindrome = prod
b -= 1
a -= 1
... | def find_max_palindrome(min=100, max=999):
max_palindrome = 0
a = 999
while a > 99:
b = 999
while b >= a:
prod = a * b
if prod > max_palindrome and str(prod) == str(prod)[::-1]:
max_palindrome = prod
b -= 1
a -= 1
return max_pal... |
def write():
systemInfo_file = open("writeTest.txt", "a")
systemInfo_file.write("\nTEST DATA2")
systemInfo_file.close()
| def write():
system_info_file = open('writeTest.txt', 'a')
systemInfo_file.write('\nTEST DATA2')
systemInfo_file.close() |
# Problem Statement: https://www.hackerrank.com/challenges/exceptions/problem
for _ in range(int(input())):
try:
a, b = map(int, input().split())
print(a // b)
except (ZeroDivisionError, ValueError) as e:
print(f'Error Code: {e}') | for _ in range(int(input())):
try:
(a, b) = map(int, input().split())
print(a // b)
except (ZeroDivisionError, ValueError) as e:
print(f'Error Code: {e}') |
class Location:
__slots__ = 'name', '_longitude', '_latitude'
def __init__(self, name, longitude, latitude):
self._longitude = longitude
self._latitude = latitude
self.name = name
@property
def longitude(self):
return self._longitude
@property
d... | class Location:
__slots__ = ('name', '_longitude', '_latitude')
def __init__(self, name, longitude, latitude):
self._longitude = longitude
self._latitude = latitude
self.name = name
@property
def longitude(self):
return self._longitude
@property
def latitude(se... |
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
if not nums:
return 0
nums.sort()
count = 1
longest_streak = []
for index, value in enumerate(nums):
if index + 1 >= len(nums):
break
if nums[index + 1]... | class Solution:
def longest_consecutive(self, nums: List[int]) -> int:
if not nums:
return 0
nums.sort()
count = 1
longest_streak = []
for (index, value) in enumerate(nums):
if index + 1 >= len(nums):
break
if nums[index + ... |
jobs = {}
class JobInfo(object):
def __init__(self, jobId):
self.jobId = jobId
self.data = None
self.handlers = []
| jobs = {}
class Jobinfo(object):
def __init__(self, jobId):
self.jobId = jobId
self.data = None
self.handlers = [] |
print(list(enumerate([])))
print(list(enumerate([1, 2, 3])))
print(list(enumerate([1, 2, 3], 5)))
print(list(enumerate([1, 2, 3], -5)))
print(list(enumerate(range(10000))))
| print(list(enumerate([])))
print(list(enumerate([1, 2, 3])))
print(list(enumerate([1, 2, 3], 5)))
print(list(enumerate([1, 2, 3], -5)))
print(list(enumerate(range(10000)))) |
programming_dictonary = {
"Bug":"An error in program that prevents the program running as expected",
"Function":"A piece of code that you can call over and over again",
}
# Retreive
print(programming_dictonary["Bug"])
# Adding items
programming_dictonary["Loop"] = "The action of doing something again and again... | programming_dictonary = {'Bug': 'An error in program that prevents the program running as expected', 'Function': 'A piece of code that you can call over and over again'}
print(programming_dictonary['Bug'])
programming_dictonary['Loop'] = 'The action of doing something again and again'
empty_list = []
empty_dictonary = ... |
# ========== base graph node class / generic knowledge representation (AST/ASG)
class Object():
# node constructor with scalar initializer
def __init__(self, V):
# node class/type tag
self.type = self.__class__.__name__.lower()
# node name / scalar value
self.value = V
... | class Object:
def __init__(self, V):
self.type = self.__class__.__name__.lower()
self.value = V
self.slot = {}
self.nest = []
def __repr__(self):
return self.dump()
def test(self):
return self.dump(test=True)
def dump(self, cycle=[], depth=0, prefix=''... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.