content
stringlengths
7
1.05M
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 17 16:17:25 2017 @author: jorgemauricio Instrucciones 1. Ordenar la siguiente lista de valores por medio de ciclos y/o validaciones arreglo = [54,26,93,17,77,31,44,55,20] Resultado arreglo = [54,26,93,17,77,31,44,55,20] arreglo = [17, 2...
# Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada, o programa deverá perguntar se o usuário quer ou não continuar. No final, mostre: # A) quantas pessoas tem mais de 18 anos. # B) quantos homens foram cadastrados. # C) quantas mulheres tem menos de 20 anos. print('-' * 100) prin...
''' 293. Flip Game ========= You are playing the following Flip Game with your friend: Given a string that contains only these two characters: + and -, you and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move and therefore the other person will be the ...
test_patterns = ''' Given source text and a list of pattens, look for matches for each patterns within the text and print them to stdout''' # Look for each pattern in the text and print the results.
# Source : https://leetcode.com/problems/range-sum-of-bst/ # Author : foxfromworld # Date : 27/04/2021 # Second attempt (recursive) class Solution: def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int: self.retV = 0 def sub_rangeSumBST(root): if root: if low <= root.val <= high: ...
class IntegerString: def __init__(self) -> None: self.digits = bytearray([0]) self._length = 0 def __init__(self, digits: bytearray) -> None: self.digits = digits self._length = len(self.digits) @property def length(self): return self._length def add(se...
def readint(prompt, min, max): while True: try: num = int(input(prompt)) assert num >= min and num <= max return num except ValueError: print("Error: entrada incorrecta") except AssertionError: print("Error: el valor no está dentro ...
# format the date in January 1, 2022 form def format_date(date): return date.strftime('%B %d, %Y') # format plural word def format_plural(total, word): if total != 1: return word + 's' return word
# Transliteration rules for Chakma ASCII to Chakma Description = u'Chakma ASCII to Unicode conversion' TRANS_LIT_RULES = CCP_UNICODE_TRANSLITERATE = u""" $letter = [\u11103-\u11126]; $evowel = \u1112C; $virama = \u11133; \u0000 > \u0020 ; # null \u000D > \u000D ; # Carriage return \u0020 > \u0020 ; # sp...
# -*- coding: utf-8 -*- class Visitor: def visit(self, manager): self.begin_visit(manager) manager.visit(self) return self.end_visit(manager) def begin_visit(self, manager): pass def end_visit(self, manager): pass def begin_chapter(self, chapter): pas...
# 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 rightSideView(self, root: Optional[TreeNode]) -> List[int]: if not root: return [] ...
# Given inorder and postorder traversal of a tree, construct the binary tree. # Note: # You may assume that duplicates do not exist in the tree. # For example, given # inorder = [9,3,15,20,7] # postorder = [9,15,7,20,3] # Return the following binary tree: # 3 # / \ # 9 20 # / \ # 15 7 # Definition ...
_base_ = ["./common_base.py", "./renderer_base.py"] # ----------------------------------------------------------------------------- # base model cfg for self6d-v2 # ----------------------------------------------------------------------------- refiner_cfg_path = "configs/_base_/self6dpp_refiner_base.py" MODEL = dict( ...
# # PySNMP MIB module RADLAN-SOCKET-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RADLAN-SOCKET-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:49:20 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
RATING_DATE = 'rating_date' ANALYSTS_MIN_MEAN_SUCCESS_RATE = 'ANALYSTS_MIN_MEAN_SUCCESS_RATE' DAYS_SINCE_ANALYSTS_ALERT = 'DAYS_SINCE_ANALYSTS_ALERT' QUESTIONABLE_SOURCES = [] EMISSIONS = 'emissions'
# Source and destination file names. test_source = "cyrillic.txt" test_destination = "xetex-cyrillic.tex" # Keyword parameters passed to publish_file. writer_name = "xetex" # Settings settings_overrides['language_code'] = 'ru' # use "smartquotes" transition: settings_overrides['smart_quotes'] = True
# Leetcode 101. Symmetric Tree # # Link: https://leetcode.com/problems/symmetric-tree/ # Difficulty: Easy # Complexity: # O(N) time | where N represent the number of nodes in the tree # O(N) space | where N represent the number of nodes in the tree # Definition for a binary tree node. # class TreeNode: # def _...
# !/usr/bin/env python3 # Author: C.K # Email: theck17@163.com # DateTime:2021-07-09 19:40:06 # Description: class Solution: def isValid(self, s: str) -> bool: n = len(s) if n == 0: return True if n % 2 != 0: return False while '()' in ...
''' Numerical validations. All functions are boolean. ''' def is_int(string: str) -> bool: ''' Returns True if the string argument represents a valid integer. ''' try: int(string) except ValueError: return False else: return True def is_float(string: str) -> bool: ...
def method1(ll: list) -> int: inversionCount = 0 for i in range(len(ll) - 1): for j in range(i + 1, len(ll)): if ll[i] > ll[j]: inversionCount = inversionCount + 1 return inversionCount if __name__ == "__main__": """ from timeit import timeit ll = [1, 9, 6,...
""" Exceptions raised in the sublp package. """ __all__ = [ 'SublpException', 'ProjectNotFoundError', 'ProjectsDirectoryNotFoundError', 'UnmatchedInputString' ] class SublpException(Exception): """Root exception type for sublp module.""" pass class ProjectNotFoundError(SublpException, IOErro...
class DumbCRC32(object): def __init__(self): self._remainder = 0xffffffff self._reversed_polynomial = 0xedb88320 self._final_xor = 0xffffffff def update(self, data): bit_count = len(data) * 8 for bit_n in range(bit_count): bit_in = data[bit_n >> 3] & (1 << (bit_n & 7)) self._remainder ^= 1 if bit_in...
""" @Author Jay Lee Credits to joeld at stackoverflow for the examples and also the link to the blender build script for the bcolors class link: https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-terminal-in-python """ class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m'...
# Leetcode 36. Valid Sudoku # # Link: https://leetcode.com/problems/valid-sudoku/ # Difficulty: Medium # Complexity: # O(9^2) time # O(9^2) space class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: width, height = len(board[0]), len(board) rows = collections.defaultdict(set) ...
filename="data2.txt" file=open(filename, "r") rs=file.read() fs=rs.split(",") il=[] for i in fs: il.append(int(i)) i=0 while i<len(il): moved=False if il[i]==1: il[il[i+3]]=il[il[i+1]]+il[il[i+2]] moved=True elif il[i]==2: il[il[i+3]]=il[il[i+1]]*il[il[i+2]] moved=Tru...
class Post: def __init__(self, index, title, subtitle, body): self.id = index self.title = title self.subtitle = subtitle self.body = body
# Rwapple - #Lesson 1: saying hello # Chapter one of the book. Print ('Hello, World!')
# Write your solution here word = input("Please type in a word: ") char = input("Please type in a character: ") index = word.find(char) if (char in word and index < len(word)-2): print(word[index:index+3])
def last_charges(bot, user, chat, args, dbman, LANG, currency, parse_mode): if len(args) > 1: bot.sendMessage(chat["id"], LANG["helper_commands"]["LAST_CHARGES"], parse_mode=parse_mode) return n_max_charges = 0 if len(args) == 0: n_max_charges = 5 elif len(args) == 1: try: n_max_charges = int(args[0]) ...
def multi_bracket_validation(str): open_brackets = tuple('({[') close_brackets = tuple(')}]') map = dict(zip(open_brackets, close_brackets)) queue = [] for i in str: if i in open_brackets: queue.append(map[i]) elif i in close_brackets: if not queue o...
#!/usr/bin/python # -*- coding: utf-8 -*- # Author: illuz <iilluzen[at]gmail.com> # File: AC_simulation_1.py # Create Date: 2015-03-02 23:19:56 # Usage: AC_simulation_1.py # Descripton: class Solution: # @return an integer def romanToInt(self, s): val = {'I': 1, 'V': 5, 'X': 10, '...
s = 0 for c in range(1,501): if c % 2 != 0 and c % 3 == 0: s += c print ('''\nO valor total da soma no intervalo de 1 a 500, considerando apenas os números impares e múltiplos de 3 é: {}'''.format(s))
""" 15051. Máquina de café 작성자: xCrypt0r 언어: Python 3 사용 메모리: 29,380 KB 소요 시간: 64 ms 해결 날짜: 2020년 9월 20일 """ def check_time(floor, people): time = 0 for i in range(3): time += abs(floor - i) * people[i] * 2 return time def main(): A = [int(input()) for _ in range(3)] time = [check_time(...
"""A python implementation of the PageRank algorithm. Requirements: ------------ None Usage: ------------ python3 page_rank.py NB: this code was developed and tested with python 3.7 Disclaimer: this code is intended for teaching purposes only. """ def page_rank(G, d=0.85, tolerance=0.01, max_iterations=50):...
frase = str(input('Digite uma frase: ')).strip().upper() palavras = frase.split() junto = ''.join(palavras) inverso = '' for letras in range(len(junto)-1,-1,-1): inverso += junto[letras] print(inverso) if inverso == junto: print('É um palíndromo.') else: print('Não é um palíndromo')
__version__ = "0.7.1" def version(): return __version__
lista = [1, 3, 5, 7] lista_animal = ['cachorro', 'gato', 'elefante'] print(lista) print(type(lista)) print(lista_animal[1])
class Credentials: """ Class that generates new instances of credentials. """ def __init__(self,username,password): self.username = username self.password = password
# The version number is stored here here so that: # 1) we don't load dependencies by storing it in the actual project # 2) we can import it in setup.py for the same reason as 1) # 3) we can import it into all other modules __version__ = '0.0.1'
class Solution: def isConvex(self, points): def direction(a, b, c): return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) d, n = 0, len(points) for i in range(n): a = direction(points[i], points[(i + 1) % n], points[(i + 2) % n]) if not d: d = a ...
#!/usr/bin/python # -*- coding: utf-8 -*- # Author: violinsolo # Created on 28/09/2018 FILTER_TOKENS = { ' ': '', '\n': '', '\t': '', '\r': '', '󾠮': '', '🏻': '', '🏼': '', '𓆟': '', } def filter_string(target: str, to_removed_tokens: list=None) -> str: """ element-wise doin...
""" [2017-05-29] Challenge #317 [Easy] Collatz Tag System https://www.reddit.com/r/dailyprogrammer/comments/6e08v6/20170529_challenge_317_easy_collatz_tag_system/ # Description Implement the [Collatz Conjecture tag system described here](https://en.wikipedia.org/wiki/Tag_system#Example:_Computation_of_Collatz_sequenc...
# 你和你的朋友,两个人一起玩 Nim 游戏:桌子上有一堆石头,每次你们轮流拿掉 1 - 3 块石头。 拿掉最后一块石头的人就是获胜者。你作为先手。 # 你们是聪明人,每一步都是最优解。 编写一个函数,来判断你是否可以在给定石头数量的情况下赢得游戏。 class Solution(object): def canWinNim(self, n): return bool() b = Solution().canWinNim(4) print(b)
#! -*- coding: utf-8 -*- SIGBITS = 5 RSHIFT = 8 - SIGBITS MAX_ITERATION = 1000 FRACT_BY_POPULATIONS = 0.75
def in_radius(signal, lag=6): n = len(signal) - 6 r = [] for m in range(n): a = sqrt((signal[m] - signal[m + 2]) ** 2 + (signal[m + 1] - signal[m + 3]) ** 2) b = sqrt((signal[m] - signal[m + 4]) ** 2 + (signal[m + 1] - signal[m + 5]) ** 2) c = sqrt((signal[m + 2] - signal[m + 4]) **...
#!/usr/bin/python # -*- coding: utf-8 -*- ''' @AUTHOR:Joselyn Zhao @CONTACT:zhaojing17@foxmail.com @HOME_PAGE:joselynzhao.top @SOFTWERE:PyCharm @FILE:20060501.py @TIME:2020/6/5 18:46 @DES: 8. 字符串转换整数 (atoi) ''' # # s = ' 23' # # s = '23' # # s=' -42' # s="4193 with words" # s="words and 987" # s="-91283472332" # ...
# Determine the sign of number n = float(input("Enter a number: ")) if n > 0: print("Positive.") elif n < 0: print("Negative.") else: print("STRAIGHT AWAY ZERROOO.")
""" Conta espaços e vogais. Dado uma string com uma frase informada pelo usuário (incluindo espaços em branco), conte: a. quantos espaços em branco existem na frase. b. quantas vezes aparecem as vogais a, e, i, o, u. """ frase = str(input('Digite uma frase: ')).strip().upper() contador_vogais = 0 for palavra in fras...
def simpleFun(dim, device): """ Args: dim: integer device: "cpu" or "cuda" Returns: Nothing. """ x = torch.rand(dim, dim).to(device) y = torch.rand_like(x).to(device) z = 2*torch.ones(dim, dim).to(device) x = x * y x = x @ z del x del y del z ## TODO: Implement the function abov...
# https://codeforces.com/problemset/problem/520/A n = int(input()) s = sorted(set(list(input().upper()))) flag = 0 if len(s) == 26: for i in range(len(s)): if chr(65 + i) != s[i]: flag = 1 break print("YES") if flag == 0 else print("NO") else: print("NO")
{ 'targets':[ { 'target_name': 'native_module', 'sources': [ 'src/native_module.cc', 'src/native.cc' ], 'conditions': [ ['OS=="linux"', { 'cflags_cc': [ '-std=c++0x' ] }] ] } ...
level = 3 name = 'Pacet' capital = 'Cikitu' area = 91.94
# Function to calculate the mask of a number. def split(n): b = [] # Iterating the number by digits. while n > 0: # If the digit is lucky digit it is appended to the list. if n % 10 == 4 or n % 10 == 7: b.append(n % 10) n //= 10 # Return the mask. return b # Inp...
class Hunk(object): """ Parsed hunk data container (hunk starts with @@ -R +R @@) """ def __init__(self): self.startsrc = None #: line count starts with 1 self.linessrc = None self.starttgt = None self.linestgt = None self.invalid = False self.desc = '' ...
class Player: """ Behavior to have a paddle controlled by the player """ def __init__(self, upKey, downKey): """ Initialize the Player """ self.upKey = upKey self.downKey = downKey def start(self): """ Connect the player input """ self.inputH...
## Model parameters model_hidden_size = 256 model_embedding_size = 256 model_num_layers = 3 ## Training parameters learning_rate_init = 1e-4 #speakers_per_batch = 64 speakers_per_batch = 128 utterances_per_speaker = 10
fyrst_number = int(input()) second_number = int(input()) third_number = int(input()) if fyrst_number > second_number and fyrst_number > third_number: print(fyrst_number) elif second_number > fyrst_number and second_number > third_number: print(second_number) else: print(third_number)
class OGCSensor: """ This class represents the SENSOR entity of the OCG Sensor Things model. For more info: http://developers.sensorup.com/docs/#sensors_post """ def __init__(self, name: str, description: str, metadata, encoding: str = "application/pdf"): self._id = None # the id is assign...
s1 = input().upper() s2 = input().upper() def sol(s1, s2): i = 0 while i < len(s1): if ord(s1[i]) < ord(s2[i]): return -1 elif ord(s1[i]) > ord(s2[i]): return 1 i += 1 return 0 print(sol(s1, s2))
lexy_copts = select({ "@bazel_tools//src/conditions:windows": ["/std:c++latest"], "@bazel_tools//src/conditions:windows_msvc": ["/std:c++latest"], "//conditions:default": ["-std=c++20"], })
#!/usr/bin/env python3 TITLE = "Юникод" STATEMENT = ''' Выбросы бывают разные. Некоторые из них просто уничтожают всё живое вокруг. Другие не столь смертоносны для людей, но портят к чёртовой матери всю технику. Как-то раз один сталкер из нашей группы не успел вовремя укрыться, когда начался очередной выброс пси-...
class URLInfo: def __init__(self, domain, subject): self.domain = domain self.subject = subject def __str__(self): result = "" result += f"domain: {self.domain}\n" result += f"subject: {self.subject}\n" return result
def insertion_sorting(input_array): for i in range(len(input_array)): value, position = input_array[i], i while position > 0 and input_array[position-1] > value: input_array[position] = input_array[position - 1] position = position - 1 input_array[position] = value ...
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def buildTree(preorder, inorder): """ https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/ 输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序 遍历的结果中都不含重复的数字。 """ if not preorder: ...
A=[3,5,7] B=[1,8] C=[] counter=0 while len(A)>0 and len(B)>0: if A[0] <= B[0]: C[counter]=A[0] A=A[1:] counter=counter+1 else: C[counter]=B[0] B=B[1:] counter=counter+1 print(C)
"""Source module to create ``Assumption`` space from. This module is a source module to create ``Assumption`` space and its sub spaces from. The formulas of the cells in the ``Assumption`` space are created from the functions defined in this module. The ``Assumption`` space is the base space of the assumption spaces ...
name = str(input('digite seu name: ')).upper() if name == 'LUZIA': print(f'{name} good night') else: print(f'hello {name}')
""" A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given an encoded message containing digits, determine the total number of ways to decode it. For example, Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). The n...
# -*- coding: utf-8 -*- class NesFile(object): def __init__(self, data: bytes): self.format = None self.prg_rom_unit_size = None self.chr_rom_unit_size = None self.trainer = None self.prg_rom = None self.chr_rom = None self._setup(data) def _setup(self...
# All participants who ranked A-th or higher get a T-shirt. # Additionally, from the participants who ranked between # (A+1)-th and B-th (inclusive), C participants chosen uniformly at random get a T-shirt. A, B, C, X = map(int, input().split()) if(X <= A): print(1.000000000000) elif(X > A and X <= B): print(...
cifar10_config = { 'num_clients': 100, 'model_name': 'Cifar10Net', # Model type 'round': 1000, 'save_period': 200, 'weight_decay': 1e-3, 'batch_size': 50, 'test_batch_size': 256, # no this param in official code 'lr_decay_per_round': 1, 'epochs': 5, 'lr': 0.1, 'print_freq':...
class ConnectedClientsList(list): """A response class representing the clients connected to the router at this time (or that have been recently connected). """ pass class ConnectedClientsListItem(object): """A client entry in the :class:`ConnectedClientsList`.""" LEASE_TIME_PERMANENT = 'Perma...
# Problem: Set Matrix Zeros # Difficulty: Medium # Category: Array # Leetcode 73: https://leetcode.com/problems/set-matrix-zeroes/description/ # Description: """ Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. Follow up: Did you use extra space? A straight forward solution...
def insertion_sort(a, n): """ insertion sort algorithm # outer loop from left to right start from 1 # inner loop from right to left end to right counter eq 0 start outer loop: 1. compare 2 elements 2. and swap 3. and decrement right counter # let l be left_cnf # let r be right...
class Percentil(object): def __init__(self, _edad): self.edad = int(_edad) self.score = {} self.matriz = {} self.resultados = {} def get_percentiles(self): raise NotImplementedError() def fit_normal_normal_bajo_deficit(self, pruebas, percentiles_deficit, percentiles...
# OpenWeatherMap API Key weather_api_key = "9cfaeb3dbd4832137f0fb5f0e12ca0f4" # Google API Key g_key = "AIzaSyBwiWBdcMksrxnWzcOvCM1cjxhqV8017_A"
input = """ zwanzig(A) :- A=5*4. fuenf(A) :- 20=A*4. eins(A) :- 3=2+A. """ output = """ zwanzig(A) :- A=5*4. fuenf(A) :- 20=A*4. eins(A) :- 3=2+A. """
"""A module for the ProjectListing class.""" class ProjectListing: """A class to respresent a projects listing.""" def __init__(self, response): self.response = response def can_access_project(self, project: str): """Check if the provided project ID is in the response.""" return ...
class Shape: def __init__(self): pass def area(self): return 0 class Square(Shape): def __init__(self, length): self.length = length def area(self): return self.length * self.length unittest = Square(88) print(unittest.area()) unittest2 = Shape() print((unittest2.area...
# Description: 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 # # Examples: 输入: 121, 输出: true # 输入: -121, 输出: false, 解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。 # 输入: 10, 输出: false, 解释: 从右向左读, 为 01 。因此它不是一个回文数。 # 输入: "words and 987", 输出: 0, 解释: 第一个非空字符是 'w', 但它...
# TESTS FOR COLOURABLE # graph with no vertices g0 = Graph(0) print(str(colourable(g0)) + "... should be TRUE") # graph with one vertice (no edge) g1 = Graph(1) g1.matrix[0][0] = True print(str(colourable(g1)) + "... should be FALSE") # graph with one vertice (and edge) g2 = Graph(1) print(str(colourable(g2)) + ".....
class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: nums.sort() ret = set() for i, v in enumerate(nums): j, k = i + 1, len(nums) - 1 while j < k: if nums[j] + nums[k] == -v: ret.add((v, nums[j], nums[k])) if nums[j] + nums[k] > -v: k -= 1...
''' (C) Copyright 2021 Steven; @author: Steven kangweibaby@163.com @date: 2021-06-30 '''
with open('day13/input.txt', 'r') as file: timestamp = int(file.readline()) data = str(file.readline()).split(',') data_1 = [int(x) for x in data if x != 'x'] res = sorted([(x - timestamp % x, x) for x in data_1], key=lambda x: x[0]) data_2 = [(int(x), data.index(x)) for x in data if x != 'x'] superbus_t...
#O(n) Space and time Complexity # Maintain a frequency map as {prefix_Sum:frequency of this prefix sum} # While looping the array: #0. hash_map[current_prefix_sum] += 1 #1. If (current_prefix_sum - k) exists in the map, it means there is a subarray found hence increment the counter. class Solution: def subarraySu...
# Here's a challenge for you to help you practice # See if you can fix the code below # print the message # There was a single quote inside the string! # Use double quotes to enclose the string print("Why won't this line of code print") # print the message # There was a mistake in the function name print('This line ...
POST_ACTIONS = [ 'oauth.getAccessToken', 'oauth.getRequestToken', 'oauth.verify', 'comment.digg', 'comment.bury', 'shorturl.create', 'story.bury', 'story.digg', ]
N = input() before = "" count = 1 for s in N: if before == -1: before = s else: if before == s: count += 1 if count >= 3: print("Yes") exit() else: before = s count = 1 print("No")
N,Y=map(int, input().split()) # (2)数字が2つ以上で別々に受け取り 入力例:A B for ii in range(N+1): for jj in range(N+1-ii): kk = N-ii-jj val = 10000*ii + 5000*jj + 1000*kk if val == Y: print(ii, jj, kk) exit() print("-1 -1 -1")
class Optimizer: pass class RandomRestartOptimizer(Optimizer): def __init__(self, N=10): self.N=N
class Solution(object): def license_key_formatiing(self, S, K): """ You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes. :type S: str :type K: int :rtype: str...
class Piece(object): BLACK = 'X' WHITE = 'O' def __init__(self, position, state): self.x = position[0] self.y = position[1] self.state = state @property def other_side(self): """The opposite side of this piece. Returns: str: Whatever the other s...
AUTH_USER_MODEL = 'users.User' AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validat...
class AlgorithmConfigurationProvider: def __init__(self, chromosome_config, left_range_number, right_range_number, population_number, epochs_number, selection_amount, elite_amount, selection_method, is_maximization): self.__chromosome_config = chromosome_config self.__left_range_...
def get_ids_and_classes(tag): attrs = tag.attrs if 'id' in attrs: ids = attrs['id'] if isinstance(ids, list): for subitem in ids: yield subitem else: yield ids if 'class' in attrs: classes = attrs['class'] if isinstance(classes...
def testHasMasterPrimary(nodeSet, up): masterPrimaryCount = 0 for node in nodeSet: masterPrimaryCount += int(node.monitor.hasMasterPrimary) assert masterPrimaryCount == 1
""" Kata Sort deck of cards - Use a sort function to put cards in order #1 Best Practices: zebulan, Unnamed, acaccia, j_codez, Mr.Child, iamchingel (plus 8 more warriors) def sort_cards(cards): return sorted(cards, key="A23456789TJQK".index) .""" def sort_cards(cards): """Sort a deck of cards.""" a_buck...
################################### # File Name : dir_normal_func.py ################################### #!/usr/bin/python3 def normal_func(): pass if __name__ == "__main__": p = dir(normal_func()) print ("=== attribute ===") print (p)
# -*- coding: mbcs -*- """ ========================================= PyQus 0.1.0 Author: Pedro Jorge De Los Santos E-mail: delossantosmfq@gmail.com https://github.com/JorgeDeLosSantos/pyqus ========================================= """
dividendo=int(input("Dividendo: ")) divisor=int(input("Divisor: ")) if dividendo>0 and divisor>0: cociente=0 residuo=dividendo while (residuo>=divisor): residuo-=divisor cociente+=1 print(residuo) print(cociente)