content stringlengths 7 1.05M |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by Hao Luo at 2019-06-20
"""io.py
:description : script
:param :
:returns:
:rtype:
"""
def solution2txt(solution,model,outfile):
need_fluxes =solution.fluxes[abs(solution.fluxes)>1e-10]
with open(outfile,'w') as outf:
for need_id in need_flux... |
class DBRouter(object):
def db_for_read(self, model, **hints):
if model._meta.app_label == 'extoon':
return 'extoon'
if model._meta.app_label == 'emmdx':
return 'emmdx'
return 'default'
def db_for_write(self, model, **hints):
if model._meta.app_label == '... |
# -*- coding: utf-8 -*-
{
'name': "api_for_download_attachment_directly",
'summary': """ Attachment Download """,
'description': """
Api For Downloading Attachment Directly Without Login Odoo
""",
'author': "Roger",
'website': "http://www.yourcompany.com",
# Categories can be use... |
def binary_search(array , target):
first = 0
last = len(array) - 1
while first <= last:
midpoint = (first+last)//2
if array[midpoint] == target:
return midpoint
elif array[midpoint] > target:
last = midpoint - 1
else:
first = ... |
class Skill:
def __init__(self):
self.max_cooldown = 0
self.cooldown = 0
self.damage_multiplier = 0
self.damage_cap = 0
self.ally_buffs = []
self.ally_debuffs = []
self.foe_buffs = []
self.foe_debuffs = []
def use(self, attack):
self.coold... |
class RandomizedSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.values = []
self.positions = {} # store corresponding positions of values in set
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set... |
# Problem Set 4A
# Name: <your name here>
# Collaborators:
# Time Spent: x:xx
def get_permutations(sequence):
'''
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute. Assume that it is a
non-empty string.
You MUST use recursion for this par... |
'''
Problem Name: HCF and LCM
Problem Code: FDGHLM
Problem Link: https://www.codechef.com/problems/FDGHLM
Solution Link: https://www.codechef.com/viewsolution/47003480
'''
def gcd(m, n):
if n == 0:
return m
return gcd(n, m%n)
def lcm(m, n):
prod = m*n
return prod//gcd(m, n)
... |
# -*- coding: utf-8 -*-
"""Algoritmo de Ordenamiento
Se puede definir un algoritmo de ordenamiento de datos
en una lista con estos datos de forma ascendente o
descendente
Recuerda que en Python podemos intercambiar variables
de forma sencilla: a, b = b, a
"""
def bubble_sort(list_data):
# Obtenemos la longitud... |
# Author: b1tank
# Email: b1tank@outlook.com
#=================================
'''
720_Longest_Word_in_Dictionary on LeetCode
Solution:
- Trie: TrieNode has a value and a hashmap of child nodes
- Depth First Search (DFS) implemented using both stack and recursive
'''
class TrieNode():
... |
COLLECTION = "user"
blog_collection = "blogs"
blogs_comments = "comments"
Activities ="requests"
|
array = [116, 176382, 94, 325, 3476, 4, 2542, 9, 21, 56, 322, 322]
print(array)
def insertion(array, g):
for i in range(g, len(array)):
v = array[i]
j = i-g
while j >= 0 and array[j] > v:
array[j + g] = array[j]
j = j - g
array[j+g] = v
def shellsort(arra... |
class A:
def foo(self):
print('a')
class B:
def foo(self):
print('b')
class C:
def foo(self):
print('c')
class D:
def foo2(self):
print('d')
class E(A, B, C):
def __init__(self):
super()
class F(D, C, B):
def __init__(self):
super()
class G(A, B, C):
def foo(self):
super(G, self).foo()
e = E... |
print("Wellcome to the Multiplication/Exponent Tabel App\n")
name = str(input("What is your name: ")).title()
number = float(input("What number would you like to work with: "))
print(f"\nMultiplication Table For {number}\n")
print(f"\t1.0 * {number} = {number * 1}")
print(f"\t2.0 * {number} = {number * 2}")
print(f"... |
"""
参数
"""
class Config:
"""
zip_png配置参数
"""
image_save_path = 'data/'
new_image_path = 'temp/temp.png'
PNG_ALLOWED_EXTENSIONS = set(['png'])
"""
html转pdf
"""
pdf_save_path = 'temp/'
html_file = 'data/temp.pdf'
"""
flask主服务
"""
port = 3301
|
n = 6
a = [0] * n
result = []
def recur(s, n, was, result):
if len(s) == n:
result.append(s)
return
for i in range(0, n):
if was[i] == 0:
was[i] = 1
recur(s + str(i + 1), n, was, result)
was[i] = 0
recur("", n, a, result)
print(result)
|
print("\nPrograma creado en Python\n"
+"que recibe dos valores numericos\n"
+"que representan dos años\n"
+"y crea una lista que muestra los años bisiestos entre los dos años.\n"
+"---\n"
+"Programa creado por: Jesús Urrego\n"
+" ID: 00000216768\n"
+" Fecha de creación: ... |
"""
2. 군인 정렬하기
N명의 전사가 무작위로 배열되어 있다. 이때, 병사들은 특정한 값의 전투력을 가질때, 전투력이 높은순서부터 낮은 순서대로 배열을 하고자 한다.
최소한으로 병사를 제외하여 내림차순을 만들 수 있을때, 제외해야 할 병사의 수는?
"""
def solve(n):
for i in range(1, n):
for j in range(i):
if soldiers[i] > soldiers[j]:
memo[i] = max(memo[i], memo[j] + 1)
return m... |
"""
Function use to convert assembly in graph
"""
def asm2gfa(input_path, output_path, k):
"""
Convert bcalm assemblie in gfa format
"""
with open(input_path) as input_file:
# name stores the id of the unitig
# optional is a list which stores all the optional tags of a segment
... |
def calculate_price_change(curr_state: dict, new_state: dict):
curr_price = curr_state["coinbase_btcusd_close"]
next_price = new_state["coinbase_btcusd_close"]
return curr_price - next_price
def buy(curr_state: dict, prev_interps, new_state: dict, new_interps):
return calculate_price_change(curr_state... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Artificially cap how fast we can launch our probe.
# Select this value carefully, or else we might lose valid
# shot selections.
MAX_Y_VELOCITY = 1000
def tick(pos, vel):
# On each step, these changes occur in the following order:
#
# The probe's x position increases... |
# -*- coding: utf-8 -*-
class ClassifyBar:
def polarity(self,a,b):
return a <= b
pass
class RetrieveData:
def init():
pass
class FormatData:
def init():
pass
class ConsolidateBar:
def init():
pass
# Test Class for Simple Calculator functi... |
#
# PySNMP MIB module A3COM-HUAWEI-IPV6-ADDRESS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-IPV6-ADDRESS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:05:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ve... |
class Solution(object):
def strStr(self, haystack, needle):
i = 0
j = 0
m = len(needle)
n = len(haystack)
if m ==0:
return 0
while i<n and n-i+1>=m:
if haystack[i] == needle[j]:
temp = i
while j<m and i<n and needle[j]==haystack[i]:
... |
a = int(input())
f = int(input())
if a == f:
print('YES')
elif a != 1 and f != 1:
print('YES')
else:
print('NO') |
# _*_ coding: utf-8 _*_
"""
Created by Alimazing on 2018/6/24.
"""
__author__ = 'Alimazing'
APP_ID = 'wx5511fgf81259cd7339b'
APP_SECRET = '266db3182ae98421940d292e0ce021182c'
LOGIN_URL = 'https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code' |
extn2tag = { '.c' : 'c', \
'.cpp' : 'cpp', '.cpp_' : 'cpp', '.cpp1' : 'cpp', '.cpp2' : 'cpp', '.cppclean' : 'cpp', '.cpp_NvidiaAPI_sample' : 'cpp', '.cpp-s8inyu' : 'cpp', '.cpp-woains' : 'cpp', \
'.cs' : 'csharp', '.csharp' : 'csharp', \
'.m' : 'objc', \
'.java' : 'java', \
'.s... |
#! /usr/bin/env python
def count_routes(n, a):
count = 1
for i in range(len(a)):
count *= a[i]
return count
if __name__ == '__main__':
t = int(input())
for _ in range(t):
n = int(input())
a = [int(x) for x in input().split()]
print(count_routes(n, a) % 1234567)
|
print('-'*30)
print('sequência de fibonacci')
print('-'*30)
n=int(input('quantos termos você que mostrar? '))
t1=0
t2=1
print('~'*30)
print('{} - {} '.format(t1,t2),end='')
cont=3
while cont <= n:
t3=t1 + t2
print(' - {} '.format(t3),end='')
t1=t2
t2=t3
cont += 1
print(' - fim')
print('~'*30)
|
#!/usr/bin/env python3
r"""
Botorch Errors.
"""
class BotorchError(Exception):
r"""Base botorch exception."""
pass
class CandidateGenerationError(BotorchError):
r"""Exception raised during generating candidates."""
pass
class UnsupportedError(BotorchError):
r"""Currently unsupported feature... |
print('\033[32m =\033[m'*50)
print('BUILD AN PYTHON SCRIPT THAT READ AN NAME AND SHOW AN MENSAGE OF GRETTINS ACORD WITH TYPED VALUE'.title())
print('\033[32m =\033[m'*50)
name = str(input('\033[4m Welcome Little Locust please type your name :\033[m \n'))
print(' Hello \033[4;34m{}!\033[m nice to meet you '.format(name)... |
customer_basket_cost = 34
shipping_cost_per_kg = 1.2
customer_basket_weight = 44
if customer_basket_cost >= 100:
print(str(customer_basket_cost) + "€")
else:
shipping_cost = shipping_cost_per_kg * customer_basket_weight
total_price = shipping_cost + customer_basket_cost
print(str(total_price) + ... |
# Time: O(n)
# Space: O(1)
# dp
class Solution(object):
def countTexts(self, pressedKeys):
"""
:type pressedKeys: str
:rtype: int
"""
MOD = 10**9+7
dp = [1]*5
for i in xrange(1, len(pressedKeys)+1):
dp[i%5] = 0
for j in reversed(xrang... |
def for_p():
""" Pattern of Small Alphabet: 'p' using for loop """
for i in range(9):
for j in range(4):
if i in (1,4) and j!=3 or j==0 or j==3 and i in(2,3):
print('*',end=' ')
else:
... |
# coding:utf-8
class SSError(Exception):
pass
|
# x = int(input("How many candies you want:"))
# av = 5
# i = 1
# while i <= x:
# if i > av:
# print("We are out of stock")
# break
# print("Candy")
# i = i+1
# print("Bye")
# for i in range(1,101):
# if i %3 == 0 and i%5==0:# skip the values whick=h are divisible by 3 and(both) ... |
def parse_field(field):
name, valid = field.split(':')
valid = [tuple(map(int, r)) for r in
(r.split('-') for r in valid.split(' or '))]
return name, valid
def read_ticket(_ticket):
return list(map(int, _ticket.split(',')))
with open("input.txt") as f:
fields, ticket, nearby = f.rea... |
# do not create a map in this way
names = ['Jack', 'John', 'Joe', 'Mary']
m = {}
for name in names:
m[name] = len(name)
# create a map in this way, using a map comprehension
names = ['Jack', 'John', 'Joe', 'Mary']
m = {name: len(name) for name in names}
|
# code/load_original_interkey_speeds.py
# Left: Right:
# 1 2 3 4 25 28 13 14 15 16 31
# 5 6 7 8 26 29 17 18 19 20 32
# 9 10 11 12 27 30 21 22 23 24
Time24x24 = np.array([
[196,225,204,164,266,258,231,166,357,325,263,186,169,176,178,186,156,156,158,163,171,175,177,189],
[225,181,1... |
class Solution(object):
def bitwiseComplement(self, num):
"""
:type N: int
:rtype: int
"""
return (1 << len(bin(num)) >> 2) - num - 1
|
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
maxlen = 0
for i in range(len(matrix)):
for j in range(len(matrix[i])):
matrix[i][j] = int(matrix[i][j])
if matrix[i][j] and i and j:
matrix[i][j] = min(matrix[i... |
#!/usr/bin/env python3
# 文字入力をする処理
text = input("食べ物の名前を入力: ")
# if文で条件を指定する
if text == "ばなな":
print("好き!")
if text == "なす":
print("苦手!")
|
class InvalidListOfWordsException(Exception):
print("Invalid list of words exception raised")
class InvalidWordException(Exception):
print("InvalidWordException raised")
class GameWonException(Exception):
print("You won the game! Congrats!")
class GameLostException(Exception):
print("You lost the ... |
{
"cells": [
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[ 0.20107669 0.29543058 -0.16135565 -0.26139101 0.21345801]]\n",
"[ 0.20107669 0.29543058 -0.16135565 -0.26139101 0.21345801]... |
def power_level(x, y, grid_sn):
rack_id = x + 10
result = rack_id * y + grid_sn
result *= rack_id
return (result % 1000 // 100) - 5
def create_grid(grid_sn):
return [[power_level(x, y, grid_sn) for y in range(301)]
for x in range(301)]
def best(grid_sn, sq):
grid = create_grid(gr... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 15 00:39:06 2018
@author: Mohammed
"""
#Problem Statement
"""
An isogram is a word that has no repeating letters, consecutive or
non-consecutive. Implement a function that determines whether a string
that contains only letters is an isogram. Assume the empty string is ... |
class queue_array():
def __init__(self, length = 10):
self.array = [None]*length
self.index = 0
def __str__(self):
output = ""
for i in range(len(self.array)):
if (self.array[i]):
output += str(self.array[i]) + " -> "
output += " End "
... |
# put lua51 include path before macports in case lua 5.2 is installed
CPPPATH = ['__PREFIX__/include/lua-5.1', '__PREFIX__/include']
CPPDEFINES = []
LIBPATH = ['__PREFIX__/lib']
CCFLAGS = ['-fsigned-char']
LINKFLAGS = ['$__RPATH']
CC = ['__CC__']
CXX = ['__CXX__']
MINGWCPPPATH = []
MINGWLIBPATH = []
|
sjzips = [
'95101',
'95102',
'95106',
'95108',
'95109',
'95110',
'95111',
'95112',
'95113',
'95114',
'95115',
'95116',
'95117',
'95118',
'95119',
'95120',
'95121',
'95122',
'95123',
'95124',
'95125',
'95126',
'95127',
'95128... |
def tarea9():
#definir variables
print ("consulta que vacuna te toca")
#datos de entrada
añosX=int(input("ingresa tu edad:"))
#proceso
if añosX>=70:
resultadoaños="se le aplica la vacuna tipo C"
if añosX>16 and añosX<=69:
sexoX=input("ingresar sexo:")
if sexoX=="hombre":
resultadoaño... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 29 20:46:11 2021
@author: thibaut
function karatsuba to multiply 2 integers
"""
def karatsuba(num1, num2):
#if it's one-digit numbers just multiply
if len(str(num1))==1 and len(str(num2))==1:
return num1*num2
# write the numbers in this form:10^(... |
#!/usr/bin/env python
# This python script checks the sfincsOutput.h5 file for an example to
# see if the results are close to expected values. This script may be
# run directly, and it is also called when "make test" is run from the
# main SFINCS directory.
execfile('../testsCommon.py')
desiredTolerance = 0.001
... |
#Algoritmos Computacionais e Estruturas de Dados
#4a Lista de Exercícios
#Prof.: Laercio Brito
#Dia: 07/10/2021
#Turma 2BINFO
#Alunos:
#Dora Tezulino Santos
#Guilherme de Almeida Torrão
#Mauro Campos Pahoor
#Victor Kauã Martins Nunes
#Victor Pinheiro Palmeira
#Questão 2
tamV=int(input("Insira o tamanho do vetor V: "))... |
n = int(input())
if n >= 404:
print("MSU")
elif n >= 322:
print("MPI")
elif n >= 239:
print("MIT")
else:
print(":(")
|
def z_algorithm(S: str):
ret = [0] * len(S)
ret[0] = len(S)
i, j = 1, 0
while i < len(S):
while i + j < len(S) and S[j] == S[i + j]:
j += 1
ret[i] = j
if j == 0:
i += 1
continue
k = 1
while i + k < len(S) and k + ret[k] < j:
... |
# ---------- PROBLEM : SECRET STRING ----------
# Receive a uppercase string and then hide its meaning by turning it into a string of unicode
# Then translate it from unicode back into its original meaning
# Enter a string to hide in uppercase
# Secret Message : 34567890
# Original Message : HIDE
# Input string to be... |
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
GREEN = ( 0, 255, 0) #S-BLOCK
RED = ( 255, 0, 0) # Z-BLOCK
BLUE = (0,0,255) # J-BLOCK
ORANGE = (255, 127, 0) # L-BLOCK
YELLOW = (255,255,0) # O-BLOCK
PURPLE = (128, 0 , 128) # T-BLOCK
TURQUOISE = (64, 224, 208) # I-BLOCK
x = 50 # The direction of our Blocks, LEFT... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 15 09:45:06 2022
@author: craig
"""
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
name = name1 + name2
name_lower = name.lower()
name_count_t = name_lower.count("t")
name_count_r = n... |
STUDENT_MANAGING_GET = {
'tags': ['상벌점 관리'],
'description': '학생 목록 조회',
'parameters': [
{
'name': 'Authorization',
'description': 'JWT Token(JWT ***)',
'in': 'header',
'type': 'str',
'required': True
}
],
'responses': {
... |
N = int(input())
mod = 10 ** 9 + 7
dp = [[[[0] * 4 for _ in range(4)] for _ in range(4)] for _ in range(N + 1)]
dp[0][3][3][3] = 1
for i in range(N):
for j in range(4):
for k in range(4):
for m in range(4):
if dp[i][j][k][m] == 0:
continue
... |
load(
"@bazel_gazelle//internal:go_repository.bzl",
_go_repository = "go_repository",
)
load(
"@bazel_gazelle//internal:go_repository_cache.bzl",
"go_repository_cache",
)
load(
"@bazel_gazelle//internal:go_repository_tools.bzl",
"go_repository_tools",
)
load(
"@bazel_gazelle//internal:go... |
# source unclear
# modified to add policy
funder_names = [
{
"name": "Wellcome Trust",
"alternate_names": "Wellcome Trust",
"works_count": 13550,
"id": 100004440,
"policy": "plan-s",
"country": "United Kingdom",
"country_iso": "GB"
},
# {
# "n... |
#desafio 69: Análise de dados do grupo.
pessoas18 = homens = mulheres20 = 0
while True:
idade = int(input('Idade: '))
sexo = ' '
while sexo not in 'FM':
sexo = str(input('Sexo [F/M]: ')).upper().strip()[0]
r = ' '
while r not in 'SN':
r = str(input('Quer continuar? [S/N]: ')).upper(... |
"""
Codemonk link: https://www.hackerearth.com/practice/math/number-theory/basic-number-theory-1/practice-problems/algorithm/the-final-fight-6/
Fatal Eagle has had it enough with Arjit aka Mr. XYZ who's been trying to destroy the city from the first go. He cannot
tolerate all this nuisance anymore. He's... tired of it... |
#!/usr/bin/env python3
class TaskList():
"""Task list for Jenkins."""
tasks = []
__lock__ = False
def is_locked(self):
"""Check if list is locked."""
return self.__lock__
def lock(self):
"""Lock TaskList."""
self.__lock__ = True
def unlock(self):
"""... |
'''10. Write a Python program to reverse the digits of a given number and add it to the original,
If the sum is not a palindrome repeat this procedure.
Note: A palindrome is a word, number, or other sequence of characters which reads the same
backward as forward, such as madam or racecar.'''
def reverseInteger(x):
... |
# One common problem when prompting for numerical input
# occurs when people provide text instead of numbers. When you try to convert
# the input to an int, you’ll get a ValueError. Write a program that prompts for
# two numbers. Add them together and print the result. Catch the ValueError if
# either input value is no... |
prefixes = {
8: "ampersand_angleBracket_currency_accent_tilde_mathPower_@_scriptIndicator_dagger_prefix",
16: "asterisk_roundBracket_basicMathSign_ditto_dash_prefix",
24: "genderSign_doubleQuotation_IP_accent_paragraphSection_degree_boldIndicator_ligaturedIndicator_prefix",
32: "capital_singleQuotation_... |
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
l = len(cost)
if l == 2:
return min(cost)
res = [0] * (l)
for i in range(2, l):
res[i] = min(cost[i-1] + res[i-1], res[i-2] + cost[i-2])
return... |
def get_max(lst):
return max(lst)
def get_min(lst):
return min(lst)
def get_avg(lst):
return sum(lst)/len(lst)
|
# -*- coding: utf-8 -*-
linha = int(input())
coluna = int(input())
if linha == coluna: corCasaInferiorDireito = 1
elif linha % 2 == 0:
if coluna % 2 != 0: corCasaInferiorDireito = 0
else: corCasaInferiorDireito = 1
elif linha % 2 != 0:
if coluna % 2 != 0: corCasaInferiorDireito = 1
else: corCasaInferior... |
# read file
file = open('data.txt')
data = file.read()
file.close()
# write file
out = open('data2.txt', 'w')
out.write(data)
out.close()
|
# -*- coding: utf-8 -*-
"""
We prefer to address the txt file containing data as the format [src des]
"""
def readFile(path):
f = open(path,'r')
array_list = []
for line in f:
src, des = map(int,line.split())
if len(array_list)-1 < src:
array_list.append([])
array_list[s... |
#
# PySNMP MIB module BDCOM-MEMORY-POOL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BDCOM-MEMORY-POOL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:19:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... |
"""
File: anagram.py
Name: Amber Chang
----------------------------------
This program recursively finds all the anagram(s)
for the word input by user and terminates when the
input string matches the EXIT constant defined
at line 19
If you correctly implement this program, you should see the
number of anagrams for eac... |
a = int(input())
x = ""
c = 0
b = False
for i in range(a):
x += input()
for char in x:
if char == "{":
c += 1
elif char == "}":
c -= 1
if c < 0:
b = True
break
if c != 0 or b:
print("N")
else:
print("S")
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
... |
""" Introduction to Binary Tree """
class Node:
def __init__(self, data):
self.right=None
self.left=None
self.key=data
root=Node(1)
root.left=Node(2)
root.right=Node(3)
root.left.left=Node(4)
|
"""
Parameter conversion table
*CONVERSION_TABLE* gives the old model name and a dictionary of old parameter
names for each parameter in sasmodels. This is used by :mod:`convert` to
determine the equivalent parameter set when comparing a sasmodels model to
the models defined in previous versions of SasView and sasmod... |
class Contact:
def __init__(self, name, midname, last_name, nick, title, comp_name, address, home, email,
date, birth_month, birth_year):
self.name = name
self.midname = midname
self.last_name = last_name
self.nick = nick
self.title = title
... |
def hex_to_rgb(hex_code):
hex_code = hex_code.lstrip('#')
return tuple(int(hex_code[i:i + 2], 16) for i in (0, 2, 4))
def rgb_to_float(red, green, blue):
return tuple(x / 255.0 for x in (red, green, blue))
def hex_to_float(hex_code):
rgb = hex_to_rgb(hex_code)
return rgb_to_float(*rgb)
class C... |
def isPrime(num):
for k in range(2, num // 2):
if (num % k == 0):
return False
return True
numSets = int(input())
for _ in range(numSets):
num = int(input())
print("%d " % num, end='')
if (isPrime(num)):
print("0")
else:
i = num - 1
while True:... |
class Employee:
num_of_emps = 0
raise_amount = 1.04
def __init__ (self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = f'{first.lower()}.{last.lower()}@company.com' #first + '.' + last + '@company.com'
Employee.num_of_emps += 1
... |
"""
_get_offspring and associated functions
"""
def get_complete_gen(tree):
"""
Given a tree, return a list of lists indexed by node number.
Each list entry is a set of points that can be added
as an offspring node to that node
"""
return map(_get_new_points(tree), range(len(tree)))
def _get... |
"""
Module with Clock which helps countdown time
"""
class Clock:
"""
Countdown time and perform an action after time is over
"""
def __init__(self, when_end=None, start_time=0):
"""
Pass start_time here if it is const
:param when_end: Action that will be performed after the ... |
#最初の文字を大文字にし、残りを小文字に
print(b'abcdefg'.capitalize())
print(b'ABCDEFG'.capitalize())
print(b'abcdefg'.upper())
print(b'ABCDEFG'.lower())
print(bytearray(b'abcdefg').capitalize())
print(bytearray(b'ABCDEFG').capitalize())
print(bytearray(b'abcdefg').upper())
print(bytearray(b'ABCDEFG').lower())
|
# 1 test case failed
def isPrime(n) :
if (n <= 1) :
return False
if (n <= 3) :
return True
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
n... |
sol = [0,1]
disBS = False
def disG(n: int):
print( "Sequence number " + str(n) + " is " + str(get(n)) )
def disS(n: int):
print( str(n) + " is sequence " + str(search(n)) )
def solT():
print( "Solution Table: \n" + "\t" + str(sol) )
def get(n: int) -> int:
if(len(sol) - 1 >= n):
# Then we have the soluti... |
'''pessoas = {'nome': 'Vanessa', 'sexo': 'F', 'idade': 32}
pessoas['peso'] = 55.6
print(pessoas)
print()
print(pessoas['nome'])
print()
print(f'A {pessoas["nome"]} tem {pessoas["idade"]} anos.')
print()
print(pessoas.keys())
print()
print(pessoas.values())
print()
print(pessoas.items())
print()
for k in pessoas.keys():... |
"""
3 for/whils-Schleifen (Tag 1)
3.2 Schreibe ein Programm, das für eine vorher festgelegte Zahl die Fakultät berechnet.
Beispiele:
- 5! = 120
- 10! = 3628800
"""
def fakultaet(n):
antwort = 1
while n > 1:
antwort *= n
n -= 1
return antwort
if __name__ == '__main__':
assert... |
cities = [
'Asuncion',
'Ciudad del Este',
'San Lorenzo',
'Capiata',
'Lambare',
'Fernando de la Mora',
'Limpio',
'Nemby',
'Pedro Juan Caballero',
'Encarnacion',
'Mariano Roque Alonso',
'Itaugua',
'Villa Elisa',
'Villa Hayes',
'San Antonio',
'Caaguazu',
... |
#input
# 17
# 15 4 3 3 16 4 14 2 2 10 11 2 6 18 17 10 4 8 11 3 19 9 4 13 6 6 14 3 3 14 19 16 17 3
# 13 5 13 14 6 4 5 6 9 3 4 17 6 10 8 8 9 16 10 3 2 15 15 4 16 10 4 13 7 5 11 19 8 5
# 13 7 17 17 14 19 19 12 6 10 19 12 17 15 2 19 15 15 14 17 11 5 19 5 11 5 15 10 11 18
# 4 6 2 2 19 2 2 12 6 10 11 17 8 6 17 7 2 13 2 18 5 ... |
class Counter:
instance = None
def __init__(self):
self.same_as_original = 0
self.dict = {}
@staticmethod
def get():
if Counter.instance is None:
Counter.instance = Counter()
return Counter.instance
|
class CILNode:
pass
class CILProgram(CILNode):
def __init__(self, dottypes, dotdata, dotcode):
self.dottypes = dottypes
self.dotdata = dotdata
self.dotcode = dotcode
class CILType(CILNode):
def __init__(self, name, attributes, methods):
self.name = name
self.attri... |
titles = ['Creature if Habit','Crewel Fate']
plots = ['A num turns into a monster', 'A haunted yarn shop']
movies = dict( zip(titles, plots) )
# expected output:
'''
{'Creature if Habit': 'A num turns into a monster', 'Crewel Fate': 'A haunted yarn shop'}
'''
print( movies) |
## Predicting using a regression model
# Generate predictions with the model using those inputs
predictions = model.predict(new_inputs.reshape(-1,1))
# Visualize the inputs and predicted values
plt.scatter(new_inputs, predictions, color='r', s=3)
plt.xlabel('inputs')
plt.ylabel('predictions')
plt.show() |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
def _deleteDuplicates(self,head,a,pointer):
if head.next is None:
return 0
else:
if head.val == head.next.val:
a = head.val
... |
# Дан список чисел. Определите, сколько в этом списке элементов, которые больше двух своих соседей и выведите
# количество таких элементов.
strval = input()
# strval = "1 5 1 5 1 6 2"
lst = strval.split(" ")
strlen = len(lst) - 1
i = 1
c = 0
while i < strlen:
if int(lst[i]) > int(lst[i + 1]) and int(lst[i]) > in... |
class AudioModel():
classes_: []
classifier: None
def __init__(self, settings, classifier):
self.settings = {}
self.settings['version'] = settings['version']
self.settings['RATE'] = settings['RATE']
self.settings['CHANNELS'] = settings['CHANNELS']
self.settings['... |
"""
定义所有错误的code与描述
"""
error_message = {
501: "请求方式错误",
502: "请求参数验证失败",
503: "授权认证失败",
504: "",
2002: "数据异常",
2017: "密码长度只能6位",
2018: "密码只能使用字母或数字",
2101: "用户不存在",
2102: "登录异常",
2103: "退出失败",
2104: "用户名或密码错误",
2105: "您的账号已存在",
2106: "您的账号因违规已被封禁!",
2107: "修改Ah... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.