content stringlengths 7 1.05M |
|---|
class Solution:
def simplifyPath(self, path: str) -> str:
stk = []
for p in path.split('/'):
if p == '..':
if stk:
stk.pop()
elif p and p != '.':
stk.append(p)
return '/' + '/'.join(stk) |
class Fraction(object):
def __init__(self, num, den):
self.__num = num
self.__den = den
self.reduce()
def __str__(self):
return "%d/%d" % (self.__num, self.__den)
def __invert__(self):
return Fraction(self.__den,self.__num)
def __neg__(self):
return Fr... |
"""Configuration file for common models/experiments"""
MAIN_PARAMS = {
'sent140': {
'small': (10, 2, 2),
'medium': (16, 2, 2),
'large': (24, 2, 2)
},
'femnist': {
'small': (30, 10, 2),
'medium': (100, 10, 2),
'large': (400, 20, 2)
},
'uni-fem... |
# filter1.py to get even numbers from a list
def is_dublicate(item):
return not(item in mylist)
mylist = ["Orange","Apple", "Banana", "Peach", "Banana"]
new_list = list(filter(is_dublicate, mylist))
print(new_list)
|
class strongly_connected_component():
def __init__(self, graph=None, visited=None):
self.graph = dict()
self.visited = dict()
self.stack=list()
def add_vertex(self, v, graph, visited):
if not graph.get(v):
graph[v] = []
visited[v]=0
def add_edge(self, v1, v2, e, gra... |
AVAILABLE_LANGUAGES = {
"english": "en",
"indonesian": "id",
"czech": "cs",
"german": "de",
"spanish": "es-419",
"french": "fr",
"italian": "it",
"latvian": "lv",
"lithuanian": "lt",
"hungarian": "hu",
"dutch": "nl",
"norwegian": "no",
"polish": "pl",
"portuguese ... |
sala = []
def AdicionarSala(cod_sala,lotacao):
aux = [cod_sala,lotacao]
sala.append(aux)
print (" === Sala adicionada === ")
def StatusOcupada(cod_sala):
for s in sala:
if (s[0] == cod_sala):
s[1] = "Ocupada"
return s
return None
def StatusLivre(cod_sala):
for s... |
"""
Características:
- Inverted a posição dos elementos de uma lista
- Enquanto reverse() só funciona com listas, reversed() funciona com todos os iteráveis
"""
# Exemplo
numeros = [6, 1, 8, 2]
res = reversed(numeros)
# Lista
print(list(reversed(numeros)))
# Tupla
print(tuple(reversed(numeros)))
# Conjunto (Set)
pr... |
"""
All wgpu structs.
"""
# THIS CODE IS AUTOGENERATED - DO NOT EDIT
# %% Structs (45)
RequestAdapterOptions = {"power_preference": "GPUPowerPreference"}
DeviceDescriptor = {
"label": "str",
"extensions": "GPUExtensionName-list",
"limits": "GPULimits",
}
Limits = {
"max_bind_groups": "GPUSize32",
... |
class InvalidStateTransition(Exception):
pass
class State(object):
def __init__(self, initial=False, **kwargs):
self.initial = initial
def __eq__(self, other):
if isinstance(other, basestring):
return self.name == other
elif isinstance(other, State):
retur... |
__author__ = 'Aleksander Chrabaszcz'
__all__ = ['config', 'parser', 'pyslate']
__version__ = '1.1'
|
"""
Class to handle landmarkpoints
template pt {"y":392,"x":311,"point":0,"state":"visible"}
"""
class l_point(object):
def __init__(self, **kwargs):
self.__x__ = kwargs['x']
self.__y__ = kwargs['y']
'''
self.__indx__ = kwargs['point']
if kwargs['state'] in 'visible':
... |
H, W = map(int, input().split())
for _ in range(H):
C = input()
print(C)
print(C)
|
class ResponseStatus:
"""Possible values for attendee's response status
* NEEDS_ACTION - The attendee has not responded to the invitation.
* DECLINED - The attendee has declined the invitation.
* TENTATIVE - The attendee has tentatively accepted the invitation.
* ACCEPTED - The attendee has accepte... |
public_key = 28
# Store the discovered factors in this list
factors = []
# Begin testing at 2
test_number = 2
# Loop through all numbers from 2 up until the public_key number
while test_number < public_key:
# If the public key divides exactly into the test_number, it is a factor
if public_key % test_number... |
# -*- coding: utf-8 -*-
"""
The custom exception module
Copyright 2017-2018, Leo Moll and Dominik Schlösser
Licensed under MIT License
"""
class DatabaseCorrupted(RuntimeError):
"""This exception is raised when the database throws errors during update"""
class DatabaseLost(RuntimeError):
"""This exception ... |
# Display
default_screen_width = 940
default_screen_height = 600
screen_width = default_screen_width
screen_height = default_screen_height
is_native = False
max_tps = 16
board_width = 13
board_height = 9
theme = "neon" # neon/paper/football
# Sound
sound_volume = 0.1
sound_muted = False
|
class Funcionario:
def __init__(self, nome):
self.nome = nome
def registrar_horas(self, horas):
print(f"Horas registradas: {horas}")
def mostrar_tarefas(self):
print("Mostrando tarefas")
class Caelum(Funcionario):
def mostrar_tarefas(self):
print("Mostrando tarefas do... |
# -*- coding: utf-8 -*-
"""
Functions for navigating trees represented as embedded dictionaries.
"""
__author__ = "Julian Jara-Ettinger"
__license__ = "MIT"
def BuildKeyList(Dictionary):
"""
WARNING: This function is for internal use.
Return a list of lists where each inner list is chain of valid keys w... |
MIN_SIZE = 13
# coding: utf-8
class Reporter(object):
def __init__(self):
self.cnt = 0
self.cliques = []
def inc_count(self):
self.cnt += 1
def record(self, clique):
self.cliques.append(clique)
def print_report(self):
print ('%d recursive calls' % self.cn... |
fib = [1, 1]
for i in range(2, 11):
fib.append(fib[i - 1] + fib[i - 2])
def c2f(c):
n = ord(c)
b = ''
for i in range(10, -1, -1):
if n >= fib[i]:
n -= fib[i]
b += '1'
else:
b += '0'
return b
ALPHABET = [chr(i) for i in range(33,126)]
print(ALPHABET)
flag = ['10000100100','10010000010','10010001010... |
# -*- coding: utf-8 -*-
__version__ = "20.4.1a"
__author__ = "Taro Sato"
__author_email__ = "okomestudio@gmail.com"
__license__ = "MIT"
|
# represents the format of the string (see http://docs.python.org/library/datetime.html#strftime-strptime-behavior)
# format symbol "z" doesn't wok sometimes, maybe you will need to change csv2youtrack.to_unix_date(time_string)
DATE_FORMAT_STRING = ""
FIELD_NAMES = {
"Project" : "project",
"Summary" ... |
# -*- coding: utf-8 -*-
# @Author: jerry
# @Date: 2017-09-09 21:15:54
# @Last Modified by: jerry
# @Last Modified time: 2017-09-09 21:21:08
'''[你想封装类的实例上面的“私有”数据,但是Python语言并没有访问控制。]
[解决方案]
Python程序员不去依赖语言特性去封装数据,而是通过遵循一定的属性和方法命名规约来达到这个效果。 第一个约定是任何以单下划线_开头的名字都应该是内部实现。
'''
class A:
def __init__(self):
... |
#variables
vetor = []
#input
for(i) in range(0, 10):
num = int(input("Digite um número para o vetor {0}/10: ".format(i + 1)))
vetor.append(num)
vetor.reverse() #inverte a ordem
for(i) in (vetor):
print(i) |
# taken from: http://pjreddie.com/projects/mnist-in-csv/
# convert reads the binary data and outputs a csv file
def convert(image_file_path, label_file_path, csv_file_path, n):
# open files
images_file = open(image_file_path, "rb")
labels_file = open(label_file_path, "rb")
csv_file = open(csv_file_path... |
# SPDX-License-Identifier: MIT
# Source: https://github.com/microsoft/MaskFlownet/tree/5cba12772e2201f0d1c1e27161d224e585334571
class Reader:
def __init__(self, obj, full_attr=""):
self._object = obj
self._full_attr = full_attr
def __getattr__(self, name):
if self._object is None:
... |
"""
Relaxation methods
------------------
The multigrid cycle is formed by two complementary procedures: relaxation and
coarse-grid correction. The role of relaxation is to rapidly damp oscillatory
(high-frequency) errors out of the approximate solution. When the error is
smooth, it can then be accurately represente... |
taboada = int(input('Qual taboada você quer ver? '))
contador = 0
continuar = ''
while True:
if taboada < 0:
print('Não imprimimos taboada com números negativos!')
break
if contador != 10:
contador += 1
print(f'{taboada} x {contador} = {taboada * contador}')
if contador == 10... |
# Copyright 2016 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
class InitializationError(Exception):
"""Raised by RemoteClient.initialize on fatal errors."""
def __init__(self, last_error):
super(Ini... |
numeros = ("zero","um","dois","três","quatro","cinco","seis","sete","oito","nove")
busca = int(input("Digite um número: "))
print(numeros[busca]) |
"""Special Pythagorean triplet
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
def is_pythagorean_triplet(a, b, c):
"""De... |
"""
Python program to check whether given tree is binary search tree(BST) or not
[BST details - https://en.wikipedia.org/wiki/Binary_search_tree]
"""
class Node:
# Create node for binary tree
def __init__(self, v):
self.value = v
self.left = None
self.right = None
def inorder_travers... |
# Write your solution for 1.4 here!
def is_prime(x):
# mod = x
for i in range(x-1, 1, -1):
if x % i == 0 :
return False
return True
# else:
# return True
# is_prime(8)
print(is_prime(5191))
|
#!/usr/bin/env python
# Copyright 2020 The Kubernetes Authors.
#
# 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 appli... |
class CurveLoopIterator(object,IEnumerator[Curve],IDisposable,IEnumerator):
""" An iterator to a curve loop. """
def Dispose(self):
""" Dispose(self: CurveLoopIterator) """
pass
def MoveNext(self):
"""
MoveNext(self: CurveLoopIterator) -> bool
Increments the iterator to the next item.
... |
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/913/A
# 求m%(2**n), 问题是n,m都很大..
# 用bit运算?? mask??
# n很大,直接算肯定会溢出,所以要利用数学属性?
# 如果n足够大, 答案就是m
# 如果n不够大, 就可以用对m的位运算?
# https://codeforces.com/blog/entry/56992
# 敢于尝试/落实最简单的方案
n = int(input()) #1e8
m = int(input()) #1e8
print(m if n>=27 else m%(2**n)... |
class InternalServerError(Exception):
pass
class SchemaValidationError(Exception):
pass
class EmailAlreadyExistsError(Exception):
pass
class UnauthorizedError(Exception):
pass
class NoAuthorizationError(Exception):
pass
class UpdatingUserError(Exception):
pass
class DeletingUserError... |
"""This rule gathers all .proto files used by all of its dependencies.
The entire dependency tree is searched. The search crosses through cc_library
rules and portable_proto_library rules to collect the transitive set of all
.proto dependencies. This is provided to other rules in the form of a "proto"
provider, using ... |
#
# PySNMP MIB module DELL-NETWORKING-COPY-CONFIG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DELL-NETWORKING-COPY-CONFIG-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:37:52 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pytho... |
text = input()
first = "AB"
second = "BA"
flag = False
while True:
if text.find(first) != -1:
text = text[text.find(first)+2:]
elif text.find(second) != -1:
text = text[text.find(second)+2:]
else:
break
if len(text) == 0:
flag = True
break
if flag == True:
... |
routes = {
'{"command": "devs"}' : {"STATUS":[{"STATUS":"S","When":1553528607,"Code":9,"Msg":"3 GPU(s)","Description":"sgminer 5.6.2-b"}],"DEVS":[{"ASC":0,"Name":"BKLU","ID":0,"Enabled":"Y","Status":"Alive","Temperature":43.00,"MHS av":14131.4720,"MHS 5s":14130.6009,"Accepted":11788,"Rejected":9,"Hardware Errors":0,"... |
TAG_ALBUM = "album"
TAG_ALBUM_ARTIST = "album_artist"
TAG_ARTIST = "artist"
TAG_DURATION = "duration"
TAG_GENRE = "genre"
TAG_TITLE = "title"
TAG_TRACK = "track"
TAG_YEAR = "year"
TAGS = frozenset([
TAG_ALBUM,
TAG_ALBUM_ARTIST,
TAG_ARTIST,
TAG_DURATION,
TAG_GENRE,
TAG_TITLE,
TAG_TRACK,
... |
class Solution:
def sortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]:
cnt = 0
groups = collections.defaultdict(list)
for i, g in enumerate(group):
if g == -1:
group[i] = cnt + m
cnt += 1
group... |
def calc_eccentricity(dist_list):
"""Calculate and return eccentricity from list of radii."""
apoapsis = max(dist_list)
periapsis = min(dist_list)
eccentricity = (apoapsis - periapsis) / (apoapsis + periapsis)
return eccentricity
|
description = 'NICOS demo startup setup'
group = 'lowlevel'
# startupcode = '''
# printinfo("============================================================")
# printinfo("Welcome to the NICOS demo.")
# printinfo("Run one of the following commands to set up either a triple-axis")
# printinfo("or a SANS demo setup:")
# pr... |
#!/usr/bin/env python
class Life:
def __init__(self, name='unknown'):
print('Hello ' + name)
self.name = name
def live(self):
print(self.name)
def __del__(self):
print('Goodbye ' + self.name)
brian = Life('Brian')
brian.live()
brian = 'leretta'
|
# Articles and their urls.
topics_links = {
"документи для в'їзду в ірландію":"""
Документі необхідні для в’їзду до Ірландії\:
На даний час Ірландія приймає:
1\. Міжнародний паспорт, з біометрією або без неї, прострочений в тому числі\.
2\. Внутрішній паспорт України\. В тому числі прострочений\.
3\. Свідоцтво про на... |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'lzma_sdk_sources': [
'7z.h',
'7zAlloc.c',
'7zAlloc.h',
'7zArcIn.c',
'7zBuf.c',
'7zBuf.h',
... |
config = {
'sampling_rate': 22050,
'hop_size': 256,
'model_type': 'hifigan_generator',
'hifigan_generator_params': {
'out_channels': 1,
'kernel_size': 7,
'filters': 128,
'use_bias': True,
'upsample_scales': [8, 8, 2, 2],
'stacks': 3,
'stack_kernel_... |
def countdown(num):
print(num)
if num == 0:
return
else:
countdown(num - 1)
if __name__ == "__main__":
countdown(10)
|
class GridNode(object):
"""
A structure that represents a particular location in (U,V) from a grid.
GridNode(uIndex: int,vIndex: int)
"""
@staticmethod
def __new__(self,uIndex,vIndex):
"""
__new__[GridNode]() -> GridNode
__new__(cls: type,uIndex: int,vIndex: int)
"""
pass
UIn... |
"""
You are given an m x n matrix M initialized with all 0's and an array of operations ops, where ops[i] = [ai, bi] means M[x][y] should be incremented by one for all 0 <= x < ai and 0 <= y < bi.
Count and return the number of maximum integers in the matrix after performing all the operations.
Example 1:
Input: m... |
class LocationPathFormatError(Exception):
pass
class LocationStepFormatError(Exception):
pass
class NodenameFormatError(Exception):
pass
class PredicateFormatError(Exception):
pass
class PredicatesFormatError(Exception):
pass
|
class Estado:
nome_estado: str
sigla: str
pais: str
qt_estado: int
def __init__(self, nome_estado, sigla):
self.nome_estado = nome_estado
self.sigla = sigla
self.pais = 'Brasil'
self.qtd_estado = 0 # é a soma dos qt_casos da classe Cidade
def __str__(self):
... |
burst_time=[]
print("Enter the number of process: ")
n=int(input())
print("Enter the burst time of the processes: \n")
burst_time=list(map(int, input().split()))
waiting_time=[]
avg_waiting_time=0
turnaround_time=[]
avg_turnaround_time=0
waiting_time.insert(0,0)
turnaround_time.insert(0,burst_time[0])
for i ... |
"""
link: https://leetcode.com/problems/wildcard-matching/
problem: 问类正则表达式p是否能完全匹配s,其中p的匹配规则为 * -> 0+ any chars && ? -> 1 any char
solution: DP,定义 dp[i][j] 为s[:i]是否匹配p[:j],注意是dp[0][0]代表空字符串和空正则允许匹配
初始化dp[0][k]后分情况讨论即可(注意实际代码为了方便处理,将s,p均右移了一位):
dp[i][j] = (p[j] == '*' && dp[i][j-1]) # '*' ... |
lista = [
[1,2,3,4,5,6,7,9,8,10],
[1,3,3,4,5,6,7,8,9,10],
[1,7,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,2,3,4,5,6,7,8,9,10],
[1,8,3,4,5,6,7,8,9,10],
]
def verificar(lista):
ls = lista
for index_lista in lista:
for aux in index_lista:
... |
#Leia duas notas e diga a média: abaixo de 5 reprovado; 5 a 6.9 recuperação; 7 ou mais aprovado
n1= int(input('Digite a sua primeira nota: '))
n2= int(input('Digite a sua segunda nota: '))
media = (n1+n2)/2
if media < 5:
print('Você foi reprovado por ter média igual a {} !!'.format(media))
elif 5<= media < 7:
... |
# Problem0019 - Counting Sundays
#
# https: // github.com/agileshaw/Project-Euler
def totalDays(month, year):
month_list = [4, 6, 9, 11]
if month == 2:
if year % 400 == 0 or ((year % 4 == 0) and year % 100 != 0):
return 29
else:
return 28
elif month in month_list:
... |
def get_integer_input(message):
"""
This function will display the message to the user
and request that they input an integer.
If the user enters something that is not a number
then the input will be rejected
and an error message will be displayed.
The user will then be asked to try again.... |
N = int(input())
a = list(map(int, input().split()))
# 1開始にする
A = [0]+a
# いい入れ方(1はボールが入っている)
B = [0]*(N+1)
# ボールが入っている箱の番号
ans = []
# Nから1までループ
for i in range(N, 0, -1):
# iの1つ目の倍数からNまでの倍数の箱にボールが入っている箱の個数を求める
tmp = 0
for j in range(i*2, N+1, i):
tmp += B[j]
# 合計%2がA[i]と不一致ならボールを入れる
if tmp... |
def lower_bound(arr, value, first, last):
"""Find the lower bound of the value in the array
lower bound: the first element in arr that is larger than or equal
to value
Args:
arr : input array
value : target value
first : starting point of the search, inclusi... |
class CraftParser:
@staticmethod
def calculate_mass(craft_filepath: str, masses: dict) -> int:
parts = []
craft_lines = []
with open(craft_filepath) as craft:
craft_lines = [line.strip() for line in craft.readlines()]
for index, line in enumerate(craft_lines):
if "part = " in line:
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 4 23:24:41 2019
@author: rocco
"""
#function to convert datetime to seconds
def datetime2seconds(date_time):
return time.mktime(date_time.timetuple())
#function to convert datetime to seconds
def dateinterv2date(interval):
return interval.left.to_pyd... |
"""
Author: Shengjia Yan
Date: 2018-05-11 Friday
Email: i@yanshengjia.com
Time Complexity: O(n)
Space Complexity: O(n)
"""
class Solution:
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
words = s.split(' ')
res = []
for word in words:
... |
"""You are given an integer n, the number of teams in a tournament that has strange rules:
If the current number of teams is even, each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round.
If the current number of teams is odd, one team randomly advances i... |
# flake8: noqa
responses = {
"success": {
"status_code": 200,
"content": {
"resourceType":"Bundle",
"id":"389a548b-9c85-4491-9795-9306a957030b",
"meta":{
"lastUpdated":"2019-12-18T13:40:02.792-05:00"
},
"type":"searchset",
... |
# Problem: https://leetcode.com/problems/range-sum-query-2d-immutable/submissions/
#["NumMatrix", "sumRegion", "sumRegion", "sumRegion"]
null_matrix= [[3, 0, 1, 4, 2],
[5, 6, 3, 2, 1],
[1, 2, 0, 1, 5],
[4, 1, 0, 1, 7],
[1, 0, 3, 0, 5]]
row1 = 1
col1 = 2
row2 = ... |
def log_info(func):
def wrapper():
print("Wywołuję funkcję...")
func()
print("Już po wszystkim :)")
return wrapper
def say_hello():
print("Hello World!")
def run_example():
say_hello_with_log_info = log_info(say_hello)
say_hello_with_log_info()
if __name__ == '__main_... |
__version__ = "3.0.0-beta"
VERSION = __version__
DOMAIN = "krisinfo"
BASE_URL = "https://api.krisinformation.se/v3/"
NEWS_PARAMETER = "news?format=json"
VMAS_PARAMETER = "vmas?format=json"
LANGUAGE_PARAMETER = "&language="
USER_AGENT = "homeassistant_krisinfo/" + VERSION
|
# Road of Regrets 2 (270020200) => Resting Spot of Regret
# The One Who Walks Down the Road of Regrets2
if sm.hasQuestCompleted(3509):
sm.warp(270020210, 3)
else:
sm.chat("Those who do not have the Goddess' permission may not move against the flow of time, and will be sent back to their previous location.")
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created by tianhao.wang at 9/6/18
""" |
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 2:
return n
pre1 = 2
pre2 = 1
cur = 0
while(n>2):
cur = pre1 + pre2
pre2 = pre1
pre1 = cur
n ... |
"""Constants for the AlarmDecoder component."""
CONF_ALT_NIGHT_MODE = "alt_night_mode"
CONF_AUTO_BYPASS = "auto_bypass"
CONF_CODE_ARM_REQUIRED = "code_arm_required"
CONF_DEVICE_BAUD = "device_baudrate"
CONF_DEVICE_PATH = "device_path"
CONF_RELAY_ADDR = "zone_relayaddr"
CONF_RELAY_CHAN = "zone_relaychan"
CONF_ZONE_LOOP... |
# Collaborators (including web sites where you got help: (enter none if you didn't need help)
#
# Write a program that asks for the user's name and another piece of information.Then prints a response using both of the inputs.
x = input("What is your name?")
y = input("How old are you?")
print("Hello " + x + ", you ... |
_base_ = './upernet_vit-b16_mln_512x512_160k_ade20k.py'
model = dict(
pretrained='pretrain/deit_base_patch16_224-b5f2ef4d.pth',
backbone=dict(drop_path_rate=0.1),
)
|
#!/usr/bin/env python3
"""Error exceptions."""
class InputError(Exception):
"""Raised on invalid user input."""
|
#coding=utf-8
'''
Created on 2015-10-10
@author: Devuser
'''
class Tag(object):
def __init__(self,tagid,name,color):
self.tagid=tagid
self.tagname=name
self.tagcolor=color
|
def log(str):
ENABLED = False # Set False to disable loggin
if ENABLED:
print(str) |
# add 6 _
name = 'Mark'
align_right = f'{name:_>10}'
print(align_right)
# '______Mark' |
def main(n):
ret = 1
while 1:
if n == 1:
break
n = (n // 2, 3 * n + 1)[n & 1]
ret += 1
return ret
if __name__ == '__main__':
print(main(int(input())))
|
t = '########### ###########\n########## ##########\n######### #########\n######## ########\n####### #######\n###### ######\n##### #####\n#### ####\n### ###\n## ##\n# #\n \n'
d... |
"""
Copyright (C) 2015, MuChu Hsu
Contributed by Muchu Hsu (muchu1983@gmail.com)
This file is part of BSD license
<https://opensource.org/licenses/BSD-3-Clause>
""" |
#
# PySNMP MIB module CISCO-EPM-NOTIFICATION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-EPM-NOTIFICATION-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:40:04 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... |
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
# Project Euler - Problem 9
# Aidan O'Connor_G00364756_01/03/2018
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a^2 + b^2 = c^2
# For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
d... |
#
# Copyright (C) 2019 Databricks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
'''https: // practice.geeksforgeeks.org/problems/permutations-of-a-given-string2041/1
Permutations of a given string
Basic Accuracy: 49.85 % Submissions: 31222 Points: 1
Given a string S. The task is to print all permutations of a given string.
Example 1:
Input: ABC
Output:
ABC ACB BAC BCA CAB CBA
Explanation:
Given... |
class TreeNode:
"""Definition for a binary tree node."""
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def is_balanced(self, root: TreeNode) -> bool:
return self.depth(root) != -1
def depth(self, node: TreeNode) -> int:
... |
s = input()
y = s[0]
w = s[2]
if int(y) > int(w):
p = 7 - int(y)
else:
p = 7 - int(w)
if p == 1:
print('1/6')
if p == 2:
print('1/3')
if p == 3:
print('1/2')
if p == 4:
print('2/3')
if p == 5:
print('5/6')
if p == 6:
print('1/1')
|
# -*- coding: utf-8 -*-
"""
Jokes from stackoverflow - provided under CC BY-SA 3.0
http://stackoverflow.com/questions/234075/what-is-your-best-programmer-joke?page=4&tab=votes#tab-top
"""
neutral = [
"Trionfalmente, Beth ha rimosso Python 2.7 dal server nel 2020.'Finalmente!' ha detto con gioia, solo per vedere l... |
'''Question 1: Given a two integer numbers return their product
and if the product is greater than 1000, then return their sum'''
num1=int(input("Enter the first no:"))
num2=int(input("Enter the second no:"))
product=num1*num2
if(product>1000):
print("sum is:",num1+num2)
else:
print("Invalid n... |
def collection_json():
"""Returns JSON skeleton for Postman schema."""
collection_json = {
"info": {
"name": "Test_collection",
"description": "Generic text used for documentation.",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
... |
"""Constants for the Alexa integration."""
DOMAIN = 'alexa'
# Flash briefing constants
CONF_UID = 'uid'
CONF_TITLE = 'title'
CONF_AUDIO = 'audio'
CONF_TEXT = 'text'
CONF_DISPLAY_URL = 'display_url'
CONF_FILTER = 'filter'
CONF_ENTITY_CONFIG = 'entity_config'
CONF_ENDPOINT = 'endpoint'
CONF_CLIENT_ID = 'client_id'
CONF... |
'''
Author: Aditya Mangal
Date: 20 september,2020
Purpose: python practise problem
'''
def input_matrixes(m, n):
output = []
for i in range(m):
row = []
for j in range(n):
user_matrixes = int(input(f'Enter number on [{i}][{j}]\n'))
row.append(user_matrixes)
... |
d=int(input())
m=int(input())
n=int(input())
x=[int(z) for z in input().split(" ")]
dist_travelled=0
i=0
refuel=0
while(dist_travelled<d and i<n-1):
if(dist_travelled+m>=d):
break
if(dist_travelled+m>=x[i] and dist_travelled+m<x[i+1]):
dist_travelled=x[i]
refuel+=1
elif(dist_travelle... |
def palin(n):
if n == n[::-1]:
return True
def main():
n = str(input('insira a palavra: '))
n = n.upper()
palin(n)
if palin(n) == True:
print('É palindromo')
else:
print('Não é palindromo')
main()
|
# Copyright (c) 2018 PaddlePaddle 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 app... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.