content
stringlengths
7
1.05M
""" Triangles A few functions that determine a points location relative to a triangle Author: Jared Siraco """ def splitPoints(r,q,testpoint,points): #splits points between points on the same side if points == []: return [],[] if q==testpoint: testpoint = points[0] side1 = [] #as testpoint and those not...
print("a(x**2) + b(x) + c = 0") print("Enter the values of a,b,c") a = int(input("Enter the value of a:")) b = int(input("Enter the value of b:")) c = int(input("Enter the value of c:")) d = b**2 - 4*(a*c) x = (-b - (d**0.5))/(2*a) y = (-b + (d**0.5))/(2*a) print("The roots of the equation are :",x,"and", y)
with open('input.txt') as file: data = [int(line.strip()) for line in file.readlines()] # to speed things up a little bit... data = list(sorted(data)) def part1(): for i in range(len(data)): for j in range(i + 1, len(data)): if data[i] + data[j] == 2020: return data[i] * da...
x = 0 if x < 1000 and x % 3 == 0: print(x, "is a multiple of 3!") x += 1 if x < 1000 and x % 3 == 0: print(x, "is a multiple of 3!") x += 1 if x < 1000 and x % 3 == 0: print(x, "is a multiple of 3!") x += 1 if x < 1000 and x % 3 == 0: print(x, "is a multiple of 3!") x += 1
class PythonPackageTemplate(object): def __unicode__(self): return "just a template" @staticmethod def ping(): return "pong"
class ageError(Exception):#Creating a new exception class def __init__(self,message): Exception.__init__(self,message) class nameError(Exception): def __init(self,message): Exception.__init__(self,message) class marksError(Exception): def __init__(self,message): Exception.__init__(se...
# https://www.hackerrank.com/challenges/absolute-permutation/problem def absolutePermutation(n, k): arr = list(range(1,n+1)) j = 0 l = -1 while(j<n): l *= -1 for _ in range(max([1,k])): arr[j] += l*k j +=1 if(j==n): break return st...
try: liczba1 = int (input()) except: print("zjebales") try: liczba2 = int (input()) except: print("zjebales") try: print (f"Twoja liczba to: {liczba1+liczba2}") except: print("zjebales")
class BaseType: def check_value(self, value): """Check if value is good""" pass def set(self, value): """Check and set value""" pass def get(self): """Get value""" pass def to_save(self): """Build a serializable data to save""" pass ...
class Problem: def __init__(self, inp): self.data = [{}, {}, {}, {}, {}, {}, {}, {}] for line in inp.read().strip().split("\n"): for i, char in enumerate(line): self.data[i][char] = self.data[i].get(char, 0) + 1 def step1(self): return ''.join(map(lambda m: s...
db.define_table( 'di_order', *bucket_generic_fields ) db.define_table( 'di_order_outbox', Field('parent', 'reference di_order'), *bucket_outbox_generic_fields ) # IMPORTANT - always set not required fields to default = "", or else != operator in queries will return wrong values # #http...
# -*- coding: utf-8 -*- i=1 j=60 while j>-1: print("I=%i J=%i"%(i,j)) i+=3 j-=5
#concatenacion con metodo f-Strings print("Aplicando f-Strings") nombre = "Mariano" edad = 22 f"Hola, {nombre}. Tienes {edad} años." #Ejemplo 2 print(f"El resultado de 4+1 es: {4+1}") #Ejemplo 3 nombre = "Mariano" estatura = 1.60 edad = 22 print(f"Hola, {nombre}. Tienes {edad} años y tu estatur...
"""Simple example calling str.format(...) directly.""" name = "Peter" price = 1.2 print(str.format("Hello {}, do you have ${:0.2f}?", name, price))
''' Xldlib/Onstart ______________ Modules to initializes XL Discoverer. :copyright: (c) 2015 The Regents of the University of California. :license: GNU GPL, see licenses/GNU GPLv3.txt for more details. ''' __all__ = [ 'app', 'args', 'check_imports', 'error', 'launch', 'mai...
""" Copyright 2020 Twitter, Inc. SPDX-License-Identifier: Apache-2.0 """ development_seed = 1684992425 seeds = [ 4258031807, 3829679737, 3706579387, 789594926, 3628091752, 54121625, 825346923, 646393804, 1579300575, 246132812, 2882726575, 970387138, 413984459, 28...
s = input() r = input() t = "" for i in range(1, len(s) + 1): t += s[-i] if r == t: print("YES") else: print("NO")
print('66666666') print('乌七八糟的')
n = int(input('Enter number of levels: ')) for i in range(1, n + 1): string = "\t" * (n - i) for j in range(i): string += '*\t' print(string)
n = int(input()) my_list = [] is_balanced = True old_line = '' for i in range(n): line = input() if line == '(' and old_line == '(': is_balanced = False my_list.append(line) old_line = line if my_list.count('(') == my_list.count(')') and is_balanced: print('BALANCED') else: print('UNBA...
# Python program to print prime numbers in an interval def print_primes(lower_limit: int, upper_limit: int) -> None: # iterating the lower interval till it reaches the upper interval for i in range(lower_limit, upper_limit + 1): if lower_limit > 1: interval = 2 # now as 2 is al...
#!/usr/bin/env python3 # encoding: utf-8 """ @version: 0.1 @author: lyrichu @license: Apache Licence @contact: 919987476@qq.com @site: http://www.github.com/Lyrichu @file: pso_config.py @time: 2018/06/07 23:11 @description: config settings for PSO """ class BASIC_CONFIG: def __init__(self): self.c1 = 1.49...
class Solution: def fourSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[List[int]] """ result = [] nums.sort() for i in range(len(nums)-2): if i and nums[i-1] == nums[i]: continue ...
"""An event's location.""" class EventLocation: """An event's location as a textual description and a list of places.""" def __init__(self, description, places): """Initialize with the location description and a list of places.""" self.description = description self.places = places ...
a=0 b=1 input_n = int(input("Enter the number till you want to find fiboncci:")) print(a,b,end=' ') for i in range(2,input_n): # Since two numbers are already printed so now we will start range from 2 c= a+b print(c,end= ' ') a = b b =c print("\n\nFibonacci number of ",input_n," is ",c)
#!/usr/bin/env python3 # GUI def required_option_not_set(option_name): readable_name = option_name.replace('_', ' ').title() return 'Option {0} is required but not set'.format(readable_name) # Scraping SCRAPE_INVALID_PLATFORM = 'You must provide a valid platform (emulated system) to enable scraping' SCRAPE_...
curso = "Curso de Python" #STring nada mais é do que um Array de caracteres print(curso) print(curso[2]) #Posicao de indice 2 vai imprimir a letra r print(curso[9]) #Posicao de indice 2 vai imprimir a letra P print(curso[0:5]) #Faixa de intervalo vai imprmir Curso print(curso[9:15]) #Faixa de intervalo vai imprmir Py...
def read_matrix(): matrix_size = int(input()) matrix = [] for _ in range(matrix_size): matrix.append(input().split()) return matrix matrix = read_matrix() symbol = input() is_found = False for col in range(len(matrix)): if symbol in matrix[col][0]: index, column = matrix[col][0...
# my_lambdata/my_mod.py def enlarge(n): """ Param n is a number Function will enlarge the number """ return n * 100 # this code breaks our ability to import enlarge from other files, if left in the global scope: # # print("HELLO") # y = int(input("Please choose a number")) # print(y, enlarge(y)) ...
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: d={} for i,n in enumerate(nums): d_n=target-n if d_n in d: return [d[d_n],i] d[n]=i return [None,None]
""" Input validation classes. """ yn_answers = ['y', 'n', 'yes', 'no'] commands = ['mkfs', 'open', 'ls', 'read', 'write', 'seek', 'close', 'mkdir', 'rmdir', 'tree', 'cd', 'cat', 'import', 'export'] def validate_yes_no(text): if text: if text not in yn_answers: print('This i...
#!/usr/bin/env python3 def search_insert(nums, target: int) -> int: start = 0 end = len(nums) - 1 mid = 0 while start <= end: mid = (start + end) // 2 curr = nums[mid] if curr == target: return mid if target < curr: end = mid - 1 else: ...
class ProcessorProperty: def __init__(self, label, default_value, min_value=None, max_value=None): self.label = label self.value = default_value self.default_value = default_value self._type = type(default_value) self.min_value = min_value self.max_value = max_value ...
## Tower of Hanoi # Given the number of disks and the three towers labels, the program will displays the moves required to solve. def TowerOfHanoi(numDisks, source, intermediate, destination): if(numDisks == 1): print("Move Disk 1 From Pole {} to Pole {}".format(source, destination)) # if there is onl...
a = 1 b = 2 c = a + b d = '668'
class RowSource(object): def get_rows(self, start, count): raise Exception("not implemented") class FileRowSource(RowSource): def __init__(self, fileobj): super().__init__(); self.fileobj = fileobj def next_page(self, rows): lines = [] for i in range(rows): ...
""" Static values about mods and mod actions that generally shouldn't need to change. """ BOTS = ["AnimeMod", "AutoModerator"] ADMINS = ["reddit", "Reddit Legal", "Anti-Evil Operations"] # There are more types of actions that can be set here, currently used in selecting distinct posts/comments/users. MOD_ACTIONS_POS...
#!/usr/bin/env python3 name = input("what is your name? ") print("hello", name)
class LexStatusCodes: LA_OK = 0 LA_FAIL = 1 LA_EXPIRED = 20 LA_SUSPENDED = 21 LA_GRACE_PERIOD_OVER = 22 LA_TRIAL_EXPIRED = 25 LA_LOCAL_TRIAL_EXPIRED = 26 LA_RELEASE_UPDATE_AVAILABLE = 30 LA_RELEASE_NO_UPDATE_AVAILABLE = 31 LA_E_FILE_PATH = 40 LA_E_PRODUCT_FILE = 41 ...
# encoding: utf-8 __author__ = "Nils Tobias Schmidt" __email__ = "schmidt89 at informatik.uni-marburg.de" ''' Project constants ''' ''' Project name ''' PROJECT_NAME = "AndroLyze" PROJECT_COPYRIGHT = u"Copyright (c) 2015 Nils Tobias Schmidt and Lars Baumgärtner, {schmidt89,lbaumgaertner} at informatik.uni-marburg.d...
num = cont = soma = 0 while True: num = int(input('Digite um valor: ')) if num == 999: break soma += num cont += 1 print(f'Você digitou {cont} números e a soma entre eles é igual a {soma}')
DEBUG=True DEBUG_EXTRACT=True DEBUG_ROOIBOS=True DEBUG_PATCH_LOCATIONS=True DEBUG_RESOLVE_DYNLIB=True DEBUG_ADDR2LINE=True DEBUG_PATCHING=True DEBUG_LTRACE=False DEBUG_FIND=True TEST=True
# ----------------------------------------------------------------------------- # 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 without restriction, including without limitation the rights # ...
class GuacamoleConfiguration(object): def __init__(self, protocol=None): self.connectionID = None self.protocol = protocol self.parameters = {} @property def connectionID(self): return self._connectionID @connectionID.setter def connectionID(self, connectionID): ...
a, b, c = input().split(" ") a = float(a) b = float(b) c = float(c) if a >= b and a >= c: n1 = a if b >= c: n2 = b n3 = c else: n2 = c n3 = b if b >= a and b >= c: n1 = b if a >= c: n2 = a n3 = c else: n2 = c n3 = a if c >= a and c...
def only_numbers(input_list): integers_list = [list_entry for list_entry in input_list if type(list_entry) == int] return integers_list print(only_numbers([99, 'no data', 95, 93, 'no data'])) def only_numbers_greater_zero(input_list): integers_list = [list_entry for list_entry in input_list if list_entry...
## https://docs.python.org/3/howto/logging-cookbook.html#an-example-dictionary-based-configuration ## https://docs.djangoproject.com/en/1.9/topics/logging/#configuring-logging logcfg = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)...
#! /usr/bin/env python3 #Aleksandra Rzepka #Calculate the square root of a number def sqrt(x): """ Calculate the square root of argument x. """ #Check that x is positive. if x < 0: print("Error: negative value supplied") return -1 else: print("Here we go...") #Initial guess for the square root...
class Solution(object): def maxDistance(self, nums): """ :type arrays: List[List[int]] :rtype: int """ low = float('inf') high = float('-inf') res = 0 for num in nums: # We can use num[0] && num[-1] only because these lists are sorted ...
"""Constants and allowed parameter values specified in the Userlist API.""" PUSH_URL = 'https://push.userlist.com/' # Date formats VALID_DATE_FORMATS = ['%Y-%m-%dT%H:%M:%S%z', '%Y-%m-%dT%H:%M:%S']
# Rolling hash usage of a multiply accumlate unit with multiplier from the FNV hash, but linear style like the Ghash of AES-GCM def rolling_hash_by_mac(list): hash = 0 for byte in list: hash += byte hash *= 0x01000193 hash %= 2**32 return(hash) #powers of the multiplier o...
# OpenWeatherMap API Key weather_api_key = "bfabad3eec079b77cd6e28110d3ad22f" # Google API Key g_key = "AIzaSyBKZyrmnIxatibyVFhiPyCHD87TQW0ulAA"
# vim: set encoding=utf-8 # Copyright (c) 2016 Intel Corporation  # # 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 require...
target = 1000000 for i in range(1,500001): if target % i != 0: continue if '0' in str(i): continue j = int(target / i) if '0' in str(j): continue print ('Factors: ' + str(i) + ' : ' + str(j)) exit
# Databricks notebook source # MAGIC %run ./_utility-methods $lesson="12.1" # COMMAND ---------- DA.cleanup() DA.init(create_db=False) DA.conclude_setup() # COMMAND ---------- def print_sql(rows, sql): html = f"<textarea style=\"width:100%\" rows={rows}> \n{sql.strip()}</textarea>" displayHTML(html) # COMM...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __all__ = ["test_bettersis", "test_siscompleter", "test_texteditor", "test_update_checker"]
# path = 'D:/PythonWorkspace/learn-python/lesson10/pi_digits.txt' # 土鳖写法 # f = open(path) # contents = f.read() # print(contents) # f.close() # with open('pi_digits.txt') as f: # 一个点表示当前目录,两个点表示上一级目录 # contents = f.read() # 把整个文件读出来 # print(contents) # with open('pi_digits.txt') as f: # # for line in f:...
''' Dataset information ''' coco_classes = [ 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic_light', 'fire_hydrant', 'stop_sign', 'parking_meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep',...
line = input().split() n = int(line[0]) t = int(line[1]) visited = {0} line = [int(i) for i in input().split()] current = 1 while(current != t): if(current in visited or current > len(line)): print("NO") break else: visited.add(current) current += line[current - 1] if(current == ...
"""Default reserved words that should not be anonymized by sensitive word anonymization.""" # Copyright 2018 Intentionet # # 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...
# Create a task list. A user is presented with the text below. # Let them select an option to list all of their tasks, add a task to their list, delete a task, or quit the program. # Make each option a different function in your program. # Do NOT use Google. # Do NOT use other students. # Try to do this on your own. ...
class StringFormat(object): def format_string(self, pattern, *args, **kwargs): return pattern.format(*args, **kwargs) # To create distributable package: # # python3 setup.py bdist_wheel --universal # # Upload the package to pypi: # # twine upload dist/*
# function to check string is # palindrome or not def isPalindrome(str): # Run loop from 0 to len/2 for i in xrange(0, len(str)/2): if str[i] != str[len(str)-i-1]: return False return True # main function s = "malayalam" ans = isPalindrome(s) if (ans): print("Yes") else: print("No")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive", "http_file") load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") load("@bazel_tools//tools/build_defs/repo:jvm.bzl", "jvm_maven_import_external") def rules_mybuilder_dependencies( maven_servers = ["https://repo1.maven.org/maven2/"]...
class FileHelper: """description of class""" file = ""; def __init__(self, filename): self.file = filename; def ReadFile(self): fileStream = open(self.file); lines = fileStream.readlines(); fileStream.close(); return lines;
""" @Author: huuuuusy @GitHub: https://github.com/huuuuusy 系统: Ubuntu 18.04 IDE: VS Code 1.36 工具: python == 3.7.3 """ """ 思路: 分配一个 Set 去保存所有的列表节点,我们逐一遍历列表,检查当前节点是否出现过 如果节点已经出现过,那么一定形成了环且它是环的入口 否则如果有其他点是环的入口,我们应该先访问到其他节点而不是这个节点 其他情况,没有成环则直接返回 null 如果 while 循环终止,我们返回 null 因为我们已经将所有的节点遍历了一遍且没有遇到重复的节...
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
""" PRACTICE ON BOOLEAN LOGIC!!!! """ """ 1) what will be displayed? """ # print(True) # True # print(type(True)) # bool # print(1 == 1) # True # print(1 == 2) # False # print(1 != 1) # False # print(1 < 2) # True # print(not (-1 <= 1)) # False # print(1 > 2 and 2 < 5) # short-circuit --> False # print(1 > 2 ...
n = int(input()) s = [input().split() for _ in [0] * n] c = 0 for i in s: if i[1] == "JPY": c += int(i[0]) else: c += float(i[0]) * 380000 print(c)
if __name__ == '__main__': print(True) print(3 < 5) if 3 > 2: print('x') my_list = ['2'] my_empty_list = [] if my_empty_list: pass else: print('List is empty') # operateurs arithmetics var = 1 * 2 / 2 - 3 + 5 print(5 % 2) print(5 // 2) # oper...
# -*- coding: utf-8 -*- """\ This is a python port of "Goose" orignialy licensed to Gravity.com under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Python port was written by Xavier Grangier for Recrutae Gravity.co...
# PingPong_Calculator.py def convert_in2cm(inches): return inches * 2.54 def convert_lb2kg(pounds): return pounds / 2.2 height_in = int(input("Enter your height in inches: ")) weight_lb = int(input("Enter your weight in pounds: ")) height_cm = convert_in2cm(height_in) weight_kg = convert_lb2kg(weight_lb) ping_p...
# -*- coding: utf-8 -*- """ Created on Sun Sep 6 20:41:00 2020 @author: 一叶之秋 """ global PATH PATH = r'F:\研二上\钱老板给的项目\项目实现\code\download'
def replace(string, ant, novo): novaString = '' for letra in string: if letra == ant: novaString += novo # Vou concaternar o que eu quero substituir else: novaString += letra # Vou concaternar com a própria letra return novaString # replace(string, ant, novo) print(r...
n = int(input()) count = [0]*5 for _ in range(n): s = list(input()) if s[0] == "M": count[0] += 1 if s[0] == "A": count[1] += 1 if s[0] == "R": count[2] += 1 if s[0] == "C": count[3] += 1 if s[0] == "H": count[4] += 1 ans = 0 for i in range(3): for j ...
class MemLog: """ In-memory Raft log (for testing) """ def __init__(self): self.log = [(0, None)] def get_term(self, index): if index < len(self.log): return self.log[index][0] def append(self, entries): pass def last(self): log_index = len(self.log) -...
# # PySNMP MIB module TRUNK-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRUNK-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:27:43 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23...
"""Statistics""" def counter(li,number): num = 0 for c in li: if c == number: num += 1 return num def occurance_dic(li): dic = {} for number in li: dic[number] = counter(li,number) return dic def mean(li): """Avearage or mean of elements - shaonutil.stats.mean(list of numbers)""" return sum(li)/len(li)...
problem_string = '73167176531330624919225119674426574742355349194934'\ '96983520312774506326239578318016984801869478851843'\ '85861560789112949495459501737958331952853208805511'\ '12540698747158523863050715693290963295227443043557'\ '668966489504452445...
class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if len(prices) <= 1: return 0 ans = 0 for key in range(1, len(prices)): ans += prices[key] - prices[key-1] if prices[key]-prices[key-1]>0 else 0 ...
def genesis_block_generation(): print("\nGenesis Block is generated. The Blockchain system is up...!") print("Miners will now collect transactions from memPool and start building blocks...\n\n") def block_info(block, consensus_algorithm): print("The following block has been proposed by " + block['ge...
# encoding: utf-8 # Versioning convention # https://www.python.org/dev/peps/pep-0440/ __version__ = "0.4.0"
def get_price(auction_id): return 0 def make_bid(bid, auction_id): auction_price = get_price(auction_id) if bid <= auction_price: return False auction_price = bid return True
add_location_schema = { "type": "object", "properties": { "state": {"type": "string"}, "capital": {"type": "string"} }, "required": ["state", "capital"] } update_capital_schema = { "type": "object", "properties": { "capital": {"type": "string"} }, "required": ["c...
def AppendFIFO(list, value, max_values): list.append(value) while len(list) > max_values: list.pop(0) return list def clamp(v, low, high): """clamp v to the range of [low, high]""" return max(low, min(v, high))
a = 12.7 b = 3 x = 5 y = 6 # dodawanie, mnożenie, odejmowanie zapisuje się # i działają one tak jak w normalnej matematyce: e = (a + b) * 4 - y # dzielenie zmiennoprzecinkowe c = x / y #dzielenie całkowite b = a // b # reszta z dzielenia z = x % y; # wypisanie wyników print(e, c, b, z) # operacje logiczne: # ((a...
class Parentheses(object): def find_pair(self, num_pairs): if num_pairs is None: raise TypeError('num_pairs cannot be None') if num_pairs < 0: raise ValueError('num_pairs cannot be < 0') if not num_pairs: return [] results = [] curr_result...
''' * @Author: csy * @Date: 2019-04-28 13:48:03 * @Last Modified by: csy * @Last Modified time: 2019-04-28 13:48:03 ''' age = 12 if age < 4: print("Your admission cost is $0.") elif age < 18: print("Your admission cost is $5.") else: print("Your admission cost is $10.") age = 12 if age < 4: price...
def test_task_names_endpoint(client): tasks_json = client.get(f'api/meta/tasks').json tasks = [task['task_name'] for task in tasks_json] assert {'classification', 'regression', 'ts_forecasting', 'clustering'} == set(tasks) def test_metric_names_classification_endpoint(c...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def closestValue(self, root: TreeNode, target: float) -> int: result = root.val while root: if abs(root.val - target) <...
""" Compatibility layer for Python 3/Python 2 single codebase """ try: _basestring = basestring _bytes_or_unicode = (str, unicode) except NameError: _basestring = str _bytes_or_unicode = (bytes, str)
cooling_type_limits = { 'PASSIVE_COOLING': {'low': 0, 'high':35 }, 'HI_ACTIVE_COOLING': {'low': 0, 'high':45 }, 'MED_ACTIVE_COOLING': {'low': 0, 'high':40 } } boundary_constants_text = {'TOO_LOW':'too low', 'TOO_HIGH':'too high', 'NORMAL': 'normal'} boundary_constants = {'low':'TOO_LOW', 'high': 'TOO_HIGH', 'normal' :...
class SilverbachConjecture: def solve(self, n): ls = [True] * 2001 for i in xrange(2, 2001): if ls[i]: for j in xrange(2 * i, 2001, i): ls[j] = False for i in xrange(2, n - 1): if not ls[i] and not ls[n - i]: return ...
# Advent of Code - Davertical 2 - Part One def result(data): horizontal, vertical = 0, 0 for line in data: direction, i = line.split(' ') i = int(i) if direction == 'forward': horizontal += i if direction == 'up': vertical -= i if direction == '...
# -*- coding: utf-8 -*- # -*- author: JeremySun -*- # -*- dating: 21/4/9 -*- """求斐波那契数列的第n项""" def fibonacci(n): """递归写法,进行了大量子问题的重复计算,所以递归写法效率低""" if n == 1 or n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def fibonacci_non_recurrent(n): """ ...
def distance(puissance: int, reserve: str) -> str: """Calculation of the shooting distance Args: puissance (int): Power of the shot reserve (str): Reserve of flakes Returns: str: Distance reached """ return str(puissance * len(reserve)//2 - 1) + 'm' print(distance(25, '❄️...
""" Lester Interpretor """ class parser( object ): def __init__( self ): self.comment = '#' self.escape = '\\' self.group = '()[]{}' self.string = '"\'' self.token = ' ' self._stack = [] self._text = '' def is_open( self ): return l...
# Codecademy's training document works with Markov_chains.py # Inna I. Ivanova training_doc2 = """ "Papa Don't Preach" Madonna Lyrics Papa, I know you're going to be upset 'Cause I was always your little girl But you should know by now, I'm not a baby You always taught me right from wrong I need your help, daddy, ple...
# # @lc app=leetcode.cn id=277 lang=python3 # # [277] find-the-celebrity # None # @lc code=end
# © its-leo-bitch #!/usr/bin/env python3 # -*- coding: utf-8 -*- class PistonType: def __str__(self) -> str: return f"<{self.__class__.__name__}: {self.__dict__}>" def __repr__(self) -> str: return self.__str__() class Language(PistonType): def __init__( self, r=dict, ...