content
stringlengths
7
1.05M
__author__ = 'roeiherz' """ Given two straight line segments (represents as a start point and end point), compute the point of intersection, if any. """ class Line: def __init__(self, point1, point2): self.point1 = point1 self.point2 = point2 self.m = self.slope() self.n = self.ge...
def sortStack(stack): if len(stack) == 0: return stack top = stack.pop() sortStack(stack) insertInSortedOrder(stack, top) return stack def insertInSortedOrder(stack, value): if len(stack) == 0 or stack[-1] <= value: stack.append(value) return top = stack.pop() ...
def safe_strftime(d, format_str='%Y-%m-%d %H:%M:%S') -> str: try: return d.strftime(format_str) except Exception: return ''
# WebSite Name WebSiteName = 'Articles Journal' ###################################################################################### # Pages __HOST = 'http://127.0.0.1:8000' ############# # Register SignUP = __HOST + '/Register/SignUP' SignUP_Template = 'Register/SignUP.html' Login = __HOST + '/Register/Login' L...
def compute_opt(exact_filename, preprocessing_filename): datasets = set() # Dataset names exact_solution_lookup = {} # Maps dataset names to OPT with open(exact_filename, 'r') as infile: # Discard header infile.readline() for line in infile.readlines(): line = line.split...
brd = { 'name': ('StickIt! MPU-9150 V1'), 'port': { 'pmod': { 'default' : { 'scl': 'd1', 'clkin': 'd2', 'sda': 'd3', 'int': 'd5', 'fsync': 'd7' } }, 'wing': { ...
def for_K(): """ Upper case Alphabet letter 'K' pattern using Python Python for loop""" for row in range(6): for col in range(4): if col==0 or row+col==3 or row-col==2: print('*', end = ' ') else: ...
class BlockTerminationNotice(Exception): pass class IncorrectLocationException(Exception): pass class SootMethodNotLoadedException(Exception): pass class SootFieldNotLoadedException(Exception): pass
class TipoCadastro: nomeC = '' dataN = '' tel = 0 ender = '' serie = 0 def menu(): vetAluno = [] while True: print('__'*30) print('Menu de opções:') print('1.Cadastrar alunos') print('2.Consulta por nome') print('3.Visualizar todos os dados') ...
# description: various useful helpers class DataKeys(object): """standard names for features and transformations of features """ # core data keys FEATURES = "features" LABELS = "labels" PROBABILITIES = "probs" LOGITS = "logits" LOGITS_NORM = "{}.norm".format(LOGITS) ORIG_SEQ ...
class Corner(object): def __init__(self, row, column, lines): self.row = row self.column = column self.lines = lines self.done = False for line in self.lines: line.add_corner(self) self.line_number = None def check_values(self): if self.done:...
#Table used for the example 2split.py ################################################################################################# source_path = "/home/user/Scrivania/Ducks/"# Where the images are output_path = "/home/user/Scrivania/Ducks/"# Where the two directory with the cutted images will be stored RIGHT_CUT_...
''' Exercício Python 081: Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, mostre: A) Quantos números foram digitados. B) A lista de valores, ordenada de forma decrescente. C) Se o valor 5 foi digitado e está ou não na lista. ''' num = [] while True: num.append(int...
def logic(value, a, b): if value: return a return b hero.moveXY(20, 24); a = hero.findNearestFriend().getSecretA() b = hero.findNearestFriend().getSecretB() c = hero.findNearestFriend().getSecretC() hero.moveXY(30, logic(a and b and c, 33, 15)) hero.moveXY(logic(a or b or c, 20, 40), 24) hero.moveXY(3...
def a(mem): seen = set() tup = tuple(mem) count = 0 while tup not in seen: seen.add(tup) index = 0 max = 0 for i in range(len(mem)): n = mem[i] if(n > max): max = n index = i mem[index] = 0 index += 1 while(max > 0): ...
def mergeSort(l): if len(l) > 1: mid = len(l) // 2 L = l[:mid] R = l[mid:] mergeSort(L) mergeSort(R) i = j = k = 0 while i < len(L) and j < len(R): if L[i] < R[j]: l[k] = L[i] i += 1 else: ...
class Solution: def minAbbreviation(self, target: str, dictionary: List[str]) -> str: m = len(target) def getMask(word: str) -> int: # mask[i] = 0 := target[i] == word[i] # mask[i] = 1 := target[i] != word[i] # e.g. target = "apple" # word = "blade" # mask = 11110...
#! python3 # __author__ = "YangJiaHao" # date: 2018/2/8 class Solution: def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ if len(digits) <= 0: return [] keys = [[''], [''], ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ...
{ "targets": [ { "target_name": "example", "sources": [ "example.cxx", "example_wrap.cxx" ] } ] }
'''exemplo1''' print('Olá Mundo') print(5 + 10) print('5'+'10') '''#exemplo2''' print('Olá Mundo', 10) '''#exemplo3''' nome = 'Xand_LIn' idade = 20 peso = 55 print('Nome:', nome, '\nidade:', idade, '\nPeso:', peso) '''#exemplo4''' nome1 = input('Qual é o seu nome?: ') idade1 = input('Sua idade?: ') peso1 = input('Qual ...
# Event: LCCS Python Fundamental Skills Workshop # Date: Dec 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Solution to programming exercises 6.1 Q2 # Purpose: A program to find the GCD of any two positive integers # Determines if one number is a factor of the other def isFactor(a1, a2):...
assert format(5, "b") == "101" try: format(2, 3) except TypeError: pass else: assert False, "TypeError not raised when format is called with a number"
#!/usr/bin/env python3 names = ['Alice', 'Bob', 'John'] for name in names: print(name)
''' Exception classes for cr-vision library ''' # Definitive guide to Python exceptions https://julien.danjou.info/python-exceptions-guide/ class CRVError(Exception): '''Base exception class''' class InvalidNumDimensionsError(CRVError): '''Invalid number of dimensions error''' class InvalidNumChannelsErro...
# 存在安全风险 doc_title_html_tag = '<div class="doc_title">{}</div>' doc_info_html_tag = '<div class="doc_info">{}</div>' doc_body_html_tag = '<div class="doc_line"">{}</div>' doc_empty_lint_tag = '<div style="height: 10pt;"></div>' class LegalDoc(object): def __init__(self, title: str = None, court: str = None, case...
# pylint: disable=too-many-instance-attributes # number of attributes is reasonable in this case class Skills: def __init__(self): self.acrobatics = Skill() self.animal_handling = Skill() self.arcana = Skill() self.athletics = Skill() self.deception = Skill() self.h...
class TestResult: def __init__(self, test_case) -> None: self.__test_case = test_case self.__failed = False self.__reason = None def record_failure(self, reason: str): self.__reason = reason self.__failed = True def test_case(self) -> str: return type(self._...
# -*- coding: utf-8 -*- def get_tokens(line): """tokenize a line""" return line.split() def read_metro_map_file(filename): """read ressources from a metro map input file""" sections = ('[Vertices]', '[Edges]') vertices = dict(); edges = list(); line_number = 0 section = None wit...
#!/usr/bin/python #-*-coding:utf-8-*- '''This packge contains the UCT algorithem of the UAV searching. The algorithem conform to the standard OperateInterface defined in the PlatForm class.''' __all__ = ['UCTControl', 'UCTSearchTree', 'UCTTreeNode']
# --- Starting python tests --- #Funct def functione(x,y): return x*y # call print(format(functione(2,3)))
# # CLASS MEHTODS # class Employee: # company ="camel" # salary = 100 # location = "mumbai" # def ChangeSalary(self, sal): # self.__class__.salary = sal # # THE EASY METHOD FOR THE ABOVE STATEMENT AND FOR THE CLASS ATTRIBUTE IS # @classmethod # def ChangeSalary(cls, sal): # ...
# Marcelo Campos de Medeiros # ADS UNIFIP 2020.1 # Patos-PB 17/03/2020 ''' Tendo como dado de entrada a altura (h) de uma pessoa, construa um algoritmo que calcule seu peso ideal, utilizando as seguintes fórmulas: Para homens: (72.7*h) - 58 Para mulheres: (62.1*h) - 44.7 ''' print('='*43) print('PROGRAMA PESO ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def bubble_sort(arr): for n in range(len(arr)-1, 0, -1): for k in range(n): if r[k] > r[k+1]: tmp = r[k] r[k] = r[k+1] r[k+1] = tmp if __name__ == '__main__': r = [5, 4, 2, 3, 1] bubble_sor...
# Let's say you have a dictionary matchinhg your friends' names # with their favorite flowers: fav_flowers = {'Alex': 'field flowers', 'Kate': 'daffodil', 'Eva': 'artichoke flower', 'Daniel': 'tulip'} # Your new friend Alice likes orchid the most: add this info to the # fav_flowers dict and print the di...
num1 = float(input("Enter 1st number: ")) op = input("Enter operator: ") num2 = float(input("Enter 2nd number: ")) if op == "+": val = num1 + num2 elif op == "-": val = num1 - num2 elif op == "*" or op == "x": val = num1 * num2 elif op == "/": val = num1 / num2 print(val)
def count_substring(string, sub_string): times = 0 length = len(sub_string) for letter in range(0, len(string)): if string[letter:letter+length] == sub_string: times += 1 return times
#!/usr/bin/pthon3 # Time complexity: O(N) def solution(A): count = {} size_A = len(A) leader = None for i, a in enumerate(A): count[a] = count.get(a, 0) + 1 if count[a] > size_A // 2: leader = a equi_leader = 0 before = 0 for i in range(size_A)...
class Solution: def isHappy(self, n): """ :type n: int :rtype: bool """ tried = set() while n not in tried and n != 1: tried.add(n) n2 = 0 while n > 0: n2, n = n2 + (n % 10) ** 2, n // 10 n = n2 r...
salhora=15 horasT=int(input('Informe quantas horas voce trabalhou esta semana: ')) if horasT<=40: salario = salhora * horasT print('O salário é {0:.2f}'.format(salario)) elif horasT>40: salario = salhora * horasT salarioextra = (horasT-40)*0.5+salario print('O salário é {0:.2f}'.format(sala...
n1 = int(input('digite um valor >>')) n2 = int(input('digite outro vaor >>')) n3 = int(input('digite outro valor >>')) #menor menor = n1 if n2 < n1 and n2 < n3: menor = n2 if n3 < n1 and n3 < n2: menor = n3 #maior maior = n1 if n2 > n1 and n2 > n3: maior = n2 if n3 > n1 and n3 > n2: maior = n3 print('o ...
def fahrenheit_to_celsius(deg_F): """Convert degrees Fahrenheit to Celsius.""" return (5 / 9) * (deg_F - 32) def celsius_to_fahrenheit(deg_C): """Convert degrees Celsius to Fahrenheit.""" return (9 / 5) * deg_C + 32 def celsius_to_kelvin(deg_C): """Convert degree Celsius to Kelvin.""" return...
class TypeFactory(object): def __init__(self, client): self.client = client def create(self, transport_type, *args, **kwargs): klass = self.classes[transport_type] cls = klass(*args, **kwargs) cls._client = self.client return cls
# Copyright 2020-present Kensho Technologies, LLC. """Tools for constructing high-performance query interpreters over arbitrary schemas. While GraphQL compiler's database querying capabilities are sufficient for many use cases, there are many types of data querying for which the compilation-based approach is unsuitabl...
length = float(input("Enter the length of a side of the cube: ")) total_surface_area = 6 * length ** 2 volume = 3 * length ** 2 print("The surface area of the cube is", total_surface_area) print("The volume of the cube is", volume) close = input("Press X to exit") # The above code keeps the program op...
#========================================================================================= class Task(): """Task is a part of Itinerary """ def __init__(self, aName, aDuration, aMachine): self.name = aName self.duration = aDuration self.machine = aMachine self.taskChanged = Fals...
""" lec 4, tuple and dictionary """ my_tuple='a','b','c','d','e' print(my_tuple) my_2nd_tuple=('a','b','c','d','e') print(my_2nd_tuple) test='a' print(type(test)) #not a tuple bc no comma Test='a', print(type(Test)) print(my_tuple[1]) print(my_tuple[-1]) print(my_tuple[1:3]) print(my_tuple[1:]) print(my_tuple[:3]) ...
n = int (input()) for i in range(1,n+1): b = str (input()) if "кот" in b or "Кот": print ("may") else: print("no")
def generate(): class Spam: count = 1 def method(self): print(count) return Spam() generate().method()
def add(a, b): """Adds a and b.""" return a + b if __name__ == '__main__': assert add(2, 5) == 7, '2 and 5 are not 7' assert add(-2, 5) == 3, '-2 and 5 are not 3' print('This executes only if I am main!')
# Title : Generators in python # Author : Kiran raj R. # Date : 31:10:2020 def printNum(): num = 0 while True: yield num num += 1 result = printNum() print(next(result)) print(next(result)) print(next(result)) result = (num for num in range(10000)) print(result) print(next(result)) print(...
""" Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. """ class Solution(object): def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ if numRows==0: return [] if numRows==1: retu...
def funcion(nums,n): print(nums) res = [] for i in range(len(nums)): suma = 0 aux = [] suma += nums[i] for j in range(i+1,len(nums)): print(i,j) if suma + nums[j] == n: aux.append(nums[i]) aux.append(nums[j]) ...
class Solution: def findRadius(self, houses, heaters): """ :type houses: List[int] :type heaters: List[int] :rtype: int """ houses.sort() heaters.sort() radius = 0 i = 0 for house in houses: while i < len(heaters) and heater...
""" A list of the custom settings used on the site. Many of the external libraries have their own settings, see library documentation for details. """ VAVS_EMAIL_FROM = 'address shown in reply-to field of emails' VAVS_EMAIL_TO = 'list of staff addresses to send reports to' VAVS_EMAIL_SURVEYS = 'address to send s...
class TestHLD: # edges = [ # (0, 1), # (0, 6), # (0, 10), # (1, 2), # (1, 5), # (2, 3), # (2, 4), # (6, 7), # (7, 8), # (7, 9), # (10, 11), # ] # root = 0 # get_lca = lca_hld(edges, root) # print(get_lca(3, 5))...
input = """ ok:- #count{V:b(V)}=X, not p(X). b(1). p(2). """ output = """ ok:- #count{V:b(V)}=X, not p(X). b(1). p(2). """
# # PySNMP MIB module OVERLAND-NEXTGEN (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OVERLAND-NEXTGEN # Produced by pysmi-0.3.4 at Wed May 1 14:35:46 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
class Solution(object): def XXX(self, x): """ :type x: int :rtype: int """ if x==0: return 0 x = (x//abs(x)) * int(str(abs(x))[::-1]) if -2 ** 31 < x < 2 ** 31 - 1: return x return 0
class Solution: def diStringMatch(self, S: str): l = 0 r = len(S) ret = [] for i in S: if i == "I": ret.append(l) l += 1 else: ret.append(r) r -= 1 ret.append(r) return ret slu =...
#CONSIDER: composable authorizations class Authorization(object): ''' Base authorization class, defaults to full authorization ''' #CONSIDER: how is this notified about filtering, ids, etc def __init__(self, identity, endpoint): self.identity = identity self.endpoint = endpoint ...
# Len of signature in write signed packet SIGNATURE_LEN = 12 # Attribute Protocol Opcodes OP_ERROR = 0x01 OP_MTU_REQ = 0x02 OP_MTU_RESP = 0x03 OP_FIND_INFO_REQ = 0x04 OP_FIND_INFO_RESP = 0x05 OP_FIND_BY_TYPE_REQ = 0x06 OP_FIND_BY_TYPE_RESP= 0x07 OP_READ_BY_TYPE_REQ = 0x08 OP_READ_BY_TYPE_RESP = 0x09 OP_READ_REQ = 0x0...
''' Description: ------------ When objects are instantiated, the object itself is passed into the self parameter. The Object is passed into the self parameter so that the object can keep hold of its own data. ''' print(__doc__) print('-'*25) class State(object): def __init__(self): global x...
# -*- coding: utf-8 -*- phrases_map = { 'caro': 'Vicky > Caro', 'vicky': 'Vicky 😍😍😍', 'gracias por venir': '¡Gracias por estar!', 'facho': 'callate zurdito', 'zurdito': 'callate gorilón', 'ayy': 'ayylmaokai', 'lmao': 'ayy', 'al toque': 'TO THE TOUCH', 'distro': 'https://distrowatch.com', 'roger': 'LINUX >...
# escreva um programa que leia dois numeros inteiros e compare-os. # mostrando na tela uma mensagem: # o primeiro valor é maior # o segundo valor é maior # não existe valor maior, os dois são iguais n1 = int(input('Dê um número inteiro: ')) n2 = int(input('Dê mais um: ')) if n1 > n2: print('O primeiro valor é maio...
# # @lc app=leetcode id=611 lang=python3 # # [611] Valid Triangle Number # # https://leetcode.com/problems/valid-triangle-number/description/ # # algorithms # Medium (49.73%) # Likes: 1857 # Dislikes: 129 # Total Accepted: 109.5K # Total Submissions: 222.7K # Testcase Example: '[2,2,3,4]' # # Given an integer ar...
""" Objects dealing with EBUS boundaries for plotting, statistics, etc. Functions --------- - `visual_bounds` : lat/lon bounds for close-up shots of our regions. - `latitude_bounds` : lat bounds for statistical analysis To do ----- - `full_scope_bounds` : regions pulled from Chavez paper for lat/lon to show full system...
"""from discord.ext import commands import os import discord import traceback import asyncio import random rbtflag = False bot = commands.Bot(command_prefix='.', description='自動でチーム募集をするBOTです') client = discord.Client() token = os.environ['DISCORD_BOT_TOKEN'] recruit_message = {} lastest_recruit_data = {} cache_limi...
#Calcula o volume de uma fossa sépica para estabelecimentos residenciais em conformidade com a NBR 7229/1993 ''' Entre com os dados da Fossa Séptica ''' print(' Dimensionamento de uma Fossa Séptica pra estabelecimentos residenciais em conformidade com a NBR 7229/1993:') N = 1 while N != 0: N = int(input('Digite...
# Computers are fast, so we can implement a brute-force search to directly solve the problem. def compute(): PERIMETER = 1000 for a in range(1, PERIMETER + 1): for b in range(a + 1, PERIMETER + 1): c = PERIMETER - a - b if a * a + b * b == c * c: # It is now implied that b < c, because we have a > 0 r...
{ "targets": [ { "target_name": "yolo", "sources": [ "src/yolo.cc" ] } ] }
archivo = open('paises.txt', 'r') """" for pais_y_capital in archivo: print(pais_y_capital) """ #1. Cuente e imprima cuantas ciudades inician con la letra M """ archivo = open('paises.txt', 'r') lista=[] ciudad=[] for i in archivo: a=i.index(":") for r in range(a+2,len(i)): lista.append(i[r]) a="".join(list...
class Docs(object): def __init__(self, conn): self.client = conn.client def size(self): r = self.client.get('/docs/size') return int(r.text) def add(self, name, content): self.client.post('/docs', files={'upload': (name, content)}) def clear(self): self.client....
class SlowDisjointSet: def __init__(self, N): self.N = N self._bubbles = [] for i in range(N): self._bubbles.append({i}) self._operations = 0 self._calls = 0 def _find_i(self, i): """ Find the index of the bubble that holds a particular ...
# -*- coding: utf-8 -*- class SmsTypes: class Country: RU = '0' # Россия (Russia) UA = '1' # Украина (Ukraine) KZ = '2' # Казахстан (Kazakhstan) CN = '3' # Китай (China) # PH = '4' # Филиппины (Philippines) MM = '5' # Мьянма (Myanmar) # ID = '6' # Индонезия (Indonesia) # MY = '7' # Малайзия (...
#!/bin/env python3 option = input("[E]ncryption, [D]ecryption, or [Q]uit -- ") def key_generation(a, b, a1, b1): M = a * b - 1 e = a1 * M + a d = b1 * M + b n = (e * d - 1) / M return int(e), int(d), int(n) def encryption(a, b, a1, b1): e, d, n = key_generation(a, b, a1, b1) print("You ma...
#!/usr/bin/env python # coding: utf-8 # # Seldon Kafka Integration Example with CIFAR10 Model # # In this example we will run SeldonDeployments for a CIFAR10 Tensorflow model which take their inputs from a Kafka topic and push their outputs to a Kafka topic. We will experiment with both REST and gRPC Seldon graphs. F...
# Code generated by ./release.sh. DO NOT EDIT. """Package version""" __version__ = "0.9.5-dev"
# Creates the file nonsilence_phones.txt which contains # all the phonemes except sil. source = open("slp_lab2_data/lexicon.txt", 'r') phones = [] # Get all the separate phonemes from lexicon.txt. for line in source: line_phones = line.split(' ')[1:] for phone in line_phones: phone = phone.strip(' ') ...
""" A basic doubly linked list implementation @author taylor.osmun """ class LinkedList(object): """ Internal object representing a node in the linked list @author taylor.osmun """ class _Node(object): def __init__(self, _data=None, _next=None, _prev=None): self.data = _data ...
class Computer(): def __init__(self, model, memory): self.mo = model self.me = memory c = Computer('Dell', '500gb') print(c.mo,c.me)
""" add 2 number """ def add(x, y): return x + y """ substract y from x """ def substract(x, y): return y - x
# Hier sehen wir, wie man eine Schleife baut # range macht uns eine Folge von Zahlen for index in range(10): # ab hier wird um 4 Leerzeichen eingerückt, so lange bis die Schleife vorbei ist print(index) # hier kommt alles, was die Schleife tun soll print('Jetzt sind wir fertig') # Bis zu welcher Zahl zähl...
#!/usr/bin/env python files = [ "dpx_nuke_10bits_rgb.dpx", "dpx_nuke_16bits_rgba.dpx" ] for f in files: command += rw_command (OIIO_TESTSUITE_IMAGEDIR, f) # Additionally, test for regressions for endian issues with 16 bit DPX output # (related to issue #354) command += oiio_app("oiiotool") + " src/input_rgb_matt...
# https://leetcode.com/problems/remove-nth-node-from-end-of-list/ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode} head # @param {integer} n # @return {ListNode} def removeNthFromEn...
def validate_required_kwargs_are_not_empty(args_list, kwargs): """ This function checks whether all passed keyword arguments are present and that they have truthy values. ::args:: args_list - This is a list or tuple that contains all the arguments you want to query for. The arguments are strings seperat...
__author__ = 'roeiherz' """ Design a method to find the frequency of occurrences of any given word in a book. What if we were running this algorithm multiplies times. """ def create_hashmap(book): hash_map = {} words = book.split(' ') for word in words: process_word = word.lower().replace(',', '...
def get_url(): return None result = get_url().text print(result)
myStr = input("Enter a String: ") count = 0 for letter in myStr: count += 1 print (count)
a = 1 b = 2 c = 3 def foo(): a = 1 b = 2 c = 3 foo() print('TEST SUCEEDED')
train = [[1,2],[2,3],[1,1],[2,2],[3,3],[4,2],[2,5],[5,5],[4,1],[4,4]] weights = [1,1,1] def perceptron_predict(inputs, weights): activation = weights[0] for i in range(len(inputs)-1): activation += weights[i+1] * inputs[i] return 1.0 if activation >= 0.0 else 0.0 for inputs in train: print(p...
def msg_retry(self, buf): print("retry") return buf[1:] MESSAGES = {1: msg_retry}
print("WELCOME!\nTHIS IS A NUMBER GUESSING QUIZ ") num = 30 num_of_guesses = 1 guess = input("ARE YOU A KID?\n") while(guess != num): guess = int(input("ENTER THE NUMBER TO GUESS\n")) if guess > num: print("NOT CORRECT") print("LOWER NUMBER PLEASE!") num_of_guesses += 1 elif guess...
""" A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? ![...
MAX_FOOD_ON_BOARD = 25 # Max food on board EAT_RATIO = 0.50 # Ammount of snake length absorbed FOOD_SPAWN_RATE = 3 # Number of turns per food spawn HUNGER_THRESHOLD = 100 # Turns of inactivity before snake starvation SNAKE_STARTING_LENGTH = 3 # Snake starting size TURNS_PER_GOLD = 20 # Turns between the spawn of ...
def trier(Tab): Tri = dict(sorted(Tab.items(), key=lambda item: item[1], reverse=True)) return Tri def afficher(Tab): for Equipe,Score in Tab.items(): print(Equipe," : ",Score) def Tableau(Tab): Tab2=[] for Equipe in Tab: Tab2.append(Equipe[0]) return Tab2 def main(): #Gr...
# https://codeforces.com/problemset/problem/1399/A t = int(input()) for _ in range(t): length_a = int(input()) list_a = [int(x) for x in input().split()] list_a.sort() while True: if len(list_a) == 1: print('YES') break elif abs(list_a[0] - list_a[1]) <= 1: ...
sentence = input().split() latin = "" for word in sentence: latin += word[1:] + word[0]+"ay " print(latin,end="")
modulename = "Help" creator = "YtnomSnrub" sd_structure = {}
class DeBracketifyMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): cleaned = request.GET.copy() for key in cleaned: if key.endswith('[]'): val = cleaned.pop(key) cleaned_key = ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ SER-347 - Joao Felipe Lista-05 Exercício 02. Para criar uma senha na internet, geralmente são aplicados critérios de força da senha. Neste exercício, uma senha forte possui caracteres maiúsculos e minúsculos, e tem pelo menos 8 caracteres. Do contrário, é fraca. Crie u...