content
stringlengths
7
1.05M
# Actually, this solution is to be finished because it is out of time limits. # The time complexity is n^2, which is still rejected by Leetcode. # Date: 2018-08-13. class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ if len...
# 6 - Faça um Programa que leia três números e mostre o maior deles. num1 = int(input("Digite o primeiro número: ")) num2 = int(input("Digite o segundo número: ")) num3 = int(input("Digite o terceiro número: ")) if(num1 > num2 and num1 > num3): print("O maior é: %d" %num1) elif(num2 > num1 and num2 > num3):...
class Occurrence(object): """ An Occurrence is an incarnation of a recurring event for a given date. """ def __init__(self,event,start,end): self.event = event self.start = start self.end = end def __unicode__(self): return "%s to %s" %(self.start, self.end) de...
def partition(arr, start, end): pivot = arr[end] tail_index = start for i in range(start, end): if arr[i] < pivot: arr[i], arr[tail_index] = arr[tail_index], arr[i] tail_index += 1 arr[end], arr[tail_index] = arr[tail_index], arr[end] return tail_index def find_kt...
# -*- coding: utf-8 -* def format_table(table, format): if format == "xml": return table2xml(keyphrases_table) elif format == "csv": return table2csv(keyphrases_table) else: raise Exception("Unknown table format: '%s'. " "Please use one of: 'xml', 'csv'." % ...
#!/usr/bin/env python numbers = [ 1721, 979, 366, 299, 675, 1456, ] # Identify pairs pairs = list() for i in numbers: for j in numbers: if i+j == 2020: pairs.append((i, j)) # Remove redundant pairs for pair in pairs: i, j = pair if (j, i) in pairs: pairs.remove((j, i)) # Print the answer[s] for pair ...
""" 1357. Path Sum II https://www.lintcode.com/problem/path-sum-ii/description?_from=ladder&&fromId=131 """ """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: a binary tree @param su...
class CollectionClass: def __init__(self, items, params): self.items = items self.params = params self.cursor = 0 def items(self): return self.items def params(self): return self.params def delete_all(self): self.cursor = 0 while len(self.items)...
# execfile(r'C:\qtlab-aalto\scripts\Qubit\TimeDomain\swap_batch\0dbm_swap\swap_with_high_pulse_30.py') # execfile(r'C:\qtlab-aalto\scripts\Qubit\TimeDomain\swap_batch\0dbm_swap\swap_with_high_pulse_100.py') #execfile(r'C:\qtlab-aalto\scripts\Qubit\TimeDomain\swap_batch\0dbm_swap\swap_with_high_pulse_200.py') #execfi...
def test(): r0 = 123.0 r1 = 123.1 r2 = 123.2 r3 = 123.3 r4 = 123.4 r5 = 123.5 r6 = 123.6 r7 = 123.7 r8 = 123.8 r9 = 123.9 i = 0 while i < 1e7: t = r0 t = r1 t = r2 t = r3 t = r4 t = r5 t = r6 t = r7 ...
def permutation(array, start = 0): if (start == len(array)): print(array) return for i in range(start, len(array)): array[start], array[i] = array[i], array[start] permutation(array, start + 1) array[start], array[i] = array[i], array[start] if __name__ == "__main__": permutation(['d','a','n']...
def end_zeros(num: int) -> int: """ find out how many zeros a given number has at the end How it works: ------------- Find the first non-zero while looping to the inverse string representation of the number """ zero_count = 0 for c in str(num)[::-1]: if c != "0": ...
""" Implementation of a labeled property graph. Note that classes are fine to be keys in a dictionary, so the graph itself is going to be a dictionary with Node class objects as keys. """ class Node: """Node object that will have a relationship to other nodes. Methods incorporate CRUD principles. """ ...
#Getting Input strInput = input('Enter a string: ') #Check if string is empty if strInput == "": print('The string is empty.') else: #String length function print(len(strInput))
# # @lc app=leetcode id=172 lang=python3 # # [172] Factorial Trailing Zeroes # # @lc code=start class Solution: def trailingZeroes(self, n: int) -> int: res = 0 while n > 0: n //= 5 res += n return res # @lc code=end # Accepted # 502/502 cases passed(32 ms) # Your...
income = float(input()) middle_grade = float(input()) minimal_payment = float(input()) scholarship = 0 if income < minimal_payment and middle_grade > 4.50: scholarship = minimal_payment * 0.65 elif middle_grade <= 5.50: scholarship = middle_grade * 25
def estimate_probability(word, previous_n_gram, n_gram_counts, n_plus1_gram_counts, vocabulary_size, k=1.0): denominator = n_gram_counts.get(previous_n_gram, 0) denominator += k * vocabulary_size numerator = n_plus1_gram_counts.get(previous_n_gram + ' ' + word, 0) numerator += ...
""" Workflow Archiver Error """ class WorkflowArchiverError(Exception): """ Error for Workflow Archiver module """ def __init__(self, message): super().__init__(message)
"""File output for field(s) value on a grid. """ class XDMFWriter(object): def __init__(self, h5filename, dimension, resolution, origin, space_step, dataset_names, ite, time): """ Parameters ---------- h5filename : nom du fichier h5 contenant les donnees d...
# Hayley # Check if a number is prime p = 13 * 17 m = 2 while m < p: if p % m == 0: print(m , "divides", p, "and therefore", p, "is not prime.") m = m + 1
class QuickFindUF: id = [] def __init__(self, N): self.id = [] for i in range(N): self.id[i] = i def connected(self, p, q): return self.id[p] == self.id[q] def union(self, p, q): pid = self.id[p] qid = self.id[q] for i in range(len(self.id))...
#!/usr/bin/python3 class Solution: def isPalindrome(self, x: int) -> bool: if x < 0: return False elif x < 10: return True reversed, k = 0, x while k != 0: reversed = reversed * 10 + (k % 10) k //= 10 return x == reversed
class Host: """A single host in the network. Note this class is mainly used to store initial scenario data for a host. The HostVector class is used to store and track the current state of a host (for efficiency and ease of use reasons). """ def __init__(self, address, ...
''' O bloco with é utilizado para criar um contexto de trabalho onde os recursos utilizados são fechados após o bloco with Por exemplo: Passos para se trabalhar com um arquivo: 1 - Abrir o arquivo; 2 - Trabalhar o arquivo 3 - Fechar o arquivo ''' with open('texto.txt', encoding='UTF-8') as arquivo: print(arquivo....
max=0 while True: a=int(input("masukan bilangan : ")) if max < a : max = a if a==0: break print("bilangan terbesar adalah = ",max)
# Author: Gaurav Pande # find the paths in a bt which adds up to the target. # link: https://leetcode.com/problems/path-sum-iii/description/ class Solution(object): def helper(self, root, target, so_far, cache): if root: complement = so_far + root.val - target if complement in cache...
class Person: "This is the Base Class" def get_name(self, name): "This is the Person Class Function" self.name= name def get_details(self): return self.name class Student(Person): def fill_details(self, name, branch, year): Person.get_name(self, name) ...
n, k=map(int,input().split()) e=list(map(int,input().split())) p=v=0 a='' for c, i in enumerate(e[1:]): if i > e[c]: if a == 'd':v+=1 a='s' elif i < e[c]: if a=='s': p+=1 a='d' print('beautiful') if k==p==v+1 else print('ugly')
""" 56. Merge Intervals Given a collection of intervals, merge all overlapping intervals. Example 1: Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. Example 2: Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals ...
# Databricks notebook source # MAGIC %md-sandbox # MAGIC # MAGIC <div style="text-align: center; line-height: 0; padding-top: 9px;"> # MAGIC <img src="https://databricks.com/wp-content/uploads/2018/03/db-academy-rgb-1200px.png" alt="Databricks Learning" style="width: 600px"> # MAGIC </div> # COMMAND ---------- # M...
########## Imports and other setup ############ ########## Preparing data ############## target = open('../data/example').read().split(': ')[1].split(', ') xTarget = target[0]; yTarget = target[1] xTarget = xTarget.split('=')[1].split('..'); yTarget = yTarget.split('=')[1].split('..') xTarget = [int(x) for x in xT...
#!/usr/bin/python3 # -*-coding:utf-8-*- __author__ = "Bannings" class Solution: def toGoatLatin(self, S: str) -> str: vowel = set([ 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U', ]) ans, words_count, first_char, is_begin = [], 1, "", True for char in S: ...
""" checks section sizes on disk and in virtual meory to indicate a packer """ def run(peobject): alerts = [] found = [] # loop through each section d = peobject.dict() if 'SECTIONS' in d: for s in d['SECTIONS']: # check for a raw size of 0 on disk but a non-zero size in virtual memory if (s[...
class Node: def __init__(self ,data): self.left = None self.right = None self.data = data def breadthfirst(root): if root is None: return my_list = [] result=[] result.append(root.data) my_list.append(root) while(len(my_list) > 0): node = my_list.pop...
size(256, 256) scale(0.5, 0.5) p = '../images/drawbot.png' blendMode("multiply") image(p, (0, 0)) image(p, (100, 100))
# DB connection PORT = 8000 db_name="routing" db_user="routing" db_pass="KadufZyn8Dr" # E-mail email_login="login" email_password="password" email_adress="login@email.com"
class TestDataError(Exception): pass class MissingElementAmountValue(TestDataError): pass class FactoryStartedAlready(TestDataError): pass class NoSuchDatatype(TestDataError): pass class InvalidFieldType(TestDataError): pass class MissingRequiredFields(TestDataError): pass class UnmetDependentFields(TestDataError): pas...
class NotFoundError(Exception): '''raise this when requested repository is not found''' pass class ApiRateLimitError(Exception): '''raise this when API rate limit exceeded''' pass class BadCredentialsError(Exception): '''raise this when bad credentials were provided for the API''' pass
""" You are given an unsorted array with both positive and negative elements. The positive numbers need not be in range from 1 to n !! You have to find the smallest positive number missing from the array in O(n) time using constant extra space. Examples Input: {2, 3, 7, 6, 8, -1, -10, 15} Output: 1 Input: { 2, 3...
#faça um programa que calcule a soma entre todos os números impares que são múltiplos de três e que se encontram no intervalo de 1 até 500. soma = cont = 0 #declaracao das variaveis for c in range(1, 501, 2): #para c no intervalo de 1 ate 500 if c % 3 == 0: #se o resto da divisao de c por 3 é igual a 0 con...
class MigrationScope: _engine = None @classmethod def engine(cls): assert cls._engine is not None return cls._engine def __init__(self, engine): self.old = None self.engine = engine def __enter__(self): self.old = MigrationScope._engine MigrationSco...
# https://www.urionlinejudge.com.br/judge/en/problems/view/1061 dia_comeco = input().split(" ") hora_comeco = input().split(" : ") dia_termino = input().split(" ") hora_termino = input().split(" : ") inicio_dia = int(dia_comeco[1]) termino_dia = int(dia_termino[1]) inicio_hora = int(hora_comeco[0]) inicio_m...
n=int(input()) s=input().lower() if len(set(s))==26: print("YES") else: print("NO")
n = 0 while n != 5: v = int(input('O 1° numero: ')) v2 = int(input('O 2° numero: ')) n = int(input('''[1] Somar [2] Multiplicar [3] Maior [4] Novos números [5] fechar Adicione sua opição: ''')) if n == 2 or n == 1: if n == 1: r = v + v2 t = 'soma' elif n == 2: ...
# -*- coding: utf-8 -*- ''' File name: code\strong_achilles_numbers\sol_302.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #302 :: Strong Achilles Numbers # # For more information see: # https://projecteuler.net/problem=302 # Problem St...
# username ,password => database # 'Bla Bla' , '123456' a, b, c, d = 5, 5, 10, 4 password = '1234' username = 'Bla Bla' result = (a == b) # true result = (a == c) # false result = ('blbl'== username) result = ('Bla Bla'== username) result = (a != b) result = (a != c) result = (a > c) result = (a < c...
#Given an integer, write a function that reverses the bits (in binary) and returns the integer result. #Examples: #csReverseIntegerBits(417) -> 267 #417 in binary is 110100001. Reversing the binary is 100001011, which is 267 in decimal. #csReverseIntegerBits(267) -> 417 #csReverseIntegerBits(0) -> 0 def csReverseInteg...
#14. Faça um programa que converta uma temperatura digitada em Celsius para Fahrenheit e Kelvin. def Main014(): TempCelsius = float(input('Temperatura em Celsius:')) TempFah = (((9*TempCelsius)+160)/5) print(f'Em Fahrenheit: {TempFah} F°.\nEm Kelvin: {TempCelsius + 273} K°.')
class GutenbergBook: """ @brief A Gutenberg Book object metadata only, used along with the books data source. This is a convenience class provided for users who wish to use this data source as part of their application. It provides an API that makes it easy to access the attributes of this data ...
# loooooooop """5个1相加""" totalSum = 0 for index in range(0, 5): totalSum += 1 """ 1+2+3+4+5 """ totalSum1 = 0 for index in range(1, 6): totalSum1 += index """ e^x 麦克劳林公式计算e^x """ def calcEMaclaurin(x,k): totalSum = 0 for i_of_items in range(0,k): fen1Mu3 = 1 fo...
# %% [1290. Convert Binary Number in a Linked List to Integer](https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/) class Solution: def getDecimalValue(self, head: ListNode) -> int: return int("".join(str(i) for i in to_iter(head)), 2) def to_iter(ln, isval=True): while ln...
class Solution: """ @param a: the list of salary @param target: the target of the sum @return: the cap it should be """ def getCap(self, a, target): start = min(a) end = target // len(a) + 1 while start + 1 < end: mid = start + (end - start) // 2 i...
#!/usr/bin/env python3 # https://cses.fi/problemset/task/1083 n = int(input()) print(n * (n + 1) // 2 - sum(map(int, input().split())))
ix.enable_command_history() ix.application.get_selection().deselect_all() ix.disable_command_history()
class UnsupportedLanguageError(AttributeError): """Raised when an unsupported language is supplied""" pass class InvalidGeolocationError(ValueError): """Raised when an invalid latitude or longitude is supplied""" pass
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: dummy = ListNode(-1) dummy.next = head pre = dummy whil...
# File: Grid.py # Description: Assignment 11 | Greatest Path Sum in a Grid # Student Name: Matthew Maxwell # Student UT EID: mrm5632 # Course Name: CS 313E # Unique Number: 50205 # Date Created: 10-07-2019 # Date Last Modified: 10-13-2019 # counts all the possible paths in a grid recursively def count_...
# data TRAINING_DATA_FILE = "raw.csv" PIPELINE_NAME = 'model' TARGET = 'RUL' # input variables FEATURES = ['engine_id', 'time_cycle','op_set_1', 'op_set_2', 'op_set_3', 'sensor_1', 'sensor_2', 'sensor_3', 'sensor_4', 'sensor_5', 'sensor_6', 'sensor_7', 'sensor_8', 'sensor_9', 'sensor_10', 'sen...
# -*- coding: utf-8 -*- # # panel_label.py # # Copyright 2017 Sebastian Spreizer # The MIT License def panel_label(ax, label, x=-0.4, y=1.0): ax.text(x, y, label, transform=ax.transAxes, fontsize=10, fontweight='bold', va='bottom', ha='left')
# float number 0.5 is represented as 0.4999999999998 in python def get_zt_price(price): zt_price = int(price * 1.1 * 100 + 0.50001) /100.0 return zt_price def get_dt_price(price): zt_price = int(price * 0.9 * 100 + 0.50001) /100.0 return zt_price
# generated from genmsg/cmake/pkg-genmsg.context.in messages_str = "/home/rudy-001/Relocalisation/src/select_pcd/msg/updated_coord.msg" services_str = "" pkg_name = "select_pcd" dependencies_str = "sensor_msgs;std_msgs" langs = "gencpp;geneus;genlisp;gennodejs;genpy" dep_include_paths_str = "select_pcd;/home/rudy-001/...
# coding: utf-8 class RpiCarDExp(Exception): """ An exception used for this project. """ def __init__(self, retcode, retmsg): """ Init. :retcode: retcode :retmsg: retmsg """ Exception.__init__(self) self._retcode = retcode self._retmsg ...
#Maior e Menor num1 = int(input('Digite o 1° número: ')) num2 = int(input('Digite o 2° número: ')) num3 = int(input('Digite o 3° número: ')) #Maior numero usando if maior = num1 if (maior < num2): maior = num2 if (maior < num3): maior = num3 print(f'O maior valor digitado foi {maior}') #Menor numero usando ...
# compare three values, return true only if 2 or more values are equal # integer value of boolean True is 1 # integer value of boolean False is 0 def compare(a = None, b = None, c = None): try: value = False a = int(a) b = int(b) c = int(c) print("Valid values.") ...
def run(): # Continue # for i in range(1000): # if i % 2 != 0: # continue # print(i) # for i in range(10000): # print(i) # if i == 300: # break text = input('Write a text: ') for char in text: if char == 'o': break ...
input=__import__('sys').stdin.readline r="";c=1 while True: n=int(input()) if n==0: break r+=str(c)+'\n';c+=1 a=[input().strip() for _ in range(n)] a.sort() r+='\n'.join(a) r+='\n' print(r.strip())
"""Depth-first traversing in a graph. Call a function _f on every vertex accessible for vertex _v, in depth-first prefix order Source: programming-idioms.org """ # Implementation author: bukzor # Created on 2018-04-08T19:17:47.214988Z # Last modified on 2018-04-08T19:18:25.491984Z # Version 2 # It's best to not rec...
""" Contains the custom exceptions used by the restclients. """ class PhoneNumberRequired(Exception): """Exception for missing phone number.""" pass class InvalidPhoneNumber(Exception): """Exception for invalid phone numbers.""" pass class InvalidNetID(Exception): """Exception for invalid neti...
class Matematica(object): def somar(valor1, valor2): ''' Este metodo tem a funcionalidade de somar dois valores. Parametros: 1. Valor1 (Number) - Primeira parcela 2. Valor2 (Number) - Segunda parcela Ex: Matematica.somar(1, 2) ''' return valor1 + v...
class Solution: def minimumEffortPath(self, heights: List[List[int]]) -> int: # The maximum cost seen H, W = len(heights), len(heights[0]) costs = [[math.inf] * W for _ in range(H)] costs[0][0] = 0 pq = [(0, 0, 0)] while pq: cost, r, c = heapq.heappop(pq) ...
# Description: Label the main chain atoms with the following: resn,resi,atom name. # Source: placeHolder """ cmd.do('label name n+c+o+ca,"%s%s%s" % (resn,resi,name);') """ cmd.do('label name n+c+o+ca,"%s%s%s" % (resn,resi,name);')
## Find Maximum and Minimum Values of a List ## 8 kyu ## https://www.codewars.com//kata/577a98a6ae28071780000989 def minimum(arr): return min(arr) def maximum(arr): return max(arr)
def my_chain(*args, **kwargs): for items in args: yield from items def main(): # 模拟分表后的两个查询结果 user1 = [{"name": "小张"}, {"name": "小明"}] user2 = [{"name": "小潘"}, {"name": "小周"}] user3 = [{"name": "test1"}, {"name": "test2"}] # 需求:合并并遍历 for item in my_chain(user1, user2, user3): ...
# Find this puzzle at: # https://adventofcode.com/2020/day/2 with open('input.txt', 'r') as file: puzzle_input = file.read().splitlines() valid = 0 for line in puzzle_input: # Extract the limits, letter, and password limits, letter, password = line.split() limit_low, limit_hi = limits.split('-') # ...
# Diameter of Binary Tree: https://leetcode.com/problems/diameter-of-binary-tree/ # Given the root of a binary tree, return the length of the diameter of the tree. # The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. # The le...
load("//3rdparty:dependencies.bzl", "maven_dependencies") load("//3rdparty:load.bzl", "declare_maven") def a_app(): print ("Loading [a.app]") maven_dependencies(declare_maven)
''' Mcast Genie Ops Object Outputs for IOSXR. ''' class McastOutput(object): ShowVrfAllDetail = { "default": { "description": "not set", "vrf_mode": "regular", "address_family": { "ipv6 unicast": { "route_target": { ...
def bad_apples(apples): res=[] remain=[] indexes=[] index=0 for i in apples: if i[0]==0 and i[1]==0: continue elif i[0]==0 or i[1]==0: remain.append(i[0]) if i[1]==0 else remain.append(i[1]) indexes.append(index) index+=1 res.append...
__author__ = 'Claudio' """Demonstrate how to use Python’s list comprehension syntax to produce the list [ a , b , c , ..., z ], but without having to type all 26 such characters literally. """ def demonstration_list_comprehension_abc(): return [chr(x) for x in range(ord('a'), ord('z')+1)]
class EchoService: @staticmethod def echo(text): return { 'text': text }
"""Investigate how classifiers utilize the structure of the dataset. Functions for finding groupings of attributes in a dataset. The groupings reveal how a classifier utilizes the structure of the data when classifying the data. The implementation is strongly oriented on https://bitbucket.org/aheneliu/goldeneye See ...
class Solution: def customSortString(self, order: str, str: str) -> str: m = {} for i, c in enumerate(order): m[c] = i return ''.join(sorted(list(str), key=lambda x: m[x] if x in m else 27)) if __name__ == '__main__': order = input() str = input() print(Solution().cu...
# list instantaneous nfs performance for all file systems res = client.get_file_systems_performance(protocol='nfs') print(res) if type(res) == pypureclient.responses.ValidResponse: print(list(res.items)) # list instantaneous nfs performance for file systems 'fs1' and 'fs2' res = client.get_file_systems_performance...
def binary_conversor(x: int) -> int: print(x) if x > 2: return binary_conversor(x // 2) def main() -> None: print(binary_conversor(25)) if __name__ == "__main__": main()
class OtherClassA(object): def sort(self): pass class OtherClassB(object): def sort(self): pass
#!/usr/bin/python3 for x in range(1, 11): print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ') # 注意上一行的'end'用法 print(repr(x*x*x).rjust(4)) # 两个print之间终端输出会有换行 print(1) print('2'.rjust(8)) for x in range(1, 11): print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)) print('12'.zfill(5)) print('-3.14'.z...
#!/usr/bin/env python # -*- coding: utf-8 -*- # abstract - abstract base classes for challenge handlers # Copyright (c) Rudolf Mayerhofer, 2019. # available under the ISC license, see LICENSE class AbstractChallengeHandler: def __init__(self, config): self.config = config @staticmethod def get_c...
# https://leetcode.com/problems/island-perimeter class Solution: def islandPerimeter(self, grid: List[List[int]]) -> int: def nei(i, j): t = 0 for (di, dj) in [(-1, 0), (1, 0), (0, -1), (0, 1)]: if 0 <= i + di < len(grid) and 0 <= j + dj < len(grid[0]): ...
# Copyright 2013 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. class RetainingEdge(object): """Data structure for representing a retainer relationship between objects. Attributes: from_object_id: int, id of the ...
# -*- coding: utf-8 -*- """ Created on Thu Mar 5 23:03:47 2020 @author: garyn """ """ We need to process a list of Event objects using their attributes to generate a report that lists all users currently logged in to the machines. """
n = 5 for i in range (n): for j in range (2*n,i,-1): print(' ', end='') for k in range (i+1): print('* ', end='') print() for i in range (n): for j in range (n,i,-1): print(' ', end='') for k in range (i+1): print('* ', end='') for l in range (i+1, n): pri...
# RTFM -> http://docs.gunicorn.org/en/latest/settings.html#settings bind = '0.0.0.0:8000' workers = 4 timeout = 30 worker_class = 'gevent' max_requests = 2000 max_requests_jitter = 500 proc_name = 'archery' accesslog = '-' errorlog = '-' loglevel = 'info'
tables6 = \ [([0, 1, 2, 3, 4, 5], (1, 0, 3, 2, 5, 4), (2, 3, 4, 5, 0, 1), (3, 2, 5, 4, 1, 0), (4, 5, 0, 1, 2, 3), (5, 4, 1, 0, 3, 2)), ([0, 1, 2, 3, 4, 5], (1, 0, 3, 2, 5, 4), (2, 3, 4, 5, 1, 0), (3, 2, 5, 4, 0, 1), (4, 5, 1, 0, 3, 2), (5, 4, 0, 1, 2, 3)), ([0, 1, 2, 3, 4, 5], (1, 0, 3, 2, 5, 4)...
# -*- coding: utf-8 -*- """ Created on Mon Aug 5 09:35:10 2019 @author: Rajan """ #The player class will hold all information regarding a team or player class player: #Each player must have a unique name def __init__(self, name): self.name = name self.score = 0 self.h...
#------------------------------------------------------------------------------- # Function: betterEnumeration # Description: Computes the maximum sub-array and and associated sum using # the "better enumeration" algorithm. # Receives: values - list of integers # Returns: maximum sub-array s...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2020/7/1 17:00 # @Author : 一叶知秋 # @File : decodeString.py # @Software: PyCharm """ 394. 字符串解码 给定一个经过编码的字符串,返回它解码后的字符串。 编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。 你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。 此外,你可以认为原始数据不...
high = [] for _ in range(4): high.append(int(input())) #증가 if high[0]<high[1]<high[2]<high[3]: print("Fish Rising") #감소 elif high[0]>high[1]>high[2]>high[3]: print("Fish Diving") #일정 elif high[0] == high[1] == high[2] == high[3]: print("Fish At Constant Depth") #그 외 else: print("No Fish")
""" description: merge-two-sorted-lists(合并两个有序链表) author: jiangyx3915 date: 2018/10/13 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 示例: 输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4 解题思路: 新建立一个新的链表。建立两个指针cur1和cur2,分别指向两个链表。然后只需要通过比较两个链表每个元素的大小,小的元素添加到新的链表中即可。 最后,我们要分别判断cur1和cur2是否是各自链表的末尾,如果不是,将剩余元素添加到新的链表末尾即可。 """...
""" Implementation of a circular buffer of fixed storage size. Author: George Heineman """ class CircularBuffer: def __init__(self, size): """Store buffer in given storage.""" self.buffer = [None]*size self.low = 0 self.high = 0 self.size = size ...
with open('inputs/input6.txt') as fin: raw = fin.read() def parse(data): return [x.replace('\n', '') for x in data.split('\n\n')] def parse2(data): return [x.splitlines() for x in data.split('\n\n')] forms = parse(raw) forms2 = parse2(raw) def part_1(groups): return sum([len(set(x)) for x in gro...