content
stringlengths
7
1.05M
#!/usr/bin/env python3 def proc(x): print(x) x = proc("testing 1, 2, 3...") print("below is x: ") print(x) print("above is x: ")
GET_POWER_FLOW_REALTIME_DATA = { 'timestamp': { 'value': '2019-01-10T23:33:12+01:00' }, 'status': { 'Code': 0, 'Reason': '', 'UserMessage': '' }, 'energy_day': { 'value': 0, 'unit': 'Wh' }, 'energy_total': { 'value': 26213502, '...
""" Problem 4. The greatest common divisor of two positive integers is the largest integer that divides each of them without remainder. For example: gcd(2, 12) = 2 gcd(6, 12) = 6 gcd(9, 12) = 3 gcd(17, 12) = 1 Write an iterative function, gcdIter(a, b), that implements this idea. One easy way to do this i...
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ Python implementation of BlastLine, an alternative Cython implementation is available in .cblast.BlastLine, which may be up to 2x faster """ class BlastLine(object): __slots__ = ('query', 'subject', 'pctid', 'hitlen', 'nmismatch', 'ngaps', \ 'qsta...
#while True: # print("Ahoj") a = 0 while a < 5: a = int(input("Zadej číslo od 5 výše: ")) print(a) a = 0 while True: a = int(input("Zadej číslo od 5 výše: ")) if a >= 5: break print(a) # (a >= 0 and a <= 5) or a == 10
try: numberEight=8 print(numberEight/0) print("没有出现异常,一切顺利") except ZeroDivisionError: print("这是一个除零错误")
# # PySNMP MIB module Wellfleet-CONSOLE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-CONSOLE-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:39:44 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
##Q1 def sumOfDigits(String): sumNumber=0 for i in range(0,len(String)): if String[i].isdigit(): sumNumber=sumNumber+int(String[i]) return sumNumber ##Q2 def smallerThanN(intList,integer): newList=[] for intInList in intList: if intInList<integer: newList....
''' Calculating Function ''' n = int(input()) result = 0 if n % 2 == 0: result = n // 2 else: result = n // 2 - n print(result)
## this file is for common methods that are not necessarily Pokemon related ## for now, i'll just call this common or convenience functions. ## they might be added TO dnio later, if they're useful enough # import pokefunctions as pkf def make_nicknames_dictionary(input_names, nickname_as_key=True, verbose=False): '''...
Motivations = [ # Acolyte 'I ran away from home at an early age and found refuge in a temple.', 'My family gave me to a temple, since they were unable or unwilling to care for me.', 'I grew up in a household with strong religious convictions. Entering the service of one or more gods seemed natural.', 'An impassioned se...
'''Crie um programa que leia valores e mostre um menu na tela: [1]soma [2]multiplicar [3]maior [4]novos números [5]sair do programa. o programa deverá realizar a operação solicitada em cada caso.''' print('------ Calculadora ------') n = int(input('Digite um número: ')) n2 = int(input('Digite outro número: ')) op = 0 w...
"""Stack implementation.""" class Stack(): """Stack class.""" def __init__(self): """ :type None :rtype None """ self.items = [] def push(self, item): """ Push item onto the stack. :type item to add to the top of the stack. :rtype None """ self.items.append(ite...
# coding: utf8 # Copyright 2017 Vincent Jacques <vincent@vincent-jacques.net> project = "sphinxcontrib-ocaml" author = '<a href="http://vincent-jacques.net/">Vincent Jacques</a>' copyright = ('2017 {} <script>var jacquev6_ribbon_github="{}"</script>'.format(author, project) + '<script src="https://jacque...
def add(x, *args): total = x for i in args: total += i print(f'{x=} + {args=} = {total}') add(1, 2, 3) add(1, 2) add(1, 2, 3, 4, 5, 6, 7) add(1)
class orphan_external_exception(Exception): def __init__(self, args=None): if args: self.args = (args,) else: self.args = ("Wow I have been imported",) self.external_demo_attr = "Now imported"
# Created by Egor Kostan. # GitHub: https://github.com/ikostan # LinkedIn: https://www.linkedin.com/in/egor-kostan/ def increment_string(string: str) -> str: """ A function which increments a string, to create a new string: 1. If the string already ends with a number, the number should be incremented b...
__title__ = 'imgur-cli' __author__ = 'Usman Ehtesham Gul' __email__ = 'uehtesham90@gmail.com' __license__ = 'MIT' __version__ = '0.0.1' __url__ = 'https://github.com/ueg1990/imgur-cli.git'
#!/usr/bin/python # -*- coding : utf-8 -*- """ brief: Mediator. Define an object that encapsulates how a set of objects interact.Mediator promotes loose coupling by keeping objects from referring to each other explicitly,and it lets you vary their interaction independently. ( Renter and Landlord co...
class Solution: # @param candidates, a list of integers # @param target, integer # @return a list of lists of integers def combinationSum(self, candidates, target): self.results = [] candidates.sort() self.combination(candidates, target, 0, []) return self.results ...
a = True b = False print('AND Logic:') print('a and a =', a and a) print('a and b =', a and b) print('b and b =', b and b) print('b and a =', b and a) print('\nOR Logic:') print('a or a =', a or a) print('a or b =', a or b) print('b or b =', b or b) print('\nNOT Logic:') print('a =' , a , '\tnot a =' , not a ) print...
'''https://leetcode.com/problems/non-overlapping-intervals/ 435. Non-overlapping Intervals Medium 2867 79 Add to List Share Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. Exam...
''' Refaça o exercício 1 imprimindo os retângulos sem preenchimento, de forma que os caracteres que não estiverem na borda do retângulo sejam espaços. ''' largura = int(input('Digite a largura: ')) altura = int(input('Digite a altura: ')) if (largura > 2) and (altura > 2): meio = largura - 4 espaços = ' ' * me...
s = 0 i = 0 while True: n = int(input('Digite un número [999 para sair]: ')) if n == 999: break s += n i += 1 print(f'\033[33mA soma dos {i} foi {s}')
# LANGUAGE: Python 3 # AUTHOR: Luiz Devitte # GitHub: https://github.com/LuizDevitte def greetings(name): print('\n') print('Hello, World!') print('And Hello, {}!'.format(name)) print('\n') return 0 def main(): name = input('Hey, who are you? ') greetings(name) if __name__=='__main__': ...
# --------------------------------------------------------------------------- # Copyright 2018 The Open Source Electronic Health Record Agent # # 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 #...
#!/usr/bin/env python MAX_LOG_LENGTH = 1000 MESSAGE_MAX_LENGTH = 2000 class ScriptLogger: def __init__(self, db): self.db = db def save(self, user_name, path, logs): # Don't save empty logs if len(logs) == 0: return # If logs are longer than the ...
# # PySNMP MIB module Fore-DSX1-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Fore-DSX1-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:03:21 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
# -*- coding: utf-8 -*- """ Created on Mon Jan 18 18:30:07 2021 @author: SethHarden Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order. """ nums = [1,5,4,3] list = ['a','b','c'] list.append('s') popped = list.pop() courses_2 = ['x', 'z'] list.i...
class BattleEventsListener: def on_battle_begins(self): pass def on_battle_ends(self): pass def on_reflected_attack(self, attack_obj): pass def on_unit_damaged(self, attack_obj): pass def on_unit_killed(self, attack_obj): pass def on_s...
# -*- coding: utf-8 -*- class GameConfig: # Frame dimensions width = 30 height = 15 # Start the game at this speed initial_speed = 3.0 # For every point scored, increase game speed by this amount speed_increase_factor = 0.15 # Maximum game speed. max_speed = 30 # Enforce co...
# fibonaccisequence2.py # This program sums numbers in a Fibonacci sequence to a point specified by the # user. """The Fibonacci sequence starts 1, 1, 2, 3, 5, 8,... Each number in the sequence (after the first two) is the sum of the previous two. Write a program that computes and outputs the nth Fibonacci number, whe...
print('-' * 20) Funcionário = (input('Nome do Funcionário: ')) Cargo = (input('Seu cargo: ')) salario = float (input('Escreva o valor do salário: R$ ')) percent = int (input('Qual o percentual? ')) novo = salario + (salario * percent / 100) print ('O valor antigo do salário era R$ {:.2f}, com aumento de {} % passa a s...
print("%s" % 1.0) print("%r" % 1.0) print("%d" % 1.0) print("%i" % 1.0) print("%u" % 1.0) # these 3 have different behaviour in Python 3.x versions # uPy raises a TypeError, following Python 3.5 (earlier versions don't) #print("%x" % 18.0) #print("%o" % 18.0) #print("%X" % 18.0) print("%e" % 1.23456) print("%E" % 1....
# Exercicios Listas https://wiki.python.org.br/ExerciciosListas # Marcelo Campos de Medeiros # Aluno UNIFIP ADS 2020 # Patos-PB, maio de 2020. ''' 16 - Utilize uma lista para resolver o problema a seguir. Uma empresa paga seus vendedores com base em comissões. O vendedor recebe $200 por semana mais 9% por cento de sua...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ result = [] ...
N,K=map(int,input().split()) S=[int(input()) for i in range(N)] length=left=0 mul=1 if 0 in S: length=N else: for right in range(N): mul*=S[right] if mul<=K: length=max(length,right-left+1) else: mul//=S[left] left+=1 print(length)
class SERPException(Exception): pass class ItemNotFoundException(SERPException): pass
#! /usr/bin/python3 def parts(arr): arr.append(0) arr.append(max(arr)+3) arr.sort() _type1 = 0 _type2 = 0 for _x in range(0, len(arr)-1): _difference = arr[_x+1] - arr[_x] if _difference == 1: _type1 += 1 elif _difference == 3: _type2 += 1 _...
# Debug flag DEBUG = False # Menu tuple IDX return IDX_STOCK = 0 IDX_DATE_RANGE = 1 IDX_PERCENT_TRAINED = 2
""" Detecting Loop in a given linked list """ class Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null class LinkedList: # Function to initialize head def __init__(self): self.h...
# Copyright 2020 Google LLC # # 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 deep_reverse(arr): if len(arr) == 0: return [] last_el = arr[-1] rem_list = deep_reverse(arr[:-1]) # remaining list if type(last_el) is list: last_el = deep_reverse(last_el) rem_list.insert(0, last_el) return rem_list def test_function(test_case): arr = test_case[...
# problem link: https://leetcode.com/problems/combination-sum-iii/ class Solution: def combinationSum3(self, k: int, n: int) -> List[List[int]]: end_num = 10 # candidates numbers are btw 0 - 9 def dfs(cur_list, cur_size, next_num): if cur_size == k and sum(cur_list) == n: ...
def insertion_sort(arr): for k in range(1, len(arr)): key = arr[k] j = k while j > 0 and arr[j-1] > arr[j]: arr[j], arr[j-1] = arr[j-1], arr[j] j = j - 1 my_list = [24, 81, 13, 57, 16] insertion_sort(my_list) print(my_list)
# # PySNMP MIB module ELTEX-MES-VLAN-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-MES-VLAN-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:02:10 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
L, R = int(input()), int(input()) max_xor = 0 for i in range(L, R+1): for j in range(i+1, R+1): if i^j > max_xor: max_xor = i^j print(max_xor)
f = open("file_name.txt", "w") # open file for writing f.write("Some text with out new line ") f.write("Some text.\nSome text.\nSome text.") f.close() # always close the file # "D:\\myfiles\file_name.txt" - backslash symbol (\) is for path in windows # "/myfiles/file_name.txt" - slash symbol (/) is for path in ...
class ActivitiesHelper: ''' Given a pressure data timeseries, calculate a step count ''' def calculate_step_count(self, dataframe, low_threshold = 0, high_threshold = 4): p_avg = dataframe.mean(axis=1) p_diff = p_avg.diff() status = 0 step_count = 0 for p_diff_t ...
class SemiFinder: def __init__(self): self.f = "" self.counter = 0 #Path is inputted from AIPController #Returns semicolon counter def sendFile(self, path): self.f = open(path) for line in self.f: try: self.counter += self.get_all_semis(line...
#operate string of imgdata ,get the new string after ',' def cutstr(sStr1,sStr2): nPos = sStr1.index(sStr2) return sStr1[(nPos+1):] if __name__ == '__main__': print (cutstr('qwe,qw123123e2134123',','))
""" 2차원 행열이 주어질 때, 특정 지점에서 일정 크기의 부분행렬을 구할 필요가 있을 때 TODO 일단은 소스코드 정리는... 필요할 때 하기로 하고 유닛테스트도 나중에 따로 분리하는걸로... TODO cProfile을 사용해서 풀이 방법 별 성능 비교해보기 """ tiles = [ ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09'], ['10', '11', '12', '13', '14', '15', '16', '17', '18', '19'], ['20', '21', '22', '2...
flame_graph_template = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstr...
""" Chapter 01 - Problem 01 - Is Unique - CTCI 6th Edition page 90 Problem Statement: Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? Example: "aalex" -> False Solution: Assume that the input string will contain only ASCII characters. Trav...
class Node: def __init__(self,data,freq): self.left=None self.right=None self.data=data self.freq=freq root=Node("x",5) root.left=Node("x",2) root.right=Node("A",3) root.left.left=Node("B",1) root.left.right=Node("C",1) s="1001011" #encoded data ans="" root2=roo...
class NehushtanMPTerminatedSituation(Exception): """ Since 0.2.13 """ pass
# Q6. Write a programs to print the following pattern : ''' a)A A B A B C A B C D A B C D E b)1 1 2 1 2 3 1 2 3 4 c) 4 3 2 1 3 2 1 2 1 1 '''
def func(*args, **kwargs): print(args) idade = kwargs.get('idade') if idade is not None: print(idade) else: print('Idade não encontrada') lista = [1,2,3,4,5] lista1 = [10, 20, 30, 40, 50] func(*lista, *lista1, nome='Luiz', sobrenome='Miranda', idade=30)
""" Project constants module. All the constants are included in this script. """ # ======================================= Comma.ai dataset test data size and random state constants TEST_SIZE = .2 RANDOM_STATE = 42 # ======================================= Comma.ai dataset training data and label directories TRAIN_D...
data = ( 'Shou ', # 0x00 'Yi ', # 0x01 'Zhi ', # 0x02 'Gu ', # 0x03 'Chu ', # 0x04 'Jiang ', # 0x05 'Feng ', # 0x06 'Bei ', # 0x07 'Cay ', # 0x08 'Bian ', # 0x09 'Sui ', # 0x0a 'Qun ', # 0x0b 'Ling ', # 0x0c 'Fu ', # 0x0d 'Zuo ', # 0x0e 'Xia ', # 0x0f 'Xiong ', # 0x10 ...
# -*- coding: utf-8 -*- # Exercise 2.24 # Author: Little Horned Owl x = 1 # valid, integer x = 1. # valid, float x = 1; # valid, integer (with a end-of-statement semicolon) # x = 1! # invalid # x = 1? # invalid # x = 1: # invalid x = 1, # valid, tuple (but with only one element) ""...
""" 링크드 리스트 - 마지막 노드에서 k 번째 노드 데이터 출력하기 """ class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self, value): self.head = Node(value) def append(self, value): cur = self.head while cur.next is not None: ...
def Even_Length(Test_string): return "\n".join([words for words in Test_string.split() if len(words) % 2 == 0]) Test_string = input("Enter a String: ") print(f"Output: {Even_Length(Test_string)}")
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Part of the Reusables package. # # Copyright (c) 2014-2020 - Chris Griffith - MIT License _roman_dict = { "I": 1, "IV": 4, "V": 5, "IX": 9, "X": 10, "XL": 40, "L": 50, "XC": 90, "C": 100, "CD": 400, "D": 500, "CM": 900, ...
batch_size = 32 stages = 4 epochs = 32 learning_rate = 0.00005
class InvalidSignError(Exception): pass class PositionTakenError(Exception): pass class ColumnIsFullError(Exception): pass
# -*- coding: utf-8 -*- # Copyright 2019 Cohesity Inc. class AlertTypeBucketEnum(object): """Implementation of the 'AlertTypeBucket' enum. Specifies the Alert type bucket. Specifies the Alert type bucket. kSoftware - Alerts which are related to Cohesity services. kHardware - Alerts related to har...
""" 6. Faça um Programa que peça o raio de um círculo, calcule e mostre sua área. """ raio = float(input("Digite o raio do círculo em metros: ")) area = 3.1416 * raio ** 2 print(f"A area dessa circunferência é de {area:.2f}m²")
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ------------------------------------------------- @ Author : Max_Pengjb @ date : 2018/9/23 22:37 @ IDE : PyCharm @ GitHub : https://github.com/JackyPJB @ Contact : pengjianbiao@hotmail.com -----------...
def test_cookie(request): """ Return the result of the last staged test cookie. returns cookie_state = bool """ if request.session.test_cookie_worked(): request.session.delete_test_cookie() cookie_state = True else: cookie_state = False return cookie_state class C...
"""Helper for creating connections to AMQP servers""" def aio_pika_connect_params(config, keypath: str = None) -> dict: """Return a dict keyword arguments that can be passed to aio_pika.connect """ if keypath is None: mq_conf = config else: mq_conf = config.get(keypath) re...
def adjust_travellers_number(travellers_input_val, num, subtract_btn, add_btn): while travellers_input_val > num: subtract_btn.click() travellers_input_val -= 1 while travellers_input_val < num: add_btn.click() travellers_input_val += 1 def set_travellers_number(driver, num, fo...
class Default: """ No-op Implementation """ def __init__(self, *args, **kwargs): pass def gauge(self, name, value): pass def report_time(self, fn): pass
# Copyright 2020 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
data_format = { "Inputs": { "input2": { "ColumnNames": ["temperature", "humidity"], "Values": [ [ "value", "value" ], ] }, }, "GlobalParameters": { } } sensor_value = { "ColumnNames": ["currentTime...
# # Generic error collection for pynucleus. # This file is part of pynucleus. # class BoardNotFoundError(IOError): """ Class representing a condition where no board was found. """ class ProgrammingFailureError(IOError): """ Class representing a condition where programming failed. """
""" Premium Question """ __author__ = 'Daniel' """ This is the interface that allows for creating nested lists. You should not implement it, or speculate about its implementation """ class NestedInteger(object): def isInteger(self): """ @return True if this NestedInteger holds a single integer, ...
def Eyes(thoughts, eyes, eye, tongue): return f""" {thoughts} {thoughts} .::!!!!!!!:. .!!!!!:. .:!!!!!!!!!!!! ~~~~!!!!!!. .:!!!!!!!!!UWWW\$\$\$ :\$\$NWX!!: .:!!!!!!XUWW\$\$\$\$\$\$\$\$\$P \$\$\$\$\$##WX!: ...
class VegaScatterPlot(object): def __init__(self, width: int, height: int): self._width = width self._height = height def build(self): # TODO error log here print("illegal") assert 0
#!/usr/bin/env python # -*- coding: utf-8 -*- # Astounding Horror 1930s chart = ["only", "absent-mindedly", "absolutely", "afterward", "ahead", "alike", "alongside", "always", "around", "asleep", "audibly", "away", "backward", "barely", "blankly", "blind", "blindly", "bravely", "brilliantly", "brokenly", "calmly", "clo...
#Program 4 #Write a user defined function to accept two strings and concatenate them #Name:Vikhyat #Class:12 #Date of Execution:15.06.2021 def FuncConcat(x,y): print(x+y) print("Enter 2 strings to see them concatenated:") l=(input("Enter String 1:")) u=(input("Enter String 2:")) FuncConcat(l,u) '''O...
class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ index = 0 result = 0 count = 0 cutline = -1 dictionary = {} while index < len(s): chr = s[index] oldIndex = dictio...
def nocache(app): @app.after_request def add_header(resp): resp.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate' resp.headers['Pragma'] = 'no-cache' resp.headers['Expires'] = '0' resp.headers['Cache-Control'] = 'public, max-age=0' return resp
""" This module registers the models we created for the "educator" application. After registering the model, the data will be accessible through Django's admin functionality. """
KEY = 'key' DESCRIPTION = 'description' TAGS = 'tags' XTRA_ATTRS = 'xtra_attrs' SEARCH_TERMS = 'search_terms' def list_search_terms(key): '''Given a stat key, returns a list of search terms.''' terms = [] if KEY in key: terms += key[KEY].lower().split('.') terms.append(key[KEY].lower()) ...
# # PySNMP MIB module ADTRAN-AOS-DNS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADTRAN-AOS-DNS-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:13:59 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
class Solution: def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int: """ 4 [[0,1,3],[1,2,1],[1,3,4],[2,3,1]] 4 5 [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]] 2 5 [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,4],[3,...
def spec(packet, config, transmitted_packet): if packet.device == config['wan device']: assert transmitted_packet.device == config['lan device'] else: assert transmitted_packet.device == config['wan device'] # assert transmitted_packet.data[:96] == packet.data[:96] # ignore MACs for now
class HashTable: def __init__(self, sz, stp): self.size = sz self.step = stp self.slots = [None] * self.size def hash_fun(self, value): result = 0 for pos in range(len(value)): sym = value[pos] result += ord(sym) * pos return result % self...
n=int(input()) for i in range(n): s,k=input().split() k=int(k) s=s.replace('-','1').replace('+','0') s=int(s,2) ans=0 x=int('1'*k,2) while s: ss=len(bin(s))-2 if ss-k < 0: ans="IMPOSSIBLE" break s^=x<<(ss-k) ans+=1 print("Case #%d: %s"%(i+1,str(ans)))
# Python - 3.6.0 Test.describe('Basic Tests') Test.assert_equals(twice_as_old(36, 7), 22) Test.assert_equals(twice_as_old(55, 30), 5) Test.assert_equals(twice_as_old(42, 21), 0) Test.assert_equals(twice_as_old(22, 1), 20) Test.assert_equals(twice_as_old(29 ,0), 29)
def somma1(v,i,j):#i=inizio del vettore, j=elemento da sommare print("somma1") if i==j: return v[i] else: return somma1(v,i,(i+j)//2)+somma1(v,(i+j)//2+1,j) #Credo che questa somma sia di complessità computazionale quadratica def somma2(v,i,j): print("somma2") if i==j:...
x = [1, 2, 3] # Create the first list y = [4, 5, 6] # Create the second list t = (x, y) # Create the tuple from the lists print(t) # Print the tuple print(type(t)) # Display the type 'tuple' print(t[0]) # Display the first list print(t[0][1]) # Display the second element of the first list a, b = t # Assi...
#!/usr/bin/env python3 #this progam will write Hello World! print("Hello World!")
# 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 isValidBST(self, root: TreeNode) -> bool: nodes = [] self._isValidBST(root, nodes) ...
class Indexer: """An indexer class.""" def __init__(self, candidates, index=0): """Constructor. Args: candidates (Sequence): A candidates. """ self.candidates = candidates self.index = index @property def index(self): """int: A current index....
# Write a Python program to remove the first item from a specified list. color = ["Red", "Black", "Green", "White", "Orange"] print("Original Color: ", color) del color[0] print("After removing the first color: ", color) print()
# # PySNMP MIB module CISCO-LWAPP-DOT11-CLIENT-CCX-REPORTS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-LWAPP-DOT11-CLIENT-CCX-REPORTS-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:05:14 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davw...
# -*- coding: utf-8 -*- __author__ = 'willmcginnis' class SQLContext(object): def __init__(self, parkContext, sqlContext=None): pass @property def _ssql_ctx(self): """ NotImplemented :return: """ raise NotImplementedError def setConf(self, key, value...
def neighbor(neighbor_list,peer_state, **kwargs): if peer_state in neighbor_list: return 1 else: return 0