content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class PolishWordnetParser:
__LEXICAL_UNIT = 'lexical-unit'
__SYNSET_UNIT = 'synset'
__LEXICAL_RELATIONS = 'lexicalrelations'
__SYNSET_RELATIONS = 'synsetrelations'
def __init__(self, version):
self.version = version
def lexical_unit(self):
return self.__LEXICAL_UNIT
def ... | class Polishwordnetparser:
__lexical_unit = 'lexical-unit'
__synset_unit = 'synset'
__lexical_relations = 'lexicalrelations'
__synset_relations = 'synsetrelations'
def __init__(self, version):
self.version = version
def lexical_unit(self):
return self.__LEXICAL_UNIT
def sy... |
"""Top-level package for education_math_homework_generator."""
__author__ = """Michael Shawn Marshall"""
__email__ = 'physbean@gmail.com'
__version__ = '0.2.0'
| """Top-level package for education_math_homework_generator."""
__author__ = 'Michael Shawn Marshall'
__email__ = 'physbean@gmail.com'
__version__ = '0.2.0' |
def register_to(bot):
def sauce(*args):
_, msg, _ = args
msg.reply('https://gitlab.stusta.mhn.de/stustanet/prism/').send()
return True
bot.respond('gimme-sauce', sauce,
help_text='gimme-sauce: posts the url of the source')
bot.respond('invoke-gpl', sauce, help_text... | def register_to(bot):
def sauce(*args):
(_, msg, _) = args
msg.reply('https://gitlab.stusta.mhn.de/stustanet/prism/').send()
return True
bot.respond('gimme-sauce', sauce, help_text='gimme-sauce: posts the url of the source')
bot.respond('invoke-gpl', sauce, help_text=None)
bot.r... |
def main(N, M, A):
memo = N - sum(A)
if memo >= 0:
return memo
else:
return -1
if __name__ == '__main__':
N, M = list(map(int, input().split()))
A = list(map(int, input().split()))
# N = 314
# M = 15
# A = list(map(int, "9 26 5 35 8 9 79 3 23 8 46 2 6 43 3".split()))
... | def main(N, M, A):
memo = N - sum(A)
if memo >= 0:
return memo
else:
return -1
if __name__ == '__main__':
(n, m) = list(map(int, input().split()))
a = list(map(int, input().split()))
print(main(N, M, A)) |
class TEST_MODULE:
def __init__(self, parent):
self.parent = parent
self.test = "test"
self.new_commands = {
"big_test": self.testf,
}
self.add_self()
# or just
# self.parent.parser.commands.update(self.new_commands)
# but I figured a function would be kinda better in special use cases
def testf... | class Test_Module:
def __init__(self, parent):
self.parent = parent
self.test = 'test'
self.new_commands = {'big_test': self.testf}
self.add_self()
def testf(self, arg=None):
print(self.test)
self.parent.command_out_set(f'{self.test}')
self.parent.comman... |
#
# PySNMP MIB module Wellfleet-DIFFSERV-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-DIFFSERV-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:39:50 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_range_constraint, value_size_constraint, constraints_union, single_value_constraint) ... |
def get_ref(db, col, identifier, obj):
for doc in db.collection(col).where(identifier, u'==', obj).stream():
return doc.reference
return None
def get_field(ref, field):
return ref.get().to_dict()[field]
def update(ref, key, val):
return ref.set({key: val}, merge=True)
def addEntry(ref, key, v... | def get_ref(db, col, identifier, obj):
for doc in db.collection(col).where(identifier, u'==', obj).stream():
return doc.reference
return None
def get_field(ref, field):
return ref.get().to_dict()[field]
def update(ref, key, val):
return ref.set({key: val}, merge=True)
def add_entry(ref, key, ... |
# ------------------------------
# 249. Group Shifted Strings
#
# Description:
# Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence:
# "abc" -> "bcd" -> ... -> "xyz"
# Given a list of strings which contains only lower... | class Solution:
def group_strings(self, strings):
"""
:type strings: List[str]
:rtype: List[List[str]]
"""
group = {}
for s in strings:
if len(s) == 1:
group.setdefault('a', []).append(s)
else:
key = 'a'
... |
# MIT License
# (C) Copyright 2021 Hewlett Packard Enterprise Development LP.
#
# vrrp : ECOS VRRP configuration
def get_vrrp_interfaes(
self,
ne_id: str,
cached: bool,
) -> list:
"""Get configured vrrp interfaces on appliance
.. list-table::
:header-rows: 1
* - Swagger Section
... | def get_vrrp_interfaes(self, ne_id: str, cached: bool) -> list:
"""Get configured vrrp interfaces on appliance
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - vrrp
- GET
- /vrrp/{neId}?cached={cached}
:param ne_id... |
# Momijigaoka
if sm.hasQuest(57106):
sm.warp(807030000, 0)
elif sm.hasQuest(57107):
sm.warp(807030100, 0)
else:
sm.systemMessage("There is nothing to see here.")
#sm.warp(807030200, 0) | if sm.hasQuest(57106):
sm.warp(807030000, 0)
elif sm.hasQuest(57107):
sm.warp(807030100, 0)
else:
sm.systemMessage('There is nothing to see here.') |
# 1401 - Warriors of Perion
sm.setSpeakerID(1022000) # Dances with Balrog
response = sm.sendAskYesNo("So you want to become a Warrior?")
if response:
sm.completeQuestNoRewards(parentID)
sm.jobAdvance(100)
sm.resetAP(False, 100)
sm.giveItem(1302182)
sm.sendSayOkay("You are now a #bWarrior#k.")
| sm.setSpeakerID(1022000)
response = sm.sendAskYesNo('So you want to become a Warrior?')
if response:
sm.completeQuestNoRewards(parentID)
sm.jobAdvance(100)
sm.resetAP(False, 100)
sm.giveItem(1302182)
sm.sendSayOkay('You are now a #bWarrior#k.') |
sm.setSpeakerID(1033210) # Great Spirit
response = sm.sendAskYesNo("Are you ready to take on great power?")
if response:
sm.startQuest(parentID)
sm.dispose()
| sm.setSpeakerID(1033210)
response = sm.sendAskYesNo('Are you ready to take on great power?')
if response:
sm.startQuest(parentID)
sm.dispose() |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
return se... | class Treenode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def sorted_array_to_bst(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
return self.get_middle(nums)
def get_... |
# Ground station location
lat = 0.0
lon = 0.0
alt = 0
min_elevation = 5.0 # in degrees, in urban or heavily wooded areas, increase as appropriate
# Change this to false if you don't want the realtime receiver to plot anything
realtime_plotting = True | lat = 0.0
lon = 0.0
alt = 0
min_elevation = 5.0
realtime_plotting = True |
inc="docs/floatlib.inc"
f=open(inc,'r+')
data=f.readlines()
f.close()
d=[]
for i in data:
if not i.startswith(" ") and not i.startswith("#") and not i.startswith("."):
i=i.split(';')[0]
i=i.split('=')[0]
i=i.strip()
if len(i)!=0:
d+=[': .db "'+i.upper()+',0" \ .dw '+i+'\n']
d=sorte... | inc = 'docs/floatlib.inc'
f = open(inc, 'r+')
data = f.readlines()
f.close()
d = []
for i in data:
if not i.startswith(' ') and (not i.startswith('#')) and (not i.startswith('.')):
i = i.split(';')[0]
i = i.split('=')[0]
i = i.strip()
if len(i) != 0:
d += [': .db "' + i.u... |
# General
TITLE = "Home Control"
# Security config
PASSWORD = "1234"
SECRET = "81dc9bdb52d04dc20036dbd8313ed055"
# Server config
HOST = "0.0.0.0"
PORT = 8000
DEBUG = False
# Switch list
SWITCHES = [
{
"name": "Room",
"system": 8,
"device": 1,
"icon": "ion-ios-lightbulb",
},
... | title = 'Home Control'
password = '1234'
secret = '81dc9bdb52d04dc20036dbd8313ed055'
host = '0.0.0.0'
port = 8000
debug = False
switches = [{'name': 'Room', 'system': 8, 'device': 1, 'icon': 'ion-ios-lightbulb'}, {'name': 'Desk', 'system': 16, 'device': 2, 'icon': 'ion-ios-lightbulb'}, {'name': 'Bed', 'system': 8, 'dev... |
# Question 1.
# Function to print username
def hello_name(user_name):
print(f"hello_{user_name}!")
hello_name('Shakti')
# Question 2.
# Function to odd numbers from 1-100
def first_odds():
num = 0
while(num<100):
num += 1
if(num % 2 != 0):
print(num)
else:
c... | def hello_name(user_name):
print(f'hello_{user_name}!')
hello_name('Shakti')
def first_odds():
num = 0
while num < 100:
num += 1
if num % 2 != 0:
print(num)
else:
continue
print(first_odds())
def max_num_in_list(a_list):
max_num = 0
for num in a_list... |
"""Functions that accept either a numpy array or a dask array, and return
another of the matching type.
Typyically invoked through ``xarray.apply_ufunc(dask='allowed').
"""
| """Functions that accept either a numpy array or a dask array, and return
another of the matching type.
Typyically invoked through ``xarray.apply_ufunc(dask='allowed').
""" |
################################
# #
# James Bachelder #
# CWCT - Python #
# M01 Programming Assignment 2 #
# 18 June 2021 #
# #
################################
print('Guido van Rossum')
print('20 February 1991')
pr... | print('Guido van Rossum')
print('20 February 1991')
print('Benevolent dictator for life') |
# Where memories will be temporarily kept.
#SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/staticfuzz.db'
# Database for memories.
#
# Use a sqlite database file on disk:
#
# SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/staticfuzz.db'
#
# Use sqlite memory database (never touches disk):
SQLALCHEMY_DATABASE_URI = 'sqlite:... | sqlalchemy_database_uri = 'sqlite:///:memory:'
port = 5000
debug = True
secret_key = 'BETTER CHANGE ME'
first_message = u'scream into the void'
thumb_max_height = 360
thumb_max_width = 360
min_colors = 2
max_colors = 10
sleep_rate = 0.2
retry_time_ms = 3000
whisper_secret = 'lain'
max_characters = 140
notification_soun... |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/test_nbdev.ipynb (unless otherwise specified).
__all__ = ['test_nbdev_func']
# Cell
def test_nbdev_func():
return 42 | __all__ = ['test_nbdev_func']
def test_nbdev_func():
return 42 |
"""
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
"""
class Solution():
def missingNumber(self, nums: list):
summ = sum(nums)
n = len(nums)
arithmetic_sum = int(n * (n + 1) / 2)
return arithmetic_sum - summ
... | """
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
"""
class Solution:
def missing_number(self, nums: list):
summ = sum(nums)
n = len(nums)
arithmetic_sum = int(n * (n + 1) / 2)
return arithmetic_sum - summ
... |
"""
URL: https://codeforces.com/problemset/problem/1339/A
Author: Safiul Kabir [safiulanik at gmail.com]
Tags: brute force, db, implementation, math, *900
"""
t = int(input())
for _ in range(t):
print(input())
| """
URL: https://codeforces.com/problemset/problem/1339/A
Author: Safiul Kabir [safiulanik at gmail.com]
Tags: brute force, db, implementation, math, *900
"""
t = int(input())
for _ in range(t):
print(input()) |
__all__ = ["slice"]
def slice(d, keys):
"""return dictionary with given keys"""
result = dict()
for k in keys:
if k in d:
result[k] = d[k]
return result
| __all__ = ['slice']
def slice(d, keys):
"""return dictionary with given keys"""
result = dict()
for k in keys:
if k in d:
result[k] = d[k]
return result |
class Shopping:
def __init__(self, shop):
self.shop = shop
self.cart = {}
def add_cart(self, item, quantity):
if item in self.cart:
self.cart[item] += quantity
else:
self.cart[item] = quantity
def remove_cart(self, item, quantity):
if item in self.cart:
self.cart[item] -= quantity
if self.c... | class Shopping:
def __init__(self, shop):
self.shop = shop
self.cart = {}
def add_cart(self, item, quantity):
if item in self.cart:
self.cart[item] += quantity
else:
self.cart[item] = quantity
def remove_cart(self, item, quantity):
if item i... |
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... |
# -*- coding: utf-8 -*-
__all__ = [
"contact_us",
"contact_us_thank_you",
"feedback",
"landing",
"how_to_set_up_in_the_uk",
"how_we_help_you_expand",
"hpo",
"hpo_contact_us",
"hpo_contact_us_thank_you",
"pixels",
"uk_setup_guide_pages",
]
| __all__ = ['contact_us', 'contact_us_thank_you', 'feedback', 'landing', 'how_to_set_up_in_the_uk', 'how_we_help_you_expand', 'hpo', 'hpo_contact_us', 'hpo_contact_us_thank_you', 'pixels', 'uk_setup_guide_pages'] |
#!/usr/bin/python3
""" 1-safe_print_integer """
def safe_print_list_integers(my_list=[], _x=0):
""" safe_print_list_integers """
counter = 0
for i in range(_x):
try:
print("{:d}".format(my_list[i]), end="")
counter += 1
except (ValueError, TypeError):
... | """ 1-safe_print_integer """
def safe_print_list_integers(my_list=[], _x=0):
""" safe_print_list_integers """
counter = 0
for i in range(_x):
try:
print('{:d}'.format(my_list[i]), end='')
counter += 1
except (ValueError, TypeError):
continue
print()
... |
a=0
while a!=2002:
a=int(input())
if a== 2002:
print('Acesso Permitido')
else:
print('Senha Invalida')
| a = 0
while a != 2002:
a = int(input())
if a == 2002:
print('Acesso Permitido')
else:
print('Senha Invalida') |
# -*- coding: utf-8 -*-
# @Time : 2018/5/23 20:53
# @Author : xiaoke
# @Email : 976249817@qq.com
# @File : my_test.py
print(range(1))
for i in range(1):
print(i)
| print(range(1))
for i in range(1):
print(i) |
model = dict(
type='StaticUnconditionalGAN',
generator=dict(type='WGANGPGenerator', noise_size=128, out_scale=128),
discriminator=dict(
type='WGANGPDiscriminator',
in_channel=3,
in_scale=128,
conv_module_cfg=dict(
conv_cfg=None,
kernel_size=3,
... | model = dict(type='StaticUnconditionalGAN', generator=dict(type='WGANGPGenerator', noise_size=128, out_scale=128), discriminator=dict(type='WGANGPDiscriminator', in_channel=3, in_scale=128, conv_module_cfg=dict(conv_cfg=None, kernel_size=3, stride=1, padding=1, bias=True, act_cfg=dict(type='LeakyReLU', negative_slope=0... |
class EndUploadEvent(object):
"""Event dispatched when an upload starts"""
def __init__(self, filepath, uploaded_files, files_to_upload):
"""
Constructor
:param str filepath: file uploaded
:param int uploaded_files: total files uploaded count
:param int files_to_upload:... | class Enduploadevent(object):
"""Event dispatched when an upload starts"""
def __init__(self, filepath, uploaded_files, files_to_upload):
"""
Constructor
:param str filepath: file uploaded
:param int uploaded_files: total files uploaded count
:param int files_to_upload:... |
# not yet finished
N = int(input())
input()
for _ in range(int(input())):
A, F = int(input()), int(input())
try:
input()
except EOFError:
pass
| n = int(input())
input()
for _ in range(int(input())):
(a, f) = (int(input()), int(input()))
try:
input()
except EOFError:
pass |
def minion_game(string):
# your code goes here
vowels = "AEIOU"
kevsc = 0
stusc = 0
for i in range(len(string)):
if string[i] in vowels:
kevsc += (len(string) - i)
else:
stusc += (len(string) - i)
if kevsc > stusc:
print("Kevin", k... | def minion_game(string):
vowels = 'AEIOU'
kevsc = 0
stusc = 0
for i in range(len(string)):
if string[i] in vowels:
kevsc += len(string) - i
else:
stusc += len(string) - i
if kevsc > stusc:
print('Kevin', kevsc)
elif kevsc < stusc:
print('St... |
input = """
%This is an example where we can not eliminate the duplicates of the rules.
%#maxint=8.
p(X) | r(X) :- q(X,Y), q(A,B), s(X,A), s(Y,B).
q(1,3).
q(2,4).
q(2,7).
q(3,8).
q(3,5).
q(1,6).
s(0,1).
s(1,2).
s(2,3).
s(3,4).
s(4,5).
s(5,6).
s(6,7).
s(7,8).
"""
output = """
%This is an exampl... | input = '\n%This is an example where we can not eliminate the duplicates of the rules.\n\n%#maxint=8.\n \np(X) | r(X) :- q(X,Y), q(A,B), s(X,A), s(Y,B).\n\nq(1,3).\nq(2,4).\nq(2,7).\nq(3,8).\nq(3,5).\nq(1,6).\n\ns(0,1).\ns(1,2).\ns(2,3).\ns(3,4).\ns(4,5).\ns(5,6).\ns(6,7).\ns(7,8).\n'
output = '\n%This is an example wh... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = self.right = None
class Solution:
def isSymmetric(self, root):
def isSym(left, right):
if left is None or right is None:
return left == right
if left.val != right.val:
... | class Treenode:
def __init__(self, x):
self.val = x
self.left = self.right = None
class Solution:
def is_symmetric(self, root):
def is_sym(left, right):
if left is None or right is None:
return left == right
if left.val != right.val:
... |
ncases = int(input())
for _ in range(ncases):
X, Y, Z = map(int, input().split())
A = [X, Y]
B = [X, Z]
C = [Y, Z]
found = False
for a in A:
for b in B:
for c in C:
if X == max(a, b) and Y == max(a, c) and Z == max(b, c):
print("YES")
... | ncases = int(input())
for _ in range(ncases):
(x, y, z) = map(int, input().split())
a = [X, Y]
b = [X, Z]
c = [Y, Z]
found = False
for a in A:
for b in B:
for c in C:
if X == max(a, b) and Y == max(a, c) and (Z == max(b, c)):
print('YES')
... |
# lambda function is a different type function which does not have name
# and is only used to return values
# lambda functions are exclusively used to operate on inputs and return outputs
def add(x, y):
return x+y
print(add(5, 7))
# OR
def add_lambda(x, y): return x+y
print(add_lambda(10, 10))
# Real Usage... | def add(x, y):
return x + y
print(add(5, 7))
def add_lambda(x, y):
return x + y
print(add_lambda(10, 10))
def double(x):
return x * 2
seq = [1, 2, 3, 4, 5]
doubled = [double(x) for x in seq]
print(doubled)
doubled_lambda = list(map(lambda x: x * 2, seq))
print(doubled_lambda) |
def maximum(values):
large = None
for value in values:
if large is None or value > large:
large = value
return large
print(maximum([9,10,100])) | def maximum(values):
large = None
for value in values:
if large is None or value > large:
large = value
return large
print(maximum([9, 10, 100])) |
def save_txt(file):
saida = open('cache/data.txt','w')
for line in file:
saida.write(str(line.replace('\n',''))+'\n')
saida.close() | def save_txt(file):
saida = open('cache/data.txt', 'w')
for line in file:
saida.write(str(line.replace('\n', '')) + '\n')
saida.close() |
f = open("Q2/inputs.txt","r")
z = f.readlines()
c = d = 0
for i in z:
#print(i)
a,b = i.split()
if a == "forward":
c += int(b)
elif a == "down":
d += int(b)
else:
d -= int(b)
print(c*d)
c = d = 0
aim = 0
for i in z:
#print(i)
a,b = i.split()
if a == "forward":
... | f = open('Q2/inputs.txt', 'r')
z = f.readlines()
c = d = 0
for i in z:
(a, b) = i.split()
if a == 'forward':
c += int(b)
elif a == 'down':
d += int(b)
else:
d -= int(b)
print(c * d)
c = d = 0
aim = 0
for i in z:
(a, b) = i.split()
if a == 'forward':
c += int(b)
... |
#when we cretae a tuple , we normally assign values to it this is called packing a tuple
fruits=("apple","banana","cherry")
(green,yellow,red)= fruits
print(green)
print(yellow)
print(red)
#The number of variable must match the number of values in tuple if not , you must use an asterisk to collect the remeaing value ... | fruits = ('apple', 'banana', 'cherry')
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red) |
def solution(board: list, moves: list) -> int:
# board: 2d array
# moves: column
stack = []
answer = 0
row = len(board)
for m in moves:
for i in range(row):
if board[i][m-1]:
if not stack:
stack.append(board[i][m-1])
else:
... | def solution(board: list, moves: list) -> int:
stack = []
answer = 0
row = len(board)
for m in moves:
for i in range(row):
if board[i][m - 1]:
if not stack:
stack.append(board[i][m - 1])
elif stack[-1] == board[i][m - 1]:
... |
def method1(n: int, l: list) -> list:
n = 2
l = [i for i in range(10)] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
return l.remove(2) # [0, 1, 3, 4, 5, 6, 7, 8, 9]
def method2(n: int, l: list) -> list:
n = 2
l = [i for i in range(10)] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
return l.pop(0) # [1, 2, 3, 4, 5,... | def method1(n: int, l: list) -> list:
n = 2
l = [i for i in range(10)]
return l.remove(2)
def method2(n: int, l: list) -> list:
n = 2
l = [i for i in range(10)]
return l.pop(0)
if __name__ == '__main__':
'\n n = 2\n l = [i for i in range(10)] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n from... |
"""
The Natural Language Generator for hospital data. The generator will:
a) Determine an opening line about the data
b) Follow up by verbalizing some choices
c) If there are more than 2 choices, it will also show tabular data
d) If your highest rated option is no the closest, it will mention that fact
e) Make a lexica... | """
The Natural Language Generator for hospital data. The generator will:
a) Determine an opening line about the data
b) Follow up by verbalizing some choices
c) If there are more than 2 choices, it will also show tabular data
d) If your highest rated option is no the closest, it will mention that fact
e) Make a lexica... |
'''
The Vector class of Section 2.3.3 provides a constructor that takes an integer
d, and produces a d-dimensional vector with all coordinates equal to 0.
Another convenient form for creating a new vector would be to send the
constructor a parameter that is some iterable type representing a sequence
of numbers, and to... | """
The Vector class of Section 2.3.3 provides a constructor that takes an integer
d, and produces a d-dimensional vector with all coordinates equal to 0.
Another convenient form for creating a new vector would be to send the
constructor a parameter that is some iterable type representing a sequence
of numbers, and to... |
def sort(words):
# write your code here...
return
print(sort( ['hi', 'bye'] ))
print(sort( ['abc', 'def'] ))
print(sort( ['hi', 'bye', 'def', 'abc'] ))
print(sort( ['add', 'some', 'more', 'words', 'here!'] ))
| def sort(words):
return
print(sort(['hi', 'bye']))
print(sort(['abc', 'def']))
print(sort(['hi', 'bye', 'def', 'abc']))
print(sort(['add', 'some', 'more', 'words', 'here!'])) |
class CityScrapersLoggingPipeline(object):
"""
Dummy logging pipeline. Enabled by default, it reminds developers to
turn on some kind of backend storage pipeline.
"""
def process_item(self, item, spider):
spider.logger.warn(
'Processing {0}. Enable a database pipeline to save it... | class Cityscrapersloggingpipeline(object):
"""
Dummy logging pipeline. Enabled by default, it reminds developers to
turn on some kind of backend storage pipeline.
"""
def process_item(self, item, spider):
spider.logger.warn('Processing {0}. Enable a database pipeline to save items.'.format(... |
PATHS_TO_BACKUP = ['C:\\', 'd:\\'] #case sensetive
EXCLUDED_PATHS = ['C:\\Program Files (x86)', 'C:\\Program Files', 'C:\\Windows']
BACKUP_DESTINATION = 'PCBACKUP'
PROGRESS_INTERNALS = 1
DRIVE_SCAN_PAGE_SIZE = 100
WORKERS = 30
UPLOAD_RETRIES = 3
LOG_LEVEL = 'INFO' # DEBUG, INFO, ERROR
FULL_SYNC_EVERY = 14 * 24 ... | paths_to_backup = ['C:\\', 'd:\\']
excluded_paths = ['C:\\Program Files (x86)', 'C:\\Program Files', 'C:\\Windows']
backup_destination = 'PCBACKUP'
progress_internals = 1
drive_scan_page_size = 100
workers = 30
upload_retries = 3
log_level = 'INFO'
full_sync_every = 14 * 24 * 60 * 60
paths_to_backup = ['C:\\drive-backu... |
def main():
n = int(input())
vec = None
for _ in range(n):
current_vec = [int(x) for x in input().split()]
if vec == None:
vec = [0] * len(current_vec)
vec = [vec[i] + current_vec[i] for i in range(len(current_vec))]
print("NO") if set(vec) != set([0]) else print("... | def main():
n = int(input())
vec = None
for _ in range(n):
current_vec = [int(x) for x in input().split()]
if vec == None:
vec = [0] * len(current_vec)
vec = [vec[i] + current_vec[i] for i in range(len(current_vec))]
print('NO') if set(vec) != set([0]) else print('YES... |
def meia_noite(h, m, s):
ts=((h*60)*60)+(m*60)+s
r=ts-0
return r
h=int(input())
m=int(input())
s=int(input())
t=meia_noite(h, m,s)
def mensagem(msg):
print(msg)
def main():
mensagem(t)
if __name__=='__main__':
main() | def meia_noite(h, m, s):
ts = h * 60 * 60 + m * 60 + s
r = ts - 0
return r
h = int(input())
m = int(input())
s = int(input())
t = meia_noite(h, m, s)
def mensagem(msg):
print(msg)
def main():
mensagem(t)
if __name__ == '__main__':
main() |
def ciSono(parola,lettere):
i = 0
lunghezza = (len(parola))-1
while i < lunghezza:
a = parola[lunghezza]
if a in lettere:
return True
lunghezza = lunghezza-1
return False
def usaSolo(parola,lettere):
if ciSono(parola,lettere) == True:
if parola in le... | def ci_sono(parola, lettere):
i = 0
lunghezza = len(parola) - 1
while i < lunghezza:
a = parola[lunghezza]
if a in lettere:
return True
lunghezza = lunghezza - 1
return False
def usa_solo(parola, lettere):
if ci_sono(parola, lettere) == True:
if parol... |
def var_args(name, *args):
print(name)
print(args)
def var_args2(name, **kwargs):
print(name)
print(kwargs['description'], kwargs['feedback'])
var_args('Mark', 'loves python', None, True)
var_args2('Mark', description="loves python", feedback=None) | def var_args(name, *args):
print(name)
print(args)
def var_args2(name, **kwargs):
print(name)
print(kwargs['description'], kwargs['feedback'])
var_args('Mark', 'loves python', None, True)
var_args2('Mark', description='loves python', feedback=None) |
'''Take the following Python code that stores a string:
str = 'X-DSPAM-Confidence: 0.8475 '
Use "find" and string slicing to extract the portion of the string after the colon character and then use the "float" function to convert the extracted string into a floating point number. '''
str = 'X-DSPAM-Confidence: 0.84... | """Take the following Python code that stores a string:
str = 'X-DSPAM-Confidence: 0.8475 '
Use "find" and string slicing to extract the portion of the string after the colon character and then use the "float" function to convert the extracted string into a floating point number. """
str = 'X-DSPAM-Confidence: 0.847... |
def main():
ran = range(3)
for i in ran:
path = 'class'+str(i)+'/'
f = open(path+'word.db','w')
f.close()
f = open('dictionary','w')
f.close()
f = open('dictionary2','w')
f.close()
if __name__=='__main__':
main()
| def main():
ran = range(3)
for i in ran:
path = 'class' + str(i) + '/'
f = open(path + 'word.db', 'w')
f.close()
f = open('dictionary', 'w')
f.close()
f = open('dictionary2', 'w')
f.close()
if __name__ == '__main__':
main() |
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'test_app',
'product_name': 'Test App',
'type': 'executable',
'mac_bundle': 1,
'sources': [
... | {'targets': [{'target_name': 'test_app', 'product_name': 'Test App', 'type': 'executable', 'mac_bundle': 1, 'sources': ['main.c'], 'xcode_settings': {'INFOPLIST_FILE': 'TestApp-Info.plist'}}, {'target_name': 'test_app_postbuilds', 'product_name': 'Test App 2', 'type': 'executable', 'mac_bundle': 1, 'sources': ['main.c'... |
# This file is part of Project Deity.
# Copyright 2020-2021, Frostflake (L.A.)
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights... | equippable_item_types = ['Accessory', 'Helmet', 'Ring', 'Weapon', 'Armor', 'Shield', 'Gloves', 'Legs', 'Boots']
async def equip_item(cursor, follower_id, slot_num):
cursor.execute('SELECT item_id\n FROM "project-deity".follower_inventories\n WHERE follower_id = %s\n ... |
#
# PySNMP MIB module FOUNDRY-MAC-VLAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FOUNDRY-MAC-VLAN-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:01:17 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_size_constraint, constraints_union, value_range_constraint, constraints_intersection) ... |
def gridSearch(G, P):
p_h, p_w = len(P), len(P[0])
search_h, search_w = len(G) - p_h + 1, len(G[0]) - p_w + 1
nrow_match = 0
for i in range(search_h):
for j in range(search_w):
if G[i][j:j+p_w] == P[0]:
nrow_match += 1
# dfs
for m in r... | def grid_search(G, P):
(p_h, p_w) = (len(P), len(P[0]))
(search_h, search_w) = (len(G) - p_h + 1, len(G[0]) - p_w + 1)
nrow_match = 0
for i in range(search_h):
for j in range(search_w):
if G[i][j:j + p_w] == P[0]:
nrow_match += 1
for m in range(1, p_h)... |
# Query to join weather to call records by date columns
query = """
SELECT *
FROM hpd311calls
JOIN weather
ON hpd311calls.created_date = weather.date;
"""
# Create data frame of joined tables
calls_with_weather = pd.read_sql(query, engine)
# View the data frame to make sure all columns were joined
print(calls... | query = '\nSELECT * \n FROM hpd311calls\n JOIN weather \n ON hpd311calls.created_date = weather.date;\n'
calls_with_weather = pd.read_sql(query, engine)
print(calls_with_weather.head())
"\n<script.py> output:\n unique_key created_date agency complaint_type incident_zip ... prcp snow tavg tmax tmin\n 0 38... |
def create_matrix(size):
return [input().split() for line in range(size)]
def find_miner_start_position(matrix, size):
for r in range(size):
for c in range(size):
if matrix[r][c] == "s":
return r, c
def find_total_coal(matrix):
result = 0
for r in range(size):
... | def create_matrix(size):
return [input().split() for line in range(size)]
def find_miner_start_position(matrix, size):
for r in range(size):
for c in range(size):
if matrix[r][c] == 's':
return (r, c)
def find_total_coal(matrix):
result = 0
for r in range(size):
... |
## Function 3 - multiplying two numbers
## 8 kyu
## https://www.codewars.com/kata/523b66342d0c301ae400003b
def multiply(x,y):
return x * y | def multiply(x, y):
return x * y |
# special websocket message types used for managing the connection
# corresponds to constants at the top of websockets.js
HELLO_TYPE = 'HELLO'
GOT_HELLO_TYPE = 'GOT_HELLO'
PING_TYPE = 'PING'
PING_RESPONSE_TYPE = 'PING'
RECONNECT_TYPE = 'RECONNECT'
# use the value in this json field in the message to pick an
# on_VALU... | hello_type = 'HELLO'
got_hello_type = 'GOT_HELLO'
ping_type = 'PING'
ping_response_type = 'PING'
reconnect_type = 'RECONNECT'
routing_key = 'type' |
#----------* CHALLENGE 40 *----------
#Ask for a number below 50 and then count down from 50 to that number, making sure you show the number they entered in the output
num = int(input("Enter a number below 50: "))
for i in range(50,num-1,-1):
print(i) | num = int(input('Enter a number below 50: '))
for i in range(50, num - 1, -1):
print(i) |
class Solution(object):
def wiggleSort(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
nums.sort()
tmp, length = nums[:], len(nums)
cursor = length / 2 + length % 2
i, k = cursor - 1, 0
... | class Solution(object):
def wiggle_sort(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
nums.sort()
(tmp, length) = (nums[:], len(nums))
cursor = length / 2 + length % 2
(i, k) = (cursor - ... |
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
DEPS = [
'chromium',
'chromium_tests',
'depot_tools/tryserver',
'recipe_engine/platform',
'recipe_engine/properties',
'test_results',... | deps = ['chromium', 'chromium_tests', 'depot_tools/tryserver', 'recipe_engine/platform', 'recipe_engine/properties', 'test_results']
def run_steps(api):
api.chromium.set_config('chromium')
api.test_results.set_config('public_server')
test_runner = api.chromium_tests.create_test_runner(tests=[api.chromium_t... |
dp = [[0 for _ in range(101)] for _ in range(101)]
def solve(n, m):
if dp[n][m]: return dp[n][m]
if m==0 or n==m: return 1
dp[n][m]=solve(n-1, m-1)+solve(n-1, m)
return dp[n][m]
n, m=map(int, input().split())
print(solve(n, m)) | dp = [[0 for _ in range(101)] for _ in range(101)]
def solve(n, m):
if dp[n][m]:
return dp[n][m]
if m == 0 or n == m:
return 1
dp[n][m] = solve(n - 1, m - 1) + solve(n - 1, m)
return dp[n][m]
(n, m) = map(int, input().split())
print(solve(n, m)) |
def test_captcha(app, start):
app.account.captcha_off()
def test_new_account(app):
link = app.account.find_link_for_create_account()
app.account.go_to_create_account_page(link)
user = app.account.create_account()
app.account.account_has_been_created()
app.account.logout()
app.account.login... | def test_captcha(app, start):
app.account.captcha_off()
def test_new_account(app):
link = app.account.find_link_for_create_account()
app.account.go_to_create_account_page(link)
user = app.account.create_account()
app.account.account_has_been_created()
app.account.logout()
app.account.login(... |
# SiteTool
# 2019
APP_VERSION = '0.1.0'
| app_version = '0.1.0' |
"""
Find the sum of all left leaves in a given binary tree.
Example:
3
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# ... | """
Find the sum of all left leaves in a given binary tree.
Example:
3
/ 9 20
/ 15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
"""
class Solution:
def sum_of_left_leaves(self, root):
"""
:type root: TreeNode
:rtype: ... |
load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies")
load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies")
load("@com_google_protobuf//:protobuf_deps.bzl", "protobuf_deps")
def buildifier_deps_deps():
go_rules_dependencies()
go_register_toolchains()
gazelle_depend... | load('@io_bazel_rules_go//go:deps.bzl', 'go_register_toolchains', 'go_rules_dependencies')
load('@bazel_gazelle//:deps.bzl', 'gazelle_dependencies')
load('@com_google_protobuf//:protobuf_deps.bzl', 'protobuf_deps')
def buildifier_deps_deps():
go_rules_dependencies()
go_register_toolchains()
gazelle_depende... |
"""
Implementation of BOWSR paper
Zuo, Yunxing, et al.
"Accelerating Materials Discovery with Bayesian Optimization and Graph Deep Learning."
arXiv preprint arXiv:2104.10242 (2021).
"""
| """
Implementation of BOWSR paper
Zuo, Yunxing, et al.
"Accelerating Materials Discovery with Bayesian Optimization and Graph Deep Learning."
arXiv preprint arXiv:2104.10242 (2021).
""" |
#Device Source for vector division
kernel_code_div = """
__global__ void kernel(float *d, float *a, float *b)
{
int tid = blockIdx.x * blockDim.x + threadIdx.x;
d[tid] = a[tid] / b[tid];
}
""" | kernel_code_div = '\n\t\t__global__ void kernel(float *d, float *a, float *b)\n\t{\n\t\t int tid = blockIdx.x * blockDim.x + threadIdx.x;\n\n\t\t d[tid] = a[tid] / b[tid];\n\t}\n' |
year = int(input())
is_hapyy_year = False
while not is_hapyy_year:
year += 1
str_year = str(year)
set_year = set(str_year)
if len(str_year) == len(set_year):
is_hapyy_year = True
print(year)
| year = int(input())
is_hapyy_year = False
while not is_hapyy_year:
year += 1
str_year = str(year)
set_year = set(str_year)
if len(str_year) == len(set_year):
is_hapyy_year = True
print(year) |
class SDL_SubSystem:
SDL_INIT_TIMER = 1
SDL_INIT_AUDIO = 16
SDL_INIT_VIDEO = 32
SDL_INIT_JOYSTICK = 512
SDL_INIT_HAPTIC = 4096
SDL_INIT_GAMECONTROLLER = 8192
SDL_INIT_EVENTS = 16384
SDL_INIT_EVERYTHING = 6201
class SDL_EventType:
"""SDL EventType.
See: https://wiki.libsdl.org/... | class Sdl_Subsystem:
sdl_init_timer = 1
sdl_init_audio = 16
sdl_init_video = 32
sdl_init_joystick = 512
sdl_init_haptic = 4096
sdl_init_gamecontroller = 8192
sdl_init_events = 16384
sdl_init_everything = 6201
class Sdl_Eventtype:
"""SDL EventType.
See: https://wiki.libsdl.org/S... |
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
len_ = 0
temp_list = []
for ch in s:
if ch in temp_list:
print(ch)
len_ = max(len_, len(temp_list))
temp_list = temp_list[temp_list.index(ch)+1:]
pri... | class Solution:
def length_of_longest_substring(self, s: str) -> int:
len_ = 0
temp_list = []
for ch in s:
if ch in temp_list:
print(ch)
len_ = max(len_, len(temp_list))
temp_list = temp_list[temp_list.index(ch) + 1:]
... |
geral = list()
nomepeso = list()
maiorpeso = list()
while True:
nomepeso.append(str(input('Nome: ')))
nomepeso.append(int(input('Peso: ')))
geral.append(nomepeso[:])
nomepeso.clear()
sn = str(input('Deseja continuar? [S/N] '))
if sn in 'Nn':
break
for c in geral:
maiorpeso.append(c[1... | geral = list()
nomepeso = list()
maiorpeso = list()
while True:
nomepeso.append(str(input('Nome: ')))
nomepeso.append(int(input('Peso: ')))
geral.append(nomepeso[:])
nomepeso.clear()
sn = str(input('Deseja continuar? [S/N] '))
if sn in 'Nn':
break
for c in geral:
maiorpeso.append(c[1... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
test=float('inf')
print('test>1',test>1)
print('test>10',test>10)
print('test>10',test>100)
# In[7]:
#To represent positive and negative infinity:
# positive infinity
p_inf = float("inf")
# negative infinity
n_inf = float("-inf")
print("n_inf",n_inf <-10)
# In[ ]:... | test = float('inf')
print('test>1', test > 1)
print('test>10', test > 10)
print('test>10', test > 100)
p_inf = float('inf')
n_inf = float('-inf')
print('n_inf', n_inf < -10) |
"""
Lab 6 for Loop and Range
"""
#3.1
for i in range(6):
if i !=3:
print(i)
#3.2
#result = 1
#for i in range(1,6):
# result = result * i
#print(result)
# #3.3
# result = 0
# for i in range(1,6):
# result = result + i
# print(result)
# #3.4
# result = 1
# for i in range(3,9):
# result =... | """
Lab 6 for Loop and Range
"""
for i in range(6):
if i != 3:
print(i)
my_tweet = {'favorite_count': 1138, 'lang': 'en', 'coordinates': (-75, 40), 'entities': {'hashtags': ['Preds', 'Pens', 'SingIntoSpring']}}
print(my_tweet['entities']['hashtags'])
result = 0
for hashtag in my_tweet['entities']['hashtags'... |
n = 1
c = 1
f = "-"
print(f"{f*10}INICIO | DIGITE UM NUMERO NEGATIVO PARA SAIR{f*10}")
while True:
n = int(input("Informe um valor para ver sua tabuada: "))
c = 1
if n > 0:
while n*11 != n*c:
print(f"{n}x{c}={n*c}")
c += 1
else:
break
print("FIM")
| n = 1
c = 1
f = '-'
print(f'{f * 10}INICIO | DIGITE UM NUMERO NEGATIVO PARA SAIR{f * 10}')
while True:
n = int(input('Informe um valor para ver sua tabuada: '))
c = 1
if n > 0:
while n * 11 != n * c:
print(f'{n}x{c}={n * c}')
c += 1
else:
break
print('FIM') |
def minimum2(L):
min_1 = L[0]
min_2 = L[1]
if min_1 < min_2:
min_1, min_2 = min_2, min_1
i = 0
while i < len(L):
if L[i] < min_1:
min_2, min_1 = min_1, L[i]
elif L[i] < min_2 and L[i] > min_1:
min_2 = L[i]
i += 1
return min_2
print(minimum2([3,2,5,7,2]))
| def minimum2(L):
min_1 = L[0]
min_2 = L[1]
if min_1 < min_2:
(min_1, min_2) = (min_2, min_1)
i = 0
while i < len(L):
if L[i] < min_1:
(min_2, min_1) = (min_1, L[i])
elif L[i] < min_2 and L[i] > min_1:
min_2 = L[i]
i += 1
return min_2
print(... |
TEST_NAME = "030-trackingreview"
BRANCH_NAME = [TEST_NAME + "-1",
TEST_NAME + "-2"]
UPSTREAM_NAME = [name + "-upstream"
for name in BRANCH_NAME]
SUMMARY = TEST_NAME
ORIGINAL_SHA1 = "37bfd1ee7d301b364d0a8c716e9bca36efd5d139"
REVIEWED_SHA1 = []
UPSTREAM_SHA1 = ["22afd9377add956e1e8d8dd6ef... | test_name = '030-trackingreview'
branch_name = [TEST_NAME + '-1', TEST_NAME + '-2']
upstream_name = [name + '-upstream' for name in BRANCH_NAME]
summary = TEST_NAME
original_sha1 = '37bfd1ee7d301b364d0a8c716e9bca36efd5d139'
reviewed_sha1 = []
upstream_sha1 = ['22afd9377add956e1e8d8dd6efa378fad9237532', '702c1b1a4043d88... |
def check_goldbach_for_num(n,primes_set) :
'''gets an even integer- n, and a set of primes- primes_set. Returns whether there're two primes which their sum is n'''
for prime in primes_set :
if ((p < n) and ((n - prime) in primes_set)):
return True
return False
| def check_goldbach_for_num(n, primes_set):
"""gets an even integer- n, and a set of primes- primes_set. Returns whether there're two primes which their sum is n"""
for prime in primes_set:
if p < n and n - prime in primes_set:
return True
return False |
#!/usr/bin/env python
#********************
# retroSpeak vocabulary
# retroSpeak is a Raspberry Pi controlled speech synthesizer using the vintage
# SP0256-AL2 chip, and MCP23S17 SPI controlled port expander.
#
# Vocabulary based on example wordlists in the Archer/Radioshack SP0256 datasheet
# with typos corrected and... | vocabulary = {'a': 'EY', 'alarm': 'AX LL AR MM', 'am': 'AE AE PA2 MM', 'and': 'AE AE NN1 PA2 DD1', 'april': 'EY PA3 PP RR2 IH IH LL', 'ate': 'EY PA3 TT2', 'august': 'AO AO PA2 GG2 AX SS PA3 TT1', 'b': 'BB2 IY', 'bathe': 'BB2 EY DH2', 'bather': 'BB2 EY DH2 ER1', 'bathing': 'BB2 EY DH2 IH NG', 'beer': 'BB2 YR', 'bread': ... |
def create_tables(cursor,fileName):
file = open(fileName)
sql = file.readline()
while sql:
cursor.execute(sql)
sql = file.readline()
file.close()
| def create_tables(cursor, fileName):
file = open(fileName)
sql = file.readline()
while sql:
cursor.execute(sql)
sql = file.readline()
file.close() |
# Date: 2020/11/05
# Author: Luis Marquez
# Description:
# ##
#
#
def square():
#DEFINING EPSILON (MARGIN OF ERROR)
epsilon = 0.01
#DEFINING STEP (HOW MUCH I CAN APPROXIMATE IN EACH STEP)
step = epsilon**2
#DEFINFING ANSWER
answer = 0.0
#DEFINING OBJECTIVE (TO CALCULATE... | def square():
epsilon = 0.01
step = epsilon ** 2
answer = 0.0
objective = int(input(f'\nType an integer number.\nNumber: '))
print(f'\n')
while abs(answer ** 2 - objective) >= epsilon and answer <= objective:
answer += step
if abs(answer ** 2 - objective) >= epsilon:
print(f"... |
"""
The idea here is to build a segment tree. Each node stores the left and right
endpoint of an interval and the sum of that interval. All of the leaves will store
elements of the array and each internal node will store sum of leaves under it.
Creating the tree takes O(n) time. Query and updates are bo... | """
The idea here is to build a segment tree. Each node stores the left and right
endpoint of an interval and the sum of that interval. All of the leaves will store
elements of the array and each internal node will store sum of leaves under it.
Creating the tree takes O(n) time. Query and updates are bo... |
#!/usr/bin/python3
with open('data') as f:
lines = f.readlines()
n = 0
for i in range(len(lines)-1):
if int(lines[i]) < int(lines[i+1]):
n += 1
print('python3, day 1, part 1 :', n)
| with open('data') as f:
lines = f.readlines()
n = 0
for i in range(len(lines) - 1):
if int(lines[i]) < int(lines[i + 1]):
n += 1
print('python3, day 1, part 1 :', n) |
height= float(input("Please Enter your height : "))
weight= int(input("Please Enter your weight : "))
BMI=weight/height ** 2
print("your BMI is : " + str(BMI)) | height = float(input('Please Enter your height : '))
weight = int(input('Please Enter your weight : '))
bmi = weight / height ** 2
print('your BMI is : ' + str(BMI)) |
# rin, kn_x, kn_y = input().split(), input().split(), input().split()
# def s(kn_t, axis):
# b_s = list(())
# for e_i, e_v in enumerate([int(a) for a in kn_t]):
# if e_i==0: b_s.append(e_v)
# elif e_i==len(kn_t)-1: b_s.append(int(rin[axis])-e_v)
# else: b_s.append(e_v-int(kn_t[e_i-... | (rin, kn_x, kn_y, areas) = ([int(a) for a in input().split()], [0], [0], list(()))
kn_x.extend([int(b) for b in input().split()])
kn_y.extend([int(c) for c in input().split()])
kn_x.append(rin[0])
kn_y.append(rin[1])
for ex in range(1, len(kn_x)):
for ey in range(1, len(kn_y)):
areas.append((kn_x[ex] - kn_x... |
#
# PySNMP MIB module HPN-ICF-MAC-INFORMATION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-MAC-INFORMATION-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:40:07 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_size_constraint, constraints_intersection, constraints_union, value_range_constraint) ... |
# Time: O(n)
# Space: O(h)
# Given a binary tree, find the leftmost value in the last row of the tree.
#
# Example 1:
# Input:
#
# 2
# / \
# 1 3
#
# Output:
# 1
# Example 2:
# Input:
#
# 1
# / \
# 2 3
# / / \
# 4 5 6
# /
# 7
#
# Output:
# 7
# Note: You may a... | class Solution(object):
def find_bottom_left_value(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def find_bottom_left_value_helper(root, curr_depth, max_depth, bottom_left_value):
if not root:
return (max_depth, bottom_left_value)
... |
# -*- coding:utf-8 -*-
# --------------------------------------------------------
# Copyright (C), 2016-2021, lizhe, All rights reserved
# --------------------------------------------------------
# @Name: constant.py
# @Author: lizhe
# @Created: 2021/11/18 - 22:08
# ------------------------------... | dlc = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 12: 9, 16: 10, 20: 11, 24: 12, 32: 13, 48: 14, 64: 15} |
# Fibonacci numbers
# 1, 1, 2, 3, 5, 8, 13, 21, ...
def fibonacci(limit):
nums = []
currnum = 0
nextnum = 1
while currnum < limit:
currnum, nextnum = nextnum, nextnum + currnum
nums.append(currnum)
return nums
print('via lists')
for n in fibonacci(100):
print(n, end=', ')
p... | def fibonacci(limit):
nums = []
currnum = 0
nextnum = 1
while currnum < limit:
(currnum, nextnum) = (nextnum, nextnum + currnum)
nums.append(currnum)
return nums
print('via lists')
for n in fibonacci(100):
print(n, end=', ')
print()
def fibonacci_co():
currnum = 0
nextnu... |
text = "X-DSPAM-Confidence: 0.8475"
fiveposition = text.find("5")
# print(fiveposition)
zeroposition = text.find("0")
# print(zeroposition)
number = text[zeroposition:]
print(float(number))
| text = 'X-DSPAM-Confidence: 0.8475'
fiveposition = text.find('5')
zeroposition = text.find('0')
number = text[zeroposition:]
print(float(number)) |
MORSE_ALPHABET = {
"A": ".-",
"B": "-...",
"C": "-.-.",
"D": "-..",
"E": ".",
"F": "..-.",
"G": "--.",
"H": "....",
"I": "..",
"J": ".---",
"K": "-.-",
"L": ".-..",
"M": "--",
"N": "-.",
"O": "---",
"P": ".--.",
"Q": "--.-",
"R": ".-.",
"S": ".... | morse_alphabet = {'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--',... |
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
"""
:type tokens: List[str]
:rtype: int
"""
stack = list()
operations = {'+', '-', '*', '/'}
for token in tokens:
if token in operations:
right = stack.pop()
... | class Solution:
def eval_rpn(self, tokens: List[str]) -> int:
"""
:type tokens: List[str]
:rtype: int
"""
stack = list()
operations = {'+', '-', '*', '/'}
for token in tokens:
if token in operations:
right = stack.pop()
... |
cookies = input("hoeveel koekjes wil je maken")
sugar = (1.5 / 48) * int(cookies)
butter = (1 / 48) * int(cookies)
flour = (2.75 / 48) * int(cookies)
print ("suiker: ", sugar, "\n", "boter: ", butter, "\n", "bloem: ", flour)
| cookies = input('hoeveel koekjes wil je maken')
sugar = 1.5 / 48 * int(cookies)
butter = 1 / 48 * int(cookies)
flour = 2.75 / 48 * int(cookies)
print('suiker: ', sugar, '\n', 'boter: ', butter, '\n', 'bloem: ', flour) |
class CaseData:
"""
A test case.
Attributes
----------
bond_factory : :class:`.BondFactory`
The bond factory to test.
atoms : :class:`tuple` of :class:`.Atom`
The atom to pass to :meth:`.BondFactory.get_bonds`.
bonds : :class:`tuple` of :class:`.Bond`
The bonds whi... | class Casedata:
"""
A test case.
Attributes
----------
bond_factory : :class:`.BondFactory`
The bond factory to test.
atoms : :class:`tuple` of :class:`.Atom`
The atom to pass to :meth:`.BondFactory.get_bonds`.
bonds : :class:`tuple` of :class:`.Bond`
The bonds whi... |
__author__ = "Sunrit Jana"
__email__ = "warriordefenderz@gmail.com"
__version__ = "0.1.0"
__license__ = "MIT License"
__copyright__ = "Copyright 2021 Sunrit Jana"
| __author__ = 'Sunrit Jana'
__email__ = 'warriordefenderz@gmail.com'
__version__ = '0.1.0'
__license__ = 'MIT License'
__copyright__ = 'Copyright 2021 Sunrit Jana' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.