content stringlengths 7 1.05M |
|---|
#!/usr/bin/env python
""" Problem 38 daily-coding-problem.com """
def n_queens(n, board=[]):
''' see https://www.dailycodingproblem.com/blog/an-introduction-to-backtracking/'''
if n == len(board):
return 1
count = 0
for col in range(n):
board.append(col)
if is_valid(board):
... |
class American(object):
pass
class NewYorker(American):
pass
anAmerican = American()
aNewYorker = NewYorker()
|
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
# hash表方法
hashmap1 = {}
hashmap2 = {}
for s1, t1 in zip(s, t):
# 建立一次对应关系之后,发现于原来的不一致
# (原来存在过,但是这个是新的)
if hashmap1.get(s1, t1) != t1 or hashmap2.get(t1, s1) != s1:
ret... |
# [7 kyu] Descending Order
#
# Author: Hsins
# Date: 2019/12/31
def descending_order(num):
return int("".join(sorted(str(num), reverse=True)))
|
def minimum_bracket_reversals(input_string):
if len(input_string) % 2 == 1:
return -1
stack = Stack()
count = 0
for bracket in input_string:
if stack.is_empty():
stack.push(bracket)
else:
top = stack.top()
if top != bracket:
if... |
'''解説読んだ'''
H,W,A,B=[int(x) for x in input().split()]
[print(''.join(["0" if j<A else "1" for j in range(W)])) if i<B else print(''.join(["1" if j<A else "0" for j in range(W)])) for i in range(H)]
# 読みやすいバージョン
for i in range(H):
if i < B:
print(''.join(["0" if j < A else "1" for j in range(W)]))
else:... |
# -*- coding: utf-8 -*-
"""
460. LFU Cache
Design and implement a data structure for Least Frequently Used (LFU) cache.
It should support the following operations: get and set.
"""
class LFUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity = ca... |
def intercalaEmOrdem(lista1, lista2):
intercalada = []
lista1.sort()
lista2.sort()
while len(lista1) > 0 and len(lista2) > 0:
if lista1[0] < lista2[0]:
intercalada.append(lista1.pop(0))
else:
intercalada.append(lista2.pop(0))
if len(lista1) > 0:
inte... |
def f2(a):
global b
print(a)
print(b)
b = 9
print(b)
b = 5
f2(3) |
#
# PySNMP MIB module CPQCLUSTER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CPQCLUSTER-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:27:15 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... |
#!/usr/bin/env python
f = open('/Users/kosta/dev/advent-of-code-17/day10/input.txt')
lengths = list(map(int, f.readline().split(',')))
hash_list = list(range(256))
skip = 0
cur_index = 0
for length in lengths:
if cur_index + length > len(hash_list):
sub_list = hash_list[cur_index:]
sub_list.exten... |
def softmax(x):
t = np.exp(x)
return t/t.sum()
q_relu = softmax(C @ relu(A @ x + b) + d)
q_sigmoid = softmax(C @ sigmoid(A @ x + b) + d) |
"""Image-to-text implementation based on http://arxiv.org/abs/1411.4555.
"Show and Tell: A Neural Image Caption Generator"
Oriol Vinyals, Alexander Toshev, Samy Bengio, Dumitru Erhan
"""
class ShowAndTellModel(object):
"""Image-to-text implementation based on http://arxiv.org/abs/1411.4555.
"Show and Tell: A Neural ... |
# Filters and the expression register are two really cool ways of calling arbitrary code from vim.
# Filters are just anything that takes your text via stdin and gives you something via stdout
# Filters can be invoked via `!{motion}` or `!` while selecting, and can call arbitrary scripts
# Examples with either `!}` or... |
#encoding:utf-8
subreddit = 'india'
t_channel = '@r_indiaa'
def send_post(submission, r2t):
return r2t.send_simple(submission)
|
"""
Problem:
There are three types of edits that can be performed on strings: insert
a character, remove a character, or replace a character. Given two
strings, write a function to check if they are one edit (or zero edits)
away.
Implementation:
An initial solution might check for all three cases s... |
#Write a program that reads the words in words.txt and stores them as keys in a dictionary.
#It doesn’t matter what the values are. Then you can use the in operator as a fast way
#to check whether a string is in the dictionary.
name = input("Enter file:")
if len(name) < 1:
name = "text.txt"
handle = open(... |
microcode = '''
def macroop VCVTSD2SS_XMM_XMM {
cvtf2f xmm0, xmm0m, destSize=4, srcSize=8, ext=Scalar
movfph2h xmm0, xmm0v, dataSize=4
movfp xmm1, xmm1v, dataSize=8
vclear dest=xmm2, destVL=16
};
def macroop VCVTSD2SS_XMM_M {
ldfp ufp1, seg, sib, disp, dataSize=8
cvtf2f xmm0, ufp1, destSize=4... |
# --- Day 2: I Was Told There Would Be No Math ---
def createLineList(input):
lineList = [line.rstrip('\r\n') for line in open(input)]
return lineList
def createDimList(lines):
dimList = []
for L in lines:
dim = L.split("x")
for i in range(0, len(dim)):
dim[i] = int(dim[i])
dimList.append(dim)
return di... |
"""
Problem:
Write a function that returns the bitwise AND of all integers between M and N,
inclusive.
"""
def bitwise_and_on_range(start: int, end: int) -> int:
# using naive approach
result = start
for num in range(start + 1, end + 1):
result = result & num
return result
if __name__ == "_... |
__author__ = 'burakks41'
line1 = input().split()
line2 = input().split()
flowers = int(line1[0])
persons = int(line1[1])
person = [0] * persons
flowers_cost = sorted([int(n) for n in line2],reverse=True)
sum = 0
for i in range(flowers):
x, person[i % persons] = person[i % persons], person[i % persons] + 1
su... |
"""
返回字符串中第一个不重复的字符
输入:ABCACDBEFD
输出:E
"""
str01="ABCACDBEFD"
for i in str01:
if str01.count(i)==1:
print(i)
break
# def not_repead(str01):
# for i in str01:
# if str01.count(i) == 1:
# return i
#
# res=not_repead("ABCACDBEFD")
# print(res) |
# You are given an array of non-negative integers numbers. You are allowed to choose any number from this array and swap any two digits in it. If after the swap operation the number contains leading zeros, they can be omitted and not considered (eg: 010 will be considered just 10).
# Your task is to check whether it... |
def balanced_split_exists(arr):
if len(arr) < 2 or sum(arr) % 2 != 0:
return False
arr.sort() # n log n
l, r = 0, len(arr) - 1
left_sum, right_sum = arr[l], arr[r]
while l <= r:
if arr[l] >= arr[r]:
return False
if left_sum < right_sum:
l += 1
... |
def get_hours_since_midnight(total_seconds):
hours = total_seconds // 3600
return hours
total_seconds = int(input('Enter a number of seconds: '))
hours = get_hours_since_midnight(total_seconds)
format(hours,'02d')
def get_minutes(total_seconds):
minutes = ( total_seconds % 3600)
minutes //= 60
re... |
# 常量性质的东西都放到这里
# 普通脚本只放功能性的东西
domains = {
'JP':'https://www.amazon.co.jp',
'UK':'https://www.amazon.co.uk',
'ES':'https://www.amazon.es',
'FR':'https://www.amazon.fr',
'US':'https://www.amazon.com',
'IT':'https://www.amazon.it',
'DE':'https://www.amazon.de',
'CA':'https://www.amazon.ca'... |
# Copyright (C) 2018-present ichenq@outlook.com. All rights reserved.
# Distributed under the terms and conditions of the Apache License.
# See accompanying files LICENSE.
CSHARP_MANAGER_TEMPLATE = """
public class %s
{
public const char TABUGEN_CSV_SEP = '%s'; // CSV field delimiter
public con... |
brd = {
'name': ('Raspberry Pi B+/2'),
'port': {
'rpigpio': {
'gpio' : {
# BCM/Functional RPi pin names.
'bcm2_sda' : '3',
'bcm3_scl' : '5',
'bcm4_gpclk0': '7',
'bcm17' : '11',
... |
n = int(input())
X = list(map(int, input().split()))
X.sort()
def median(n, X):
if n % 2 == 0:
numerator = X[int(n / 2)] + X[int(n / 2 - 1)]
median_value = numerator / 2
else:
median_value = X[int(n / 2)]
return int(median_value)
print(median(int(n / 2), X[: int(n / 2)]))
prin... |
{
'includes': [ '../common.gyp' ],
'targets': [
{
'target_name': 'libzxing',
'type': 'static_library',
'include_dirs': [
'core/src',
],
'sources': [
'core/src/bigint/BigInteger.cc',
'core/src/bigint/BigIntegerAlgorithms.cc',
'core/src/bigint/BigInteg... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 1 10:11:25 2022
@author: User
"""
# contadore de 1 en 1
cont = 0
cont +=1 #--> cont= cont + 1
# 1.- contar numero del 1 al 10 y mostrar en la pantalla
while cont < 10:
cont = cont + 1
print(cont)
# 2.- Sumar los numeros del 1 al 10
# list = {1,2,3,..... |
# /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# 20221BSI0153.py Aqui Entra o Nome do Arquivo do Código fonte
#
# Copyright 2022 Marllon Christiani dos Santos Ribeiro
#
def main():
# Declaração de variáveis
massa = float(0.000)
massa = float(input())
segundos = int(0)
minutos = int(0)
horas = int(0)
#I... |
# --------------
# Code starts here
class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio']
class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes']
new_class = (class_1 + class_2)
print (new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Carla Gentry')
print(new_c... |
def increment(x, by=1):
return x + by
def tokenize(sentence):
return pos_tag(word_tokenize(sentence))
def synsets(sentence):
tokens = tokenize(sentence)
return remove_none(tagged_to_synset(*t) for t in tokens)
def remove_none(xs):
return [x for x in xs if x is not None]
def score(synset, syn... |
#56-desenvolva um programa que leia o nome, idade e o sexo de 4 pessoas. no final do program,mostre:
#a media de idade do grupo
#qual e o nome do homem mais velho
#quantas mulheres tem menos de 20 anos
somaidade = 0
mediaidade=0
maioridadehome=0
nomevelho=''
totmulher20=0
for p in range(1, 5):
print('{}ª pessoa:'.f... |
# Function to find the first occurrence of a given number
# in a sorted list of integers
def findFirstOccurrence(A, x):
(left, right) = (0, len(A) - 1)
result = -1
while left <= right:
# find the mid-value in the search space and compares it with the target
mid = (left + right) // 2... |
class Solution(object):
def bruteforce(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
result = ''
if len(strs) == 0:
return ''
i = 0
d = {i: len(v) for i,v in enumerate(strs)}
count = min(d.values())
for i i... |
n = int(input(">> "))
sum = 0
for i in range(n):
sum = sum + (i+1)
print("1 から " + str(n) + " までの和は " + str(sum)) |
s1 = input()
s2 = input()
pairs = set()
for i in range(len(s2) - 1):
pairs.add(s2[i:i + 2])
ans = 0
for i in range(len(s1) - 1):
if s1[i: i + 2] in pairs:
ans += 1
print(ans)
|
# makes a BST from an array
class Node:
def __init__(self, value, left, right):
self.value = value
self.left = left
self.right = right
def bst_from_array(array, start, end):
if start >= end:
return None
mid = (start + end) // 2
value = array[mid]
left = bst_from_arra... |
# Author: Tianyao (Till) Chen
# Email: tillchen417@gmail.com
# File: settings.py
class Settings:
"""The class to store all the settings for Alien Invasion."""
def __init__(self):
"""Initialize the static settings."""
# Screen settings.
self.screen_width = 1200
self.screen_height... |
'''
Created on 24.05.2011
@author: Sergey Khayrulin
'''
class Position(object):
'''
Definition for position of point
'''
def __init__(self,proximal_point=None,distal_point=None):
'''
Constructor
'''
self.distal_point = distal_point
self.pr... |
sum_counter = 0
# 600851475143
number = 600851475143
for i in range(2, 10000):
for j in range(1, i + 1):
if i % j == 0:
sum_counter += 1
if sum_counter == 2:
# print(i, end= " ")
if number % i == 0:
print()
print(f"prime factors for {number} : {i}", ... |
'''Szablon z zarysem prostego "framework'u" dla tworzenia prostych gier.
'''
##
# jeżeli używamy dodatkowych modułów to zaimportujmy je tutaj
# ...
##
# definicje funkcji i zmiennych globalnych powinny znaleźć się tutaj
# ...
##
# kod głównej pętli gry
#
printGameDescription()
# flaga kontynuacji gry: True = gram... |
class MemoryItem:
def __init__(self, observation, action, next_observation, reward, done, info):
self.observation = observation
self.action = action
self.next_observation = next_observation
self.reward = reward
self.done = done
self.info = info
|
class Queen:
def __init__(self, pos, visited):
self.pos = pos
self.visited = visited
|
VALID_USER = {
"username": "Test",
"email": "test@email.com",
"password": "Test@123",
"password2": "Test@123",
}
|
class Solution:
def minJumps(self, arr, n):
jumps = [-1] * n
jumps[0] = 0
front = 0
rear = 0
while rear < n :
remaining_jumps = arr[rear] - (front - rear)
while remaining_jumps > 0 and front < n-1:
front += 1
j... |
#
# Copyright (c) 2013-2014, PagerDuty, Inc. <info@pagerduty.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notic... |
# 3. File Writer
# Create a program that creates a file called my_first_file.txt.
# In that file write a single line with the content: 'I just created my first file!'
# file = open("my_first_file.txt", "w")
#
# file.write('I just created my first file!')
#
# file.close()
# With manager is better than just open as it ... |
# Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento. Para salários superiores a R$1250,00, calcule um aumento de 10%. Para os inferiores ou iguais, o aumento é de 15%.
print('-' * 100)
print('{: ^100}'.format('EXERCÍCIO 034 - AUMENTOS MÚLTIPLOS'))
print('-' * 100)
salario =... |
# 4-5. Summing a Million: Make a list of the numbers from one to one million, and then use min() and max()
# to make sure your list actually starts at one and ends at one million.
# Also, use the sum() function to see how quickly Python can add a million numbers.
numbers = list(range(1, 1000001))
print(min(numbers))
... |
print('-=' * 20)
print('{:^40}'.format('\033[32mPRODUTO ALEATÓRIO QUALQUER.CIA\033[m'))
print('-=' * 20)
cont = soma = 0
print('DIGITE \033[1;30m0\033[m PARA FINALIZAR A OPERAÇÃO')
while True:
cont += 1
n = float(input(f'Produto {cont}: R$ '))
soma += n
if n == 0:
print(f'TOTAL: R$ {soma}')
... |
def print_formatted(number):
# your code goes here
if number in range (1,100):
l = len(bin(number)[2:])
for i in range (1,n+1):
decimal = str(i).rjust(l)
octal = str(oct(i)[2:]).rjust(l)
hexadecimal = hex(i)[2:].rjust(l)
binary = bin(i)[2:].rjust(l... |
def get_city_year(p0, perc, delta, p):
years = 1
curr = p0 + p0 * (0.01 * perc) + delta
if curr <= p0: # remember == would imply stagnation
return -1
else:
while curr < p:
curr = curr + curr * (0.01 * perc) + delta
years += 1
return years
print(get_cit... |
#First Example - uncomment lines or change values to test the code
phone_balance = 7.62
bank_balance = 104.39
#phone_balance = 12.34
#bank_balance = 25
if phone_balance < 10:
phone_balance += 10
bank_balance -= 10
print(phone_balance)
print(bank_balance)
#Second Example
#change the number to experiment!
numbe... |
print('pypypy')
print('pypypy111')
print('pycharm1111')
print('pycharm222')
print('pypypy222')
print('pycharm3333')
print('pypypy333')
hheheheh
# zuishuaidezishi
ssshhhhhhh
|
# Design
# a
# stack
# that
# supports
# push, pop, top, and retrieving
# the
# minimum
# element in constant
# time.
#
# Implement
# the
# MinStack
#
#
# class:
#
#
# MinStack()
# initializes
# the
# stack
# object.
# void
# push(int
# val) pushes
# the
# element
# val
# onto
# the
# stack.
# void
# pop()
# removes
# ... |
def baseline_opt_default_args(prob_type):
defaults = {}
defaults['simpleVar'] = 100
defaults['simpleIneq'] = 50
defaults['simpleEq'] = 50
defaults['simpleEx'] = 10000
defaults['nonconvexVar'] = 100
defaults['nonconvexIneq'] = 50
defaults['nonconvexEq'] = 50
defaults['nonconvexEx'] = ... |
class S1C1():
@staticmethod
def ret_true():
return True
@staticmethod
def hex_to_base64(hx):
return "x"
|
# Given n balloons, indexed from 0 to n-1.
# Each balloon is painted with a number on it represented by array nums.
# You are asked to burst all the balloons.
# If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins.
# Here left and right are adjacent indices of i.
# After the burst, the ... |
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip
def calc_hba1c(value):
"""
Calculate the HbA1c from the given average blood glucose... |
s = input()
answer = len(s)
k = s.count('a')
for i in range(len(s)):
cnt = 0
for j in range(k):
if s[(i+j)%len(s)] == 'b':
cnt+=1
if cnt < answer:
answer = cnt
print(answer) |
def math():
i_put = input()
if len(i_put) <= 140:
print('TWEET')
else:
print('MUTE')
if __name__ == '__main__':
math()
|
'''
A better way to implement the fibonacci series
T(n) = 2n + 2
'''
def fibonacci(n):
# Taking 1st two fibonacci nubers as 0 and 1
FibArray = [0, 1]
while len(FibArray) < n + 1:
FibArray.append(0)
if n <= 1:
return n
else:
if FibArray[n... |
eval_cfgs = [
dict(
metrics=dict(type='OPE'),
dataset=dict(type='OTB100'),
hypers=dict(
epoch=list(range(31, 51, 2)),
window=dict(
weight=[0.200, 0.300, 0.400]
)
)
),
] |
class Solution:
# Enumerate shortest length (Accepted), O(n*l) time, O(l) space (n = len(strs), l = len(shortest str))
def longestCommonPrefix(self, strs: List[str]) -> str:
min_len = min(len(s) for s in strs)
res = ""
for i in range(min_len):
c = strs[0][i]
for s... |
n = int(input("Please enter the size of the table: "))
# print the first row (header)
print(" ", end = "")
for i in range(1, n + 1):
print(" ", i, end = "")
print() # new line
# print the actual table
for row in range(1, n + 1):
# print row number at the beginning of each row
print(" ", row, end =... |
# Copyright 2018 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# DO NOT MANUALLY EDIT!
# Generated by //scripts/sdk/bazel/generate.py.
load("@io_bazel_rules_dart//dart/build_rules/internal:pub.bzl", "pub_repository")
d... |
# 给你一根长度为 n 的绳子,请把绳子剪成整数长度的 m 段(m、n都是整数,n>1并且m>1),每段绳子的长度记为 k[0],k[1]...k[m] 。请问 k[0]*k[1]*...*k[m] 可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。
#
# 示例 1:
#
# 输入: 2
# 输出: 1
# 解释: 2 = 1 + 1, 1 × 1 = 1
# 示例 2:
#
# 输入: 10
# 输出: 36
# 解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36
# 提示:
#
# 2 <= n <= 58
# 注意:本题与主站 343 题相同:... |
def split(list):
n = len(list)
if n == 1:
return list, []
middle = int(n/2)
return list[0:middle], list[middle:n]
def merge_sort(list):
if len(list) == 0:
return list
a, b = split(list)
if a == list:
return a
else:
new_a = merge_sort(a)
... |
# 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
# We would need to create an map out of in-order array to access index easily
class Solution:
# Faster solution
def bu... |
"""
Buffer the StreetTrees feature class by 20 meters
"""
# Import modules
# Set variables
# Execute operation
|
# 静态方法和显式类名称可能对于处理一个类本地的数据来说可能是更好地方法'
# 类方法可能更适合处理对层级中的每个类不同的数据
# 静态方法统计实例
class SpamStatic:
numInstance = 0
def __init__(self):
SpamStatic.numInstance += 1
def printNumInstance():
print(SpamStatic.numInstance)
printNumInstance = staticmethod(printNumInstance)
# 类方法统计实例
class Spam:... |
class Solution:
def partitionLabels(self, S):
"""
:type S: str
:rtype: List[int]
"""
positions = dict()
for i, c in enumerate(S):
if c not in positions:
positions[c] = []
positions[c].append(i)
result = []
end =... |
a = 3
b = 4
z = a + b
print(z)
|
expected = 'Jana III Sobieskiego'
a = ' Jana III Sobieskiego '
b = 'ul Jana III SobIESkiego'
c = '\tul. Jana trzeciego Sobieskiego'
d = 'ulicaJana III Sobieskiego'
e = 'UL. JA\tNA 3 SOBIES\tKIEGO'
f = 'UL. jana III SOBiesKIEGO'
g = 'ULICA JANA III SOBIESKIEGO '
h = 'ULICA. JANA III SOBIeskieGO'
i = ' Jana 3 Sobieski... |
#
# PySNMP MIB module CISCO-CALL-TRACKER-TCP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-CALL-TRACKER-TCP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:34:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... |
def test_index(client):
res = client.get("/")
json_data = res.get_json()
assert json_data["msg"] == "Don't panic"
assert res.status_code == 200
|
#!/usr/bin/env python
numbers = [1,2,3,4,5,8,3,2,3,1,1,1]
def bubblesort(numbers):
# Keep a boolean to determine if we switched
switched = True
# One round of sorting
while switched:
switched = False
indexA = 0
indexB = 1
while indexB < len(numbers):
num... |
#作业:实现一个闰年的函数
def run_nian(year):
return (year%4==0 and year%100!=0) or year%400==0
#断言: 4个测试用例
assert run_nian(2004)==True
assert run_nian(2005)==False
assert run_nian(2000)==True
assert run_nian(2100)==False |
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = None
count = 0
for n in nums:
if res is None:
res = n
count = 1
elif res == n:
coun... |
"""
7.3 – Múltiplos de dez: Peça um número ao usuário e, em seguida, informe se o
número é múltiplo de dez ou não.
"""
numero = int(input("Digite o valor de um número: "))
if numero % 10 == 0:
print(f"O número digitado {numero} é múltiplo de 10")
else:
print(f"O número digitado {numero} não é múltiplo de 10") |
class Solution:
def transpose(self, A: List[List[int]]) -> List[List[int]]:
output=[]
rows=len(A)
cols=len(A[0])
output=[[0]*rows for i in range(cols)]
for i in range(0,len(A)):
for j in range(0,len(A[0])):
output[j][i]=A[i][j]
return outp... |
# -*- coding: utf-8 -*-
# author: Phan Minh Tâm
# source has refer to java source of BURL method: http://web.informatik.uni-mannheim.de/AnyBURL/IJCAI/ijcai19.html file CompletionResult.java
class CompletionResult(object):
def __init__(self, triple):
self.triple = triple
self.head_results = []
self.tail_... |
""" spin multiplicities
"""
def spin(mult):
""" number of unpaired electrons
"""
return mult - 1
|
def missing_values1 (data):
"""
Deals in place with missing values in specified columns:
'fields_of_study', 'title', 'abstract', 'authors', 'venue', 'references', 'topics'
"""
data.loc[data['fields_of_study'].isnull(), 'fields_of_study'] = ""
data.loc[data['title'].isnull(), 'title'] = ""
... |
def Settings( **kwargs ):
return {
'flags': [
'-O3', '-std=gnu11', '-fms-extensions',
'-Wno-microsoft-anon-tag',
'-Iinclude/', '-Ilib/', '-pthread',
'-Wall', '-Werror', '-pedantic']
}
|
#
# @lc app=leetcode id=257 lang=python
#
# [257] Binary Tree Paths
#
# https://leetcode.com/problems/binary-tree-paths/description/
#
# algorithms
# Easy (45.03%)
# Likes: 835
# Dislikes: 65
# Total Accepted: 221.4K
# Total Submissions: 484.4K
# Testcase Example: '[1,2,3,null,5]'
#
# Given a binary tree, return... |
def traduz(palavras, eng2port):
traduzido = []
for p in palavras:
traduzido.append(eng2port[p])
return traduzido
palavras = ['blackberry', 'cherry', 'plum', 'apple', 'pineapple']
eng2port = {'pineapple': 'abacaxi', 'plum': 'ameixa', 'blackberry': 'amora', 'apple': 'maçã', 'cashew': 'caju',... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
'快速排序'
def partition(self, arr, start, end):
'找轴点应该在的位置,左侧比他小,右侧比他大'
low = start
high = end
pivot = arr[start] #选定轴点,‘坑’
while low < high: #直到访问完所有元素
while low < high and arr[high] >= ... |
schema = {
# Schema definition, of the CLARA items.
'main_scale': {
'type': 'string',
'minlength': 1,
'maxlength': 20,
'required': True
},
'itembank_id': {
'type': 'string',
'minlength': 1,
'maxlength': 4,
'required': True
},
'prese... |
n,d = map(int,raw_input().split())
c = map(int,raw_input().split(' '))
gc = 0
for i in range(len(c)):
if c[i]+d in c and c[i]+2*d in c:
gc+=1
print (gc) |
{
"targets": [
{
"target_name": "glace",
"sources": [
"target/glace.cc",
],
"include_dirs": [
"target/deps/include",
],
"libraries": [],
"library_dirs": [
"/usr/local/lib"
... |
OUT_FORMAT_CONVERSION = {
"t": "",
"b": "b",
"u": "bu",
}
|
Scale.default = Scale.egyptian
Root.default = 0
Clock.bpm = 110
~p1 >> play('m', dur=PDur(3,16), sample=[0,2,3])
~p2 >> play('V', dur=1, pan=[-1,1], sample=var([0,2],[24,8]))
~p3 >> play('n', dur=var([.5,.25,.125,2/3],[24,4,2,2]))
p_all.lpf = 0
p_all.rate = .5
~s1 >> space(P[0,3,5,1]+(0,3), dur=4, chop=6, slide=0, e... |
""""
Copyright 2019 by J. Christopher Wagner (jwag). All rights reserved.
:license: MIT, see LICENSE for more details.
This packages contains OPTIONAL models for various ORMs/databases that can be used
to quickly get the required DB models setup.
These models have the fields for ALL features. This makes it easy for a... |
params = {
# file to load wav from
'file': 'C:/Users/qweis/Documents/GitHub/unknown-pleasures/wavs/famous.wav',
# output file for images
'save_loc': 'covers/frame.png',
# save location for video
'vid_save': 'time_test.mp4',
# number of spacers between each data point
'spacers': 5,
# ... |
input = """-1,-1,-4,-1
0,1,8,5
-8,-5,2,-6
-1,3,-2,-3
-1,1,6,1
4,-8,0,-5
8,-6,-5,6
-6,2,-8,1
-5,6,-2,-5
3,-8,0,0
-3,-7,-5,-6
-1,-4,-7,-5
-7,3,1,-6
-5,4,-4,0
1,-7,0,-6
4,-1,1,2
6,1,6,-2
2,1,-8,-6
-7,-7,3,2
-8,-5,8,-5
-8,2,-1,4
8,6,7,1
6,-4,-1,-7
8,-2,2,4
0,8,8,3
6,-7,-6,8
-8,-2,8,6
1,-8,-6,-8
-6,-1,5,-6
5,2,7,-3
5,7,0,-3... |
# The Twitter API keys needed to send tweets
# Two applications for the same account are needed,
# since two streamers can't be run on the same account
# main account. needs all privileges
CONSUMER_KEY = "enter your consumer key here"
CONSUMER_SECRET = "enter your secret consumer key here"
ACCESS_TOKEN = "enter your ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.