content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
f = open('rucsac.txt', 'r')
n = int(f.readline())
v = []
for i in range(n):
linie = f.readline().split()
v.append((i+1, int(linie[0]), int(linie[1])))
G = int(f.readline())
cmax = [[0 for i in range(G+1)] for j in range(n+1)]
for i in range(1, n+1):
for j in range(1, G+1):
if v[i-1][1] > j... | f = open('rucsac.txt', 'r')
n = int(f.readline())
v = []
for i in range(n):
linie = f.readline().split()
v.append((i + 1, int(linie[0]), int(linie[1])))
g = int(f.readline())
cmax = [[0 for i in range(G + 1)] for j in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, G + 1):
if v[i - 1][1] >... |
for _ in range(int(input())):
a,b = map(str,input().split())
l1 = len(a)
l2 = len(b)
flag = True
k = ""
while l1>0 and l2>0:
if a[-1]<=b[-1]:
l1-=1
l2-=1
a1 = a[-1]
b1 = b[-1]
a = a[:-1]
b = b[:-1]
a1 = i... | for _ in range(int(input())):
(a, b) = map(str, input().split())
l1 = len(a)
l2 = len(b)
flag = True
k = ''
while l1 > 0 and l2 > 0:
if a[-1] <= b[-1]:
l1 -= 1
l2 -= 1
a1 = a[-1]
b1 = b[-1]
a = a[:-1]
b = b[:-1]
... |
BILL_TYPES = {
'hconres': 'House Concurrent Resolution',
'hjres': 'House Joint Resolution',
'hr': 'House Bill',
'hres': 'House Resolution',
'sconres': 'Senate Concurrent Resolution',
'sjres': 'Senate Joint Resolution',
's': 'Senate Bill',
'sres': 'Senate Resolution',
}
| bill_types = {'hconres': 'House Concurrent Resolution', 'hjres': 'House Joint Resolution', 'hr': 'House Bill', 'hres': 'House Resolution', 'sconres': 'Senate Concurrent Resolution', 'sjres': 'Senate Joint Resolution', 's': 'Senate Bill', 'sres': 'Senate Resolution'} |
def is_file_h5(item):
output = False
if type(item)==str:
if item.endswith('.h5') or item.endswith('.hdf5'):
output = True
return output
| def is_file_h5(item):
output = False
if type(item) == str:
if item.endswith('.h5') or item.endswith('.hdf5'):
output = True
return output |
class World:
def __init__(self):
self.children = []
def addChild(self, child):
child.world = self
self.children.append(child)
def getChildByName(self, name):
for child in self.children:
if child.name == name:
return name
return None
... | class World:
def __init__(self):
self.children = []
def add_child(self, child):
child.world = self
self.children.append(child)
def get_child_by_name(self, name):
for child in self.children:
if child.name == name:
return name
return None
... |
class Solution(object):
def findContentChildren(self, g, s):
"""
:type g: List[int]
:type s: List[int]
:rtype: int
"""
g = sorted(g)
s = sorted(s)
ans = 0
start = 0
for x in range(0, len(s)):
for y in range(start, len(g)):
... | class Solution(object):
def find_content_children(self, g, s):
"""
:type g: List[int]
:type s: List[int]
:rtype: int
"""
g = sorted(g)
s = sorted(s)
ans = 0
start = 0
for x in range(0, len(s)):
for y in range(start, len(g))... |
""" Enumerates results and states used by Go CD. """
ASSIGNED = 'Assigned'
BUILDING = 'Building'
CANCELLED = 'Cancelled'
COMPLETED = 'Completed'
COMPLETING = 'Completing'
DISCONTINUED = 'Discontinued'
FAILED = 'Failed'
FAILING = 'Failing'
PASSED = 'Passed'
PAUSED = 'Paused'
PREPARING = 'Preparing'
RESCHEDULED = 'Resche... | """ Enumerates results and states used by Go CD. """
assigned = 'Assigned'
building = 'Building'
cancelled = 'Cancelled'
completed = 'Completed'
completing = 'Completing'
discontinued = 'Discontinued'
failed = 'Failed'
failing = 'Failing'
passed = 'Passed'
paused = 'Paused'
preparing = 'Preparing'
rescheduled = 'Resche... |
# Taken from https://engineering.semantics3.com/a-simplified-guide-to-grpc-in-python-6c4e25f0c506
def message_to_send(x):
if x=="hi":
return 'hello, how can i help you'
elif x=="good afternoon":
return "good afternoon, how you doing"
elif x== 'Do you think you can really help me?':
return 'Yes, O... | def message_to_send(x):
if x == 'hi':
return 'hello, how can i help you'
elif x == 'good afternoon':
return 'good afternoon, how you doing'
elif x == 'Do you think you can really help me?':
return 'Yes, Of Course I can!'
elif x == 'How can I contact You?':
return 'You can... |
'''
URL: https://leetcode.com/problems/shortest-unsorted-continuous-subarray/description/
Time complexity: O(n)
Space complexity: O(1)
'''
class Solution(object):
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
re... | """
URL: https://leetcode.com/problems/shortest-unsorted-continuous-subarray/description/
Time complexity: O(n)
Space complexity: O(1)
"""
class Solution(object):
def find_unsorted_subarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
... |
# Python program to implement graph deletion operation | delete node | using dictionary
nodes = []
graph = {}
# delete a node undirected and unweighted
def delete_node(val):
if val not in graph:
print(val, "is not present in the graph")
else:
graph.pop(val) # pop the key with all valu... | nodes = []
graph = {}
def delete_node(val):
if val not in graph:
print(val, 'is not present in the graph')
else:
graph.pop(val)
for i in graph:
list1 = graph[i]
if val in list1:
return list1.remove(val)
def delete_node(val):
if val not in gra... |
with open('day14/input.txt') as f:
lines = f.readlines()
dic = {}
for line in lines:
a, b = line.strip().split(" -> ")
dic[a] = b
def grow(poly: str) -> str:
result = ""
for i in range(len(poly) - 1):
q = poly[i:i+2]
result += poly[i] +dic[q]
result += poly[-1]
return resul... | with open('day14/input.txt') as f:
lines = f.readlines()
dic = {}
for line in lines:
(a, b) = line.strip().split(' -> ')
dic[a] = b
def grow(poly: str) -> str:
result = ''
for i in range(len(poly) - 1):
q = poly[i:i + 2]
result += poly[i] + dic[q]
result += poly[-1]
return r... |
n, m = map(int, input().split())
notes = [list(map(int, input().split())) for _ in range(m)]
if m == 1:
d, h = notes[0]
print(max(h+(d-1), h+(n-d)))
exit(0)
d0, h0 = notes[0]
ans = h0+(d0-1)
for i in range(m-1):
d1, h1 = notes[i]
d2, h2 = notes[i+1]
if d2-d1 < abs(h1-h2):
ans = -1
... | (n, m) = map(int, input().split())
notes = [list(map(int, input().split())) for _ in range(m)]
if m == 1:
(d, h) = notes[0]
print(max(h + (d - 1), h + (n - d)))
exit(0)
(d0, h0) = notes[0]
ans = h0 + (d0 - 1)
for i in range(m - 1):
(d1, h1) = notes[i]
(d2, h2) = notes[i + 1]
if d2 - d1 < abs(h1 ... |
t = int(input())
outs = []
for _ in range(t):
n = input()
a = list(map(int, input().split()))
if a[0] != a[1]:
correct = a[2]
else:
correct = a[0]
for i in range(len(a)):
if a[i] != correct:
outs.append(i+1)
break
for out in outs:
print(out) | t = int(input())
outs = []
for _ in range(t):
n = input()
a = list(map(int, input().split()))
if a[0] != a[1]:
correct = a[2]
else:
correct = a[0]
for i in range(len(a)):
if a[i] != correct:
outs.append(i + 1)
break
for out in outs:
print(out) |
d={
"Aligarh":"It is the city in UP ",
"bharatpur":"it is the city in Rajasthan",
"delhi ":"it is the capital of India",
"Mumbai":"it is the city in Maharashtra"
}
print("enter the name which you want to search ")
n1=input()
print(d[n1])
| d = {'Aligarh': 'It is the city in UP ', 'bharatpur': 'it is the city in Rajasthan', 'delhi ': 'it is the capital of India', 'Mumbai': 'it is the city in Maharashtra'}
print('enter the name which you want to search ')
n1 = input()
print(d[n1]) |
class Persona:
def __init__(self,nombre,apellidoPaterno,apellidoMaterno,sexo,edad,domicilio,telefono):
self.nombre = nombre
self.apellidoPaterno = apellidoPaterno
self.apellidoMaterno = apellidoMaterno
self.sexo = sexo
self.edad = edad
self.domicilio = domicilio
... | class Persona:
def __init__(self, nombre, apellidoPaterno, apellidoMaterno, sexo, edad, domicilio, telefono):
self.nombre = nombre
self.apellidoPaterno = apellidoPaterno
self.apellidoMaterno = apellidoMaterno
self.sexo = sexo
self.edad = edad
self.domicilio = domicil... |
# 1. Write a Python class named Rectangle constructed by a length and width and a method which will
# compute the area of a rectangle.
class rectangle():
def __init__(self, width, length):
self.width = width
self.length = length
def area(self):
return self.width * self.length
a = int... | class Rectangle:
def __init__(self, width, length):
self.width = width
self.length = length
def area(self):
return self.width * self.length
a = int(input('Enter length of rectangle: '))
b = int(input('Enter width of rectangle: '))
obj = rectangle(a, b)
print('Area of rectangle:', obj.a... |
CONNECTION_TAB_DEFAULT_TITLE = "Untitled"
CONNECTION_STRING_SUPPORTED_DB_NAMES = ["SQLite"]
CONNECTION_STRING_PLACEHOLDER = "Enter..."
CONNECTION_STRING_DEFAULT = "demo.db"
QUERY_EDITOR_DEFAULT_TEXT = "SELECT name FROM sqlite_master WHERE type='table'"
QUERY_CONTROL_CONNECT_BUTTON_TEXT = "Connect"
QUERY_CONTROL_EXECUTE... | connection_tab_default_title = 'Untitled'
connection_string_supported_db_names = ['SQLite']
connection_string_placeholder = 'Enter...'
connection_string_default = 'demo.db'
query_editor_default_text = "SELECT name FROM sqlite_master WHERE type='table'"
query_control_connect_button_text = 'Connect'
query_control_execute... |
# -*- coding: utf-8 -*-
# Copyright 2015 Pietro Brunetti <pietro.brunetti@itb.cnr.it>
#
# 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
# Unle... | __authors__ = 'Pietro Brunetti'
__all__ = ['peptidome', 'raw', 'by_targets', 'ChangeTargetPeptides', 'DialogCommons', 'EPPI_dataEPPI', 'flatnotebook', 'html_generator', 'Join', 'ManageVars', 'pages', 'project', 'ReportProtein,ReportSequence', 'Resume', 'Search', 'SelPepts', 'Targets'] |
#!/usr/bin/python
# This script simply generates a table of the voltage to expect
# if I combine my photoresistors with some of my resitors from stock..
# As there is no strong sunlight at the moment here, I will have to
# postpone the real life testing..
voltage=5.
resistor=[59,180,220,453,750,1000,10000,20000]
me... | voltage = 5.0
resistor = [59, 180, 220, 453, 750, 1000, 10000, 20000]
measurement = [2000000, 1000000, 600000, 200000, 100000, 80000, 40000, 20000, 10000, 8000, 6000, 4000, 2000, 1000, 800, 600, 400, 200, 100, 80, 60, 40, 20, 8, 2]
def measure(r, p):
return round(voltage - voltage / (r + p) * r, 4)
print('')
print... |
# Calculates total acres based on square feet input
# Declare variables
sqftInOneAcre = 43560
# Prompt user for total square feet of parcel of land
totalSqft = float(input('\nEnter total square feet of parcel of land: '))
# Calculate and display total acres
totalAcres = totalSqft / sqftInOneAcre
print('Total acres: ... | sqft_in_one_acre = 43560
total_sqft = float(input('\nEnter total square feet of parcel of land: '))
total_acres = totalSqft / sqftInOneAcre
print('Total acres: ', format(totalAcres, ',.1f'), '\n') |
class ReportEntry:
def __init__(self):
self.medium = 'Book'
self.title = None
self.url = None
self.classification = None
self.length = None
self.start_date = None
self.stop_date = None
self.distribution_percent = None
| class Reportentry:
def __init__(self):
self.medium = 'Book'
self.title = None
self.url = None
self.classification = None
self.length = None
self.start_date = None
self.stop_date = None
self.distribution_percent = None |
def rank_cal(rank_list, target_index):
rank = 0.
target_score = rank_list[target_index]
for score in rank_list:
if score >= target_score:
rank += 1.
return rank
def reciprocal_rank(rank):
return 1./rank
def accuracy_at_k(rank, k):
if rank <= k:
return... | def rank_cal(rank_list, target_index):
rank = 0.0
target_score = rank_list[target_index]
for score in rank_list:
if score >= target_score:
rank += 1.0
return rank
def reciprocal_rank(rank):
return 1.0 / rank
def accuracy_at_k(rank, k):
if rank <= k:
return 1.0
e... |
pos = 0
for k in range(6):
if float(input()) > 2: pos += 1
print(pos, "valores positivos")
| pos = 0
for k in range(6):
if float(input()) > 2:
pos += 1
print(pos, 'valores positivos') |
class NumMatrix:
def __init__(self, matrix: List[List[int]]):
if not any(matrix):
return
m, n = len(matrix), len(matrix[0])
self.tree = [[0] * (n + 1) for _ in range(m + 1)]
self.R = m + 1
self.C = n + 1
for i in range(m):
for j in range(n):
... | class Nummatrix:
def __init__(self, matrix: List[List[int]]):
if not any(matrix):
return
(m, n) = (len(matrix), len(matrix[0]))
self.tree = [[0] * (n + 1) for _ in range(m + 1)]
self.R = m + 1
self.C = n + 1
for i in range(m):
for j in range(n... |
width = 800
height = 700
fps = 60
font_n = 'arial'
sheetload = "spritesheet_jumper.png"
mob_fq = 5000
player_acc = 0.5
player_friction = -0.12
player_gra = 0.8
player_jump = 21
platform_list = [(0,height-50),(width/2-50,height*3/4),
(235,height-350),(350,200),(175,100)]
white = (255,255,... | width = 800
height = 700
fps = 60
font_n = 'arial'
sheetload = 'spritesheet_jumper.png'
mob_fq = 5000
player_acc = 0.5
player_friction = -0.12
player_gra = 0.8
player_jump = 21
platform_list = [(0, height - 50), (width / 2 - 50, height * 3 / 4), (235, height - 350), (350, 200), (175, 100)]
white = (255, 255, 255)
black... |
n = int(input())
ans = 0
number = 0
for i in range(n):
a, b = map(int, input().split())
A = int(str(a)[::-1]) # reverse
B = int(str(b)[::-1]) # reverse
ans = A + B
number = int(str(ans)[::-1]) # reverse
print(number)
| n = int(input())
ans = 0
number = 0
for i in range(n):
(a, b) = map(int, input().split())
a = int(str(a)[::-1])
b = int(str(b)[::-1])
ans = A + B
number = int(str(ans)[::-1])
print(number) |
#***Library implementing the sorting algorithms***
def quick_sort(seq,less_than):
if len(seq) < 1:
return seq
else:
pivot=seq[0]
left = quick_sort([x for x in seq[1:] if less_than(x,pivot)],less_than)
right = quick_sort([x for x in seq[1:] if not less_than(x,pivot)],less_than)
return left + [pivot] + right... | def quick_sort(seq, less_than):
if len(seq) < 1:
return seq
else:
pivot = seq[0]
left = quick_sort([x for x in seq[1:] if less_than(x, pivot)], less_than)
right = quick_sort([x for x in seq[1:] if not less_than(x, pivot)], less_than)
return left + [pivot] + right |
# -*- coding: utf-8 -*-
"""
Copyright (C) 2014 Netflix, Inc.
Copyright (C) 2021 Stefano Gottardo (python porting)
SSDP Server helper
SPDX-License-Identifier: BSD-2-Clause
See LICENSES/BSD-2-Clause-Netflix.md for more information.
"""
# IMPORTANT: Make sure to maintain the header structure with exac... | """
Copyright (C) 2014 Netflix, Inc.
Copyright (C) 2021 Stefano Gottardo (python porting)
SSDP Server helper
SPDX-License-Identifier: BSD-2-Clause
See LICENSES/BSD-2-Clause-Netflix.md for more information.
"""
search_response = 'HTTP/1.1 200 OK\nLOCATION: http://{ip_addr}:{port}/ssdp/device-desc.xm... |
class LigneTexte:
"""Une ligne de texte dans un document. """
def __init__(self, texte):
self.texte = texte
| class Lignetexte:
"""Une ligne de texte dans un document. """
def __init__(self, texte):
self.texte = texte |
'''
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
... |
"""
handler.py
A two operands handler.
"""
class Handler():
def handle(self, expression):
operator = None
operand_1 = None
operand_2 = None
error = None
try:
tokens = expression.split(" ")
operator = tokens[1]
operand_1 = int(tokens[0])... | """
handler.py
A two operands handler.
"""
class Handler:
def handle(self, expression):
operator = None
operand_1 = None
operand_2 = None
error = None
try:
tokens = expression.split(' ')
operator = tokens[1]
operand_1 = int(tokens[0])
... |
def spd_pgs_limit_range(data, phi=None, theta=None, energy=None):
"""
Applies phi, theta, and energy limits to data structure(s) by
turning off the corresponding bin flags.
Input:
data: dict
Particle data structure
Parameters:
phi: np.ndarray
Minimum and ma... | def spd_pgs_limit_range(data, phi=None, theta=None, energy=None):
"""
Applies phi, theta, and energy limits to data structure(s) by
turning off the corresponding bin flags.
Input:
data: dict
Particle data structure
Parameters:
phi: np.ndarray
Minimum and max... |
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 |
#Given two arrays, write a function to compute their intersection.
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
l=[]
for i in nums1:
if i in nums2:
l.append(i)
return list(set(l)) | class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
l = []
for i in nums1:
if i in nums2:
l.append(i)
return list(set(l)) |
"""
Module for YamlTemplateFieldBuilder
"""
__author__ = 'DWI'
class TemplateReader(object):
"""
Class for reading complete Templates from files.
"""
def __init__(self, template_field_builder):
self.field_builder = template_field_builder
def read(self, file_name):
"""
Re... | """
Module for YamlTemplateFieldBuilder
"""
__author__ = 'DWI'
class Templatereader(object):
"""
Class for reading complete Templates from files.
"""
def __init__(self, template_field_builder):
self.field_builder = template_field_builder
def read(self, file_name):
"""
Read... |
#!/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... |
# -*- coding: utf-8 -*-
def get_tokens(line):
"""tokenize an Epanet line (i.e. split words; stopping when ; encountered)"""
tokens=list()
words=line.split()
for word in words:
if word[:1] == ';':
break
else:
tokens.append(word)
return tokens
def read_epanet_file(fi... | def get_tokens(line):
"""tokenize an Epanet line (i.e. split words; stopping when ; encountered)"""
tokens = list()
words = line.split()
for word in words:
if word[:1] == ';':
break
else:
tokens.append(word)
return tokens
def read_epanet_file(filename):
"... |
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... |
"""
signals we use to trigger regular batch jobs
"""
run_hourly_jobs = object()
run_daily_jobs = object()
run_weekly_jobs = object()
run_monthly_jobs = object()
| """
signals we use to trigger regular batch jobs
"""
run_hourly_jobs = object()
run_daily_jobs = object()
run_weekly_jobs = object()
run_monthly_jobs = object() |
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] |
frutas = open('frutas.txt', 'r')
numeros = open('numeros.txt', 'r')
def copia_lista(lista:list)->list:
return lista.copy()
"""
if __name__ == "__main__":
lista_fruta_nueva=eliminar_un_caracter_de_toda_la_lista(lista_frutas,"\n")
print(lista_fruta_nueva)
""" | frutas = open('frutas.txt', 'r')
numeros = open('numeros.txt', 'r')
def copia_lista(lista: list) -> list:
return lista.copy()
'\nif __name__ == "__main__":\n lista_fruta_nueva=eliminar_un_caracter_de_toda_la_lista(lista_frutas,"\n")\n print(lista_fruta_nueva)\n' |
# 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... |
"""
File IO
1.Create
-------------------
f = open('file_name.txt','w')
f.close()
-------------------
2.Write
-------------------
f = open('file_name.txt','w')
data = 'hi'
f.write(data)
f.close()
-------------------
3.Read
1) Readline
-------------------
f ... | """
File IO
1.Create
-------------------
f = open('file_name.txt','w')
f.close()
-------------------
2.Write
-------------------
f = open('file_name.txt','w')
data = 'hi'
f.write(data)
f.close()
-------------------
3.Read
1) Readline
-------------------
f ... |
# 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) |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 28 22:08:00 2017
@author: Roberto Piga
"""
s = 'azcbobobegghakl'
s = 'abcbcd'
subString = ""
maxString = ""
charval = ""
for char in s:
if char >= charval:
subString += char
elif char < charval:
subString = char
charval ... | """
Created on Sat Jan 28 22:08:00 2017
@author: Roberto Piga
"""
s = 'azcbobobegghakl'
s = 'abcbcd'
sub_string = ''
max_string = ''
charval = ''
for char in s:
if char >= charval:
sub_string += char
elif char < charval:
sub_string = char
charval = char
if len(subString) > len(maxString... |
# 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)) |
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
m = len(matrix)
n = len(matrix[0]) if m else 0
if m * n == 0:
return False
if target < matrix[0][0]... | class Solution(object):
def search_matrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
m = len(matrix)
n = len(matrix[0]) if m else 0
if m * n == 0:
return False
if target < matrix[0][... |
# 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... |
# Write a function that takes a string as input and reverse only the vowels of a string.
# Example 1:
# Input: "hello"
# Output: "holle"
# Example 2:
# Input: "leetcode"
# Output: "leotcede"
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
... | class Solution(object):
def reverse_vowels(self, s):
"""
:type s: str
:rtype: str
"""
dic = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
string = list(s)
(i, j) = (0, len(string) - 1)
while i < j:
while i < j and string[i] not in dic... |
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 =... |
"""
Calculating the mean
"""
def calculate_mean(numbers):
s=sum(numbers)
N=len(numbers)
mean=s/N
return mean
def main():
donations=[100,60,70,900,100,200,500,500,503,600,1000,1200]
mean=calculate_mean(donations)
N=len(donations)
print("Mean donation over the last {0} days is {1}".forma... | """
Calculating the mean
"""
def calculate_mean(numbers):
s = sum(numbers)
n = len(numbers)
mean = s / N
return mean
def main():
donations = [100, 60, 70, 900, 100, 200, 500, 500, 503, 600, 1000, 1200]
mean = calculate_mean(donations)
n = len(donations)
print('Mean donation over the la... |
'''
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 |
class Base:
""" This is a class template. All the other classes will be made according to this templae """
def __init__(self) -> None:
""" constructor function """
pass
def enter(self, **param) -> None:
""" This function is called first when we change a group """
pa... | class Base:
""" This is a class template. All the other classes will be made according to this templae """
def __init__(self) -> None:
""" constructor function """
pass
def enter(self, **param) -> None:
""" This function is called first when we change a group """
pass
... |
# 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 |
# https://www.programiz.com/python-programming/function-argument
# Python allows functions to be called using keyword arguments. When we call
# functions in this way, the order (position) of the arguments can be changed.
# As we can see, we can mix positional arguments with keyword arguments during
# a function call. ... | def greet(name, msg='Good morning!'):
"""
This function greets to the person with the provided message.
If message is not provided, it defaults to "Good morning!"
"""
print('Hello', name + ', ' + msg)
greet(name='Bruce', msg='How do you do?')
greet(msg='How do you do?', name='Bruce')
greet('Bruce', ... |
"""
Topological Sort
"""
class Solution(object):
def alienOrder(self, words):
#return true if cycles are detected.
def dfs(c):
if c in path: return True
if c in visited: return False
path.add(c)
for nei in adj[c]:
if dfs(nei): return Tr... | """
Topological Sort
"""
class Solution(object):
def alien_order(self, words):
def dfs(c):
if c in path:
return True
if c in visited:
return False
path.add(c)
for nei in adj[c]:
if dfs(nei):
... |
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... |
def partition_labels(string):
#
"""
"""
indices = {}
for i, char in enumerate(string):
indices[char] = i
result = []
left, right = -1, -1
for i, char in enumerate(string):
right = max(right, indices[char])
if i == right:
result.append(right - le... | def partition_labels(string):
"""
"""
indices = {}
for (i, char) in enumerate(string):
indices[char] = i
result = []
(left, right) = (-1, -1)
for (i, char) in enumerate(string):
right = max(right, indices[char])
if i == right:
result.append(right - left)
... |
class Solution(object):
def dominantIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_index = -1
second_max_value = -1
for i in range(len(nums)):
if i == 0:
max_index = i
continue
value = n... | class Solution(object):
def dominant_index(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_index = -1
second_max_value = -1
for i in range(len(nums)):
if i == 0:
max_index = i
continue
value =... |
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,... |
# pylint: disable-all
"""Test inputs for day 2"""
test_position: str = """forward 5
down 5
forward 8
up 3
down 8
forward 2"""
test_position_answer: int = 150
test_position_answer_day_two: int = 900
| """Test inputs for day 2"""
test_position: str = 'forward 5\ndown 5\nforward 8\nup 3\ndown 8\nforward 2'
test_position_answer: int = 150
test_position_answer_day_two: int = 900 |
input = """
a :- b.
b | c.
d.
:- d, a.
"""
output = """
a :- b.
b | c.
d.
:- d, a.
"""
| input = '\na :- b.\nb | c.\n\nd.\n:- d, a.\n'
output = '\na :- b.\nb | c.\n\nd.\n:- d, a.\n' |
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) |
########################################################
# Copyright (c) 2015-2017 by European Commission. #
# All Rights Reserved. #
########################################################
extends("BaseKPI.py")
"""
Investment Analysis (euro)
---------------------------
Indexed ... | extends('BaseKPI.py')
'\nInvestment Analysis (euro)\n---------------------------\n\nIndexed by\n\t* scope\n\t* energy\n\t* test case\n\t* production asset\n\nThe Investment Analysis calculates the economic profitability of a given production asset in a given delivery point, defined as the difference between the produce... |
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 + ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.