content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class Obj(object): def __init__(self, filename): with open(filename) as f: self.lines = f.read().splitlines() self.vertices = [] self.vfaces = [] self.read() def read(self): for line in self.lines: if line: prefix, value = line.spl...
class Obj(object): def __init__(self, filename): with open(filename) as f: self.lines = f.read().splitlines() self.vertices = [] self.vfaces = [] self.read() def read(self): for line in self.lines: if line: (prefix, value) = line....
# Consider a row of n coins of values v1 . . . vn, where n is even. # We play a game against an opponent by alternating turns. In each turn, # a player selects either the first or last coin from the row, removes it # from the row permanently, and receives the value of the coin. Determine the # maximum possible amount o...
def find_max_val_recur(coins, l, r): if l + 1 == r: return max(coins[l], coins[r]) if l == r: return coins[i] left_choose = coins[l] + min(find_max_val_recur(coins, l + 1, r - 1), find_max_val_recur(coins, l + 2, r)) right_choose = coins[r] + min(find_max_val_recur(coins, l + 1, r - 1), ...
''' Example: Given an array of distinct integer values, count the number of pairs of integers that have difference k. For example, given the array { 1, 7, 5, 9, 2, 12, 3 } and the difference k = 2,there are four pairs with difference2: (1, 3), (3, 5), (5, 7), (7, 9). ''' def pairs_of_difference(array, diff): hash...
""" Example: Given an array of distinct integer values, count the number of pairs of integers that have difference k. For example, given the array { 1, 7, 5, 9, 2, 12, 3 } and the difference k = 2,there are four pairs with difference2: (1, 3), (3, 5), (5, 7), (7, 9). """ def pairs_of_difference(array, diff): hash...
numbers_count = int(input()) sum_number = 0 for counter in range(numbers_count): current_number = int(input()) sum_number += current_number print(sum_number)
numbers_count = int(input()) sum_number = 0 for counter in range(numbers_count): current_number = int(input()) sum_number += current_number print(sum_number)
# coding=utf-8 def test_common_stats_insert(session): raise NotImplementedError def test_duplicate_common_stats_error(session): raise NotImplementedError def test_common_stats_default_values(session): raise NotImplementedError def test_common_stats_negative_value_error(session): raise NotImpleme...
def test_common_stats_insert(session): raise NotImplementedError def test_duplicate_common_stats_error(session): raise NotImplementedError def test_common_stats_default_values(session): raise NotImplementedError def test_common_stats_negative_value_error(session): raise NotImplementedError def test_...
#common utilities for all module def trap_exc_during_debug(*args): # when app raises uncaught exception, print info print(args)
def trap_exc_during_debug(*args): print(args)
# Copyright 2011 Nicholas Bray # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
def do_nothing(node): pass class Cfgdfs(object): def __init__(self, pre=doNothing, post=doNothing): self.pre = pre self.post = post self.processed = set() def process(self, node): if node not in self.processed: self.processed.add(node) self.pre(node...
def optical_flow(img_stack): """ Given an image stack (N, H, W, C) calculate the optical flow beginning from the center image (rounded down) towards either end. Returns the disparity maps stackes as (N, H, W, 2) """ pass
def optical_flow(img_stack): """ Given an image stack (N, H, W, C) calculate the optical flow beginning from the center image (rounded down) towards either end. Returns the disparity maps stackes as (N, H, W, 2) """ pass
class Calculator(object): def __init__(self, corpus, segment_size): self.corpus = corpus self.segment_size = segment_size @staticmethod def calc_proportion(matches, total): """ Simple float division placed into a static method to prevent Zero division error. """ ...
class Calculator(object): def __init__(self, corpus, segment_size): self.corpus = corpus self.segment_size = segment_size @staticmethod def calc_proportion(matches, total): """ Simple float division placed into a static method to prevent Zero division error. """ ...
""" ytsync.py Synchronize YouTube playlists on a channel to local storage. Downloads all videos using youtube-dl. """
""" ytsync.py Synchronize YouTube playlists on a channel to local storage. Downloads all videos using youtube-dl. """
def summation(number): total = 0 for num in range(number + 1): total += num return total if __name__ == "__main__": print(summation(1000))
def summation(number): total = 0 for num in range(number + 1): total += num return total if __name__ == '__main__': print(summation(1000))
a = int(input('Informe um numero:')) if a%2 == 0 : print("Par!") else: print('Impar!')
a = int(input('Informe um numero:')) if a % 2 == 0: print('Par!') else: print('Impar!')
class Piece: def __init__(self, board, square, white): self.square = square self.row = square[0] self.col = square[1] self.is_clicked = False #dk if i need this self._white = white self.pinned = False #self.letter def move(self): pass def che...
class Piece: def __init__(self, board, square, white): self.square = square self.row = square[0] self.col = square[1] self.is_clicked = False self._white = white self.pinned = False def move(self): pass def check_move(self): if self.is_click...
print('please input the starting annual salary(annual_salary):') annual_salary=float(input()) print('please input The portion of salary to be saved (portion_saved):') portion_saved=float(input()) print("The cost of your dream home (total_cost):") total_cost=float(input()) portion_down_payment=0.25 current_savings=0 nu...
print('please input the starting annual salary(annual_salary):') annual_salary = float(input()) print('please input The portion of salary to be saved (portion_saved):') portion_saved = float(input()) print('The cost of your dream home (total_cost):') total_cost = float(input()) portion_down_payment = 0.25 current_savin...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- mylist = [ "a", 2, 4.5 ] myotherlist = mylist[ : ] mylist[1] = "hello" print(myotherlist) mytext = "Hello world" myothertext = mytext mytext = "Hallo Welt!" #print(myothertext) print(mylist[ : ])
mylist = ['a', 2, 4.5] myotherlist = mylist[:] mylist[1] = 'hello' print(myotherlist) mytext = 'Hello world' myothertext = mytext mytext = 'Hallo Welt!' print(mylist[:])
''' Pig Latin: Rules if word starts with a vowel, add 'ay' to end if word does not start with a vowel, put first letter at the end, then add 'ay' word -> ordway apple -> appleay ''' def pig_latin(word): initial_letter = word[0] if initial_letter in 'aeiou': translated_word = word + 'ay' else: translated_word...
""" Pig Latin: Rules if word starts with a vowel, add 'ay' to end if word does not start with a vowel, put first letter at the end, then add 'ay' word -> ordway apple -> appleay """ def pig_latin(word): initial_letter = word[0] if initial_letter in 'aeiou': translated_word = word + 'ay' else: ...
class Queryable: """This superclass holds all common behaviors of a queryable route of MBTA's API v3""" @property def list_route(self): raise NotImplementedError class SingularQueryable(Queryable): def __init__(self, id): self._id = id def __eq__(self, other): return ...
class Queryable: """This superclass holds all common behaviors of a queryable route of MBTA's API v3""" @property def list_route(self): raise NotImplementedError class Singularqueryable(Queryable): def __init__(self, id): self._id = id def __eq__(self, other): return ...
class Break: def __init__(self, dbRow): self.flinch = dbRow[0] self.wound = dbRow[1] self.sever = dbRow[2] self.extract = dbRow[3] self.name = dbRow[4] def __repr__(self): return f"{self.__dict__!r}"
class Break: def __init__(self, dbRow): self.flinch = dbRow[0] self.wound = dbRow[1] self.sever = dbRow[2] self.extract = dbRow[3] self.name = dbRow[4] def __repr__(self): return f'{self.__dict__!r}'
# -*- coding: utf-8 -*- empty_dict = dict() print(empty_dict) d = {} print(type(d)) #zbiory definuje sie set e = set() print(type(e)) # klucze nie moga sie w slowniku powtarzac #w slowniku uporzadkowanie nie jest istotne, i nie jest uporzadkowane pol_to_eng = {'jeden':'one', 'dwa':'two', 'trzy': 'th...
empty_dict = dict() print(empty_dict) d = {} print(type(d)) e = set() print(type(e)) pol_to_eng = {'jeden': 'one', 'dwa': 'two', 'trzy': 'three'} name_to_digit = {'Jeden': 1, 'dwa': 2, 'trzy': 3} len(name_to_digit) pol_to_eng['cztery'] = 'four' pol_to_eng.clear() pol_to_eng_copied = pol_to_eng.copy() pol_to_eng.keys() ...
class WordDictionary: def __init__(self, cache=True): self.cache = cache def train(self, data): raise NotImplemented() def predict(self, data): raise NotImplemented() def save(self, model_path): raise NotImplemented() def read(self, model_path): raise NotI...
class Worddictionary: def __init__(self, cache=True): self.cache = cache def train(self, data): raise not_implemented() def predict(self, data): raise not_implemented() def save(self, model_path): raise not_implemented() def read(self, model_path): raise ...
''' Exercise 2: Odd Or Even Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2? Extras: If the number is a multiple of 4, print out a different message. Ask the user for two nu...
""" Exercise 2: Odd Or Even Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2? Extras: If the number is a multiple of 4, print out a different message. Ask the user for two nu...
"Macros for loading dependencies and registering toolchains" load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") load("//lib/private:jq_toolchain.bzl", "JQ_PLATFORMS", "jq_host_alias_repo", "jq_platform_repo", "jq_toolchains_repo", _DEFAUL...
"""Macros for loading dependencies and registering toolchains""" load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive') load('@bazel_tools//tools/build_defs/repo:utils.bzl', 'maybe') load('//lib/private:jq_toolchain.bzl', 'JQ_PLATFORMS', 'jq_host_alias_repo', 'jq_platform_repo', 'jq_toolchains_repo', _DEF...
# wwwhisper - web access control. # Copyright (C) 2012-2018 Jan Wrobel <jan@mixedbit.org> """wwwhisper authentication and authorization. The package defines model that associates users with locations that each user can access and exposes API for checking and manipulating permissions. It also provides REST API to logi...
"""wwwhisper authentication and authorization. The package defines model that associates users with locations that each user can access and exposes API for checking and manipulating permissions. It also provides REST API to login, logout a user and to check if a currently logged in user can access a given location. ""...
# Copyright 2017 Neural Networks and Deep Learning lab, MIPT # # 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 appli...
""" Description of the module agents.paraphraser: The task of the module To recognize whether two sentences are paraphrases or not. The module should give a positive answer in the case if two sentences are paraphrases, and a negative answer in the other case. Models architecture All models use Siamese architecture....
#!/usr/bin/env python # Copyright (c) 2019 VMware, Inc. All Rights Reserved. # SPDX-License-Identifier: BSD-2 License # The full license information can be found in LICENSE.txt # in the root directory of this project. SERVER_CONSTANTS = ( REQUEST_QUEUE_SIZE, PACKET_SIZE, ALLOW_REUSE_ADDRESS ) = ( 100, 1024, Tr...
server_constants = (request_queue_size, packet_size, allow_reuse_address) = (100, 1024, True)
class Formatting: """Terminal formatting constants""" SUCCESS = '\033[92m' INFO = '\033[94m' WARNING = '\033[93m' END = '\033[0m'
class Formatting: """Terminal formatting constants""" success = '\x1b[92m' info = '\x1b[94m' warning = '\x1b[93m' end = '\x1b[0m'
class Stack: def __init__(self, stack=[], lim=None): self._stack = stack self._lim = lim def push(self, data): if self._lim is not None and len(self._stack) == self._lim: print("~~STACK OVERFLOW~~") return self._stack.append(int(data)) def pop(self):...
class Stack: def __init__(self, stack=[], lim=None): self._stack = stack self._lim = lim def push(self, data): if self._lim is not None and len(self._stack) == self._lim: print('~~STACK OVERFLOW~~') return self._stack.append(int(data)) def pop(self)...
### Code is based on PySimpleAutomata (https://github.com/Oneiroe/PySimpleAutomata/) # MIT License # Copyright (c) 2017 Alessio Cecconi # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software with...
def _epsilon_closure(states, epsilon, transitions): new_states = states while new_states: curr_states = set() for state in new_states: curr_states.update(transitions.get(state, {}).get(epsilon, set())) new_states = curr_states - states states.update(curr_states) def ...
def ab(b): c=input("Term To Be Search:") if c in b: print ("Term Found") else: print ("Term Not Found") a=[] while True: b=input("Enter Term(To terminate type Exit):") if b=='Exit' or b=='exit': break else: a.append(b) ab(a)
def ab(b): c = input('Term To Be Search:') if c in b: print('Term Found') else: print('Term Not Found') a = [] while True: b = input('Enter Term(To terminate type Exit):') if b == 'Exit' or b == 'exit': break else: a.append(b) ab(a)
n = int(input()) def weird(n): string = str(n) while n != 1: if n%2 == 0: n = n//2 string += ' ' + str(n) else: n = n*3 + 1 string += ' ' + str(n) return string print(weird(n))
n = int(input()) def weird(n): string = str(n) while n != 1: if n % 2 == 0: n = n // 2 string += ' ' + str(n) else: n = n * 3 + 1 string += ' ' + str(n) return string print(weird(n))
PRICES = [0.01, 0.02, 0.05, 0.10, 0.20, 0.50, 1, 2] QUESTIONS = [ "Voer het aantal 1 centen in:\n", "Voer het aantal 2 centen in: \n", "Voer het aantal 5 centen in: \n", "Voer het aantal 10 centen in: \n", "Voer het aantal 20 centen in: \n"...
prices = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2] questions = ['Voer het aantal 1 centen in:\n', 'Voer het aantal 2 centen in: \n', 'Voer het aantal 5 centen in: \n', 'Voer het aantal 10 centen in: \n', 'Voer het aantal 20 centen in: \n', 'Voer het aantal 50 centen in: \n', "Voer het aantal 1 euro's in: \n", "Voer het a...
spec = { 'name' : "The devil's work...", 'external network name' : "exnet3", 'keypair' : "openstack_rsa", 'controller' : "r720", 'dns' : "10.30.65.200", 'credentials' : { 'user' : "nic", 'password' : "nic", 'project' : "nic" }, 'Networks' : [ { 'name' : "merlynctl" , "start": "172.1...
spec = {'name': "The devil's work...", 'external network name': 'exnet3', 'keypair': 'openstack_rsa', 'controller': 'r720', 'dns': '10.30.65.200', 'credentials': {'user': 'nic', 'password': 'nic', 'project': 'nic'}, 'Networks': [{'name': 'merlynctl', 'start': '172.16.1.2', 'end': '172.16.1.100', 'subnet': ' 172.16.1.0/...
# coding: utf-8 # fields names BITMAP = 'bitmap' COLS = 'cols' DATA = 'data' EXTERIOR = 'exterior' INTERIOR = 'interior' MULTICHANNEL_BITMAP = 'multichannel_bitmap' ORIGIN = 'origin' POINTS = 'points' ROWS = 'rows' TYPE = 'type' NODES = 'nodes' EDGES = 'edges' ENABLED = 'enabled' LABEL = 'label' COLOR = 'color' TEMPL...
bitmap = 'bitmap' cols = 'cols' data = 'data' exterior = 'exterior' interior = 'interior' multichannel_bitmap = 'multichannel_bitmap' origin = 'origin' points = 'points' rows = 'rows' type = 'type' nodes = 'nodes' edges = 'edges' enabled = 'enabled' label = 'label' color = 'color' template = 'template' location = 'loca...
# Data taken from the MathML 2.0 reference data = ''' "(" form="prefix" fence="true" stretchy="true" lspace="0em" rspace="0em" ")" form="postfix" fence="true" stretchy="true" lspace="0em" rspace="0em" "[" form="prefix...
data = '\n\n"(" form="prefix" fence="true" stretchy="true" lspace="0em" rspace="0em"\n")" form="postfix" fence="true" stretchy="true" lspace="0em" rspace="0em"\n"[" form="prefix" fence="true" stretchy="true" lspace="...
# -*- coding: utf-8 -*- # User role USER = 0 ADMIN = 1 USER_ROLE = { ADMIN: 'admin', USER: 'user', } # User status INACTIVE = 0 ACTIVE = 1 USER_STATUS = { INACTIVE: 'inactive', ACTIVE: 'active', } # Project progress PR_CHALLENGE = -1 PR_NEW = 0 PR_RESEARCHED = 10 PR_SKETCHED = 20 PR_PROTOTYPED = 30 P...
user = 0 admin = 1 user_role = {ADMIN: 'admin', USER: 'user'} inactive = 0 active = 1 user_status = {INACTIVE: 'inactive', ACTIVE: 'active'} pr_challenge = -1 pr_new = 0 pr_researched = 10 pr_sketched = 20 pr_prototyped = 30 pr_launched = 40 pr_live = 50 project_progress = {PR_CHALLENGE: 'This is an idea or challenge d...
""" This script allows you to hijack http/https networks. Before you start use this commands on Kali machine 1. Enable ip forwarding: echo 1 > /proc/sys/net/ipv4/ip_forward 2. Activate your packets Queues - If want to test on your machine: iptables -I OUTPUT -j NFQUEUE --queue-num 0;iptables -I INPUT -j NFQUEUE --q...
""" This script allows you to hijack http/https networks. Before you start use this commands on Kali machine 1. Enable ip forwarding: echo 1 > /proc/sys/net/ipv4/ip_forward 2. Activate your packets Queues - If want to test on your machine: iptables -I OUTPUT -j NFQUEUE --queue-num 0;iptables -I INPUT -j NFQUEUE --q...
q = int(input()) e = str(input()).split() indq = 0 mini = int(e[0]) for i in range(1, len(e)): if int(e[i]) > mini: mini = int(e[i]) elif int(e[i]) < mini: indq = i + 1 break print(indq)
q = int(input()) e = str(input()).split() indq = 0 mini = int(e[0]) for i in range(1, len(e)): if int(e[i]) > mini: mini = int(e[i]) elif int(e[i]) < mini: indq = i + 1 break print(indq)
__version__ = "1.8.0" __all__ = ["epsonprinter","testpage"]
__version__ = '1.8.0' __all__ = ['epsonprinter', 'testpage']
class RequestExeption(Exception): def __init__(self, request): self.request = request def badRequest(self): self.message = "bad request url : %s" % self.request.url return self def __str__(self): return self.message
class Requestexeption(Exception): def __init__(self, request): self.request = request def bad_request(self): self.message = 'bad request url : %s' % self.request.url return self def __str__(self): return self.message
class Solution: def dieSimulator(self, n: int, rollMax: List[int]) -> int: # dp[i][j]: how many choices we have with i dices and the last face is j # again dp[i][j] means the number of distinct sequences that can be obtained when rolling i times and ending with j MOD = 10 ** 9 + 7 dp...
class Solution: def die_simulator(self, n: int, rollMax: List[int]) -> int: mod = 10 ** 9 + 7 dp = [[0] * 7 for i in range(n + 1)] for i in range(6): dp[1][i] = 1 dp[1][6] = 6 for i in range(2, n + 1): total = 0 for j in range(6): ...
n1 = int(input('Digite um valor: ')) n2 = int(input('Digite um valor: ')) n3 = int(input('Digite um valor: ')) menor = n1 maior = n2 if n2 < n1 and n2 < 3: menor = n2 if n3 < n1 and n3 < n2: menor = n3 if n1 > n2 and n1 > n3: maior = n1 if n3 > n1 and n3 > n2: maior = n3 print(f'O maior valor digitado f...
n1 = int(input('Digite um valor: ')) n2 = int(input('Digite um valor: ')) n3 = int(input('Digite um valor: ')) menor = n1 maior = n2 if n2 < n1 and n2 < 3: menor = n2 if n3 < n1 and n3 < n2: menor = n3 if n1 > n2 and n1 > n3: maior = n1 if n3 > n1 and n3 > n2: maior = n3 print(f'O maior valor digitado f...
# a = ['a1','aa1','a2','aaa1'] # a.sort() # print(a) # print(2346/10) def repeat_to_length(string_to_expand, length): return (string_to_expand * (int(length/len(string_to_expand))+1))[:length] for i in range(200): if i > 10: strnum = str(i) tens = int(strnum[0:-1]) last = strnum[-1] ...
def repeat_to_length(string_to_expand, length): return (string_to_expand * (int(length / len(string_to_expand)) + 1))[:length] for i in range(200): if i > 10: strnum = str(i) tens = int(strnum[0:-1]) last = strnum[-1] print(strnum) print(tens) print(repeat_to_leng...
''' Given a binary string s (a string consisting only of '0's and '1's), we can split s into 3 non-empty strings s1, s2, s3 (s1+ s2+ s3 = s). Return the number of ways s can be split such that the number of characters '1' is the same in s1, s2, and s3. Since the answer may be too large, return it modulo 10^9 + 7. ...
""" Given a binary string s (a string consisting only of '0's and '1's), we can split s into 3 non-empty strings s1, s2, s3 (s1+ s2+ s3 = s). Return the number of ways s can be split such that the number of characters '1' is the same in s1, s2, and s3. Since the answer may be too large, return it modulo 10^9 + 7. ...
arr = [2,3,5,8,1,8,0,9,11, 23, 51] num = 0 def searchElement(arr, num): n = len(arr) for i in range(n): if arr[i] == num: print("From if block") return i elif arr[n-1] == num: print("From else if block") return n-1 n-=1 print(searchElement...
arr = [2, 3, 5, 8, 1, 8, 0, 9, 11, 23, 51] num = 0 def search_element(arr, num): n = len(arr) for i in range(n): if arr[i] == num: print('From if block') return i elif arr[n - 1] == num: print('From else if block') return n - 1 n -= 1 prin...
class MidiProtocol: NON_REAL_TIME_HEADER = 0x7E GENERAL_SYSTEM_INFORMATION = 0x06 DEVICE_IDENTITY_REQUEST = 0x01 @staticmethod def device_identify_request(target=0x00): TARGET_ID = target SUB_ID_1 = MidiProtocol.GENERAL_SYSTEM_INFORMATION SUB_ID_2 = MidiProtocol.DEVICE_IDE...
class Midiprotocol: non_real_time_header = 126 general_system_information = 6 device_identity_request = 1 @staticmethod def device_identify_request(target=0): target_id = target sub_id_1 = MidiProtocol.GENERAL_SYSTEM_INFORMATION sub_id_2 = MidiProtocol.DEVICE_IDENTITY_REQUES...
"""Exceptions raised by flowpipe.""" class CycleError(Exception): """Raised when an action would result in a cycle in a graph."""
"""Exceptions raised by flowpipe.""" class Cycleerror(Exception): """Raised when an action would result in a cycle in a graph."""
def get_chunks(start, value): for each in range(start, 2000000001, value): yield range(each, each+value) def sum_xor_n(value): mod_value = value&3 if mod_value == 3: return 0 elif mod_value == 2: return value+1 elif mod_value == 1: return 1 elif mod_value == 0: ...
def get_chunks(start, value): for each in range(start, 2000000001, value): yield range(each, each + value) def sum_xor_n(value): mod_value = value & 3 if mod_value == 3: return 0 elif mod_value == 2: return value + 1 elif mod_value == 1: return 1 elif mod_value =...
#! /usr/bin/python # -*- coding: utf-8 -*- VER_MAIN = '3' VER_SUB = '5' BUILD_SN = '160809'
ver_main = '3' ver_sub = '5' build_sn = '160809'
#4-9 Cube Comprehension numberscube = [value ** 3 for value in range(1, 11)] print(numberscube)
numberscube = [value ** 3 for value in range(1, 11)] print(numberscube)
#coding:utf-8 while True: l_c = input().split() x1 = int(l_c[0]) y1 = int(l_c[1]) x2 = int(l_c[2]) y2 = int(l_c[3]) if x1+x2+y1+y2 == 0: break else: if (x1 == x2 and y1 == y2): print(0) elif ((x2-x1) == -(y2-y1) or -(x2-x1) == -(y2-y1)): ...
while True: l_c = input().split() x1 = int(l_c[0]) y1 = int(l_c[1]) x2 = int(l_c[2]) y2 = int(l_c[3]) if x1 + x2 + y1 + y2 == 0: break elif x1 == x2 and y1 == y2: print(0) elif x2 - x1 == -(y2 - y1) or -(x2 - x1) == -(y2 - y1): print(1) elif -(x2 - x1) == y2 -...
# Definition for a binary tree node. # class Node(object): # def __init__(self, val=" ", left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def expTree(self, s: str) -> 'Node': def process_op(): op = op_stack.pop() ...
class Solution: def exp_tree(self, s: str) -> 'Node': def process_op(): op = op_stack.pop() rhs = val_stack.pop() lhs = val_stack.pop() node = node(val=op, left=lhs, right=rhs) val_stack.append(node) def priority(op): if op i...
# Practice problem 1 for chapter 4 # Function that takes an array and returns a comma-separated string def make_string(array): answer_string = "" for i in array: if array.index(i) == 0: answer_string += str(i) # Last index word finishes with "and" before it elif array.index(...
def make_string(array): answer_string = '' for i in array: if array.index(i) == 0: answer_string += str(i) elif array.index(i) == len(array) - 1: answer_string += ', and ' + str(i) else: answer_string += ', ' + str(i) print(answer_string) my_arr = ...
class RCListener: def __iter__(self): raise NotImplementedError() class Source: def listener(self, *args, **kwargs): raise NotImplementedError() def query(self, start, end, *args, types=None, **kwargs): raise NotImplementedError()
class Rclistener: def __iter__(self): raise not_implemented_error() class Source: def listener(self, *args, **kwargs): raise not_implemented_error() def query(self, start, end, *args, types=None, **kwargs): raise not_implemented_error()
class DataGridEditingUnit(Enum, IComparable, IFormattable, IConvertible): """ Defines constants that specify whether editing is enabled on a cell level or on a row level. enum DataGridEditingUnit,values: Cell (0),Row (1) """ def __eq__(self, *args): """ x.__eq__(y) <==> x==yx.__eq__(y)...
class Datagrideditingunit(Enum, IComparable, IFormattable, IConvertible): """ Defines constants that specify whether editing is enabled on a cell level or on a row level. enum DataGridEditingUnit,values: Cell (0),Row (1) """ def __eq__(self, *args): """ x.__eq__(y) <==> x==yx.__eq__(y) <==> x==y...
for _ in range(int(input())): n,q = [int(x) for x in input().split()] a = [int(x) for x in input().split()] for _ in range(q): k = int(input()) sum = 0 # if(k == 0):k = 1 for i in range(0,n,k + 1): sum += a[i] print(sum)
for _ in range(int(input())): (n, q) = [int(x) for x in input().split()] a = [int(x) for x in input().split()] for _ in range(q): k = int(input()) sum = 0 for i in range(0, n, k + 1): sum += a[i] print(sum)
def front_back(s): if len(s) > 1: string = [s[-1]] string.extend([i for i in s[1:-1]]) string.append(s[0]) return "".join(string) else: return s
def front_back(s): if len(s) > 1: string = [s[-1]] string.extend([i for i in s[1:-1]]) string.append(s[0]) return ''.join(string) else: return s
# twitter api data (replace yours here given are placeholder) # if you have not yet, go for applying at: https://developer.twitter.com/ TWITTER_KEY="" TWITTER_SECRET="" TWITTER_APP_KEY="" TWITTER_APP_SECRET="" with open("twitter_keys.txt") as f: for line in f: tups=line.strip().split("=") if tups[0] == "TWITTER_...
twitter_key = '' twitter_secret = '' twitter_app_key = '' twitter_app_secret = '' with open('twitter_keys.txt') as f: for line in f: tups = line.strip().split('=') if tups[0] == 'TWITTER_KEY': twitter_key = tups[1] elif tups[0] == 'TWITTER_SECRET': twitter_secret = tu...
def maximum_subarray_1(coll): n = len(coll) max_result = 0 for i in xrange(1, n+1): for j in range(n-i+1): result = sum(coll[j: j+i]) if max_result < result: max_result = result return max_result def maximum_subarray_2(coll): n = len(coll) max_...
def maximum_subarray_1(coll): n = len(coll) max_result = 0 for i in xrange(1, n + 1): for j in range(n - i + 1): result = sum(coll[j:j + i]) if max_result < result: max_result = result return max_result def maximum_subarray_2(coll): n = len(coll) ...
lines = [] for i in xrange(3): line = Line() line.xValues = xrange(5) line.yValues = [(i+1 / 2.0) * pow(x, i+1) for x in line.xValues] line.label = "Line %d" % (i + 1) lines.append(line) plot = Plot() plot.add(lines[0]) inset = Plot() inset.add(lines[1]) inset.hideTickLabels(...
lines = [] for i in xrange(3): line = line() line.xValues = xrange(5) line.yValues = [(i + 1 / 2.0) * pow(x, i + 1) for x in line.xValues] line.label = 'Line %d' % (i + 1) lines.append(line) plot = plot() plot.add(lines[0]) inset = plot() inset.add(lines[1]) inset.hideTickLabels() inset.title = 'Ins...
file = open('csv_data.txt', 'r') lines = file.readlines() file.close() lines = [line.strip() for line in lines[1:]] for line in lines: person_data = line.split(',') name = person_data[0].title() age = person_data[1] university = person_data[2].title() degree = person_data[3].capitalize() prin...
file = open('csv_data.txt', 'r') lines = file.readlines() file.close() lines = [line.strip() for line in lines[1:]] for line in lines: person_data = line.split(',') name = person_data[0].title() age = person_data[1] university = person_data[2].title() degree = person_data[3].capitalize() print(f...
"""Top-level package for BioCyc and BRENDA in Python.""" __author__ = """Yi Zhou""" __email__ = 'zhou.zy.yi@gmail.com' __version__ = '0.1.0'
"""Top-level package for BioCyc and BRENDA in Python.""" __author__ = 'Yi Zhou' __email__ = 'zhou.zy.yi@gmail.com' __version__ = '0.1.0'
def media(n1, n2): m = (n1 + n2)/2 return m print(media(n1=10, n2=5)) def juros(preco, juros): res = preco * (1 + juros/100) return res print(juros(preco=10, juros=50))
def media(n1, n2): m = (n1 + n2) / 2 return m print(media(n1=10, n2=5)) def juros(preco, juros): res = preco * (1 + juros / 100) return res print(juros(preco=10, juros=50))
"""Multiply two arbitrary-precision integers. - [EPI: 5.3]. """ def multiply(num1, num2): sign = -1 if (num1[0] < 0) ^ (num2[0] < 0) else 1 num1[0], num2[0] = abs(num1[0]), abs(num2[0]) result = [0] * (len(num1) + len(num2)) for i in reversed(range(len(num1))): for j in reversed(range(len(nu...
"""Multiply two arbitrary-precision integers. - [EPI: 5.3]. """ def multiply(num1, num2): sign = -1 if (num1[0] < 0) ^ (num2[0] < 0) else 1 (num1[0], num2[0]) = (abs(num1[0]), abs(num2[0])) result = [0] * (len(num1) + len(num2)) for i in reversed(range(len(num1))): for j in reversed(range(len(n...
def test_session_interruption(ui, ui_interrupted_session): ui_interrupted_session.click() interrupted_test = ui.driver.find_element_by_css_selector('.item.test') css_classes = interrupted_test.get_attribute('class') assert 'success' not in css_classes assert 'fail' not in css_classes interrupted...
def test_session_interruption(ui, ui_interrupted_session): ui_interrupted_session.click() interrupted_test = ui.driver.find_element_by_css_selector('.item.test') css_classes = interrupted_test.get_attribute('class') assert 'success' not in css_classes assert 'fail' not in css_classes interrupted...
# 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 sortedArrayToBST(self, nums): return self.recurse(nums,0,len(nums)-1) def recurse(self,nums,start,en...
class Treenode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def sorted_array_to_bst(self, nums): return self.recurse(nums, 0, len(nums) - 1) def recurse(self, nums, start, end): if end < star...
"""Helper function to save serializer""" def save_serializer(serializer): """returns a particular response for when serializer passed is valid or not""" serializer.save() data = { "status": "success", "data": serializer.data } return data
"""Helper function to save serializer""" def save_serializer(serializer): """returns a particular response for when serializer passed is valid or not""" serializer.save() data = {'status': 'success', 'data': serializer.data} return data
Vivaldi = Goalkeeper('Juan Vivaldi', 83, 77, 72, 82) Peillat = Outfield_Player('Gonzalo Peillat', 'DF', 70, 89, 78, 73, 79, 67) Ortiz = Outfield_Player('Ignacio Ortiz', 'MF', 79, 78, 77, 80, 75, 81) Rey = Outfield_Player('Matias Rey', 'MF', 81, 77, 74, 72, 87, 72) Vila = Outfield_Player('Lucas Vila', 'FW', 87, 50, ...
vivaldi = goalkeeper('Juan Vivaldi', 83, 77, 72, 82) peillat = outfield__player('Gonzalo Peillat', 'DF', 70, 89, 78, 73, 79, 67) ortiz = outfield__player('Ignacio Ortiz', 'MF', 79, 78, 77, 80, 75, 81) rey = outfield__player('Matias Rey', 'MF', 81, 77, 74, 72, 87, 72) vila = outfield__player('Lucas Vila', 'FW', 87, 50, ...
def factorial(x): '''calculo de factorial con una funcion recursiva''' if x == 1: return 1 else: return (x * factorial(x-1)) num = 928 print('el factorial de: ', num ,'is ', factorial(num))
def factorial(x): """calculo de factorial con una funcion recursiva""" if x == 1: return 1 else: return x * factorial(x - 1) num = 928 print('el factorial de: ', num, 'is ', factorial(num))
# prompting user to enter the file name fname = input('Enter file name: ') d = dict() # catching exceptions try: fhand = open(fname) except: print('File does not exist') exit() # reading the lines in the file for line in fhand: words = line.split() # we only want email addresses if ...
fname = input('Enter file name: ') d = dict() try: fhand = open(fname) except: print('File does not exist') exit() for line in fhand: words = line.split() if len(words) < 2 or words[0] != 'From': continue else: d[words[1]] = d.get(words[1], 0) + 1 print(d)
# Copyright 2014 Google Inc. # # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'skia_warnings_as_errors': 0, }, 'targets': [ { 'target_name': 'libpng', 'type': 'none', 'conditions': [ [ 'skia_android_framewor...
{'variables': {'skia_warnings_as_errors': 0}, 'targets': [{'target_name': 'libpng', 'type': 'none', 'conditions': [['skia_android_framework', {'dependencies': ['android_deps.gyp:png'], 'export_dependent_settings': ['android_deps.gyp:png']}, {'dependencies': ['libpng.gyp:libpng_static'], 'export_dependent_settings': ['l...
_base_ = "./common_base.py" # ----------------------------------------------------------------------------- # base model cfg for gdrn # ----------------------------------------------------------------------------- MODEL = dict( DEVICE="cuda", WEIGHTS="", # PIXEL_MEAN = [103.530, 116.280, 123.675] # bgr ...
_base_ = './common_base.py' model = dict(DEVICE='cuda', WEIGHTS='', PIXEL_MEAN=[0, 0, 0], PIXEL_STD=[255.0, 255.0, 255.0], LOAD_DETS_TEST=False, CDPN=dict(NAME='GDRN', TASK='rot', USE_MTL=False, BACKBONE=dict(PRETRAINED='torchvision://resnet34', ARCH='resnet', NUM_LAYERS=34, INPUT_CHANNEL=3, INPUT_RES=256, OUTPUT_RES=6...
#This app does your math addition = input("Print your math sign, +, -, *, /: ") if addition == "+": a = int(input("First Number: ")) b = int(input("Seccond Number: ")) c = a + b print(c) elif addition == "-": a = int(input("First Number: ")) b = int(input("Seccond Number: ")) c = a - b ...
addition = input('Print your math sign, +, -, *, /: ') if addition == '+': a = int(input('First Number: ')) b = int(input('Seccond Number: ')) c = a + b print(c) elif addition == '-': a = int(input('First Number: ')) b = int(input('Seccond Number: ')) c = a - b print(c) elif addition == ...
class Solution: def sequentialDigits(self, low: int, high: int) -> List[int]: sequence, base, result = '123456789', 10, [] for length in range(len(str(low)), len(str(high)) + 1): for start in range(base - length): number = int(sequence[start : start + length]) ...
class Solution: def sequential_digits(self, low: int, high: int) -> List[int]: (sequence, base, result) = ('123456789', 10, []) for length in range(len(str(low)), len(str(high)) + 1): for start in range(base - length): number = int(sequence[start:start + length]) ...
# -*- coding: utf-8 -*- def range(start, stop, step=1.): """Replacement for built-in range function. :param start: Starting value. :type start: number :param stop: End value. :type stop: number :param step: Step size. :type step: number :returns: List of values from `start` to `stop` in...
def range(start, stop, step=1.0): """Replacement for built-in range function. :param start: Starting value. :type start: number :param stop: End value. :type stop: number :param step: Step size. :type step: number :returns: List of values from `start` to `stop` incremented by `size`. ...
class Solution(object): def largestRectangleArea1(self, heights): """ :type heights: List[int] :rtype: int """ self.ans = float('-inf') def recurse(heights, l, r): if l > r: return 0 min_idx = l # index r is inclu...
class Solution(object): def largest_rectangle_area1(self, heights): """ :type heights: List[int] :rtype: int """ self.ans = float('-inf') def recurse(heights, l, r): if l > r: return 0 min_idx = l for i in range(l,...
class PaceMaker(): """ Class for a server that distributes the anonymized and hashed contact traces. Attributes: connected_peers = []: List of peers to communicate with. trace_buffer = {area: hashed_events}: Temporarily stored hashed events. """ def receive_hashed_trace(se...
class Pacemaker: """ Class for a server that distributes the anonymized and hashed contact traces. Attributes: connected_peers = []: List of peers to communicate with. trace_buffer = {area: hashed_events}: Temporarily stored hashed events. """ def receive_hashed_trace(self, ...
while True: try: comprimento, eventos = [int(x) for x in input().split()] except EOFError: break lucro, utilizado, estacionamento = 0, 0, {} # 'veic' : tamanho for aux in range(0, eventos): evento = input().split(' ') if len(evento) == 3: # entrada veic if c...
while True: try: (comprimento, eventos) = [int(x) for x in input().split()] except EOFError: break (lucro, utilizado, estacionamento) = (0, 0, {}) for aux in range(0, eventos): evento = input().split(' ') if len(evento) == 3: if comprimento >= utilizado + int(...
class EmbeddedDocumentMixin: _fields = {} _db_name_map = {} _dirty_fields = {} def __init__(self, **kwargs): self._values = {} for name, value in kwargs.items(): if name in self._fields: setattr(self, name, value) self._make_clean() def to_mongo(...
class Embeddeddocumentmixin: _fields = {} _db_name_map = {} _dirty_fields = {} def __init__(self, **kwargs): self._values = {} for (name, value) in kwargs.items(): if name in self._fields: setattr(self, name, value) self._make_clean() def to_mong...
with open("input.txt", "r") as input_file: input = input_file.read().split("\n") total = 0 group_answers = {} for line in input: if not line: total += len(group_answers) group_answers = {} for char in line: group_answers[char] = 1 total += len(group_answers) print(total)
with open('input.txt', 'r') as input_file: input = input_file.read().split('\n') total = 0 group_answers = {} for line in input: if not line: total += len(group_answers) group_answers = {} for char in line: group_answers[char] = 1 total += len(group_answers) print(total)
class Solution: def calPoints(self, ops): """ :type ops: List[str] :rtype: int """ opsstack = [] point = 0 for o in ops: p = 0 if o == '+': p = opsstack[-1] + opsstack[-2] point += p opss...
class Solution: def cal_points(self, ops): """ :type ops: List[str] :rtype: int """ opsstack = [] point = 0 for o in ops: p = 0 if o == '+': p = opsstack[-1] + opsstack[-2] point += p ops...
# This file is implements of 'The elements of computer systesm' # chap 6.Assembler # author:gongqingkui AT 126.com # date:2021-09-18 jumpTable = { 'null': '000', 'JGT': '001', 'JEQ': '010', 'JGE': '011', 'JLT': '100', 'JNE': '101', 'JLE': '110', 'JMP': '111'} compTable = { # a = 0 ...
jump_table = {'null': '000', 'JGT': '001', 'JEQ': '010', 'JGE': '011', 'JLT': '100', 'JNE': '101', 'JLE': '110', 'JMP': '111'} comp_table = {'0': '0101010', '1': '0111111', '-1': '0111010', 'D': '0001100', 'A': '0110000', '!D': '0001101', '!A': '0110001', '-D': '0001111', '-A': '0110011', 'D+1': '0011111', 'A+1': '0110...
# -*- encoding: utf-8 -*- ''' __author__ = "Larry_Pavanery ''' class User(object): def __init__(self, id, url_keys=[]): self.id = id self.url_keys = url_keys
""" __author__ = "Larry_Pavanery """ class User(object): def __init__(self, id, url_keys=[]): self.id = id self.url_keys = url_keys
def vmax(lista): n = 0 for c in range(len(lista)): for i in range(len(lista)): if lista[i] > lista[c]: n = i return n freq = [] num = int(input()) lista = list(range(2, num + 1)) n = num n_1 = 0 c = 0 while True: print(n_1) if n_1 <= len(lista) - 1: if n...
def vmax(lista): n = 0 for c in range(len(lista)): for i in range(len(lista)): if lista[i] > lista[c]: n = i return n freq = [] num = int(input()) lista = list(range(2, num + 1)) n = num n_1 = 0 c = 0 while True: print(n_1) if n_1 <= len(lista) - 1: if n %...
mp = 'Today is a Great DAY' print(mp.lower()) print(mp.upper()) print(mp.strip()) print(mp.startswith('w')) print(mp.find('a'))
mp = 'Today is a Great DAY' print(mp.lower()) print(mp.upper()) print(mp.strip()) print(mp.startswith('w')) print(mp.find('a'))
""" Trie tree. """ class TrieNode: def __init__(self, data: str): self.data = data self.children = [None] * 26 self.is_ending_char = False class TrieTree: def __init__(self): self._root = TrieNode('/') def insert(self, word: str) -> None: p = self._root ...
""" Trie tree. """ class Trienode: def __init__(self, data: str): self.data = data self.children = [None] * 26 self.is_ending_char = False class Trietree: def __init__(self): self._root = trie_node('/') def insert(self, word: str) -> None: p = self._root ...
#!/usr/bin/env python3 class Node(object): """Node class for binary tree""" def __init__(self, data=None): self.left = None self.right = None self.data = data class Tree(object): """Tree class for binary search""" def __init__(self, data=None): self.root = Node(data) ...
class Node(object): """Node class for binary tree""" def __init__(self, data=None): self.left = None self.right = None self.data = data class Tree(object): """Tree class for binary search""" def __init__(self, data=None): self.root = node(data) def insert(self, da...
# Copyright 2017 The Switch Authors. All rights reserved. # Licensed under the Apache License, Version 2, which is in the LICENSE file. """ This package implements a transport model for the transmission network. The core modules in the package are build and dispatch. """ core_modules = [ 'switch_model.transmiss...
""" This package implements a transport model for the transmission network. The core modules in the package are build and dispatch. """ core_modules = ['switch_model.transmission.transport.build', 'switch_model.transmission.transport.dispatch']
# Programa que le a altura de uma parede em metros # e calcule a sua area e a quantidade de tinta necessaria # para pinta-la, sabendo que cada litro de tinta, pinta uma area # de 2m^2 larg = float(input('Digite a largura da parede: ')) alt = float(input('Digite a altura da parede: ')) area = larg * alt tinta = area / ...
larg = float(input('Digite a largura da parede: ')) alt = float(input('Digite a altura da parede: ')) area = larg * alt tinta = area / 2 print('A parede tem {}{}{} metros quadrados e para pintar essa parede precisaremos de {} litros de tintas'.format('\x1b[1;107m', area, '\x1b[m', tinta))
#----------* CHALLENGE 37 *---------- #Ask the user to enter their name and display each letter in their name on a separate line. name = input("Enter your name: ") for i in name: print(i)
name = input('Enter your name: ') for i in name: print(i)
class Camera(object): def __init__(self, macaddress, lastsnap='snaps/default.jpg'): self.macaddress = macaddress self.lastsnap = lastsnap
class Camera(object): def __init__(self, macaddress, lastsnap='snaps/default.jpg'): self.macaddress = macaddress self.lastsnap = lastsnap
# coding: utf-8 strings = ['KjgWZC', 'arf12', ''] for s in strings: if s.isalpha(): print("The string " + s + " consists of all letters.") else: print("The string " + s + " does not consist of all letters.")
strings = ['KjgWZC', 'arf12', ''] for s in strings: if s.isalpha(): print('The string ' + s + ' consists of all letters.') else: print('The string ' + s + ' does not consist of all letters.')
''' In order to get the Learn credentials, they do not to open a case on behind the blackboard nor email developers@blackboard.com. They need to go to developer.blackboard.com and register from there to grab the Learn credentials for their application, it is also imperative to remind them that they are creating an app...
""" In order to get the Learn credentials, they do not to open a case on behind the blackboard nor email developers@blackboard.com. They need to go to developer.blackboard.com and register from there to grab the Learn credentials for their application, it is also imperative to remind them that they are creating an app...
""" Frozen subpackages for meta release. """ frozen_packages = { "libpysal": "4.2.2", "esda": "2.2.1", "giddy": "2.3.0", "inequality": "1.0.0", "pointpats": "2.1.0", "segregation": "1.2.0", "spaghetti": "1.4.1", "mgwr": "2.1.1", "spglm": "1.0.7", "spint": "1.0.6", "spreg": "1...
""" Frozen subpackages for meta release. """ frozen_packages = {'libpysal': '4.2.2', 'esda': '2.2.1', 'giddy': '2.3.0', 'inequality': '1.0.0', 'pointpats': '2.1.0', 'segregation': '1.2.0', 'spaghetti': '1.4.1', 'mgwr': '2.1.1', 'spglm': '1.0.7', 'spint': '1.0.6', 'spreg': '1.0.4', 'spvcm': '0.3.0', 'tobler': '0.2.0', '...
class CardError(Exception): pass class IssuerNotRecognised(CardError): pass class InvalidCardNumber(CardError): pass
class Carderror(Exception): pass class Issuernotrecognised(CardError): pass class Invalidcardnumber(CardError): pass
def Wspak(dane): for i in range(len(dane)-1, -1, -1): yield dane[i] tablica = Wspak([1, 2, 3]) print('tablica [1, 2, 3]', end=' ') print('[', end='') print(next(tablica), end=', ') print(next(tablica), end=', ') print(next(tablica), end=']') print()
def wspak(dane): for i in range(len(dane) - 1, -1, -1): yield dane[i] tablica = wspak([1, 2, 3]) print('tablica [1, 2, 3]', end=' ') print('[', end='') print(next(tablica), end=', ') print(next(tablica), end=', ') print(next(tablica), end=']') print()
class Solution: def getHint(self, secret, guess): ss, gs = {str(x): 0 for x in range(10)}, {str(x): 0 for x in range(10)} A = 0 for s, g in zip(secret, guess): if s == g: A += 1 ss[s] += 1 gs[g] += 1 ans = 0 for k, v in ss.items(): ...
class Solution: def get_hint(self, secret, guess): (ss, gs) = ({str(x): 0 for x in range(10)}, {str(x): 0 for x in range(10)}) a = 0 for (s, g) in zip(secret, guess): if s == g: a += 1 ss[s] += 1 gs[g] += 1 ans = 0 for (k, ...
class Sample: def __init__(self, source=None, data=None, history=None, uid=None): if history is not None: self.history = history elif source is not None: self.history = [("init", "", source)] else: self.history = [] if data is not None: ...
class Sample: def __init__(self, source=None, data=None, history=None, uid=None): if history is not None: self.history = history elif source is not None: self.history = [('init', '', source)] else: self.history = [] if data is not None: ...
# class Solution: # # @param A : integer # # @return a strings def findDigitsInBinary(self, A): res = "" while(A != 0): temp = A%2 res += str(temp) A = A//2 res = res[::-1] return res print(findDigitsInBinary(6))
def find_digits_in_binary(self, A): res = '' while A != 0: temp = A % 2 res += str(temp) a = A // 2 res = res[::-1] return res print(find_digits_in_binary(6))
class Solution(object): def minimumSum(self, num): """ :type num: int :rtype: int """ num = list(str(num)) min_sum = 9999 for i in range(3): s1 = int(num[i] + num[i + 1]) + int(num[i - 2] + num[i - 1]) s2 = int(num[i] + num[i + 1]) + in...
class Solution(object): def minimum_sum(self, num): """ :type num: int :rtype: int """ num = list(str(num)) min_sum = 9999 for i in range(3): s1 = int(num[i] + num[i + 1]) + int(num[i - 2] + num[i - 1]) s2 = int(num[i] + num[i + 1]) + ...
#!python class Node(object): def __init__(self, data): """Initialize this node with the given data""" self.data = data self.prev = None self.next = None def __repr__(self): """Return a string representation of this node""" return 'Node({!r})'.format(self.da...
class Node(object): def __init__(self, data): """Initialize this node with the given data""" self.data = data self.prev = None self.next = None def __repr__(self): """Return a string representation of this node""" return 'Node({!r})'.format(self.data) class Dou...