content
stringlengths
7
1.05M
# Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. # SPDX-License-Identifier: Apache-2.0 load("//bazel_tools:haskell.bzl", "da_haskell_test") load("//bazel_tools/sh:sh.bzl", "sh_inline_test") def damlc_compile_test( name, srcs, main, damlc...
class InfiniteLineup: def __init__(self, players): self.players = players def lineup(self): lineup_max = len(self.players) idx = 0 while True: if idx < lineup_max: yield self.players[idx] else: idx = 0 ...
class StoreObject: def _log_template(self, token): return f"<{token.server.upper()} {token.method}: {' '.join([str(token.params[k]) for k in token.params])}>" async def get(self, token, *args, **kwargs): raise NotImplementedError async def set(self, token, response, *args, **kwargs): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Faça um programa que pergunte quanto você ganha por hora # e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês gph = float(input("Digite o valor ganho por hora: ")) ntm = float(input("Digite o numero de hora trabalhas no mes...
# ------------------------------ # 674. Longest Continuous Increasing Subsequence # # Description: # Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray). # Example 1: # Input: [1,3,5,4,7] # Output: 3 # Explanation: The longest continuous increasing subsequence i...
""" Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. set(key, value) - Set or insert the value if the key is not already...
"""grating_coupler_meep - grating coupler meep""" __version__ = "0.0.1" __author__ = "Simon Bilodeau <<46427609+simbilod@users.noreply.github.com>>" __all__ = []
class SIR: def __init__(self, susceptible, infected, removed, region_id=None): self.region_id = region_id self.susceptible = susceptible self.infected = infected self.removed = removed self.total_pop = susceptible + infected + removed def copy(self): return SIR...
a = 10 b = 22 while b - a > 4: c = b - (2 * a) if c > 0: d = c + 1 else: d = c + 5 a = a + 3 b = b - 2
_html = """<HTML><HEAD><?HEAD><BODY>{}</BODY><?HTML>""" def index_page(): content = """This is a simple api for exploring the <a href="http://www.geonames.org">geonames</a> <a href="http://download.geonames.org/export/dump">data</a>, specificially the cities1000 data, which is cities with population of greater t...
# HEAD # Destructing or Multiple Assignment Operators # DESCRIPTION # Describe incorrect usage of # multiple assignation which throws error # RESOURCES # # The number of items in the destructuring # have to be the same as variables used for assignation cat = ['fat', 'orange', 'loud'] # Will give an err...
pkg_dnf = { 'bind-utils': {}, 'bzip2': {}, 'coreutils': {}, 'curl': {}, 'diffutils': {}, 'file': {}, 'gcc': {}, 'gcc-c++': {}, 'git': {}, 'grep': {}, 'gzip': {}, 'hexedit': {}, 'hostname': {}, 'iotop': {}, 'iputils': {}, 'less': {}, 'lsof': {}, 'ly...
"""NVX Impedance data.""" class Impedance: """Impedance holds impedance data from all EEG channels, as well as GND.""" _INVALID = 2147483647 # INT_MAX (assuming int is 4 bytes) """Invalid (not connected) impedance value.""" def __init__(self, raw_data, count_eeg): self.raw_data = raw_data ...
# A - Set Lot Charge, Piece Price, Added Lead Time variables lot_charge = var('Lot Charge', 0, 'Lot charge for outside_service service', currency) piece_price = var('Piece Price', 0, 'Price per unit for the outside_service service', currency) added_lead_time = var('Added Lead Time', 0, 'Days of added lead time for outs...
# # PySNMP MIB module ZHONE-GEN-VOICESTAT (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHONE-GEN-VOICESTAT # Produced by pysmi-0.3.4 at Wed May 1 15:47:39 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
'''https://practice.geeksforgeeks.org/problems/common-elements1132/1 Common elements Easy Accuracy: 38.69% Submissions: 81306 Points: 2 Given three arrays sorted in increasing order. Find the elements that are common in all three arrays. Note: can you take care of the duplicates without using any additional Data Struc...
# the follow code is for key handover KEY_ACCEPTED = 1 KEY_NOT_ACCEPTED = 0 KEY_DESTINATION = 0 KEY_ESTATE = 1 KEY_ILOCK = 2 KEY_OTHER = 3 # the follow code is for note NOTE_USED = 1 NOTE_DISCARDED = 0 NOTE_TYPE_HOME = 0 NOTE_TYPE_OFFER = 1 NOTE_TYPE_USER = 2 # the follow code is for Utility UTILITY_USED = 1 UTILI...
class Tile: """ map tile properties like opacity and movement block """ def __init__(self,blocked, block_sight=None): self.blocked = blocked #default movement blocking causes sight blocking if block_sight is None: block_sight = blocked self.b...
# -*- coding: utf-8 -*- """ File Name: myPow Author : jing Date: 2020/3/27 https://leetcode-cn.com/problems/powx-n/ Pow(x, n) 需要考虑整数、负数、分数 """ class Solution: def myPow(self, x: float, n: int) -> float: if n < 0: return self.myPow(1 / x, -n) if ...
def mergeSort(lst): pass print(mergeSort([2,3,4,5,15,19,26,27,36,38,44,46,47,48,50] ))
def attach_label_operation(label_id: 'Long' = None, campaign_id: 'Long' = None, ad_id: 'Long' = None, ad_group_id: 'Long' = None, criterion_id: 'Long' = None, customer_id: 'Long' = None, operator: 'String' = 'ADD', ...
valor1 = float(input('Primeiro número: ')) valor2 = float(input('Segundo número: ')) if valor1 > valor2: print('O primeiro número é maior!') elif valor1 < valor2: print('O segundo valor é maior!') else: print('Os dois números são iguais!')
"""Regression Follow jupyter notebook workflow for better understanding of how to apply data_reader and Regression model to train your AI. https://kotsky.github.io/projects/ai_from_scratch/regression_workflow.html Jupiter notebook: https://github.com/kotsky/ai-dev/blob/main/regression_workflow.ipynb Package:...
# Source : https://leetcode.com/problems/shortest-palindrome/ # Author : henrytine # Date : 2020-07-23 ##################################################################################################### # # Given a string s, you are allowed to convert it to a palindrome by adding characters in front of # it. Fin...
# -*- coding: utf-8 -*- """ Created on Tue Feb 14 20:22:47 2017 @author: Zachary """ def f(i): return i + 2 def g(i): return i > 5 def applyF_filterG(L, f, g): listA = [] for i in L: if g(f(i)) == True: listA.append(i) L[:] = listA if len(L) == 0: ...
def update_parameters(parameters, gradients, lr, batch_size, a): parameters["Wax"] = parameters["Wax"] - (lr/batch_size) * gradients["dWax"] parameters["Waa"] = parameters["Waa"] - (lr / batch_size) * gradients["dWaa"] parameters["ba"] = parameters["ba"] - (lr / batch_size) * gradients["dba"] if a == ...
#!/usr/bin/python3 s='ODITSZAPC' p='ba9876420' for comb in range(0, 2**9): x = comb i = 0 c = '' v = 0 while x != 0: f = x % 2 if f == 1: c += s[i] v += 1<<int(p[i], 16) i += 1 x = int(x/2) if c == '': continue print('Z%s = 0x%...
#Escribir un programa que pregunte al usuario una cantidad a invertir, el interés anual y el número de años, y muestre por pantalla el capital obtenido en la inversión cantidad = float(input("¿Cantidad a invertir? ")) interes = float(input("¿Interés porcentual anual? ")) años = int(input("¿Años?")) print("Capital final...
""" author : Ali Emre SAVAS Link : https://www.hackerrank.com/challenges/30-exceptions-string-to-integer/problem """ S = input().strip() try: print(int(S)) except: print("Bad String")
MAX_INT8 = 1 << 7 - 1 MIN_INT8 = -1 << 7 MAX_INT16 = 1 << 15 - 1 MIN_INT16 = -1 << 15 MAX_INT32 = 1 << 31 - 1 MIN_INT32 = -1 << 31 MAX_INT64 = 1 << 63 - 1 MIN_INT64 = -1 << 63 MAX_UINT8 = 1 << 8 - 1 MAX_UINT16 = 1 << 16 - 1 MAX_UINT32 = 1 << 32 - 1 MAX_UINT64 = 1 << 64 - 1
# board # display board # play game # handle turn # check win # check rows # check coumns # check diagonals # check tie # flip player #--------Global Variables------ #Game board board = ["-","-","-", "-","-","-", "-","-","-",] #if game is still going game_still_going = True #Who won? or tie? win...
# -*- coding: utf-8 -*- """ Created on Fri Jun 30 18:29:52 2017 MIT 6.00.1x course on edX.org: Midterm P6 Task: Write a function that satisfies the docstring @author: Andrey Tymofeiuk Important: This code is placed at GitHub to track my progress in programming and to show my way of thinking. Also I will be ha...
def __somefunc__(): return 42 def not_dunder_func(arg1, arg2): """Docstring of function1""" return 42
# 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, l2): p1=l1 p2=l2 count=0 while p1 and p2: count+=p1.val count+=p2.val ...
height = 6 num = 1 for i in range(height,-height-1,-1): for j in range(1,abs(i)+1): print(end=" ") if(i >= 0) : num = 1 else: num = abs(i) + 1; for j in range(height,abs(i)+1,-1): print(num,end=" ") num += 1 print() # ...
f1 = 1 f2 = 2 not_a_flag = 3 print("step: 1") print("stat_1: 0.5") print("stat_2: 0.6") print("step: 2") print("stat_1: 0.7") print("stat_2: 0.8")
# -*- coding: utf-8 -*- """ Created on Sun Oct 27 00:30:31 2019 dogName1 = "One" dogName2 = "Two" dogName3 = "Three" dogName4 = "Four" dogName5 = "Five" dogName6 = "Six" @author: Gunardi Saputra """ print("Enter the name of dog 1: ") dogName1 = input() print("Enter the name of dog 2: ") dogName2 = input() print("E...
load("@obazl_rules_ocaml//ocaml:providers.bzl", "OpamConfig", "BuildConfig") opam_pkg = { "async": ["v0.12.0"], "bignum": ["v0.12.0"], # WARNING: depends on zarith which depends on libgmp-dev on local system "bin_prot": ["v0.12.0"], "core": ["v0.12.1"], "core_kernel": ["v0.12.3"], "digestif": [...
keyFinancialIncomeStatement = [ # Valuation Measures "Revenue", "Total Revenue", "Cost of Revenue", ]
def classic_levenshtein(string_1, string_2): """ Calculates the Levenshtein distance between two strings. This version is easier to read, but significantly slower than the version below (up to several orders of magnitude). Useful for learning, less so otherwise. Usage:: >>> classic_le...
""" 981 time based key-value store medium Create a timebased key-value store class TimeMap, that supports two operations. 1. set(string key, string value, int timestamp) Stores the key and value, along with the given timestamp. 2. get(string key, int timestamp) Returns a value such that set(key, value, timestamp_pr...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: zhlinhng@gmail.com Version: 0.0.1 Created Time: 2016-05-07 Last_modify: 2016-05-07 ****************************************** ''' ''' Given an array of citations (each citation...
""" Module: 'network' on pySBC 1.13.0 with FW1.5.12-264 """ # MCU: (sysname='pySBC', nodename='pySBC', release='1.13.0 with FW1.5.12', version='v1.13-264-gb0c6ec5bb-dirty on 2020-11-25', machine='simpleRTK-SBC with STM32F745') # Stubber: 1.3.4 class SMS: '' def callback(): pass def send(): pass def isbusy()...
# Author: Ben Wichser # Date: 12/12/2019 # Description: Jupiter oon movement. see www.adventofcode.com/2019 (day 12) for more information class Moon: """ Moon class.""" def __init__(self, position_x, position_y, position_z): """Initialization. Creates moon at given position. Creates initial veloc...
# -*- coding: utf-8 -*- """ Created on Sun Feb 26 17:29:16 2017 @author: Thautwarm """ template=\ """ package _PACKAGE_; import _ENTITY_PACKAGE_; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import GraceJava.SQL; import GraceJava.ToStr; public class _ENTITY_CLASS_NAME_Dao exten...
def wordInTarget(word, target): ''' Can a 'word', be made using letters from 'target'. ''' targetlist = list(target) i = 0 while i < len(word): letter = word[i] if letter in targetlist: targetlist.remove(letter) i += 1 else: ...
# coding=utf-8 """ 合并k个排序链表 描述: 合并k个排序链表,并且返回合并后的排序链表。尝试分析和描述其复杂度。 思路: 并归的思想 将数列里的链表 两两合并排序 不断重复,直到只剩一个 """ """ Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param lists: a list of ListNode ...
N = int(input()) first_word = input() W = [input() for _ in range(N - 1)] last = first_word[-1] word_set = set([first_word]) for w in W: if w[0] != last or w in word_set: print("No") break word_set.add(w) last = w[-1] else: print("Yes")
# -*- coding: utf-8 -*- # # Code released in the Public Domain. You can do whatever you want with this package. # Look at NOTES file to see how to adapt this program. # Originally written by Pierre Métras <pierre@alterna.tv> for the OLPC XO laptop. """Module to test set of rules for writing time in full letters, in va...
salario = float(input('Salário do colaborador: ')) print ('------------------------------') print ('* organizações: *') print ('* *') print ('* A *') print ('* B *') print ('* C *') print ('------...
''' este grupo de numeros tiene un bucle, digamos que hacemos el algoritmo para "x" numero la sucesion comenzara con (2, 2x, 2, ... , 2, 2x, 2, ...) donde ... es un bucle entonces cuando 2x aparezca por segunda vez cortamos alli la sucesion y sacamos el maximo ''' def algoritmo(a): lista = [] i = 0 cont = 0 xam = ...
def getConfidenceInterval(df): """ Compute 95% confidence interval (frequentist approach) Args: dataframe: first column is name(string), second column is score(numeric) Return: dataframe(three columns:name,lower_bound,upper_bound) """ pass def getCredibleInterval(df): """ com...
""" https://leetcode.com/problems/special-positions-in-a-binary-matrix/ Given a rows x cols matrix mat, where mat[i][j] is either 0 or 1, return the number of special positions in mat. A position (i,j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexe...
class FpsCounter: def __init__(self, update_interval_seconds = 0.5): """ read self.fps for output """ self.fps = 0. self.interval = update_interval_seconds self._counter = 0. self._age = 0. self._last_output_age = 0. def tick(self, dt): ...
'''> Greater that - True if left operand is greater than the right x > y < Less that - True if left operand is less than the right x < y == Equal to - True if both operands are equal x == y != Not equal to - True if operands are not equal x != y >= Greater than or equal to - True if left operand is greater than or equa...
expected_output = { "vrf": { "default": { "address_family": { "ipv4": { "instance": { "65109": { "areas": { "0.0.0.8": { "database": { ...
'''Faça um programa que leia uma frase pelo teclado e mostre quantas vezes aparece a letra "A", em que posição ela aparece a primeira vez e em que posição ela aparece a última vez.''' frase = str(input('Digite uam Frase: ')).upper() frase.strip() quant = frase.count('A') maius = frase.find('A') print("A Letra A apar...
"""Graphite-beacon -- simple alerting system for Graphite.""" __version__ = "0.27.5" __license__ = "MIT"
{ "variables": { "major_version": "<!(node -pe 'v=process.versions.node.split(\".\"); v[0];')", "minor_version": "<!(node -pe 'v=process.versions.node.split(\".\"); v[1];')", "micro_version": "<!(node -pe 'v=process.versions.node.split(\".\"); v[2];')" }, "targets": [ { ...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def levelOrder(self, root: TreeNode): if not root: return [] parents = [root] res = [] while parents: ...
def get_stats(data, country_list=None): country_list = list(country_list) country_list_slugs = [] country_list_codes = [] error_lst = [] cases = [] new_cases = [] deaths = [] new_deaths = [] recovered = [] new_recovered = [] names = [] codes = [] stats = [] ...
def sum_up_diagonals(matrix): """Given a matrix [square list of lists], return sum of diagonals. Sum of TL-to-BR diagonal along with BL-to-TR diagonal: >>> m1 = [ ... [1, 2], ... [30, 40], ... ] >>> sum_up_diagonals(m1) 73 >>> m2 = [ ....
""" Randy Zhu 11-06-2020 """ number_of_inputs = int(input()) inputs: "list[str]" = [] for _ in range(number_of_inputs): inputs += input().split(" ") # new_inputs = [] # for row in enumerate(inputs): # new_inputs += inputs[row[0]].split(" ") print(inputs)
class Platform: def set_nonblocking(self, read_fd): raise NotImplementedError( "Non-blocking capture not impelemented on this platform" ) def apply_workarounds(self): pass
#이진 탐색 def binary_search(array, target, start, end): if start > end: return None mid = (start+end) // 2 if array[mid] == target: return mid elif array[mid] > target: return binary_search(array, target, start, mid-1) else: return binary_search(array, target, mid+1, end...
#request class DmRequest(object): __slots__ = ['gatewayobj'] def __init__(self, gatewayobj): self.gatewayobj = gatewayobj def DMchannel(self, channel_id): self.gatewayobj.send({'op':self.gatewayobj.OPCODE.DM_UPDATE,'d':{'channel_id':channel_id}})
""" @Author: huuuuusy @GitHub: https://github.com/huuuuusy 系统: Ubuntu 18.04 IDE: VS Code 1.37 工具: python == 3.7.3 """ """ 思路: 递归 结果: 执行用时 : 340 ms, 在所有 Python3 提交中击败了36.03%的用户 内存消耗 : 49.7 MB, 在所有 Python3 提交中击败了5.54%的用户 """ class Solution: def reverseString(self, s): def helper(start,end,ls):...
numbers = [] # Going up first (1st digit cannot be 0) for digit1 in range(1, 10): for digit2 in range(0, 10): for digit3 in range(0, 10): if digit2 > digit1 and digit3 < digit2: numbers.append(str(digit1) + str(digit2) + str(digit3)) # Going down first for digit1 in range(1, 10...
# -*- coding: utf-8 -*- """ Handler utility to parse slicing keys. """ def parse_slice(ds_slice): """ Parse dataset slice Parameters ---------- ds_slice : tuple | int | slice | list Slice to extract from dataset Returns ------- ds_slice : tuple slice for axis (0, 1) ...
def MeasureTime( v, t ): sT = time.process_time( ) leer_matriz(v, t) triangulo_superior(v, t) eT = time.process_time( ) return float( eT - sT ) def leer_matriz(v, t): for i in range (t): for j in range (t): print ("Escriba el elemento %u de la columna %u: ", j+1, i+1) v[i][j] = input() for...
a = 'In this letter I make some remarks on a general principle relevant to enciphering in general and my machine.' b = 'If qualified opinions incline to believe in the exponential conjecture, then I think we cannot afford not to make use of it.' c = 'The most direct computation would be for the enemy to try all 2^r pos...
weight=1 def run(): r.absrot(90) r.absrot(0) r.absrot(-90) r.absrot(90)
__author__ = 'Aaron Yang' __email__ = 'byang971@usc.edu' __date__ = '8/14/2020 6:00 PM' class Solution: def __init__(self): self.data = ['1', '11', '21', '1211', '111221'] def read(self, string): pre = string[0] count = 1 res = [] for val in string[1:]: if...
''' Given an int array length 2, return True if it contains a 2 or a 3. has23([2, 5]) → True has23([4, 3]) → True has23([4, 5]) → False ''' def has23(nums): if len(nums) != 2: return 0 if 2 in nums or 3 in nums: return True return False
class JobState(basestring): """ Jobs execute as self-contained state machines. They follow a series of careful steps from creation to destruction. These steps are dictated by the states that they find themselves in as well as the allowable list of states they may transition into. The state can...
vcasa = float(input('Valor da casa: R$')) salario = float(input('Salário do comprador: R$')) anos = int(input('Quantos anos de financiamento: ')) prestacao = vcasa / (anos * 12) minimo = salario * 30 / 100 if prestacao <= minimo: print('APROVADO. Parcela R${:.2f}'.format(prestacao)) else: print('NEGADO')
# Sorting ## Sorting with keys airports = [ ('MROC', 'San Jose, CR'), ('KLAS', 'Las Vegas, USA'), ('EDDM', 'Munich, DE'), ('LSZH', 'Zurich, CH'), ('VNLK', 'Lukla, NEP') ] sorted_airports = dict(sorted(airports, key=lambda x:x[0])) print(sorted_airports)
# Create Trend Filter to remove linear, annual, and semi-annual trend fl_tf = skdiscovery.data_structure.table.filters.TrendFilter('TrendFilter', []) # Create stage container for the trend filter sc_tf = StageContainer(fl_tf)
# encode categorical protocol name to number def encode_protocol(text): # put frequent cases to the front if 'tcp' in text: return 6 elif 'udp' in text: return 17 elif 'icmp' in text: return 1 elif 'hopopt' in text: return 0 elif 'igmp' in text: return 2 elif 'ggp' in text: return ...
class WebServer: def __init__(): pass
class super: name ="" age ="" def set_user(self,a,b): self.name = a self.age = b def show(self): print(str(self.name)) print(str(self.age)) class sub(super): def pp(self): print("Python") obj1 = sub() obj1.set_user("AungMoe...
# Python3 code to find the element that occur only once INT_SIZE = 32 def getSingle(arr, n) : result = 0 for i in range(0, INT_SIZE) : sm = 0 x = (1 << i) for j in range(0, n) : if (arr[j] & x) : sm = sm + 1 if ((sm % 3)!= 0) : result = result | x return result arr = [12, 1, 12, 3, 1...
# -*- coding: utf-8 -*- __about__ = """ This project demonstrates the use of a waiting list and signup codes for sites in private beta. Otherwise it is the same as basic_project. """
""" Convert a non-negative integer num to its English words representation. Example 1: Input: num = 123 Output: "One Hundred Twenty Three" Example 2: Input: num = 12345 Output: "Twelve Thousand Three Hundred Forty Five" Example 3: Input: num = 1234567 Output: "One Million Two Hundred Thirty Four Thousand Five Hun...
#!/usr/bin/env python __version__ = "3.0.0" version = __version__
def closest_intersections(first_wire, second_wire): least_no_of_steps = None shortest_mh_distance = None steps_taken_first = 0 point_a_first = (0, 0) for instr_first in first_wire: point_b_first, steps_to_b_first = next_point(point_a_first, instr_first) steps_taken_second = 0 ...
_COURSIER_CLI_VERSION = "2.12" _COURSIER_VERSION = "1.1.0-M9" COURSIER_CLI_SHA256 = "8e7333506bb0db2a262d747873a434a476570dd09b30b61bcbac95aff18a8a9b" COURSIER_CLI_MAVEN_PATH = "io/get-coursier/coursier-cli_{COURSIER_CLI_VERSION}/{COURSIER_VERSION}/coursier-cli_{COURSIER_CLI_VERSION}-{COURSIER_VERSION}-standalone.jar"....
userinput = "" print("Before User input ", userinput) userinput = input("EnterSomething :") print("After User input ", userinput)
''' WRITTEN BY Ramon Rossi PURPOSE The prime number is position one is 2. The prime number in position two is 3. The prime number is position three is 5. This function is_prime() finds the prime number at any position. It accepts an integer as an argument which is the position of the prime number t...
ter = 'i+*()#' nonter = 'EDTSF' analysis_table = [ [' ', 'i', '+', '*', '(', ')', '#'], ['E', 'TD', '', '', 'TD', '', ''], ['D', '', '+TD', '', '', 'ε', 'ε'], ['T', 'FS', '', '', 'FS', '', ''], ['S', '', 'ε', '*FS', '', 'ε', 'ε'], ['F', 'i', '', '', '(E)', '', ''], ] stack_str = '#E' ptr = 0
# -*- coding: utf-8 -*- # @Author: Anderson # @Date: 2018-10-05 01:44:18 # @Last Modified by: Anderson # @Last Modified time: 2018-11-26 11:20:20 def anagrams(strs): word_dict = {} for word in strs: sorted_word = ''.join(sorted(word)) if sorted_word not in word_dict: word_dict[...
# Aluguel de carro dias = int(input('Quantos dias o carro foi alugado?')) km = float(input('Quantos km rodados?')) # Preço a pagar... R$60/dia e R$0.15/kmrodado print('O preço a pagar pelo aluguel do carro é R${}'.format(60*dias + 0.15*km))
name = input("Enter your name: ") print("Your name is", name, ".") age = int(input("Enter your age: ")) if age > 18: print(name, "is", age, "years old.") height = float(input("Enter your Height(cm):")) if height > 0: print("That's a positive size!") weight = float(input("Enter your Weigh...
t=int(input()) for i in range(t): n=int(input()) dp=[0 for i in range(n+1)] dp[0]=1 dp[1]=1 for i in range(2,n+1): for j in range(0,i): dp[i]+=dp[j]*dp[i-j-1] print(dp[n])
""" descriptor ДЕСКРИПТОР это атрибут объекта который связан с его поведением фактически descriptor является инкапсулированием протокола взаимодействия с атрибутом соединение descriptor-ра с классом protocol __get__ __set__ __delete__ descriptor определяет как формируется доступ к кому-то атрубуту или ф-и descriptor он...
# You have a red lottery ticket showing ints a, b, and c, each of which is 0, 1, or 2. # If they are all the value 2, the result is 10. # Otherwise if they are all the same, the result is 5. # Otherwise so long as both b and c are different from a, the result is 1. # Otherwise the result is 0. # Write a function t...
#!/usr/bin/env python3 """player module.""" class Player: """Player for Checkers.""" def __init__(self, token): """Initialize object.""" self._token = token.lower() self._unpromoted = 12 self._promoted = 0 self._total = self._unpromoted + self._promoted def get_to...
# 1 Write a Python function, which gets 2 numbers, and return True if the second number is first number divider, otherwise False. def divider(a, b): if b % a == 0: return True else: return False # 2 Write a Python function, which gets a number, and return True if that number is palindrome, oth...
def get_fibonacci_huge(n): if n <= 1: return n previous = 0 current =1 sum = 1 for __ in range(2,n+1): previous,current = current, previous+current sum = sum+(current*current) # print(sum, ' ', current*current) return sum%10 if __name__ == '__main__': n ...
class Particle(object): def __init__(self, sprite): self.gravity = PVector(0, 0.1) self.lifespan = 255 self.velocity = PVector() partSize = random(10, 60) self.part = createShape() self.part.beginShape(QUAD) self.part.noStroke() self.part.texture(spri...