content
stringlengths
7
1.05M
# Three stones are on a number line at positions a, b, and c. # Each turn, you pick up a stone at an endpoint (ie., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints. Formally, let's say the stones are currently at positions x, y, z with x < y < z. You pick u...
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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 ...
def ha_muito_tempo_atras(): n = int(input()) for i in range(n): anos = int(input()) if anos > 2014: print(f'{anos-2014} A.C.') else: print(f'{2015-anos} D.C.') ha_muito_tempo_atras()
# Problem Set 5 - Problem 3 - CiphertextMessage # # Released 2021-07-07 14:00 UTC+00 # Started 2021-07-08 04:25 UTC+00 # Finished 2021-07-08 04:28 UTC+00 # https://github.com/lcsm29/edx-mit-6.00.1x # # oooo w r i t t e n b y .oooo. .ooooo. # `888 ...
# set representation to bit representation and then return answer # to read input form file a,arr= [],[] start,end = 3,4 with open('Naive Algo\Input\Toycontext(bit)') as file: for line in file: line = line.strip() for c in line: if c != ' ': # print(int(c)) ...
# # PySNMP MIB module PANDATEL-FHFL-MODEM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PANDATEL-FHFL-MODEM-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:28:09 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 ...
# A function to check whether all salaries are equal def areAllEqual(array): s = set(array) if(len(s)==1): return True else: return False # Main code starts here testCases = int(input()) for x in range(testCases): moveCount=0 salArray = [] n = int(input()) for j in range(n):...
""" Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For example, Given n = 3, there are a total of 5 unique BST's. 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ ...
''' Hexdumping functions ''' def hexdump(this, html=True, width=16, prefix=""): ''' Hexdump an artifact ''' txt1 = "" txt2 = "" for n, x in enumerate(this): i = n % width if not i: txt1 = prefix + "%04x " % n txt2 = " ┆" txt1 += " %02x" % x if...
#!/usr/bin/env python3 st = "I am a string."; #intializes string variable print(type(st)); #prints the data type of st y = True; #initializes true boolean variable print(type(y)); #prints the data type of y n = False; #initializes false boolean variable print(type(n)); #prints the data type of n alpha_list = ["a...
""" Q509 Fibonacci number Easy The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n > 1. Given n, calculate F(n). """ class Solutio...
class Foldable: """ A foldable is a data structure that can be collapsed into a single value. """ def fold(self, f, z): """ Apply a two-parameter function `f` to each element of the foldable structure `t a`, passing the result onto the next element. An initial ...
"""workflow_common - common lib for workflow plugins""" __version__ = '0.0.1' __author__ = 'misdirectedpuffin <misdirectedpuffin@gmail.com>' __all__ = []
lst1 = input("First input: ") lst2 = input("Second input: ") lst1 = lst1.split() lst2 = lst2.split() lst2 = sorted(lst2) templst = [] count = 0 while count < int(lst1[1]): #running the loop for k times for elm in lst2: elm = int(elm) if elm <5: #checking if the player is acceptab...
class BinarySearchTree: def __init__(self, value): self.value = value self.left = None self.right = None def insert(self, to_add): if self.value > to_add: if self.left: self.left.insert(to_add) else: self.left = BinarySear...
class Continuous: def __init__(self, cont): self.cont = cont self.string = "ing" vowels = "aeiou" # Get vowels res = set([each for each in cont if each in vowels]) #Convert to string res = ''.join(res) #The exceptions in English if co...
class Solution: def search(self, nums: 'List[int]', target: 'int') -> 'int': rotateindex = 0 n = len(nums) for i in range(n - 1): if nums[i] > nums[i + 1]: rotateindex = i + 1 break left = 0 right = n - 1 while left <= right...
lista = [] for i in range(3): lista.append(int(input('Digite o valor da reta {}: '.format(i + 1)))) lista.sort() if lista[0] + lista[1] > lista[2]: print('As três retas podem formar um triangulo') else: print('As três retas não podem formar um triangulo')
class ZBException(Exception): pass class ZBApiException(ZBException): pass class ZBMissingApiKeyException(ZBException): pass
#!/usr/bin/env python3 def has_cycle(head): curr = head seen = set() while curr: if curr in seen: return True seen.add(curr) curr = curr.next return False # Much better to understand def has_cycle(head): fast = head; while (fast != None and fast.next != None...
__author__ = 'pavelkosicin' def test_validation_check_invalid_email_short_password(app): app.validation.enter_wrong_data(username="p", password="a") app.validation.check_invalid_email_short_password_error_message()
#!/usr/bin/env python __version__ = '0.9.4'
X, Y = map(int, input().split()) flag = False for i in range(100): for j in range(100): if i+j == X and 2*i+4*j == Y: flag = True if flag: print("Yes") else: print("No")
class Solution: """ @param nums: A list of integers @return: A integer indicate the sum of max subarray """ def maxSubArray(self, nums): if len(nums) > 0: maxSum = nums[0] previousSum = nums[0] # maxSumSubArray=[] # currentArray=[nums[0]] ...
def forceAspect(ax, aspect): """ Forces the aspect ratio of an axis onto which an image what plotted with imshow. From: https://www.science-emergence.com/Articles/How-to-change-imshow-aspect-ratio-in-matplotlib-/ """ im = ax.get_images() extent = im[0].get_extent() ax.set_asp...
# 6. Реализовать генератор с помощью функции с ключевым словом yield, создающим очередное значение. # При вызове функции должен создаваться объект-генератор. # Функция должна вызываться следующим образом: for el in fact(n). # Функция отвечает за получение факториала числа, а в цикле необходимо выводить только первые n ...
# Problem Statement : Given a number A, find the smallest number that has same set of digits as A and is greater than A. # Time Complexity : O(N) def SmallestNumberSameSetOfDigitsAsA(A): A_list = list(map(int, A)) l = len(A_list) i = 0 # First we loop in the reverse order to find if there ...
def imposto_de_renda(salario): if 0 <= salario <= 2000.0: return print('Isento') elif 2000.01 <= salario <= 3000.0: imposto_sobre_salario = imposto_de_8(salario) elif 3000.01 <= salario <= 4500.0: imposto_sobre_salario = imposto_de_18(salario) elif salario > 4500.00: impo...
x=[] for i in range(10): x.append(int(input())) if x[i]<=0:x[i]=1 for i in range(10):print(f"X[{i}] = {x[i]}")
# 08_Faça um Programa que pergunte em que turno você estuda. # Peça para digitar M -matutino ou V - Vespertino ou N - Noturno. # Imprima a mensagem "Bom Dia!", "Boa Tarde!" ou "Boa Noite!" ou "Valor Inválido!", # conforme o caso. turno = (input('Digite seu turno sendo: M = matutino, V = vespertino ou N = noturno. ')...
class BFC: order_id = 80 menu = {} def __init__(self) -> None: self.menu = {} def addChicken(self,*args): for elm in range(0,len(args),2): BFC.menu[args[elm]] = args[elm+1] def placeOrderof(self,obj): sum1 = 0 BFC.order_id += 1 print(f"Order ID: {B...
# -*- coding: utf8 -*- """ Test module to be called from C++""" # from __future__ import print_function def add(a, b): """ Returns the sum of two numbers.""" a, b = int(a), int(b) c = str(a + b) print("a = {} and b = {} and a + b = {}".format(a, b, c)) return c
""" Chapter Two - Linked Lists """ # Creating a simple node class. class Node: def __init__(self, data): self.data = data self.next = None self.prev = None # Build a linked list from a list for testing. def llist_from_list(lst): if len(lst) == 0: return None n = N...
# Time O(n) # Space O(n) # More time efficient and applicable for both Sorted and Unsorted Linked List def removeDuplicates(ListNode): if ListNode.head is None: return None current = ListNode.head visited_nodes = set([current.value]) while current.next: if current.next.value in visited...
dest = [0x21, 0x58, 0x33, 0x57, 0x24, 0x2c, 0x66, 0x25, 0x45, 0x53, 0x34, 0x28, 0x08, 0x61, 0x11, 0x07, 0x14, 0x3d, 0x07, 0x62, 0x13, 0x72, 0x02, 0x4c] flag = "" random = 2019 for i in range(24): random = (random * 23333 + 19260817) % 127 flag += chr(random ^ dest[i]) print(flag)
""" Sedan type with 2 sub-types: -Luxury sedan -Sport sedan """ class SedanCar: w_type = 'car' w_meaning = '4+1 doors and a separate trunk' def __init__(self, traction, gen, color, custom): self._traction = traction self._gen = gen self._color = color self._custom ...
""" Doctests: >>> 1 == 1 True """
# File Not Found Error try: file = open("a_text.txt") # a_dictionary = { # "key" : "value" # } # print(a_dictionary["aehdg"]) except FileNotFoundError: file = open("a_text.txt", "w") file.write("Write Something") except KeyError as error_message: print(f"The key {error_message} ...
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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 applicab...
# __ __ __ __ __ __ __ __ __ __ __ __ ___ # |_ / \|\/|/ \ | \|__)|\ /|_ |\ | | \|_ \ /|_ | / \|__)|\/||_ |\ | | # | \__/| |\__/ |__/| \ | \/ |__| \| |__/|__ \/ |__|__\__/| | ||__| \| | # VERSION = (0, 0, 1) __version__ = '.'.join(map(str, VERSION)) #print(__ver...
def fib(n): if n==1 or n == 2: return 1 else: return fib(n-1)+fib(n-2)
n= int(input("Enter the number : ")) sum = 0 temp = n while (n): i = 1 fact = 1 rem = int(n % 10) while(i <= rem): fact = fact * i i = i + 1 sum = sum + fact n = int(n / 10) if(sum == temp): print(temp,end = "") print(" is a strong number") else: print(temp,end = "") print...
def InsertionSubSort(L, k): n = len(L) for i in range(k, n): current = L[i] position = i-k while position >= 0 and current < L[position]: print("omar") L[position + k] = L[position] position -= k L[position + k] = current def ShellSort(L,k): ...
tokens = ['0031834b-ae7c-e116-576f-5bca37d05b78', '01690fff-bad4-8cc7-c9fd-6f1a3617caaf', '01f08ea7-aa8a-751d-2170-fd9d8c6a6d53', '0271ba8e-982e-17f8-0696-df6217651a96', '02c4fe49-f60a-deea-e9a6-62b574351be9', '0308bb28-6e1f-b0f4-c0f1-bab9212069fb', '03af9789-f51f-466e-5030-5129cdb0a556', '04834ee4-d89b-cbb7-922f-7e44d...
n = int(input()) a = [int(i) for i in input().split()] a.sort() res = 10001 for i in range(1, n): tmp = a[i] - a[i-1] if tmp < res: res = tmp print(res)
# collatz conjecture revision # the number we perform the collatz operations on n = 25 # keep looping until we reach 1 while n != 1: print(n) # print the current value of n if n % 2 == 0: # checks if n is even n = n / 2 # if so divide by 2, single / gives decimals, double // gives a whole num...
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( arr , n , k ) : count = 0 arr.sort ( ) l = 0 r = 0 while r < n : if arr [ r ] - arr [ l...
# Copyright (c) 2020 PaddlePaddle 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 appli...
# encoding: utf-8 # module Rhino.FileIO calls itself FileIO # from Rhino3dmIO,Version=5.1.30000.14,Culture=neutral,PublicKeyToken=null # by generator 1.145 # no doc # no imports # no functions # classes class BinaryArchiveException(IOException,ISerializable,_Exception): """ BinaryArchiveException(message:...
# Long lines of method , extracing methods is impossible # from class Order: # ... def price(self): primaryBasePrice = 0 secondaryBasePrice = 0 tertiaryBasePrice = 0 # long computation. # ... pass # to class Order: # ... def price(self): return ...
def _shader_db(var_type, DB): [FLAG, MATERIAL, STR, TEXTURE, INT, FLOAT, BOOL, COLOR, VEC2, VEC3, VEC4, MATRIX, MATRIX_4X2, FOUR_CC] = var_type DB['%compile2dsky'] = FLAG DB['%compileblocklos'] = FLAG DB['%compileclip'] = FLAG DB['%compiledetail'] = FLAG DB['%compilefog'] = FLAG DB['%compile...
class Album: def __init__(self, id, title, file): self.id = id self.title = title self.file = file
for astTuple in Query.input.tuples('ast'): assignment = astTuple.ast leftType = assignment.left.type() rightType = assignment.right.type() if type(leftType) is ArrayType and type(rightType) is ArrayType: if not leftType.elementType().equals(rightType.elementType()): Query.result.add(...
hora_entrada = float (input("informe as horas de entrada :")) min_entrada = float (input("informe os minutos de entrada :")) hora_saida = float (input("informe as horas de saida :")) min_saida = float (input("informe os minutos de saida :")) #caso tempo dentro do estacionamento seja menos que 24 horas if hora_e...
print('=' * 30) print('{:^30}'.format(' BANCO CENTRAL ')) print('=' * 30) v = int(input('Qual valor você deseja sacar? R$ ')) if v / 50: n50 = v / 50 v = v % 50 if v / 20: n20 = v / 20 v = v % 20 if v / 10: n10 = v / 10 v = v % 10 if v / 1: n1 = v / 1 v = v % 1 if n50...
def merge_sort(a): n = len(a) if n <= 1: return a mid = n // 2 # 리스트를 둘로 나눔 g1 = merge_sort(a[:mid]) g2 = merge_sort(a[mid:]) result = [] # 둘로 나눈 리스트 중 하나라도 빌때까지 반복 while g1 and g2: if g1[0] < g2[0]: result.append(g1.pop(0)) else: ...
def add_time(start, duration, requested_day=""): # List for weekdays week_days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") # Convert start string in start list clock = start.split() time = clock[0].split(":") am_pm = clock[1] # Calculate 24hr format ...
# Ejercicio: 4. What is the time complexity in terms of O()? # Autor: Luque Ccosi Paul Alexander # O(n * m) # n : # m : #"fgh" "abcdefghi" # Algoritmo en python def findNeedle(needle, haystack): needle_index = 0 haystack_index = 0 found_needle = False while haystack_index < len(haystack): ...
# Link --> https://www.hackerrank.com/challenges/tree-level-order-traversal/problem # Code: def levelOrder(root): if root: queue = [] queue.append(root) while queue: temp_node = queue[0] queue.pop(0) print(temp_node.info, end = " ") ...
class Zoo: def __init__(self, name, budget, animal_capacity, workers_capacity): self.__budget = budget self.__animal_capacity = animal_capacity self.__workers_capacity = workers_capacity self.name = name self.animals = [] self.workers = [] def add_animal(self, an...
def arrMul(lst): out = [None] * len(lst) prod = 1 i = 0 while i < len(lst): out [i] = prod prod *= lst[i] i += 1 print ("First Four Pass",out) prod = 1 i = len(lst) - 1 while i >= 0: out[i] *= prod prod *= lst[i] i -= 1 ...
''' 插入排序, 平均时间O(n^2), 最好O(n), 最坏O(n^2), 空间O(1), in, 稳定 步骤: 1第一个元素看作有序序列,第二个到最后的元素看作未排序序列 2依次扫描未排序序列,将每个元素插入到有序序列中的适当位置,若有元素相等则插入到后面 ''' def insertionSort(lst): countCompare = 0 countSwap = 0 length = len(lst) print("插入排序") print("数据:{0}".format(lst)) for i in range(length): pre...
#Programa Escola Antenor Reis alunos = list() notas = list() controle = list() media = float() while True: while True: nome = input('Nome: ') if nome.isalpha(): nome = str(nome) break else: print('Informe um nome válido!') controle.append(nome) ...
# # PySNMP MIB module TUBS-IBR-PROC-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TUBS-IBR-PROC-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:27:52 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
class GRPCConfiguration: def __init__(self, client_side: bool, server_string=None, user_agent=None, message_encoding=None, message_accept_encoding=None, max_message_length=33554432): self._client_side = client_side if client_side and server_string is not None: ...
#string method name ="Emanuele Micheletti" print(len(name)) print(name.find("B")) # -1 if not found, index otherwise print(name.capitalize()) print(name.upper()) print(name.lower()) print(name.isdigit()) #false if contains alpha char, True only if all chars are numeric print(name.isalpha()) #space is not alpha print...
# Calculadora em Python # Desenvolva uma calculadora em Python com tudo que você aprendeu nos capítulos 2 e 3. # A solução será apresentada no próximo capítulo! # Assista o vídeo com a execução do programa! soma = lambda num1, num2: num1 + num2 subtracao = lambda num1, num2: num1 - num2 multiplcacao = lambda num1, ...
""" Module: 'websocket' on esp32_LoBo MCU: (sysname='esp32_LoBo', nodename='esp32_LoBo', release='3.2.24', version='ESP32_LoBo_v3.2.24 on 2018-09-06', machine='ESP32 board with ESP32') Stubber: 1.0.0 """ class websocket: '' def close(): pass def ioctl(): pass def read(): pass ...
# Definition for singly-linked list. class _ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def removeElements(self, head: _ListNode, val: int) -> _ListNode: prev = None curr = head while curr is not None: if c...
class PlayFabBaseObject(): pass class PlayFabRequestCommon(PlayFabBaseObject): """ This is a base-class for all Api-request objects. It is currently unfinished, but we will add result-specific properties, and add template where-conditions to make some code easier to follow """ pass class P...
ENVFileTemplate=""" #!/usr/bin/env bash # https://github.com/toggl/toggl_api_docs export TOGGL_API_TOKEN='' # Sometimes you have a billable rate and a non-billable rate. export BILLABLE_RATE='10.0' export NON_BILLABLE_RATE='5.0' export FULFILLMENT_DELAY='30' # Make sure to iterate the invoice number with each use ex...
"""Repeating elements: All elements appear exactly once except one element, we have to find that element. Also all elements from 0 to max of the array are present at least once in the array. Eg: [0, 2, 1, 3, 2, 2] O/P: 2""" """ Solution: """ def repeating_element(a) -> int: n = len(a) for i in range(n): ...
# https://practice.geeksforgeeks.org/problems/distribute-n-candies/1# # try to distribute as many candies as possible in a complete round # when a candies required in a turn are more than left, then # find out the last person to get full turn candy # give remaining to next and return the array class Solution: ...
num = int(input('Digite algum numero: ')) u = num // 1 % 10 d = num // 10 % 10 c = num // 100 % 10 m = num // 1000 % 10 print(f'Analisando numero {num}') if u > 0: print(f'Unidade: {u}') if d > 0: print(f'Dezena: {d}') if c > 0: print(f'Centena: {c}') if m > 0: print(f'Milhar: {m}')
"""Defines a repository rule for configuring the helm executable. """ def _impl(repository_ctx): substitutions = {"%{TOOL_ATTRS}": " target_tool = \"%s\"\n" % repository_ctx.attr.target_tool} repository_ctx.template( "BUILD", Label("@ltd_fox_hound_rules_helm//toolchains/helm:BUILD.tpl"), ...
class Solution: def ipToCIDR(self, ip, n): """ :type ip: str :type n: int :rtype: List[str] """ def iptoint(ip): nums = list(map(int, ip.split('.'))) return sum(num << (32 - (i + 1) * 8) for i, num in enumerate(nums)) def inttoip(num): ...
""" Author: shikechen Function: def FileTool class Version: 6.0 Date: 2019/2/8 """ class PasswordTool: def __init__(self, password): self.password = password self.strength_level = 0 def process_password(self): # Rule 1: length >= 8 if len(self.password) >= 8: ...
# Pandigital products def check_pandigital_product(x, y): if ''.join(sorted(str(x*y)+str(x)+str(y))) == '123456789': return True return False pandig_products = [] for x in range(int(10), int(1e4)): for y in range(int(10), int(1e4)): if len(str(x)+str(y)+str(x*y)) != 9: ...
###################################################################### # Author: Thy H. Nguyen TODO: Change this to your names # Username: nguyent2 TODO: Change this to your usernames # # Assignment: A09: Caesar Cipher # # Purpose: The class imports a file, encrypts the file, and exports the ciph...
# -*- coding: utf-8 -*- class Guild: def __init__(self, data=None): self.id: str = "" self.name: str = "" self.icon: str = "" self.owner_id: str = "" self.owner: bool = False self.member_count: int = 0 self.max_members: int = 0 self.description: str ...
''' - Classificação de cinema ''' class No: def __init__(self, valor=None): self.filme = valor self.alt = 0 self.filho_esq = None self.filho_dir = None # Balanceamento def altura_no(no): if no is None: return -1 return no.alt def fator_balanceamento(no): ret...
def default_state(): state = dict( user_action=[], system_action=[], belief_state={}, cur_domain=None, request_slots=[], terminated=False, history=[], ) state["belief_state"] = { "景点": { "名称": "", "门票": "", "...
""" Given a data stream input of non-negative integers a1, a2, ..., an, ..., summarize the numbers seen so far as a list of disjoint intervals. For example, suppose the integers from the data stream are 1, 3, 7, 2, 6, ..., then the summary will be: 1 [1, 1] 3 [1, 1], [3, 3] 7 [1, 1], [3, 3],...
class PiRGBArray: def __init__(self, *args, **kwargs): self.array = None def truncate(self, _): pass class PiYUVArray: def __init__(self, *args, **kwargs): self.array = None
class Course: def __init__(self,name,ratings): self.name=name self.ratings=ratings def average(self): numberOfRatings= len(self.ratings) average = sum(self.ratings)/numberOfRatings print("Average Ratings For ",self.name," Is ",average) c1 = Course...
'''faça um programa que leia um ano qualquer e mostre se ele é bissexto''' ano = int(input('Digite um ano: ')) #dívisivel por 4 #não ser multiplo de 100 #ser multiplo de 400 if (ano % 4 == 0 and ano % 100 != 0) or ano % 400 == 0: print('O ano {} é bissexto'.format(ano)) else: print('O ano {} não é bissexto'....
class SubClass1: pass class SubClass2: pass async def async_function() -> None: return
GOOGLE_MAP_API_KEY = 'AIzaSyA2b8Zh0rzAJQjwDn0_CZ_tHdPXm6G2Sjs' FIREBASE_FCM_API_KEY = 'AIzaSyAYd8wWQYEJFBzdLJgSGaa1fpJO0OT4APA'
#!/usr/bin/env python """ © Copyright, UbiHPC All rights reserved Developped by Leonardo Camargo Forero, UbiHPC CEO email: lecf.77@gmail.com 2019 High Performance Robotic Computing Cooperative Flying (COFL) simulator This simulator is based on The ARCHADE SimPlat For more information write us in https://ubihpc.com/cont...
# -*- coding: utf-8 -*- class Student(object): def __init__(self, name, score): self.name = name self.score = score def print_score(std): print('%s: %s' % (std.name, std.score)) #print(std.name,std.score) def get_grade(self): if self.score >= 90: retur...
List1=[] user=int(input()) for i in range(user): List1.append(int(input())) n=len(List1) for k in range(n-1): for j in range(n-1-k): if List1[j]>List1[j+1]: List1[j],List1[j+1]=List1[j+1],List1[j] for i in List1: print(i)
class Solution(object): # dp - Bottom up, O(n) space def climbStairs_On(self, n): """ :type n: int :rtype: int """ ls = [0]*(n+1) if n == 0: return 1 if n == 1: return 1 ls[0] = ls[1] = 1 for i ...
# Part of the Crubit project, under the Apache License v2.0 with LLVM # Exceptions. See /LICENSE for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception load("@bazel_tools//tools/build_defs/repo:git.bzl", "new_git_repository") # Create a loader/trampoline repository that we can call into to...
#Fizz Buzz Algorithm def fizzBuzz(input): if (input % 3 == 0) and (input % 5 == 0): return "FizzBuzz" elif input % 3 == 0: return "Fizz" elif input % 5 == 0: return "Buzz" return input data = int(input("Enter any number :")) print(fizzBuzz(data))
def power(base , pow): answer = 1 for index in range(pow): answer = answer * base return answer print(power(2 , 14))
# Only 4xx errors information will be returned currently # https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_errors MSG = "msg" # 400x BAD_REQUEST_4000 = 4000 INVALID_INPUT_4001 = 4001 INVALID_INPUT_4001_MSG = "Invalid inputs." WRONG_CREDENTIALS_4002 = 4002 WRONG_CREDENTIALS_4002_MSG = "Incorrect us...
class WordCleaner: special_char = ['|', '>', '<', '-', '_', ',', '.', '`', ';', ':', '\'', '=', '€', '~', '*', '!', '$', '%', '^', '&', '(', ')', '/', '\\'] frequently_misread_letters = ['Y', 'v', 'V'] @classmethod def remove_single_special_characters...
# Задача №4: # Нарисовать контуры шахматной доски в псевдографике # # =!!= Запускать с помощью Python3 =!!= # формируем строку s = ' ' + ' _'*8 + '\n' \ + '\n'.join( str(8-i)+'|_'*8+'|' for i in range(8) ) + '\n' \ + ' ' + ' '.join( chr( ord('a')+j ) for j in range(8) ) # Выводим A print( s ) # Пояснения: #...
class Solution(object): def coinChangeIter(self, coins, amount): sum = 0 dp = [0 for i in range(amount+1)] for i in range(1, amount+1): min = -1 for coin in coins: if i-coin >= 0 and dp[i-coin] != -1: if min < 0 or dp[i-coin] +1 < ...
# -*- coding: utf-8 -*- """ Created on Mon Dec 2 22:43:50 2019 @author: ZWH """