content
stringlengths
7
1.05M
#!/usr/bin/env python '''This is a wrapper around the Goldilocks libdecaf library. Currently only the ed448 code is wrapped. It is available in the submodule ed448. '''
def bubbleSort(a): for i in range(0,len(a)-1): for j in range(len(a)-1): if(a[j]>=a[j+1]): aux=a[j] a[j]=a[j+1] a[j+1]=aux
#!/usr/bin/python # -*- coding:utf-8 -*- IMAGE_CODE_REDIS_EXPIRE = 180 # 图片验证码redis保存的有效期,单位秒 IMAGE_CODE_YTX_EXPIRE = '5' # 图片验证码redis保存的有效期,单位秒 SMS_CODE_REDIS_EXPIRE = 300 # 短信验证码redis保存的有效期,单位秒 QINIU_URL_DOMAIN = "http://p6n6yrdpr.bkt.clouddn.com/" # 七牛的访问域名 LOGIN_ERROR_MAX_NUM = 5 # 登录的最大错误次数 LOGIN_ERROR...
class Room(): def __init__(self, name, description=None): self.__name = name self.__description = description self.__linked_rooms = {} self.__character = None @property def Name(self): return self.__name @Name.setter def Name(self, value): ...
def read_line(file_name): with open(file_name) as f: p_list = [] for line in f.readlines(): line_text = line.strip("\n") nums = list(line_text) p_list.append(nums) return p_list def move_east(arr): height, width = len(arr), len(arr[0]) moves = [] ...
""" Enunciado Faça um programa que dadas duas listas de mesmo tamanho, imprima o produto escalar entre elas. OBS: produto escalar é a soma do resultado da multiplicação entre o número na posição i da lista1 pelo número na posição i da lista2, com i variando de 0 ao tamanho da lista. """ lista1 = [1, 4, 5] lista2 = [2...
def extractCyborgTlCom(item): ''' Parser for 'cyborg-tl.com' ''' badwords = [ 'Penjelajahan', ] if any([bad in item['title'] for bad in badwords]): return None badwords = [ 'bleach: we do knot always love you', 'kochugunshikan boukensha ni naru', 'bahasa indonesia', 'a returner\'s mag...
BUTTON_PIN = 14 # pin for door switch BUZZER_PIN = 12 # pin for piezo buzzer ENABLE_LOG = True # logs the events to log/door.log LEGIT_OPEN_TIME = 20 # how many seconds until the alarm goes off CLOSING_SOUND = True # enable a confirmation sound for closing the door ONE_UP = True # play an achievement sound if the...
class DictDiffer(object): """ Calculate the difference between two dictionaries as: (1) items added (2) items removed (3) keys same in both but changed values (4) keys same in both and unchanged values Originally from: https://stackoverflow.com/questions/1165352/calculate-difference-in-keys-...
#criando dicionario dentro de uma lista brasil=[] estado1={'uf':'Rio de janeiro', 'Sigla': 'RJ'} estado2= {'Uf':'Sao paulo', 'Sigla':'SP'} brasil.append(estado1) brasil.append(estado2) print(brasil) print(brasil[1]) print(brasil[0]['uf']) print(brasil[1]['Sigla']) print('+='*30) for p in brasil: print(p)
class NombreVacioError(Exception): pass def __init__(self, mensaje, *args): super(NombreVacioError, self).__init__(mensaje, args) def imprmir_nombre(nombre): if nombre == "": raise NombreVacioError("El nombre esta vacio") print(nombre) try: 3 / 0 imprmir_nombre("") except No...
def test_basic_case(__): """ {count:text.test_cases} """ assert __.text.text_with_cases(count=0) == "в бане нет пользователей" assert __.text.text_with_cases(count=1) == "в бане 1 пользователь" assert __.text.text_with_cases(count=3) == "в бане 3 пользователя" assert __.text.text_with_cases...
#204 # Time: O(n) # Space: O(n) # Count the number of prime numbers less than a non-negative number, n # # Hint: The number n could be in the order of 100,000 to 5,000,000. class Sol(): def countPrimes(self,n): is_primes=[True]*n is_primes[0]=is_primes[1]=False for num in range(2,int(n...
""" This Package contains the implementation of different Desing Patterns. The *patterns* package is intended to be a collection of useful Design Patterns ready to be used in your projects. We intend to be extremly pythonic in the implementation and provide scalability and performance. Fell free to report any issue r...
d_lang = { "US English": "en-US", "GB English": "en-GB", "ES Spanish": "es-ES" }
self.description = 'download remote packages with -U with a URL filename' self.require_capability("gpg") self.require_capability("curl") url = self.add_simple_http_server({ # simple '/simple.pkg': 'simple', '/simple.pkg.sig': { 'headers': { 'Content-Disposition': 'attachment; filename="simple.sig-a...
''' @author: Pranshu Aggarwal @problem: https://hack.codingblocks.com/app/practice/1/1039/problem ''' """ TODO: OPTIMIZE THE CODE FOR TIME LIMIT EXCEEDED ERROR """ MAX_SIZE = 1000005 primes = [True if i%2==1 else False for i in range(MAX_SIZE)] primes[1], primes[2] = 0, 1 def sieve_of_eratosthenes(): f...
class Solution: def buildWall(self, height: int, width: int, bricks: List[int]) -> int: kMod = int(1e9) + 7 # valid rows in bitmask rows = [] self._buildRows(width, bricks, 0, rows) n = len(rows) # dp[i] := # of ways to build `h` height walls # with rows[i] in the bottom dp = [1] * n ...
"""This is an implementation of a zork-esque game using classes to implement major elements of the game. This is just a rough sketch, and there is a lot of space for improvement and experimentation. For example: * More dynamic/flexible room connection * Allow rooms to block doors until certain actions are taken or cri...
class Worker(object): def __init__(self, wid, address, port): self.wid = wid self.address = address self.port = port def __eq__(self, other): if isinstance(other, self.__class__): if self.wid == other.wid: if self.address == other.address: ...
class myclass(object): """This is a class that really says something""" def __init__(self, msg : str): self.msg = msg def saysomething(self): print(self.msg) m = myclass("hello") m.saysomething()
TORRENT_SAVE_PATH = r'torrents/' INSTALLED_SCRAPERS = [ 'scrapers.dmhy', ] ENABLE_AUTO_DOWNLOAD = True WEBAPI_PORT = 9010 WEBAPI_USERNAME = 'pythontest' WEBAPI_PASSWORD = 'helloworld'
# # @lc app=leetcode.cn id=1008 lang=python3 # # [1008] binary-tree-cameras # None # @lc code=end
_base_ = [ '../_base_/models/improved_ddpm/ddpm_64x64.py', '../_base_/datasets/imagenet_noaug_64.py', '../_base_/default_runtime.py' ] lr_config = None checkpoint_config = dict(interval=10000, by_epoch=False, max_keep_ckpts=20) custom_hooks = [ dict( type='MMGenVisualizationHook', output_di...
#creamos clase class Empleado: def __init__(self, nombre, sueldo): self.nombre = nombre self.sueldo = sueldo #enviamos a impresion def __str__(self): return "Nombre : "+ self.nombre + " "+ str(self.sueldo)
### # Adobe Camera Raw parameters used in Adobe Lightroom and their default values. ### LR_WHITE_BALANCE = { 'Temperature': 6200, 'Tint': 2, 'WhiteBalance': 'As Shot'} LR_TONE = { 'Blacks2012': 0, 'Contrast2012': 0, 'Exposure2012': 0, 'Highlights2012': 0, 'Shadows2012': 0, 'Whites201...
# # Copyright 2020 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: utf-8 -*- class ApiException(Exception): """ Base Kriegspiel API exception. """ http_code = None string_code = None def to_dict(self): return { 'code': self.string_code, } class NotAuthenticated(ApiException): http_code = 401 string_code = '...
#script # Task name: Update Calm service category with project name # Description: The propose of this task is to update the current service executing the # task with the project name as a category key in a specified category name. The objective # is to allow security policies to be applied based on Calm projects. ...
num=int(input("Enter a Number : ")) def pr(num): if num>1: for i in range(2,num): if num%i==0: return False; else: return False return True if pr(num): a=str(num)[::-1] a=int(a) if pr(a): print(num," and ",a," is a prime number which means ",nu...
"""https://open.kattis.com/problems/romans""" X = float(input()) def toRoman(X): return round(X * 1000 * 5280 / 4854) print(toRoman(X))
# -*- coding: utf-8 -*- data = [] with open('input.txt') as f: data = [l.strip() for l in f.readlines()] def CountsAs(s): letters = set(s) counts_2 = 0 let_2 = '' counts_3 = 0 for l in letters: n = 0 for c in s: if c == l: n += 1...
ATOM_TYPE_DICT = 'atom_type_dict' BOND_TYPE_DICT = 'bond_type_dict' ANGLE_TYPE_DICT = 'angle_type_dict' DIHEDRAL_TYPE_DICT = 'dihedral_type_dict' IMPROPER_TYPE_DICT = 'improper_type_dict' UNIT_WARNING_STRING = '{0} are assumed to be in units of {1}'
""" * @section LICENSE * * @copyright * Copyright (c) 2015-2017 Intel Corporation * * @copyright * 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 * * @copyright * http://www.apach...
# Ввод данных proceeds = int(input('Введите пожалуйста вашу выручку: ')) costs = int(input('Введите пожалуйста ваши издержки: ')) profitability = 0 netProfit = proceeds - costs staff = 0 profitPerPerson = 0 # Проверка и вывод if proceeds > costs: print('В этот раз у вас прибыль') profitability = netProfit / ...
def copy_files(name, srcs = [], outs = []): """ We have dependencies on data files outside of our project, and the filegroups provided by that project include extra stuff we don't want. This function will extract the provided filenames from the provided filegroups and copy them i...
# Copyright (c) 2015 Piotr Tworek. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'qt_version%': '<!(pkg-config --modversion Qt5Core)', }, 'targets': [ { 'target_name': 'qtcore', 'type': 'none', ...
print("10 / 3 = ", 10 / 3) print("9 / 3 = ", 9 / 3) print("10 // 3 = ", 10 // 3) print("10 % 3 = ", 10 % 3)
""" Wraps exceptions for authorizing and/or exchanging tokens. """ class CloudAuthzBaseException(ValueError): """ Base class for all the exceptions thrown (or relayed) in CloudAuthnz. """ def __init__(self, message, code=404, details=None): """ Base class for all the exceptions thrown ...
_base_ = './detector.py' model = dict( type='ATSS', neck=dict( type='FPN', in_channels=[24, 32, 96, 320], out_channels=64, start_level=1, add_extra_convs=True, extra_convs_on_inputs=False, num_outs=5, relu_before_extra_convs=True ), bbox_h...
# class Solution: # def canThreePartsEqualSum(self, A: list) -> bool: # # if len(A) < 3: # return False # # a, b = 0, len(A) - 1 # c = 0 # while a + 1 < b: # if sum(A[:a + 1]) == sum(A[b:]) == sum(A[a + 1: b]): # return True # elif ...
# # PySNMP MIB module CISCO-NDE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-NDE-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:08:18 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
# Databricks notebook source aws_bucket_name = "databricks-dhdev-db-research" mount_name = "databricks-dhdev-db-research" #access_key = dbutils.secrets.get(scope = "aws", key = "XXXXXXX") #secret_key = dbutils.secrets.get(scope = "aws", key = "XXXXXXX") #encoded_secret_key = secret_key.replace("/", "%2F") dbutils.fs.mo...
error_dict = { "required": "{} missing", "empty_field": "{} cannot be empty.", "invalid_name": "{0} cannot have spaces or special characters.", "invalid_number": "The {} must contain numbers only.", 'invalid_password': 'Password must have at least a number, and a least an uppercase and a lowercase l...
''' Pattern Enter number of rows: 5 1 12 123 1234 12345 1234 123 12 1 ''' print('Number of patterns: ') number_rows=int(input('Enter number of rows: ')) #upper part of the pattern for row in range(1,number_rows+1): for column in range(number_rows-1,row-1,-1): print(' ',end=' ') ...
class nmap_plugin(): # user-defined script_id = 'ssh-hostkey' script_source = 'service' script_types = ['port_info'] script_obj = None output = '' def __init__(self, script_object): self.script_obj = script_object self.output = script_object['output'] def port_info(...
# Copyright 2020, General Electric Company. All rights reserved. See https://github.com/xcist/code/blob/master/LICENSE def ReadMaterialFile(mtFile): # read material file d0 = [] for line in open(mtFile, 'r'): line = line[:-1] # remove the end '\n' if line and line[0].isdigit(): ...
""" Iterate over the given names and countries lists, printing them prepending the number of the loop (starting at 1) - See sample output in function docstring. The 2nd column should have a fixed width of 11 chars, so between Julian and Australia there are 5 spaces, between Bob and Spain, there are 8. This column sho...
#Imprime a mensagem chocolate nutella #programa feito por Pedro #versao 1.0 print("Chocolate Nutella!") """ sadsfghgh zdfxghcgh xfhg dfshg dfsgh dfgh dfsdghdfdgh xfgchvjbkj """ print("ADORO!")
class Docstore: def __init__(self, doc_cls, id_field='doc_id'): self._doc_cls = doc_cls self._id_field = id_field self._id_field_idx = doc_cls._fields.index(id_field) def get(self, doc_id, field=None): result = self.get_many([doc_id], field) if result: retu...
# %% COMSOFT rff, POC # from atm import asterix def read_file_header(f, position): f.seek(position, 0) header = f.read(128) position += 128 return position, header def read_block_header(f, position): astheader = f.read(6) length = int.from_bytes(astheader[4:6], byteorder='little') posit...
#!/usr/bin/env python3 N, *a = map(int, open(0)) n = N//2 - 1 a.sort() print(2*sum(a[n+2:]) - 2*sum(a[:n]) + a[n+1] - a[n] - (min(a[n]+a[n+2], 2*a[n+1]) if N%2 else 0))
class SelectionSet(object): """ This class defines DG behavior related to the 'selection set'. Note: This class keeps nothing in memory. The way to retrieve the information is to query the DG using the name to build the DG path """ def __init__(self, name, tobeCreated)...
bone_25 = ((1, 8), (0, 1), (15, 0), (17, 15), (16, 0), (18, 16), (5, 1), (6, 5), (7, 6), (2, 1), (3, 2), (4, 3), (9, 8), (10, 9), (11, 10), (24, 11), (22, 11), (23, 22), (12, 8), (13, 12), (14, 13), (21, 14), (19, 14), (20, 19), (8, 8))
while True: a = input() if a == "0.00": break k = 0 c = 2 a = float(a) while k < a: k += 1/c c+=1 print(c-2,"card(s)")
expected_output = { "FiftyGigE6/0/11": { "service_policy": { "output": { "policy_name": { "parent": { "class_map": { "tc7": { "bytes_output": 0, ...
class Solution: def countBits(self, num: 'int') -> '[int]': dp = [0] * (num + 1) for i in range(1,len(dp)): dp[i] = dp[i & (i-1)] + 1 return dp
# -*- coding: utf-8 -*- # Copyright: (c) 2017 Alibaba Group Holding Limited. He Guimin <heguimin36@163.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) class ModuleDocFragment(object): # Alicloud only documentation fragment DOCUMENTATION = r''' options: ali...
def upload_to(instance, name): return f'{instance.pk}/{name}' def calculate_vat(price): value = float(price) return value * 1.2
class NeocitizenError(Exception): """ Base class for exceptions in this module. """ pass class CredentialsRequiredError(NeocitizenError): pass class ApiError(NeocitizenError): pass class ArgumentError(NeocitizenError): pass
print("----------------------------\nZap's Band Name Generator\n----------------------------\n") city = input("What city did you grow up in?\n") pet = input("What is the name of your pet?\n") print(f"Your band name is: {city.title()} {pet.title()}")
class MockWebsocketConnection: def __init__(self, request): self.request = request self.send_data_buffer = list() def send(self, data): self.send_data_buffer.append(data) def pop_output_message(self): return self.send_data_buffer.pop(0)
''' Lets compare python lists and tuples. They are often confused. A python tuple is immutable, meaning you cannot change it. That said, less space is going to be required to generate a tuple, and you can use it for things where you don't want the tuple to change. To define a tuple, you either use round brackets, or n...
class DataGridLengthConverter(TypeConverter): """ Converts instances of various types to and from instances of the System.Windows.Controls.DataGridLength class. DataGridLengthConverter() """ def CanConvertFrom(self, *__args): """ CanConvertFrom(self: DataGridLengthConverter,context:...
s = '''Hello World''' print(s)
""" Custom Exceptions related to loading and parsing Environment Variable(s) """ class EnvVarNotFound(Exception): """ Exception to throw when Environment Variable is not set properly. """ pass class EnvVarValueNotValid(Exception): """ Exception to throw when Environment Variable's set va...
def print_usage_info(args): if args[1] not in ['-h', '--help']: print('{}: invalid command(s): {}'\ .format(args[0], ' '.join(args[1:])) ) print() print('Usage: garrick [COMMAND]') print() print('Launching garrick without arguments starts a regular review session, p...
def day14_pt1_pt2(polymer, rules, lettersFreq): for step in range(40): updPolymer = {} for rule in rules: pair, addon = rule if pair in polymer.keys(): lettersFreq[addon] = lettersFreq.get(addon, 0) + polymer[pair] updPolymer[pair[0] + addon] =...
def add_txt(t1, t2): return t1 + ":" + t2 def reverse(x, y, z): return z, y, x
#!/usr/bin/python # Filename: ex_inherit.py class SchoolMember: '''Represents any school member.''' def __init__(self, name, age): self.name = name self.age = age print('(Initialized SchoolMember: {0})'.format(self.name)) def tell(self): '''Tell my details.''' print...
def simuliraj(self, level=0): self.izracunaj_potezo() if self.odpri: p1 = self.odpri.pop() self.simuliraj_potezo(p1) print(level * " ", "Simuliram potezo ", p1) if not self.preveri_veljavnost_polja(): print(level * " ", "Neveljavno polje!") self.preklici...
# Tab length compensation a negative number will increase the gap between the tabs # a fudge factor that increases the gap along the finger joint when negative - it should be 1/4 of the gap you want fudge=0.1 thickness=3 # box_width=60 box_height=15 box_depth = 25 cutter='laser' tab_length=5 centre = V(0,0) mo...
def _go_template_impl(ctx): input = ctx.files.srcs output = ctx.outputs.out args = ["-o=%s" % output.path] + [f.path for f in input] ctx.actions.run( inputs = input, outputs = [output], mnemonic = "GoGenericsTemplate", progress_message = "Building Go template %s" % ctx.label, arg...
class Solution(object): def countElements(self, arr): """ :type arr: List[int] :rtype: int """ cnt = 0 for num in arr: if num + 1 in arr: cnt += 1 return cnt
# ============================================================================= # Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/ # FileName: 619.py # Description: UVa Online Judge - 619 # ============================================================================= def get_comma(...
input = """ aa:- link(X5,X0,X6), pp(X7, in_state,X6,open), h(X7,X3), time(X3), tank_of(X0,X4), h(X8,X3), qq(X8, press, X5,X1), ss(X2,press,X0,X1), tank_of(X1,X4). link(l,l,l). pp(p,in_state,l,open). h(p,1). time(1). time(2). h(p,2). tank_of(l,t). h(press,1). h(pre,2). qq(pre,press,l,1). ss(2, pr...
#! /usr/bin/python class Loose(object): """javascript style objects""" def __init__(self, obj=dict()): super(Loose, self).__init__() self.obj = obj def __call__(self): return self.__getattr__('_default')() def __getattr__(self, method_name): try: return ...
# def authorize(password, attempt): string = [] for letter in password: string += [ord(letter)] p = 131 M = 1000000007 n = len(string) - 1 p_exponents = [p ** i for i in range(0, n + 2)] hash_value = 0 for index, letter in enumerate(string): hash_value += letter * p_expo...
symbol = r'''`!@#$%^&*()_+-=/*{}[]\|'";:/?,.<>''' char = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' number = '0123456789' temp = input('请输入需要检查的密码组合:') # 判断长度 length = len(temp) while (temp.isspace() or length == 0) : passwd = input("您输入的密码为空(或空格),请重新输入:") length = len(temp) if length <= 8: ...
test_input = """ 0 <-> 2 1 <-> 1 2 <-> 0, 3, 4 3 <-> 2, 4 4 <-> 2, 3, 6 5 <-> 6 6 <-> 4, 5""".strip().splitlines() with open('d12_input.txt') as f: puzzle_input = f.readlines() def build_groups(inp): return dict(parse_line(line) for line in inp) def parse_line(line): """return the index and direct lin...
# coding=utf-8 # # @lc app=leetcode id=1010 lang=python # # [1010] Pairs of Songs With Total Durations Divisible by 60 # # https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/description/ # # algorithms # Easy (45.72%) # Likes: 198 # Dislikes: 16 # Total Accepted: 15.3K # Total Submi...
# -*- coding: utf-8 -*- """CacheException. Exception interface for all exceptions thrown by an Implementing Library. """ class CacheException(Exception): pass
# -*- coding: utf-8 -*- """ tutil python Library for tuyy ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Basic usage: >>> from tutil.functional import * >>> go([1, 2, 3, 4], map(lambda v: v + 1), sum) 14 https://github.com/tuyy/tutil copyright: (c) 2020 tuyy license: MIT, see LICENSE for more details."""
# List_comprehension oferece uma sintaxe mais curta quando # você deseja criar uma nova lista com base nos valores de um lista existente. # [ expressão for item in list if condicional] dobros = [i * 2 for i in range(10)] # if condicional não foram usados p/exemplo acima print(dobros) # Versaão 'normal' dobros = [] ...
DJANGO_VERSION_KEY = "django_version" TEMPLATE_FOLDER_NAME_KEY = "template_folder_name" PROJECT_ROOT_KEY = "project_root" INVALID_OPTION_MESSAGE = "Invalid option" VALIDATING_OPTIONS_MESSAGE = "Validating options" OPTIONS_VALIDATED_MESSAGE = "Options validated" INSTALLING_DJANGO_MESSAGE = "Installing django"
class Solution: def exist(self, board, word): x = False visited = [False * len(board[0]) for i in range(len(board))] for i in range(len(board)): for j in range(len(board[0])): if word[0] == board[i][j]: x = x | self.dfs(board, word, i, j, 1, vi...
def swatch(color): r, g, b, a = color lighter = (r*.2, g, b, a) darker = (r*.8, g, b, a) return lighter, darker for p in range(5): if p != 0: newPage() if p == 0: color = (.3,.5,0,1) else: color = (1/p,.5,0,1) lighter, darker = swatch(color) fill(*l...
_POSITION = ( ("Trener", "Trener"), ("Oppmann", "Oppmann"), ("Instruktør", "Instruktør"), ("Hjelpetrener", "Hjelpetrener") ) _COMPENSATIONS = ( ("ingen", "ingen"), ("treningskort", "treningskort"), ("betalt reise", "betalt reise"), ("annet", "annet") )
# Copyright 2021 The XLS 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 applicable law or agreed to in writ...
""" @Author: huuuuusy @GitHub: https://github.com/huuuuusy 系统: Ubuntu 18.04 IDE: VS Code 工具: python == 3.7.6 介绍: 深度之眼《Python高手之路》作业08:迭代生成 """ """ 练习 解决八皇后问题:国际象棋棋盘是8 * 8的方格,每个方格里放一个棋子。皇后这种棋子可以攻击同一行或者同一列或者斜线(左上左下右上右下四个方向)上的棋子。在一个棋盘上如果要放八个皇后,使得她们互相之间不能攻击(即任意两两之间都不同行不同列不同斜线),求出布局方式。 """ def conflict(chesses_placed, ...
P = int(input("Input P: ")) H = int(input("Input H: ")) print("If you want to exit input number = P or number = H") sum_num = 0 mul_num = 1 counter = 0 while True: numbers = int(input("Input numbers: ")) if numbers == P or numbers == H: break if numbers < P: sum_num += numbers if numbers...
class Node: def __init__(self, value=None, next=None, previous=None): self.data = value self.next = next self.previous = previous class DoublyLinkedList: def __init__(self, head=None, tail=None): self.head = head self.tail = tail def append(self, value=None): ...
def pytest_addoption(parser): parser.addoption( "--conn_str", action="store", default='', help="Address of InfServer", )
# we start with good praxis def run(): # # This code only will print even numbers # for i in range(1000): # if i % 2 != 0: # continue # This line skips each iteration # # where the result is not Zero with Odd numbers # print(i) # import random as rnd # fo...
def factorial_iterative(n): # 반복문으로 구현한 팩토리얼 함수 result = 1 for i in range(1, n + 1): result *= n return result def factorial_recursive(n): # 재귀로 구현한 팩토리얼 함수 if n <= 1: return 1 return n * factorial_recursive(n - 1) def main(): print(factorial_iterative(5)) print(factori...
def msisdn_formatter(msisdn): """ Formats the number to the International format with the Nigerian prefix """ # remove + msisdn = str(msisdn).replace('+', '') if msisdn[:3] == '234': return msisdn if msisdn[0] == '0': msisdn = msisdn[1:] return f"234{msisdn}"
DEFAULT_CAPNP_TOOL = "@capnproto//:capnp_tool" CapnpToolchainInfo = provider(fields = { "capnp_tool": "capnp_tool compiler target", }) def _capnp_toolchain_impl(ctx): return CapnpToolchainInfo( capnp_tool = ctx.attr.capnp_tool, ) capnp_toolchain = rule( implementation = _capnp_toolchain_impl,...
N = int(input()) distinct_country = set() if N in range (0,1000): for i in range(N): distinct_country.add(input()) output = len(distinct_country) print (output)
# Copyright (C) 2012 Ion Torrent Systems, Inc. All Rights Reserved #!/usr/bin/python # Ion Plugin Ion Reporter Uploader def sample_relationship_fields(): # Webservice Call For Workflow Data Structure goes here. Replace later webservice_call = [ {"Workflow": "TargetSeq Germline"}, {"Workflow": ...
''' File to hold the basic naming convention data for the Elder Scrolls universe ''' # ALTMER NAMES ## Surnames altmer_surname_a = ['Ad', 'Caem', 'Elsin', 'Gae', 'Gray', 'High', 'Jor', 'Lareth', 'Silin', 'Spell', 'Storm', 'Throm'] altmer_surname_b = ['aire', 'al', 'binder', 'ian', 'ire', 'ius', 'lock', 'or', 'orin', ...