content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
'simple demo of using map to create instances of objects'
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print("Woof! %s is barking!" % self.name)
dogs = list(map(Dog, ['rex', 'rover', 'ranger']))
| """simple demo of using map to create instances of objects"""
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print('Woof! %s is barking!' % self.name)
dogs = list(map(Dog, ['rex', 'rover', 'ranger'])) |
#!/usr/bin/python3
max_integer = __import__('6-max_integer').max_integer
print(max_integer([1, 2, 3, 4]))
print(max_integer([1, 3, 4, 2]))
| max_integer = __import__('6-max_integer').max_integer
print(max_integer([1, 2, 3, 4]))
print(max_integer([1, 3, 4, 2])) |
try:
# Check if the basestring type if available, this will fail in python3
basestring
except NameError:
basestring = str
class ControlFileParams:
generalParams = "GeneralParams"
spawningBlockname = "SpawningParams"
simulationBlockname = "SimulationParams"
clusteringBlockname = "clustering... | try:
basestring
except NameError:
basestring = str
class Controlfileparams:
general_params = 'GeneralParams'
spawning_blockname = 'SpawningParams'
simulation_blockname = 'SimulationParams'
clustering_blockname = 'clusteringTypes'
class Generalparams:
mandatory = {'restart': 'bool', 'output... |
num = int(input())
if num == 0:
print("zero")
elif num == 1:
print("one")
elif num == 2:
print("two")
elif num == 3:
print("three")
elif num == 4:
print("four")
elif num == 5:
print("five")
elif num == 6:
print("six")
elif num == 7:
print("seven")
elif num == 8:
print("eight")
elif ... | num = int(input())
if num == 0:
print('zero')
elif num == 1:
print('one')
elif num == 2:
print('two')
elif num == 3:
print('three')
elif num == 4:
print('four')
elif num == 5:
print('five')
elif num == 6:
print('six')
elif num == 7:
print('seven')
elif num == 8:
print('eight')
elif n... |
# -*- coding:utf-8 -*-
"""
Description:
Exceptions
Usage:
from AntShares.Exceptions import *
"""
class WorkIdError(Exception):
"""Work Id Error"""
def __init__(self, info):
super(Exception, self).__init__(info)
self.error_code = 0x0002
class OutputError(Exception):
"""Output Error... | """
Description:
Exceptions
Usage:
from AntShares.Exceptions import *
"""
class Workiderror(Exception):
"""Work Id Error"""
def __init__(self, info):
super(Exception, self).__init__(info)
self.error_code = 2
class Outputerror(Exception):
"""Output Error"""
def __init__(self, ... |
# Crie um progrmaa que leia dois numeros e mostra a soma entre eles
n1 = int(input('Digite o primeiro numero: '))
n2 = int(input('Digite o segundo numero: '))
s = n1 + n2
print('A soma de \033[31m{}\033[m e \033[34m{}\033[m eh de \033[32m{}\033[m ' .format(n1, n2, s))
| n1 = int(input('Digite o primeiro numero: '))
n2 = int(input('Digite o segundo numero: '))
s = n1 + n2
print('A soma de \x1b[31m{}\x1b[m e \x1b[34m{}\x1b[m eh de \x1b[32m{}\x1b[m '.format(n1, n2, s)) |
# TODO(dan): Sort out how this displays in tracebacks, it's terrible
class ValidationError(Exception):
def __init__(self, errors, exc=None):
self.errors = errors
self.exc = exc
self._str = str(exc) if exc is not None else '' + ', '.join(
[str(e) for e in errors])
def __str_... | class Validationerror(Exception):
def __init__(self, errors, exc=None):
self.errors = errors
self.exc = exc
self._str = str(exc) if exc is not None else '' + ', '.join([str(e) for e in errors])
def __str__(self):
return self._str |
#
# PySNMP MIB module SONUS-NTP-SERVICES-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SONUS-NTP-SERVICES-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:02:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_union, value_range_constraint, constraints_intersection) ... |
JSVIZ1='''<script type="text/javascript">
function go() {
var zoomCanvas = document.getElementById('canvas');
origZoomChart = new Scribl(zoomCanvas, 100);
//origZoomChart.scale.min = 0;
// origZoomChart.scale.max = 12000;
'''
JSVIZ2='''
origZoomChart.scrollable =... | jsviz1 = '<script type="text/javascript">\n\t\t function go() {\n var zoomCanvas = document.getElementById(\'canvas\');\n origZoomChart = new Scribl(zoomCanvas, 100);\n //origZoomChart.scale.min = 0;\n\t // origZoomChart.scale.max = 12000;\n'
jsviz2 = '\n origZoomChart.scr... |
"""Default constants used in this library.
Exponential Coulomb interaction.
v(x) = amplitude * exp(-abs(x) * kappa)
See also ext_potentials.exp_hydrogenic. Further details in:
Thomas E Baker, E Miles Stoudenmire, Lucas O Wagner, Kieron Burke,
and Steven R White. One-dimensional mimicking of electronic structure:... | """Default constants used in this library.
Exponential Coulomb interaction.
v(x) = amplitude * exp(-abs(x) * kappa)
See also ext_potentials.exp_hydrogenic. Further details in:
Thomas E Baker, E Miles Stoudenmire, Lucas O Wagner, Kieron Burke,
and Steven R White. One-dimensional mimicking of electronic structure:... |
def catalan_rec(n):
if n <= 1:
return 1
res = 0
for i in range(n):
res += catalan_rec(i) * catalan_rec(n-i-1)
return res
def catalan_rec_td(n, arr):
if n <= 1:
return 1
if arr[n] > 0:
return arr[n]
res = 0
for i in range(n):
res += catalan_rec_td(i, arr) * catalan_rec_td(n-i-1,... | def catalan_rec(n):
if n <= 1:
return 1
res = 0
for i in range(n):
res += catalan_rec(i) * catalan_rec(n - i - 1)
return res
def catalan_rec_td(n, arr):
if n <= 1:
return 1
if arr[n] > 0:
return arr[n]
res = 0
for i in range(n):
res += catalan_rec... |
# %%
P = {"task.variable_a": "value-used-during-interactive-development"}
# %% tags=["parameters"]
# ---- During automated runs parameters will be injected in this cell ---
# %%
# -----------------------------------------------------------------------
# %%
# Example comment
print(1 + 12 + 123)
# %%
print(f"""variable_a... | p = {'task.variable_a': 'value-used-during-interactive-development'}
print(1 + 12 + 123)
print(f"variable_a={P['task.variable_a']}") |
class Solution:
def isValidSerialization(self, preorder: str) -> bool:
return self.isValidSerializationStack(preorder)
'''
Initial, Almost-Optimal, Split Iteration
Look at the question closely.
If i give you a subset from start, will you be able to tell me easily if ... | class Solution:
def is_valid_serialization(self, preorder: str) -> bool:
return self.isValidSerializationStack(preorder)
"\n Initial, Almost-Optimal, Split Iteration\n Look at the question closely.\n If i give you a subset from start, will you be able to tell me easily if its v... |
"""
Shell Sort
Approach: Divide and Conquer
Complexity: O(n2)
"""
def sort_shell(input_arr):
print("""""""""""""""""""""""""")
print("input " + str(input_arr))
print("""""""""""""""""""""""""")
print("""""""""""""""""""""""""")
print("result " + str(input_arr))
print(""""""""""""""""""""""""... | """
Shell Sort
Approach: Divide and Conquer
Complexity: O(n2)
"""
def sort_shell(input_arr):
print('')
print('input ' + str(input_arr))
print('')
print('')
print('result ' + str(input_arr))
print('')
if __name__ == '__main__':
arr = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14]
sort_shell(arr) |
#!/usr/bin/env python3
# Day 22: Binary Tree Zigzag Level Order Traversal
#
# Given a binary tree, return the zigzag level order traversal of its nodes'
# values. (ie, from left to right, then right to left for the next level and
# alternate between).
# Definition for a binary tree node.
class TreeNode:
def __ini... | class Treenode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def zigzag_level_order(self, root: TreeNode) -> [[int]]:
if root is None:
return []
result = [[root.val]]
queue = [r... |
def minion_game(string):
length = len(string)
the_vowel = "AEIOU"
kevin = 0
stuart = 0
for i in range(length):
if string[i] in the_vowel:
kevin = kevin + length - i
else:
stuart = stuart + length - i
if kevin > stuart:
print ("Kevin %d" % kevi... | def minion_game(string):
length = len(string)
the_vowel = 'AEIOU'
kevin = 0
stuart = 0
for i in range(length):
if string[i] in the_vowel:
kevin = kevin + length - i
else:
stuart = stuart + length - i
if kevin > stuart:
print('Kevin %d' % kevin)
... |
class PatchExtractor:
def __init__(self, img, patch_size, stride):
self.img = img
self.size = patch_size
self.stride = stride
def extract_patches(self):
wp, hp = self.shape()
return [self.extract_patch((w, h)) for h in range(hp) for w in range(wp)]
def... | class Patchextractor:
def __init__(self, img, patch_size, stride):
self.img = img
self.size = patch_size
self.stride = stride
def extract_patches(self):
(wp, hp) = self.shape()
return [self.extract_patch((w, h)) for h in range(hp) for w in range(wp)]
def extract_pa... |
class OnegramException(Exception):
pass
# TODO [romeira]: Login exceptions {06/03/18 23:07}
class AuthException(OnegramException):
pass
class AuthFailed(AuthException):
pass
class AuthUserError(AuthException):
pass
class NotSupportedError(OnegramException):
pass
class RequestFailed(OnegramExcep... | class Onegramexception(Exception):
pass
class Authexception(OnegramException):
pass
class Authfailed(AuthException):
pass
class Authusererror(AuthException):
pass
class Notsupportederror(OnegramException):
pass
class Requestfailed(OnegramException):
pass
class Ratelimitederror(RequestFaile... |
# _version.py
# Simon Hulse
# simon.hulse@chem.ox.ac.uk
# Last Edited: Tue 10 May 2022 10:24:50 BST
__version__ = "0.0.6"
| __version__ = '0.0.6' |
def fact(n):
if n == 0:
return(1)
return(n*fact(n-1))
def ncr(n, r):
return(fact(n)/(fact(r)*fact(n-r)))
million = 1000000
n = 0
a = 0
comp = 0
for n in range(100, 0, -1):
for r in range(a, n):
if ncr(n,r) > million:
comp += n-2*r + 1
a = r-1
break
... | def fact(n):
if n == 0:
return 1
return n * fact(n - 1)
def ncr(n, r):
return fact(n) / (fact(r) * fact(n - r))
million = 1000000
n = 0
a = 0
comp = 0
for n in range(100, 0, -1):
for r in range(a, n):
if ncr(n, r) > million:
comp += n - 2 * r + 1
a = r - 1
... |
#!/usr/bin/env python
#
# Copyright 2019 DFKI GmbH.
#
# 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 to use, copy, modify, merg... | log_mode_error = -1
log_mode_info = 1
log_mode_debug = 2
_lines = []
_active = True
_mode = LOG_MODE_INFO
def activate():
global _active
_active = True
def deactivate():
global _active
_active = False
def set_log_mode(mode):
global _mode
_mode = mode
def write_log(*args):
global _active
... |
#
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# 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 right... | original_value = 0
top_resolution = 1
slot_config = {'event_name': {'type': TOP_RESOLUTION, 'remember': True, 'error': 'I couldn\'t find an event called "{}".'}, 'event_month': {'type': ORIGINAL_VALUE, 'remember': True}, 'venue_name': {'type': ORIGINAL_VALUE, 'remember': True}, 'venue_city': {'type': ORIGINAL_VALUE, 'r... |
"""
Examples:
>>> square(1)
1
>>> square(2)
4
>>> square(3)
9
>>> spam = Spam()
>>> spam.eggs()
42
"""
def square(x):
"""
Examples:
>>> square(1)
1
>>> square(2)
4
>>> square(3)
9
"""
return x * x
class Spam(object):
"""
Examples:
>>> spam = Spam()
>>> s... | """
Examples:
>>> square(1)
1
>>> square(2)
4
>>> square(3)
9
>>> spam = Spam()
>>> spam.eggs()
42
"""
def square(x):
"""
Examples:
>>> square(1)
1
>>> square(2)
4
>>> square(3)
9
"""
return x * x
class Spam(object):
"""
Examples:
>>> spam = Spam()
>>> spa... |
''''
def multiplica(a,b):
return a*b
print(multiplica(4,5))
def troca(x,y):
aux = x
x=y
y=aux
x=10
y=20
troca(x,y)
print("X=",x,"e y =",y)
'''
def total_caracteres (x,y,z):
return (len(x)+len(y)+len(z))
| """'
def multiplica(a,b):
return a*b
print(multiplica(4,5))
def troca(x,y):
aux = x
x=y
y=aux
x=10
y=20
troca(x,y)
print("X=",x,"e y =",y)
"""
def total_caracteres(x, y, z):
return len(x) + len(y) + len(z) |
#!/usr/bin/env python3
def encode(message):
encoded_message = ""
i = 0
while (i <= len(message) - 1):
count = 1
ch = message[i]
j = i
while (j < len(message) - 1):
if (message[j] == message[j + 1]):
count = count + 1
j = j + 1
... | def encode(message):
encoded_message = ''
i = 0
while i <= len(message) - 1:
count = 1
ch = message[i]
j = i
while j < len(message) - 1:
if message[j] == message[j + 1]:
count = count + 1
j = j + 1
else:
... |
class MainClass:
class_number = 20
class_string = 'Hello, world'
def get_local_number(self):
return 14
def get_lass_number(self):
return MainClass.class_number
def get_class_string(self):
return MainClass.class_string
| class Mainclass:
class_number = 20
class_string = 'Hello, world'
def get_local_number(self):
return 14
def get_lass_number(self):
return MainClass.class_number
def get_class_string(self):
return MainClass.class_string |
friendly_names = {
"fim_s01e01": "Season 1, Episode 1",
"fim_s01e02": "Season 1, Episode 2",
"fim_s01e03": "Season 1, Episode 3",
"fim_s01e04": "Season 1, Episode 4",
"fim_s01e05": "Season 1, Episode 5",
"fim_s01e06": "Season 1, Episode 6",
"fim_s01e07": "Season 1, Episode 7",
"fim_s01e0... | friendly_names = {'fim_s01e01': 'Season 1, Episode 1', 'fim_s01e02': 'Season 1, Episode 2', 'fim_s01e03': 'Season 1, Episode 3', 'fim_s01e04': 'Season 1, Episode 4', 'fim_s01e05': 'Season 1, Episode 5', 'fim_s01e06': 'Season 1, Episode 6', 'fim_s01e07': 'Season 1, Episode 7', 'fim_s01e08': 'Season 1, Episode 8', 'fim_s... |
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
# Simple brute force
# while val in nums:
# nums.remove(val)
# return (len(nums))
# Trying a 2 pointer approac... | class Solution(object):
def remove_element(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
k = 0
for i in range(len(nums)):
if nums[i] != val:
nums[k] = nums[i]
k += 1
return k |
class SpotUrls:
token='85392160'
CFID='459565'
venice_morning_good='https://camrewinds.cdn-surfline.com/live/wc-venicebeachclose.stream.20191103T162900647.mp4'
venice_static='https://camrewinds.cdn-surfline.com/live/wc-venicebeachclose.stream.20191027T235900139.mp4'
lookup={'breakwater': 'http://ww... | class Spoturls:
token = '85392160'
cfid = '459565'
venice_morning_good = 'https://camrewinds.cdn-surfline.com/live/wc-venicebeachclose.stream.20191103T162900647.mp4'
venice_static = 'https://camrewinds.cdn-surfline.com/live/wc-venicebeachclose.stream.20191027T235900139.mp4'
lookup = {'breakwater': '... |
s = input()
n = len(s)
formulas = s.split('+')
ans = 0
for f in formulas:
for i in range(len(f)):
if f[i] == '0':
break
if i == len(f) - 1:
ans += 1
print(ans)
| s = input()
n = len(s)
formulas = s.split('+')
ans = 0
for f in formulas:
for i in range(len(f)):
if f[i] == '0':
break
if i == len(f) - 1:
ans += 1
print(ans) |
x = int(input('Qual tabuada multiplicar: '))
print('-' * 15)
print('{} x {:2} = {}'.format(x, 1, (x*1)))
print('{} x {:2} = {}'.format(x, 2, (x*2)))
print('{} x {:2} = {}'.format(x, 3, (x*3)))
print('{} x {:2} = {}'.format(x, 4, (x*4)))
print('{} x {:2} = {}'.format(x, 5, (x*5)))
print('{} x {:2} = {}'.format(x, 6, (x*... | x = int(input('Qual tabuada multiplicar: '))
print('-' * 15)
print('{} x {:2} = {}'.format(x, 1, x * 1))
print('{} x {:2} = {}'.format(x, 2, x * 2))
print('{} x {:2} = {}'.format(x, 3, x * 3))
print('{} x {:2} = {}'.format(x, 4, x * 4))
print('{} x {:2} = {}'.format(x, 5, x * 5))
print('{} x {:2} = {}'.format(x, 6, x *... |
def FibonacciSearch(arr, key):
fib2 = 0
fib1 = 1
fib = fib1 + fib2
while (fib < len(arr)):
fib2 = fib1
fib1 = fib
fib = fib1 + fib2
index = -1
while (fib > 1):
i = min(index + fib2, (len(arr)-1))
if (arr[i] < key):
fib = fib1
fib1 =... | def fibonacci_search(arr, key):
fib2 = 0
fib1 = 1
fib = fib1 + fib2
while fib < len(arr):
fib2 = fib1
fib1 = fib
fib = fib1 + fib2
index = -1
while fib > 1:
i = min(index + fib2, len(arr) - 1)
if arr[i] < key:
fib = fib1
fib1 = fib2... |
# from fluprodia import FluidPropertyDiagram
def test_main():
pass
| def test_main():
pass |
"""
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Example 1:
Input: [1,2,3,1]
Output: true
Example 2:
Input: [1,2,3,4]
Output: false
Example 3:
Inpu... | """
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Example 1:
Input: [1,2,3,1]
Output: true
Example 2:
Input: [1,2,3,4]
Output: false
Example 3:
Inpu... |
a=0
pg=[[]]
# input the number of chapters
# input the maximum number of problems per page
x,y=map(int,input().split(' '))
# input the number of problems in each chapter
l=list(map(int,input().split(' ')))
for i in l:
k = [[] for _ in range(100)]
for j in range(i):
k[j//y].append(j+1)
for i in k:
... | a = 0
pg = [[]]
(x, y) = map(int, input().split(' '))
l = list(map(int, input().split(' ')))
for i in l:
k = [[] for _ in range(100)]
for j in range(i):
k[j // y].append(j + 1)
for i in k:
if i != []:
pg.append(i)
for i in range(len(pg)):
if i in pg[i]:
a += 1
print(a... |
# Import Data
commands = []
with open('../input/day_2.txt') as f:
lines = f.read().splitlines()
for line in lines:
splitline = line.split(" ")
splitline[1] = int(splitline[1])
commands.append(splitline)
# Process Data
positionHorizontal = 0
positionVertical = 0
for command in commands:
... | commands = []
with open('../input/day_2.txt') as f:
lines = f.read().splitlines()
for line in lines:
splitline = line.split(' ')
splitline[1] = int(splitline[1])
commands.append(splitline)
position_horizontal = 0
position_vertical = 0
for command in commands:
direction = command[0]
... |
def product(fracs):
t = reduce(lambda x, y: x * y, fracs, 1)
return t.numerator, t.denominator
| def product(fracs):
t = reduce(lambda x, y: x * y, fracs, 1)
return (t.numerator, t.denominator) |
#Copyright 2010 Google Inc.
#
#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 writing, softw... | def slugify(inStr):
removelist = ['a', 'an', 'as', 'at', 'before', 'but', 'by', 'for', 'from', 'is', 'in', 'into', 'like', 'of', 'off', 'on', 'onto', 'per', 'since', 'than', 'the', 'this', 'that', 'to', 'up', 'via', 'with']
for a in removelist:
aslug = re.sub('\\b' + a + '\\b', '', inStr)
aslug = re... |
'this crashed pychecker from calendar.py in Python 2.2'
class X:
'd'
def test(self, item):
return [e for e in item].__getslice__()
# this crashed in 2.2, but not 2.3
def f(a):
a.a = [x for x in range(2) if x > 1]
| """this crashed pychecker from calendar.py in Python 2.2"""
class X:
"""d"""
def test(self, item):
return [e for e in item].__getslice__()
def f(a):
a.a = [x for x in range(2) if x > 1] |
#!/usr/bin/env python3
def round_down_to_even(value):
return value & ~1
for _ in range(int(input())):
input() # don't need n
a = list(map(int, input().split()))
for i in range(0, round_down_to_even(len(a)), 2):
if a[i] > a[i + 1]:
a[i], a[i + 1] = a[i + 1], a[i]
print(*a)
| def round_down_to_even(value):
return value & ~1
for _ in range(int(input())):
input()
a = list(map(int, input().split()))
for i in range(0, round_down_to_even(len(a)), 2):
if a[i] > a[i + 1]:
(a[i], a[i + 1]) = (a[i + 1], a[i])
print(*a) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fileencoding=utf_8
"""Add doc string
"""
__author__ = 'M. Kocher'
__copyright__ = ""
__credits__ = ['M. Kocher']
__license__ = 'MIT License'
__maintainer__ = 'M. Kocher'
__email__ = 'Michael.Kocher@me.com'
__version__ = '0.1'
| """Add doc string
"""
__author__ = 'M. Kocher'
__copyright__ = ''
__credits__ = ['M. Kocher']
__license__ = 'MIT License'
__maintainer__ = 'M. Kocher'
__email__ = 'Michael.Kocher@me.com'
__version__ = '0.1' |
num = [int(x) for x in input("Enter the Numbers : ").split()]
index=[int(x) for x in input("Enter the Index : ").split()]
target=[]
for i in range(len(num)):
target.insert(index[i], num[i])
print("The Target array is :",target)
| num = [int(x) for x in input('Enter the Numbers : ').split()]
index = [int(x) for x in input('Enter the Index : ').split()]
target = []
for i in range(len(num)):
target.insert(index[i], num[i])
print('The Target array is :', target) |
def func(param1=True, param2="default val"):
"""Description of func with docstring groups style (Googledoc).
Parameters
----------
param1 :
descr of param1 that has True for default value
param2 :
descr of param2 (Default value = 'default val')
Returns
-------
type
... | def func(param1=True, param2='default val'):
"""Description of func with docstring groups style (Googledoc).
Parameters
----------
param1 :
descr of param1 that has True for default value
param2 :
descr of param2 (Default value = 'default val')
Returns
-------
type
... |
# Python Program to find Power of a Number
number = int(input(" Please Enter any Positive Integer : "))
exponent = int(input(" Please Enter Exponent Value : "))
power = 1
for i in range(1, exponent + 1):
power = power * number
print("The Result of {0} Power {1} = {2}".format(number, exponent, power))
# by a... | number = int(input(' Please Enter any Positive Integer : '))
exponent = int(input(' Please Enter Exponent Value : '))
power = 1
for i in range(1, exponent + 1):
power = power * number
print('The Result of {0} Power {1} = {2}'.format(number, exponent, power)) |
# anything above 0xa0 is printed as Unicode by CPython
# the abobe is CPython implementation detail, stick to ASCII
for c in range(0x80):
print("0x%02x: %s" % (c, repr(chr(c))))
print("PASS") | for c in range(128):
print('0x%02x: %s' % (c, repr(chr(c))))
print('PASS') |
# Title : Linked list :- delete element at front and back of a list
# Author : Kiran raj R.
# Date : 30:10:2020
class Node:
"""Create a node with value provided, the pointer to next is set to None"""
def __init__(self, value):
self.value = value
self.next = None
class Simply_linked_list:
... | class Node:
"""Create a node with value provided, the pointer to next is set to None"""
def __init__(self, value):
self.value = value
self.next = None
class Simply_Linked_List:
"""create a empty singly linked list """
def __init__(self):
self.head = None
def print_list(se... |
TEMPLATE = """
# Related Pages
Here is a list of all related documentation pages:
{% for page in nodes -%}
* [*{{page.title}}*]({{page.url}}) {{page.brief}}
{% endfor -%}
"""
| template = '\n# Related Pages\n\nHere is a list of all related documentation pages:\n\n{% for page in nodes -%}\n* [*{{page.title}}*]({{page.url}}) {{page.brief}}\n{% endfor -%}\n' |
'''
URL: https://leetcode.com/problems/reverse-words-in-a-string-iii/
Difficulty: Easy
Description: Reverse Words in a String III
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCod... | """
URL: https://leetcode.com/problems/reverse-words-in-a-string-iii/
Difficulty: Easy
Description: Reverse Words in a String III
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCod... |
"""Top-level package for Copernicus Marine ToolBox."""
__author__ = """E.U. Copernicus Marine Service Information"""
__email__ = 'servicedesk.cmems@mercator-ocean.eu'
__version__ = '0.1.17'
| """Top-level package for Copernicus Marine ToolBox."""
__author__ = 'E.U. Copernicus Marine Service Information'
__email__ = 'servicedesk.cmems@mercator-ocean.eu'
__version__ = '0.1.17' |
# PROCURANDO UMA STRING DENTRO DA OUTRA
nome = str(input('Digite seu nome: ').strip().lower())
print("silva" in nome.split()) # DESSA MANEIRA EVITA-SE QUE SILVA SEJA CONFUNDIDO DENTRO DE OUTRA STRING.
| nome = str(input('Digite seu nome: ').strip().lower())
print('silva' in nome.split()) |
'''THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE
DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OT... | """THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE
DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OT... |
class Node:
def __init__(self, ch):
self.ch = ch
self.children = {}
self.isWordTerminal = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = Node('\0')
def insert(self, word: str) -> None:
"""
... | class Node:
def __init__(self, ch):
self.ch = ch
self.children = {}
self.isWordTerminal = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = node('\x00')
def insert(self, word: str) -> None:
"""
... |
#
# PySNMP MIB module HP-ICF-CONNECTION-RATE-FILTER (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-CONNECTION-RATE-FILTER
# Produced by pysmi-0.3.4 at Wed May 1 13:33:37 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ve... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_union, constraints_intersection, value_range_constraint) ... |
_base_ = [
'../_base_/datasets/togal.py',
'../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py'
]
# model settings
norm_cfg = dict(type='BN', requires_grad=True)
model = dict(
type='EncoderDecoder',
pretrained=None,
backbone=dict(
type='Unet',
encoder_name="tu-tf_effici... | _base_ = ['../_base_/datasets/togal.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py']
norm_cfg = dict(type='BN', requires_grad=True)
model = dict(type='EncoderDecoder', pretrained=None, backbone=dict(type='Unet', encoder_name='tu-tf_efficientnetv2_b3', encoder_depth=5), decode_head=dict(type=... |
class DimFieldModel:
def __init__(
self,
*kwargs,
field_key: str,
project_id: str,
name: str,
control_type: str,
default_value: str = None,
counted_character: bool,
counted_character_date_from_key: int,
counted_character_time_from_key: ... | class Dimfieldmodel:
def __init__(self, *kwargs, field_key: str, project_id: str, name: str, control_type: str, default_value: str=None, counted_character: bool, counted_character_date_from_key: int, counted_character_time_from_key: int, counted_character_date_to_key: int, counted_character_time_to_key: int, count... |
nome = input('what is your name? ')
idade = input('how old are you ' + nome + '?')
peso = input('what is your weight {}?'.format(nome) + '?')
print('dados: {}'.format(nome) + ' Weight:' + peso + 'Idade:' + idade)
| nome = input('what is your name? ')
idade = input('how old are you ' + nome + '?')
peso = input('what is your weight {}?'.format(nome) + '?')
print('dados: {}'.format(nome) + ' Weight:' + peso + 'Idade:' + idade) |
""" All the custom exceptions types
"""
class PylasError(Exception):
pass
class UnknownExtraType(PylasError):
pass
class PointFormatNotSupported(PylasError):
pass
class FileVersionNotSupported(PylasError):
pass
class LazPerfNotFound(PylasError):
pass
class IncompatibleDataFormat(PylasErr... | """ All the custom exceptions types
"""
class Pylaserror(Exception):
pass
class Unknownextratype(PylasError):
pass
class Pointformatnotsupported(PylasError):
pass
class Fileversionnotsupported(PylasError):
pass
class Lazperfnotfound(PylasError):
pass
class Incompatibledataformat(PylasError):
... |
# common
classes_file = './data/classes/voc.names'
num_classes = 1
input_image_h = 448
input_image_w = 448
down_ratio = 4
max_objs = 150
ot_nodes = ['detector/hm/Sigmoid', "detector/wh/Relu", "detector/reg/Relu"]
moving_ave_decay = 0.9995
# train
train_data_file = './data/dataset/voc_train.txt'
batch_size =... | classes_file = './data/classes/voc.names'
num_classes = 1
input_image_h = 448
input_image_w = 448
down_ratio = 4
max_objs = 150
ot_nodes = ['detector/hm/Sigmoid', 'detector/wh/Relu', 'detector/reg/Relu']
moving_ave_decay = 0.9995
train_data_file = './data/dataset/voc_train.txt'
batch_size = 4
epochs = 80
lr_type = 'exp... |
# _*_ coding=utf-8 _*_
class Config():
def __init__(self):
self.device = '1'
self.data_dir = '../data'
self.logging_dir = 'log'
self.samples_dir = 'samples'
self.testing_dir = 'test_samples'
self.checkpt_dir = 'checkpoints'
self.max_srclen = 25
se... | class Config:
def __init__(self):
self.device = '1'
self.data_dir = '../data'
self.logging_dir = 'log'
self.samples_dir = 'samples'
self.testing_dir = 'test_samples'
self.checkpt_dir = 'checkpoints'
self.max_srclen = 25
self.max_tgtlen = 25
se... |
t1 = ('OI', 2.0, [40, 50])
print(t1[2:])
t = 1, 4, "THiago"
tupla1 = 1, 2, 3, 4, 5
tulpla2 = 6, 7, 8, 9, 10
print(tupla1 + tulpla2) # concatena
| t1 = ('OI', 2.0, [40, 50])
print(t1[2:])
t = (1, 4, 'THiago')
tupla1 = (1, 2, 3, 4, 5)
tulpla2 = (6, 7, 8, 9, 10)
print(tupla1 + tulpla2) |
yformat = u"%(d1)i\xB0%(d2)02i'%(d3)02.2f''"
xformat = u"%(hour)ih%(minute)02im%(second)02.2fs"
def getFormatDict(tick):
degree1 = int(tick)
degree2 = int((tick * 100 - degree1 * 100))
degree3 = ((tick * 10000 - degree1 * 10000 - degree2 * 100))
tick = (tick + 360) % 360
totalhours = float(tick * 24.0 / 360)
ho... | yformat = u"%(d1)i°%(d2)02i'%(d3)02.2f''"
xformat = u'%(hour)ih%(minute)02im%(second)02.2fs'
def get_format_dict(tick):
degree1 = int(tick)
degree2 = int(tick * 100 - degree1 * 100)
degree3 = tick * 10000 - degree1 * 10000 - degree2 * 100
tick = (tick + 360) % 360
totalhours = float(tick * 24.0 / 3... |
print('MyMy',end=' ')
print('Popsicle')
print('Balloon','Helium','Blimp',sep=' and ')
| print('MyMy', end=' ')
print('Popsicle')
print('Balloon', 'Helium', 'Blimp', sep=' and ') |
N,M=map(int,input().split())
A=[int(input()) for i in range(M)][::-1]
ans=[]
s=set()
for a in A:
if a not in s:ans.append(a)
s.add(a)
for i in range(1,N+1):
if i not in s:ans.append(i)
print(*ans,sep="\n") | (n, m) = map(int, input().split())
a = [int(input()) for i in range(M)][::-1]
ans = []
s = set()
for a in A:
if a not in s:
ans.append(a)
s.add(a)
for i in range(1, N + 1):
if i not in s:
ans.append(i)
print(*ans, sep='\n') |
#fix me.. but for now lets just pass the data back..
def compress(data):
return data
def decompress(data):
return data
| def compress(data):
return data
def decompress(data):
return data |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 1 09:26:03 2022
@author: thejorabek
"""
'''son=10
print(son,type(son))
son=3.14
print(son,type(son))
son='Salom Foundationchilar'
print(son,type(son))
son=True
print(son,type(son))
son=int()
print(son,type(son))
print("Assalom",123,3.14,True,sep='... | """
Created on Tue Feb 1 09:26:03 2022
@author: thejorabek
"""
'son=10\nprint(son,type(son))\nson=3.14\nprint(son,type(son))\nson=\'Salom Foundationchilar\'\nprint(son,type(son))\nson=True\nprint(son,type(son))\nson=int()\nprint(son,type(son))\nprint("Assalom",123,3.14,True,sep=\'salom\')\nprint(1,2,3,4,5,6,7,8,9,10,... |
print('Hello World!!!')
if True:
print('FROM if')
num = 1
while num <= 10:
print(num)
num += 1
list_ = [1, 2, 3, 4, 5]
for i in range(1, 7):
print(i)
| print('Hello World!!!')
if True:
print('FROM if')
num = 1
while num <= 10:
print(num)
num += 1
list_ = [1, 2, 3, 4, 5]
for i in range(1, 7):
print(i) |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 29 10:35:53 2017
@author: User
"""
L = [[1,2], [35,4,78], [7,8,1,10],[2,3], [9,1,45]]
#def testA(L):
# aFactor = 2
# for m in L:
# for ind, element in enumerate(m):
# newElement = element*aFactor
# m.pop(ind) # this works... | """
Created on Fri Dec 29 10:35:53 2017
@author: User
"""
l = [[1, 2], [35, 4, 78], [7, 8, 1, 10], [2, 3], [9, 1, 45]]
def test_a(L):
for m in L:
for (ind, element) in enumerate(m):
m[ind] *= 2
return L
print(test_a(L)) |
# -*- coding: utf-8 -*-
# Authors: Y. Jia <ytjia.zju@gmail.com>
def binary_search(arr, target, begin=None, end=None):
"""
:param arr:
:param target:
:param begin:
:param end:
:return:
"""
if begin is None:
begin = 0
if end is None:
end = len(arr) - 1
if end <... | def binary_search(arr, target, begin=None, end=None):
"""
:param arr:
:param target:
:param begin:
:param end:
:return:
"""
if begin is None:
begin = 0
if end is None:
end = len(arr) - 1
if end < begin or end < 0:
return (False, None)
elif end == begi... |
#
# PySNMP MIB module LOWPAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/LOWPAN-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:58:25 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:... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, constraints_union, value_range_constraint, value_size_constraint) ... |
def split_targets(targets, target_sizes):
results = []
offset = 0
for size in target_sizes:
results.append(targets[offset:offset + size])
offset += size
return results
| def split_targets(targets, target_sizes):
results = []
offset = 0
for size in target_sizes:
results.append(targets[offset:offset + size])
offset += size
return results |
class Aggrraidtype(basestring):
"""
raid_dp|raid4
Possible values:
<ul>
<li> "raid_dp" ,
<li> "raid4" ,
<li> "raid0" ,
<li> "mixed_raid_type"
</ul>
"""
@staticmethod
def get_api_name():
return "aggrraidtype"
| class Aggrraidtype(basestring):
"""
raid_dp|raid4
Possible values:
<ul>
<li> "raid_dp" ,
<li> "raid4" ,
<li> "raid0" ,
<li> "mixed_raid_type"
</ul>
"""
@staticmethod
def get_api_name():
return 'aggrraidtype' |
"""
interploation search
# interploation and binary are both require a SORTED list
let said you have the follow phone number prefix array, and you are looking for 1144
0011, 0022, 0033, 1144, 1166, 1188, 3322, 3344, 3399
instead of using binary search in the middle, or linear search from the left... | """
interploation search
# interploation and binary are both require a SORTED list
let said you have the follow phone number prefix array, and you are looking for 1144
0011, 0022, 0033, 1144, 1166, 1188, 3322, 3344, 3399
instead of using binary search in the middle, or linear search from the left... |
# This sample tests the case where a finally clause contains some conditional
# logic that narrows the type of an expression. This narrowed type should
# persist after the finally clause.
def func1():
file = None
try:
file = open("test.txt")
except Exception:
return None
finally:
... | def func1():
file = None
try:
file = open('test.txt')
except Exception:
return None
finally:
if file:
file.close()
reveal_type(file, expected_text='TextIOWrapper')
def func2():
file = None
try:
file = open('test.txt')
except Exception:
... |
def remove_passwords(instances):
clean_instances = []
for instance in instances:
clean_instance = {}
for k in instance.keys():
if k != 'password':
clean_instance[k] = instance[k]
clean_instances.append(clean_instance)
return clean_instances
| def remove_passwords(instances):
clean_instances = []
for instance in instances:
clean_instance = {}
for k in instance.keys():
if k != 'password':
clean_instance[k] = instance[k]
clean_instances.append(clean_instance)
return clean_instances |
class cURL:
def __init__(self, url_='.'):
self.url = url_
def replace(self, replaceURL_, start_, end_):
'''
example: 'https://www.google.com/search'
https:// -> -1
www.google.com -> 0
search -> 1
'''
if start_ == -1:
... | class Curl:
def __init__(self, url_='.'):
self.url = url_
def replace(self, replaceURL_, start_, end_):
"""
example: 'https://www.google.com/search'
https:// -> -1
www.google.com -> 0
search -> 1
"""
if start_ == -1:
start_ = 0
... |
def get_primes(n):
# Based on Eratosthenes Sieve
# Initially all numbers are prime until proven otherwise
# False = Prime number, True = Compose number
nonprimes = n * [False]
count = 0
nonprimes[0] = nonprimes[1] = True
prime_numbers = []
for i in range(2, n):
if not nonprimes[... | def get_primes(n):
nonprimes = n * [False]
count = 0
nonprimes[0] = nonprimes[1] = True
prime_numbers = []
for i in range(2, n):
if not nonprimes[i]:
prime_numbers.append(i)
count += 1
for j in range(2 * i, n, i):
nonprimes[j] = True
re... |
'''DATALOADERS'''
def LoadModel(name):
# print(name)
# classes = []
# D = 0
# H = 0
# W = 0
# Height = 0
# Width = 0
# Bands = 0
# samples = 0
if name == 'PaviaU':
classes = []
#Size of 3D images
D = 610
H = 340
... | """DATALOADERS"""
def load_model(name):
if name == 'PaviaU':
classes = []
d = 610
h = 340
w = 103
height = 27
width = 21
bands = 103
samples = 2400
patch = 300000
elif name == 'IndianPines':
classes = ['Undefined', 'Alfalfa', 'Corn... |
parallel = dict(
data=1,
pipeline=1,
tensor=dict(size=4, mode='2d'),
)
| parallel = dict(data=1, pipeline=1, tensor=dict(size=4, mode='2d')) |
# -*- coding: utf-8 -*-
project = "thumbtack-client"
copyright = "2019, The MITRE Corporation"
author = "The MITRE Corporation"
version = "0.3.0"
release = "0.3.0"
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.napoleon",
"sphinx.ext.viewcode",
]
templates_path = ["_templates"]
source_suffix = ".rst"... | project = 'thumbtack-client'
copyright = '2019, The MITRE Corporation'
author = 'The MITRE Corporation'
version = '0.3.0'
release = '0.3.0'
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinx.ext.viewcode']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
language = None
exclud... |
def main():
result = 0
with open("input.txt") as input_file:
for x in input_file:
x = int(x)
while True:
x = x // 3 - 2
if x < 0:
break
result += x
print(result)
if __name__ == "__main__":
main()
| def main():
result = 0
with open('input.txt') as input_file:
for x in input_file:
x = int(x)
while True:
x = x // 3 - 2
if x < 0:
break
result += x
print(result)
if __name__ == '__main__':
main() |
DATAMART_AUGMENT_PROCESS = 'DATAMART_AUGMENT_PROCESS'
# ----------------------------------------------
# Related to the "Add User Dataset" process
# ----------------------------------------------
ADD_USER_DATASET_PROCESS = 'ADD_USER_DATASET_PROCESS'
ADD_USER_DATASET_PROCESS_NO_WORKSPACE = 'ADD_USER_DATASET_PROCESS_NO... | datamart_augment_process = 'DATAMART_AUGMENT_PROCESS'
add_user_dataset_process = 'ADD_USER_DATASET_PROCESS'
add_user_dataset_process_no_workspace = 'ADD_USER_DATASET_PROCESS_NO_WORKSPACE'
new_dataset_doc_path = 'new_dataset_doc_path'
dataset_name_from_ui = 'name'
dataset_name = 'dataset_name'
skip_create_new_config = '... |
alpha_num_dict = {
'a':1,
'b':2,
'c':3
}
alpha_num_dict['a'] = 10
print(alpha_num_dict['a']) | alpha_num_dict = {'a': 1, 'b': 2, 'c': 3}
alpha_num_dict['a'] = 10
print(alpha_num_dict['a']) |
"""
Time:
Best: O(n)
Average: O(n^2)
Worst: O(n^2)
Space:
O(1)
Stable:
Yes
Worst Case Scenario:
Reverse Sorted Array
Algorithm Overview:
This algorithm works like how a person would normally sort a hand of cards from left to right.
You take the second card and compare with all the ... | """
Time:
Best: O(n)
Average: O(n^2)
Worst: O(n^2)
Space:
O(1)
Stable:
Yes
Worst Case Scenario:
Reverse Sorted Array
Algorithm Overview:
This algorithm works like how a person would normally sort a hand of cards from left to right.
You take the second card and compare with all the ... |
# https://leetcode.com/problems/minimum-size-subarray-sum/
class Solution:
def minSubArrayLen(self, target: int, nums: list[int]) -> int:
min_len = float('inf')
curr_sum = 0
nums_added = 0
for idx in range(len(nums)):
num = nums[idx]
if num >= target:
... | class Solution:
def min_sub_array_len(self, target: int, nums: list[int]) -> int:
min_len = float('inf')
curr_sum = 0
nums_added = 0
for idx in range(len(nums)):
num = nums[idx]
if num >= target:
return 1
curr_sum += num
... |
#!/usr/bin/env python
# encoding: utf-8
class Dynamic(str):
"""Wrapper for the strings that need to be dynamically interpreted by the generated Python files."""
pass | class Dynamic(str):
"""Wrapper for the strings that need to be dynamically interpreted by the generated Python files."""
pass |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""View module for Find Convex Hull program
Notes
-----
Comments are omitted because code is self-explanatory.
"""
colors = [
'aquamarine',
'azure',
'blue',
'brown',
'chartreuse',
'chocolate',
'coral',
'crimson',
'cyan',
'darkblue',... | """View module for Find Convex Hull program
Notes
-----
Comments are omitted because code is self-explanatory.
"""
colors = ['aquamarine', 'azure', 'blue', 'brown', 'chartreuse', 'chocolate', 'coral', 'crimson', 'cyan', 'darkblue', 'darkgreen', 'fuchsia', 'gold', 'green', 'grey', 'indigo', 'khaki', 'lavender', 'lightb... |
class DataGridSelectionUnit(Enum,IComparable,IFormattable,IConvertible):
"""
Defines constants that specify whether cells,rows,or both,are used for selection in a System.Windows.Controls.DataGrid control.
enum DataGridSelectionUnit,values: Cell (0),CellOrRowHeader (2),FullRow (1)
"""
def __eq__(self,*arg... | class Datagridselectionunit(Enum, IComparable, IFormattable, IConvertible):
"""
Defines constants that specify whether cells,rows,or both,are used for selection in a System.Windows.Controls.DataGrid control.
enum DataGridSelectionUnit,values: Cell (0),CellOrRowHeader (2),FullRow (1)
"""
def __eq__(self,... |
class Solution:
def sortArrayByParity(self, A: List[int]) -> List[int]:
l = 0
r = len(A) - 1
while l < r:
if A[l] % 2 == 1 and A[r] % 2 == 0:
A[l], A[r] = A[r], A[l]
if A[l] % 2 == 0:
l += 1
if A[r] % 2 == 1:
r -= 1
return A
| class Solution:
def sort_array_by_parity(self, A: List[int]) -> List[int]:
l = 0
r = len(A) - 1
while l < r:
if A[l] % 2 == 1 and A[r] % 2 == 0:
(A[l], A[r]) = (A[r], A[l])
if A[l] % 2 == 0:
l += 1
if A[r] % 2 == 1:
... |
peso = float(input('Peso em Kilogramas: '))
altura = float(input('Altura em Centimetros: '))
imc = peso / ((altura / 100) ** 2)
print('O IMC esta em {:.2f}'.format(imc))
if imc < 18.5:
print('Abaixo do Peso!')
elif imc <= 25:
print('Peso Ideal')
elif imc <= 30:
print('Sobrepeso')
elif imc <= 40:
print('... | peso = float(input('Peso em Kilogramas: '))
altura = float(input('Altura em Centimetros: '))
imc = peso / (altura / 100) ** 2
print('O IMC esta em {:.2f}'.format(imc))
if imc < 18.5:
print('Abaixo do Peso!')
elif imc <= 25:
print('Peso Ideal')
elif imc <= 30:
print('Sobrepeso')
elif imc <= 40:
print('Ob... |
"""
Place class. Part of the StoryTechnologies project.
August 17, 2019
Brett Alistair Kromkamp (brett.kromkamp@gmail.com)
"""
class TimeInterval:
def __init__(self, from_time_point: str, to_time_point: str) -> None:
self.from_time_point = from_time_point
self.to_time_point = to_time_point
| """
Place class. Part of the StoryTechnologies project.
August 17, 2019
Brett Alistair Kromkamp (brett.kromkamp@gmail.com)
"""
class Timeinterval:
def __init__(self, from_time_point: str, to_time_point: str) -> None:
self.from_time_point = from_time_point
self.to_time_point = to_time_point |
class Menu(object):
def __init__(self):
gameList = None;
def _populateGameList(self):
pass
def chooseGame(self):
pass
def start(self):
pass
| class Menu(object):
def __init__(self):
game_list = None
def _populate_game_list(self):
pass
def choose_game(self):
pass
def start(self):
pass |
class Solution:
# @param {integer[]} candidates
# @param {integer} target
# @return {integer[][]}
def combinationSum2(self, candidates, target):
self.results = []
candidates.sort()
self.combination(candidates, target, 0, [])
return self.results
def combination(self,... | class Solution:
def combination_sum2(self, candidates, target):
self.results = []
candidates.sort()
self.combination(candidates, target, 0, [])
return self.results
def combination(self, candidates, target, start, result):
if target == 0:
self.results.append(... |
# -*- coding: utf-8 -*-
"""
file_utils module to hold simple bioinformatics course text file parsing class
"""
INPUT_STRING = 'Input'
OUTPUT_STRING = 'Output'
class FileUtil(object):
"""
Holds I/O values parsed from course text files for example problems
Initialized with a text file, parses 'Input' and '... | """
file_utils module to hold simple bioinformatics course text file parsing class
"""
input_string = 'Input'
output_string = 'Output'
class Fileutil(object):
"""
Holds I/O values parsed from course text files for example problems
Initialized with a text file, parses 'Input' and 'Output' values to
obje... |
t = int(input())
def solve():
candy = 0
x = input()
r, c = map(int, input().split())
a = []
for _ in range(r):
a.append(input())
for i in range(r):
for j in range(c - 2):
if a[i][j] == '>' and a[i][j + 1] == 'o' and a[i][j + 2] == '<':
candy += 1
... | t = int(input())
def solve():
candy = 0
x = input()
(r, c) = map(int, input().split())
a = []
for _ in range(r):
a.append(input())
for i in range(r):
for j in range(c - 2):
if a[i][j] == '>' and a[i][j + 1] == 'o' and (a[i][j + 2] == '<'):
candy += 1
... |
# Write_a_function
# Created by JKChang
# 14/08/2018, 10:58
# Tag:
# Description: https://www.hackerrank.com/challenges/write-a-function/problem
# In the Gregorian calendar three criteria must be taken into account to identify leap years:
# The year can be evenly divided by 4, is a leap year, unless:
# The year can be... | def is_leap(year):
leap = False
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
leap = True
return leap
year = int(input())
print(is_leap(year)) |
class NorthInDTO(object):
def __init__(self):
self.platformIp = None
self.platformPort = None
def getPlatformIp(self):
return self.platformIp
def setPlatformIp(self, platformIp):
self.platformIp = platformIp
def getPlatformPort(self):
return self.platformPort
... | class Northindto(object):
def __init__(self):
self.platformIp = None
self.platformPort = None
def get_platform_ip(self):
return self.platformIp
def set_platform_ip(self, platformIp):
self.platformIp = platformIp
def get_platform_port(self):
return self.platfor... |
h, m = map(int, input().split())
if h - 1 < 0:
h = 23
m += 15
print(h,m)
elif m - 45 < 0:
h -= 1
m += 15
print(h, m)
else:
m -= 45
print(h, m) | (h, m) = map(int, input().split())
if h - 1 < 0:
h = 23
m += 15
print(h, m)
elif m - 45 < 0:
h -= 1
m += 15
print(h, m)
else:
m -= 45
print(h, m) |
class Settings():
""" This is just variables stored as properties of a class.
It still needs (allthough void) .inputs(), .output() and .build() and defines whatever else is handy.
(It is nice, as in this case, to separate constants from methods.)
"""
def inputs(self):
return None
def output(self):
return ... | class Settings:
""" This is just variables stored as properties of a class.
It still needs (allthough void) .inputs(), .output() and .build() and defines whatever else is handy.
(It is nice, as in this case, to separate constants from methods.)
"""
def inputs(self):
return None
def output(sel... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Advent of Code 2020
Day 4, Part 2
"""
class Passport:
def __init__(self, byr=-1, iyr=-1, eyr=-1, hgt=-1, hfc=-1, ecl=-1, pid=-1, cid=-1):
self.fields = {
'byr': byr,
'iyr': iyr,
'eyr': eyr,
'hgt': hgt,
... | """
Advent of Code 2020
Day 4, Part 2
"""
class Passport:
def __init__(self, byr=-1, iyr=-1, eyr=-1, hgt=-1, hfc=-1, ecl=-1, pid=-1, cid=-1):
self.fields = {'byr': byr, 'iyr': iyr, 'eyr': eyr, 'hgt': hgt, 'hcl': hfc, 'ecl': ecl, 'pid': pid, 'cid': cid}
def parse(line):
fields = line.split()
field... |
class Pessoa:
def __init__(self, nome, email, celular):
self.nome = nome
self.email = email
self.celular = celular
def get_nome(self):
return f"Caro(a) {self.nome}"
def get_email(self):
return(self.email)
def get_celular(self):
return(self.celular)
d... | class Pessoa:
def __init__(self, nome, email, celular):
self.nome = nome
self.email = email
self.celular = celular
def get_nome(self):
return f'Caro(a) {self.nome}'
def get_email(self):
return self.email
def get_celular(self):
return self.celular
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.