content stringlengths 7 1.05M |
|---|
#
# Problem: Given an array of ints representing a graph, where:
# - the position of the array indicates the node value
# - the value of the array at that position indicates the node value that this node is attached to
# - the beginning of the graph will be the item whose value is equal to the index it is in
# Write a ... |
NEW_RANKING_RULES = ['typo', 'exactness']
DEFAULT_RANKING_RULES = [
'words',
'typo',
'proximity',
'attribute',
'sort',
'exactness'
]
def test_get_ranking_rules_default(empty_index):
"""Tests getting the default ranking rules."""
response = empty_index().get_ranking_rules()
assert i... |
def distinct(collection: list) -> int:
"""
Checks for the distinct values in a collection and returns the count
Performs operation in nO(nlogn) time
:param collection: Collection of values
:returns number of distinct values in the collection
"""
length = len(collection)
if length == 0:
... |
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/83511833
# IDEA : DP
# STATUS EQ : dp[i] = [b | A[i] for b in dp[i - 1]] + A[i]
class Solution(object):
def subarrayBitwiseORs(self, A):
"""
:type A: List[int]
:rtype: int
"""
res = set()
cur = set()
... |
pt = int(input("Qual o primeiro termo? "))
r = int(input("Qual a razão? "))
soma = pt + (10-1)*r
for c in range(pt, soma + r, r):
print(c, end=" ")
|
#!/usr/bin/python
# ==============================================================================
# Author: Tao Li (taoli@ucsd.edu)
# Date: Jun 11, 2015
# Question: 225-Implement-Stack-using-Queues
# Link: https://leetcode.com/problems/implement-stack-using-queues/
# =========================================... |
"""
Кобзарь О.С. Водопьян А.О. Хабибуллин Р.А. 09.08.2019
Модуль-интерфейс-инструмент для извлечения данных из расчетных классов
"""
# TODO обеспечить хранение внутренних классов на любом уровне вложенности, пока сохраняется только верхний
# TODO использоавать встроенную библиотеку collection.defaultdict
# TODO пос... |
#!/usr/bin/env python3
def color_translator(color):
if color == "red":
hex_color = "#ff0000"
elif color == "green":
hex_color = "#00ff00"
elif color == "blue":
hex_color = "#0000ff"
return hex_color
print(color_translator("blue")) #Should be #0000fff
print(color_translator("yell... |
"""[if文について]
もし〜だったら、こうして
"""
# 条件によって処理を変えたい場合などに使います
distance = 3403 |
def create_multi_graph(edges):
graph = dict()
for x, y in edges:
graph[x] = []
graph[y] = []
for x, y in edges:
graph[x].append(y)
return graph
def is_eulerian(multi_graph):
number_enter = dict()
number_exit = dict()
for vertex in multi_graph:
number_enter... |
class IntCode:
def __init__(self, intcode):
self.index = 0
self.output_ = 0
self.intcode = intcode
def add(self, a, b):
return a + b
def mult(self, a, b):
return a * b
def store(self, v, p):
self.intcode[p] = v
def output(self, p):
... |
while True:
print(('=' * 20))
n = int(input('De qual valor você quer ver uma [VALOR NEGATIVO para PARAR]: '))
print(('=' * 20))
if n <= -1:
break
for c in range(1, 11):
print(f'{n} x {c} = {n*c}')
print('=' * 20)
print('Programa encerrado com sucesso. Volte sempre!') |
def math():
lists = []
count = 0
for i in range(20):
j = int(input())
lists.append(j)
for j in range(20)[::-1]:
print('N[' + str(count) + '] =', lists[j])
count += 1
if __name__ == '__main__':
math()
|
class NumberCheckerOnGroup:
@classmethod
def numberToGroup(cls, tNumber):
clsNumber = 1
if tNumber >= 1 and tNumber <= 9:
clsNumber = 1
elif tNumber >= 10 and tNumber <= 19:
clsNumber = 10
elif tNumber >= 20 and tNumber <= 29:
clsNumber = 20... |
# -*- coding: utf-8 -*-
"""
Created on 2014-09-16
:author: Natan Žabkar (nightmarebadger)
A for loop is usually used when we want to repeat a piece of code 'n' number of
times, or when we want to iterate through the elements of a list (or something
similar).
In this example our program will 'sing' out the 99 bottles... |
def between_markers(text: str, begin: str, end: str) -> str:
"""
returns substring between two given markers
"""
# your code here
return text[text.find(begin)+1:text.find(end)]
if __name__ == '__main__':
print('Example:')
print(between_markers('What is >apple<', '>', '<'))
# These... |
#addBorder
picture = ["abc", "ded"]
def addBorder(mang):
print("*****")
for x in mang:
print("*"+x+"*")
print("*****")
|
class Student:
free_students = set()
def __init__(self, sid: int, pref_list: list, math_grade, cs_grade, utils):
self.sid = sid
self.math_grade = math_grade
self.cs_grade = cs_grade
self.pref_list = pref_list
self.project = None
self.utils = utils
self.pa... |
text = "X-DSPAM-Confidence: 0.8475"
pos = text.find(':')
numString = text[pos+1:]
num = float(numString)
print(num)
|
x = [42,34,33,35,99]
end = len(x) - 1
"""
if len(x) % 2 == 0:
m = int((0 + end) / 2)
else:
m = int((0 + end + 1) / 2)
print(m)
"""
def find(arr, start, stop):
# global peak
if stop % 2 == 0:
mid = int((start + stop) / 2)
else:
mid = int((start + stop - 1) / 2)
if arr... |
def IsPrime(num):
for i in range(2, num):
if num % i == 0:
return False
return True
fac = []
def solve(num):
i = 2
while i <= num:
if not IsPrime(i):
i += 1
continue
if num % i == 0:
fac.append(i)
num /= i
else... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class TrackedObj(object):
def __init__(self, val):
self.val = val
def __str__(self):
return '[%s]' % self.val
class TrackField(TrackedObj):
pass
class TrackIndex(TrackedObj):
pass
class TrackVariant(TrackedObj):
pass
class Trac... |
class DataGridBoolColumn(
DataGridColumnStyle,
IComponent,
IDisposable,
IDataGridColumnStyleEditingNotificationService,
):
"""
Specifies a column in which each cell contains a check box for representing a Boolean value.
DataGridBoolColumn()
DataGridBoolColumn(prop: PropertyDescr... |
def standardize_text(df, question_field):
df[question_field] = df[question_field].str.replace(r"http\S+", "")
df[question_field] = df[question_field].str.replace(r"http", "")
df[question_field] = df[question_field].str.replace(r"@\S+", "")
df[question_field] = df[question_field].str.replace(
r"[... |
class Solution:
def countPairs(self, nums: List[int], k: int) -> int:
ans = 0
gcds = Counter()
for num in nums:
gcd_i = math.gcd(num, k)
for gcd_j, count in gcds.items():
if gcd_i * gcd_j % k == 0:
ans += count
gcds[gcd_i] += 1
return ans
|
class WebDriverFactory:
def __init__(self):
self._drivers = {}
self._driver_options = {}
def register_web_driver(self, driver_type, web_driver, driver_options):
self._drivers[driver_type] = web_driver
self._driver_options[driver_type] = driver_options
def get_registered_web... |
class Solution(object):
def countConsistentStrings(self, allowed, words):
"""
:type allowed: str
:type words: List[str]
:rtype: int
"""
str_count = 0
for i in words:
flag = True
str_count += 1
for j in i:
if ... |
class Image:
def __init__(self):
pass
# @classmethod
# def load(cls, path):
#
# raise NotImplementedError
|
'''
Just like a balloon without a ribbon, an object without a reference variable cannot be used later.
'''
class Mobile:
def __init__(self, price, brand):
self.price = price
self.brand = brand
Mobile(1000, "Apple")
#After the above line the Mobile
# object created is lost and unusable
|
expected_output = {
"slot": {
"rp0": {
"cpu": {
"0": {
"idle": 99.1,
"irq": 0.0,
"nice_process": 0.0,
"sirq": 0.0,
"system": 0.2,
"user": 0.7,
"waiting... |
# Create a program that receives two strings on a single line separated by a single space.
# Then, it prints the sum of their multiplied character codes as follows:
# multiply str1[0] with str2[0] and add the result to the total sum, then continue with the next two characters.
# If one of the strings is longer than ... |
OPENERS = {'(', '{', '['}
CLOSER_MAP = {')': '(', '}': '{', ']': '['}
def solve(s: str) -> bool:
stack = []
for c in s:
if c in OPENERS:
stack.append(c)
elif len(stack) == 0 or stack.pop() != CLOSER_MAP[c]:
return False
return True if len(stack) == 0 else False
def ... |
"""
Given the triangle of consecutive odd numbers:
1
3 5
7 9 11
13 15 17 19
21 23 25 27 29
...
Calculate the row sums of this triangle from the row index (starting at index 1)
"""
def row_sum_odd_numbers(number: int) -> int:
"""Returns the row sums... |
'''
Task:
Your task is to write a function which returns the sum of following series upto nth term(parameter).
Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +...
Rules:
You need to round the answer to 2 decimal places and return it as String.
If the given value is 0 then it should return 0.00
You will only be given Nat... |
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython
Even though the group is only for spanish speakers, english
speakers are welcome.
"""
numbers = [50, 30, 20, 50, 50, 62, 70, 50]
# just the first match
print("Index ->", numbers.index(50))
# output: Index -> 0
# all matches
print("Indexes ->", list((i fo... |
# -*- coding: utf-8 -*-
"""
1963. Minimum Number of Swaps to Make the String Balanced
https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced/
Example 1:
Input: s = "][]["
Output: 1
Explanation: You can make the string balanced by swapping index 0 with index 3.
The resulting string is "[[]]... |
def count_unique_values(arr):
# return 0 of the length of array is 0
# loop the array by the second element at index j
# compare the previous element at index i
arr_len = len(arr)
if arr_len == 0:
return 0
pre_index = 0
unique_arr = [arr[pre_index]]
for j in range(1, arr_len):
... |
#05_01_converter
class ScaleConverter:
def __init__(self, units_from, units_to, factor):
self.units_from = units_from
self.units_to = units_to
self.factor = factor
def description(self):
return 'Convert ' + self.units_from + ' to ' + self.units_to
def convert(self, value):
return value * self.factor
... |
#local storage
LOCAL="/home/pi/MTU-Timelapse-Pi"
#in minutes. 60 % interval must be 0
INTERVAL=5
#time between failed uploads
FAILTIME=5
#retry count
RETRYCOUNT=3
CMD="raspistill -o '/home/pi/MTU-Timelapse-Pi/cam/%s/%s-%s.jpg' -h 1080 -w 1920 --nopreview --timeout 1"
|
#!/usr/bin/env python3
"""
This Python script is to create temporary dictionary caches. These caches are
designed to limit redundant queries.
"""
__author__ = 'John Bumgarner'
__date__ = 'October 15, 2020'
__status__ = 'Production'
__license__ = 'MIT'
__copyright__ = "Copyright (C) 2020 John Bumgarner"
#############... |
"""Zero_Width table. Created by setup.py."""
# Generated: 2020-03-23T04:40:34.685051
# Source: DerivedGeneralCategory-13.0.0.txt
# Date: 2019-10-21, 14:30:32 GMT
ZERO_WIDTH = (
(0x0300, 0x036F,), # Combining Grave Accent ..Combining Latin Small Le
(0x0483, 0x0489,), # Combining Cyrillic Titlo..Combining Cyr... |
class line(object):
def __init__(self, _char, _row, _column, _dir, _length):
self.char = _char
self.row = _row
self.column = _column
self.dir = _dir
self.length = _length
return None
|
"""Compare two version numbers version1 and version2.
If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.
You may assume that the version strings are non-empty and contain only digits and the . character.
The . character does not represent a decimal point and is used to separate numb... |
A, B, C = map(int, input().split())
print((A+B)%C)
print((A%C+B%C)%C)
print((A*B)%C)
print(((A%C)*(B%C))%C)
|
lst_1=[1,2,4,88]
lst_2=[1,3,4,95,120]
lst_3=[]
i=0
j=0
for k in range(len(lst_1)+len(lst_2)):
if (lst_1[i]<= (lst_2[j])):
lst_3.append(lst_1[i])
if (i>=len(lst_1)-1):
if j<=(len(lst_2)-1):
lst_3.append(lst_2[j])
if j<len(lst_2)-1:
... |
class JournalBlock:
"""
Represents a JournalBlock that was recorded after executing a transaction in the ledger.
"""
def __init__(self, block_address, transaction_id, block_timestamp, block_hash, entries_hash, previous_block_hash,
entries_hash_list, transaction_info, revisions):
... |
__author__ = 'shukkkur'
'''
https://codeforces.com/problemset/problem/1475/B
B. New Year's Number
'''
t = int(input())
for _ in range(t):
n = int(input())
if n < 2020:
print('NO')
else:
if n % 2020 <= n / 2020:
print('YES')
... |
def caller():
a = []
for i in range(33, 49):
a.append(chr(i))
b = []
c = []
d = []
for i in range(65, 91):
b.append(chr(i))
for i in range(97, 123):
c.append(chr(i))
for i in range(48, 58):
d.append(chr(i))
... |
"""
A list of CSS properties to expand.
Format:
(property, [aliases], unit, [values])
- property : (String) the full CSS property name.
- aliases : (String list) a list of aliases for this shortcut.
- unit : (String) when defined, assumes that the property has a value with a
unit. When the value is numberless (... |
class Beacon():
def __init__(self, sprite, type):
self.sprite = sprite
self.type = type
'''
self.x = 0
self.y = 0
def set_pos(self, x, y):
self.x = x
self.y = y
'''
@property
def position(self):
return self.sprite.posit... |
#Escreva um programa que leia a velocidade de um carro.
#Se ela ultrapassar 80km/h, mostre a mensagem dizendo que ele foi multado.
#A multa vai custar R$7,00 por cada km acima do limite
vel = float(input('Qual é a velocidade atual do carro? '))
if vel > 80:
print('Você acaba de ser multado. O valor d... |
class Attribute:
NAME = 'Keyboard'
class KeyState:
LEFT_ARROW_DOWN = 'leftArrowDown'
RIGHT_ARROW_DOWN = 'rightArrowDown'
UP_ARROW_DOWN = 'upArrowDown'
DOWN_ARROW_DOWN = 'downArrowDown'
|
#Hierarchical Inheritance
class A: #Super Class or Parent Class
def feature1(self):
print("Feature 1 Working")
def feature2(self):
print("Feature 2 Working")
class B(A): # Subclass or Child Class
def feature3(self):
print("Feature 3 Working")
def feature4(self):
pr... |
def hurdleRace(k, height):
if k >= max(height):
return 0
else:
return max(height) - k
# test case
h = [1,3,4,5,2,5]
print(hurdleRace(3, h)) # Should be 2
print(hurdleRace(8, h)) # Should be 0 |
DATETIME_FORMAT = 'j. F Y H:i'
SHORT_YEAR_FORMAT = 'Y'
SHORT_MONTH_FORMAT = 'b'
SHORT_DAY_FORMAT = 'j.'
SHORT_DAY_MONTH_FORMAT = 'j.n.'
SHORT_YEAR_MONTH_FORMAT = 'n/Y'
SHORT_DATE_FORMAT = 'j.n.Y'
SHORT_TIME_FORMAT = 'q'
LONG_DATE_FORMAT = 'l, j. F Y'
YEAR_FORMAT = 'Y'
MONTH_FORMAT = 'F'
DAY_FORMAT = 'j.'
DAY_MONTH... |
# try:
# except KeyError:
# return render(request, "circle/error.html", context={"message": "Upload file.!!", "type": "Key Error", "link": "newArticle"})
# except ValueError:
# return render(request, "circle/error.html", context={"message": "Invalid Value to given field image.!!", "type": "Value Error", "link... |
class Solution:
def isPalindrome(self, s: str) -> bool:
string2 = ""
for character in s.lower():
if character.isalnum():
string2 += character
if string2 == string2[::-1]:
return True
return False
|
squares = [value ** 2 for value in range(1, 11)]
print(squares)
cubes = [value ** 3 for value in range(1, 11)]
print(cubes)
a_million = list(range(1, 1_000_0001))
print(min(a_million))
print(max(a_million))
print(sum(a_million))
|
class Restaurant:
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_serverd = 0
def describe_restaurant(self):
print(f'Welcome to {self.restaurant_name.title()}')
print(f'Our cousine ... |
mtx = []
while True:
n = str(input())
if n == 'end':
break
mtx.append([int(s) for s in n.split()])
out_mtx = [[0 for j in range(len(mtx[i]))] for i in range(len(mtx))]
for i in range(len(mtx)):
for j in range(len(mtx[i])):
ylen = len(mtx)
xlen = len(mtx[0])
out_mtx[i][... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# @Author: Bai Lingnan
# @Project: Pytorch-Template
# @Filename: metric.py
# @Time: 2020/3/12 10:15
"""
"""
tricks:
1.torch-optimizer:实现了最新的一些优化器.
2.numba:import numba as nb,纯python或numpy加速,加@nb.njit或@nb.jit(nopython=True)
3.swifter:df.apply()→·df.sw... |
# https://leetcode.com/problems/check-array-formation-through-concatenation/
class Solution:
def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool:
result = []
for j in arr:
for i in pieces:
if i[0] == j:
for m in range(len... |
a = 10
b = 3
print('Add -', a + b)
print('Subtract -', a - b)
print('Multiply -', a * b)
print('Divide (with floating point) -', a / b)
print('Divide (ignoring floats) -', a // b)
# With interactive python
# >>> 10 / 3
# 3.3333333333333335
# >>> 10.0 / 3
# 3.3333333333333335
# >>> 10 // 3
# 3
# >>> 10 // 3.0
# 3.0
p... |
class IrregualrConfigParser(object):
COMMENT_FLAGS = ("#", ";")
def __init__(self):
super(IrregualrConfigParser, self).__init__()
self.__content = []
def read(self, fn_or_fp):
content = []
if isinstance(fn_or_fp, file):
content = [line.strip() for line in fn_or_... |
# -*- coding: utf-8 -*-
'''
tagset_constants.py.py
Constants for opencorpora and syntagrus tagsets
Author: mkudinov
'''
#Grammar categories
CAT_POS = u'POS'
CAT_ANIMACY = u'ANIMACY'
CAT_GENDER = u'GENDER'
CAT_NUMBER = u'NUMBER'
CAT_CASE = u'CASE'
CAT_ASPECT = u'ASPECT'
CAT_TENSE = u'TENSE'
CAT_MODE = u'MODE'
CAT_VOI... |
def readConstants(constants_list):
constants = []
for attribute, value in constants_list.items():
constants.append({"name": attribute, "cname": "c_" + attribute, "value": value})
return constants
def readClocks(clocks_lists):
clocks = {"par": [], "seq": []}
for attribute, value in clocks_... |
def main() -> None:
N = int(input())
S = []
T = []
for _ in range(N):
S.append(input())
for _ in range(N):
T.append(input())
assert 1 <= N <= 100
assert all(len(S_i) == N for S_i in S)
assert all(len(T_i) == N for T_i in S)
assert all(S_ij in ('.', '#') for S_i in S... |
#
# @lc app=leetcode id=134 lang=python3
#
# [134] Gas Station
#
# https://leetcode.com/problems/gas-station/description/
#
# algorithms
# Medium (35.34%)
# Likes: 966
# Dislikes: 321
# Total Accepted: 163.9K
# Total Submissions: 463.7K
# Testcase Example: '[1,2,3,4,5]\n[3,4,5,1,2]'
#
# There are N gas stations ... |
""" --- Even the last --- Elementary
You are given an array of integers. You should find the sum of the
elements with even indexes (0th, 2nd, 4th...) then multiply this summed
number and the final element of the array together.
Don't forget that the first element has an index of 0.
For an empty array, the result wi... |
def fib(n):
if n == 1:
return 1
return n + fib(n-1)
def main():
n = 0
m = 1
result = 0
while n < 4000000:
tmp = n
n = n + m
m = tmp
if n % 2 == 0:
result += n
# print(n, n % 2)
# print(n, result)
print("Problem 2:", result)
|
# file path (load_data.py, main.py, and compute_relation_vectors.py)
_SOURCE_DATA = '../data/source.csv'
_TARGET_DATA = '../data/target.csv'
_RESULT_FILE = '../results/results.csv'
_MEAN_RELATION = '../results/relation_vectors_before.csv'
_MODIFIED_MEAN_RELATINON = '../results/relation_vectors_after.csv'
_COUNT_... |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
# Copyright © 2021 by Shun Huang. All rights reserved.
# Licensed under MIT License.
# See LICENSE in the project root for license information.
variable = 10
variable = "string"
variable = 2.0
variable = [1, 2, 3]
|
class Instruction:
def __init__(self, name):
if not(name in dir(self)):
raise Exception("Instruction not exists")
self.name = name
def execute(self, cpu, a, b, c):
func = getattr(self,self.name)
func(cpu, a, b, c)
def addr(self, cpu, a, b, c):
... |
TITLE = "Служба восстановления данных"
STATEMENT_TEMPLATE = '''
В службу восстановления данных с флешек и дисков обратился клиент. Он принёс эту флешку. Говорит, что случайно её отформатировал. Посмотрите, что здесь можно сделать.
[usb.img.tar.gz](http://ctf.sicamp.ru/static/xn9gwqz3/{0}.tar.gz)
'''
def generate... |
'''
modifier: 02
eqtime: 10
'''
def main():
info("Jan Air Sniff Pipette x1")
gosub('jan:WaitForMiniboneAccess')
gosub('jan:PrepareForAirShot')
gosub('jan:EvacPipette2')
gosub('common:FillPipette2')
gosub('jan:PrepareForAirShotExpansion')
close(name="M", description="Microbone to Getter NP-10... |
class Verdict:
OK = 'OK'
WA = 'WA'
RE = 'RE'
CE = 'CE'
TL = 'TL'
ML = 'ML'
FAIL = 'FAIL'
NR = 'NR'
|
# 2014.10.20 12:29:04 CEST
typew = {'AROMATIC': 3.0,
'DOUBLE': 2.0,
'TRIPLE': 3.0,
'SINGLE': 1.0}
heterow = {False: 2,
True: 1}
missingfragmentpenalty = 10.0
mims = {'H': 1.0078250321,
'He': 3.016029,
'Li': 6.015122,
'Be': 9.012182,
'B': 10.012937,
'C': 12.000000,
'N': 14.0030740052,
'O': 15.9949146221,
'F... |
for i in range(1, 101):
name = str(i)
name = name + ".txt"
print(name)
print(type(name))
arq = open(name, "w")
arq.close();
|
guild = """CREATE TABLE IF NOT EXISTS guild (guild_id bigint NOT NULL, guild_name varchar(100) NOT NULL,
prefix varchar(5), server_log bigint, mod_log bigint, ignored_channel bigint[], lockdown_channel bigint[],
filter_ignored_channel bigint[], profanity_check boolean DEFAULT false, invite_link boolean DEFAULT false,
P... |
def post_to_dict(post):
data = {}
data["owner_username"] = post.owner_username
data["owner_id"] = post.owner_id
data["post_date"] = post.date_utc
data["post_caption"] = post.caption
data["tagged_users"] = post.tagged_users
data["caption_mentions"] = post.caption_mentions
data["is... |
class Solution:
def equationsPossible(self, equations: List[str]) -> bool:
parent = {}
def findParent(x):
if x not in parent:
parent[x] = x
else:
while parent[x] != x:
parent[x] = parent[parent[x]]
x = pa... |
def new_decorator(func):
def wrapper_func():
print('code before executing func')
func()
print('func() has been called')
return wrapper_func
@new_decorator
def func_needs_decorator():
print('this function is in need of decorator!')
# func_needs_decorator()
# before adding @new_d... |
class Stats:
def min(dataset):
value = dataset[0]
for data in dataset:
if data < value:
value = data
return value
def max(dataset):
value = dataset[0]
for data in dataset:
if data > value:
value = data
return value
def range(dataset):
return Stats.max(dataset) - Stats.min(dataset)
def me... |
# -*- coding: utf-8 -*-
#
# Copyright © 2020 The Aerospace Corporation
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the “Software”), to deal in the Software without restriction, including without limitation
# the rights to use, c... |
########
# PART 1
# on python 3.7+ can just call pow(base, exp, mod), no need to implement anything!
def modexp(base, exp, mod):
''' mod exp by repeated squaring '''
res = 1
cur = base
while (exp > 0):
if (exp % 2 == 1):
res = (res * cur) % mod
exp = exp >> 1
cur = ... |
# swap it to get solution
fin = open("pic.png", "rb")
fout = open("../public/file.bin", "wb")
data = fin.read()[::-1]
result = bytearray()
for byte in data:
high = byte >> 4
low = byte & 0xF
rbyte = (low << 4) + high
result.append(rbyte)
fout.write(result)
fout.close()
|
WTF_CSRF_ENABLED = True
SECRET_KEY = 'you-will-never-guess'
projects = {}
|
# -*- encoding: utf-8 -*-
SCORE_NONE = -1
class Life(object):
"""个体类"""
def __init__(self, aGene = None):
self.gene = aGene
self.score = SCORE_NONE
|
# some specific relevant fields
timestamp_field = 'requestInTs'
service_call_fields = ["clientMemberClass", "clientMemberCode", "clientXRoadInstance", "clientSubsystemCode", "serviceCode",
"serviceVersion", "serviceMemberClass", "serviceMemberCode", "serviceXRoadInstance",
... |
##1
x = float(input())
if x < 60:
print("不及格")
elif 60 < x and x < 80:
print("及格")
elif 80 < x and x < 90:
print("良好")
elif 90 < x and x < 100:
print("优秀")
|
class Mesh(GeometryObject,IDisposable):
""" A triangular mesh. """
def Dispose(self):
""" Dispose(self: Mesh,A_0: bool) """
pass
def ReleaseManagedResources(self,*args):
""" ReleaseManagedResources(self: APIObject) """
pass
def ReleaseUnmanagedResources(self,*args):
""" ReleaseUnmanagedResources(... |
n, k = map(int, input().split())
graph = []
printInfo = []
for i in range(n):
graph.append([])
for i in range(k):
oper, u, v = input().split()
u = int(u) - 1
v = int(v) - 1
if oper == '+':
graph[u] += [v]
graph[v] += [u]
if oper == '?':
if not(graph[u] and graph[v]):
printInfo += ['?']
elif set... |
# A colection of key value pairs
# Keys need to be a string
my_dict = {'name':'john', 'age':27, 'gender':'male', 'subs': ['Eng', 'Math', 'Sci'], 'marks':(58, 79,63)}
print(my_dict['name'])
print(my_dict['age'])
my_dict['age'] += 3
print(my_dict['age'])
print(my_dict['subs'])
print(my_dict['marks'])
print(my_dict['s... |
str1="Never give in — Never, never, never, never, in nothing great or small, \
large or petty, never give in except to convictions of honour and good sense. \
Never yield to force; never yield to the apparently overwhelming might of the enemy. O horror, horror, horror. \
Words, words, word. But you never know now ... |
simulation_parameters = {
'temperature', 'integrator', 'collisions_rate', 'integration_timestep',
'initial_velocities_to_temperature', 'constraint_tolerance', 'platform', 'cuda_precision'
}
def is_simulation_dict(dictionary):
keys=set(dictionary.keys())
output = (keys <= simulation_parameters)
... |
# %% [836. *Rectangle Overlap](https://leetcode.com/problems/rectangle-overlap/)
# 問題:2つの長方形が重なるかどうかを返せ
# 解法:X軸、Y軸で重なるかを調べる
class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
x1, y1, x2, y2, x3, y3, x4, y4 = *rec1, *rec2
return x1 < x4 and x3 < x2 and y1 < y4 and... |
"""
isValidIP("0.0.0.0") ==> true
isValidIP("12.255.56.1") ==> true
isValidIP("137.255.156.100") ==> true
isValidIP('') ==> false
isValidIP('abc.def.ghi.jkl') ==> false
isValidIP('123.456.789.0') ==> false
isValidIP('12.34.56') ==> false
isValidIP('01.02.03.04') ==> false
"""
def isValidIP(string):
info = strin... |
"""
Regression utils
"""
class Regressor(object):
def __init__(self):
pass
def fit(self):
pass
|
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"triee": "00_core.ipynb",
"cov": "01_oval_clean.ipynb",
"numpts": "01_oval_clean.ipynb",
"Points": "01_oval_clean.ipynb",
"vlen": "01_oval_clean.ipynb",
"major": "... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.