content stringlengths 7 1.05M |
|---|
n = int(input())
combinations = 0
for x1 in range(0, n + 1):
for x2 in range(0, n + 1):
for x3 in range(0, n + 1):
for x4 in range(0, n + 1):
for x5 in range(0, n + 1):
if x1 + x2 + x3 + x4 + x5 == n:
combinations += 1
print(combinati... |
PP_names = {1: 'H.pbe-rrkjus_psl.0.1.UPF', 2: 'He_ONCV_PBE-1.0.upf',
3: 'li_pbe_v1.4.uspp.F.UPF', 4: 'Be_ONCV_PBE-1.0.upf',
5: 'B.pbe-n-kjpaw_psl.0.1.UPF', 6: 'C_pbe_v1.2.uspp.F.UPF',
7: 'N.pbe.theos.UPF', 8: 'O.pbe-n-kjpaw_psl.0.1.UPF',
9: 'f_pbe_v1.4.uspp.F.UPF', 10: 'N... |
'''
1. Write a Python function that takes two lists and returns True if they have at least one common member.
2. Write a Python program to print a specified list after removing the 0th, 4th and 5th elements.
Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
Expected Output : ['Green', 'White', 'Blac... |
class System():
#A full System
def __init__(self):
# Empty Clock Domain
self.clk_domain = None
# Empty memory containers
self.memories = []
self.mem_mode = None
self.mem_ranges = []
self.mem_ctrl = None
self.system_port = None
# Empty ... |
test = { 'name': 'q1',
'points': 0,
'suites': [ { 'cases': [ {'code': '>>> pairwise_multiply([2, 3, 4], [10, 20, 30]) == [20, 60, 120]\nTrue', 'hidden': False, 'locked': False},
{'code': '>>> pairwise_multiply(list(range(1, 10)), list(range(9, 0, -1))) == [9, 16, 21, 2... |
# Problem code
def hammingWeight(n):
count = 0
while n:
count += n & 1
n >>= 1
return count
# Setup
a = 23
print("Number of set bits in 23:")
b = hammingWeight(a)
print(b)
|
def goodbye():
return 'Good Bye'
def main():
print(goodbye())
if __name__ == '__main__':
main()
|
class Solution:
def numSub(self, s: str) -> int:
s = s.split('0')
res = 0
for x in s:
y = len(x)
res += (y + 1) * y // 2
return res
if __name__ == '__main__':
s = "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111... |
"""Modules for fetching traces from a trace file."""
__all__=['CSVFileRequestHandler',
'FileRequestHandlerFactory',
'TEXTFileRequestHandler',
'ContextMonkeyFileCache',
'FileSchemaFactory',
'XMLFileRequestHandler',
'FileRequestHandler',
'JSONFileRequ... |
"""
Handlers
========
Placeholder for interface that takes requests from the rx queue and provides
results in the tx queue.
.. Copyright:
Copyright 2019 Wirepas Ltd under Apache License, Version 2.0.
See file LICENSE for full license details.
"""
|
# Problem Number: 187
# Time complexity: O((N-l)l)
# Space Complexity: O((N-l)l)
class Solution:
def findRepeatedDnaSequences(self, s: str) -> List[str]:
n=len(s)
l=10
all_str=set()
output= set()
for i in range(n-l+1):
temp= s[i:i+l]
if temp ... |
#!/usr/bin/env python
# Copyright (C) 2010 Google Inc. 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
# notice, this list ... |
def link_codable() -> str:
return """
public class Link: Codable {
public var _add: String
public init(link: String) {
self._add = link
}
}
public class UnLink: Codable {
public var _del: String
public init(unLink: String) {
self._del = unLink
}
}
public enum CreateOrLink<T... |
print('*** Calculadora de preço de passagem ***\n')
d = float(input('Digite a distância da viagem em Km: '))
p = d * 0.50 if d <= 200 else d * 0.45
print('Você deverá pagar: R${:.2f}'.format(p))
|
# -*- coding: utf-8 -*-
def journal_context(record={}, params={}):
for k, v in params.items():
record["JOURNAL_" + k] = v
return record
|
__author__ = 'Aaron Yang'
__email__ = 'byang971@usc.edu'
__date__ = '9/5/2020 3:52 AM'
num = 5
num //= 2
print(num) |
frase = 'Curso em vídeo Phyton'
print(frase[:5])
### DICA DE PRINT: USE 3 ASPAS PARA IMPRIMIR UM TEXTO GRANDE
frase = 'Curso em vídeo Phyton'
print(frase.count('o')) # CONTANDO LETRAS.
frase = 'Curso em vídeo Phyton'
print(frase.upper().count('o')) # Lembre que existe variação de maiusculo e minuscu... |
# Aufgabe 10
# Ermitteln Sie die Anzahl der Wörter in einer
# Nutzereingabe und die durchschnittliche Wortlänge.
def anzahlwoerter(nutzereingabe):
nutzereingabe_splitted = nutzereingabe.split(" ")
return nutzereingabe_splitted
def wortlaenge(nutzereingabe, nutzereingabe_splitted):
durchschnittliche_wortla... |
# pedindo um cateto oposto e um cateto adjacente
co = float(input('Cateto Oposto: '))
ca = float(input('Cateto Adjacente: '))
# calculando os cateto para encontrar um hipotenusa
hi = (co ** 2 + ca ** 2) / 0.5
# mostrando a hipotenusa dos catetos
print(f'Cateto oposto: {co}, cateto Adjacente {ca}')
print(f'Hipotenusa: {... |
def solution(s: str) -> str:
if all(i.islower() for i in s):
return s
return ''.join(' ' + i if i.isupper() else i for i in s)
|
a = [1, 2, 3, 4, 5]
n = len(a)
d = 4
print(a[d:] + a[:d]) |
human_years = 10
catYears_1st_year = 15
catYears_2nd_year = 9
catYears_older = 4
dogYears_1st_year = 15
dogYears_2st_year = 9
dogYears_older = 5
if human_years == 1:
print(human_years, catYears_1st_year, dogYears_1st_year)
if human_years == 2:
print(human_years, catYears_1st_year + catYears_2nd_year, dogYears_1... |
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/1293/B
# 1/2 +... + 1/n = ? 没有求和公式! 直接算..
n = int(input()) #1e5
print(sum([1/i for i in range(1,n+1)]))
|
class Validator():
@classmethod
def validate(cls, value):
raise NotImplementedError()
class Transformer():
@classmethod
def transform(cls, value):
raise NotImplementedError()
class BooleanStringValidator(Validator):
"""Validate a string is in boolean type."""
@classmethod
... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
node= None
while(head != null ):
next= head.next
head.ne... |
EDGES_BODY_25 = [
[0, 1],
[1, 2],
[2, 3],
[3, 4],
[1, 5],
[5, 6],
[6, 7],
[1, 8],
[8, 9],
[9, 10],
[10, 11],
[11, 22],
[22, 23],
[11, 24],
[8, 12],
[12, 13],
[13, 14],
[14, 19],
[19, 20],
[14, 21],
[0, 15],
[15, 17],
[0, 16],
... |
#Reyn_AI 2.0.0 采用加权思想全新改版
#暂定比赛版本
#Author: Ryen Zhang
#University: NUAA
#point-val对应列表
point_val = [28,6,8,10,12,15,18,20,21,22,23,24,25, 100] # 目前最强版本
#该函数负责转换点数所对应的val
def get_point_val(card,curRank):
if card[1] == curRank and card[0] == 'H':
return 500
if card[1] == curRank:
return 100
... |
#
# PySNMP MIB module CTRON-APPN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CTRON-APPN-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:26:48 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... |
l = [4, 7, 44, 47, 74, 77, 444, 447, 474, 477, 744, 747, 774, 777]
n = int(input())
for i in l:
if n%i==0:
print("YES")
break
else:
print("NO") |
class InvalidSign(Exception):
pass
class InvalidCoordinate(Exception):
pass
class PreoccupiedCell(Exception):
pass
class GameStatus(Exception):
def __init__(self, sign):
self.sign = sign
class Victory(GameStatus):
pass
class Draw(GameStatus):
pass |
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
index = 0
length = len(arr)
while index < length:
if arr[index]== 0:
arr.pop(-1)
arr.ins... |
"""
secstill plugin Senerio
This plugin will monitor camera view using motion tracking.
When motion tracking is triggered, the camera will take an HD still image
then stop and monitor for the next motion tracking event. There will
be a delay in taking the image due to camera change from streaming mode
therefore faster... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def check(N,S):
if S=='.':
return N+1,False
else:
return N,True
def main():
H,W,X,Y = map(int,input().split())
S = [list(map(str,input())) for i in range(H)]
X -= 1
Y -= 1
ans = -3
for i in range(X,H,1):
ans,flag = ... |
'''Crie um programa que leia duas notas de um
aluno e calcule sua média, mostrando uma mensagem
no final, de acordo com a média atingida:
- Média abaixo de 5.0: REPROVADO
- Média entre 5.0 e 6.9: RECUPERAÇÂO
- Média 7.0 ou superior: APROVADO'''
nota0 = float(input('Digite sua primeira nota: '))
nota1 = float(input('Dig... |
class Pet:
def __init__(self, name, age):
self.name = name
self.age = age
def show(self):
print(f'Hello! I am {self.name} and I am {self.age} years old!')
def speak(self):
print('I dont know what I say!')
class Cat(Pet):
def __init__(self, name, age, color):
su... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 31 02:08:01 2020
@author: mlampert
"""
"""
USEFUL COMMANDS WHICH I NEED FROM TIME TO TIME
"""
|
# Python dictionary with keys having multiple inputs
# First Example
dict = {}
x, y, z = 10, 20, 30
dict[x, y, z] = x + y - z
x, y, z = 5, 2, 4
dict[x, y, z] = x + y - z
print(dict)
# Second Example
places = {("19.07'53.2", "72.54'51.0"):"Mumbai", ("28.33'34.1", "77.06'16.6"):"Delhi"}
print(places)
lat = []
l... |
"""
# OrangeLuyao 的 MachineLearning
> 这个是我自己的机器学习的代码,很多和图像识别有关
## 目录:
### 1. K-means
### 2. BPNeturalNetwork
"""
str = __doc__
# str = str.encode('gbk')
fp = open(r'README.md','w')
print(str)
print(str,file=fp)
fp.close() |
# Warning: This is an example of how you should *not*
# implement stimulus presentation in time-critical
# experiments.
#
# Prepare canvas 1 and show it
canvas1 = Canvas()
canvas1 += Text('This is the first canvas')
t1 = canvas1.show()
# Sleep for 95 ms to get a 100 ms delay
clock.sleep(95)
# Prepare canvas 2 and show ... |
#!/usr/bin/env python3
a = []
s = input()
while s != "end":
a.append(s)
s = input()
n = input()
i = 0
while i < len(a):
s = a[i]
if s[0] == n:
print(s)
i = i + 1
|
# Scrapy settings for booksbot project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://docs.scrapy.org/en/latest/topics/settings.html
# https://docs.scrapy.org/en/latest/topics/downloader-middlewar... |
coordinates_7F0030 = ((151, 114),
(151, 115), (151, 116), (151, 117), (151, 118), (151, 119), (151, 120), (151, 121), (151, 122), (151, 123), (151, 124), (151, 125), (151, 126), (151, 127), (151, 128), (151, 129), (151, 130), (151, 131), (151, 132), (151, 133), (151, 135), (152, 111), (152, 113), (152, 135), (153, 11... |
x = getattr(None, '') # 0 <mixed>
l = [] # 0 [<mixed>]
l.extend(x) # 0 [<mixed>] # e 0
# TODO: test converting to top
s = [ # 0 [(str, int)]
('', 1),
('', 1),
('', 1),
('', 1),
('', 1),
('', 1),
('', 1),
('', 1),
('', 1),
('', 1),
('', 1),
('', 1),
('', 1),
('',... |
# Algorithm:
# This pattern is an observational one. For eg, if n = 3
# 3 3 3 3 3
# 3 2 2 2 3
# 3 2 1 2 3
# 3 2 2 2 3
# 3 3 3 3 3
# The no. of columns and rows are equal to (2 * n - 1).
# The first (n - 1) and last (n - 1) rows can easily be printed using nested for loops
# The mi... |
###############################
# Overview
#
# Without using built a math
# library, calculate the square root
# of a number.
#
# Assume number is not negative.
# Comlex numbers out of scope.
# square root 4 -> 2
###############################
# Using newton's method
# y ^ (1/2) = x =>
# y = x^2 ... |
class A:
pass
def foo():
pass
class B:
""""""
pass
def bar():
""""""
pass
class C:
@property
def x(self):
return 42
@x.setter
def x(self, value):
pass
@x.deleter
def x(self):
pass |
def make_url_part(name, value, value_type):
if value == None:
return ''
if type(value) != value_type:
raise ValueError('{}={} must be {}'.format(
name, value, value_type))
result = "&${}={}".format(name, value)
return result
|
# Copyright 2021 The Bazel Authors. All rights reserved.
#
# 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 la... |
#Refazer o Desafio 51 da PA usando o "while"
primeirotermo = int(input('Digite o primeiro termo da PA: '));
razao = int(input('Agora digite a razão da PA: '));
vezes = 10;
cont = 0;
pa = primeirotermo;
print(f'Os {vezes} termos da PA são: {pa}', end=' ');
cont += 1;
while cont < vezes:
pa = pa + razao;... |
__version__ = "1.4.0"
__title__ = "ADLES"
__summary__ = "Automated Deployment of Lab Environments System (ADLES)"
__license__ = "Apache 2.0"
__author__ = "Christopher Goes"
__email__ = "goesc@acm.org"
__url__ = "https://github.com/GhostofGoes/ADLES"
__urls__ = {
'GitHub': __url__,
'Homepage': 'https://ghost... |
bin1=input("what kind of fruit do you want?")
if bin1=="apples":
print("apples in bin 1")
elif bin1=="orenges":
print("orenges in bin 2")
elif bin1=="bananas":
print("bananas in bin 3")
else:
print("Error! I dont recognize this fruit!")
|
#
# PySNMP MIB module HP-ICF-IPCONFIG (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-IPCONFIG
# Produced by pysmi-0.3.4 at Mon Apr 29 19:21:43 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
# coding: utf8
'''This file contains all the DAta archetype structures needed for the portal '''
class UnitView():
'''represent an article object in the main content part
<div class="unitview">
<div class="unitview-header">
<h1 class="unitview-title">Sample Post 1</h1... |
message = "This is a test at replacing text"
print(message)
message = "Change of text"
print(message) |
#!/usr/bin/env python3
"""
Deepget is a small function enabling the user to "cherrypick" specific values
from deeply nested dicts or lists.
Author: Florian Rämisch <raemisch@ub.uni-leipzig.de>
Copyright: Universitätsbibliothek Leipzig, 2018
License: GPLv3
"""
def deepget(obj, keys):
"""
Deepget is a small fu... |
class Node:
def __init__(self, key=None, parent=None):
self.key = key
self.parent = parent
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self, key=None):
self.root = None
if key is not None:
self.root = Node(key)
def pr... |
if __name__ == '__main__':
the_list = list()
for _ in range(int(input())):
command, *args = input().split()
try:
getattr(the_list, command)(*(int(arg) for arg in args))
except AttributeError:
print(the_list)
|
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if not root: return
root.right, root.left = root.left, root.right
self.invertTr... |
def config_list_to_dict(l):
d = {}
for kv in l:
if kv.count("=") != 1:
raise ValueError(f"invalid 'key=value' pair: {kv}")
k, v = kv.split("=")
if len(v) == 0:
raise ValueError(f"invalid 'key=value' pair: {kv}")
_dot_to_dict(d, k, v)
return d
def ... |
# Return the root of the modified BST after deleting the node with value X
def inorderSuccessor(root,ans,key,parent,node):
if root is None:
return False
currParent=parent[0]
parent[0]=root
if root.data == key :
node[0]=root
if root.right:
curr=root.right
w... |
# 1021
valor = float(input())
notas = [100, 50, 20, 10, 5, 2]
moedas = [1, 0.50, 0.25, 0.10, 0.05, 0.01]
print("NOTAS:")
for nota in notas:
quantidade_nota = int(valor / nota)
print("{} notas(s) de R$ {:.2f}".format(quantidade_nota, nota))
valor -= quantidade_nota * nota
print("MOEDAS:")
for moeda in mo... |
TIMER_READ = 1; # ms
SILAB_IMAGE_SIZE = 16384
SILAB_IMAGE_TOTAL_SUBPART = 144 # size/114+1
SILAB_BOOTLOADER_SIZE = 9216
SILAB_BOOTLOADER_TOTAL_SUBPART = 81 # size/114+1
BT_IMAGE_SIZE = 124928
BT_IMAGE_TOTAL_SUBPART = 1952 # size/64
BT_BOOTLOADER_SIZE = 4096
BT_BOOTLOADER_TOTAL_SUBPART = 64 # size/64
RFID_... |
# Bubble sort
def bubble_sort(Array: list):
while True:
changes = 0
for index in range(len(Array) - 1):
if Array[index] > Array[index + 1]:
Array[index], Array[index + 1] = Array[index + 1], Array[index]
changes = changes + 1
if changes == 0:
return Array
# Complexity:
# wo... |
def swipe_up(driver, t=500, n=1): # 向上滑
size = driver.get_window_size()
x_start = size['width'] * 0.5 # x坐标
y_start = size['height'] * 0.75 # 起始y坐标
x_end = size['height'] * 0.25 # 终点y坐标
for i in range(n):
driver.swipe(x_start, y_start, x_start, x_end, t)
def swipe_down(driver, t=500, n=1): # 向下滑
size = d... |
#Shape of capital A:
def for_A():
"""printing capital 'A' using for loop"""
for row in range(6):
for col in range(11):
if row+col == 5 or col-row==5 or row==3 and col not in(0,1,9,10):
print("*",end=" ")
else:
print(" ",end=" ")
pr... |
def get_string(addr):
out = ""
while True:
if Byte(addr) != 0:
out += chr(Byte(addr))
else:
break
addr += 1
return out
def get_string_at(addr):
return get_string(addr - 0x12040 + 0x001fb5a0)
def get_i32_at(addr):
addr = addr - 0x12040 + 0x001fb5a0
... |
class Solution:
def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool:
n = len(arr)
# initialize hashmap
mapping = {p[0]: p for p in pieces}
i = 0
while i < n:
# find target piece
if arr[i] not in mapping:
return Fals... |
nome_homem = ''
idade_velho = 0
idade_media = 0
idade_novo = 0
for c in range(1, 5):
nome = str(input('Digite o nome: '))
idade = int(input('Digite a idade: '))
sexo = str(input('Homem ou mulher: '.capitalize()))
idade_novo = idade
idade_media += idade
if idade_velho < idade and sexo == 'Homem':... |
# -*- coding: utf-8 -*-
# author:lyh
# datetime:2020/5/28 16:02
"""
65. 有效数字
验证给定的字符串是否可以解释为十进制数字。
例如:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
" -90e3 " => true
" 1e" => false
"e3" => false
" 6e-1" => true
" 99e2.5 " => false
"53.5e93" => true
" --6 " => false
"-+3" => false
"95a54... |
APP_ERROR_SEND_NOTIFICATION = True
APP_ERROR_RECIPIENT_EMAIL = ('dev@example.com',)
APP_ERROR_EMAIL_SENDER = "server@example.com"
APP_ERROR_SUBJECT_PREFIX = ""
APP_ERROR_MASK_WITH = "**************"
APP_ERROR_MASKED_KEY_HAS = ("password", "secret")
APP_ERROR_URL_PREFIX = "/dev/error"
|
#Exercício Python 030: Crie um programa que leia um número inteiro e mostre na tela se ele é PAR ou ÍMPAR.
numero = int(input('Me diga um número qualquer: '))
print('O número {} é PAR'.format(numero) if numero % 2 == 0 else 'O número {} é IMPAR'.format(numero))
|
#!/usr/bin/env python
# Written against python 3.3.1
# Matasano Problem 21
# Implement the MT19937 Mersenne Twister RNG
# generated from code on the wikipedia
class MT19937:
def __init__(self, seed):
self.MT = [0] * 624;
self.index = 0;
self.seed = 0;
self.initialize_gene... |
# https://codeforces.com/problemset/problem/96/A
teams = input() + "-"
count = 0
isOnes = True if teams[0] == "1" else False
isDangerous = False
for player in teams:
if count == 7:
isDangerous = True
break
if player == "1":
if not(isOnes):
count = 0
... |
#! /usr/bin/env python
""" pyweek 22 entry 'You can't let him in here."""
__author__ = "Rex Allison"
__copyright__ = "Copyright 2016, Rex Allison"
__license__ = "MIT"
nemesis = [
# nemesis 1
' '
,' '
,' '
,' X'
... |
def try_or_default(default_value, func):
def wrap(*args, **kwargs):
try:
return func(*args, **kwargs)
except:
return default_value
return wrap
def try_or_false(func):
return try_or_default(False, func)
def try_or_true(func):
return try_or_default(True, func)
|
'''
罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。
字符 数值
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做 XXVII, 即为 XX + V + II 。
通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左... |
{
'variables': {
'target_arch': 'ia32',
'VERSION_FULL': '<!(python tools/version.py)',
'VERSION_MAJOR': '<!(python tools/version.py major)',
'VERSION_MINOR': '<!(python tools/version.py minor)',
'VERSION_PATCH': '<!(python tools/version.py patch)',
'VERSION_RELEASE': '<!(python tools/version.p... |
class StorageResult:
def __init__(self, result=None):
if result is None:
self.total = 0
self._hits = []
self.chunk = 0
else:
self.total = result['hits']['total']['value']
self._hits = result['hits']['hits']
self.chunk = len(self... |
class Sortness:
def getSortness(self, a):
s = 0.0
for i, e in enumerate(a):
s += len(filter(lambda j: j > e, a[:i]))
s += len(filter(lambda j: j < e, a[i+1:]))
return s / len(a)
|
# This code has to be added to the corresponding __init__.py
DRIVERS["lis3dh"] = ["LIS3DH"]
|
def hello(name):
return 'Hello, {}.'.format(name)
def test_hello():
assert 'Hello, Fred.' == hello('Fred')
if __name__ == '__main__':
print(hello('Taro'))
|
# -*- coding: utf-8 -*-
INSTALLED_APPS += ("ags2sld",)
DATA_UPLOAD_MAX_MEMORY_SIZE = 1073741824
FILE_UPLOAD_MAX_MEMORY_SIZE = 1073741824 # maximum file upload 1GB
|
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
h,m=map(int,input().split());m+=60*h-45
if m<0:
m+=24*60
print(m//60,m%60)
|
data1 = 12, 34, 1, 7, 16, 16
data2 = (23, 56, 12, 34, 89, 90, 5.6, 'Adisak')
# print("{}".format(data2))
# print("{}".format(type(data2)))
print("{}".format(data1))
print("{}".format(data1[4]))
print("มีสมาชิก {}".format(len(data1)))
print("มีสมาชิก {}".format(data1.__len__())) # Dunder Method or Magic Method
... |
## func
def make_withdrawal(balance):
def inner(withdraw):
balance -= withdraw
if balance <0:
print("Error: withdraw amount is more than initial balance")
else:
return balance
return inner
## Explain
print("updating the balance inner function doesn't work. In the inner function block, variable balance's... |
class LinkedListMode:
def __init__(self, value):
self.vale = value
self.next = None
def reverse(head_of_list):
current = head_of_list
previous = None
next = None
# until we have 'fallen off' the end of the list
while current:
# copy a pointer to the next element
... |
#
# @lc app=leetcode id=657 lang=python3
#
# [657] Robot Return to Origin
#
# https://leetcode.com/problems/robot-return-to-origin/description/
#
# algorithms
# Easy (74.23%)
# Total Accepted: 288.7K
# Total Submissions: 388.7K
# Testcase Example: '"UD"'
#
# There is a robot starting at position (0, 0), the origin,... |
def insertion_sort(arr):
length = len(arr)
for i in range(1, length):
#Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
key = arr[i]
j=i-1
while( j>=0 and arr[j]>key):
arr[j+1] = arr[j]
... |
task_dataset = "entry-small-1"
# number of individuals for each population
population_size = 40
# number of generations (rounds)
generations = 1000
exitAfter = 250
# for controlling the time scheduling, in minutes
block_size = 10 # in minutes (less than or equal 1 hour)
# define the parents selection method for cro... |
t = """DrawBot is an powerful, free application for MacOSX that invites you to write simple Python scripts to generate two-dimensional graphics. The builtin graphics primitives support rectangles, ovals, (bezier) paths, polygons, text objects and transparency.
DrawBot is an ideal tool to teach the basics of programmin... |
class Solution:
def gen(self, nums, target):
for i, A in enumerate(nums, 0):
for k, B in enumerate(nums[i + 1:], i + 1):
if target - A == B:
yield list((i, k))
def twoSum(self, nums: List[int], target: int) -> List[int]:
for a ... |
"""
Holds all global app variables.
"""
SUPPLIER_DEFAULT_INVENTORY_INTERVAL = 86400
THK_VERSION_NUMBER = "2.0.0"
THK_VERSION_NAME = "Arrakis"
THK_CYCLE_PID = "ThunderhawkCycle"
THK_CYCLE_LAST_POSITION = "thunderhawk cycle last position"
"""
Collections.
"""
MONGO_USERS_COLLECTION = "Users"
MONGO_SUPPLIER_REGISTER_CO... |
class Solution:
def fib(self, n: int) -> int:
if (n == 0):
return 0
if (n == 1):
return 1
last = 1
lastlast = 0
for i in range(n-1):
tmp = last
last += lastlast
lastlast = tmp
return last
|
def sumatorioNumeros(num):
sum = 0
for i in str(num):
sum += int(i)
return sum
numero=int(input("Introduzca número: "))
print("La suma de todos los dígitos da:",sumatorioNumeros(numero))
|
# heuristic monster types lists
ONLY_RANGED_SLOW_MONSTERS = ['floating eye', 'blue jelly', 'brown mold', 'gas spore', 'acid blob']
EXPLODING_MONSTERS = ['yellow light', 'gas spore', 'flaming sphere', 'freezing sphere', 'shocking sphere']
INSECTS = ['giant ant', 'killer bee', 'soldier ant', 'fire ant', 'giant beetle', '... |
# [이진탐색] 부품 찾기
#========== input ===========
# n : 전체 부품의 개수
# data1 : 전체 부품의 종류
# m : 요청한 부품의 개수
# data2 : 요청한 부품의 종류
#========== output ==========
# result : 요청한 부품이 있으면 각각 yes, no로 표시
# 풀이 : 1) 이진탐색 2) 계수정렬 3) set 사용
# 1) 이진탐색
def BS_v2(array, target, start, end):
while start <=end:
mid = (start + end)//... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Comment:
"""评论类,一般不直接使用,而是作为``Answer.comments``迭代器的返回类型."""
def __init__(self, cid, answer, author,
upvote_num, content, time, group_id=None):
"""创建评论类实例.
:param int cid: 评论ID
:param int group_id: 评论所在的组ID
... |
Point = tuple([int, int])
class Field:
"""Placeholder object for a single field in the grid.
It can empty, inaccessible, etc.
Object should fully describe what's at `self.point`,
but implement no mechanism for change."""
def __init__(self, point: Point):
self.point = point
self.p... |
'''
For a non-negative integer X, the array-form of X is an array of its digits in left to right order. For example, if X = 1231, then the array form is [1,2,3,1].
Given the array-form A of a non-negative integer X, return the array-form of the integer X+K.
Example 1:
Input: A = [1,2,0,0], K = 34
Output: [1,2,3,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.