content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def kubus(x):
return x * x * x
kubusLambda = lambda x : x*x*x
print("Normal function: ", kubus(5))
print("Lambda function: ", kubusLambda(5))
# ====
def test(other_func, umur):
nama = other_func(umur)
print(nama)
def gabung(umur):
return f"Umurku {umur} tahun"
test(gabung, 18) | def kubus(x):
return x * x * x
kubus_lambda = lambda x: x * x * x
print('Normal function: ', kubus(5))
print('Lambda function: ', kubus_lambda(5))
def test(other_func, umur):
nama = other_func(umur)
print(nama)
def gabung(umur):
return f'Umurku {umur} tahun'
test(gabung, 18) |
class TaskNotReady(Exception):
pass
class EmptyOutput(Exception):
pass
| class Tasknotready(Exception):
pass
class Emptyoutput(Exception):
pass |
# Abstract Class to
class VirtualizedInstanceInterface:
__mime_type = 'virtualized_instance/interface'
__description = None
def __init__(self):
print(f'Hi')
def getMimeType(self) -> str:
return self.__mime_type
def getDescription(self) -> str:
return self.__description
| class Virtualizedinstanceinterface:
__mime_type = 'virtualized_instance/interface'
__description = None
def __init__(self):
print(f'Hi')
def get_mime_type(self) -> str:
return self.__mime_type
def get_description(self) -> str:
return self.__description |
x = [
-2.764193895, -1.961371891, -1.656290164, -1.30732842, -1.158709371, -0.945359755, -0.857407827, -0.7038015981,
-0.6486940967, -0.5288635476, -0.4942730649, -0.4663968385, -0.3965859287, -0.3755999076, -0.3460053028,
-0.282238155, -0.2518183324, -0.2077810119, -0.1777473592, -0.1481019359, -0.1197748752, -0.10... | x = [-2.764193895, -1.961371891, -1.656290164, -1.30732842, -1.158709371, -0.945359755, -0.857407827, -0.7038015981, -0.6486940967, -0.5288635476, -0.4942730649, -0.4663968385, -0.3965859287, -0.3755999076, -0.3460053028, -0.282238155, -0.2518183324, -0.2077810119, -0.1777473592, -0.1481019359, -0.1197748752, -0.100488... |
minv, maxv, x, y, n = int(input()), int(input()), 0, 0, int(input())
while n != -1:
if minv <= n <= maxv:
x += 1
else:
y += 1
n = int(input())
print(x)
print(y)
| (minv, maxv, x, y, n) = (int(input()), int(input()), 0, 0, int(input()))
while n != -1:
if minv <= n <= maxv:
x += 1
else:
y += 1
n = int(input())
print(x)
print(y) |
_base_ = [
'../_base_/dataset_coco.py',
'../_base_/PoseDet_DLA34.py',
'../_base_/train_schedule.py',
]
exp_name = 'PoseDet_DLA34_coco'
work_dir = './output/' + exp_name | _base_ = ['../_base_/dataset_coco.py', '../_base_/PoseDet_DLA34.py', '../_base_/train_schedule.py']
exp_name = 'PoseDet_DLA34_coco'
work_dir = './output/' + exp_name |
DEBUG = True
SECRET_KEY = 'd5213711b8b332608a2eb8c7f9d62314b126fc99ee79ed02' # make sure to change this
SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/news_flask.db'
| debug = True
secret_key = 'd5213711b8b332608a2eb8c7f9d62314b126fc99ee79ed02'
sqlalchemy_database_uri = 'sqlite:////tmp/news_flask.db' |
# Swap for int arrays
def swap(A, i, j):
temp = A[i];
A[i] = A[j];
A[j] = temp;
| def swap(A, i, j):
temp = A[i]
A[i] = A[j]
A[j] = temp |
# Constante
DIRECTORY_RRD = "RRD" # Carpeta para archivos RRD
DIRECTORY_XML = "XML" # Carpeta para archivos XML
DIRECTORY_IMG = "IMG" # Carpeta para archivos IMG
MODULES_NAME = (
"cargaCPU",
"cargaRAM",
"cargaSTG",
)
def hexToString( cadena ) -> str:
string: str
string_hex = cadena[2:]
bytes_ob... | directory_rrd = 'RRD'
directory_xml = 'XML'
directory_img = 'IMG'
modules_name = ('cargaCPU', 'cargaRAM', 'cargaSTG')
def hex_to_string(cadena) -> str:
string: str
string_hex = cadena[2:]
bytes_object = bytes.fromhex(string_hex)
try:
string = bytes_object.decode()
except UnicodeDecodeError:... |
# NOTE: If you are running a local test environment, settings_dev will already have sensible defaults for many of these.
# Only override the ones you need to, so you're less likely to have to make manual settings updates after pulling in changes.
# Choose one of these:
# from .deployments.settings_dev import *
# from ... | admins = ()
managers = ADMINS
DATABASES['default']['NAME'] = 'perma'
DATABASES['default']['USER'] = 'perma'
DATABASES['default']['PASSWORD'] = 'perma'
secret_key = ''
allowed_hosts = []
default_from_email = 'email@example.com'
developer_email = DEFAULT_FROM_EMAIL
host = 'perma.cc'
sauce_username = ''
sauce_access_key =... |
#!/usr/bin/env python3
# A normal `open()` will open a new file descriptor,
# and it has to be closed manually, else it can end up
# showing unexpected data.
# A `with` statement does not require you to close the fd
# but will close it automatically when the reference is done with.
# The file handler will be closed ... | with open('/tmp/new.txt') as handle:
content = handle.readlines()
print(content)
try:
with open('/tmp/new.txt') as file_handler:
for line in file_handler:
print(line)
except IOError:
print('IOError') |
# optimizer
# optimizer = dict(type='AdamW',
# weight_decay = 1e-4)
optimizer_config = dict(grad_clip=None)
# lr
lr_dict = dict(lr=1e-4,
lr_backbone=1e-5)
weight_decay = 1e-4
# learning policy
lr_config = dict(
policy='step',
warmup='linear',
warmup_iters=500,
warmup_ra... | optimizer_config = dict(grad_clip=None)
lr_dict = dict(lr=0.0001, lr_backbone=1e-05)
weight_decay = 0.0001
lr_config = dict(policy='step', warmup='linear', warmup_iters=500, warmup_ratio=1e-05, step=[20, 29])
total_epochs = 1 |
for t in range(int(input())):
d = {}
n = int(input())
for i in range(n):
a,b = input().split()
try:
d[b]+=1
except:
d[b]=1
c = 1
for i in d:
c*=(d[i]+1)
print(c-1) | for t in range(int(input())):
d = {}
n = int(input())
for i in range(n):
(a, b) = input().split()
try:
d[b] += 1
except:
d[b] = 1
c = 1
for i in d:
c *= d[i] + 1
print(c - 1) |
URL = 'https://reisadvies-api-ast.9292.nl'
APIVERSION = 'v1/api'
LANG = 'nl-NL' # Another option is en-EN
HEADERS = {'Authorization': 'Token '}
| url = 'https://reisadvies-api-ast.9292.nl'
apiversion = 'v1/api'
lang = 'nl-NL'
headers = {'Authorization': 'Token '} |
# made by @ninjamar (https://github.com/ninjamar)
class ProcessFailedError(Exception):
pass
| class Processfailederror(Exception):
pass |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
REDIS_HOST = '192.168.146.134'
REDIS_PORT = 6379
PROXIES_REDIS_KEY = "proxies"
PROXIES_SPIDERS = [
# "spiders.daili66.Daili66ProxySpider",
"spiders.kuaidaili.KuaidailiSpider"
] | redis_host = '192.168.146.134'
redis_port = 6379
proxies_redis_key = 'proxies'
proxies_spiders = ['spiders.kuaidaili.KuaidailiSpider'] |
CONTROLLER_ROUTES_ATTR = '__fcb_controller_routes__'
FN_ROUTES_ATTR = '__fcb_fn_routes__'
NO_ROUTES_ATTR = '__fcb_no_routes__'
NOT_VIEWS_ATTR = '__fcb_not_views_method_names__'
REMOVE_SUFFIXES_ATTR = '__fcb_remove_suffixes__'
| controller_routes_attr = '__fcb_controller_routes__'
fn_routes_attr = '__fcb_fn_routes__'
no_routes_attr = '__fcb_no_routes__'
not_views_attr = '__fcb_not_views_method_names__'
remove_suffixes_attr = '__fcb_remove_suffixes__' |
def formChanger(oldData):
newData=[]
for i in oldData:
newData.append((i[0],i[1],int(i[2])))
return newData | def form_changer(oldData):
new_data = []
for i in oldData:
newData.append((i[0], i[1], int(i[2])))
return newData |
expected_output = {
"slot": {
"rp": {
"0/RSP0": {
"name": "A9K-RSP440-SE",
"full_slot": "0/RSP0/CPU0",
"state": "IOS XR RUN",
"config_state": "PWR,NSHUT,MON",
"redundancy_state": "Active"
}
},
... | expected_output = {'slot': {'rp': {'0/RSP0': {'name': 'A9K-RSP440-SE', 'full_slot': '0/RSP0/CPU0', 'state': 'IOS XR RUN', 'config_state': 'PWR,NSHUT,MON', 'redundancy_state': 'Active'}}, 'lc': {'0/0': {'name': 'A9K-MOD80-SE', 'full_slot': '0/0/CPU0', 'state': 'IOS XR RUN', 'config_state': 'PWR,NSHUT,MON', 'subslot': {'... |
# Standard configuration
FLP_BUILDER_CONFIG = '''
catalogs:
- title: Custom Catalog
id: ZCUSTOM_CATALOG
target_mappings:
- title: My Reporting App
semantic_object: MyReporting
semantic_action: display
url: /sap/bc/ui5_ui5/sap/ZMY_REPORT # path to the BSP app on the SAP system
... | flp_builder_config = '\ncatalogs:\n - title: Custom Catalog\n id: ZCUSTOM_CATALOG\n target_mappings:\n - title: My Reporting App\n semantic_object: MyReporting\n semantic_action: display\n url: /sap/bc/ui5_ui5/sap/ZMY_REPORT # path to the BSP app on the SAP system\n ui5_componen... |
podcast = {
"title": "Muffin Cast",
"description": "Un super podcast!",
"url": "",
"author": "Muffi, the Muffin",
"lang": "fr",
"email": "",
"donation": "",
"audio_base": "",
"itunes_category": "Comedy",
"itunes_subcategory": "",
"itunes_subtitle": "",
"itunes_type": "episodic",
"itunes_explic... | podcast = {'title': 'Muffin Cast', 'description': 'Un super podcast!', 'url': '', 'author': 'Muffi, the Muffin', 'lang': 'fr', 'email': '', 'donation': '', 'audio_base': '', 'itunes_category': 'Comedy', 'itunes_subcategory': '', 'itunes_subtitle': '', 'itunes_type': 'episodic', 'itunes_explicit': 'no', 'base_descriptio... |
# Declare second integer, double, and String variables.
num=input()
fd=input()
mystr=input()
# Read and save an integer, double, and String to your variables.
# Print the sum of both integer variables on a new line.
print(int(num)+i)
# Print the sum of the double variables on a new line.
print(d+float(fd))
#... | num = input()
fd = input()
mystr = input()
print(int(num) + i)
print(d + float(fd))
print(s + mystr) |
class StartsWithAssertion(object):
def assertStartsWith(self, a, b):
self.assertTrue(
b.startswith(a),
'{0} does not start with {1}'.format(b, a)
)
class IOStubs(object):
def yes_input(self, output):
self.log_output(output)
return 'y'
def no_input(s... | class Startswithassertion(object):
def assert_starts_with(self, a, b):
self.assertTrue(b.startswith(a), '{0} does not start with {1}'.format(b, a))
class Iostubs(object):
def yes_input(self, output):
self.log_output(output)
return 'y'
def no_input(self, output):
self.log_... |
#!/usr/bin/python3
plainText = input ("Introduce una palabra en minusculas:")
distancia = int(input("Que distancia entre letras:"))
code = ""
for ch in plainText:
ordValor = ord(ch)
cipherValor=ordValor+distancia
if cipherValor > ord('z'):
cipherValor= ord('a') + distancia - (ord('z') - ordValor + 1... | plain_text = input('Introduce una palabra en minusculas:')
distancia = int(input('Que distancia entre letras:'))
code = ''
for ch in plainText:
ord_valor = ord(ch)
cipher_valor = ordValor + distancia
if cipherValor > ord('z'):
cipher_valor = ord('a') + distancia - (ord('z') - ordValor + 1)
code ... |
class Car:
def needsFuel(self):
pass
def getEngineTemperature(self):
pass
def driveTo(self, destination):
pass
| class Car:
def needs_fuel(self):
pass
def get_engine_temperature(self):
pass
def drive_to(self, destination):
pass |
# If a peer returns 0 results, wait this many seconds before asking it for anything else
EMPTY_PEER_RESPONSE_PENALTY = 15.0
# Picked a reorg number that is covered by a single skeleton header request,
# which covers about 6 days at 15s blocks
MAX_SKELETON_REORG_DEPTH = 35000
| empty_peer_response_penalty = 15.0
max_skeleton_reorg_depth = 35000 |
class Component:
def __init__(self, name, block):
self.name = name
self.block = block
def to_pair(self):
return self.name, self.block()
| class Component:
def __init__(self, name, block):
self.name = name
self.block = block
def to_pair(self):
return (self.name, self.block()) |
sentence = input("Sentence: ")
sentence = sentence.replace(" ", "\n")
print(sentence, "\a")
| sentence = input('Sentence: ')
sentence = sentence.replace(' ', '\n')
print(sentence, '\x07') |
class Syntax:
def __init__(self, **kwargs):
# First initialize a default syntax.
# General tokens.
self.terminator = ';'
self.delim = ','
self.params_start = '_{'
self.params_stop = '}'
self.paren_left = '('
self.paren_right = ')'
# Logical... | class Syntax:
def __init__(self, **kwargs):
self.terminator = ';'
self.delim = ','
self.params_start = '_{'
self.params_stop = '}'
self.paren_left = '('
self.paren_right = ')'
self.not_op = 'not'
self.and_op = 'and'
self.or_op = 'or'
s... |
## Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
## SPDX-License-Identifier: Apache-2.0
m2c2_local_resource_path = "/m2c2/job"
m2c2_metrics_url = "https://metrics.awssolutionsbuilder.com/generic"
m2c2_ddb_job_name_exists = "Job %s already exists in database."
m2c2_ddb_job_name_does_not_exist ... | m2c2_local_resource_path = '/m2c2/job'
m2c2_metrics_url = 'https://metrics.awssolutionsbuilder.com/generic'
m2c2_ddb_job_name_exists = 'Job %s already exists in database.'
m2c2_ddb_job_name_does_not_exist = 'Job %s not found in database.'
m2c2_ddb_job_name_version_must_be_unique = 'A unique database entry must exist fo... |
while True:
flag = hero.findFlag()
enemy = hero.findNearestEnemy()
if flag:
hero.pickUpFlag(flag)
elif enemy:
if hero.distanceTo(enemy) < 10:
if hero.isReady("cleave"):
hero.cleave(enemy)
else:
hero.attack(enemy)
| while True:
flag = hero.findFlag()
enemy = hero.findNearestEnemy()
if flag:
hero.pickUpFlag(flag)
elif enemy:
if hero.distanceTo(enemy) < 10:
if hero.isReady('cleave'):
hero.cleave(enemy)
else:
hero.attack(enemy) |
#!/usr/bin/env python
# encoding: utf-8
class Solution:
def maxSumTwoNoOverlap(self, A: List[int], L: int, M: int) -> int:
n = len(A)
if L + M > n: return 0
# presum array
# P[j] - P[i-1] = sum(A[i:j])
P = [A[0]]
for i in range(1, n):
P.append(P[-1] + A[... | class Solution:
def max_sum_two_no_overlap(self, A: List[int], L: int, M: int) -> int:
n = len(A)
if L + M > n:
return 0
p = [A[0]]
for i in range(1, n):
P.append(P[-1] + A[i])
(ans, max_l, max_m) = (P[L + M - 1], P[L - 1], P[M - 1])
for t in ... |
def map_range(x, x0, x1, y0, y1):
return y0 + (x - x0) * ((y1 - y0) / (x1 - x0))
def argmin(lst, f):
min_score = None
min_elem = None
for elem in lst:
score = f(elem)
if min_score is None or score < min_score:
min_score = score
min_elem = elem
return min_elem... | def map_range(x, x0, x1, y0, y1):
return y0 + (x - x0) * ((y1 - y0) / (x1 - x0))
def argmin(lst, f):
min_score = None
min_elem = None
for elem in lst:
score = f(elem)
if min_score is None or score < min_score:
min_score = score
min_elem = elem
return min_elem... |
# https://www.codewars.com/kata/558fc85d8fd1938afb000014
def sum_two_smallest_numbers(numbers):
a, b = None, None
for i, n in enumerate(numbers):
if i == 0: a = n
elif i == 1: b = n
elif n < a: a = n
elif n < b: b = n
if i > 0 and a < b:
# a must always b... | def sum_two_smallest_numbers(numbers):
(a, b) = (None, None)
for (i, n) in enumerate(numbers):
if i == 0:
a = n
elif i == 1:
b = n
elif n < a:
a = n
elif n < b:
b = n
if i > 0 and a < b:
(a, b) = (b, a)
retur... |
class QuestHolderBase():
def __init__(self):
self._rewardCollectors = {}
def getQuests(self):
raise 'derived must implement'
def _addQuestRewardCollector(self, collector):
cId = collector._serialNum
self._rewardCollectors[cId] = collector
def _removeQuestRewardColle... | class Questholderbase:
def __init__(self):
self._rewardCollectors = {}
def get_quests(self):
raise 'derived must implement'
def _add_quest_reward_collector(self, collector):
c_id = collector._serialNum
self._rewardCollectors[cId] = collector
def _remove_quest_reward_c... |
config = {
'primary_folder': 'static',
'system_name': 'server',
'local_host': 'localhost',
'port': 8000,
} | config = {'primary_folder': 'static', 'system_name': 'server', 'local_host': 'localhost', 'port': 8000} |
my_list = ['-', '-', '-']
print(my_list)
letter = 'u'
list_indexes = [0, 2]
for index in list_indexes:
my_list[index] = letter
print(my_list)
| my_list = ['-', '-', '-']
print(my_list)
letter = 'u'
list_indexes = [0, 2]
for index in list_indexes:
my_list[index] = letter
print(my_list) |
# Node class
class Node:
def __init__(self, data) -> None:
self.data = data
self.next = None
# Linked List class
class LinkedList:
def __init__(self) -> None:
self.head = None
# print linked list
def print_list(self):
temp = self.head
while temp:
pr... | class Node:
def __init__(self, data) -> None:
self.data = data
self.next = None
class Linkedlist:
def __init__(self) -> None:
self.head = None
def print_list(self):
temp = self.head
while temp:
print(temp.data)
temp = temp.next
def ins... |
class Solution:
def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:
# minimum spanning tree
parents_a = list(range(n))
parents_b = list(range(n))
cnt_a = n
cnt_b = n
def find(x, parents):
if parents[x] == x:
return x
... | class Solution:
def max_num_edges_to_remove(self, n: int, edges: List[List[int]]) -> int:
parents_a = list(range(n))
parents_b = list(range(n))
cnt_a = n
cnt_b = n
def find(x, parents):
if parents[x] == x:
return x
parents[x] = find(p... |
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if sorted(s) == sorted(t):
return True
else:
return False
| class Solution:
def is_anagram(self, s: str, t: str) -> bool:
if sorted(s) == sorted(t):
return True
else:
return False |
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
cur = 0
for i in range(len(nums)):
if nums[i] != val:
nums[cur] = nums[i]
cur += 1
return cur
| class Solution:
def remove_element(self, nums: List[int], val: int) -> int:
cur = 0
for i in range(len(nums)):
if nums[i] != val:
nums[cur] = nums[i]
cur += 1
return cur |
class I():
num = 0
def __init__(self):
self.num = 0
def method(self):
return
def methodA(self):
I.num = 0
def methodB(self):
I.num = I.num + 1
def methodC(self):
self.num += 1
def methodD(cls):
I.num = I.num + 1
methodD = classmetho... | class I:
num = 0
def __init__(self):
self.num = 0
def method(self):
return
def method_a(self):
I.num = 0
def method_b(self):
I.num = I.num + 1
def method_c(self):
self.num += 1
def method_d(cls):
I.num = I.num + 1
method_d = classmeth... |
class ManufacturerInfo:
def __init__(self, model, os_info):
self.os_info = os_info
self.model = model
def add_headers(self, **kwargs):
for key, value in kwargs.items():
self.headers[key] = value
def set_params(self, **kwargs):
self.params = {}
self.add_p... | class Manufacturerinfo:
def __init__(self, model, os_info):
self.os_info = os_info
self.model = model
def add_headers(self, **kwargs):
for (key, value) in kwargs.items():
self.headers[key] = value
def set_params(self, **kwargs):
self.params = {}
self.ad... |
class Solution:
def clumsy(self, N: int) -> int:
ops = [operator.mul, operator.floordiv, operator.add, operator.sub]
idx = 0
stack = [N]
while N > 1:
N -= 1
if idx == 0:
stack.append(ops[idx](stack.pop(), N))
elif idx == 1:
... | class Solution:
def clumsy(self, N: int) -> int:
ops = [operator.mul, operator.floordiv, operator.add, operator.sub]
idx = 0
stack = [N]
while N > 1:
n -= 1
if idx == 0:
stack.append(ops[idx](stack.pop(), N))
elif idx == 1:
... |
# 10. Write a program that asks the user to enter a string, then prints out each letter of the string
# doubled and on a separate line. For instance, if the user entered 'HEY', the output would be
# HH
# EE
# YY
s = input('Enter a string: ')
for c in s:
print(c * 2)
| s = input('Enter a string: ')
for c in s:
print(c * 2) |
'''
Exceptions for autotracker operation
'''
__all__ = 'AutotrackerException', 'NoConnection', 'ParseError', 'NoDevice'
class AutotrackerException(Exception):
'''
Base autotracker exception class.
'''
class NoConnection(AutotrackerException):
'''
Raised when no connection could be established.... | """
Exceptions for autotracker operation
"""
__all__ = ('AutotrackerException', 'NoConnection', 'ParseError', 'NoDevice')
class Autotrackerexception(Exception):
"""
Base autotracker exception class.
"""
class Noconnection(AutotrackerException):
"""
Raised when no connection could be established.
... |
cores = ['blue',
'green',
'yellow',
'red',
'cyan',
'gray',
'light green',
'white']
def formatar(line, conta) -> list:
line += 1
line = str(line)
formatado = list()
contador = 0
for i, c in enumerate(conta):
if c.isal... | cores = ['blue', 'green', 'yellow', 'red', 'cyan', 'gray', 'light green', 'white']
def formatar(line, conta) -> list:
line += 1
line = str(line)
formatado = list()
contador = 0
for (i, c) in enumerate(conta):
if c.isalpha() and c != '=':
p1 = i
p2 = p1 + 1
... |
class Message(object):
### DO NOT MODIFY THIS METHOD ###
def __init__(self, text):
'''
Initializes a Message object
text (string): the message's text
a Message object has two attributes:
self.message_text (string, determined by input text)
... | class Message(object):
def __init__(self, text):
"""
Initializes a Message object
text (string): the message's text
a Message object has two attributes:
self.message_text (string, determined by input text)
self.valid_words (list, determined ... |
# Copyright (C) 2014 Napuzba [kobi@napuzba.com]
# Licensed under MIT license [http://openreq.source.org/licenses/MIT]
class RequestState:
'''
The state of the request
'''
'''
The file was downloaded succesfully
'''
Downloaded = 1
'''
The file was read from cache
'''
... | class Requeststate:
"""
The state of the request
"""
'\n The file was downloaded succesfully\n '
downloaded = 1
'\n The file was read from cache\n '
cached = 2
'\n The file was not downloaded successfully\n '
fail_download = 11
'\n The file was not in cache\n... |
def breakingRecords(scores):
breaksRecord = [0, 0]
maxScore = scores[0]
minScore = scores[0]
for obj in scores:
if obj < minScore:
minScore = obj
breaksRecord[1] += 1
elif obj > maxScore:
maxScore = obj
breaksRecord[0] += 1
return breaksRecord | def breaking_records(scores):
breaks_record = [0, 0]
max_score = scores[0]
min_score = scores[0]
for obj in scores:
if obj < minScore:
min_score = obj
breaksRecord[1] += 1
elif obj > maxScore:
max_score = obj
breaksRecord[0] += 1
return... |
# Tests for all routes related to users.
def test_editProfile(byte):
byte._assert(byte.register('John', 'john', 'john@gmail.com', 'secret'))
byte._assert(byte.login('john', 'secret'))
response = byte.post('/user/edit_profile', {'name': 'John', 'username': 'john', 'email': 'john@gmail.com', 'gender': 'Male... | def test_edit_profile(byte):
byte._assert(byte.register('John', 'john', 'john@gmail.com', 'secret'))
byte._assert(byte.login('john', 'secret'))
response = byte.post('/user/edit_profile', {'name': 'John', 'username': 'john', 'email': 'john@gmail.com', 'gender': 'Male', 'birthdate': 'January 1, 2020'}, byte.a... |
# The functions below are the basics of
# creating, editting, and reading text files.
# "a" stands for "append"
myfile = open("mytext.txt", "a")
# "w" stands for "write"
myfile = open("mytext.txt", "w")
# writes into a mytext.txt on different lines
# "hello world\nhi again\nhelloooo"
# You need to use the "\n" ch... | myfile = open('mytext.txt', 'a')
myfile = open('mytext.txt', 'w')
myfile.write('hello world\n')
myfile.write('hi again\n')
myfile.write('helloooo')
myfile.close()
myfile = open('mytext.txt', 'r')
mydata = myfile.read()
print(mydata)
print(myfile.readable())
print(myfile.readline())
print(myfile.readline())
print(myfile... |
# Copyright 2018 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
load(":dart.bzl", "COMMON_COMPILE_KERNEL_ACTION_ATTRS", "compile_kernel_action")
load(":package_info.bzl", "PackageComponentInfo", "PackageLocalInfo")
# A Fu... | load(':dart.bzl', 'COMMON_COMPILE_KERNEL_ACTION_ATTRS', 'compile_kernel_action')
load(':package_info.bzl', 'PackageComponentInfo', 'PackageLocalInfo')
def _flutter_app_impl(context):
kernel_snapshot_file = context.outputs.kernel_snapshot
manifest_file = context.outputs.manifest
component_name = context.fil... |
def factorial( n ):
if n <1: # base case
return 1
else:
returnNumber = n * factorial( n - 1 ) # recursive call
print(str(n) + '! = ' + str(returnNumber))
return returnNumber | def factorial(n):
if n < 1:
return 1
else:
return_number = n * factorial(n - 1)
print(str(n) + '! = ' + str(returnNumber))
return returnNumber |
class animal():
def __init__(self, nombre, edad, ruido):
self.nombre = nombre
self.edad = edad
self.ruido = ruido
def haz_ruido(self):
print(self.ruido)
ave = animal("piolin", 2, "pio pio")
ave.haz_ruido()
print(ave.__dict__)
class perro(animal):
raza = ''
class g... | class Animal:
def __init__(self, nombre, edad, ruido):
self.nombre = nombre
self.edad = edad
self.ruido = ruido
def haz_ruido(self):
print(self.ruido)
ave = animal('piolin', 2, 'pio pio')
ave.haz_ruido()
print(ave.__dict__)
class Perro(animal):
raza = ''
class Gato(animal... |
#
# Time complexity: O(2^n) (where "n" is the number of letters in the string)
# Space complexity: O(2^n) (number of branches in the recursion tree)
#
def subsequences(str):
return helper("", str)
def helper(acc, remaining):
if not remaining:
return [acc]
with_letter = helper(acc + remaining[0], remaini... | def subsequences(str):
return helper('', str)
def helper(acc, remaining):
if not remaining:
return [acc]
with_letter = helper(acc + remaining[0], remaining[1:])
without_letter = helper(acc, remaining[1:])
return with_letter + without_letter |
digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
tens_digit = '7'
for digit in digits:
print('{}{}'.format(tens_digit, digit))
print('80')
| digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
tens_digit = '7'
for digit in digits:
print('{}{}'.format(tens_digit, digit))
print('80') |
#!/usr/bin/env python3
#////////////////////////////////////////////////////////////////////////////////////
#// Authors: Kwangsoo Han and Jiajia Li
#// (Ph.D. advisor: Andrew B. Kahng),
#// Many subsequent changes for open-sourcing were made by Mateus Fogaca
#// (Ph.D. advisor: Ricardo Reis)... | fo = open('place-2.v', 'w')
with open('place.v') as fp:
for line in fp:
if line.startswith('/*') or line.startswith('#') or line.startswith('*/') or line.startswith('//'):
continue
if ';' in line or line == '\n':
fo.write(line)
else:
fo.write(line.rstrip('... |
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
adjList = defaultdict(list)
for v, u in prerequisites:
adjList[u].append(v)
ans = []
isPossible = True
color = {k: 0 for k in range(numCourses)}
def dfs(... | class Solution:
def find_order(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
adj_list = defaultdict(list)
for (v, u) in prerequisites:
adjList[u].append(v)
ans = []
is_possible = True
color = {k: 0 for k in range(numCourses)}
def d... |
# Make this script interact with readme.md
# -- Submission Stats (as of June 08, 2021) --
# Time Complexity: O(n)
# Runtime: 28ms, faster than 95.34%
# Space Complexity: O(n)
# Memory Usage: 14.3 MB, less than 49.29%
number = 617
problemLink = "https://leetcode.com/problems/merge-tw... | number = 617
problem_link = 'https://leetcode.com/problems/merge-two-binary-trees/'
problem_title = problemLink[problemLink[:-1].rfind('/') + 1:-1].replace('-', ' ').title()
solution = ''
time = 'O(n)'
space = 'O(1)'
difficulty = 'Easy'
note = "if you're calling a built-in function more than once, use variables instead... |
#
# @lc app=leetcode id=21 lang=python3
#
# [21] Merge Two Sorted Lists
#
# https://leetcode.com/problems/merge-two-sorted-lists/description/
#
# algorithms
# Easy (56.01%)
# Likes: 6209
# Dislikes: 734
# Total Accepted: 1.3M
# Total Submissions: 2.4M
# Testcase Example: '[1,2,4]\n[1,3,4]'
#
# Merge two sorted l... | class Solution:
def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = list_node(0)
curr = head
while l1 and l2:
if l1.val > l2.val:
curr.next = l2
l2 = l2.next
else:
curr.next = l1
l1... |
# Write a program to perform division of two numbers without using division
# operator ('/')
def divide(x, y):
if y == 0:
raise ZeroDivisionError('y = 0')
sign = 1 if x * y > 0 else -1
x, y = abs(x), abs(y)
mask, quotient = 1, 0
while y <= x:
y <<= 1
mask <<= ... | def divide(x, y):
if y == 0:
raise zero_division_error('y = 0')
sign = 1 if x * y > 0 else -1
(x, y) = (abs(x), abs(y))
(mask, quotient) = (1, 0)
while y <= x:
y <<= 1
mask <<= 1
while mask > 1:
y >>= 1
mask >>= 1
if x >= y:
x -= y
... |
# -*- coding: utf-8 -*-
__author__ = 'Martijn Braam'
__email__ = 'martijn@brixit.nl'
__version__ = '0.1.0' | __author__ = 'Martijn Braam'
__email__ = 'martijn@brixit.nl'
__version__ = '0.1.0' |
#
# @lc app=leetcode id=24 lang=python3
#
# [24] Swap Nodes in Pairs
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if not head or not ... | class Solution:
def swap_pairs(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
dummy = list_node(0)
dummy.next = head
cur = dummy
while cur.next and cur.next.next:
first = cur.next
second = cur.next.next
... |
def fibo(n):
a=0
b=1
for i in range(n):
element=a
a=b
b=element+a
print(element)
return b
| def fibo(n):
a = 0
b = 1
for i in range(n):
element = a
a = b
b = element + a
print(element)
return b |
{
"variables": {
"root": "../../..",
"platform": "<(OS)",
"release": "<@(module_root_dir)/build/Release",
"vkSDK": "C:/VulkanSDK/1.1.121.2",
"cudaSDK": "C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v10.1",
"optixSDK": "C:/ProgramData/NVIDIA Corporation/OptiX SDK 7.0.0"
},
"conditions... | {'variables': {'root': '../../..', 'platform': '<(OS)', 'release': '<@(module_root_dir)/build/Release', 'vkSDK': 'C:/VulkanSDK/1.1.121.2', 'cudaSDK': 'C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v10.1', 'optixSDK': 'C:/ProgramData/NVIDIA Corporation/OptiX SDK 7.0.0'}, 'conditions': [["platform == 'win'", {'varia... |
class DAOUtils(object):
NOT_APPLIC = "n/a"
@staticmethod
def get_value_from_data(data, name):
if name in data:
return data[name]
return None
@staticmethod
def valid_id(id):
if id is not None:
return str(id)
return DAOUtils.NOT_APPLIC | class Daoutils(object):
not_applic = 'n/a'
@staticmethod
def get_value_from_data(data, name):
if name in data:
return data[name]
return None
@staticmethod
def valid_id(id):
if id is not None:
return str(id)
return DAOUtils.NOT_APPLIC |
MY_ID = 'qos' # Client-unique string
SERVER = '192.168.0.42'
SSID = 'MY_WIFI_SSID'
PW = 'PASSWORD'
PORT = 9999
TIMEOUT = 4000
| my_id = 'qos'
server = '192.168.0.42'
ssid = 'MY_WIFI_SSID'
pw = 'PASSWORD'
port = 9999
timeout = 4000 |
def num_input(prompt, default, min_n, max_n, type_func):
if default:
prompt += " (default: {}): ".format(default)
else:
prompt += ": "
while True:
user_input = input(prompt)
if not user_input and default:
return default
try:
num = typ... | def num_input(prompt, default, min_n, max_n, type_func):
if default:
prompt += ' (default: {}): '.format(default)
else:
prompt += ': '
while True:
user_input = input(prompt)
if not user_input and default:
return default
try:
num = type_func(use... |
class Pin(object):
regex = "^Pin '(?P<name>[A-Za-z0-9_-]+)' "\
"(?P<pintype>[A-Za-z/]+) "\
"(?P<unknown1>[A-Za-z]+) "\
"(?P<unknown2>[A-Za-z]+) "\
"R(?P<rotation>([0-9]+)) "\
"(?P<unknown3>[^ ]+) "\
"(?P<unknown4>[^ ]+) "\
"\((?P<pos_x>[0-9-\.]+) (?P<pos_y>[0-... | class Pin(object):
regex = "^Pin '(?P<name>[A-Za-z0-9_-]+)' (?P<pintype>[A-Za-z/]+) (?P<unknown1>[A-Za-z]+) (?P<unknown2>[A-Za-z]+) R(?P<rotation>([0-9]+)) (?P<unknown3>[^ ]+) (?P<unknown4>[^ ]+) \\((?P<pos_x>[0-9-\\.]+) (?P<pos_y>[0-9-\\.]+)\\);$"
device = None
device_pin_number = None
symbol = None
... |
# Function for converting decimal to binary
def float_bin(my_number, places=3):
my_whole, my_dec = str(my_number).split(".")
my_whole = int(my_whole)
res = (str(bin(my_whole)) + ".").replace('0b', '')
for x in range(places):
my_dec = str('0.') + str(my_dec)
temp = '%1.20f' % (float(my_d... | def float_bin(my_number, places=3):
(my_whole, my_dec) = str(my_number).split('.')
my_whole = int(my_whole)
res = (str(bin(my_whole)) + '.').replace('0b', '')
for x in range(places):
my_dec = str('0.') + str(my_dec)
temp = '%1.20f' % (float(my_dec) * 2)
(my_whole, my_dec) = temp.... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
class UselessDrawableConfig(object):
src_dir = []
res_dir = []
extra = []
white_list = []
def __init__(self, dict=[]):
if 'src_dir' in dict:
self.src_dir = dict['src_dir']
if 'res_dir' in dict:
self.res_dir = ... | class Uselessdrawableconfig(object):
src_dir = []
res_dir = []
extra = []
white_list = []
def __init__(self, dict=[]):
if 'src_dir' in dict:
self.src_dir = dict['src_dir']
if 'res_dir' in dict:
self.res_dir = dict['res_dir']
if 'extra' in dict:
... |
class Host(object):
def __init__(self,name,ip,mac,port,visible):
self.shortName=name
self.realIP=ip
self.macaddress=mac
self.portNum=port
self.deceptiveIP=""
self.distance=0
self.visible=visible
def setDecIPAddr(self,decIP):
self.deceptiveIP=de... | class Host(object):
def __init__(self, name, ip, mac, port, visible):
self.shortName = name
self.realIP = ip
self.macaddress = mac
self.portNum = port
self.deceptiveIP = ''
self.distance = 0
self.visible = visible
def set_dec_ip_addr(self, decIP):
... |
class Keyboard():
# key for opencv another way convert to ASCII
# 1048695 &0xff(hexadecimal)
# from key to bytearray ASCII(ord) example ord('a') --> 119
k_w = 1048695
k_s = 1048691
k_a = 1048673
k_d = 1048676
k_space = 1048608
k_left = 1113937
k_right = 1113939
k_up = 111393... | class Keyboard:
k_w = 1048695
k_s = 1048691
k_a = 1048673
k_d = 1048676
k_space = 1048608
k_left = 1113937
k_right = 1113939
k_up = 1113938
k_down = 1113940
k_p = 1048688
k_l = 1048684
k_z = 1048698
k_x = 1048696
k_q = 1048689
k_2 = 1048626
k_r = 1048690
... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
# Time O(h) Space O(h)
def deleteNode(self, root: TreeNode, key: int) -> TreeNode:
if not root:
... | class Treenode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def delete_node(self, root: TreeNode, key: int) -> TreeNode:
if not root:
return None
if key == root.val:
if not... |
class comment:
text: str
def __init__(self, text: str):
self.text = text
def setSxolio(self, text: str):
self.text = text
def remove(self):
del self
| class Comment:
text: str
def __init__(self, text: str):
self.text = text
def set_sxolio(self, text: str):
self.text = text
def remove(self):
del self |
#!/usr/bin/env python
# This python script checks the sfincsOutput.h5 file for an example to
# see if the results are close to expected values. This script may be
# run directly, and it is also called when "make test" is run from the
# main SFINCS directory.
execfile('../testsCommon.py')
desiredTolerance = 0.001
... | execfile('../testsCommon.py')
desired_tolerance = 0.001
num_failures = 0
species = 0
num_failures += should_be('FSABFlow', species, -0.770757651696965, desiredTolerance)
num_failures += should_be('particleFlux', species, -1.16119018442468e-05, desiredTolerance)
num_failures += should_be('heatFlux', species, -0.00088196... |
# First I create a map of all abundant numbers. That is to increase the performance.
# Eveything else is self-explanatory.
# We will use the given 28123 as the upper limit.
def is_abundant(N):
total = 0
for i in range(1, N):
if N % i == 0:
total += i
return N < total
def get_is_abund... | def is_abundant(N):
total = 0
for i in range(1, N):
if N % i == 0:
total += i
return N < total
def get_is_abundant_map(N):
abundants = {}
for i in range(1, N):
abundants[i] = is_abundant(i)
return abundants
def is_a_sum_of_two_abundant_numbers(N, abundants):
for... |
load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library")
load("@io_bazel_rules_go//proto:compiler.bzl", "go_proto_compiler")
def pgv_go_proto_library(name, proto = None, deps = [], **kwargs):
go_proto_compiler(
name = "pgv_plugin_go",
suffix = ".pb.validate.go",
valid_archive = False,
... | load('@io_bazel_rules_go//proto:def.bzl', 'go_proto_library')
load('@io_bazel_rules_go//proto:compiler.bzl', 'go_proto_compiler')
def pgv_go_proto_library(name, proto=None, deps=[], **kwargs):
go_proto_compiler(name='pgv_plugin_go', suffix='.pb.validate.go', valid_archive=False, plugin='@com_lyft_protoc_gen_valida... |
CHANNEL = "#bugbyte-ita"
BOTNAME = "CovidBot"
IRC_SERVER_ADDRESS = "irc.freenode.net"
HTTP_REQUEST_TIMEOUT = 5 # timeout in seconds
NEWSAPI_KEY = ''
OPENWEATHER_KEY = ''
YOUTUBE_KEY = ''
META_API_AUTH = ''
CLEVERBOT_KEY = ''
WOLFRAM_KEY = ''
SEARCH_ENGINE = ''
TELEGRAM_TOKEN = ''
ENABLE_MINIFLUX = False
MINIFLUX_URL ... | channel = '#bugbyte-ita'
botname = 'CovidBot'
irc_server_address = 'irc.freenode.net'
http_request_timeout = 5
newsapi_key = ''
openweather_key = ''
youtube_key = ''
meta_api_auth = ''
cleverbot_key = ''
wolfram_key = ''
search_engine = ''
telegram_token = ''
enable_miniflux = False
miniflux_url = ''
miniflux_user = ''... |
#
# PySNMP MIB module ASKEY-DSLAM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASKEY-DSLAM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:13:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_intersection, value_range_constraint, constraints_union) ... |
regex = "^ENWWW(NEEE|SSE(EE|N))$"
regex = regex[1:-1]
class RegAll:
def __init__(self, text=None):
self._order = []
self._depth = 0
if text is not None:
self.parse(text)
@property
def _point(self):
ci = self._order
for i in range(0, int(self._depth*2)):
... | regex = '^ENWWW(NEEE|SSE(EE|N))$'
regex = regex[1:-1]
class Regall:
def __init__(self, text=None):
self._order = []
self._depth = 0
if text is not None:
self.parse(text)
@property
def _point(self):
ci = self._order
for i in range(0, int(self._depth * 2)... |
def sieve(N):
cross = [False] * (N+1)
prime = []
for i in range(2, N+1):
if cross[i] == False:
prime.append(i)
for j in range(2*i, N+1, i):
cross[j] = True
return prime
cash = int(input())
obj = int(input())
times = [0 for _ in range(cash+1)]
comp = ... | def sieve(N):
cross = [False] * (N + 1)
prime = []
for i in range(2, N + 1):
if cross[i] == False:
prime.append(i)
for j in range(2 * i, N + 1, i):
cross[j] = True
return prime
cash = int(input())
obj = int(input())
times = [0 for _ in range(cash + 1)]
com... |
# -*- coding: utf-8 -*-
def scf(mol_name):
return len(mol_name)
def dft(mol_name):
return len(mol_name) - 2
| def scf(mol_name):
return len(mol_name)
def dft(mol_name):
return len(mol_name) - 2 |
# -*- coding: utf-8 -*-
class CConfigOne(object):
# [Basic Options]
datanum='1'
datapath_list=[]
PATH_FASTA = ''
PATH_RESULT_EXPORT = ''
# [Advanced Options]
co_elute='1'
input_format_list = ['raw', 'ms1', 'mgf']
input_format='raw'
isolation_width='2'
mars_threshold='-0.5'
... | class Cconfigone(object):
datanum = '1'
datapath_list = []
path_fasta = ''
path_result_export = ''
co_elute = '1'
input_format_list = ['raw', 'ms1', 'mgf']
input_format = 'raw'
isolation_width = '2'
mars_threshold = '-0.5'
ipv_file = '.\\IPV.txt'
trainingset = '.\\TrainingSet... |
class Stream:
def __init__(self):
self.pos = 0
self.bitpos = 7 # msb 7, lsb 0
self.buffer = []
def write_byte(self, val):
self.buffer.append(val)
def read_bit(self):
mask = 1 << self.bitpos
bit = (self.buffer[self.pos] & mask) >> self.bitpos
... | class Stream:
def __init__(self):
self.pos = 0
self.bitpos = 7
self.buffer = []
def write_byte(self, val):
self.buffer.append(val)
def read_bit(self):
mask = 1 << self.bitpos
bit = (self.buffer[self.pos] & mask) >> self.bitpos
self.bitpos = (self.bi... |
# https://leetcode.com/problems/diagonal-traverse
class Solution:
def findDiagonalOrder(self, matrix):
if not matrix or matrix == [[]]:
return []
R, C = len(matrix), len(matrix[0])
ans = []
def go_urd(r, c):
ans.append(matrix[r][c])
if c == C - ... | class Solution:
def find_diagonal_order(self, matrix):
if not matrix or matrix == [[]]:
return []
(r, c) = (len(matrix), len(matrix[0]))
ans = []
def go_urd(r, c):
ans.append(matrix[r][c])
if c == C - 1:
if r + 1 < R:
... |
#!/usr/bin/python3
def main():
return 0
if __name__=="__main__":
exit(main())
| def main():
return 0
if __name__ == '__main__':
exit(main()) |
def A():
ybr = input().split()
y , b , r = int(ybr[0]) , int(ybr[1]) , int(ybr[2])
a = min(y, b-1, r-2)
print(3*a+3)
A()
| def a():
ybr = input().split()
(y, b, r) = (int(ybr[0]), int(ybr[1]), int(ybr[2]))
a = min(y, b - 1, r - 2)
print(3 * a + 3)
a() |
'''
Pattern
Enter number of rows: 5
1
23
345
4567
56789
'''
print('number pattern: ')
number_rows=int(input('Enter number of rows: '))
for row in range(0,number_rows+1):
k=row
for column in range(1,row+2):
k=k+1
if k < 10:
print(f'0{k}',end=' ')
else:
print(k,end=' ')
print() | """
Pattern
Enter number of rows: 5
1
23
345
4567
56789
"""
print('number pattern: ')
number_rows = int(input('Enter number of rows: '))
for row in range(0, number_rows + 1):
k = row
for column in range(1, row + 2):
k = k + 1
if k < 10:
print(f'0{k}', end=' ')
else:
... |
_ = int(input())
set_a = set(map(int, input().split(" ")))
num_commands = int(input())
for _ in range(num_commands):
command, _ = input().split(" ")
set_b = set(map(int, input().split(" ")))
if command == "intersection_update":
set_a.intersection_update(set_b)
elif command == "update":
... | _ = int(input())
set_a = set(map(int, input().split(' ')))
num_commands = int(input())
for _ in range(num_commands):
(command, _) = input().split(' ')
set_b = set(map(int, input().split(' ')))
if command == 'intersection_update':
set_a.intersection_update(set_b)
elif command == 'update':
... |
def weighted_ensemble(weights, models, inputs):
# Assigning empty array to store 2D array of model predictions
predictions = []
# Loop through all models
for i in range(len(models)):
# Make predictions for each model
predictions.append(models[i].predict(inputs))
# Multiply predi... | def weighted_ensemble(weights, models, inputs):
predictions = []
for i in range(len(models)):
predictions.append(models[i].predict(inputs))
predictions[i] = [x * weights[i] for x in predictions[i]]
predictions_sum = [sum(x) for x in zip(*predictions)]
return predictionsSum |
# Basic data types in Python: Numbers, Strings, Booleans, Sequences, Dictionaries
myint = 5
myfloat = 13.2
mystr = "This is a string"
mybool = True
mylist = [0, 1, "two", 3.2, False]
mytuple = (0, 1, 2)
mydict = {"one" : 1, "two" : 2}
print(myint)
print(myfloat)
print(mystr)
print(mybool)
print(mylist)
p... | myint = 5
myfloat = 13.2
mystr = 'This is a string'
mybool = True
mylist = [0, 1, 'two', 3.2, False]
mytuple = (0, 1, 2)
mydict = {'one': 1, 'two': 2}
print(myint)
print(myfloat)
print(mystr)
print(mybool)
print(mylist)
print(mytuple)
print(mydict)
myint = 'abc'
print(myint, type(myint))
print(mylist[2], 'list[2]')
pri... |
N=int(input())
S=input()
count=1
for n in range(1,N):
if S[n]!=S[n-1]:
count+=1
print(count) | n = int(input())
s = input()
count = 1
for n in range(1, N):
if S[n] != S[n - 1]:
count += 1
print(count) |
# Python program to enter basic salary and calculate gross salary of an employee algorithm.
# dearness allowance is 40% of basic salary
# house rent allowance is 20% of basic salary
basic_salary=20000
dearness_allowance=(40*basic_salary)/100
house_rent=(20*basic_salary)/100
gross_salary=house_rent+dearness_al... | basic_salary = 20000
dearness_allowance = 40 * basic_salary / 100
house_rent = 20 * basic_salary / 100
gross_salary = house_rent + dearness_allowance + basic_salary
print('Dearness Allowance 40 % of Basic Salary : {}'.format(float(dearness_allowance)))
print('House Rent 20 % of Basic Salary : {}'.format(float(house_ren... |
#!/usr/bin/env python3
for i in range(0,5):
print("{}: Hello world from Python3".format(i+1))
| for i in range(0, 5):
print('{}: Hello world from Python3'.format(i + 1)) |
t = int(input())
for _ in range(t):
n = int(input())
if n==1:
print(1)
elif(n&1):
print(n//2 + 1)
else:
print(n//2)
| t = int(input())
for _ in range(t):
n = int(input())
if n == 1:
print(1)
elif n & 1:
print(n // 2 + 1)
else:
print(n // 2) |
class Distributor:
def __init__(self, partDB):
self.partDB = partDB
def name(self):
return self.__class__.__name__.lower()
def matchPartNumber(self, data):
return None
def matchBarCode(self, data):
return None
def getData(self, distributorPartNumber):
ret... | class Distributor:
def __init__(self, partDB):
self.partDB = partDB
def name(self):
return self.__class__.__name__.lower()
def match_part_number(self, data):
return None
def match_bar_code(self, data):
return None
def get_data(self, distributorPartNumber):
... |
def is11Divisible(sayi):
sum = 0
while sayi > 0:
n = sayi % 10;
if n // 2 == 0:
sum += int(sayi[n])
else:
sum -= int(sayi[n])
n -= 1
if sum == 0 or sum % 11 == 0:
print("True")
else:
print("False")
is11Divisible(837419) | def is11_divisible(sayi):
sum = 0
while sayi > 0:
n = sayi % 10
if n // 2 == 0:
sum += int(sayi[n])
else:
sum -= int(sayi[n])
n -= 1
if sum == 0 or sum % 11 == 0:
print('True')
else:
print('False')
is11_divisible(837419) |
a = 12
b = 3
print ( a + b) # 15
print ( a - b) # 9
print ( a * b) # 36
print ( a / b) # 4.0 result is float
print ( a // b) # 4 integer division, rounded down towards minus infinity , result is integer
print ( a % b) # 0 modulo: the remainder after integer division
print() # empty line
for i in range(1, ... | a = 12
b = 3
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print()
for i in range(1, 4):
print(i)
for i in range(1, a // b):
print(i)
for i in range(1, a / b):
print(i) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.