content
stringlengths
7
1.05M
data = open(r"C:\Users\gifte\Desktop\game\data_number.txt",'r') x = data.readlines() string="" for line in x: for _ in line: if _ =="0": string+="a" elif _ =="1": string+="s" elif _ =="2": string+="d" elif _ =="3": string+="...
# # PySNMP MIB module ADIC-INTELLIGENT-STORAGE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADIC-INTELLIGENT-STORAGE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 16:58:16 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python vers...
l = float(input('Largura: ')) a = float(input('Altura: ')) mt = l * a t = mt / 2 print('A parede possui {}M², e será necessário {} litros de tinta para pintar.'.format(mt, t))
def get_cleaned_url(url, api_host, api_version): if any(prefix in url for prefix in ["http://", "https://"]): return url cleaned_url = api_host.rstrip("/") if url.startswith("/{}".format(api_version)): cleaned_url += url else: cleaned_url += "/{}{}".format(api_version, url) ...
# 1 h = float(input("请输入身高")) t = float(input("请输入体重")) BMI = t / (h * h) if BMI < 18.5: print("你这么手,可以肆无忌惮的大吃大喝啦") elif 18.5 <= BMI < 25: print("兄弟!你离模特就差八块腹肌了") elif 25 <=BMI < 30: print("控制自己哦!脂肪有点多了") elif BMI >= 30: print("不能再吃了!跑几圈去吧,你也可以是男神") #2 s = int(input("请输入出生年份")) j = int(input("请输入今年年份")) c = 0 for ...
def generate_full_name(firstname, lastname): space = ' ' fullname = firstname + space + lastname return fullname
balance = 1000.00 name = "Chuck Black" account_no = "01123581321" print("name:", name, " account:", account_no, " original balance:", "$" + str(balance)) charge01 = 5.99 charge02 = 12.45 charge03 = 28.05 balance = balance - charge01 print("name:", name, " account:", account_no, " charge:", cha...
class Article: url = '' title = '' summary = '' date = '' keywords = '' class Author: url = '' name = '' major = '' sum_publish = '' sum_download = '' class Organization: url = '' name = '' website = '' used_name = '' region = '' class Source: url = ...
# ['alexnet', 'deeplabv3_resnet101', 'deeplabv3_resnet50', 'densenet121', 'densenet161', 'densenet169', 'densenet201', # 'fcn_resnet101', 'fcn_resnet50', 'googlenet', 'inception_v3', 'mnasnet0_5', 'mnasnet0_75', 'mnasnet1_0', 'mnasnet1_3', # 'mobilenet_v2', 'resnet101', 'resnet152', 'resnet18', 'resnet34', 'resnet50'...
# # PySNMP MIB module SYMMCOMMONNETWORK (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/neermitt/Dev/kusanagi/mibs.snmplabs.com/asn1/SYMMCOMMONNETWORK # Produced by pysmi-0.3.4 at Tue Jul 30 11:34:11 2019 # On host NEERMITT-M-J0NV platform Darwin version 18.6.0 by user neermitt # Using Python version 3.7.4 (de...
# AutoTransform # Large scale, component based code modification library # # Licensed under the MIT License <http://opensource.org/licenses/MIT> # SPDX-License-Identifier: MIT # Copyright (c) 2022-present Nathan Rockenbach <http://github.com/nathro> # @black_format """Batchers take filtered Items and separate them in...
class MergeRequest: class MergeType(str): pass MergeType.DEV = MergeType('dev') MergeType.PROD = MergeType('prod') MergeType.MAINTENANCE = MergeType('maintenance') def __init__(self, merge_type: MergeType, source_branch: str, target_branch: str): self.merge_type = merge_type ...
def calc( X=1, Y=2 ): try: return X % Y except TypeError: return 5 def process( A=0, B=0 ): V, Z = (0, 0) try: Z = calc( int(A), B ) except ValueError: V += 16 except ZeroDivisionError: V += 8 except: V += 4 else: V += 2 finally...
# Settings File to declare constants TRAINING__DATA_PATH = '../training.csv' TESTING__DATA_PATH = '../test.csv' SAVE_PREDICTION_PATH = '../predictions.csv' SAVE_MODEL_PATH = '../model.pkl' CELERY_SETTINGS = 'celeryconfig'
""" Auto DM Jeremy L Thompson This file provides dictionaries for random modules """ # ------------------------------------------------------------------------------ # Dictionary of Monsters # ------------------------------------------------------------------------------ ALL_MONSTERS = [ # Monster Manual...
class ReflectionException(Exception): pass class SignatureException(ReflectionException): pass class MissingArguments(SignatureException): pass class UnknownArguments(SignatureException): pass class InvalidKeywordArgument(ReflectionException): pass
n = s = quant = 0 while True: n = int(input('Digite um número : ')) if n == 999: break s += n quant += 1 print(f'Você digitou {quant} e a soma entre eles é {s}') s = quant = 0 while True: n = int(input('Digite um número e 999 para parar : ')) if n == 999: break s += n ...
class Solution: def generateParenthesis(self, n: int) -> [str]: res = [] def dfs(i, j, tmp): if not (i or j): res.append(tmp) return if i: dfs(i - 1, j, tmp + '(') if j > i: dfs(i, j - 1, tmp + ')') ...
x = 3 y = 4 def Double(x): return 2 * x def Product(x, y): return x * y def SayHi(): print("Hello World!!!")
def oddsum(): n= int(input("Enter the number of terms:")) sum=0 for i in range (1, 2*n+1, 2): sum += i print("The sum of first", n, "odd terms is:", sum) def evensum(): n= int(input("Enter the number of terms:")) sum=0 for i in range (0, 2*n+1, 2): sum += i ...
n = int(input()) # Opt1: Without map scores_str = input().split() scores = [] for score in scores_str: scores.append(int(score)) # Opt2: With map # map is a function that takes another function and a collection # e.g, list and applies function to all items in collection # scores = map(int, input().split()) # By ...
h, w = map(int, input().split()) grid = [list(input()) for _ in range(h)] for i in range(h): for j in range(w): if grid[i][j] == '#': if i - 1 >= 0 and grid[i - 1][j] == '#': continue if i + 1 <= h - 1 and grid[i + 1][j] == '#': continue if...
def is_a_valid_message(message): index=0 while index<len(message): index2=next((i for i,j in enumerate(message[index:]) if not j.isdigit()), 0)+index if index==index2: return False index3=next((i for i,j in enumerate(message[index2:]) if j.isdigit()), len(message)-index2)+ind...
class Celula(): def __init__(self, conteudo): self.conteudo = conteudo self.proximo = None self.anterior = None class Lista_duplamente_ligada(): def __init__(self): self.__inicio = None self.__fim = None self.__quantidade: int = 0 @property def inicio(...
def cidade_pais(cidade: str, pais: str) -> str: """ -> Devolve o nome da cidade e do seu país formatados de forma elegante. :param cidade: O nome da cidade. :param pais: O nome do país. :return: Retorna a string -> 'Cidade, País' """ return f'{cidade}, {pais}'.title() cidade_pais_1 = c...
class Token: def __init__(self, token, value=None): self.token = token self.value = value def __str__(self): return "{}: {}".format(self.token, self.value) def __repr__(self): return "{}({}, value={})".format(self.__class__.__name__, self.token, self.value) CONCATENATE = ...
def test1(): """A multi-line docstring. """ def test2(): """ A multi-line docstring. """ def test2(): """ A single-line docstring.""" """ A multi-line docstring. """
#week 4 chapter 8 - assignment 8.4 #8.4 Open the file romeo.txt and read it line by line. For each line, # split the line into a list of words using the split() method. # The program should build a list of words. For each word on each # line check to see if the word is already in the list and if not # append it to...
class APIException(Exception): """Exception raised when there is an API error.""" default_message = "A server error occurred" def __init__(self, message=None): self.message = message or self.default_message def __str__(self): return str(self.message) class PermissionDenied(APIExcept...
# -*- coding: utf-8 -*- def put_color(string, color): colors = { "red": "31", "green": "32", "yellow": "33", "blue": "34", "pink": "35", "cyan": "36", "white": "37", } return "\033[40;1;%s;40m%s\033[0m" % (colors[color], string)
class Trie: WORD_MARK = '*' ANY_CHAR_MARK = '.' def __init__(self): self.trie = {} def insert(self, word: str) -> None: trie = self.trie for ch in word: trie = trie.setdefault(ch, {}) trie[self.WORD_MARK] = self.WORD_MARK def search_regex(self, regex: ...
#Condições Aninhadas nome = str(input('Qual é o seu nome? ')) if nome == 'Diego': print('Que nome bonito!') elif nome == 'Pedro' or nome == 'João' or nome == 'Maria' or nome == 'Ana': print('Sue nome é bem popular no Brasil.') elif nome in 'Juliana Camila Regina Tatiane': print('Belo nome feminino') else:...
class Solution: def mincostTickets(self, days: List[int], costs: List[int]) -> int: dp=[float("inf") for i in range(max(days)+1)] dp[0]=0 prices={1:costs[0],7:costs[1],30:costs[2]} for i in range(1,len(dp)): if i not in days: dp[i]=dp[i-1] ...
# https://www.acmicpc.net/problem/9019 def bfs(A, B): queue = __import__('collections').deque() queue.append((A, list())) visited = [False for _ in range(10000)] visited[A] = True while queue: cur, move = queue.popleft() nxt = (cur * 2) % 10000 if not visited[nxt]: ...
# Faça um programa que tenha uma função chamada maior(), que receba vários # parâmetros com valores inteiros. # Seu programa tem que analisar todos os valores e dizer qual deles é o maior. def maior(* num): tam = len(num) print('Analisando os valores passados...') for n in num: print(f'{n} ...
# Values for type component of FCGIHeader FCGI_BEGIN_REQUEST = 1 FCGI_ABORT_REQUEST = 2 FCGI_END_REQUEST = 3 FCGI_PARAMS = 4 FCGI_STDIN = 5 FCGI_STDOUT = 6 FCGI_STDERR = 7 FCGI_DATA = 8 FCGI_GET_VALUES = 9 FCGI_GET_VALUES_RESULT = 10 FCGI_UNKNOWN_TYPE = 11 # Mask for flags component of FCGIBeginRequestBody FCGI_KEEP_C...
#---------------------------------------------------------------------------------------------------------- # # AUTOMATICALLY GENERATED FILE TO BE USED BY W_HOTBOX # # NAME: Output: Alpha # COLOR: #699e69 # TEXTCOLOR: #ffffff # #-------------------------------------------------------------------------------------------...
"""Document templates configuration file.""" reports = {} # Default if no template reports['NONE'] = (''' ''') # DSCE - Social enquiry reports['DSCE'] = (''' PERSONAL DETAILS Name of Child: %(name)s Age: %(age)s Nationality: %(nationality)s Religion: %(religion)s Physical/mental fitness: %(pad...
""" 练习:创建手机类 数据:品牌、价格、颜色 行为:通话 实例化两个对象并调用其函数 """ # 类命名规范:所有单词首字母大写,不要下划线隔开 class MobilePhone: def __init__(self, brand, price=5000, color="白色"): self.brand = brand self.price = price self.color = color def call(self): print(self.brand + "通话") huawe...
class Solution: def maxConsecutive(self, bottom: int, top: int, special: List[int]) -> int: special.sort() max_count = max(special[0] - bottom, top - special[-1]) for i in range(len(special) - 1): max_count = max(max_count, special[i+1] - special[i] - 1) return max_count
r = int(input("Enter range: ")) print(f"\nThe first {r} Fibonacci numbers are:\n") n1 = n2 =1 print(n1) print(n2) for i in range(r-2): n3 = n1+n2 print(n3) n1 = n2 n2 = n3
# Base Parameters assets = asset_list('FX') # Trading Parameters horizon = 'H1' pair = 0 # Mass Imports my_data = mass_import(pair, horizon) # Indicator Parameters lookback = 60 def ma(Data, lookback, close, where): Data = adder(Data, 1) for i in range(len(Data)): ...
# # exceptions.py # # (c) 2017 by Andreas Kraft # License: BSD 3-Clause License. See the LICENSE file for further details. # # This module defines the exceptions used in various modules. # """ This sub-module defines the exceptions used in the onem2mlib module. """ class OneM2MLibError(Exception): """ Base c...
def more(message): answer = input(message) while not (answer=="y" or answer=="n"): answer = input(message) return answer=="y"
def get_input() -> list: with open(f"{__file__.rstrip('code.py')}input.txt") as f: return [l.strip().replace(" = ", " ").replace("mem[", "").replace("]", "") for l in f.readlines()] def parse_input(lines: list) -> list: instructions = [] for line in lines: if line.startswith('mask'): ...
# python2 (((((((( # noinspection PyUnusedLocal # friend_name = unicode string def hello(friend_name): return u"Hello, " + friend_name + u"!"
def test_time_traveling(w3): current_block_time = w3.eth.get_block("pending")['timestamp'] time_travel_to = current_block_time + 12345 w3.testing.timeTravel(time_travel_to) latest_block_time = w3.eth.get_block("pending")['timestamp'] assert latest_block_time >= time_travel_to
#Faça um programa que leia o nome completo de uma pessoas, mostrando em seguida o primeiro e o último nome separadamente. nameComplete = input('Olá, por favor me fala o seu nome completo: ').strip().title() nameDivided = nameComplete.split() lenghtList = len(nameDivided) print('Seu nome completo é: {}'.format(nameCompl...
BASE_RATE = 59.94 # FEE RATES PREV_POLICY_CANCELLED_FEE_AMT = 0.50 STATE_FEE_AMT = 0.25 MILES_0_100_FEE_AMT = 0.50 MILES_101_200_FEE_AMT = 0.40 MILES_201_500_FEE_AMT = 0.35 # DISCOUNT RATES NO_PREV_POLICY_CANCELLED_DIS_AMT = 0.10 PROPERTY_OWNER_DIS_AMT = 0.20 STATES_WITH_VOLCANOES = [ 'AK', 'AZ', 'CA', ...
class Solution: def kthFactor(self, n: int, k: int) -> int: factors = [i for i in range(1, n + 1) if n % i == 0] print(factors) if k <= len(factors): return factors[k - 1] return -1
""" Lecture 4 """ #my_tuple = 'a','b','c','d','e' #print(my_tuple) #print(my_tuple[1]) # using index numbers to find the letters we want #print(my_tuple[0:3]) # using slicing to find multiple letters at once #print(my_tuple[:]) #my_2nd_tuple = ('a','b','c','d','e') #as long as you have he commas, it is a tuple. #pri...
# -*- coding: utf-8 -*- """ neutrino_api This file was automatically generated for NeutrinoAPI by APIMATIC v2.0 ( https://apimatic.io ). """ class UserAgentInfoResponse(object): """Implementation of the 'User Agent Info Response' model. TODO: type model description here. Attrib...
prefix = "http://watch.peoplepower21.org" member_index = prefix + "/New/search.php" member_report = prefix +"/New/cm_info.php?member_seq=%s" bill_index = prefix + "/New/monitor_voteresult.php" bill_index_per_page = prefix + "/New/monitor_voteresult.php?page=%d" bill_vote = prefix + "/New/c_monitor_voteresult_detail.php...
class Timeframe: def __init__(self, pd_start_date, pd_end_date, pd_interval): if pd_end_date < pd_start_date: raise ValueError('Timeframe: end date is smaller then start date') if pd_interval.value <= 0: raise ValueError('Timeframe: timedelta needs to be positive') s...
# Python program for implementation of Level Order Traversal # Structure of a node class Node: def __init__(self ,key): self.data = key self.left = None self.right = None # print level order traversal def printLevelOrder(root): if root is None: return # create an empty ...
# Another alternative # • Sometimes a list comprehension or generator expression is better than using map # • Especially when the function is not already defined # • One benefit of using a list comprehension is that we don’t have to convert the result to a list to print it numbers = range(10) even_numbers = [x * 2 for...
"""Base configuration""" DEBUG = False TESTING = False SECRET_KEY = b'' EXCHANGE_SECRET_KEY = b'' SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_DATABASE_URI = '' """flask_mail configuration""" MAIL_SERVER = '' MAIL_PORT = 465 MAIL_USE_SSL = True MAIL_USE_TLS = False MAIL_USERNAME = '' MAIL_PASSWORD = '' # """Exch...
""" PlotPlayer Helpers Subpackage contains various generic miscellaneous modules and methods to ease development. Public Modules: * file_helper - Contains methods for interacting with the local file system * ui_helper - Contains methods for providing generic UI elements & dialogs """
# -*- coding: utf-8 -*- """Top-level package for my_videolibrary.""" __author__ = """Maarten Fabré""" __email__ = 'maartenfabre@gmail.com' __version__ = '0.1.0'
#El método "lower()" genera una copia de una cadena, # reemplaza todas las letras mayúsculas con sus equivalentes en minúsculas, # y devuelve la cadena como resultado. Nuevamente, la cadena original permanece intacta. print("SiGmA=60".lower()) print("josuerojasq".lower()) print("Carlita & Luciana".lower()) print("".low...
def get_formated_name (first_name, last_name): full_name = first_name + " "+last_name return full_name.title() musician = get_formated_name('jimi', 'hendrix') print(musician)
class GenericPlugin(object): ID = None NAME = None DEPENDENCIES = [] def __init__(self, app, view): self._app = app self._view = view @classmethod def id(cls): return cls.ID @classmethod def name(cls): return cls.NAME @classmethod def dependencies(cls): return cls.DEPENDENCI...
def isValidChessBoard(board): """Validate counts and location of pieces on board""" # Define pieces and colors pieces = ['king', 'queen', 'rook', 'knight', 'bishop', 'pawn'] colors = ['b', 'w'] # Set of all chess pieces all_pieces = set(color + piece for piece in pieces for color in colors) ...
def cache(func, **kwargs): attribute = '_{}'.format(func.__name__) @property def decorator(self): if not hasattr(self, attribute): setattr(self, attribute, func(self)) return getattr(self, attribute) return decorator
# Third edit: done at github.com. # First edit. # Ask the user for a word. Add .lower() to the input return so it's easier to compare the letters. This method removes case sensitivity. word = input("Enter a word: ").lower() # Ask the user for a letter. Add .lower() to the input return so it's easier to compare the let...
#leia o nome e três provas. No final informar o nome a sua média (aritmética). aluno = {'nome':str, 'notas': [float,float,float], 'media': 0} str(input("Qual o nome do aluno? ")) for i in range(len(aluno['notas'])): aluno['notas'][i] = float(input("Insira a nota %s: " % str(i+1))) aluno['media'] += aluno['notas'][i] ...
_base_ = [ '../_base_/default.py', '../_base_/logs/tensorboard_logger.py', '../_base_/optimizers/sgd.py', '../_base_/runners/epoch_runner_cancel.py', '../_base_/schedules/plateau.py', ] optimizer = dict( lr=0.001, momentum=0.9, weight_decay=0.0001, ) lr_config = dict(min_lr=1e-06) eva...
# 《複製大檔案 Copy Large File》程式設定檔案 # 此工具與 config.json 性質不同! # [Linux] 偵測 rsync 的可能位置 rsyncPossiblePath = ['/usr/bin/rsync', '/bin/rsync', '/usr/sbin/rsync', '/sbin/rsync'] # [Windows] [Linux] 檔案與目錄複製指令 # {} = 來源位置 + 目標位置 # e.g recopy_exe.py recopy2.py ## Linux 的檔案複製變數 cp_linux = 'rsync -h --progress {}' ## Windows 的資料夾複...
def reverseMapping(mapping): result = {} for i, segmentString in enumerate(mapping): result["".join(sorted(segmentString))]=i #print(result) return result def decode(p1): digitString = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] sixSegment = [] fiveSegment = [] for digit in p1: dg = ...
# @author: Michael Vorotyntsev # @email: linkofwise@gmail.com # @github: unaxfromsibiria INCORECT_PASSWORD = 'Пароль не подходит!' AUTH_OK = 'Вы успешно вошли в систему!' NEED_RELOGIN = 'Нужно ввести пароль заново!' INCORECT_CARD_DATA = 'Некорректные данные!' CARD_USED = 'Карта с номером {} уже выдана! Возьмите другую...
__version_info__ = (1, 0, 0, '') # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join(str(i) for i in __version_info__[:-1]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],)) # context processor to add version to the template environmen...
# Copyright (c) Dietmar Wolz. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory. __version__ = '0.1.3' __all__ = [ 'rayretry', 'multiretry', ]
a = [] print(type(a)) #help(a) #print(dir(a)) #print(type(type(a)))
''' Write a Binary Search Tree(BST) class. The class should have a "value" property set to be an integer, as well as "left" and "right" properties, both of which should point to either the None(null) value or to another BST. A node is said to be a BST node if and only if it satisfies the BST property: its value is stri...
#! /usr/bin/env python2 # Helpers def download_file(url): print("Downloading %s" % url) local_filename = url.split('/')[-1] # NOTE the stream=True parameter r = requests.get(url, stream=True) with open(local_filename, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if ...
class Solution(object): def getSum(self, num1, num2): """ :type a: int :type b: int :rtype: int """ ans = 0 mask = 0x01 carry = 0 for i in xrange(0, 32): a = num1 & mask b = num2 & mask c = carry...
''' import datetime from django.contrib.auth.models import User from django.core.mail import send_mail from tasks.models import Task, Report from datetime import timedelta, datetime, timezone from celery.decorators import periodic_task from celery import Celery from config.celery_app import app @periodic_task(ru...
# Databricks notebook source NRJXFYCZXPAPWUSDVWBQT YVDWRTQLOHHPYZUHJGTDMDYEZPHURUPFXD GMJLOPGLOTLZANILIDMCJSONOTNIZDYVSV HBUSZUHKJSRCMJQSJKGFSQAYLKPJUVKGUY FMJLCEHCNOQLGHLULYDPRUZUKMTWRBTLRASSIVMJ VJGQUSEDKRWDPXYLJMEEAMLNVBGMBVKRIYPGRJCKYKZX BLTCKGNOICKASIVEPWO RUJYBXAOS WGKYLEKOZP EKBYFUATSAEHQVRGCOHWHQVRMTEPOYLWLMCV...
class RedisSet: def __init__(self, redis, key, converter, content=None): self.key_ = key self.redis_ = redis self.converter_ = converter if content: self.reset(content) def __len__(self): return self.redis_.scard(self.key_) def __call__(self): r...
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def pairwiseSwap(self): temp = self.head if temp is None: return while temp is not None and temp.next is not None: ...
# Copyright (c) 2013, Anders S. Christensen # 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 of conditions...
class ValidationResult(object): def __init__(self, valid, log, err): """ Constructor @type valid: Boolean @param valid: Path to file @type log: List[String] @param log: Processing log @type err: List[String] @param err:...
#27 # Time: O(n) # Space: O(1) # Given an array and a value, remove all instances # of that value in-place and return the new length. # Do not allocate extra space for another array, # you must do this by modifying the input array # in-place with O(1) extra memory. # The order of elements can be changed. # It d...
prompt123= ''' ************************ Rane Division Tools *************************** * Divide Range in bits or bytes * * Option.1 Divide Range in bits =1 * * Option.2 Divide Range in bytes =2 ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]: if not postorde...
class Solution: def baseNeg2(self, N: int) -> str: res=[] while N: # and operation res.append(N&1) N=-(N>>1) return "".join(map(str,res[::-1] or [0]))
# 비밀번호 # List를 활용한 풀이. # https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV14_DEKAJcCFAYD&categoryId=AV14_DEKAJcCFAYD&categoryType=CODE for tc in range(1,11): n, p=input().split() result=[p[0]] for i in range(1, len(p)): if len(result): if result[-1]==p[i...
class Solution: def sortByBits(self, arr: List[int]) -> List[int]: d = {} for i in arr: temp = [] t = 0 c = i while i>1: if i%2==0: temp.append(0) i/=2 else: te...
""" appends JSON wine records from given data, formats and sort'em, output is JSON file, contains summary information by built-in parameters """ winedata_full = [] avg_wine_price_by_origin = [] ratings_count = [] def string_comb(raw_str): form_str = ' '.join( raw_str[1:-1].split() ).replace( ...
__author__ = 'Michael Andrew michael@hazardmedia.co.nz' class ChevronModel(object): name = "" locked = False def __init__(self, name): self.name = name
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ n=int(input()) a=[0]*(n+1) for i,x in enumerate(map(int,input().split())): a[x]=i x=y=0 input() for u in map(int,input().split()): x+=a[u]+1 y+=n-a[u] print(x,y)
matriz = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0,], [0, 0, 0, 0]] maior_valor = 0 linha = 0 coluna = 0 for l in range(0, 4): for c in range(0, 4): matriz[l][c] = int(input(f'Digite o valor para [{l}, {c}]: ')) if matriz[l][c] > maior_valor: maior_valor = matriz[l][c] ...
# -*- coding: utf-8 -*- # author: Phan Minh Tâm # source has refer to java source of BURL method: http://web.informatik.uni-mannheim.de/AnyBURL/IJCAI/ijcai19.html file Atom.java class Atom(object): def __init__(self, left=None, relation=None, right=None, is_left_constant=True, is_right_constant=True): self.left...
""" GENERATED FILE - DO NOT EDIT (created via @build_stack_rules_proto//cmd/depsgen) """ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def _maybe(repo_rule, name, **kwargs): if name not in native.existing_rules(): repo_rule(name = name, **kwargs) def core_deps(): io_bazel_rules...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def shell_sort(arr): arr_size = len(arr) interval = arr_size // 2 while interval > 0: j = interval while j < arr_size: aux = arr[j] k = j while k >= interval and aux < arr[k-interval]: arr[k]...
""" Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area. class crcl_plot: def __init__(self): rdus=int(input("please enter your radius for the circle: ")) self.radius=rdus def find_area(self): print(f'the area of ...
def bubblesort_once(l): res = l[:] for i in range(len(res)): for j in range(i+1, len(res)): if res[j-1] > res[j]: res[j], res[j-1] = res[j-1], res[j] return res return []
# imgur key client_id = '3cb7dabd0f805d6' client_secret = '30a9fb858f64bf4acc1651988e2fbc62e4fedaed' album_id = 'LeVFO62' album_id_lucky = '2aAnwnt' access_token = '52945d677b3e985c5e82ba7d1fbd96f52648a1bb' refresh_token = '46d87ffac8daa7d8ecd34c85b9db4c64dbc2c582' # line bot key line_channel_access_token = 'ozBtsH1AX...
#!/usr/env/bin python # https://www.hackerrank.com/challenges/python-print # Python 2 N = int(raw_input()) # N = 3 print(reduce(lambda x, y: x + y, [str(n+1) for n in xrange(N)]))
columns_to_change = set() for col in telecom_data.select_dtypes(include=['float64']).columns: if((telecom_data[col].fillna(-9999) % 1 == 0).all()): columns_to_change.add(col) print(len(columns_to_change)) columns_to_change.union(set(telecom_data.select_dtypes(include=['int64']).columns)) print(len(column...