content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
'''
This module defines the RentalException class, which handles all exception of the type RentalException.
it does not depend on any other module.
'''
class RentalException(Exception):
'''
RentalException class handles all thrown exceptions of the type RentalException. It inherits the Exception
... | """
This module defines the RentalException class, which handles all exception of the type RentalException.
it does not depend on any other module.
"""
class Rentalexception(Exception):
"""
RentalException class handles all thrown exceptions of the type RentalException. It inherits the Exception
... |
class Loss(object):
def __init__(self):
self.output = 0
self.input = 0
def get_output(self, inp, target):
pass
def get_input_gradient(self, target):
pass
| class Loss(object):
def __init__(self):
self.output = 0
self.input = 0
def get_output(self, inp, target):
pass
def get_input_gradient(self, target):
pass |
#!/user/bin/python
'''Compute the Edit Distance Between Two Strings
The edit-distance between two strings is the minimum number of operations
(insertions, deletions, and substitutions of symbols) to transform one string
into another
'''
# Uses python3
def edit_distance(s, t):
#D[i,0] = i
#D[0,j] = j
m ... | """Compute the Edit Distance Between Two Strings
The edit-distance between two strings is the minimum number of operations
(insertions, deletions, and substitutions of symbols) to transform one string
into another
"""
def edit_distance(s, t):
m = len(s)
n = len(t)
d = []
for i in range(len(s) + 1):
... |
class iron():
def __init__(self,name,kg):
self.kg = kg
self.name = name
def changeKg(self,newValue):
self.kg = newValue
def changeName(self,newName):
self.newName
| class Iron:
def __init__(self, name, kg):
self.kg = kg
self.name = name
def change_kg(self, newValue):
self.kg = newValue
def change_name(self, newName):
self.newName |
def calculate_power(base, power):
if not power:
return 1
if not power % 2:
return calculate_power(base, power // 2) * calculate_power(base, power // 2)
else:
return calculate_power(base, power // 2) * calculate_power(base, power // 2) * base
if __name__ == "__main__":
a = int... | def calculate_power(base, power):
if not power:
return 1
if not power % 2:
return calculate_power(base, power // 2) * calculate_power(base, power // 2)
else:
return calculate_power(base, power // 2) * calculate_power(base, power // 2) * base
if __name__ == '__main__':
a = int(inp... |
class Node:
def __init__(self, data, nextNode=None):
self.data = data
self.next = nextNode
# find middle uses a slow pointer and fast pointer (1 ahead) to find the middle
# element of a singly linked list
def find_middle(self):
slow_pointer = self
fast_pointer = sel... | class Node:
def __init__(self, data, nextNode=None):
self.data = data
self.next = nextNode
def find_middle(self):
slow_pointer = self
fast_pointer = self
while fast_pointer.next and fast_pointer.next.next:
slow_pointer = slow_pointer.next
fast_po... |
def extract_cfg(cfg, prefix, sep='.'):
out = {}
for key,val in cfg.items():
if not key.startswith(prefix): continue
key = key[len(prefix)+len(sep):]
if sep in key or not key: continue
out[key] = val
return out
if __name__=="__main__":
cfg = {
'a.1':'aaa',
'a.2':'bbb',
'a.x.1':'ccc',
'a.x.2':'ddd',... | def extract_cfg(cfg, prefix, sep='.'):
out = {}
for (key, val) in cfg.items():
if not key.startswith(prefix):
continue
key = key[len(prefix) + len(sep):]
if sep in key or not key:
continue
out[key] = val
return out
if __name__ == '__main__':
cfg = ... |
'''
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
'''
# Definition for a binary ... | """
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ 9 20
/ 15 7
"""
class Solution:
def buil... |
class SmMarket:
def __init__(self):
self.name = ""
self.product_dic = {}
def add_category(self, product):
self.product_dic[product.code] = product | class Smmarket:
def __init__(self):
self.name = ''
self.product_dic = {}
def add_category(self, product):
self.product_dic[product.code] = product |
#project
print("welcome to the Band name generator")
city_name = input("Enter the city you were born: ")
pet_name = input("Enter your pet name: ")
print(f"your band name could be {city_name} {pet_name}")
#coding exercise(Print)
print("Day 1 - Python Print Function")
print("The function is declared like this:")... | print('welcome to the Band name generator')
city_name = input('Enter the city you were born: ')
pet_name = input('Enter your pet name: ')
print(f'your band name could be {city_name} {pet_name}')
print('Day 1 - Python Print Function')
print('The function is declared like this:')
print('print("what to print")')
print('Da... |
num1=int(input("Enter first number :- "))
num2=int(input("Enter second number :- "))
print("Which opertation you want apply 1.add, 2.sub, 3.div")
op=input()
def add():
c=num1+num2
print("After Add",c)
def sub():
c=num1-num2
print("After sub",c)
def div():
c=num1/num2
print("After div",c)
def again... | num1 = int(input('Enter first number :- '))
num2 = int(input('Enter second number :- '))
print('Which opertation you want apply 1.add, 2.sub, 3.div')
op = input()
def add():
c = num1 + num2
print('After Add', c)
def sub():
c = num1 - num2
print('After sub', c)
def div():
c = num1 / num2
print... |
def get_odd_and_even_sets(n):
odd_nums = set()
even_nums = set()
for line in range(1, n + 1):
name = input()
name_ascii_sum = sum([ord(char) for char in name])
devised_num = name_ascii_sum // line
if devised_num % 2 == 0:
even_nums.add(devised_num)
else... | def get_odd_and_even_sets(n):
odd_nums = set()
even_nums = set()
for line in range(1, n + 1):
name = input()
name_ascii_sum = sum([ord(char) for char in name])
devised_num = name_ascii_sum // line
if devised_num % 2 == 0:
even_nums.add(devised_num)
else:
... |
class Debugger:
def __init__(self):
self.collectors = {}
def add_collector(self, collector):
self.collectors.update({collector.name: collector})
return self
def get_collector(self, name):
return self.collectors[name]
| class Debugger:
def __init__(self):
self.collectors = {}
def add_collector(self, collector):
self.collectors.update({collector.name: collector})
return self
def get_collector(self, name):
return self.collectors[name] |
# Only these modalities are available for query
ALLOWED_MODALITIES = ['bold', 'T1w', 'T2w']
STRUCTURAL_MODALITIES = ['T1w', 'T2w']
# Name of a subdirectory to hold fetched query results
FETCHED_DIR = 'fetched'
# Name of a subdirectory containing MRIQC group results used as inputs.
INPUTS_DIR = 'inputs'
# Name of the... | allowed_modalities = ['bold', 'T1w', 'T2w']
structural_modalities = ['T1w', 'T2w']
fetched_dir = 'fetched'
inputs_dir = 'inputs'
reports_dir = 'reports'
bids_data_ext = '.tsv'
plot_ext = '.png'
reports_ext = '.html'
input_file_exit_code = 10
output_file_exit_code = 11
query_file_exit_code = 12
fetched_dir_exit_code = 2... |
# Problem Statement: https://www.hackerrank.com/challenges/symmetric-difference/problem
_, M = int(input()), set(map(int, input().split()))
_, N = int(input()), set(map(int, input().split()))
print(*sorted(M ^ N), sep='\n') | (_, m) = (int(input()), set(map(int, input().split())))
(_, n) = (int(input()), set(map(int, input().split())))
print(*sorted(M ^ N), sep='\n') |
# The manage.py of the {{ project_name }} test project
# template context:
project_name = '{{ project_name }}'
project_directory = '{{ project_directory }}'
secret_key = '{{ secret_key }}'
| project_name = '{{ project_name }}'
project_directory = '{{ project_directory }}'
secret_key = '{{ secret_key }}' |
class PaymentStrategy(object):
def get_payment_metadata(self,service_client):
pass
def get_price(self,service_client):
pass
| class Paymentstrategy(object):
def get_payment_metadata(self, service_client):
pass
def get_price(self, service_client):
pass |
#this program demonstrates several functions of the list class
x = [0.0, 3.0, 5.0, 2.5, 3.7]
print(type(x)) #prints datatype of x (list)
x.pop(2) #remove the 3rd element of x (5.0)
print(x)
x.remove(2.5) #remove the element 2.5 (index 2)
print(x)
x.append(1.2) #add a new element to the end (1.2... | x = [0.0, 3.0, 5.0, 2.5, 3.7]
print(type(x))
x.pop(2)
print(x)
x.remove(2.5)
print(x)
x.append(1.2)
print(x)
y = x.copy()
print(y)
print(y.count(0.0))
print(y.index(3.7))
y.sort()
print(y)
y.reverse()
print(y)
y.clear()
print(y) |
# Enter your code here. Read input from STDIN. Print output to STDOUT
size = int(input())
nums = list(map(int, input().split()))
weights = list(map(int, input().split()))
weighted_sum = 0
for i in range(size):
weighted_sum += nums[i] * weights[i]
print(round(weighted_sum / sum(weights), 1))
| size = int(input())
nums = list(map(int, input().split()))
weights = list(map(int, input().split()))
weighted_sum = 0
for i in range(size):
weighted_sum += nums[i] * weights[i]
print(round(weighted_sum / sum(weights), 1)) |
# Lower-level functionality for build config.
# The functions in this file might be referred by tensorflow.bzl. They have to
# be separate to avoid cyclic references.
WITH_XLA_SUPPORT = True
def tf_cuda_tests_tags():
return ["local"]
def tf_sycl_tests_tags():
return ["local"]
def tf_additional_plugin_deps():
... | with_xla_support = True
def tf_cuda_tests_tags():
return ['local']
def tf_sycl_tests_tags():
return ['local']
def tf_additional_plugin_deps():
deps = []
if WITH_XLA_SUPPORT:
deps.append('//tensorflow/compiler/jit')
return deps
def tf_additional_xla_deps_py():
return []
def tf_additi... |
def estimation(text,img_num):
len_text = len(text)
read_time = (len_text/1000) + img_num*0.2
if read_time < 1:
return 1
return round(read_time) | def estimation(text, img_num):
len_text = len(text)
read_time = len_text / 1000 + img_num * 0.2
if read_time < 1:
return 1
return round(read_time) |
numbers = [10, 20, 300, 40, 50]
# random indexing --> O(1) get items if we know the index !!!
print(numbers[4])
# it can store different data types
# numbers[1] = "Adam"
# iteration methods
# for i in range(len(numbers)):
# print(numbers[i])
# for num in numbers:
# print(num)
# remove last two items
print... | numbers = [10, 20, 300, 40, 50]
print(numbers[4])
print(numbers[:-2])
print(numbers[0:2])
print(numbers[2:])
maximum = numbers[0]
for num in numbers:
if num > maximum:
maximum = num
print(maximum) |
''' Example of python control structures '''
a = 5
b = int(input("Enter an integer: "))
# If-then-else statment
if a < b:
print('{} is less than {}'.format(a,b))
elif a > b:
print('{} is greater than {}'.format(a,b))
else:
print('{} is equal to {}'.format(a,b))
# While loop
ii = 0
print("While loop:")
w... | """ Example of python control structures """
a = 5
b = int(input('Enter an integer: '))
if a < b:
print('{} is less than {}'.format(a, b))
elif a > b:
print('{} is greater than {}'.format(a, b))
else:
print('{} is equal to {}'.format(a, b))
ii = 0
print('While loop:')
while ii <= b:
print('Your number =... |
'''
Created on Apr 2, 2021
@author: mballance
'''
class InitializeReq(object):
def __init__(self):
self.module = None
self.entry = None
def dump(self):
pass
@staticmethod
def load(msg) -> 'InitializeReq':
ret = InitializeReq()
if "module"... | """
Created on Apr 2, 2021
@author: mballance
"""
class Initializereq(object):
def __init__(self):
self.module = None
self.entry = None
def dump(self):
pass
@staticmethod
def load(msg) -> 'InitializeReq':
ret = initialize_req()
if 'module' in msg.keys():
... |
# 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:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
ans = True
def tra... | class Solution:
def is_same_tree(self, p: TreeNode, q: TreeNode) -> bool:
ans = True
def traversal(node_p, node_q):
nonlocal ans
if node_p is None and node_q is None:
return
if node_p is None or node_q is None:
ans = False
... |
'''Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line:'''
x = y = z = "Orange"
print(x)
print(y)
print(z) | """Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line:"""
x = y = z = 'Orange'
print(x)
print(y)
print(z) |
#
# @lc app=leetcode id=795 lang=python3
#
# [795] Number of Subarrays with Bounded Maximum
#
# https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/description/
#
# algorithms
# Medium (48.43%)
# Likes: 1143
# Dislikes: 78
# Total Accepted: 40.2K
# Total Submissions: 77.7K
# Testcase Example: ... | class Solution:
def num_subarray_bounded_max(self, nums: List[int], left: int, right: int) -> int:
i = 0
curr = 0
res = 0
for j in range(len(nums)):
if left <= nums[j] <= right:
curr = j - i + 1
res += j - i + 1
elif nums[j] < ... |
class Human:
def __init__(self, xref_id):
self.xref_id = xref_id
self.name = None
self.father = None
self.mother = None
self.pos = None
def __repr__(self):
return "[ {} : {} - {} {} - {} ]".format(
self.xref_id,
self.name,
self... | class Human:
def __init__(self, xref_id):
self.xref_id = xref_id
self.name = None
self.father = None
self.mother = None
self.pos = None
def __repr__(self):
return '[ {} : {} - {} {} - {} ]'.format(self.xref_id, self.name, self.father, self.mother, self.pos) |
class Cell:
def __init__(self, row, col):
self.row = row
self.col = col
self.links = []
self.north = None
self.south = None
self.east = None
self.west = None
def neighbors(self):
n = []
self.north and n.append(self.north)
self.so... | class Cell:
def __init__(self, row, col):
self.row = row
self.col = col
self.links = []
self.north = None
self.south = None
self.east = None
self.west = None
def neighbors(self):
n = []
self.north and n.append(self.north)
self.sou... |
class Notifier(object):
def notify(self, title, message, retry_forever=False):
raise NotImplementedError()
def _resolve_params(self, title, message):
if callable(title):
title = title()
if callable(message):
message = message()
return title, message
| class Notifier(object):
def notify(self, title, message, retry_forever=False):
raise not_implemented_error()
def _resolve_params(self, title, message):
if callable(title):
title = title()
if callable(message):
message = message()
return (title, message) |
n = int(input())
c=0
for _ in range(n):
p, q = list(map(int, input().split()))
if q-p >=2:
c= c+1
print(c)
| n = int(input())
c = 0
for _ in range(n):
(p, q) = list(map(int, input().split()))
if q - p >= 2:
c = c + 1
print(c) |
class Solution:
def smallestRangeI(self, nums: List[int], k: int) -> int:
minNum,maxNum = min(nums),max(nums)
if maxNum-minNum>=2*k:
return maxNum-minNum-2*k
else:
return 0 | class Solution:
def smallest_range_i(self, nums: List[int], k: int) -> int:
(min_num, max_num) = (min(nums), max(nums))
if maxNum - minNum >= 2 * k:
return maxNum - minNum - 2 * k
else:
return 0 |
# Q7: What is the time complexity of
# i = 1, 2, 4, 8, 16, ..., 2^k
# El bucle termina para: i >= n
# 2^k = n
# k = log_2(n)
# O(log_2(n))
# Algoritmo
# for (i = 1; i < n; i = i*2) {
# statement;
# }
i = 1
n = 10
while i < n:
print(i)
i = i*2 | i = 1
n = 10
while i < n:
print(i)
i = i * 2 |
code_map = {
"YEAR": "year",
"MALE": "male population",
"FEMALE": "female population",
"M_MALE": "matable male population",
"M_FEMALE": "matable female population",
"C_PROB": "concieving probability",
"M_AGE_START": "starting age of mating",
"M_AGE_END": "ending age of mating",
"MX_A... | code_map = {'YEAR': 'year', 'MALE': 'male population', 'FEMALE': 'female population', 'M_MALE': 'matable male population', 'M_FEMALE': 'matable female population', 'C_PROB': 'concieving probability', 'M_AGE_START': 'starting age of mating', 'M_AGE_END': 'ending age of mating', 'MX_AGE': 'maximum age', 'MT_PROB': 'mutat... |
txt = "I like bananas"
x = txt.replace("bananas", "mangoes")
print(x)
txt = "one one was a race horse and two two was one too."
x = txt.replace("one", "three")
print(x)
txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three", 1)
print(x)
txt = "For only {price:.2f} dollars!"... | txt = 'I like bananas'
x = txt.replace('bananas', 'mangoes')
print(x)
txt = 'one one was a race horse and two two was one too.'
x = txt.replace('one', 'three')
print(x)
txt = 'one one was a race horse, two two was one too.'
x = txt.replace('one', 'three', 1)
print(x)
txt = 'For only {price:.2f} dollars!'
print(txt.form... |
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
# 0 -> 0 status = 0
# 1 -> 1 status = 1
# 1 -> 0 status = 2
# 0 -> 1 status = 3
m, n = len(board), len(board[0])
directions = [(-1,-1),(0,-1),(1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)]
for x in... | class Solution:
def game_of_life(self, board: List[List[int]]) -> None:
(m, n) = (len(board), len(board[0]))
directions = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]
for x in range(m):
for y in range(n):
lives = 0
for (d... |
def calc(x,y,ops):
if ops not in "+-*/":
return "only +-*/!!!!!"
if ops=="+":
return (str(x) +""+ ops +str(y)+"="+str(x+y))
elif ops=="-":
return (str(x) +""+ ops +str(y)+"="+str(x-y))
elif ops == "*":
return (str(x) + "" + ops + str(y) + "=" + str(x * y))
elif ops ==... | def calc(x, y, ops):
if ops not in '+-*/':
return 'only +-*/!!!!!'
if ops == '+':
return str(x) + '' + ops + str(y) + '=' + str(x + y)
elif ops == '-':
return str(x) + '' + ops + str(y) + '=' + str(x - y)
elif ops == '*':
return str(x) + '' + ops + str(y) + '=' + str(x * ... |
n = int(input())
length = 0
while True:
length += 1
n //= 10
if n == 0:
break
print('Length is', length)
| n = int(input())
length = 0
while True:
length += 1
n //= 10
if n == 0:
break
print('Length is', length) |
''' '+' Plus Operator shows polymorphism. It is overloaded to perform multiple things, so we can call it polymorphic. '''
x = 10
y = 20
print(x+y)
s1 = 'Hello'
s2 = " How are you?"
print(s1+s2)
l1 = [1,2,3]
l2 = [4,5,6]
print(l1+l2)
| """ '+' Plus Operator shows polymorphism. It is overloaded to perform multiple things, so we can call it polymorphic. """
x = 10
y = 20
print(x + y)
s1 = 'Hello'
s2 = ' How are you?'
print(s1 + s2)
l1 = [1, 2, 3]
l2 = [4, 5, 6]
print(l1 + l2) |
people = 50 #defines the people variable
cars = 10 #defines the cars variable
trucks = 35 #defines the trucks variable
if cars > people or trucks < cars: #sets up the first branch
print("We should take the cars.") #print that runs if the if above is true
elif cars < people: #sets up second branch that runs if the... | people = 50
cars = 10
trucks = 35
if cars > people or trucks < cars:
print('We should take the cars.')
elif cars < people:
print('We should not take the cars.')
else:
print("We can't decide.")
if trucks > cars:
print("That's too many trucks.")
elif trucks < cars:
print('Maybe we could take the truck... |
DESEncryptParam = "key(16 Hex Chars), Number of rounds"
INITIAL_PERMUTATION = [58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, ... | des_encrypt_param = 'key(16 Hex Chars), Number of rounds'
initial_permutation = [58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23,... |
class WikipediaKnowledge:
@staticmethod
def all_wikipedia_language_codes_order_by_importance():
# list from https://meta.wikimedia.org/wiki/List_of_Wikipedias as of 2017-10-07
# ordered by article count except some for extreme bot spam
# should use https://stackoverflow.com/questions/336... | class Wikipediaknowledge:
@staticmethod
def all_wikipedia_language_codes_order_by_importance():
return ['en', 'de', 'fr', 'nl', 'ru', 'it', 'es', 'pl', 'vi', 'ja', 'pt', 'zh', 'uk', 'fa', 'ca', 'ar', 'no', 'sh', 'fi', 'hu', 'id', 'ko', 'cs', 'ro', 'sr', 'ms', 'tr', 'eu', 'eo', 'bg', 'hy', 'da', 'zh-min... |
# -*- coding:utf-8 -*-
# @Script: rotate_array.py
# @Author: Pradip Patil
# @Contact: @pradip__patil
# @Created: 2019-04-01 21:36:57
# @Last Modified By: Pradip Patil
# @Last Modified: 2019-04-01 22:44:02
# @Description: https://leetcode.com/problems/rotate-array/
'''
Given an array, rotate the array to the right by k... | """
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Inp... |
class TrainingConfig():
batch_size=64
lr=0.001
epoches=20
print_step=15
class BertMRCTrainingConfig(TrainingConfig):
batch_size=64
lr=1e-5
epoches=5
class TransformerConfig(TrainingConfig):
pass
class HBTTrainingConfig(TrainingConfig):
batch_size=32
lr=1e-5
epoch=20
| class Trainingconfig:
batch_size = 64
lr = 0.001
epoches = 20
print_step = 15
class Bertmrctrainingconfig(TrainingConfig):
batch_size = 64
lr = 1e-05
epoches = 5
class Transformerconfig(TrainingConfig):
pass
class Hbttrainingconfig(TrainingConfig):
batch_size = 32
lr = 1e-05
... |
# mouse
MOUSE_BEFORE_DELAY = 0.1
MOUSE_AFTER_DELAY = 0.1
MOUSE_PRESS_TIME = 0.2
MOUSE_INTERVAL = 0.2
# keyboard
KEYBOARD_BEFORE_DELAY = 0.05
KEYBOARD_AFTER_DELAY = 0.05
KEYBOARD_PRESS_TIME = 0.15
KEYBOARD_INTERVAL = 0.1
# clipbaord
CLIPBOARD_CHARSET = 'gbk'
# window
WINDOW_TITLE = 'Program Manager'
WINDOW_MANAGE_TI... | mouse_before_delay = 0.1
mouse_after_delay = 0.1
mouse_press_time = 0.2
mouse_interval = 0.2
keyboard_before_delay = 0.05
keyboard_after_delay = 0.05
keyboard_press_time = 0.15
keyboard_interval = 0.1
clipboard_charset = 'gbk'
window_title = 'Program Manager'
window_manage_timeout = 5
window_new_build_timeout = 5
image... |
class Student(object):
def __init__(self, name):
self.name = name
def __str__(self):
return 'Student object (name: %s)' % self.name
def __call__(self):
print('My name 111111111is %s.' % self.name)
print("-----------------------")
ffl = Student('ffl')
print("ffl-->", ffl)
print("f... | class Student(object):
def __init__(self, name):
self.name = name
def __str__(self):
return 'Student object (name: %s)' % self.name
def __call__(self):
print('My name 111111111is %s.' % self.name)
print('-----------------------')
ffl = student('ffl')
print('ffl-->', ffl)
print('ff... |
LIMIT = 2000000;
def solve(limit):
a = 0
dam = limit
for i in range(2, 101):
for j in range(i, 101):
d = abs(i*(i + 1) * j*(j + 1)/4 - limit)
if d < dam:
a, dam = i * j, d
return a
if __name__ == "__main__":
print(solve(LIMIT))
| limit = 2000000
def solve(limit):
a = 0
dam = limit
for i in range(2, 101):
for j in range(i, 101):
d = abs(i * (i + 1) * j * (j + 1) / 4 - limit)
if d < dam:
(a, dam) = (i * j, d)
return a
if __name__ == '__main__':
print(solve(LIMIT)) |
for _ in range(int(input())):
l,r=map(int,input().split())
b=r
a=r//2+1
if a<l:
a=l
if a>r:
a=r
print(b%a) | for _ in range(int(input())):
(l, r) = map(int, input().split())
b = r
a = r // 2 + 1
if a < l:
a = l
if a > r:
a = r
print(b % a) |
print('Please think of a number between 0 and 100!')
x = 54
low = 0
high = 100
guessed = False
while not guessed:
guess = (low + high)/2
print('Is your secret number ' + str(guess)+'?')
s = raw_input("Enter 'h' to indicate the guess is too high.\
Enter 'l' to indicate the guess is too lo... | print('Please think of a number between 0 and 100!')
x = 54
low = 0
high = 100
guessed = False
while not guessed:
guess = (low + high) / 2
print('Is your secret number ' + str(guess) + '?')
s = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too lo... |
# abcabc
# g_left = a, g_right = b
#
class Solution(object):
def __convert(self, x):
return ord(x) - ord('a') + 1
def distinctEchoSubstrings(self, text):
if len(text) == 1:
return 0
m = int(1e9 + 9)
p = 31
p_pow = 1
g_left = self.__convert(text... | class Solution(object):
def __convert(self, x):
return ord(x) - ord('a') + 1
def distinct_echo_substrings(self, text):
if len(text) == 1:
return 0
m = int(1000000000.0 + 9)
p = 31
p_pow = 1
g_left = self.__convert(text[0])
g_right = self.__co... |
description = 'nGI backpack setup at ICON.'
display_order = 35
pvprefix = 'SQ:ICON:ngiB:'
includes = ['ngi_g0']
excludes = ['ngi_xingi_gratings']
devices = dict(
g1_rz = device('nicos_ess.devices.epics.motor.EpicsMotor',
epicstimeout = 3.0,
description = 'nGI Interferometer Grating Rotation G1 (... | description = 'nGI backpack setup at ICON.'
display_order = 35
pvprefix = 'SQ:ICON:ngiB:'
includes = ['ngi_g0']
excludes = ['ngi_xingi_gratings']
devices = dict(g1_rz=device('nicos_ess.devices.epics.motor.EpicsMotor', epicstimeout=3.0, description='nGI Interferometer Grating Rotation G1 (Backpack)', motorpv=pvprefix + ... |
# Input: Two strings, Pattern and Genome
# Output: A list containing all starting positions where Pattern appears as a substring of Genome
def PatternMatching(pattern, genome):
positions = [] # output variable
# your code here
for i in range(len(genome)-len(pattern)+1):
if genome[i:i+len(patt... | def pattern_matching(pattern, genome):
positions = []
for i in range(len(genome) - len(pattern) + 1):
if genome[i:i + len(pattern)] == pattern:
positions.append(i)
return positions
def approximate_pattern_matching(pattern, genome, d):
positions = []
for i in range(len(genome) - ... |
def encodenum(num):
num = str(num)
line =""
for c in num:
line += chr(int(c) + ord('a'))
return line
def decodenum(line):
num = ""
for c in line:
num += str(ord(c)-ord('a'))
return num | def encodenum(num):
num = str(num)
line = ''
for c in num:
line += chr(int(c) + ord('a'))
return line
def decodenum(line):
num = ''
for c in line:
num += str(ord(c) - ord('a'))
return num |
class exemplo():
def __init__(self):
pass
def thg_print(darkcode):
print(darkcode)
| class Exemplo:
def __init__(self):
pass
def thg_print(darkcode):
print(darkcode) |
class Foo():
_myprop = 3
@property
def myprop(self):
return self.__class__._myprop
@myprop.setter
def myprop(self, val):
self.__class__._myprop = val
f = Foo()
g = Foo()
print(f.myprop, g.myprop)
f.myprop = 4
print(f.myprop, g.myprop)
| class Foo:
_myprop = 3
@property
def myprop(self):
return self.__class__._myprop
@myprop.setter
def myprop(self, val):
self.__class__._myprop = val
f = foo()
g = foo()
print(f.myprop, g.myprop)
f.myprop = 4
print(f.myprop, g.myprop) |
#author: Lynijah
# date: 07-01-2021
def blank():
return print(" ")
# --------------- Section 1 --------------- #
# ---------- Integers and Floats ---------- #
# you may use floats or integers for these operations, it is at your discretion
# addition
# instructions
# 1 - create a print statement that pri... | def blank():
return print(' ')
print('Addition Section')
print(2006 + 2000)
print(2000 + 9000 + 4)
print(-4 + -7)
blank()
print('Subtraction Section')
print(2006 - 2000)
print(2000 - 10 - 90)
print(-4 - -7)
blank()
print('Multiplication And True Division Section')
print(6 * 2000)
print(2000 / 9)
print(5 * 8 / 2)
bl... |
#
# PySNMP MIB module CISCO-ENTITY-REDUNDANCY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ENTITY-REDUNDANCY-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:39:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, constraints_intersection, value_size_constraint, single_value_constraint) ... |
message = "This is a message!"
print(message)
message = "This is a new message!"
print(message) | message = 'This is a message!'
print(message)
message = 'This is a new message!'
print(message) |
# author: Roy Kid
# contact: lijichen365@126.com
# date: 2021-09-20
# version: 0.0.1
def flat_kwargs(kwargs):
tmp = []
values = list(kwargs.values())
lenValue = len(values[0])
for v in values:
assert len(v) == lenValue, 'kwargs request aligned value'
for i in range(lenValue):
tmp.ap... | def flat_kwargs(kwargs):
tmp = []
values = list(kwargs.values())
len_value = len(values[0])
for v in values:
assert len(v) == lenValue, 'kwargs request aligned value'
for i in range(lenValue):
tmp.append({})
for (k, v) in kwargs.items():
for (i, vv) in enumerate(v):
... |
# Created by MechAviv
# Kinesis Introduction
# Map ID :: 331001120
# Hideout :: Training Room 2
KINESIS = 1531000
JAY = 1531001
if "1" not in sm.getQuestEx(22700, "E2"):
sm.setNpcOverrideBoxChat(KINESIS)
sm.sendNext("Jay, I feel so slow walking around like this. I'm going to switch to my speedier moves.")
... | kinesis = 1531000
jay = 1531001
if '1' not in sm.getQuestEx(22700, 'E2'):
sm.setNpcOverrideBoxChat(KINESIS)
sm.sendNext("Jay, I feel so slow walking around like this. I'm going to switch to my speedier moves.")
sm.setNpcOverrideBoxChat(JAY)
sm.sendSay('#face9#Fine, whatever! Just ignore the test plan I ... |
def do_something(x):
sq_x=x**2
return (sq_x) # this will make it much easier in future problems to see that something is actually happening
| def do_something(x):
sq_x = x ** 2
return sq_x |
class SetUp:
base = "http://localhost:8890/"
URL = "http://localhost:8890/notebooks/test/testing.ipynb"
kernel_link = "#kernellink"
start_kernel = "link=Restart & Run All"
start_confirm = "(.//*[normalize-space(text()) and normalize-space(.)='Continue Running'])[1]/following::button[1]"
title = ... | class Setup:
base = 'http://localhost:8890/'
url = 'http://localhost:8890/notebooks/test/testing.ipynb'
kernel_link = '#kernellink'
start_kernel = 'link=Restart & Run All'
start_confirm = "(.//*[normalize-space(text()) and normalize-space(.)='Continue Running'])[1]/following::button[1]"
title = ... |
# int object is immutable
age = 30
print(id(age)) # id is used to get a object reference id
age = 40
print(id(age))
# list is mutable
series1 = [1, 2, 3]
series2 = series1
print(id(series1))
print(id(series1))
series1[1] = 10
print(series1)
print(series2)
print(id(series1))
print(id(series1))
# i... | age = 30
print(id(age))
age = 40
print(id(age))
series1 = [1, 2, 3]
series2 = series1
print(id(series1))
print(id(series1))
series1[1] = 10
print(series1)
print(series2)
print(id(series1))
print(id(series1))
series1 = [1, 2, 3]
series2 = [1, 2, 3]
print(series1 is series2)
print(series1 == series2) |
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def has_cycle(head):
fast = head
slow = head
while slow != None and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False... | class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def has_cycle(head):
fast = head
slow = head
while slow != None and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
... |
__author__ = 'rene_esteves'
def factorial(input):
if input < 1: # base case
return 1
else:
return input * factorial(input - 1) # recursive call
def sum(input):
if input == 1: # base_case
return 1
else:
return input + sum(input - 1) # recursive call
def fibonacci... | __author__ = 'rene_esteves'
def factorial(input):
if input < 1:
return 1
else:
return input * factorial(input - 1)
def sum(input):
if input == 1:
return 1
else:
return input + sum(input - 1)
def fibonacci(input):
if input == 1 or input == 0:
print('PAROU')
... |
class MySQL:
def __init__(self, db):
self.__db = db
def pre_load(self):
# do nothing
return
def load(self, check_id, results):
for result in results:
responsetime = result.get('responsetime', None)
self.__db.query(
'REPLACE INTO pingd... | class Mysql:
def __init__(self, db):
self.__db = db
def pre_load(self):
return
def load(self, check_id, results):
for result in results:
responsetime = result.get('responsetime', None)
self.__db.query('REPLACE INTO pingdom_check_result (`check_id`, `at`, `p... |
#
# PySNMP MIB module OPT-IF-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OPT-IF-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:26:00 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:... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, value_size_constraint, single_value_constraint, constraints_union) ... |
def checkrootpos(root, params):
a, b, c, d = params
return a * root**3 + b * root**2 + c * root + d > 0
def checkrootneg(root, params):
a, b, c, d = params
return a * root**3 + b * root**2 + c * root + d < 0
def fbinsearch(l, r, eps, check, params):
while l + eps < r:
m = (l + r) / 2
... | def checkrootpos(root, params):
(a, b, c, d) = params
return a * root ** 3 + b * root ** 2 + c * root + d > 0
def checkrootneg(root, params):
(a, b, c, d) = params
return a * root ** 3 + b * root ** 2 + c * root + d < 0
def fbinsearch(l, r, eps, check, params):
while l + eps < r:
m = (l + ... |
LOWER_BOUND = -2147483648
UPPER_BOUND = 2147483647
def solve(i: int) -> int:
base = 10
digit_arr = []
mult = 1 if i > 0 else -1
num = abs(i)
while num:
digit_arr.append(num % base)
num //= base
reverse_num = 0
for digit in digit_arr[::-1]:
reverse_num += mult * dig... | lower_bound = -2147483648
upper_bound = 2147483647
def solve(i: int) -> int:
base = 10
digit_arr = []
mult = 1 if i > 0 else -1
num = abs(i)
while num:
digit_arr.append(num % base)
num //= base
reverse_num = 0
for digit in digit_arr[::-1]:
reverse_num += mult * digit... |
class MultiSerializerMixin:
def get_serializer_class(self):
return self.serializer_classes[self.action]
| class Multiserializermixin:
def get_serializer_class(self):
return self.serializer_classes[self.action] |
# While loops practice
# PART A
ages = [5, 6, 24, 32, 21, 70]
counter = 0
while ages[counter] < 30:
print("Part A - The ages is : " +str(ages[counter]))
counter+=1
print("Part A - The value that caused the loop to stop : " +str(ages[counter]))
print("\n")
# PART B
counter = 0
while ages[counter] < 30:
... | ages = [5, 6, 24, 32, 21, 70]
counter = 0
while ages[counter] < 30:
print('Part A - The ages is : ' + str(ages[counter]))
counter += 1
print('Part A - The value that caused the loop to stop : ' + str(ages[counter]))
print('\n')
counter = 0
while ages[counter] < 30:
if ages[counter] > 20:
print('Part... |
def out_red(text):
return "\033[31m {}" .format(text)
def out_yellow(text):
return "\033[33m {}" .format(text)
def out_green(text):
return "\033[32m {}" .format(text)
| def out_red(text):
return '\x1b[31m {}'.format(text)
def out_yellow(text):
return '\x1b[33m {}'.format(text)
def out_green(text):
return '\x1b[32m {}'.format(text) |
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
vowels.sort()
# print vowels
print('Sorted list:', vowels)
| vowels = ['e', 'a', 'u', 'o', 'i']
vowels.sort()
print('Sorted list:', vowels) |
# set the path-to-files
TRAIN_FILE = "/home/luban/work_jupyter/point_rec_data/train.csv"
TEST_FILE = "/home/luban/work_jupyter/point_rec_data/test.csv"
SUB_DIR = "./output"
NUM_SPLITS = 3
RANDOM_SEED = 2017
# types of columns of the dataset dataframe
CATEGORICAL_COLS = [
'common.os',
'common.loc_provider',... | train_file = '/home/luban/work_jupyter/point_rec_data/train.csv'
test_file = '/home/luban/work_jupyter/point_rec_data/test.csv'
sub_dir = './output'
num_splits = 3
random_seed = 2017
categorical_cols = ['common.os', 'common.loc_provider', 'time.time', 'time.week']
numeric_cols = ['personal.cur_rectangle', 'common.loc_a... |
HIVE_CONFIG = {
"host": '127.0.0.1',
"port": 10000,
"username": 'username',
"password": 'password'
}
MYSQL_CONFIG = {
'test':
{
"host": "127.0.0.1",
"port": 3306,
"user": "username",
"password": "password",
"database": "default"},
... | hive_config = {'host': '127.0.0.1', 'port': 10000, 'username': 'username', 'password': 'password'}
mysql_config = {'test': {'host': '127.0.0.1', 'port': 3306, 'user': 'username', 'password': 'password', 'database': 'default'}, 'prod': {'host': '127.0.0.1', 'port': 3306, 'user': 'username', 'password': 'password', 'data... |
# mock.py
# Metadata
NAME = 'mock'
ENABLE = True
PATTERN = r'^!mock (?P<phrase>.*)'
USAGE = '''Usage: !mock <phrase>
Given a phrase, this translates the phrase into a mocking spongebob phrase.
Example:
> !mock it should work on slack and irc
iT ShOuLd wOrK On sLaCk aNd iRc
'''
# Command
async def mock... | name = 'mock'
enable = True
pattern = '^!mock (?P<phrase>.*)'
usage = 'Usage: !mock <phrase>\nGiven a phrase, this translates the phrase into a mocking spongebob phrase.\nExample:\n > !mock it should work on slack and irc\n iT ShOuLd wOrK On sLaCk aNd iRc\n'
async def mock(bot, message, phrase):
phrase = phr... |
# Check For Vowel in a sentence....
s = input("Enter String: ")
s = s.lower()
f = 0
for i in range(0, len(s)):
if(s[i] == 'a' or s[i] == 'e' or s[i] == 'i' or s[i] == 'o' or s[i] == 'u'):
f = 2
break
else:
f = 1
if f > 1:
print("Yes, Present")
else:
print("No, Not Present")
| s = input('Enter String: ')
s = s.lower()
f = 0
for i in range(0, len(s)):
if s[i] == 'a' or s[i] == 'e' or s[i] == 'i' or (s[i] == 'o') or (s[i] == 'u'):
f = 2
break
else:
f = 1
if f > 1:
print('Yes, Present')
else:
print('No, Not Present') |
# Given a 2D grid, each cell is either a wall 'W',
# an enemy 'E' or empty '0' (the number zero),
# return the maximum enemies you can kill using one bomb.
# The bomb kills all the enemies in the same row and column from
# the planted point until it hits the wall since the wall is too strong
# to be destroyed.
# Note t... | def max_killed_enemies(grid):
if not grid:
return 0
(m, n) = (len(grid), len(grid[0]))
max_killed = 0
(row_e, col_e) = (0, [0] * n)
for i in range(m):
for j in range(n):
if j == 0 or grid[i][j - 1] == 'W':
row_e = row_kills(grid, i, j)
if i == ... |
def insertion_sort(arr):
isSorted = None
while not isSorted:
isSorted = True
for x,val in enumerate(arr):
try:
if val>arr[x+1]:
temp = arr[x]
arr[x] = arr[x+1]
arr[x+1] = temp
isSorted = False
except IndexError:
x-=1
return arr
print(insertion_sort([5,3,1,2,10... | def insertion_sort(arr):
is_sorted = None
while not isSorted:
is_sorted = True
for (x, val) in enumerate(arr):
try:
if val > arr[x + 1]:
temp = arr[x]
arr[x] = arr[x + 1]
arr[x + 1] = temp
... |
# -*- coding: utf-8 -*-
def main():
a, b = map(int, input().split())
a -= 1
b -= 1
n = 100
grid = [['.'] * n for _ in range(n // 2)]
for _ in range(n // 2):
grid.append(['#'] * n)
print(n, n)
for i in range(0, n // 2, 2):
for j in range(0, n, 2):
... | def main():
(a, b) = map(int, input().split())
a -= 1
b -= 1
n = 100
grid = [['.'] * n for _ in range(n // 2)]
for _ in range(n // 2):
grid.append(['#'] * n)
print(n, n)
for i in range(0, n // 2, 2):
for j in range(0, n, 2):
if b > 0:
grid[i][j... |
# Constant values
IS_COLD_START = True
WARM_ACTION_INDENTIFIER = 'warm_up'
DEFAULT_WARM_METHOD = 'sleep'
| is_cold_start = True
warm_action_indentifier = 'warm_up'
default_warm_method = 'sleep' |
def test_endpoint_with_var2(client):
response = client.get("/items2/2")
assert response.status_code == 200
assert response.json() == {"item_id": 2}
| def test_endpoint_with_var2(client):
response = client.get('/items2/2')
assert response.status_code == 200
assert response.json() == {'item_id': 2} |
class SampleClass:
@staticmethod
def sample_method(a, b):
return a + b
| class Sampleclass:
@staticmethod
def sample_method(a, b):
return a + b |
name = "S - Density Squares"
description = "Trigger randomly placed squares"
knob1 = "Square Size"
knob2 = "Density"
knob3 = "Line Width"
knob4 = "Color"
released = "March 21 2017"
| name = 'S - Density Squares'
description = 'Trigger randomly placed squares'
knob1 = 'Square Size'
knob2 = 'Density'
knob3 = 'Line Width'
knob4 = 'Color'
released = 'March 21 2017' |
'''
Interface Genie Ops Object Outputs for IOSXR.
'''
class InterfaceOutput(object):
ShowInterfacesDetail = {
'GigabitEthernet0/0/0/0': {
'auto_negotiate': True,
'bandwidth': 768,
'counters': {'carrier_transitions': 0,
'drops': 0,
... | """
Interface Genie Ops Object Outputs for IOSXR.
"""
class Interfaceoutput(object):
show_interfaces_detail = {'GigabitEthernet0/0/0/0': {'auto_negotiate': True, 'bandwidth': 768, 'counters': {'carrier_transitions': 0, 'drops': 0, 'in_abort': 0, 'in_broadcast_pkts': 0, 'in_crc_errors': 0, 'in_discards': 0, 'in_er... |
# Least Recently Used Cache
#
# The LRU caching scheme remove the least recently used data when the cache is full and a new page is referenced which is not there in cache.
#
# We use two data structures to implement an LRU Cache:
# - Double Linked List: The maximum size of the queue will be equal to the total number of... | class Node:
"""Double Linked List node implemetation for handling LRU Cache data"""
def __init__(self, key, value):
self.value = value
self.key = key
self.prev = None
self.next = None
def __repr__(self):
return f'Node({self.key}, {self.value})'
def __str__(self... |
#python 3.5.2
'''
With the Remained Methods first you count the number of elements you what to store. So the length of the
array will eaual the number of elements you want so each element will have place to be stored. When you
do the divide by array length the remainer will always to equal or less than the numbe... | """
With the Remained Methods first you count the number of elements you what to store. So the length of the
array will eaual the number of elements you want so each element will have place to be stored. When you
do the divide by array length the remainer will always to equal or less than the number of element in the
... |
def secti(a, b):
return a + b
if __name__ == '__main__':
print(secti(1, 2))
# https://stackoverflow.com/questions/419163/what-does-if-name-main-do
| def secti(a, b):
return a + b
if __name__ == '__main__':
print(secti(1, 2)) |
weights_path = './weights'
#pre trained model
name_model = 'model_unet'
#directory where read noisy sound to denoise
audio_dir_prediction = './mypredictions/input/'
#directory to save the denoise sound
dir_save_prediction = './mypredictions/output/'
#Name noisy sound file to denoise
#audio_input_prediction = args.a... | weights_path = './weights'
name_model = 'model_unet'
audio_dir_prediction = './mypredictions/input/'
dir_save_prediction = './mypredictions/output/'
sample_rate = 8000
min_duration = 1.0
frame_length = 8064
hop_length_frame = 8064
n_fft = 255
hop_length_fft = 63 |
BOT_NAME = 'books_images'
SPIDER_MODULES = ['books_images.spiders']
NEWSPIDER_MODULE = 'books_images.spiders'
ROBOTSTXT_OBEY = True
ITEM_PIPELINES = {
'books_images.pipelines.BooksImagesPipeline': 1
}
FILES_STORE = r'downloaded'
# Change this to your path
DOWNLOAD_DELAY = 2
# Change to 0 for fastest crawl
| bot_name = 'books_images'
spider_modules = ['books_images.spiders']
newspider_module = 'books_images.spiders'
robotstxt_obey = True
item_pipelines = {'books_images.pipelines.BooksImagesPipeline': 1}
files_store = 'downloaded'
download_delay = 2 |
#punto1
def triangulo(a,b):
area = (b * a)/2
print(area)
triangulo(30,50)
| def triangulo(a, b):
area = b * a / 2
print(area)
triangulo(30, 50) |
area = float(input())
kgInM = float(input())
badGrape = float(input())
allGrape = area * kgInM
restGrape = allGrape - badGrape
rakia = restGrape * 45 / 100
sell = restGrape * 55 / 100
lRakia = (rakia / 7.5) * 9.80
lSell = sell * 1.5
print('%.2f' % lRakia)
print('%.2f' % lSell) | area = float(input())
kg_in_m = float(input())
bad_grape = float(input())
all_grape = area * kgInM
rest_grape = allGrape - badGrape
rakia = restGrape * 45 / 100
sell = restGrape * 55 / 100
l_rakia = rakia / 7.5 * 9.8
l_sell = sell * 1.5
print('%.2f' % lRakia)
print('%.2f' % lSell) |
inputFile = open("input/day7.txt", "r")
inputLines = inputFile.readlines()
listBagsWithoutShinyGold = []
listBagsWithShinyGold = []
listUncertain = []
def goldMiner():
for line in inputLines:
splittedLine = line.split()
bagColor = splittedLine[0] + splittedLine[1]
childrenBags = []
... | input_file = open('input/day7.txt', 'r')
input_lines = inputFile.readlines()
list_bags_without_shiny_gold = []
list_bags_with_shiny_gold = []
list_uncertain = []
def gold_miner():
for line in inputLines:
splitted_line = line.split()
bag_color = splittedLine[0] + splittedLine[1]
children_bag... |
# Given an integer array nums, find the contiguous subarray (containing at least one number)
# which has the largest sum and return its sum.
# Example:
# Input: [-2,1,-3,4,-1,2,1,-5,4],
# Output: 6
# Explanation: [4,-1,2,1] has the largest sum = 6.
# Follow up:
# If you have figured out the O(n) solution, try codin... | class Solution:
def max_sub_array(self, nums):
total_sum = max_sum = nums[0]
for i in nums[1:]:
total_sum = max(i, total_sum + i)
max_sum = max(max_sum, total_sum)
return max_sum
if __name__ == '__main__':
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print(solution... |
def sum2(nums):
if len(nums) >= 2 :
return (nums[0] + nums[1])
elif len(nums) == 1 :
return nums[0]
else :
return 0 | def sum2(nums):
if len(nums) >= 2:
return nums[0] + nums[1]
elif len(nums) == 1:
return nums[0]
else:
return 0 |
''' r : It opens the file to read-only. The file pointer exists at the beginning. The file
is by default open in this mode if no access mode is passed. '''
''' w : It opens the file to write only. It overwrites the file if previously exists
or creates a new one if no file exists with the same name. The... | """ r : It opens the file to read-only. The file pointer exists at the beginning. The file
is by default open in this mode if no access mode is passed. """
' w : It opens the file to write only. It overwrites the file if previously exists \n or creates a new one if no file exists with the same name. The ... |
# !/usr/bin/env python3
#############################################################################
# #
# Program purpose: Displays a histogram from list data #
# Program Author : Happi Yvan <ivensteinpoker@gmail.co... | def histogram(someList, char):
for x in someList:
while x > 0:
print(f'{char}', end='')
x = x - 1
print(f'\n')
if __name__ == '__main__':
rand_list = [3, 7, 4, 2, 6]
histogram(randList, '*') |
class Dice(object):
def __init__(self, labels):
self.stat = labels
def roll_e(self):
self.stat[0], self.stat[2], self.stat[5], self.stat[3] = self.stat[3], self.stat[0], self.stat[2], self.stat[5]
def roll_w(self):
self.stat[0], self.stat[2], self.stat[5], self.stat[3] = self.stat[... | class Dice(object):
def __init__(self, labels):
self.stat = labels
def roll_e(self):
(self.stat[0], self.stat[2], self.stat[5], self.stat[3]) = (self.stat[3], self.stat[0], self.stat[2], self.stat[5])
def roll_w(self):
(self.stat[0], self.stat[2], self.stat[5], self.stat[3]) = (se... |
def sum(number1, number2):
total = number1 + number2
print(total)
print("suma de 1 + 50")
sum(1,50)
print("suma de 1 + 500")
sum(500,1)
print("programa terminado") | def sum(number1, number2):
total = number1 + number2
print(total)
print('suma de 1 + 50')
sum(1, 50)
print('suma de 1 + 500')
sum(500, 1)
print('programa terminado') |
class Solution:
def isUgly(self, n: int) -> bool:
while True:
k=n
if n%2==0:
n=n//2
if n%3==0:
n=n//3
if n%5==0:
n=n//5
if k==n:
break
if n==1:
return True
| class Solution:
def is_ugly(self, n: int) -> bool:
while True:
k = n
if n % 2 == 0:
n = n // 2
if n % 3 == 0:
n = n // 3
if n % 5 == 0:
n = n // 5
if k == n:
break
if n == 1:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.