content
stringlengths
7
1.05M
""" Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its zigzag level order traversal as: [ [...
# -*- coding: utf-8 -*- def main(): n = int(input()) mod = 10 ** 9 + 7 ans = 0 for i in range(n): ans += ((i + 1) ** 10 - i ** 10) * (n // (i + 1)) ** 10 ans %= mod print(ans) if __name__ == '__main__': main()
load("//tools/bzl:maven_jar.bzl", "maven_jar") GUAVA_VERSION = "30.1-jre" GUAVA_BIN_SHA1 = "00d0c3ce2311c9e36e73228da25a6e99b2ab826f" GUAVA_DOC_URL = "https://google.github.io/guava/releases/" + GUAVA_VERSION + "/api/docs/" TESTCONTAINERS_VERSION = "1.15.3" def declare_nongoogle_deps(): """loads dependencies t...
# leetcode 625. Minimum Factorization # Given a positive integer a, find the smallest positive integer b whose multiplication of each digit equals to a. # If there is no answer or the answer is not fit in 32-bit signed integer, then return 0. # Example 1 # Input: # 48 # Output: # 68 # Example 2 # Input: # 15 ...
''' Last digit of number's factorial Status: Accepted ''' ############################################################################### def main(): """Read input and print output""" nonzero = {} nonzero[1] = 1 nonzero[2] = 2 nonzero[3] = 6 nonzero[4] = 4 for _ in range(int(input())): ...
def find_metathesis_pair(filename): """Takes a word list as text file, returns a list of word pairs that can be created by swapping one pair of letters""" res = [] t = find_anagrams(filename) for i in t: possibles = i for x in range(len(possibles)): for y in...
Import("env") print("Extra Script (Pre): common_pre.py") # Get build flags values from env def get_build_flag_value(flag_name): build_flags = env.ParseFlags(env['BUILD_FLAGS']) flags_with_value_list = [build_flag for build_flag in build_flags.get('CPPDEFINES') if type(build_flag) == list] defines = {k: v...
KONSTANT = "KONSTANT" def funktion(value): print(value) class Klass: def method(self): funktion(KONSTANT) Klass().method()
#!/usr/bin/python # -*- coding: utf-8 -*- """ multiset.py -- non-recursive n multichoose k and non-recursive multiset permutations for python lists author: Erik Garrison <erik.garrison@bc.edu> last revised: 2010-07-15 Copyright (c) 2010 by Erik Garrison Permission is hereby granted, ...
# -*- coding: utf-8 -*- """ square This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). """ class HttpResponse(object): """Information about an HTTP Response including its status code, returned headers, and raw body Attributes: status_code (int): The status code ...
conf = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'isAccessLog': { '()': 'utils.CustomLogFilter.AccessLogFilter' }, 'isHuntLog': { '()': 'utils.CustomLogFilter.HuntLogFilter' }, 'isHuntResultLog': { '()': 'utils...
def isPerfectCube(num): ans = 0 while ans**3 < abs(num): ans += 1 if ans**3 != abs(num): print("Not a perfect cube") else: if num < 0: ans = -ans print(ans, "is a cube root of", num) def main(): if __name__ == "__main__": print(isPerfectCube(8), "a...
# -*- coding: utf-8 -*- """ #project: CCP_Python3 #file: CCPRest.py #author: ceephoen #contact: ceephoen@163.com #time: 2019/6/13 21:43:21 #desc: """
# Common data problems!! # In this chapter, you'll learn how to overcome some of the most common dirty data problems. You'll convert data types, apply range constraints to remove future data points, and remove duplicated data points to avoid double-counting. # Numeric data or ... ? # In this exercise, and throughout ...
""" # Definition for Employee. class Employee: def __init__(self, id: int, importance: int, subordinates: List[int]): self.id = id self.importance = importance self.subordinates = subordinates """ class Solution: def getImportance(self, employees: List['Employee'], id: int) -> int: ...
def detect_db(fh): """ Parameters ---------- fh : file-like object Returns ------- db_type : str one of 'irefindex', 'string' Notes ----- STRING ====== head -n2 9606.protein.links.full.v10.5.txt protein1 protein2 neighborhood neighborhood_transferred fusion cooccurence homology coexpres...
""" This module contains exceptions for use throughout the L11 Colorlib. """ class ColorMathException(Exception): """ Base exception for all colormath exceptions. """ pass class UndefinedConversionError(ColorMathException): """ Raised when the user asks for a color space conversion that doe...
# Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Modifications made by Cloudera are: # Copyright (c) 2016 Cloudera, Inc. 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. A cop...
NORMALIZED_POWERS = { 191: ('1x127', '1.5'), 200: ('1x133', '1.5'), 330: ('1x220', '1.5'), 345: ('1x230', '1.5'), 381: ('1x127', '3'), 399: ('1x133', '3'), 445: ('1x127', '3.5'), 466: ('1x133', '3.5'), 572: ('3x220/127', '1.5'), 598: ('3x230/133', '1.5'), 635: ('1x127', '5'),...
dict_camera = {'wfpc1': 1, 'wfpc1_planetary': 2, 'wfpc1_foc_f48': 3, 'wfpc1_foc_f48': 4, 'wfpc2': 5, 'wfpc2_planetary': 6, 'wfpc2_foc_f48': 7, 'wfpc2_foc_f48': 8, 'nicmos1_precryo': 9, 'nicmos2_precryo': 10, 'nicmos3_precryo': 11, 'stis_ccd': 12, 'stis_nuv': 13, 'stis_fuv': 14, 'acs_widefield': 15, 'acs_highres': 16,...
def log_error(error): ''' This logging function just print a formated error message ''' print(error)
class Depvar: """The Depvar object specifies solution-dependent state variables. Notes ----- This object can be accessed by: .. code-block:: python import material mdb.models[name].materials[name].depvar import odbMaterial session.odbs[name].materials[name].depvar ...
host = 'Your SMTP server host here' port = 25 # Your SMTP server port here username = 'Your SMTP server username here' password = 'Your SMTP server password here' encryption = 'required' # Your SMTP server security policy here. Must be one of 'required', 'optional', or 'ssl' __all__ = ['host', 'port', 'username', '...
class Solution: # @param {string} a a number # @param {string} b a number # @return {string} the result def addBinary(self, a, b): # Write your code here alen, blen = len(a), len(b) if alen > blen: b = '0' * (alen - blen) + b nlen = alen else: ...
palettes = { "material_design": { "red_500": 0xF44336, "pink_500": 0xE91E63, "purple_500": 0x9C27B0, "deep_purple_500": 0x673AB7, "indigo_500": 0x3F51B5, "blue_500": 0x2196F3, "light_blue_500": 0x03A9F4, "cyan_500": 0x00BCD4, "teal_500": 0x0096...
class Node: """This class represents one node of a trie tree Parameters ---------- self.char --> str the character it stores, i.e. one character per node self.valid --> bool True if the character is the end of a valid word self.parent --> Node the parent node, i.e. e...
def main(request, response): try: name = "recon_fail_" + request.GET.first("id") headers = [("Content-Type", "text/event-stream")] cookie = request.cookies.first(name, None) state = cookie.value if cookie is not None else None if state == 'opened': status = (200...
chat_component = { "video_id" : "video_id", "timeout" : 10, "chatdata": [ { "addChatItemAction": { "item": { "liveChatTextMessageRenderer": { "message": { "runs": [ { ...
#! python3 # __author__ = "YangJiaHao" # date: 2018/2/14 class Solution: def findSubstring(self, s, words): """ :type s: str :type words: List[str] :rtype: List[int] """ if words == []: return [] word_length = len(words[0]) words_length = ...
# Python - 3.6.0 paradise = God() test.assert_equals(isinstance(paradise[0], Man), True, 'First object are a man')
# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- # pylint:...
#input # 15 # 2 4 3 6 7 9 1 5 8 # 9 3 7 8 6 1 5 2 4 # 1 4 9 5 6 3 2 8 7 # 1 6 8 3 4 2 9 7 5 # 7 4 6 5 1 9 3 8 2 # 8 1 7 5 6 3 9 2 4 # 2 4 3 9 7 8 5 1 6 # 6 3 1 9 2 7 4 5 8 # 1 4 7 6 8 9 5 3 2 # 7 9 1 8 5 6 3 2 4 # 1 3 9 6 8 2 5 7 4 # 8 5 4 6 3 7 2 1 9 # 7 2 4 5 8 1 9 3 6 # 5 2 6 1 8 4 9 3 7 # 4 8 5 3 2 6 1 7 9 class G...
#!/usr/bin/env python3 # Write a program that prints the reverse-complement of a DNA sequence # You must use a loop and conditional dna = 'ACTGAAAAAAAAAAA' rvdna = '' for i in range(len(dna) -1, -1, -1) : nt = dna[i] if nt == 'A' : rvdna += 'T' elif nt == 'T': rvdna += 'A' elif nt == 'C': rvdna += 'G' elif nt ...
load( "//ruby/private/tools:deps.bzl", _transitive_deps = "transitive_deps", ) load( "//ruby/private:providers.bzl", "RubyGem", "RubyLibrary", ) def _get_transitive_srcs(srcs, deps): return depset( srcs, transitive = [dep[RubyLibrary].transitive_ruby_srcs for dep in deps], )...
def average_price_per_year(dates,prices): year = '' counter = 0 accumulator = 0 average_year_years = [] average_year_prices = [] # for every date in the date list # do the following for index in range(len(dates)): # Set the first year. if year == '': year = da...
# The maximum size of a WebSocket message that can be sent or received # by the Determined agent and trial-runner. The master uses a different limit, # because it uses the uwsgi WebSocket implementation; see # `websocket-max-size` in `uwsgi.ini`. MAX_WEBSOCKET_MSG_SIZE = 128 * 1024 * 1024 # The maximum HTTP request si...
""" @author Wildo Monges Grid was provided as an initial skeleton of the project. Note: This was a project that I did for the course of Artificial Intelligence in Edx.org To run it, just execute GameManager.py """ class BaseAI: def get_move(self, grid): pass
""" defined: _exec(cmd, input="", pipe_from_memory=False) : executes a command and returns output _absrelerr(actual, expected, eps=1e-6): check if floating point absrel error is below epsilon tmp_path : temporary file the problem definition may use (e.g. input file for other program) verbose : if verbose mode activat...
""" Define the ChangeEvent class """ class ChangeEvent: """ A class to represents a change in the website """ def __init__(self, did_change=False, whitelisted_words=[], blacklisted_words=[]): """Hold information about the change in a site Args: did_change (bool, optional): Did the...
# -*- coding: utf-8 -*- """ The models in directory default have been added as a pure convenience and for demonstration purpose. Whenever there is a need to use a modified version, copy one of these models into the projects model directory and adopt it to your needs. Otherwise just import the model into your own models...
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
# # @lc app=leetcode id=7 lang=python # # [7] Reverse Integer # # https://leetcode.com/problems/reverse-integer/description/ # # algorithms # Easy (25.07%) # Total Accepted: 593.7K # Total Submissions: 2.4M # Testcase Example: '123' # # Given a 32-bit signed integer, reverse digits of an integer. # # Example 1: # #...
""" This function is intended to wrap the rewards returned by the CityLearn RL environment, and is meant to be modified by the participants of The CityLearn Challenge. CityLearn returns the energy consumption of each building as a reward. This reward_function takes all the electrical demands of all the buildings and ...
def avaliarSituacao(media): if media >= 6: print('aprovado') else: print('reprovado') def calcularMedia(p1, p2): media = (p1 + p2) / 2 avaliarSituacao(media) def main(): p1 = float(input('Digite a primeira nota: ')) p2 = float(input('Digite a segunda nota: ')) calcularM...
####################### # Dennis MUD # # list_users.py # # Copyright 2018-2020 # # Michael D. Reiley # ####################### # ********** # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal i...
""" Given an input string, reverse the string word by word. For example, Given s = "the sky is blue", return "blue is sky the". click to show clarification. Clarification: What constitutes a word? A sequence of non-space characters constitutes a word. Could the input string contain leading or trailing spaces? Yes. H...
#!/usr/bin/env python # coding=utf-8 """ 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为 数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转 数组的最小元素。例如,数组[3,4,5,1,2]为[1,2,3,4,5]的一个旋转, 该数组的最小值为1. """ class Solution(object): def min(self, data): if not data: return length = len(data) index_mid = index1 = 0 ind...
def extractEuricetteWordpressCom(item): ''' Parser for 'euricette.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('Greatest Alchemist', 'Someday Will I Be The Greatest A...
class Solution(object): def subsetsWithDup(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ if not nums: return [] n = len(nums) res = [] nums.sort() # 思路1 def helper1(idx, n, temp_list): if temp_list...
# i = 4, tallest library building ''' Nearly complete building_coordinations = [[(-0.126585027793863,16.8195412372661), (-1.26360571382314,26.9366491540346), (-15.8471949722061,25.2976587627339), (-14.7101742861769,15.1805508459654)], [(-23.0767794626376,16.8481382394501), (-15.1990122585185,17.6...
# Created by MechAviv # ID :: [4000022] # Maple Road : Adventurer Training Center 1 sm.showFieldEffect("maplemap/enter/1010100", 0)
# simplify_fraction.py def validate_input_simplify(fraction): if type(fraction) is not tuple: raise Exception('Argument can only be of type "tuple".') if len(fraction) != 2: raise Exception('Tuple can only contain 2 elements.') if type(fraction[0]) != int or type(fraction[1]) != int: raise Exception('Tuple ca...
items3 = ["Mic", "Phone", 323.12, 3123.123, "Justin", "Bag", "Cliff Bars", 134] def my_sum_and_count(my_num_list): total = 0 count = 0 for i in my_num_list: if isinstance(i, float) or isinstance(i, int): total += i count += 1 return total, count def my_avg(my_num_lis...
# coding: utf-8 PI = [58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7]...
"""D.""" def fun(a, b, name): print(a, b , name) x = (1, 2) fun(*x, 'fuck') print(F)
"""Errors specific to this library""" class ScreenConnectError(Exception): """ Base class for ScreenConnect errors """ @property def message(self): """ Returns provided message to construct error """ return self.args[0]
# -*- coding: utf-8 -*- """ pagarmeapisdk This file was automatically generated by APIMATIC v3.0 ( https://www.apimatic.io ). """ class CreateBankAccountRequest(object): """Implementation of the 'CreateBankAccountRequest' model. Request for creating a bank account Attributes: ...
# Crie um programa que leia nome e duas notas de vários alunos e guarde tudo em uma lista composta. # No final, mostre um boletim contendo a média de cada um e permita que # o usuário possa mostrar as notas de cada aluno individualemte. ficha = list() while True: nome = str(input('Nome: ')) nota1 = float(input(...
"""Python implementations of built-in fprime types This package provides the modules necessary for the representation of fprime types (Fw/Types) package in a Python context. These standard types are represented as Python classes representing each individual type. Example: U32 is represented by fprime.common.modul...
# Instructions: The following code example would print the data type of x, what data type would that be? x = 20.5 print(type(x)) ''' Solution: float The inexact numbers are float type. Read more here: https://www.w3schools.com/python/python_datatypes.asp '''
seg1 = float(input('Primeiro segmento:')) seg2 = float(input('Segundo segmento:')) seg3 = float(input('Terceiro Segmento:')) print('\033[1;33;04m Verificando os segmentos do seu triangulo...\033[m ') if seg1 < seg2 + seg3 and seg2 < seg1 + seg3 and seg3 < seg1 +seg2: print('\033[1;30;45mOs segmentos acima PODEM FOR...
def print_sth(s): print('print from module2: {}'.format(s)) if __name__ == "__main__": s = 'test in main' print_sth(s)
# # PySNMP MIB module FC-MGMT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FC-MGMT-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:05:00 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 0...
EXPOSED_CRED_POLICY = 'AWSExposedCredentialPolicy_DO_NOT_REMOVE' def rule(event): request_params = event.get('requestParameters', {}) if request_params: return (event['eventName'] == 'PutUserPolicy' and request_params.get('policyName') == EXPOSED_CRED_POLICY) return False def ded...
"""462. Total Occurrence of Target """ class Solution: """ @param A: A an integer array sorted in ascending order @param target: An integer @return: An integer """ def totalOccurrence(self, A, target): # write your code here ### Practice: if not A: return 0 ...
# 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 levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]: result = [] depth =...
""" LJM library error codes. """ # Success NOERROR = 0 # Warnings: WARNINGS_BEGIN = 200 WARNINGS_END = 399 FRAMES_OMITTED_DUE_TO_PACKET_SIZE = 201 DEBUG_LOG_FAILURE = 202 USING_DEFAULT_CALIBRATION = 203 DEBUG_LOG_FILE_NOT_OPEN = 204 # Modbus Errors: MODBUS_ERRORS_BEGIN = 1200 MODBUS_ERRORS_END...
# # Copyright (C) 2019 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy ofthe License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param {TreeNode} root # @return {string[]} def binaryTreePaths(self, root): if not root: return [] ...
def inc(x): return x + 1 def dec(x): return x - 1 def floor(par): x = 0 y = 1 for i in par: x = inc(x) if i == "(" else dec(x) if x == -1: return y y += 1 return x print(floor( "((((()(()(((((((()))(((()((((()())(())()(((()((((((()((()(()(((()(()((()...
""" https://www.hackerrank.com/challenges/no-idea There is an array of integers. There are also disjoint sets, and , each containing integers. You like all the integers in set and dislike all the integers in set . Your initial happiness is . For each integer in the array, if , you add to your happiness. If , yo...
#!/usr/bin/env python # -*- coding: utf-8 -*- def get_input(path): with open(path) as infile: return [line.rstrip('\n') for line in infile]
# # PySNMP MIB module JUNIPER-SMI (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/JUNIPER-SMI # Produced by pysmi-0.3.4 at Wed May 1 11:37:53 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 0...
class TcpUtils: """ Stores constants related to TCP protocol and utility methods """ TCP_HEADER_LENGTH = 5 TCP_HEADER_LENGTH_BYTES = TCP_HEADER_LENGTH * 4 TCP_OPTIONS_MAX_LENGTH_BYTES = 40 @staticmethod def validate_options_length(options): length = len(options) if leng...
# -*- coding: utf-8 -*- """ Created on Tue May 19 13:26:07 2020 @author: admin """ #Fibonacci last digit n=int(input()) n1=0 n2=1 for i in range(2,n+1): nex=n1+n2 n1=n2 n2=nex print(nex%10)
""" This test makes sure that the implicit rule dependencies are discoverable by an IDE. We stuff all dependencies into _scala_toolchain so we just need to make sure the targets we expect are there. """ attr_aspects = ["_scala_toolchain", "deps"] def _aspect_impl(target, ctx): visited = [str(target.label)] for...
# Hexadecimal print(hex(12)) print(hex(512)) # Binary print(bin(128)) print(bin(512)) # Exponential print(pow(2, 4)) print(pow(2, 4, 3)) # Absolute value print(abs(2)) # Round print(round(3.6)) # Round up print(round(3.4)) # Round down print(round(3.4, 2)) # Round down
def evaluate_list(list): list.sort() pairs_list = [] for i in range(len(list)-1): for e in list[i+1::]: if abs(list[i] - e) == 2: pairs_list.append([list[i], e]) for pair in pairs_list: print("{},{}".format(pair[0], pair[1])) def main(): custom_list = [...
print("Vou advinhar se é par ou impar") x = int(input('Digite um numero: ')) y = x % 2 if y <= 0: print("o numero é par") else: print("o numero é impar")
def update_matches(matches, nubank_month_data, mobills_month_data): """ Changes done in place. NuBank and Mobills expenses with match will be removed from original object. """ # Filter matches to only items that still exist matches_cleaned = [] for match in matches: [nubank_ids, mobill...
def long(x): separado=x.split(" ") ultima=separado[-1] a=len(ultima) print(f"La longitud de {ultima} es {a}") oracion=input("Escriba una oración: ") long(oracion)
def nonConstructibleChange(coins): if len(coins) == 0: return 1 coins.sort() change = 0 for coin in coins: if coin > change + 1: return change + 1 change += coin return change + 1
# -*- coding: utf-8 -*- """The-lost-planet.py: A text-based interactive game.""" __author__ = "Razique Mahroua" __copyright__ = "Copyright 20459, Planet GC-1450" class ParseError(Exception): pass class Sentence(object): def __init__(self, subject, verb, object): self.subject = subject[1] se...
for i in range(int(input())): n = int(input()) a = [] for j in range(n): l,r = [int(k) for k in input().split()] a.append((l,0)) a.append((r,1)) a.sort() c = 0 f = 0 m = 1e5 for j in a: if(j[1]): f=1 c-=1 else: i...
class MyData: def __del__(self): print('test __del__ OK') data = MyData()
def validate_dog_age(letter): """this function takes a letter as age and returns a tuple or range of ages""" if "b" or "y" or "a" or "s" in letter: return (1, 97) elif "b" or "y" in letter: return (1, 26) elif "a" or "s" in letter: return (25, 97) elif 'b' in letter: ...
map_sokoban = { "x" : 5, "y" : 5 } player = { "x" : 0, "y" : 4 } boxes = [ {"x" : 1, "y" : 1}, {"x" : 2, "y" : 2}, {"x" : 3, "y" : 3} ] destinations = [ {"x" : 2, "y" : 1}, {"x" : 3, "y" : 2}, {"x" : 4, "y" : 3} ] while True: for y in range(map_sokoban["y"]): for x...
input = """ edge(a,b,1). edge(a,c,3). edge(c,b,2). edge(b,d,3). edge(b,c,1). edge(c,d,3). town(T) :- edge(T,_,_). town(T) :- edge(_,T,_). """ output = """ edge(a,b,1). edge(a,c,3). edge(c,b,2). edge(b,d,3). edge(b,c,1). edge(c,d,3). town(T) :- edge(T,_,_). town(T) :- edge(_,T,_). """
""" Leia a hora inicial, minuto inicial, hora final e minuto final de um jogo. A seguir calcule a duração do jogo. OBS: O jogo tem duração mínima de um (1) minuto e duração máxima de 24 horas. """ entrada = input().split() hora1 = int(entrada[0]) minuto1 = int(entrada[1]) hora2 = int(entrada[2]) minuto2 = int(entrada...
class Queue: def __init__(self): self.queue = [] def enqueue(self, item): self.queue.insert(0, item) def dequeue(self): return self.queue.pop() def size(self): return len(self.queue) def is_empty(self): return self.queue == []
class Solution: def addToArrayForm(self, A, K): for i in range(len(A))[::-1]: A[i], K = (A[i] + K) % 10, (A[i] + K) // 10 return [int(i) for i in str(K)] + A if K else A
# use a func to create the matrix def create_matrix(rows): result = [] for _ in range(rows): result.append(list(int(el) for el in input().split())) return result #read input rows, columns = [int(el) for el in input().split()] matrix = create_matrix(rows) max_sum_square = -9999999999999 #create fo...
def gnome_sort(a): i, j, size = 1, 2, len(a) while i < size: if a[i-1] <= a[i]: i, j = j, j+1 else: a[i-1], a[i] = a[i], a[i-1] i -= 1 if i == 0: i, j = j, j+1 return a
'''VARIÁVEIS COMPOSTAS, LISTAS (parte 1)''' print('No Python, igualar duas listas significa ligar uma a outra, alterando a segunda, a primeira também se altera') a = [1, 2, 3, 4] b = a #igualando-as b[2] = 9 #modificando-a para demonstração print(f'Lista A: {a}') print(f'Lista B: {b}') print('\nMas é possível fazer u...
# iteracyjne obliczanie silni def silnia(n): s = 1 for i in range(2,n+1): s = s*i return s silnia(20)
""" Entradas: Capital -> flotador -> cap tiempo -> int -> Tiem tasa -> flotar -> Tasa Salidas: Interes -> flotar -> Interes Promedio -> flotar -> prom """ Cap = float ( input ( "Insertar capital:" )) Tiem = int ( input ( "Insertar el tiempo de inversión:" )) Tasa = float ( input ( "Insertar la tasa de interes:" )) Int...
class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x == 0: return True if x < 0 or x % 10 == 0: return False l = len(str(x)) i = 1 x1 = x2 = x while i <= l / 2: le...
''' @description 【Python】单例设计模式 2019/10/04 16:55 ''' # TODO:单例模式 # 某个类或者模型在整个程序运行中最多只能有个对象被创建 # 我们可以判断,如果User这个类没有创建对象,那么久创建一个对象保存在某个地方 # 以后如果要创建对象,我会去判断,如果之前已经创建了一个对象,那么就不再创建 # 而是直接把之前那个对象返回回去 class User(object): __instance = None def __new__(cls, *args, **kwargs): if not cls.__instance: ...
def is_primel_4(n): if n == 2: return True # 2 is prime if n % 2 == 0: print(n, "is divisible by 2") return False # all even numbers except 2 are not prime if n < 2: return False # numbers less then 2 are not prime prime = True m = n // 2 + 1 for x in range(3, ...
# # PySNMP MIB module NETSCREEN-RESOURCE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NETSCREEN-RESOURCE-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:20:16 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (d...