content stringlengths 7 1.05M |
|---|
"""for文基礎
for文によるループ処理
[説明ページ]
https://tech.nkhn37.net/python-for/#for-2
"""
# for文の基本的な使い方
data = [10, 20, 30, 40, 50]
for dt in data:
print(f'dt: {dt}')
|
def reverse_deck(d): return d[::-1]
def cut_cards(d,n): return d[n:]+d[:n]
def increment_deal(d,n): return [c for sorter,c in sorted([((i*n)%len(d),d[i]) for i in range(len(d))])]
def shrink_actions(actions,size):
while len(actions) > 3: # continue... |
dt = {"shihab": "programmer", "mahinur": "graphic designer", "jion": "civil engineer"}
for i in dt:
print(i, end=" ")
print()
for pro in dt.values():
print(pro, end=" ")
print("\n")
for i, pro in dt.items():
print(i,": ", pro)
print() |
'''
We don't use the standard keras loss logic, keep this file empty
'''
global_loss_list = {}
|
#Family name: Prabh Simran Singh Badwal
# Student number: 300057572
# Course: IT1 1120[F]
# Assignment Number 4 Part 2
class Point:
'class that represents a point in the plane'
def __init__(self, xcoord=0, ycoord=0):
''' (Point, float, float) -> None
initialize point coordinates to (xcoord, y... |
balance = 3329
annualInterestRate = 0.2
unPaidBalance = 0
fixedPayment = (balance / 15) - (balance / 15)%10
while True:
tempBalance = balance
for __ in range(12):
unPaidBalance = tempBalance - fixedPayment
tempBalance = unPaidBalance + (annualInterestRate/12)*unPaidBalance
if tempBa... |
#
# 13. Roman to Integer
#
# Roman numerals are represented by seven different symbols: I, V, X, L, C, D, M
#
# Symbols Value
#
# I 1
# V 5
# X 10
# L 50
# C 100
# D 500
# M 1000
#
# For example, two is written ... |
def config_to_file(config, path):
with open(path, "w+") as f:
f.write(config)
return
|
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( high , low , n ) :
if ( n <= 0 ) :
return 0
return max ( high [ n - 1 ] + f_gold ( high , low , ( n... |
"""Responses.
responses serve both testing purpose aswell as dynamic docstring replacement
"""
responses = {
"_v3_accounts_accountID_trades": {
"url": "v3/accounts/{accountID}/trades",
"params": {
"instrument": "DE30_EUR,EUR_USD"
},
"response": {
"trades": [
... |
def caesarCipherEncryptor(string, key):
# Write your code here.
newLetters = []
newKey = key % 26
for letter in string:
newLetters.append(getNewLetter(letter, newKey))
return "".join(newLetters)
def getNewLetter(letter, key):
newLetterCode = ord(letter) + key
return chr(newLetterCod... |
def generate_user_key(email: str):
username, domain = email.split('@')
return {
'PK': f'DOMAIN#{domain.upper()}',
'SK': f'USERNAME#{username.upper()}'
}
|
# DataFrame Columns
# Symbols
SYM_T = "t"
SYM_X = "x"
|
"""
Configuration for docs
"""
# source_link = "https://github.com/[org_name]/hexapharmachem"
# docs_base_url = "https://[org_name].github.io/hexapharmachem"
# headline = "App that does everything"
# sub_heading = "Yes, you got that right the first time, everything"
def get_context(context):
context.brand_html = "He... |
if __name__ == '__main__':
readline = input()
mn = readline.strip().split(' ')
n = int(mn[0])
m = int(mn[1])
stack = []
if n == 0:
stack.append(0)
while n > 0:
stack.append(n % m)
n = n//m
while len(stack) > 0:
x = stack.pop()
if x < 10:
... |
class InitializationException(Exception):
"""Raised when an error occurred during init of a CoML directory."""
class ForbiddenDirectoryAccessError(RuntimeError):
"""Raised when accessing a CoML directory while a step is executed."""
|
class AptlyCtlError(Exception):
def __init__(self, msg, original_exception=None):
if original_exception:
self.msg = ": ".join([msg, str(original_exception)])
else:
self.msg = msg
if original_exception:
self.original_exception = original_exception
|
num1=int(input("number 1: "))
num2=int(input("number 2: "))
#>
#<
#else
if num1>num2:
print(num1," is greater than ",num2)
elif num1<num2:
print(num2," is greater than ",num1)
else:
print(num1," is equal to ",num2)
|
def create_user(username, password, roles):
user = User(username=username,
password=password,
roles=roles)
db.session.add(user)
return user
|
# Faça um programa que leia um número inteiro e mostre a sua tabuada
n = int(input('Digite uma valor: '))
print('--'*12)
print(n, ' x 0 = {}'.format(n * 0))
print(n, ' x 1 = {}'.format(n * 1))
print(n, ' x 2 = {}'.format(n * 2))
print(n, ' x 3 = {}'.format(n * 3))
print(n, ' x 4 = {}'.format(n * 4))
print(n, ' x ... |
class MyQueue(object):
def __init__(self):
self.first = []
def peek(self):
return self.first[0]
def pop(self):
self.first = self.first[1:]
pass
def put(self, value):
self.first.append(value)
pass
queue = MyQueue()
t = int(input())
for line in range(t):
... |
x = int(input("Please enter an integer: "))
def check_num(x):
if x < 0:
print('负数')
elif x == 0:
print('零蛋')
else:
print('正数')
check_num(x)
def f(a, L=[]):
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))
def f1(a, L=None):
if L is None:
L = []
... |
# def square(x):
# '''
#
# :param x:
# :return:
# '''
# epsilon = 0.01
# guess = x / 2.0
#
# while abs(guess * guess - x) >= epsilon:
# guess = guess - (((guess ** 2) - x) / (2 * guess))
# return guess
#
# y = int(input("Enter a number: "))
# print("Square root of x is: " + str(s... |
'''Crie um programa que tenha uma tupla totalmente preenchida com uma contagem por extenso, de zero até vinte.
Seu programa deverá ler um número pelo teclado ( entre 0 e 20) e mostrá-lo por extenso.'''
numeral = ('Zero', 'Um', 'Dois', 'Três', 'Quatro', 'Cinco', 'Seis', 'Sete', 'Oito', 'Nove', 'Dez', 'Onze', 'Doze', 'T... |
# https://leetcode.com/problems/shortest-unsorted-continuous-subarray/
class Entry:
def __init__(self, num: int, idx: int):
self.num = num
self.idx = idx
def __lt__(self, other) -> bool:
return self.num < other.num
class Solution:
def findUnsortedSubarray(self, nums: list[int]) -... |
soma = 0
quantidade = 0
controle = True
while controle:
numero = int(input('Insira um número [999/Cancelar]: '))
if numero == 999:
controle = False
else:
soma += numero
quantidade += 1
print('Você digitou {} números e a somatório é {}.'.format(quantidade, soma))
|
"""Exception classes."""
class ParseError(Exception):
code = -32700
class InvalidRequest(Exception):
code = -32600
class MethodNotFound(Exception):
code = -32601
def __init__(self, method_name):
self.method_name = method_name
class InvalidParams(Exception):
code = -32602
class Int... |
# coding=utf-8
class UserTG:
def __init__(self, dict_user):
# Type: Integer
# Unique identifier for this user or bot
self.id = dict_user["id"]
# Type: String
# User‘s or bot’s first name
self.first_name = dict_user["first_name"]
# Type: String
# Us... |
class ToilletPaperAg():
def __init__(self,env) -> None:
self.env = env
self.price_average = 0
self.current_percepts = env.initial_percepts()
self.usage_average = self.current_percepts['tpnumber']
self.usage = self.current_percepts['tpnumber']
self.age = 0
sel... |
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
a=0
for x in nums:
if x!=val:
nums[a]=x #替换
a+=1
return a |
"""Service class for the Broker."""
# pylint: disable=R0205,R0903
class Service:
"""A single Service."""
name = None # Service name
requests = None # List of client requests
waiting = None # List of waiting workers
def __init__(self, name):
"""
Initialize a service.
... |
def largest_arrangement(numbers):
#this should be at least two times faster
#than permutations approach
mlen = max(map(lambda x: len(str(x)), numbers))
srtd1 = sorted(numbers)
srtd2 = sorted(srtd1, key=lambda x: custom_sort(x, mlen), reverse=1)
return int(''.join(map(str, srtd2)))
def cust... |
# Representative data that shows various events; extracted from old, historical data for illustration purposes
debug_events = [
# 0 nice cyclic_stats data with a spike
[22,28,7,6,15,13,36,60,169,219,424,429,407,317,330,294,254,250,
344,378,388,302,205,72,59,85,41,11,22,52,54,78,165,156,184,2... |
def become_to_number_1(n, k): # 해당 케이스의 경우 n = 2k-1, k = k 라면 k번 만큼의 반복문을 수행하게 된다.
count = 0
while 1 < n:
if 0 == n % k:
n /= k
else:
n -= 1
count += 1
return count
def solve(n, k):
result = 0
while True:
# N이 K로 나누어 떨어지는 수가 될 때까지만 1씩 빼기
... |
# -*- coding: utf-8 -*-
# * Copyright (c) 2009-2017. Authors: see NOTICE file.
# *
# * 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... |
N = int(input())
if 1 <= N <= 100:
for _ in range(0, N):
soma = 0
X = int(input())
for value in range(1, X):
if X % value == 0:
soma += value
if soma == X:
print(f"{X} eh perfeito")
else:
print(f"{X} nao eh perfeito") |
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'translation_unit_or_emptyleftLORleftLANDleftORleftXORleftANDleftEQNEleftGTGELTLEleftRSHIFTLSHIFTleftPLUSMINUSleftTIMESDIVIDEMODAND ANDEQUAL ARROW AUTO BREAK CHAR CHAR_C... |
OF_BYTE_LENGTH = 1250304
OF_BLOCK = [
12,
5144,
9508,
14044,
36872,
657712,
803608,
822940,
969192,
1228568,
1250316,
]
OF_BLOCK_SIZE = [
4948,
1232,
4520,
22816,
620000,
145880,
19320,
146240,
259364,
21016,
]
OF_KEY = [
1815549... |
# For memory better memory management
# Generators allow you to create a function that returns one item at a time rather than all the items at once.
# This means that if you have a large dataset, you don’t have to wait for the entire dataset to be accessible.
def __iter__(self):
return self.__generator()
def __ge... |
'''
Over writes value with 0
i=5
print("Global i :",i,end="\n\n")
for i in range(i):
print("Looped i :",i)
print("\nGlobal i :",i)
'''
'''
Does not go inside loop
i=5
print("Global i :",i,end="\n\n")
for i in range(i,5):
print("Looped i :",i)
print("\nGlobal i :",i)
'''
'''
Does not go inside loop
i=5
pr... |
baseUrl = 'https://www.playmemoriescameraapps.com/portal'
loginUrl = 'https://account.sonyentertainmentnetwork.com/liquid/external/auth/login!authenticate.action'
registerUrl = 'https://account.sonyentertainmentnetwork.com/liquid/external/create-account!input.action'
cameraUserAgent = "Mozilla/5.0 (Build/sccamera)"
loc... |
class MetaEntryPointDescription(object):
description = """
This is an entry point that describes other entry points.
"""
class CreateTemplateDescription(object):
description = """
Entry point for creating the file layout for a new project
from a template.
"""
class PasterCommandDescription... |
#Kunal Gautam
#Codewars : @Kunalpod
#Problem name: Split Strings
#Problem level: 6 kyu
def solution(s):
return [s[i:i+2] for i in range(0, len(s), 2)][:-1] + [s[-1:]+'_'] if len(s)%2 else [s[i:i+2] for i in range(0, len(s), 2)]
|
# _*_ coding:utf-8 _*_
b=0.3
h=0.4
l=1
E=2.1*10**11
I=(1.0/12)*b*h**3
#u_fea=6.726*10**-9
u_fea=6.032*10**-9
xita_fea=5.952*10**-9
xita_theory=2/(2.1*10**11*(1.0/12)*b*h**3)
u_theory=2/(2.1*10**11*(1.0/12)*b*h**3)
print('xita_theory:'+str(xita_theory))
print(('u_theory:'+str(u_theory)))
print('error_u:'+str(((u... |
# -*- coding: UTF-8 -*-
__title__ = 'utils'
__description__ = 'Utils is a collection of common Python functions and classes'
__version__ = '1.2.1'
__author__ = 'Xinyi'
__license__ = 'MIT License'
|
def fibonacci(limit=None):
a, b = 0, 1
while True:
if limit and b >= limit:
break
yield b
a, b = b, a+b |
number = 1000
for i in range(1,201):
for j in range(1, 6):
print(number, end ="\t")
number -= 1
print() |
# generated by build_frequency_lists
FREQUENCY_LISTS = {
"passwords": "123456,password,12345678,qwerty,123456789,12345,1234,111111,1234567,dragon,123123,baseball,abc123,football,monkey,letmein,shadow,master,696969,mustang,666666,qwertyuiop,123321,1234567890,pussy,superman,654321,1qaz2wsx,7777777,fuckyou,qazwsx,jord... |
'''
Non-public attributes are those that are not intended to be used by third parties.
We don't use the term "private" here, since no attribute is really private in Python,
as they are still accessible.
If your class is intended to be subclassed,
and you have attributes that you do not want subclasses to use,
consider... |
api_id = "13321231"
api_hash = "87fab454b4d6eb4429017cd45ee64cc8"
#your username
name = 'cyberspoof'
spread_user_cred_json_file_addr = "cred.json"
#input spred url containing links
fetch_spreadsheet_url = "https://docs.google.com/spreadsheets/d/1RlA_t9v1frCcTxsn6HNdA_SBzAHoX2LJhMnmsIJ4Ovw/edit#gid=0"
# usernames t... |
m, n, k = map(int, input().split())
f = []
for i in range(0, m):
f.append(list(str(input())))
for j in range(0, m):
for t in range(0, k):
result = ''
for o in range(0, n):
for p in range(0, k):
result = str(result) + str(f[j][o])
print(result)
|
DICT_SMILEY = {
":-)": "smiley",
":)": "smiley",
";)": "smiley",
";-)": "smiley",
":D": "smiley",
"xD": "smiley",
":’)": "smiley",
":’D": "smiley",
":3": "smiley",
":]": "smiley",
":^)": "smiley",
":-]": "smiley",
":-3": "smiley",
":->": "smiley",
":))": "smil... |
"""
Conditioner module related exceptions
"""
class BaseConditionerException(Exception):
"""
Base class for all conditioner related exceptions
"""
pass
class IncorrectModelException(BaseConditionerException):
"""
Model specific action/condition got wrong object instance
"""
pass
|
# Por posición, por nombre, sin argumentos
def max_two_values(first_value = None, second_value = None):
if ( first_value == None or second_value == None):
print("Debemos de especificar los dos valores")
return
if first_value > second_value:
print("Primer valor máximo")
elif first_va... |
"""Constants for wilight platform."""
DEFAULT_RECONNECT_INTERVAL = 60
DEFAULT_KEEP_ALIVE_INTERVAL = 12
CONNECTION_TIMEOUT = 15
DEFAULT_PORT = 46000
DOMAIN = "wilight"
CONF_ITEMS = "items"
# Item types
ITEM_NONE = "none"
ITEM_LIGHT = "light"
ITEM_SWITCH = "switch"
ITEM_FAN = "fan"
ITEM_COVER = "cover"
# Light types... |
p0 = int(input('Entre com o ponto inicial da PA: '))
razao = int(input('Entre com a razão da PA: '))
for c in range(0,11):
print('O termo {} da PA é {}!'.format(c, p0+(razao*c)))
|
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE'
}
stopwords_path = "static/stopwords/my_stopwords.txt"
font_path = "static/fonts/simhei.ttf" |
class ComponentProxy(object):
"""
Proxy object trough which communication happens. Will essentially hide
all private methods and attributes of a component and only expose public
functions.
"""
__slots__ = "_component"
def __init__(self, component):
self._component = component
... |
# filter(funcion para filtrar la info, objeto iterable)
# 1
def check_is_int(element): return type(element) == int
set = {'Anartz', 10, 1, 2, 3, 4, 567, 23 + 45j, 34.5}
x = list(filter(check_is_int, set))
# [10, 1, 2, 3, 4, 567]
print(x)
x_lambda = list(filter(lambda x: type(x) == int, set))
print(x_lambda)
# [10, ... |
def part1(path):
increases = 0
last_number = 999999999999
with open(path) as input:
for x in input:
x = int(x)
if x > last_number:
increases += 1
last_number = x
return increases |
# list型にして、join関数で文字列を作成
list = list(map(str, input().split()))
s = ''.join(list)
print('YES') if int(s) % 4 == 0 else print('NO')
|
"""
for for
"""
"""
print("*",end = " ")
print("*",end = " ")
print("*",end = " ")
print("*",end = " ")
print("*",end = " ")
print() # 换行
print("*",end = " ")
print("*",end = " ")
print("*",end = " ")
print("*",end = " ")
print("*",end = " ")
print() # 换行
"""
"""
for c in range(5): # 0 1 2 3 4
print("*", end... |
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
mem ={}
mem[2] = ["a","b","c"]
mem[3] = ["d","e","f"]
mem[4] = ["g","h","i"]
mem[5] = ["j","k","l"]
mem[6] = ["m","n","o"]
... |
"""
Docstring
.. pii: A long description that
spans multiple
lines
.. pii_types: id, name
"""
|
def ficha(jog='<desconhecido>',gol=0):
if jog== '':
jog = 'desconhecido'
if not gol.isnumeric():
gol=0
return f' O jogador {jog} fez {gol} gols(s) no campeonato'
n = str(input('Nome do jogador : ')).strip()
g = str(input('Numero de Gols : '))
print(ficha(n,g)) |
#DESAFIO 65
#Crie um programa que leia vários números inteiros pelo teclado.
#No final da execução, mostre a média entre todos os valores
#e qual foi o maior e o menor valores lidos.
#O programa deve perguntar ao usuário se ele quer
#ou não continuar a digitar valores.
resp = 'S'
soma=quant=média=maior=menor=0
while re... |
## All (sub)modules in laelaps_control package.
__all__ = [
'AboutDlg',
'AlarmsWin',
'images',
'RangeSensorWin',
'TwistMoveWin',
'Utils',
'WarnDlg',
]
|
"""Constants for PI step scans"""
# Replace /append actions in wavetable commands
ACTION_REPLACE = "X"
ACTION_APPEND = "&"
# States for STATE PV
STATE_NOT_CONFIGRED = 0
STATE_PREPARING = 1
STATE_ERROR = 2
STATE_READY = 3
STATE_SCAN_RUNNING = 4
# Which wave table for which axis
TABLEX = 1
TABLEY = 3
TABLEZ = 2
# Axi... |
class ComputationalBlockTwoInvalidOperationTypeException(Exception):
pass
class ComputationalBlockTwoFieldDoesNotExistException(Exception):
pass
class ComputationalBlockTwoOperationValueNotFloatException(Exception):
pass
class ComputationalBlockTwoDataValueNotFloatException(Exception):
pass
clas... |
# 用于表示季节的列表
# 元素是英语
season = [
'spring',
'summer',
'autumn',
'winter',
]
print('season[0] = ', season[0])
print('season[1] = ', season[1])
print('season[2] = ', season[2])
print('season[3] = ', season[3])
|
#
# PySNMP MIB module HUAWEI-NAT-EXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-NAT-EXT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:35:43 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
"""
In the Martian land faraway, a new virus has evolved and is attacking the individuals at a fast pace. The scientists have figured out the virus composition, V. The big task is to identify the people who are infected. The sample of N people is taken to check if they are POSITIVE or NEGATIVE. A report is generated wh... |
# DATA_DIR = "/content/drive/MyDrive/data/"
# CHECKPOINT_PATH = "/content/drive/MyDrive/data/MNIST/checkpoint"
# PLOT_PATH = "/content/drive/MyDrive/data/MNIST/plots"
# NUM_WORKERS = 1
# DEVICE = "cuda"
# BATCH_SIZE = 32
# EPOCHS = 10
DATA_DIR = "../data/"
CHECKPOINT_PATH = "../checkpoint"
PLOT_PATH = "../plots"
BATCH... |
class FightInfo:
def __init__(self, fighter1_ref, fighter2_ref, event_ref, outcome, method, round, time):
self.fighter1_ref = fighter1_ref
self.fighter2_ref = fighter2_ref
self.event_ref = event_ref
self.outcome = outcome
self.method = method
self.round = round
... |
# 207. Course Schedule
# ttungl@gmail.com
# Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
# For example:
# 2, [[1,0]]
# There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.
# 2, [[1,0],[0,1]]
#... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
if left == 1:
return self.revers... |
"""
demo_api module entry point.
"""
__author__ = 'Esteban Zamora Alvarado'
__email__ = 'esteban.zamora.al@gmail.com'
__version__ = '0.0.1'
def add(a: int, b: int):
return a + b
def mult(a: int, b: int):
return a * b
def double_if_pos(a: int):
assert a >= 0, "a is negative, cannot proceed"
return... |
# -*- coding: utf-8 -*-
# @Author: 何睿
# @Create Date: 2019-01-10 18:12:23
# @Last Modified by: 何睿
# @Last Modified time: 2019-01-10 18:16:58
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype
"""
# 如果没有节点或者只有一个节点,返回False
... |
# output from elife00270.xml
expected = [
{
"type": "author",
"corresp": "yes",
"id": "author-1032",
"role": "Editor-in-Chief",
"email": ["editorial@elifesciences.org"],
"surname": "Schekman",
"given-names": "Randy",
"references": {"competing-interest"... |
win = 0
p, j1, j2, r, a = map(int, input().split())
sum = j1 + j2
if (sum % 2 == 0 and p == 1) or (sum %2 != 0 and p == 0):
win = 1
else:
win = 2
if (r == 1 and a == 0) or (r == 0 and a ==1):
win = 1
if r == 1 and a == 1:
win = 2
print('Jogador %d ganha!' %win)
|
T = int(input())
for _ in range(T):
N = int(input())
print(int(N**0.5))
|
"""Public API for bazeldoc."""
load("//bazeldoc/private:doc_for_provs.bzl", _doc_for_provs = "doc_for_provs")
load("//bazeldoc/private:providers.bzl", _providers = "providers")
load("//bazeldoc/private:write_file_list.bzl", _write_file_list = "write_file_list")
load("//bazeldoc/private:write_header.bzl", _write_header... |
#!/usr/bin/env python3
#Fonction qui va gerer les limites
#ajout ligne pour push
lim = {
"x_min":0.0,
"x_max":200.0,
"y_min":0.0,
"y_max":200.0,
"z_min":0.0,
"z_max":200.0,
"q1_min":-45.0,
"q1_max":45.0,
"q2_min":30.0,
"q2_max":130.0,
"q3_min":-15.0,
"q3_max":60.0
}... |
a, b = input().split()
a = int(a)
b = int(b)
print("Sun Mon Tue Wed Thr Fri Sat")
print(" " * (a*3 -1 + a-1),end="")
count = a
c = 1
for p in range(b):
if count == 8:
print("\n",end="")
if c <= 9:
print(" ",end="")
else:
print(" ",end="")
count = 1
print(... |
class RootLevel:
def __init__(self, obj):
self.input_id = obj.get("input_id", None)
self.organization = obj.get("organization", None)
self.address1 = obj.get("address1", None)
self.address2 = obj.get("address2", None)
self.address3 = obj.get("address3", None)
self.add... |
def radix_sort(to_be_sorted):
maximum_value = max(to_be_sorted)
max_exponent = len(str(maximum_value))
# Create copy of to_be_sorted
being_sorted = to_be_sorted[:]
# Loop over all exponents
for exponent in range(max_exponent):
index = - (exponent + 1)
digits = [[] for digit in range(10)]
# Bu... |
n = int(input())
num = [int(input()) for i in range(n)]
res = 0
aux = sum([v*v for v in num])
aux2 = 0
for i in range(n-1, 0, -1):
aux -= num[i]*num[i]
aux2 += num[i]
res = max(res, aux*aux2)
print(res) |
# advent of code
# response to the challenge by geir owe
# day8 - challenge: https://adventofcode.com/2020/day/8
#start function
def get_all_instructions(boot_file):
allInstruct = []
#move all instructions in the boot file into a list
for instruction in boot_file:
instruction = instruction.strip()... |
# 463. Island Perimeter Easy
# You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water.
#
# Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected lan... |
#!/usr/bin/env python3
weight = int(input())
height = int(input())
bmi = (weight / (height * height)) * 10000
if bmi < 18.5:
print("underweight")
elif bmi > 18.5 and bmi < 25:
print("normal")
elif bmi > 25 and bmi < 30:
print("overweight")
else:
print("obese")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Les listes imbriquées
On les appeles aussi 'tableaux multidimensionnels'
dans d'autres langages
"""
matrix = [
[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6]
]
print(matrix)
# cette compréhension de liste intervertit
# les lignes et les colonnes d'une matrice ... |
class ValidationResult(object):
def __init__(self, is_valid=False):
self.is_valid = is_valid
self.errors = []
self.warnings = []
|
class InfogramPythonError(Exception):
""" Base exception """
class InfogramError(InfogramPythonError):
""" Exception for the Infogram API errors """
class AuthenticationError(InfogramError):
""" Exception for the Infogram API authentication errors """
class InternalServerError(InfogramError):
""" Exc... |
"""Find common values in 2 binary trees."""
def tree_intersection(bst1, bst2):
"""Return a set of common values found in two binary tree parameters."""
set1, set2, perpendicular = set(), set(), set()
bst1.pre_order(lambda n: set1.add(n.val))
bst2.pre_order(lambda n: set2.add(n.val))
for each in ... |
class User:
def __init__(self, id, email=None):
self.id = id
self.email = email
@property
def is_active(self):
return True
@property
def is_authenticated(self):
return True
@property
def is_anonymous(self):
return False
def get_id(self):
... |
# https://leetcode.com/problems/valid-palindrome-ii/
class Solution(object):
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
def helper(s):
return s[::-1]==s
left = 0
count =0
right = len(s)-1
... |
"""
Tests cookiecutter baking process and rendered content
"""
def test_project_tree(cookies):
result = cookies.bake(extra_context={
'project_name': 'hello sam'
})
assert result.exit_code == 0
assert result.exception is None
assert result.project.basename == 'hello sam'
assert resu... |
# pylint: disable=invalid-name, missing-docstring
IYELIK_EKI = 1
YONELME_EKI = 2
BULUNMA_EKI = 3
AYRILMA_EKI = 4
def ekle_aykiri(ek_tipi, kelime, ayir):
ayirma_eki = "'" if ayir else ""
if ek_tipi is IYELIK_EKI:
sonuc = kelime + ayirma_eki + "nin"
elif ek_tipi is YONELME_EKI:
sonuc = keli... |
class Solution:
def hitBricks(self, grid, hits):
m, n, ret = len(grid), len(grid[0]), [0]*len(hits)
# Connect unconnected bricks and
def dfs(i, j):
if not (0 <= i <m and 0 <= j <n) or grid[i][j] != 1:
return 0
grid[i][j] = 2
return 1 + sum... |
# List Comprehension
# [new_item for item in list]
# [new_item for item in list if condition]
# Create new list with incrementing each value by 1
list1 = [1, 2, 3]
new_list1 = [n + 1 for n in list1]
print(new_list1)
# Print letter of the name
name = "Steve"
letter_list = [n for n in name]
print(letter_list)
# Double... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.