content
stringlengths
7
1.05M
""" Merge Sort 1. Divide the unsorted list into n sublists, each containing one element (a list of one element is considered sorted). 2. Repeatedly merge sublists to produce new sorted sublists until there is only one sublist remaining. This will be the sorted list. """ def merge_sort(arr): """ merge sort ...
n = soma = cont = 0 while True: n = int(input('Digite um número: ')) if n == 999: break cont += 1 soma += n print(f'Foram digitados {cont} números, e a soma total é {soma}.')
class IndexingError(Exception): """Exception raised for errors in the indexing flow. Attributes: type -- One of 'user', 'user_replica_set', 'user_library', 'tracks', 'social_features', 'playlists' blocknumber -- block number of error blockhash -- block hash of error txhash -- tr...
""" Entradas: lista-->list-->lista elemento->str-->elemento Salidas lista-->lista """ frutas = open('frutas.txt', 'r') lista_frutas = [] for i in frutas: lista_frutas.append(i) def eliminar_un_caracter(lista: list, elemento: str): auxilar = [] for i in lista: a = i.replace(elemento, "") auxilar.append(a...
########################################################################################## # district data structure ########################################################################################## class DistrictData: def __init__(self): self.data = "" self.stato = "" self.c...
class Solution: def nextPermutation(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ i = len(nums) - 2 while (i >= 0 and nums[i+1] <= nums[i]): i -= 1 # not the first if i >= 0: ...
# -*- coding: utf-8 -*- while True: try: hm = list(map(float, input().split())) h = int((hm[0] / 360) * 12) m = int((hm[1] / 360) * 60) if m == 60: m = 0 print("{:02d}:{:02d}".format(h, m)) except (EOFError, IndexError): break
# -*- coding: utf-8 -*- __about__ = """ This project comes fully-featured, with everything that Pinax provides enabled by default. It provides all tabs available, etc. From here you can remove applications that you do not want to use, and add your own applications as well. """
# 引数のデフォルト値は、関数宣言時に val = default の形で設定する def func_power(num, power=2): return num ** power print("-------- call func_power(2) --------") print(func_power(2)) # -> 4 print("-------- call func_power(2, 3) --------") print(func_power(2, 3)) # -> 8 print() # 可変長引数 # 引数名にひとつ*をつけると、tupleとして値を受け取る # 引数名にふたつ*をつけると、dictとして値...
class Solution: def rob(self, root): def f(n): if not n: return [0, 0] l, r = f(n.left), f(n.right) return [l[1] + r[1], max(l[1] + r[1], n.val + l[0] + r[0])] return max(f(root))
# -*- coding: utf-8 -*- def create_3dskullstrip_arg_string(shrink_fac, var_shrink_fac, shrink_fac_bot_lim, avoid_vent, niter, pushout, touchup, fill_hole, avoid_eyes, use_edge, exp_frac, smooth_final, ...
#!/usr/bin/env python3.7 class Proposal: """ Sequence proposed by the player while trying to guess the secret The problem will add hint information, by setting the value of whites and reds """ """proposed secret sequence""" sequence = str """number of right colours in a wrong position"""...
# Copyright (c) 2014 The Johns Hopkins University/Applied Physics Laboratory # 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/LICEN...
TEMPLATE = { 'schemes': [ 'http' ], 'tags': [ { 'name': '계정', 'description': '계정 관련 API' }, { 'name': '도서관', 'description': '도서관 가입과 탈퇴에 관한 API' }, { 'name': '책', 'description': '도서관의 책 관리...
class BookViewModel(object): def __init__(self, data): self.title = data['title'] self.author = '、'.join(data['author']) self.binding = data['binding'] self.publisher = data['publisher'] self.image = data['image'] self.image = self.image.replace('/view/subject/m/publ...
''' If the parameter to the make payment method of the CreditCard class were a negative number, that would have the effect of raising the balance on the account. Revise the implementation so that it raises a ValueError if a negative value is sent. ''' def make_payment(self,amount): if amount < 0: raise ValueError(...
x = 3 def foo(): y = "String" return y foo()
n = int(input()) for i in range(n): r,e,c = map(int, input().split()) if((e-c) > r): print('advertise') elif((e-c) == r): print('does not matter') else: print('do not advertise')
def sum(*args): total = 0 for arg in args: total+= arg return total a = sum(1200, 300, 500) print(a)
#1) def isnegative(n): if n < 0: return True else: return False isnegative(-6) #1) list1 = [1,2,3] def count_evens(list1): even_count = 0 for num in list1: if num % 2 == 0: even_count += 1 print(even_count) #1) def increment_odds(n): nums = [] for n in ...
def bio2span(labels): spans = [] span = [None, -1, -1] for i, tag in enumerate(labels): if tag.startswith('B-'): if span[2] != -1: spans.append(span) span = [tag.split('-')[1], i, i] if i == len(labels) - 1: # 最后一个tag spans.append(...
N = int(input()) while N > 0: texto = input().lower().replace(' ', '') alfabeto = 'abcdefghijklmnopqrstuvwxyz' contador = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] result = '' a, i, count, maior = 0, 0, 0, 0 break_ = True while count < 52: if break_ == True: c...
""" Singleton objects that serve as placeholders in pyll graphs. These are used by e.g. ./nips2011.py """ class train_task(object): """`train` argument to skdata.LearningAlgo's best_model method """ class valid_task(object): """`valid` argument to skdata.LearningAlgo's best_model method """ class ct...
# Schema used for pre-2013-2014 TAPR data SCHEMA = { 'staff-and-student-information': { 'all_students_count': 'PETALLC', 'african_american_count': 'PETBLAC', 'african_american_percent': 'PETBLAP', 'american_indian_count': 'PETINDC', 'american_indian_percent': 'PETINDP', ...
class ClientError(Exception): """Common base class for all client errors.""" class NotFoundError(ClientError): """URL was not found.""" class InvalidRequestError(ClientError): """The API request was invalid.""" class TimeoutError(ClientError): # pylint: disable=redefined-builtin """The API server...
# Leo colorizer control file for bbj mode. # This file is in the public domain. # Properties for bbj mode. properties = { "commentEnd": "*/", "commentStart": "/*", "wordBreakChars": ",+-=<>/?^&*", } # Attributes dict for bbj_main ruleset. bbj_main_attributes_dict = { "default": "null", ...
# # Time complexity: # O(lines*columns) (worst case, where all the neighbours have the same color) # O(1) (best case, where no neighbour has the same color) # # Space complexity: # O(1) (color changes applied in place) # def flood_fill(screen, lines, columns, line, column, color): def inbound(l, c)...
def __residuumSign(self): if self.outcome == 0: return -1 else: return 1
# -*- coding: utf-8 -*- class RedisServiceException(Exception): pass
def main(request, response): headers = [("Content-Type", "text/javascript")] values = [] for key in request.cookies: for cookie in request.cookies.get_list(key): values.append('"%s": "%s"' % (key, cookie.value)) # Update the counter to change the script body for every request to tr...
class Solution: def minStickers(self, stickers: List[str], target: str) -> int: n = len(target) maxMask = 1 << n # dp[i] := min # of stickers to spell out i, # where i is the bit representation of target dp = [math.inf] * maxMask dp[0] = 0 for mask in range(maxMask): if dp[mask] == ...
# ----------------------------------------------------------- # Copyright (c) 2021. Danil Smirnov # A positive real number is given. Print its fractional part. # ----------------------------------------------------------- def get_fractional_part(number: float)-> float: return float(number - (int(number ...
# N개의 수가 주어질때 세자리 수 두개를 곱하여 만들 수 있는 대칭수 중 각 수보다 작은 것들 중 가장 큰 것을 고르시오 # Given N integers, find the largest palindrome made from the product of two 3-digit numbers which is less than each integer palindrome = set() for i in range(999, 99, -1): for j in range(999, 99, -1): if (i*j) % 11 == 0: s = str(i*j) if s =...
""" File: booleans.py Copyright (c) 2016 Callie Enfield License: MIT This code was used to simply gain a better understanding of what different boolean expressions will do. """ C = 41 #There will be no output. This expression is setting the variable 'C' equal to 41. C == 40 #The output will be 'False'. 40 is being...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Solutions to chapter 5 exercises. ############################################################################### # chapter5_exercises.py # # Revision: 1.00 # Date: 6/29/2021 # Author: Alex # # Purpose: Solutions to chapter 5 exercises from "Data...
def hello(): print(f"Hello, world!") if __name__ == '__main__': hello()
class IAuthenticationModule: """ Provides the base authentication interface for Web client authentication modules. """ def Authenticate(self, challenge, request, credentials): """ Authenticate(self: IAuthenticationModule,challenge: str,request: WebRequest,credentials: ICredentials) -> Authorizat...
js = """ const quote = String.fromCharCode(34); const newline = String.fromCharCode(10); const marker = quote + quote + quote; const quine = 'js = ' + marker + js + marker + newline + 'py = ' + marker + py + marker + py; exports.handler = async (body, ctx) => { return new ctx.HTTPResponse({ body: Buffer.from(quin...
# 8-3 def make_shirt(size, string): """Make shirt""" print('Size: ' + size + ', String: ' + string) make_shirt('M', 'Hello, World') make_shirt(size='M', string='Hello, World again') # 8-4 def make_shirt(size='L', string='I love Python'): """Make python shirt""" print('Size: ' + size + ', String: ' + ...
variant = dict( mlflow_uri="http://128.2.210.74:8080", gpu=False, algorithm="PPO", version="normal", actor_width=64, # Need to tune critic_width=256, replay_buffer_size=int(3E3), algorithm_kwargs=dict( min_num_steps_before_training=0, num_epoch...
# # PySNMP MIB module ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENTERASYS-RADIUS-ACCT-CLIENT-EXT-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:50:07 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # U...
par = [] impar = [] print('Para o inicio da contagem, inicie com 1 para mostrar os impares e 2 para os pares.') n1 = int(input('Digite o inico da contagem [ 1 ] [ 2 ]:')) n2 = int(input('Digite o final da contagem:')) for c in range(n1, n2+1, 2): if n1 == 2: par.append(c) elif n1 == 1: impar.app...
""" Data structures to store CommCareHQ reports """ class Report(object): """ This class is a generic object for representing data intended for specific reports. It is mostly useful so that we can transform these structures arbitrarily into xml, csv, json, etc. without changing our report generators ...
# Crie um programa onde o usuario digite # uma expressao qualquer que use parenteses. # Seu aplicativo devera analisar se a # expressao passada esta com os # parenteses abertos e fechados na ordem correta. expr = str(input('Digite a expressao: ')) pilha = list() for simb in expr: if simb == '(': pilha.appen...
# Python Program To Sort The Elements Of A Dictionary Based On A Key Or Value ''' Function Name : Sort Elements Of Dictionary Based On Key, Value. Function Date : 13 Sep 2020 Function Author : Prasad Dangare Input : String Output : String ''' colors = {10: "Red", 35: "Green"...
# Edit this file to change settings CONFIG = { # Uncomment the following two lines to set your username and password. # 'userName': '', # 'passWord': '', # The beginDate of the term in %Y-%m-%d # Should be a Monday 'beginDate': '2019-09-02', # 'default' sets whether you want to use the new...
# Mergesort is the best sorting algorithm for use with a linked-list # Time Complexity O(nlogn) # Merging will require log(n) doublings from subarrays of size (1) to a single array of size length(n), # where each pass will require (n) iterations to compare and sort each element # Space Complexity O(n) arrays ...
"""VTK/FURY Tools This module implements a set o tools to enhance VTK given new functionalities. """ class Uniform: """This creates a uniform shader variable It's responsible to store the value of a given uniform variable and call the related vtk_program """ def __init__(self, name, uniform_ty...
def solution(inp): data = [row.split() for row in inp.splitlines()] count = 0 for passphrase in data: if len(passphrase) == len(set(passphrase)): count = count + 1 return count def main(): with open('input.txt', 'r') as f: inp = f.read() print('[*] Reading input from input.txt...') print('[*] The soluti...
# -*- coding: utf-8 -*- __author__ = "venkat" __author_email__ = "venkatram0273@gmail.com"
# version code 80e56511a793+ # Please fill out this stencil and submit using the provided submission script. # Be sure that the file voting_record_dump109.txt is in the matrix/ directory. ## 1: (Task 2.12.1) Create Voting Dict def create_voting_dict(strlist): """ Input: a list of strings. Each string rep...
valores = list() maior = menor = 0 for index in range(0, 5): valores.append(int(input(f'Digite um valor para a posição {index}: '))) print('-=-' * 30) print(f'Você digitou os valores {valores}') print(f'O maior valor digitado foi {max(valores)} nas posições ', end='') for index, valor in enumerate(valores): mai...
while True: n1 = float(input("\n Escreva o lado 1 do triângulo: ")) n2 = float(input(" Escreva o lado 2 do triângulo: ")) n3 = float(input(" Escreva o lado 3 do triângulo: ")) if(n1 > 0 and n2 > 0 and n3 > 0 and n1 <= n2+n3 and n2 <= n1+n3 and n3 <= n1+n2): if(n1 == n2 and n1 != n3 or n...
s1=set([1,3,7,94]) s2=set([2,3]) print(s1) print(s2) print(s1.intersection(s2)) print(s1.difference(s2)) print(s2.difference(s1)) print(s1.symmetric_difference(s2)) print(s1.union(s2)) s1.difference_update(s2) #S1 becomes equal to the difference print(s1) s1=set([1,3]) s1.discard(1) s1.remove(3) print(s1) s1.add(5) pr...
def convert_to_alt_caps(message): lower = message.lower() upper = message.upper() data = [] space_offset = 0 for i in range(len(lower)): if not lower[i].isalpha(): space_offset += 1 if (i + space_offset) % 2 == 0: data.append(lower[i]) else: ...
TIME_FORMAT = ('day', 'hour') OPERATORS = { '==': lambda x, y: x == y, '<=': lambda x, y: x <= y, '>=': lambda x, y: x >= y, '>': lambda x, y: x > y, '<': lambda x, y: x < y, } class TimeDelta(object): def __init__(self, amount, fmt, operator): if int(amount) < 0: raise ...
# -*- coding: utf-8 -*- """ """ #make noarg a VERY unique value. Was using empty tuple, but python caches it, this should be quite unique def unique_generator(): def UNIQUE_CLOSURE(): return UNIQUE_CLOSURE return ("<UNIQUE VALUE>", UNIQUE_CLOSURE,) NOARG = unique_generator()
print('-='*30) print('Olá, seja bem vindo!') nome = str(input('Digite o seu nome completo: ')).strip() print('') print('Seu nome em letras maiúsculas: {}'.format(nome.upper())) print('Seu nome em letras minúsculas: {}'.format(nome.lower())) print('Total de letras do seu nome: {}'.format(len(nome.replace(' ', '')))) di...
class Solution: def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: banset = set(banned) for c in "!?',;.": paragraph = paragraph.replace(c, ' ') cnt = Counter(word for word in paragraph.lower().split()) ans, best = '', 0 for word in cnt: if cnt[word] > best and word no...
#program to input a number, if it is not a number generate an error message. while True: try: a = int(input("Input a number: ")) break except ValueError: print("\nThis is not a number. Try again...") print() break
# Introduction to deep learning with Python # A. Forward propogation # Process of working from the input layer to the hidden layer to the final output layer # Values contained within the input layer are multiplied by the weights that are connected to the interactions for the hidden layer. # Details contained within th...
class Destiny2APIError(Exception): pass class Destiny2InvalidParameters(Destiny2APIError): pass class Destiny2APICooldown(Destiny2APIError): pass class Destiny2RefreshTokenError(Destiny2APIError): pass class Destiny2MissingAPITokens(Destiny2APIError): pass class Destiny2MissingManifest(Des...
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: dic = {} for i, num in enumerate(numbers): if target - num in dic: return [dic[target - num] + 1, i + 1] dic[num] = i
""" Представлен список чисел. Определить элементы списка, не имеющие повторений. Сформировать итоговый массив чисел, соответствующих требованию. Элементы вывести в порядке их следования в исходном списке. Для выполнения задания обязательно использовать генератор. Пример исходного списка: [2, 2, 2, 7, 23, 1, 44, 44, 3, ...
# DROP TABLES songplay_table_drop = "DROP TABLE IF EXISTS songplays;" user_table_drop = "DROP TABLE IF EXISTS users;" song_table_drop = "DROP TABLE IF EXISTS songs;" artist_table_drop = "DROP TABLE IF EXISTS artists;" time_table_drop = "DROP TABLE IF EXISTS time;" # CREATE TABLES songplay_table_create = ("""CREATE T...
# OpenWeatherMap API Key weather_api_key = "601b4c14f4ddb46a0080bbfb5ca51d3e" # Google API Key g_key = "AIzaSyDNUFB01N6sBwZfPznGBiHayHJrON12pYw"
class BaseModel: def __init__(self): self.ops = {}
# user.py __all__ = ['User'] class User: pass def user_helper_1(): pass
description = 'IPC Motor bus device configuration' group = 'lowlevel' instrument_values = configdata('instrument.values') tango_base = instrument_values['tango_base'] # data from instrument.inf # used for: # - shutter_gamma (addr 0x31) # - nok2 (addr 0x32, 0x33) # - nok3 (addr 0x34, 0x35) # - nok4 reactor side (add...
def extractMichilunWordpressCom(item): ''' Parser for 'michilun.wordpress.com' ''' bad = [ 'Recommendations and Reviews', ] if any([tmp in item['tags'] for tmp in bad]): return None vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title...
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ lookup = dict(((v, i) for i, v in enumerate(nums))) return next(( (i+1, lookup.get(target-v)+1) for i, v in enumerate(nums) ...
# -*- coding: utf-8 -*- check_state = 0 d = {} p = [] e = [] m = [] n = int(input()) for _ in range(n): ln = input().split() d[ln[0]] = (int(ln[1]), int(ln[2]), int(ln[3])) p.append(int(ln[1])) e.append(int(ln[2])) m.append(int(ln[3])) while True: if check_state == 0: if p.cou...
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param: root: The root of the binary search tree. @param: A: A TreeNode in a Binary. @param: B: A TreeNode in a Binary. @return: Return...
def main(): with open('inputs/01.in') as f: data = [int(line) for line in f] print(sum(data)) result = 0 seen = {0} while True: for item in data: result += item if result in seen: print(result) return seen.add(resu...
strikeout = 'K' className = "This is CS50." age = 30 anotherAge = 63 pi = 3.14 morePi = 3.1415962 fun = True print("strikeout: {}".format(strikeout)) print("className: {}".format(className)) print("age: {}".format(age)) print("anotherAge: {}".format(anotherAge)) print("pi: {}".format(pi)) print("morePi: {}".format(mor...
def is_all_strings(iterable): return all(isinstance(string, str) for string in iterable) print(['a', 'b', 'c']) print([2, 'a', 'b', 'c'])
# -*- coding: utf-8 -*- class InsufficientInputError(Exception): """入力が不足していることを知らせる例外クラス""" pass class InvalidInputError(Exception): """入力が相応しくないことを知らせる例外クラス""" pass
""" You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and ...
def concat_multiples(num, multiples): return int("".join([str(num*multiple) for multiple in range(1,multiples+1)])) def is_pandigital(num): return sorted([int(digit) for digit in str(num)]) == list(range(1,10)) def solve_p038(): # retrieve only 9 digit concatinations of multiples where n = (1,2,..n) ...
# Copyright 2015 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': { 'chromium_code': 1, }, 'targets': [ { # GN version: //ui/aura_extra 'target_name': 'aura_extra', 'type': '<(...
class Env: __table = None _prev = None def __init__(self, n): self.__table = {} self._prev = n def put(self, w, i): self.__table[w] = i def get(self, w): e = self while e is not None: found = e.__table.get(w) if found is not None: ...
def foo(*args, **kwargs): pass fo<caret>o(1, 2, 3, x = 4)
#!/usr/bin/python3 # -*- coding: utf-8 -*- # # 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 ...
class physics:#universal physics(excluding projectiles because i hate them) def __init__(self,world,gravity = 2): self.gravity = gravity self.world = world def isAtScreenBottom(self,obj):#unused if obj.y + obj.size[1] <= screenSize[1]: return True else: ...
# -*- coding: utf-8 -*- # Copyright 2021 Cohesity Inc. class EnvironmentListProtectionSourcesEnum(object): """Implementation of the 'environment_ListProtectionSources' enum. TODO: type enum description here. Attributes: K_VMWARE: TODO: type description here. KSQL: TODO: type description ...
class DoublyNode: def __init__(self, data): self.data = data self.leftlink = None self.rightlink = None def __str__(self): return '| {0} |'.format(self.data) def __repr__(self): return "Node('{0}')".format(self.data) def getdata(self): return self.data...
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: """Hash table. Running time: O(n) where n == len(nums). """ d = {nums[0]: 0} for i in range(1, len(nums)): if target - nums[i] in d: return [i, d[target - nums[i]]] ...
def distinct_values_bt(bin_tree): """Find distinct values in a binary tree.""" distinct = {} result = [] def _walk(node=None): if node is None: return if node.left is not None: _walk(node.left) if distinct.get(node.val): distinct[node.val] =...
{ 'variables': { 'SMRF_LIB_DIR': '/usr/local/lib', 'SMRF_INCLUDE_DIR': '/usr/local/include' }, 'targets': [ { 'target_name': 'smrf-native-cpp', 'sources': [ 'src/smrf.cpp' ], 'cflags_cc': [ '-std=c++14' ], 'cflags!': [ '-fno-exceptions'], 'cflags_cc!': [ '-fno-exceptions'], 'incl...
# Definition for a undirected graph node # class UndirectedGraphNode: # def __init__(self, x): # self.label = x # self.neighbors = [] class Solution: # @param node, a undirected graph node # @return a undirected graph node def cloneGraph(self, node): root = UndirectedG...
class ApplicationId(object): """ Contains information used to uniquely identify a manifest-based application. This class cannot be inherited. ApplicationId(publicKeyToken: Array[Byte],name: str,version: Version,processorArchitecture: str,culture: str) """ def ZZZ(self): """hardcoded/mock instance of t...
#!/usr/bin/env python # encoding: utf-8 # This file is made available under Elastic License 2.0 # This file is based on code available under the Apache license here: # https://github.com/apache/incubator-doris/blob/master/gensrc/script/doris_builtins_functions.py # Licensed to the Apache Software Foundation (ASF) u...
#!/usr/bin/env python """ sample data for persistence/serialization examples this version is flat for saving in CSV, ini, etc. """ AddressBook = [ {'first_name': "Chris", 'last_name': "Barker", 'address_line_1':"835 NE 33rd St", 'address_line_2' : "", ...
def test_get_empty_collection(client): empty_response = client.get('/data') assert empty_response.status_code == 200 assert 'json' in empty_response.content_type assert empty_response.is_json assert empty_response.json['href'].startswith('http') assert empty_response.json['href'].endswith('/data...
""" @file @brief `c3 <http://c3js.org/gettingstarted.html>`_ """ def version(): "version" return "0.4.2"
#!/usr/bin/env python3 def next_nums(): A = 703 B = 516 for _ in range(40000000): A *= 16807 A %= 2147483647 B *= 48271 B %= 2147483647 yield (A, B) count = 0 for newA, newB in next_nums(): if newA % 65536 == newB % 65536: count += 1 print(count)
class ApiConfig: def __init__(self, environment: str = None, name: str = None, is_debug: bool = None, port: int = None, root_directory: str = None): self.port = port self.is_debug = is_debug self.name = name...
data = ( 'Mang ', # 0x00 'Zhu ', # 0x01 'Utsubo ', # 0x02 'Du ', # 0x03 'Ji ', # 0x04 'Xiao ', # 0x05 'Ba ', # 0x06 'Suan ', # 0x07 'Ji ', # 0x08 'Zhen ', # 0x09 'Zhao ', # 0x0a 'Sun ', # 0x0b 'Ya ', # 0x0c 'Zhui ', # 0x0d 'Yuan ', # 0x0e 'Hu ', # 0x0f 'Gang ', # 0x10 ...
"""739. Daily Temperatures""" class Solution(object): def dailyTemperatures(self, T): """ :type T: List[int] :rtype: List[int] """ ## R2: res = [0 for _ in range(len(T))] stack = [] for pos, tem in enumerate(T): while stack and T[stack[-1...
# Python 3.6.1 with open("input.txt", "r") as f: puzzle_input = [int(i) for i in f.read()[0:-1]] total = 0 for cur_index in range(len(puzzle_input)): next_index = cur_index + 1 if not cur_index == len(puzzle_input) - 1 else 0 puz_cur = puzzle_input[cur_index] pnext = puzzle_input[next_index] if p...