content
stringlengths
7
1.05M
which_one = int(input("What Months (1-12)?")) months = ['January' , 'February' , 'March' , 'April' , 'May' , 'June' , 'July' , 'August' , 'September' , 'October', 'November' , 'December'] if 1 <= which_one <= 12: print("Months " , months[which_one - 1])
""" Shows the mathematical timestable """ for i in range(1, 13): for j in range(1, 13): print("{0} times {1} is {2}".format(j, i, i * j)) print("--------------------------------")
EOS_IDX = 3 SOS_IDX = 2 PAD_IDX = 1 UNK_IDX = 0 EOS_STR = "<eos>" SOS_STR = "<sos>" PAD_STR = "<pad>" UNK_STR = "<unk>" BPE_TOKEN = "▁" EVALUATION_CRITERIA = {"perplexity":1, "accuracy":2, "bleu":3}
# Example 1 def setup(): # Set to the same size as the source image # https://unsplash.com/photos/mGy1Jjr2e6M size(900, 600) # Load and display and position the image image(loadImage("file.jpg"), 0, 0)
MOUSE_BTN_LEFT = b"\x90" MOUSE_BTN_RIGHT = b"\x91" MOUSE_BTN_MIDDLE = b"\x92" KEY_LEFT_CTRL = b"\xe0" KEY_LEFT_SHIFT = b"\xe1" KEY_LEFT_ALT = b"\xe2" KEY_LEFT_GUI = b"\xe3" KEY_RIGHT_CTRL = b"\xe4" KEY_RIGHT_SHIFT = b"\xe5" KEY_RIGHT_ALT = b"\xe6" KEY_RIGHT_GUI = b"\xe8" KEY_A = b"\x04" KEY_B = b"\x05" KEY_C = b"\x06...
""" pymake ------------------------------- - Eugenio Marinetto - nenetto@gmail.com ------------------------------- Created 08-08-2019 """ # __all__ variable # Fill it in with the packages you want to export in "from project_name import *" __all__ = []
x = 6 y = 7 # # Simple if # if x == y: # print(f'{x} is equal to {y}') # else: # print(f'{x} is not equal to {y}') # # Elif # if x > y: # print(f'{x} is bigger to {y}') # elif x == y: # print(f'{x} is equal to {y}') # else: # print(f'{x} is not equal to {y}') # Nested if # if x > 2: # if x <=...
# https://leetcode.com/problems/max-consecutive-ones class Solution: def findMaxConsecutiveOnes(self, nums): is_consec = False cnt, ans = 0, 0 for i in range(len(nums)): if (nums[i] == 1) and is_consec: cnt += 1 ans = max(ans, cnt) el...
""" 2015 Advent of Code, Day 1 """ with open("input", "r+") as file: puzzle_input = file.read() FLOOR = 0 POSITION = 0 BASEMENT = False for (index, character) in enumerate(puzzle_input): if character == "(": FLOOR += 1 if character == ")": FLOOR -= 1 if not BASEMENT and FLOOR < 0: ...
a = 1 b = 2 print('a = ' + str(a) + ',' + 'b = ' + str(b)) temp = a a = b b = temp print('a = ' + str(a) + ',' + 'b = ' + str(b))
THRESHOLD = 4 HEADER = '<?xml version="1.0" encoding="utf-8"?>\n\t<output>\n' FOOTER = '\t</output>\n' valMap = { '<': '', '>': '', '&': '', '\"': '' } keyMap = { '~': '', '`': '', '!': '', '@': '', '$': '', '%': '', '^': '', '&': '', '*': '', '(': '', ')': ...
class Solution(object): def productExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] """
# Whitelist of generated features in dev STATUS for quicker execution TSFRESH_FEATURE_WHITELIST = [ 'agg_autocorrelation', 'autocorrelation', 'mean', 'mean_change', 'median', 'standard_deviation', 'variance', 'minimum', ] # Size of the time-windows used for generating single time-series...
# # solver_porting.py # # Description: # Hard code the solution values from the paper # Sin-Chung Chang, # "The Method of Space-Time Conservation Element # and Solution Element - A New Approach for Solving the Navier-Stokes # and Euler Equations", # Journal of Computational Physics, Volume 119, # Issue 2...
# __version__.py # autogenerated by poetry-hooks 0.1.0 __version__ = "0.1.0a0" __title__ = "pytorch-caldera" __authors__ = ["Justin Vrana <justin.vrana@gmail.com>"] __repository__ = "" __homepage__ = "http://www.github.com/jvrana/caldera" __description__ = "" __maintainers__ = "" __readme__ = "" __license__ = ""
n = int(input()) data = [] c1, c2 = 0, 0 flag = 0 for i in range(n): val = list(map(int, input().split())) data.append(tuple(val)) c1 += val[0] c2 += val[1] if (c1 % 2) != (c2 % 2): flag = 1 if c1 % 2 == 1 and c2 % 2 == 1 and (c1+c2) % 2 == 0 and n > 1 and flag == 1: print(1) elif c1 % ...
FULL_SCREEN = "FULL_SCREEN" MOVE_UP = "MOVE_UP" MOVE_LEFT = "MOVE_LEFT" MOVE_RIGHT = "MOVE_RIGHT" MOVE_DOWN = "MOVE_DOWN" ATTACK = "ATTACK" INVENTORY = "INVENTORY" MOVEMENT_ACTION = [ MOVE_DOWN, MOVE_UP, MOVE_RIGHT, MOVE_LEFT, ]
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: current_carry = 0 current = ListNode(0) head = current ...
#!/usr/bin/python3 class Node: def __init__(self, data, lchild=None, rchild=None): self.data = data self.lchild = lchild self.rchild = rchild def pre_order(root): if root != None: print(root.data, end=' ') pre_order(root.lchild) pre_order(root.rchild) def in_or...
DEBUG = False SECRET_KEY = b'_5#y2L"F4Q8z\n\xec]/' SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://hlapse:h91040635!@rm-uf6gm31bj3hm81y14to.mysql.rds.aliyuncs.com/rss' + '?charset=utf8mb4' SQLALCHEMY_TRACK_MODIFICATIONS = False # JWT JWT_ERROR_MESSAGE_KEY = "messsage" JWT_ACCESS_TOKEN_EXPIRES = False # APScheduler SCHEDUL...
UP = 1 DOWN = 2 FLOOR_COUNT = 6 class ElevatorLogic(object): """ An incorrect implementation. Can you make it pass all the tests? Fix the methods below to implement the correct logic for elevators. The tests are integrated into `README.md`. To run the tests: $ python -m doctest -v README.md To ...
ROTATED_PROXY_ENABLED = True PROXY_STORAGE = 'scrapy_rotated_proxy.extensions.file_storage.FileProxyStorage' PROXY_FILE_PATH = '' # PROXY_STORAGE = 'scrapy_rotated_proxy.extensions.mongodb_storage.MongoDBProxyStorage' PROXY_MONGODB_HOST = '127.0.0.1' PROXY_MONGODB_PORT = 27017 PROXY_MONGODB_USERNAME = None PROXY_MONGOD...
# Copyright 2016 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. { 'targets': [ # { # 'target_name': 'cast_extension_discoverer', # 'includes': ['../../../compile_js2.gypi'], # }, # { # 'target_nam...
"""Constants for the babydriver CAN protocol.""" # pylint: disable=too-few-public-methods # Both the C and Python babydriver projects use 15 as the device ID, see can_msg_defs.h. BABYDRIVER_DEVICE_ID = 15 # The babydriver CAN message has ID 63, see can_msg_defs.h. BABYDRIVER_CAN_MESSAGE_ID = 63 class BabydriverMess...
def iscomplex(a): # TODO(beam2d): Implement it raise NotImplementedError def iscomplexobj(x): # TODO(beam2d): Implement it raise NotImplementedError def isfortran(a): # TODO(beam2d): Implement it raise NotImplementedError def isreal(x): # TODO(beam2d): Implement it raise NotImpleme...
N, K = map(int, input().split()) S = list(input()) S[K-1] = S[K-1].swapcase() print("".join(S))
''' Exercise 4: An influencer is a person who doesn’t follow anybody but is followed by everybody. Given N peoples and an adjacency matrix for the graph “following”, where the edge (A,B) means A follows B, find the influencer among the group of N peoples if it exists. Figure 1: Example of 2 social networks. On the lef...
full_submit = { 'processes' : [ { 'name': 'mkdir', 'cmd': 'mkdir -p /mnt/mesos/sandbox/sandbox/__jobio/input /mnt/mesos/sandbox/sandbox/__jobio/output' }, { 'name': 'symlink_in', 'cmd': 'ln -s /mnt/mesos/sandbox/sandbox/__jobio/input /job/input' }, { 'name': 'symlink_out', 'cmd': 'ln -s /mnt/mesos/sandbox/...
"""Make Collatz Sequence This program makes a `Collatz Sequence`_ for a given number. Write a function named :meth:`collatz` that has one parameter named number. If number is even, then :meth:`collatz` should print `number // 2` and return this value. If number is odd, then :meth:`collatz` should print and return `3 ...
class TreasureMap: def __init__(self): self.map = {} def populate_map(self): self.map['beach'] = 'sandy shore' self.map['coast'] = 'ocean reef' self.map['volcano'] = 'hot lava' self.map['x'] = 'marks the spot' return
def sum(n): a = 0 for b in range(1,n+1,4): a+=b*b # b ** 2 return a n = int(input('n=')) print(sum(n))
# %% """ # Exception handling """ # %% """ Exception handling allows a program to deal with runtime errors and continue its normal execution. Consider the following instructions: """ # %% a=input("Enter integer: ") num=int(a) inverse=1/num print(number,inverse) # %% """ What happens if the user enters a null or non...
#------------------------------------------------------------------------------ # interpreter/interpreter.py # Copyright 2011 Joseph Schilz # Licensed under Apache v2 #------------------------------------------------------------------------------ articles = [" a ", " the "] def verb(command): # A function ...
URLs = [ ["https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Current version ["https://web.archive.org/web/20220413213804/https://www.oryxspioenkop.com/2022/02/attack-on-europe-documenting-equipment.html", True], # Apr 13 - 21:38:04 UTC ["https://web.archive.org/we...
#Enquiry Form name=input('Enter your First Name ') Class=int(input('Enter your class ')) school=input('Enter your school name ') address=input('Enter your Address ') number=int(input('Enter your phone number ')) #print("Name- ",name,"Class- ",Class,"School- ",school,"Address- ",address,"Phone Number- ",number,sep='\n')...
'''ftoc.py - Fahrenheit to Celsius temperature converter''' def f_to_c(f): c = (f - 32) * (5/9) return c def input_float(prompt): ans = input(prompt) return float(ans) f = input_float("What is the temperature (in degrees Fahrenheit)? ") c = f_to_c(f) print("That is", round(c, 1), "degrees Celsius")
class Solution: # Sort (Accepted), O(n log n) time, O(n) space def maxProductDifference(self, nums: List[int]) -> int: nums.sort() return (nums[-1] * nums[-2]) - (nums[0] * nums[1]) # One Pass (Top Voted), O(n) time, O(1) space def maxProductDifference(self, nums: List[int]) -> int: ...
nota = float(input('Digite sua nota, Valor entre "0 e 10": ')) while True: if nota >= 8.5 and nota <= 10: print('Nota igual a A') elif nota >= 7.0 and nota <= 8.4: print('Nota igual a B') elif nota >= 5.0 and nota <= 6.9: print('Nota igual a C') elif nota >= 4.0 and nota <= 4.9: ...
# Given an array, rotate the array to the right by k steps, where k is # non-negative. # Example 1: # Input: [1,2,3,4,5,6,7] and k = 3 # Output: [5,6,7,1,2,3,4] # Explanation: # rotate 1 steps to the right: [7,1,2,3,4,5,6] # rotate 2 steps to the right: [6,7,1,2,3,4,5] # rotate 3 steps to the right: [5,6,7,1,2,3,4] #...
INVALID_VALUE = -9999 def search_in_dictionary_list(dictionary_list, key_name, key_value): for dictionary in dictionary_list: if dictionary[key_name] == key_value: return dictionary return None def search_value_in_dictionary_list(dictionary_list, key_name, key_value, value_key): dict...
expected_output = { "global_drop_stats": { "Ipv4NoAdj": {"octets": 296, "packets": 7}, "Ipv4NoRoute": {"octets": 7964, "packets": 181}, "PuntPerCausePolicerDrops": {"octets": 184230, "packets": 2003}, "UidbNotCfgd": {"octets": 29312827, "packets": 466391}, "UnconfiguredIpv4Fi...
def func(ord_list, num): result = True if num in ord_list else False return result if __name__ == "__main__": l = [-1,3,5,6,8,9] # using binary search def find(ordered_list, element): start_index = 0 end_index = len(ordered_list) - 1 while True: middle_index = int((end_index + start_index) / 2)...
# 54. Spiral Matrix class Solution: def spiralOrder(self, matrix): if not matrix: return matrix m, n = len(matrix), len(matrix[0]) visited = [[False] * n for _ in range(m)] ans = [] dirs = ((0,1), (1,0), (0,-1), (-1,0)) cur = 0 i = j = 0 ...
class Solution: # @param s, a string # @param wordDict, a set<string> # @return a boolean def wordBreak(self, s, wordDict): n = len(s) if n == 0: return True res = [] chars = ''.join(wordDict) for i in xrange(n): if s[i] not in chars: ...
clan = { } def add_member(tag, name, age, level): clan[tag] = { "Name": name, "age": age, "level": level } return clan def display_clan(): print(clan) add_member("Voodoo", "Andre Williams", 26, "Beginner") display_clan()
class CRSError(Exception): pass class DriverError(Exception): pass class TransactionError(RuntimeError): pass class UnsupportedGeometryTypeError(Exception): pass class DriverIOError(IOError): pass
# Search Part Problem n = int(input()) part_list = list(map(int, input().split())) m = int(input()) require_list = list(map(int, input().split())) def binary_search(array, target, start, end): mid = (start + end) // 2 if start >= end: return "no" if array[mid] == target: return "yes" ...
time_convert = {"s": 1, "m": 60, "h": 3600, "d": 86400} def convert_time_to_seconds(time): try: return int(time[:-1]) * time_convert[time[-1]] except: raise ValueError
def loadfile(name): lines = [] f = open(name, "r") for x in f: if x.endswith('\n'): x = x[:-1] lines.append(x.split("-")) return lines def pathFromPosition (position, graph, path, s, e, goingTwice, bt): beenThere = bt.copy() path = path + "-" + position print(pa...
def launch(self, Dialog, **kwargs): # This is where the magic happens! # The lx module is persistent so you can store stuff there # and access it in commands. lx._widget = Dialog lx._widgetOptions = kwargs # widgetWrapper creates whatever widget is set via lx._widget above # note we're using launchScript whi...
test = { 'name': 'q1_2', 'points': 1, 'suites': [ { 'cases': [ {'code': '>>> sum(standard_units(make_array(1,2,3,4,5))) == 0\nTrue', 'hidden': False, 'locked': False}, {'code': '>>> np.isclose(standard_units(make_array(1,2,3,4,5))[0], -1.41421356)\nTrue', 'hidden': Fal...
x = input() total = 0 while x != "NoMoreMoney": money = float(x) if money > 0: total += money print(f"Increase: {money:.2f}") x = input() elif money < 0: print("Invalid operation!") break print(f"Total: {total:.2f}")
# !/usr/bin/env python # -*- coding: utf-8 -*- """ Created on 2021/7/27 12:43 下午 @author: huangyiwei """ haa_table = ["00","0A","0B","0C","0D","0E","0F","0G","0H","0I","0J","0K","0L","0M","0N","0O","0P","0Q","0R","0S","0T","0U","0V","0W","0X","0Y","0Z","0a","0b","0c","0d","0e","0f","0g","0h","0i","0j","0k","0l","0m"...
#File Locations EXTRACT_LIST_FILE = "ExtractList.xlsx" RAW_DATA_FILE = "../../output/WorldBank/WDIData.csv" OUTPUT_PATH = "../../output/WorldBank/split_output/"
# https://leetcode.com/problems/lucky-numbers-in-a-matrix def lucky_numbers(matrix): all_lucky_numbers, all_mins = [], [] for row in matrix: found_min, col_index = float('Inf'), -1 for index, column in enumerate(row): if column < found_min: found_min = ...
[ [float("NaN"), float("NaN"), 66.66666667, 33.33333333, 0.0], [float("NaN"), float("NaN"), 33.33333333, 66.66666667, 66.66666667], [float("NaN"), float("NaN"), 0.0, 0.0, 33.33333333], ]
encrypted_string = 'OMQEMDUEQMEK' for i in range(1,27): temp_str = "" for x in encrypted_string: int_val = ord(x) + i if int_val > 90: # 90 is the numerical value for 'Z' # 65 is the numerical value for 'A' # If int_val is greater than Z then # t...
""" Contains methods for easily persisting `Pydantic <https://pydantic-docs.helpmanual.io/>`_ data structures to and from arbitrary storage back-ends. Contains a base class for the store behavior, as well as subclasses which allow Google Cloud Firestore or in-memory to be used as the storage back-end. Supports saving, ...
# -*- coding: utf-8 -*- ## \package dbr.moduleaccess # MIT licensing # See: docs/LICENSE.txt ## This class allows access to a 'name' attribute # # \param module_name # \b \e unicode|str : Ideally set to the module's __name__ attribute class ModuleAccessCtrl: def __init__(self, moduleName): self.ModuleName = mo...
# ternary method num1 = int(input('Enter the number 1::')) num2 = int(input('\nEnter the number 2::')) num3 = int(input('\nEnter the number 3::')) max = (num1 if (num1 > num2 and num1 > num3) else (num2 if(num2 > num3 and num2 > num1) else num3)) print('\n\nThe maximum number is ::', max) #with pre-...
num1 = int(input()) num2 = int(input()) if(num1>=num2): print(num1) else:print(num2)
contracts = dict((('张坏人',123),('张好人',222))) def new_user(): a = '请输入用户名:' while True: name = input(a) if name in contracts: a = '此用户名已占用,请重新输入:' continue else: break password = input('请输入密码:') contracts[name] = password print('注册...
""" This is a very common interview question. Given a binary tree, check whether it’s a binary search tree or not. Simple as that.. http://www.ardendertat.com/2011/10/10/programming-interview-questions-7-binary-search-tree-check/ """ class Node: def __init__(self, val=None): self.left, self.right, self.va...
""" Set of test functions so BeagleBone specific GPIO functions can be tested For obvious reasons these values are ONLY for testing! TODO: Expand to use test values instead of set values """ def begin(): print("WARNING, not using actual GPIO") def write(address, a, b): #print("WARNING, not actual GPIO") ...
class Solution: def leastInterval(self, tasks: List[str], n: int) -> int: tasksDict = collections.Counter(tasks) heap = [] c = 0 for k, v in tasksDict.items(): heappush(heap, (-v, k)) while heap: i = 0 stack = [] while i <= n: ...
# Written 9/10/14 by dh4gan # Some useful functions for classifying eigenvalues and defining structure def classify_eigenvalue(eigenvalues, threshold): '''Given 3 eigenvalues, and some threshold, returns an integer 'iclass' corresponding to the number of eigenvalues below the threshold iclass = 0 --> ...
# ------------------------------------------------------------------------- # # THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, # EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. # ----------------...
def column_to_list(data, index): """ Função para pegar um certo atributo dos dados. Argumentos: data: lista de dados. index: indice do atributo desejado. Retorna: Uma lista dos atributos desejados. """ return [d[index] for d in data] def run(data_list): # TAREFA 3 # ...
# Escreva um programa que leia a velocidade de um carro. # Se ele ultrapassar 80km/h, mostre uma mensagem dizendo que ele foi multado. # A multa vai custar R$7,00 para cada km acima do limite. radar = 'Radar eletrônico!' print('-' * len(radar)) print(radar) print('-' * len(radar)) velocidade = int(input('Velocidade do...
class Solution: def largeGroupPositions(self, S): """ :type S: str :rtype: List[List[int]] """ return [[m.start(), m.end() - 1] for m in re.finditer(r'(\w)\1{2,}', S)]
minombre = "NaCho" minombre = minombre.lower() print (minombre) for i in range(100): print(i) break
""" Initializing the Python package """ __version__ = '0.31' __all__ = ( '__version__', )
"""SQL formatting for Teradata queries.""" class SQLFormattingError(Exception): """Custom Exception handling for empty SQL lists.""" pass def to_sql_list(iterable): """ Transform a Python list to a SQL list. input = [a1, a2] output = "('a1', 'a2')" """ if iterable: return '...
class SceneManager: def __init__(self): self.scene_list = {} self.current_scene = None def append_scene(self, scene_name, scene): self.scene_list[scene_name] = scene def set_current_scene(self, scene_name): self.current_scene = self.scene_list[scene_name] class Scene: ...
__all__ = ["ICCError", "CmdError", "CommError"] class ICCError(Exception): """A general exception for the ICC. Anything can throw one, passing a one line error message. The top-level event loop will close/cleanup/destroy any running command and return the error message on text. """ def __in...
{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "6ff1526a", "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd\n", "import matplotlib.pyplot as plt" ] }, { "cell_type": "code", "execution_count": 2, "id": "3cea144b", ...
class Solution: def binary_search(self, array, val): index = bisect_left(array, val) if index != len(array) and array[index] == val: return index else: return -1 def smallestCommonElement(self, mat: List[List[int]]) -> int: values = mat[0] mat...
# This problem was asked by Facebook. # Given a binary tree, return all paths from the root to leaves. # For example, given the tree # 1 # / \ # 2 3 # / \ # 4 5 # it should return [[1, 2], [1, 3, 4], [1, 3, 5]]. #### class Node: def __init__(self, val = None, left = None, right = None): sel...
class ApiConfig: api_key = None api_base = 'https://www.quandl.com/api/v3' api_version = None page_limit = 100
_BEGIN = 0 ZERO=0 RAND=1 _END = 10
# -*- coding: utf-8 -*- def main(): n, d = map(int, input().split()) s = [input() for _ in range(d)] ans = 0 for i in range(d): for j in range(i, d): if i != j: count = 0 for si, sj in zip(s[i], s[j]): if si == 'o'...
TOPIC = "test.mosquitto.org" # Temperature and umidity publish interval (seconds) DATA_PUBLISH_INTERVAL = 5 # Data amount needed to start processing (reset after) DATA_PROCESS_AMOUNT = 5 # Percentage of mean temperature which will be sent to the air conditioner AIR_CONDITIONER_PERCENTAGE = 0.8 # Humidity below this...
PAGINATE_MODULES = { "Leads": { "stream_name": "leads", "module_name": "Leads", "params": {"per_page": 200, "sort_by": "Modified_Time", "sort_order": "asc"}, "bookmark_key": "Modified_Time", }, "Deals": { "stream_name": "deals", "module_name": "Deals", ...
for arquivo in os.listdir(caminho): caminho_completo = os.path.join(caminho, arquivo) #zip.write(caminho_completo, arquivo) print(caminho_completo)
class Utils: def __init__(self, data_immigration=None, data_temp=None, data_us_dem=None, data_airport=None): self.data_immigration = data_immigration self.data_temp = data_temp self.data_us_dem = data_us_dem self.data_airport = data_airport @staticmethod def process_immigrat...
#!/usr/bin/env python3 # coding:utf-8 class Solution: def Add(self, num1, num2): """ num1 ^ num2: 不计进位的相加 (num1 & num2) << 1: 进位 循环至进位为零 ~(num1 ^ 0xffffffff): 模仿 C,当 num1 为负数时,把它从无符号数转为有符号数 C 的 int 的高位是符号位,Python 没有 """ while num2 != 0: ...
class Solution: def removeCoveredIntervals(self, intervals: List[List[int]]) -> int: intervals.sort(key=lambda x: (x[0], -x[1])) count = 0 end = -1 for a, b in intervals: if b > end: count += 1 end = b return count
def comb(n, k): nCk = 1 MOD = 10**9+7 for i in range(n-k+1, n+1): nCk *= i nCk %= MOD for i in range(1, k+1): nCk *= pow(i, MOD-2, MOD) nCk %= MOD return nCk n, a, b = map(int, input().split()) mod = 10**9+7 ans = pow(2, n, mod)-1-comb(n, a)-comb(n, b) print(ans %...
dict1={1:"John",2:"Bob",3:"Bill"} print(dict1) print(dict1.items()) k=dict1.keys() for key in k: print(key) v=dict1.values() for value in v: print(value) print(dict1[3]) del dict1[2] print(dict1)
# # @lc app=leetcode id=119 lang=python3 # # [119] Pascal's Triangle II # # https://leetcode.com/problems/pascals-triangle-ii/description/ # # algorithms # Easy (45.89%) # Likes: 582 # Dislikes: 182 # Total Accepted: 237.3K # Total Submissions: 515.4K # Testcase Example: '3' # # Given a non-negative index k wher...
""" /github/enums/repositorysubscription.py Copyright (c) 2019-2020 ShineyDev 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...
#!/usr/bin/python3.8 # -*- coding: utf-8 -*- __version__ = "0.2.2" __author__ = 'Anton Vanke <f@hpu.edu.cn>' class Gobang: """ 五子棋 ===== 一个简单的五子棋类, 可以在控制台下五子棋. 提供以下函数 : new(): 新局 printcb(): 打印棋盘 player(): 获取当前应落子 ID (轮走方) sortstep(): 处理总步表 loadstep(): 将 step 步表...
# Copyright (c) 2012 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. # lzma_sdk for standalone build. { 'targets': [ { 'target_name': 'ots_lzma_sdk', 'type': 'static_library', 'defines': [ '...
""" Given an integer n. Each number from 1 to n is grouped according to the sum of its digits. Return how many groups have the largest size. """ class Solution: def countLargestGroup(self, n: int) -> int: def sum_digits(integer): tot = 0 while integer: tot += intege...
# Create a sequence where each element is an individual base of DNA. # Make the array 15 bases long. bases = 'ATTCGGTCATGCTAA' # Print the length of the sequence print("DNA sequence length:", len(bases)) # Create a for loop to output every base of the sequence on a new line. print("All bases:") for base in bases: ...
# Team 5 def save_to_json(datatables: list, directory=None): pass def open_json(): pass
_base_ = "./FlowNet512_1.5AugCosyAAEGray_AggressiveV2_Flat_Pbr_01_ape.py" OUTPUT_DIR = "output/deepim/lmPbrSO/FlowNet512_1.5AugCosyAAEGray_AggressiveV2_Flat_lmPbr_SO/duck" DATASETS = dict(TRAIN=("lm_pbr_duck_train",), TEST=("lm_real_duck_test",)) # bbnc6 # objects duck Avg(1) # ad_2 4.23 4.23 # ad_5 26....
class Solution: def sortArray(self, nums: List[int]) -> List[int]: temp = [0] * len(nums) def mergeSort(start, end): if start < end: mid = (start + end) // 2 mergeSort(start, mid) mergeSort(mid + 1, end) i = k = start ...
class Foo0(): def __init__(self): pass foo1 = Foo0() class Foo0(): ## error: redefined class def __init__(self, a): pass foo2 = Foo0()
# List of possible Pokemon types types = [ "Normal", "Fire", "Water", "Electric", "Grass", "Ice", "Fighting", "Poison", "Ground", "Flying", "Psychic", "Bug", "Rock", "Ghost", "Dragon", "Dark", "Steel", "Fairy" ] # Chart of type weaknesses. type_dict["Water"]["Fire"] assumes water is attacking fire. type_dict = {"N...