content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
test = { 'name': 'q2a',
'points': 2,
'suites': [ { 'cases': [ {'code': '>>> # This test makes sure that fav_emojis has exactly 5 key-value pairs.;\n>>> len(fav_emojis) == 5\nTrue', 'hidden': False, 'locked': False},
{ 'code': '>>> # This test makes sure that fav_emoj... | test = {'name': 'q2a', 'points': 2, 'suites': [{'cases': [{'code': '>>> # This test makes sure that fav_emojis has exactly 5 key-value pairs.;\n>>> len(fav_emojis) == 5\nTrue', 'hidden': False, 'locked': False}, {'code': ">>> # This test makes sure that fav_emojis has the five necessary keys, and nothing else.;\n>>> so... |
class Floor:
def __init__(self, pos, height):
self.pos = pos
self.height = height
self.velocity = np.array([0,0,0])
self.actor = None | class Floor:
def __init__(self, pos, height):
self.pos = pos
self.height = height
self.velocity = np.array([0, 0, 0])
self.actor = None |
# -*- coding: utf-8 -*-
"""
* Project: udacity-fsnd-p4-conference-app
* Author name: Iraquitan Cordeiro Filho
* Author login: iraquitan
* File: settings
* Date: 3/23/16
* Time: 12:16 AM
"""
# Replace the following lines with client IDs obtained from the APIs
# Console or Cloud Console.
WEB_CLIENT_ID = 'your-web-c... | """
* Project: udacity-fsnd-p4-conference-app
* Author name: Iraquitan Cordeiro Filho
* Author login: iraquitan
* File: settings
* Date: 3/23/16
* Time: 12:16 AM
"""
web_client_id = 'your-web-client-id' |
'''
acts as a model class for freq_ingest table. all the values are set and
get using the setter and getter.
'''
class Freq_Ingest(object):
'''
acts as a model class for freq_ingest table. all the values are set and
get using the setter and getter.
'''
def __init__(self, team_name=None, ... | """
acts as a model class for freq_ingest table. all the values are set and
get using the setter and getter.
"""
class Freq_Ingest(object):
"""
acts as a model class for freq_ingest table. all the values are set and
get using the setter and getter.
"""
def __init__(self, team_name=None, fr... |
#eleghei an leipei kapoio symvolo >,<,=
def check_if__miss_symbol (filename):
#filename='LP02.LTX'
keeptheprevious_number_in_string=None
counter_of_line=0
i=0
with open(filename, "r") as f:
data = f.readlines()
for line in data:
... | def check_if__miss_symbol(filename):
keeptheprevious_number_in_string = None
counter_of_line = 0
i = 0
with open(filename, 'r') as f:
data = f.readlines()
for line in data:
counter_of_line = counter_of_line + 1
for letter in line:
if letter == '\n'... |
class Player:
def __init__(self, name: str, hp: int, mp: int):
self.name = name
self.hp = hp
self.mp = mp
self.skills = {}
self.guild = 'Unaffiliated'
def add_skill(self, skill_name, mana_cost):
if skill_name in self.skills.keys():
return 'S... | class Player:
def __init__(self, name: str, hp: int, mp: int):
self.name = name
self.hp = hp
self.mp = mp
self.skills = {}
self.guild = 'Unaffiliated'
def add_skill(self, skill_name, mana_cost):
if skill_name in self.skills.keys():
return 'Skill alre... |
class Compartment:
"""
A tuberculosis model compartment.
"""
SUSCEPTIBLE = "susceptible"
EARLY_LATENT = "early_latent"
LATE_LATENT = "late_latent"
INFECTIOUS = "infectious"
DETECTED = "detected"
ON_TREATMENT = "on_treatment"
RECOVERED = "recovered"
| class Compartment:
"""
A tuberculosis model compartment.
"""
susceptible = 'susceptible'
early_latent = 'early_latent'
late_latent = 'late_latent'
infectious = 'infectious'
detected = 'detected'
on_treatment = 'on_treatment'
recovered = 'recovered' |
"""
Copyright (c) 2018-2019 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... | """
Copyright (c) 2018-2019 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... |
class Solution(object):
def minDominoRotations(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: int
"""
# check there are enough same values
if len(A) != len(B):
return -1
countA = [0] * 7
countB = [0] * 7
same... | class Solution(object):
def min_domino_rotations(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: int
"""
if len(A) != len(B):
return -1
count_a = [0] * 7
count_b = [0] * 7
same = [0] * 7
for i in range(len(A)... |
class Source:
'''
source class to define how news sources look
'''
def __init__(self,id,name,language,country):
self.id=id
self.name=name
self.language=language
self.country=country
| class Source:
"""
source class to define how news sources look
"""
def __init__(self, id, name, language, country):
self.id = id
self.name = name
self.language = language
self.country = country |
# Added at : 2016.8.3
# Author : 7sDream
# Usage : Target point(contain point and image pixel info).
__all__ = ['Target']
class Target(object):
def __init__(self, y, x, fill, contrast, point):
self._y = y
self._x = x
self._fill = fill
self._contrast = contrast
self._p... | __all__ = ['Target']
class Target(object):
def __init__(self, y, x, fill, contrast, point):
self._y = y
self._x = x
self._fill = fill
self._contrast = contrast
self._point = point
self._hard_zero = False
@property
def fill(self):
return self._fill
... |
"""Defines a rule for runtime test targets."""
load("//tools:defs.bzl", "go_test", "loopback")
def runtime_test(
name,
lang,
image_repo = "gcr.io/gvisor-presubmit",
image_name = None,
blacklist_file = None,
shard_count = 50,
size = "enormous"):
"""Generates ... | """Defines a rule for runtime test targets."""
load('//tools:defs.bzl', 'go_test', 'loopback')
def runtime_test(name, lang, image_repo='gcr.io/gvisor-presubmit', image_name=None, blacklist_file=None, shard_count=50, size='enormous'):
"""Generates sh_test and blacklist test targets for a given runtime.
Args:
... |
_base_ = [
'../../_base_/models/r50.py',
'../../_base_/datasets/imagenet_sz224_4xbs64.py',
'../../_base_/default_runtime.py',
]
# model settings
model = dict(backbone=dict(norm_cfg=dict(type='SyncBN')))
# dataset settings
data = dict(
train=dict(
data_source=dict(
list_file='data/m... | _base_ = ['../../_base_/models/r50.py', '../../_base_/datasets/imagenet_sz224_4xbs64.py', '../../_base_/default_runtime.py']
model = dict(backbone=dict(norm_cfg=dict(type='SyncBN')))
data = dict(train=dict(data_source=dict(list_file='data/meta/ImageNet/train_labeled_1percent.txt')))
optimizer = dict(type='SGD', lr=0.1,... |
def generate_dict_vpn_ip_nexthops(nexthops):
"""
This function generates the block of configurtion for the VPN IP
nexthops that will be used in CLI template to generate VPN Feature
Template
"""
vipValue = []
for nexthop in nexthops:
vipValue.append(
{
"add... | def generate_dict_vpn_ip_nexthops(nexthops):
"""
This function generates the block of configurtion for the VPN IP
nexthops that will be used in CLI template to generate VPN Feature
Template
"""
vip_value = []
for nexthop in nexthops:
vipValue.append({'address': {'vipObjectType': 'obj... |
def twoCitySchedCost(costs):
result={'A':[],'B':[]}
costs.sort(key = lambda x: x[0]-x[1])
print(costs)
n=len(costs)//2
total = 0
for cost in costs[:n]:
total+=cost[0]
for cost in costs[n:]:
total+=cost[1]
return total
if __name__ =='__main__':
costs = ... | def two_city_sched_cost(costs):
result = {'A': [], 'B': []}
costs.sort(key=lambda x: x[0] - x[1])
print(costs)
n = len(costs) // 2
total = 0
for cost in costs[:n]:
total += cost[0]
for cost in costs[n:]:
total += cost[1]
return total
if __name__ == '__main__':
costs =... |
guests_count = int(input())
budget = int(input())
covert_price = guests_count * 20
if covert_price < budget:
money_left = budget - covert_price
fireworks_money = money_left * 0.4
donation_money = money_left - fireworks_money
print(f"Yes! {fireworks_money:.0f} lv are for fireworks and {donation_money:.0... | guests_count = int(input())
budget = int(input())
covert_price = guests_count * 20
if covert_price < budget:
money_left = budget - covert_price
fireworks_money = money_left * 0.4
donation_money = money_left - fireworks_money
print(f'Yes! {fireworks_money:.0f} lv are for fireworks and {donation_money:.0f... |
# this defines the CPU execution details
EXCEPTION_STACK = [ ]
def e_size():
'''get the size of the stack'''
return len(EXCEPTION_STACK)
def e_empty():
'''test whether the stack is empty'''
return not len(EXCEPTION_STACK)
def e_clear():
'''clear the stack'''
del EXCEPTION_STACK[:]
return... | exception_stack = []
def e_size():
"""get the size of the stack"""
return len(EXCEPTION_STACK)
def e_empty():
"""test whether the stack is empty"""
return not len(EXCEPTION_STACK)
def e_clear():
"""clear the stack"""
del EXCEPTION_STACK[:]
return
def e_push(e):
"""push a new exceptio... |
"""Internal API endpoint constant library.
_______ __ _______ __ __ __
| _ .----.-----.--.--.--.--| | _ | |_.----|__| |--.-----.
|. 1___| _| _ | | | | _ | 1___| _| _| | <| -__|
|. |___|__| |_____|________|_____|____ |____|__| |__|__|__|_____|
|: 1 | ... | """Internal API endpoint constant library.
_______ __ _______ __ __ __
| _ .----.-----.--.--.--.--| | _ | |_.----|__| |--.-----.
|. 1___| _| _ | | | | _ | 1___| _| _| | <| -__|
|. |___|__| |_____|________|_____|____ |____|__| |__|__|__|_____|
|: 1 | ... |
# Copyright 2015 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.
{
'targets': [
{
'target_name': 'alert_overlay',
'dependencies': [
'../../compiled_resources2.gyp:cr',
'../../compiled_resou... | {'targets': [{'target_name': 'alert_overlay', 'dependencies': ['../../compiled_resources2.gyp:cr', '../../compiled_resources2.gyp:util'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'array_data_model', 'dependencies': ['../../compiled_resources2.gyp:cr', '../compile... |
def compare(elem1, elem2):
JS("""
if (!elem1 && !elem2) {
return true;
} else if (!elem1 || !elem2) {
return false;
}
if (!elem1.isSameNode) {
return (elem1 == elem2);
}
return (elem1.isSameNode(elem2));
""")
def eventGetButton(evt):
JS("""
var button = evt.button... | def compare(elem1, elem2):
js('\n if (!elem1 && !elem2) {\n return true;\n } else if (!elem1 || !elem2) {\n return false;\n }\n\tif (!elem1.isSameNode) {\n\t return (elem1 == elem2);\n\t}\n return (elem1.isSameNode(elem2));\n ')
def event_get_button(evt):
js('\n var button = ... |
def string_strip(stringvalue: str):
return "".join(stringvalue.split())
def string_mask(stringvalue: str):
for char in stringvalue:
print(ord(char), end=' | ')
| def string_strip(stringvalue: str):
return ''.join(stringvalue.split())
def string_mask(stringvalue: str):
for char in stringvalue:
print(ord(char), end=' | ') |
reuse = False
weight_prefix = "model_"
FLIPXY = tf.constant([
[ 1., 0., 0., 0., 0.],
[ 0.,-1., 0., 0., 0.],
[ 0., 0.,-1., 0., 0.],
[ 0., 0., 0., 1., 0.],
[ 0., 0., 0., 0., 1.]] )
models_to_combine = [5, 8, 9, 11]
num_models = len(models_to_combine)
with tf.variable_scope("ENSA... | reuse = False
weight_prefix = 'model_'
flipxy = tf.constant([[1.0, 0.0, 0.0, 0.0, 0.0], [0.0, -1.0, 0.0, 0.0, 0.0], [0.0, 0.0, -1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0, 1.0]])
models_to_combine = [5, 8, 9, 11]
num_models = len(models_to_combine)
with tf.variable_scope('ENSAI', reuse=reuse):
c... |
names = [
'andy',
'sue',
'fred',
'jim',
'carol'
]
assert names[0] == 'andy'
assert names[4] == 'carol'
assert names[-1] == 'carol'
assert names[-2] == 'jim'
assert names[0:2] == ['andy', 'sue']
assert names[1:2] == ['sue']
assert names[3:] == ['jim', 'carol']
assert names[-2:] == ['jim', 'c... | names = ['andy', 'sue', 'fred', 'jim', 'carol']
assert names[0] == 'andy'
assert names[4] == 'carol'
assert names[-1] == 'carol'
assert names[-2] == 'jim'
assert names[0:2] == ['andy', 'sue']
assert names[1:2] == ['sue']
assert names[3:] == ['jim', 'carol']
assert names[-2:] == ['jim', 'carol']
assert names[::-1] == ['... |
class DotBakError(Exception):
"""Generic errors."""
pass
| class Dotbakerror(Exception):
"""Generic errors."""
pass |
# Copyright 2010-2021, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and ... | {'variables': {'relative_dir': 'base', 'gen_out_dir': '<(SHARED_INTERMEDIATE_DIR)/<(relative_dir)'}, 'conditions': [['OS=="win"', {'targets': [{'target_name': 'win_util_test_dll', 'type': 'shared_library', 'sources': ['win_util_test_dll.cc', 'win_util_test_dll.def'], 'dependencies': ['base.gyp:base']}]}]], 'targets': [... |
__all__ = [
"dictutils",
"forwarder",
"main",
"rulecollection",
"ruleengine",
"ruleitem",
"ruleset",
"template",
"templateprocessor",
"transform",
"utils"
] | __all__ = ['dictutils', 'forwarder', 'main', 'rulecollection', 'ruleengine', 'ruleitem', 'ruleset', 'template', 'templateprocessor', 'transform', 'utils'] |
# -*- coding: utf-8 -*-
# pygada_runtime's package version information
__version_major__ = "0.4"
__version__ = "{}a".format(__version_major__)
__version_long__ = "{}a".format(__version_major__)
__status__ = "Alpha"
__author__ = "Jeremy Morosi"
__author_email__ = "jeremymorosi@hotmail.com"
__url__ = "https://github.com... | __version_major__ = '0.4'
__version__ = '{}a'.format(__version_major__)
__version_long__ = '{}a'.format(__version_major__)
__status__ = 'Alpha'
__author__ = 'Jeremy Morosi'
__author_email__ = 'jeremymorosi@hotmail.com'
__url__ = 'https://github.com/gadalang/pygada-runtime' |
#
# Copyright (c) 2022 Pim van Pelt
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writi... | """ A vppcfg configuration module that validates Linux Control Plane (lcp) elements """
def get_lcps(yaml, interfaces=True, loopbacks=True, bridgedomains=True):
"""Returns a list of LCPs configured in the system. Optionally (de)select the different
types of LCP. Return an empty list if there are none of the gi... |
# -*- coding: utf-8 -*-
# Simple Bot (SimpBot)
# Copyright 2016-2017, Ismael Lugo (kwargs)
class channel:
def __init__(self, channel_name):
self.channel_name = channel_name
self.maxstatus = False
self.users = []
self.list = {}
def __iter__(self):
return iter(self.user... | class Channel:
def __init__(self, channel_name):
self.channel_name = channel_name
self.maxstatus = False
self.users = []
self.list = {}
def __iter__(self):
return iter(self.users)
def __len__(self):
return len(self.users)
def append(self, user):
... |
# -*- coding:utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Lic... | def split_to_array(string, sep=';'):
"""
Returns an array of strings separated by regex
"""
if string is not None:
return string.split(sep)
def replace_id_to_name(main_list, type_list, str_main_id, str_type_id, str_prop):
"""
Return list replacing type id to type name
"""
for it... |
# iam configuration
# HARDCODED !! CHANGE THIS !!
trainset_file = '/media/ncsr/bee4cbda-e313-4acf-9bc8-817a69ad98ae/IAM/set_split/trainset.txt'
testset_file = '/media/ncsr/bee4cbda-e313-4acf-9bc8-817a69ad98ae/IAM/set_split/testset.txt'
line_file = '/media/ncsr/bee4cbda-e313-4acf-9bc8-817a69ad98ae/IAM/ascii/lines.txt... | trainset_file = '/media/ncsr/bee4cbda-e313-4acf-9bc8-817a69ad98ae/IAM/set_split/trainset.txt'
testset_file = '/media/ncsr/bee4cbda-e313-4acf-9bc8-817a69ad98ae/IAM/set_split/testset.txt'
line_file = '/media/ncsr/bee4cbda-e313-4acf-9bc8-817a69ad98ae/IAM/ascii/lines.txt'
word_file = '/media/ncsr/bee4cbda-e313-4acf-9bc8-81... |
# Time: O(m * n)
# Space: O(m + n)
class Solution(object):
# @param dungeon, a list of lists of integers
# @return a integer
def calculateMinimumHP(self, dungeon):
DP = [float("inf") for _ in dungeon[0]]
DP[-1] = 1
for i in reversed(xrange(len(dungeon))):
DP... | class Solution(object):
def calculate_minimum_hp(self, dungeon):
dp = [float('inf') for _ in dungeon[0]]
DP[-1] = 1
for i in reversed(xrange(len(dungeon))):
DP[-1] = max(DP[-1] - dungeon[i][-1], 1)
for j in reversed(xrange(len(dungeon[i]) - 1)):
min_h... |
# Find the kth largest element in an unsorted array. This will be the kth
# largest element in sorted order, not the kth distinct element.
def kthLargestElement(nums, k):
nums.sort()
return nums[-k]
| def kth_largest_element(nums, k):
nums.sort()
return nums[-k] |
# (C) Datadog, Inc. 2020-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
CHECK_NAME = 'scylla'
NAMESPACE = 'scylla.'
# fmt: off
INSTANCE_METRIC_GROUP_MAP = {
'scylla.alien': [
'scylla.alien.receive_batch_queue_length',
'scylla.alien.total_received_messages'... | check_name = 'scylla'
namespace = 'scylla.'
instance_metric_group_map = {'scylla.alien': ['scylla.alien.receive_batch_queue_length', 'scylla.alien.total_received_messages', 'scylla.alien.total_sent_messages'], 'scylla.batchlog_manager': ['scylla.batchlog_manager.total_write_replay_attempts'], 'scylla.cache': ['scylla.c... |
# VIOLET: We do not have 'traceback' module
# import traceback
a = 2
b = 2 + 4 if a < 5 else 'boe'
assert b == 6
c = 2 + 4 if a > 5 else 'boe'
assert c == 'boe'
d = lambda x, y: x > y
assert d(5, 4)
e = lambda x: 1 if x else 0
assert e(True) == 1
assert e(False) == 0
try:
a = "aaaa" + \
"bbbb"
1/0
except ZeroDi... | a = 2
b = 2 + 4 if a < 5 else 'boe'
assert b == 6
c = 2 + 4 if a > 5 else 'boe'
assert c == 'boe'
d = lambda x, y: x > y
assert d(5, 4)
e = lambda x: 1 if x else 0
assert e(True) == 1
assert e(False) == 0
try:
a = 'aaaa' + 'bbbb'
1 / 0
except ZeroDivisionError as ex:
tb = ex.__traceback__
assert tb.tb_l... |
#credit: freecodecamp Youtube Channel
class Question:
def __init__ (self, prompt, answer):
self.prompt = prompt
self.answer = answer
| class Question:
def __init__(self, prompt, answer):
self.prompt = prompt
self.answer = answer |
# Copyright 2017 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | """Dummy test runner rule. Does not actually run tests."""
load('@build_bazel_rules_apple//apple/testing:apple_test_rules.bzl', 'AppleTestRunnerInfo')
def _dummy_test_runner_impl(ctx):
ctx.actions.expand_template(template=ctx.file._test_template, output=ctx.outputs.test_runner_template, substitutions={})
retur... |
"""Exceptions for WLED."""
class WLEDError(Exception):
"""Generic WLED exception."""
pass
class WLEDConnectionError(WLEDError):
"""WLED connection exception."""
pass
| """Exceptions for WLED."""
class Wlederror(Exception):
"""Generic WLED exception."""
pass
class Wledconnectionerror(WLEDError):
"""WLED connection exception."""
pass |
class Solution:
def maximum69Number (self, num: int) -> int:
num = [n for n in str(num)]
for i, n in enumerate(num):
if n == '6':
num[i] = '9'
break
return int(''.join(num))
| class Solution:
def maximum69_number(self, num: int) -> int:
num = [n for n in str(num)]
for (i, n) in enumerate(num):
if n == '6':
num[i] = '9'
break
return int(''.join(num)) |
"""
The database package of the Python Discord API.
This package contains the ORM models, migrations, and
other functionality related to database interop.
"""
| """
The database package of the Python Discord API.
This package contains the ORM models, migrations, and
other functionality related to database interop.
""" |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 26 20:46:03 2018
@author: daniel
Given an array of integers, find the first missing positive integer in linear
time and constant space. In other words, find the lowest positive integer that
does not exist in the array. The array can contain duplica... | """
Created on Wed Sep 26 20:46:03 2018
@author: daniel
Given an array of integers, find the first missing positive integer in linear
time and constant space. In other words, find the lowest positive integer that
does not exist in the array. The array can contain duplicates and negative
numbers as well.
For example,... |
# good example of using map
# from kata here
# https://www.codewars.com/kata/beginner-lost-without-a-map
def maps(a):
return list(map(lambda x: x * 2, a))
| def maps(a):
return list(map(lambda x: x * 2, a)) |
class Solution:
def flipEquiv(self, root1, root2):
"""
:type root1: TreeNode
:type root2: TreeNode
:rtype: bool
"""
if not root1 and not root2:
return True
if root1 and root2 and root1.val == root2.val:
ans1 = self.flipEquiv(root1.left... | class Solution:
def flip_equiv(self, root1, root2):
"""
:type root1: TreeNode
:type root2: TreeNode
:rtype: bool
"""
if not root1 and (not root2):
return True
if root1 and root2 and (root1.val == root2.val):
ans1 = self.flipEquiv(root1... |
h,w,*hw = open(0).read().split()
h=int(h)
w=int(w)
e=h+w-1
a=sum([l.count('#') for l in hw])
if e==a:
print('Possible')
else:
print('Impossible')
| (h, w, *hw) = open(0).read().split()
h = int(h)
w = int(w)
e = h + w - 1
a = sum([l.count('#') for l in hw])
if e == a:
print('Possible')
else:
print('Impossible') |
for i in range(1,11,1):
print(i)
# limit=int(input('Enter the limit:'))
# sum=0
# for i in range(1,limit+1,1):
# print(i)
# sum=sum+i
# print("sum of numbers:",sum)
# for i in range(11,10,1):
# if(i==5):
# continue
# print(i)
# else:
# print("Hello")
| for i in range(1, 11, 1):
print(i) |
for _ in range(int(input())):
n = int(input())
l = list(map(int,input().split()))
l.sort()
print(l[0]+l[1]) | for _ in range(int(input())):
n = int(input())
l = list(map(int, input().split()))
l.sort()
print(l[0] + l[1]) |
class InvalidUserId(Exception):
"""The userid does not meet the expected pattern."""
def __init__(self, user_id):
super().__init__(f"User id '{user_id}' is not valid")
class RealtimeMessageQueueError(Exception):
"""A message could not be sent to the realtime Rabbit queue."""
def __init__(sel... | class Invaliduserid(Exception):
"""The userid does not meet the expected pattern."""
def __init__(self, user_id):
super().__init__(f"User id '{user_id}' is not valid")
class Realtimemessagequeueerror(Exception):
"""A message could not be sent to the realtime Rabbit queue."""
def __init__(self... |
def kvadrat(x):
return x**2 + 1
def test_kvadrat():
assert kvadrat(2) == 4 | def kvadrat(x):
return x ** 2 + 1
def test_kvadrat():
assert kvadrat(2) == 4 |
#!/usr/bin/env python3
# terminal input: 1
def read_value(pc, prog, mode):
if mode == 0:
return prog[prog[pc]]
elif mode == 1:
return prog[pc]
else:
raise Exception("unknown mode: %d" % mode)
def write_value(pc, prog, mode, value):
if mode != 0:
raise Exception("only... | def read_value(pc, prog, mode):
if mode == 0:
return prog[prog[pc]]
elif mode == 1:
return prog[pc]
else:
raise exception('unknown mode: %d' % mode)
def write_value(pc, prog, mode, value):
if mode != 0:
raise exception('only position mode for writes: %d' % mode)
prog... |
fig, axs = plt.subplots(3, sharex=True, gridspec_kw={'hspace': 0})
axs[0].plot(ffp, 10*np.log10(Pxp))
axs[0].set_ylim([-80, 25])
axs[0].set_xlim([-0.2, 0.2])
axs[1].plot(ffn, 10*np.log10(Pxn))
axs[1].set_ylim([-80, 25])
axs[1].set_ylabel('Power Spectral Density (dB/Hz)')
axs[2].plot(ff_out, 10*np.log10(Px_out))
axs[... | (fig, axs) = plt.subplots(3, sharex=True, gridspec_kw={'hspace': 0})
axs[0].plot(ffp, 10 * np.log10(Pxp))
axs[0].set_ylim([-80, 25])
axs[0].set_xlim([-0.2, 0.2])
axs[1].plot(ffn, 10 * np.log10(Pxn))
axs[1].set_ylim([-80, 25])
axs[1].set_ylabel('Power Spectral Density (dB/Hz)')
axs[2].plot(ff_out, 10 * np.log10(Px_out))... |
class GeneralHistogramDataObject(object):
def __init__(self, feature_name, edges, bins):
self._feature_name = feature_name
self._edges = edges
self._bins = bins
def get_feature_name(self):
return self._feature_name
def get_edges(self):
"""String representation of H... | class Generalhistogramdataobject(object):
def __init__(self, feature_name, edges, bins):
self._feature_name = feature_name
self._edges = edges
self._bins = bins
def get_feature_name(self):
return self._feature_name
def get_edges(self):
"""String representation of H... |
# Given an encoded string, return it's decoded string.
# The encoding rule is: k[encoded_string], where the encoded_string
# inside the square brackets is being repeated exactly k times.
# Note that k is guaranteed to be a positive integer.
# You may assume that the input string is always valid; No extra white spaces... | def decode_string(s):
"""
:type s: str
:rtype: str
"""
stack = []
cur_num = 0
cur_string = ''
for c in s:
if c == '[':
stack.append((cur_string, cur_num))
cur_string = ''
cur_num = 0
elif c == ']':
(prev_string, num) = stack... |
#input vertices are defined here
inputs = [[22, 6], [20, 11], [18, 6], [16, 5], [15, 8], [20, 13], [18, 15],\
[15, 13], [13, 8], [9, 13], [3, 9], [6, 2], [6, 5], [11, 6], [16, 1]]
x_p = []
y_p = []
x = 0
y = 1
px = input("Enter point x: ")
py = input("Enter point y: ")
crossing = 0
ranges = range(0, len(inputs))
size =... | inputs = [[22, 6], [20, 11], [18, 6], [16, 5], [15, 8], [20, 13], [18, 15], [15, 13], [13, 8], [9, 13], [3, 9], [6, 2], [6, 5], [11, 6], [16, 1]]
x_p = []
y_p = []
x = 0
y = 1
px = input('Enter point x: ')
py = input('Enter point y: ')
crossing = 0
ranges = range(0, len(inputs))
size = len(inputs)
for i in ranges:
... |
a,b,x=map(int,input().split())
l=0
r=10**9+1
ans=10**9
while r-l>=2:
n1=l+(r-l)//2
n2=n1+1
p1=a*n1+b*len(str(n1))
p2=a*n2+b*len(str(n2))
if p1 <= x < p2:
ans=n1
break
elif p1 < x:
l=n1
else:
r=n1
if p1>x:
print(0)
else:
print(ans)
| (a, b, x) = map(int, input().split())
l = 0
r = 10 ** 9 + 1
ans = 10 ** 9
while r - l >= 2:
n1 = l + (r - l) // 2
n2 = n1 + 1
p1 = a * n1 + b * len(str(n1))
p2 = a * n2 + b * len(str(n2))
if p1 <= x < p2:
ans = n1
break
elif p1 < x:
l = n1
else:
r = n1
if p1 >... |
'''
An implementation of the
`Annotation store API <http://docs.annotatorjs.org/en/v1.2.x/storage.html.>`_
for `Annotator.js <http://annotatorjs.org/>`_.
''' | """
An implementation of the
`Annotation store API <http://docs.annotatorjs.org/en/v1.2.x/storage.html.>`_
for `Annotator.js <http://annotatorjs.org/>`_.
""" |
# GENERATED VERSION FILE
# TIME: Wed Aug 26 17:17:32 2020
__version__ = '0.0.0rc0+unknown'
short_version = '0.0.0rc0'
| __version__ = '0.0.0rc0+unknown'
short_version = '0.0.0rc0' |
class AllResponses:
def __init__(self, identifier, query_title, project_id=None, query_id=None):
self.id = identifier
self.scopus_abstract_retrieval = None
self.unpaywall_response = None
self.altmetric_response = None
self.scival_data = None
self.query_title = query_... | class Allresponses:
def __init__(self, identifier, query_title, project_id=None, query_id=None):
self.id = identifier
self.scopus_abstract_retrieval = None
self.unpaywall_response = None
self.altmetric_response = None
self.scival_data = None
self.query_title = query_... |
def rotate_index(arr, k, src_ind, src_num, count=0):
if count == len(arr):
return
des_ind = (src_ind + k) % len(arr)
des_num = arr[des_ind]
arr[des_ind] = src_num
rotate_index(arr, k, des_ind, des_num, count + 1)
def rotate_k(arr, k):
if k < 1:
return arr
start = 0
... | def rotate_index(arr, k, src_ind, src_num, count=0):
if count == len(arr):
return
des_ind = (src_ind + k) % len(arr)
des_num = arr[des_ind]
arr[des_ind] = src_num
rotate_index(arr, k, des_ind, des_num, count + 1)
def rotate_k(arr, k):
if k < 1:
return arr
start = 0
rotat... |
rcParams = {"figdir": "figures",
"usematplotlib": True,
"storeresults": False,
"cachedir": 'cache',
"chunk": {"defaultoptions": {
"echo": True,
"results": 'verbatim',
"chunk_type": "code",
"fig": True,
... | rc_params = {'figdir': 'figures', 'usematplotlib': True, 'storeresults': False, 'cachedir': 'cache', 'chunk': {'defaultoptions': {'echo': True, 'results': 'verbatim', 'chunk_type': 'code', 'fig': True, 'multi_fig': True, 'include': True, 'evaluate': True, 'caption': False, 'term': False, 'term_prompts': False, 'name': ... |
# Grace Foster
# ITP 100-01
# EXERCISE: 06
# ageclass.py
# ----------------------------------------------------------------
print("Age Classification program")
print("-----------------------------------------------")
age = 1
while age > 0:
age = float(input(f"Enter the age: "))
if age != 0:
if age ... | print('Age Classification program')
print('-----------------------------------------------')
age = 1
while age > 0:
age = float(input(f'Enter the age: '))
if age != 0:
if age <= 1:
print('This person is an Infant')
elif 2 <= age <= 13:
print('This person is a Child')
... |
class InadequateArgsCombination(Exception):
pass
| class Inadequateargscombination(Exception):
pass |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | __all__ = ('AdAssetPolicySummary', 'AdImageAsset', 'AdMediaBundleAsset', 'AdScheduleInfo', 'AdTextAsset', 'AdVideoAsset', 'AddressInfo', 'AffiliateLocationFeedItem', 'AgeRangeInfo', 'AppAdInfo', 'AppEngagementAdInfo', 'AppFeedItem', 'AppPaymentModelInfo', 'AssetInteractionTarget', 'BasicUserListInfo', 'BidModifierSimul... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def levelOrderBottom(self, root: TreeNode):
result, level = [], [root]
while root and level:
result.append([n.val for n... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def level_order_bottom(self, root: TreeNode):
(result, level) = ([], [root])
while root and level:
result.append([n.val for n in level])
level... |
# -*- coding: utf-8 -*-
# @Time : 2020/8/21 3:56 AM
# @Author : Yinghao Qin
# @Email : y.qin@hss18.qmul.ac.uk
# @File : utils6.py
# @Software: PyCharm
#######################################################################################
# 'utils6' is used to calculate the Levenshtein distance between the p... | def levenshtein_distance(a, b):
"""
The Levenshtein distance is a metric for measuring the difference between two sequences.
Calculates the Levenshtein distance between a and b.
:param a: the first sequence, such as [1, 2, 3, 4]
:param b: the second sequence
:return: Levenshtein distance
"""... |
# Demonstration of basic Python functions beginning on page 16
#
# Basic addition
x =44+11*4-6/11
print(x)
m = 60*24*7
print("Number of minutes in a week: ", m)
times = 2304811//47 #Integer division
remainder = 2304811 - (times*47)
print("Remainder of 2304811 divided by 47 without using modulo: ", remainder)
print(2... | x = 44 + 11 * 4 - 6 / 11
print(x)
m = 60 * 24 * 7
print('Number of minutes in a week: ', m)
times = 2304811 // 47
remainder = 2304811 - times * 47
print('Remainder of 2304811 divided by 47 without using modulo: ', remainder)
print(2304811 % 47)
print(5 == 4)
print(4 == 4)
print(True and (not 5 == 4))
x = -9
y = 1 / 2
v... |
class Bridge:
__ipaddress = None
__username = None
def __init__(self):
pass
def discover_bridges(self):
pass | class Bridge:
__ipaddress = None
__username = None
def __init__(self):
pass
def discover_bridges(self):
pass |
#
# PySNMP MIB module SONUS-REDUNDANCY-SERVICES-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SONUS-REDUNDANCY-SERVICES-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:02:05 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ve... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, single_value_constraint, constraints_intersection, value_size_constraint) ... |
def TSMC_Tech_Map(depth, width) -> dict:
'''
Currently returns the tech map for the single port SRAM, but we can
procedurally generate different tech maps
'''
ports = []
single_port = {
'data_in': 'D',
'addr': 'A',
'write_enable': 'WEB',
'cen': 'CEB',
'cl... | def tsmc__tech__map(depth, width) -> dict:
"""
Currently returns the tech map for the single port SRAM, but we can
procedurally generate different tech maps
"""
ports = []
single_port = {'data_in': 'D', 'addr': 'A', 'write_enable': 'WEB', 'cen': 'CEB', 'clk': 'CLK', 'data_out': 'Q', 'alt_sigs': ... |
# A simple while loop example
user_input = input('Hey how are you ')
while user_input != 'stop copying me':
print(user_input)
user_input = input()
else:
print('UGHH Fine') | user_input = input('Hey how are you ')
while user_input != 'stop copying me':
print(user_input)
user_input = input()
else:
print('UGHH Fine') |
class A:
pass
class B(A):
"""
This is B class comments
"""
def __init__(self) -> None:
super().__init__()
@classmethod
def get_class_name(cls):
return cls.__name__
if __name__ == "__main__":
def add_attr(self):
print("add_attr")
def add_static_attr():
... | class A:
pass
class B(A):
"""
This is B class comments
"""
def __init__(self) -> None:
super().__init__()
@classmethod
def get_class_name(cls):
return cls.__name__
if __name__ == '__main__':
def add_attr(self):
print('add_attr')
def add_static_attr():
... |
#
# PySNMP MIB module ALCATEL-IND1-ISIS-SPB-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALCATEL-IND1-ISIS-SPB-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:18:13 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... | (routing_ind1_isis_spb,) = mibBuilder.importSymbols('ALCATEL-IND1-BASE', 'routingIND1IsisSpb')
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, sin... |
#
# @lc app=leetcode.cn id=236 lang=python3
#
# [236] lowest-common-ancestor-of-a-binary-tree
#
None
# @lc code=end | None |
#!/usr/bin/env python3
CI_CONFIG = {
"build_config": [
{
"compiler": "clang-13",
"build_type": "",
"sanitizer": "",
"package_type": "deb",
"bundled": "bundled",
"splitted": "unsplitted",
"alien_pkgs": True,
"tid... | ci_config = {'build_config': [{'compiler': 'clang-13', 'build_type': '', 'sanitizer': '', 'package_type': 'deb', 'bundled': 'bundled', 'splitted': 'unsplitted', 'alien_pkgs': True, 'tidy': 'disable', 'with_coverage': False}, {'compiler': 'clang-13', 'build_type': '', 'sanitizer': '', 'package_type': 'performance', 'bun... |
# import pytest
class TestTime:
def test___str__(self): # synced
assert True
def test_shift(self): # synced
assert True
def test_to_isoformat(self): # synced
assert True
def test_to_format(self): # synced
assert True
def test_now(self): # synced
ass... | class Testtime:
def test___str__(self):
assert True
def test_shift(self):
assert True
def test_to_isoformat(self):
assert True
def test_to_format(self):
assert True
def test_now(self):
assert True
def test_from_time(self):
assert True
de... |
def main():
data = open("day9/input.txt", "r")
data = [int(line.strip()) for line in data]
answer = 0
for i in range(25, len(data)):
value = data[i]
found = False
spliced_data = data[i - 25 : i]
for num in spliced_data:
num2 = value - num
if num2 ... | def main():
data = open('day9/input.txt', 'r')
data = [int(line.strip()) for line in data]
answer = 0
for i in range(25, len(data)):
value = data[i]
found = False
spliced_data = data[i - 25:i]
for num in spliced_data:
num2 = value - num
if num2 in ... |
# Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
#
# Integers in each row are sorted from left to right.
# The first integer of each row is greater than the last integer of the previous row.
# For example,
#
# Consider the following matrix:
#
# [
# ... | class Solution(object):
def search_matrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
height = len(matrix)
if height == 0:
return False
width = len(matrix[0])
if width == 0:
... |
#
# PySNMP MIB module BSUCLK-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BSUCLK-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:41:36 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, 09:... | (bsu,) = mibBuilder.importSymbols('ANIROOT-MIB', 'bsu')
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, single_value_con... |
"""
Cut matrices by row or column and apply operations to them.
"""
class Cutter:
"""
Base class that pre-calculates cuts and can use them to
apply a function to the layout.
Each "cut" is a row or column, depending on the value of by_row.
The entries are iterated forward or backwards, depending ... | """
Cut matrices by row or column and apply operations to them.
"""
class Cutter:
"""
Base class that pre-calculates cuts and can use them to
apply a function to the layout.
Each "cut" is a row or column, depending on the value of by_row.
The entries are iterated forward or backwards, depending o... |
#!/usr/bin/env python3
"""SoloLearn > Code Coach > Pig Latin"""
english = input('Enter a phrase without punctuation: ').lower()
piglatin = ''
# NOT REQUIRED: Sanitize the string
common_punctuation = ('.', '?', '!', ',', ';', ':')
for punctuation in common_punctuation:
english = english.replace(punctuation, '')
#... | """SoloLearn > Code Coach > Pig Latin"""
english = input('Enter a phrase without punctuation: ').lower()
piglatin = ''
common_punctuation = ('.', '?', '!', ',', ';', ':')
for punctuation in common_punctuation:
english = english.replace(punctuation, '')
for word in english.split():
wordlen = len(word)
word =... |
#
# @lc app=leetcode id=557 lang=python3
#
# [557] Reverse Words in a String III
#
# https://leetcode.com/problems/reverse-words-in-a-string-iii/description/
#
# algorithms
# Easy (66.26%)
# Likes: 778
# Dislikes: 80
# Total Accepted: 166.2K
# Total Submissions: 248.5K
# Testcase Example: `"Let's take LeetCode c... | class Solution:
def reverse_words(self, s: str) -> str:
lst = s.split(' ')
return ' '.join([w[::-1] for w in lst]) |
dvs = []
for i in range(9):
dvs.append(int(input()))
for i in dvs:
for j in dvs:
if i != j and i + j == sum(dvs) - 100:
dvs.remove(i)
dvs.remove(j)
break
print(*dvs)
| dvs = []
for i in range(9):
dvs.append(int(input()))
for i in dvs:
for j in dvs:
if i != j and i + j == sum(dvs) - 100:
dvs.remove(i)
dvs.remove(j)
break
print(*dvs) |
def put(data,location):
f = open(location,"w")
for i in data:
f.write(i+"\n\n--------------====================--------------\n\n")
f.close()
| def put(data, location):
f = open(location, 'w')
for i in data:
f.write(i + '\n\n--------------====================--------------\n\n')
f.close() |
def main():
print(not 1)
if __name__ == "__main__":
main()
| def main():
print(not 1)
if __name__ == '__main__':
main() |
# """
# x = int(input("Enter 1st Number "))
# y = int(input("Enter 2nd Number "))
# z = int(input("Enter 3rd Number "))
# print("The sum is : " + str(x + y + z))
# """
name = "Hey There !!"
print(name.replace('ey', 'ii'))
print(name.count("Hey There!!"))
print(name.lower())
print(name.upper())
cars = ['Lamborghini... | name = 'Hey There !!'
print(name.replace('ey', 'ii'))
print(name.count('Hey There!!'))
print(name.lower())
print(name.upper())
cars = ['Lamborghini', 'Ferrari', 'BMW', 'Audi']
cars.insert(1, 'Mercedes')
print(cars)
cars.sort()
print(cars) |
#!/usr/bin/python3
magic = [0x47, 0xCD, 0x40, 0xC6, 0x7A, 0xD9, 0x45, 0xD9, 0x45, 0xAF, 0x2F, 0xAF, 0x50, 0xC0, 0x50, 0xFC]
x = 1
for i in magic:
print(chr(i ^ x), end = '')
x ^= 0x80
| magic = [71, 205, 64, 198, 122, 217, 69, 217, 69, 175, 47, 175, 80, 192, 80, 252]
x = 1
for i in magic:
print(chr(i ^ x), end='')
x ^= 128 |
class Suit:
"""Representation of a standard playing card suit."""
def __init__(self, name: str, color: str) -> None:
self.name = name
self.color = color
def __repr__(self) -> str:
return f"Suit({self.name}, {self.color})"
def __str__(self) -> str:
return f"{self.name}"... | class Suit:
"""Representation of a standard playing card suit."""
def __init__(self, name: str, color: str) -> None:
self.name = name
self.color = color
def __repr__(self) -> str:
return f'Suit({self.name}, {self.color})'
def __str__(self) -> str:
return f'{self.name}' |
DATA = [ '210.153.84.0/24',
'210.136.161.0/24',
'210.153.86.0/24',
'124.146.174.0/24',
'124.146.175.0/24',
'202.229.176.0/24',
'202.229.177.0/24',
'202.229.178.0/24']
| data = ['210.153.84.0/24', '210.136.161.0/24', '210.153.86.0/24', '124.146.174.0/24', '124.146.175.0/24', '202.229.176.0/24', '202.229.177.0/24', '202.229.178.0/24'] |
class Solution(object):
def fib(self, n):
"""
:type n: int
:rtype: int
"""
d = {}
def fibo_r(n):
if(n in d): return d[n]
if(n < 2):
res = n
else:
res = fibo_r(n-1) + fibo_r(n-2)
... | class Solution(object):
def fib(self, n):
"""
:type n: int
:rtype: int
"""
d = {}
def fibo_r(n):
if n in d:
return d[n]
if n < 2:
res = n
else:
res = fibo_r(n - 1) + fibo_r(n - 2)
... |
#------------------------------------------------------------------------------
# Copyright (c) 2013, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-------------------------------------------------... | class Nodevisitor(object):
""" A base class for implementing node visitors.
Subclasses should implement visitor methods using the naming scheme
'visit_<name>' where `<name>` is the type name of a given node.
"""
def __call__(self, node):
""" The main entry point of the visitor class.
... |
'''
In order to get the Learn credentials, they do not to open a case on behind the blackboard nor email developers@blackboard.com.
They need to go to developer.blackboard.com and register from there to grab the Learn credentials for their application, it is also imperative to remind them that they are creating an app... | """
In order to get the Learn credentials, they do not to open a case on behind the blackboard nor email developers@blackboard.com.
They need to go to developer.blackboard.com and register from there to grab the Learn credentials for their application, it is also imperative to remind them that they are creating an app... |
#!/usr/bin/env python
class Bee:
def __init__(self, bee_id, tag_id, length_tracked):
self.bee_id = bee_id
self.tag_id = tag_id
self.length_tracked = length_tracked
self.last_path_id = None
self.path_length = None
self.last_x = None
self.last_y = None
... | class Bee:
def __init__(self, bee_id, tag_id, length_tracked):
self.bee_id = bee_id
self.tag_id = tag_id
self.length_tracked = length_tracked
self.last_path_id = None
self.path_length = None
self.last_x = None
self.last_y = None
self.list_speeds = []
... |
good_ops = {'+': '-', '-': '+', '=<': '==', '>=': '==',
'==': '=/=', '=/=': '==', '<':'>', '>': '<'}
def count(ast):
if ast.expr_name == "binary_operator":
return 1 if ast.text in good_ops else 0
if ast.children:
return sum(map(count, ast.children))
return 0
def inverse(number,... | good_ops = {'+': '-', '-': '+', '=<': '==', '>=': '==', '==': '=/=', '=/=': '==', '<': '>', '>': '<'}
def count(ast):
if ast.expr_name == 'binary_operator':
return 1 if ast.text in good_ops else 0
if ast.children:
return sum(map(count, ast.children))
return 0
def inverse(number, ast, filen... |
'''
The MIT License(MIT)
Copyright(c) 2016 Copyleaks LTD (https://copyleaks.com)
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
... | """
The MIT License(MIT)
Copyright(c) 2016 Copyleaks LTD (https://copyleaks.com)
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
... |
"""
Estimated time
5 minutes
Level of difficulty
Very easy
Objectives
Familiarize the student with:
using the for loop;
reflecting real-life situations in computer code.
Scenario
Do you know what Mississippi is? Well, it's the name of one of the states and rivers in the United States. The Mississippi River is about ... | """
Estimated time
5 minutes
Level of difficulty
Very easy
Objectives
Familiarize the student with:
using the for loop;
reflecting real-life situations in computer code.
Scenario
Do you know what Mississippi is? Well, it's the name of one of the states and rivers in the United States. The Mississippi River is about ... |
#suma de dos digitos
print(1+2)
#multiplicacion de dos digitos
print (3*4)
#division de dos digitos
print(3/2)
#division estricta, sin decimales, de dos digitos
print(81//2)
#Potencia de un digito
print(3**2)
| print(1 + 2)
print(3 * 4)
print(3 / 2)
print(81 // 2)
print(3 ** 2) |
# This is the main chess game engine that implements the rules of the game
# and stores the state of the the chess board, including its pieces and moves
class Game_state():
def __init__(self):
"""
The chess board is an 8 X 8 dimensional array (Matrix of 8 rows and 8 columns )
... | class Game_State:
def __init__(self):
"""
The chess board is an 8 X 8 dimensional array (Matrix of 8 rows and 8 columns )
i.e a list of lists. Each element of the Matrix is a string of two characters
representing the chess pieces in the order "type" + "colou... |
class Player:
VERSION = "fuck"
def betRequest(self, game_state):
return 10000000
def showdown(self, game_state):
pass
| class Player:
version = 'fuck'
def bet_request(self, game_state):
return 10000000
def showdown(self, game_state):
pass |
class WL(object):
def __init__(self,data=None):
if data:
self.id = data['id']
self.title = data['title']
self.created_at = data['created_at']
def get_id(self):
return self.id
def get_title(self):
return self.title
def get_cre... | class Wl(object):
def __init__(self, data=None):
if data:
self.id = data['id']
self.title = data['title']
self.created_at = data['created_at']
def get_id(self):
return self.id
def get_title(self):
return self.title
def get_created_at(self):... |
# Title: Array Partition 1
# Link: https://leetcode.com/problems/array-partition-i/
class Solution:
def array_pair_sum(self, nums: list) -> int:
nums = sorted(nums)
s = 0
for i in range(0, len(nums), 2):
s += nums[i]
return s
def solution():
nums = [1,4,3,2]
... | class Solution:
def array_pair_sum(self, nums: list) -> int:
nums = sorted(nums)
s = 0
for i in range(0, len(nums), 2):
s += nums[i]
return s
def solution():
nums = [1, 4, 3, 2]
sol = solution()
return sol.array_pair_sum(nums)
def main():
print(solution... |
def get_user_response(question, valid_responses, error_message=None):
"""
Function to obtain input from the user.
:param question: string Question to ask user
:param valid_responses: list of valid responses to use in error catching
:param error_message: string Message to display if an exception occu... | def get_user_response(question, valid_responses, error_message=None):
"""
Function to obtain input from the user.
:param question: string Question to ask user
:param valid_responses: list of valid responses to use in error catching
:param error_message: string Message to display if an exception occu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.