content
stringlengths
7
1.05M
def test_root_redirect(client): r_root = client.get("/") assert r_root.status_code == 302 assert r_root.headers["Location"].endswith("/overview/")
# Conversão de escalas Celsius, Kelvin e Fahrenheit celsius = float(input('Digite Quantos Graus Celsius: ')) kelvin = float(celsius + 273) fahrenheit = float(1.8 * celsius + 32) print('{}ºC é igual a {}ºK ou {:.2f}ºF'.format(celsius, kelvin, fahrenheit))
class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ size = len(prices) bought = False profit = 0 price = 0 for i in range(0, size - 1): if not bought: if prices[i] < prices[i + 1]...
'''8. Write a Python program to split a given list into two parts where the length of the first part of the list is given. Original list: [1, 1, 2, 3, 4, 4, 5, 1] Length of the first part of the list: 3 Splited the said list into two parts: ([1, 1, 2], [3, 4, 4, 5, 1]) ''' def split_two_parts(n_list, L): return n...
n = int(input()) for i in range(n): row, base, number = map(int, input().split()) remains = list() while number > 0: remain = number % base number = number // base remains.append(remain) sumOfRemains = 0 for i in range(len(remains)): remains[i] = remains[i] ** 2 ...
with open("110000.dat","r") as fi: with open("110000num.dat","w") as fo: i=1 for l in fi.readlines(): if i%100 == 0: fo.write(l.strip()+" #"+str(i)+"\n") else: fo.write(l) i = i+1
class Person(object): # This definition hasn't changed from part 1! def __init__(self, fn, ln, em, age, occ): self.firstName = fn self.lastName = ln self.email = em self.age = age self.occupation = occ class Occupation(object): def __init__(self, name, location): self.name = name sel...
#!/usr/bin/python3 class Face(object): def __init__(self, bbox, aligned_face_img, confidence, key_points): self._bbox = bbox # [x_min, y_min, x_max, y_max] self._aligned_face_img = aligned_face_img self._confidence = confidence self._key_points = key_points @property ...
start_house, end_house = map(int, input().split()) left_tree, right_tree = map(int, input().split()) number_of_apples, number_of_oranges = map(int, input().split()) apple_distances = map(int, input().split()) orange_distances = map(int, input().split()) apple_count = 0 orange_count = 0 for distance in apple_distances:...
def countInversions(nums): #Our recursive base case, if our list is of size 1 we know there's no inversion and that it's already sorted if len(nums) == 1: return nums, 0 #We run our function recursively on it's left and right halves left, leftInversions = countInversions(nums[:len(nums) // 2]) righ...
# find highest grade of an assignment def highest_SRQs_grade(queryset): queryset = queryset.order_by('-assignment', 'SRQs_grade') dict_q = {} for each in queryset: dict_q[each.assignment] = each result = [] for assignment in dict_q.values(): result.append(assignment) return resu...
def f(x): if x: return if x: return elif y: return if x: return else: return if x: return elif y: return else: return if x: return elif y: return elif z: return else: return ...
# Iterative approach using stack # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode: ...
class point: "K-D POINT CLASS" def __init__(self,coordinate, name=None, dim=None): """ name, dimension and coordinates """ self.name = name if type(dim) == type(None): self.dim = len(coordinate) else: self.dim = dim if len(coordinate) == self.dim: ...
# Ex: 076 - Crie um programa que tenha uma tupla única com nomes de produtos e # seus respectivos preços, na sequência. No final, mostre uma listagem de preços, # organizando os dados em forma tabular. print(''' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- --Seja bem-vindo! --Exercício 076 -=-=-=-=-=-=-=-=-=-=-=-=-=-=...
# 26.05.2019 # Working with BitwiseOperators and different kind of String Outputs. print(f"Working with Bitwise Operators and different kind of String Outputs.") var1 = 13 # 13 in Binary: 1101 var2 = 5 # 5 in Binary: 0101 # AND Operator with format String # 1101 13 # 0101 5 # ---- A...
""" Given a non negative integer number num. For every numbers i in the range 0 <= i <= num calculate the number of 1's in their binary representation and return them as an array. Example: For num = 5 you should return [0,1,1,2,1,2]. Follow up: It is very easy to come up with a solution with run time O(n*sizeof(inte...
""" Conf file for product catagory and payment gateway """ #Products product_sunscreens_category = ['SPF-50','SPF-30'] product_moisturizers_category = ['Aloe','Almond']
class Solution: def numTilings(self, n: int) -> int: MOD = 1000000007 if n <= 2: return n previous = 1 result = 2 current = 1 for k in range(3, n + 1): tmp = result result = (result + previous + 2 * current) % MOD curren...
# 4. Caesar Cipher # Write a program that returns an encrypted version of the same text. # Encrypt the text by shifting each character with three positions forward. # For example A would be replaced by D, B would become E, and so on. Print the encrypted text. text = input() encrypted_text = [chr(ord(character) + 3) ...
ies = [] ies.append({ "ie_type" : "Node ID", "ie_value" : "Node ID", "presence" : "M", "instance" : "0", "comment" : "This IE shall contain the unique identifier of the sending Node."}) ies.append({ "ie_type" : "F-SEID", "ie_value" : "CP F-SEID", "presence" : "M", "instance" : "0", "comment" : "This IE shall contain th...
code = """ 400 0078 Clear Display 402 21C0 V1 = 0C0h (Pattern #) 404 2200 V2 = 10h (Cell#) 406 2301 V3 = 01 (Centre) 408 B600 B = 600 Set B to point to $600 40A 1422 CALL 422 Call 422 for C0,C5,CA,CA,BC,B5 40C 21C5 V1 = C5 Print PUZZLE. 40E 1422 CALL 422 410 21CA V1 = CA 412 1422 C...
# https://www.codechef.com/problems/MISSP for T in range(int(input())): a=[] for n in range(int(input())): k=int(input()) if(k not in a): a.append(k) else: a.remove(k) print(a[0])
""" 1. Clarification 2. Possible solutions - Naive Approach - String Concatenation - Hash 3. Coding 4. Tests """ # T=O(n), S=O(1) class Solution: def fizzBuzz(self, n: int) -> List[str]: ans = [] for num in range(1, n + 1): divisible_by_3 = (num % 3 == 0) divisi...
def check_subtree(t2, t1): if t1 is None or t2 is None: return False if t1.val == t2.val: # potential subtree if subtree_equality(t2, t1): return True return check_subtree(t2, t1.left) or check_subtree(t2, t1.right) def subtree_equality(t2, t1): if t2 is None and t1 is Non...
# Sky Jewel box (2002016) | Treasure Room of Queen (926000010) eleska = 3935 skyJewel = 4031574 reactor.incHitCount() if reactor.getHitCount() >= 3: if sm.hasQuest(eleska) and not sm.hasItem(skyJewel): sm.dropItem(skyJewel, sm.getPosition(objectID).getX(), sm.getPosition(objectID).getY()) sm.removeReactor()
a[-1] a[-2:] a[:-2] a[::-1] a[1::-1] a[:-3:-1] a[-3::-1] point_coords = coords[i, :] main(sys.argv[1:])
''' for a in range(3,1000): for b in range(a+1,999): csquared= a**2+b**2 c=csquared**0.5 if a+b+c==1000: product= a*b*c print(product) print(c) break ''' def compute(): PERIMETER = 1000 for a in range(1, PERIMETER + 1): for b in range(a + 1...
# Language: Python # Level: 8kyu # Name of Problem: DNA to RNA Conversion # Instructions: Deoxyribonucleic acid, DNA is the primary information storage molecule in biological systems. # It is composed of four nucleic acid bases Guanine ('G'), Cytosine ('C'), Adenine ('A'), and Thymine ('T'). # Ribonucleic acid, RNA, ...
data = ( 'Kay ', # 0x00 'Kayng ', # 0x01 'Ke ', # 0x02 'Ko ', # 0x03 'Kol ', # 0x04 'Koc ', # 0x05 'Kwi ', # 0x06 'Kwi ', # 0x07 'Kyun ', # 0x08 'Kul ', # 0x09 'Kum ', # 0x0a 'Na ', # 0x0b 'Na ', # 0x0c 'Na ', # 0x0d 'La ', # 0x0e 'Na ', # 0x0f 'Na ', ...
# У кафе морозиво продають по три кульки і по п'ять кульок. Чи можна купити рівно k кульок морозива? # # ## Формат введення # # Вводиться число k (ціле, позитивне) # # ## Формат виведення # # Програма повинна вивести слово YES, якщо при таких умовах можна набрати рівно k кульок (не більше і не менше), в іншому випа...
class Sol(object): def __init__(self): self.suc = None def in_order(self, head, num): if not head: return None int = [] def helper(head): nonlocal int if head: self.helper(head.left) int.append(head.val) ...
# OpenWeatherMap API Key weather_api_key = "Insert your own key" # Google API Key g_key = "Insert your own key"
"Tests for pug bzl definitions" load("@bazel_tools//tools/build_rules:test_rules.bzl", "file_test", "rule_test") def _pug_binary_test(package): rule_test( name = "hello_world_rule_test", generates = ["main.html"], rule = package + "/hello_world:hello_world" ) file_test( na...
class A(object): def A(): print('factory') return A() def __init__(self): print('init') def __call__(self): print('call') print('chamar o construtor') a = A() print('chamar o construtor e a função') b = A()() print('chamar a função') c = A.A() #https://pt.stackoverflow.com/q...
class Solution: def countGoodSubstrings(self, s: str) -> int: count, i, end = 0, 2, len(s) while i < end: a, b, c = s[i-2], s[i-1], s[i] if a == b == c: i += 2 continue count += a != b and b != c and a != c i += 1 ...
( XL_CELL_EMPTY, #0 XL_CELL_TEXT, #1 XL_CELL_NUMBER, #2 XL_CELl_DATE, #3 XL_CELL_BOOLEAN,#4 XL_CELL_ERROR, #5 XL_CELL_BLANK, #6 ) = range(7) ctype_text = { XL_CELL_EMPTY: 'empty', XL_CELL_TEXT:'text', XL_CELL_NUMBER:'number', XL_CELl_DATE:'date', XL_CELL_BOOLEAN:'...
""" Dictionary key must be immutable """ string_dict = dict({"1": "1st", "2": "2nd", "3": "3rd"}) def add_element_to_string_dict(key: str, value: str): string_dict[key] = value def delete_element_to_string_dict(key: str): del string_dict[key] def get_element_from_string_dict(key: str): if key in strin...
# -*- coding:utf-8 -*- """ @Author:Charles Van @E-mail: williananjhon@hotmail.com @Time:2019-08-08 16:35 @Project:InterView_Book @Filename:String5.py @description: 用有限状态自动机匹配字符串 """ """ 题目描述: 给定两个字符串,S和T,其中S是要查找的字符串,T是被查找的文本,要求 给出一个查找算法,找出S在T中第一次出现的位置 """ class StringAutomation: def __init__(self,P): # 用字典...
escolha = 's' num = cont = soma = maior = menor = 0 while escolha not in 'Nn': num = int(input('Digite um número: ')) escolha = str(input('Quer continuar [S/N]: ')).strip()[0] if escolha not in 'SsNn': print('Escolha inválido, digite novamente') cont += 1 soma += num if cont == 1: ...
def sum6(n): nums = [i for i in range(1, n + 1)] return sum(nums) N = 10 S = sum6(N) print(S)
class ValveStatus(object): """ An enumeration of possible valve states. OPEN_AND_DISABLED should never happen. """ OPEN_AND_ENABLED, CLOSED_AND_ENABLED, OPEN_AND_DISABLED, CLOSED_AND_DISABLED = (i for i in range(4))
i = str(input('Em que cidade você nasceu? ')).strip() x1 = i.title() x2 = x1.split() x3 = x2[0] x4 = x3.find('Santo') if x4 == 0: print('Você nasceu em uma cidade que começa com "Santo"') elif x4 == -1: print('Você não nasceu em uma cidade que começa com "Santo"')
def solve(): s = sum((x ** x for x in range(1, 1001))) print(str(s)[-10:]) if __name__ == '__main__': solve()
#!/usr/bin/env python """Contains extractor configuration information """ # Setup the name of our extractor. EXTRACTOR_NAME = "" # Name of scientific method for this extractor. Leave commented out if it's unknown #METHOD_NAME = "" # The version number of the extractor VERSION = "1.0" # The extractor description DE...
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def middleNode(self, head): """ :type head: ListNode :rtype: ListNode """ tmp = head while tmp and tmp.next:...
listaDePalavras = ('Aprender','Programar','Linguagem','Python','Curso','Gratis', 'Estudar','Praticar','Trabalhar','Mercado','Programador', 'Futuro') for palavras in listaDePalavras: print(f'\n A palavra {palavras} temos', end=' ') for letras in palavras: if letras.l...
x = 1 y = 'Hello' z = 10.123 d = x + z print(d) print(type(x)) print(type(y)) print(y.upper()) print(y.lower()) print(type(z)) a = [1,2,3,4,5,6,6,7,8] print(len(a)) print(a.count(6)) b = list(range(10,100,10)) print(b) stud_marks = {"Madhan":90, "Raj":25,"Mani":80} print(stud_marks.keys()) print(stud_marks.va...
# Generate .travis.yml automatically # Configuration for Linux configs = [ # OS, OS version, compiler, build type, task ("ubuntu", "18.04", "gcc", "DefaultDebug", "Test"), ("ubuntu", "18.04", "gcc", "DefaultRelease", "Test"), ("debian", "9", "gcc", "DefaultDebug", "Test"), ("debian", "9", "gcc", "D...
######################### # # # Developer: Luis Regus # # Date: 11/24/15 # # # ######################### NORTH = "north" EAST = "east" SOUTH = "south" WEST = "west" class Robot: ''' Custom object used to represent a robot ''' def __init__(self, ...
class ToolBoxBaseException(Exception): status_code = 500 error_name = 'base_exception' def __init__(self, message): self.message = message def to_dict(self): return dict(error_name=self.error_name, message=self.message) class UnknownError(ToolBoxBaseException): status_code = 500 ...
''' lab 8 functions ''' #3.1 def count_words(input_str): return len(input_str.split()) #print(count_words('This is a string')) #3.2 demo_str = 'Hello World!' print(count_words(demo_str)) #3.3 def find_min(num_list): min_item = num_list[0] for num in num_list: if type(num) is not str: ...
users = { 'name': 'Elena', 'age': 100, 'town': 'Varna' } for key, value in users.items(): print(key, value) for key in users.keys(): print(key) for value in users.values(): print(value)
class Solution: def getSum(self, a: int, b: int) -> int: # 32 bits integer max and min MAX = 0x7FFFFFFF MIN = 0x80000000 mask = 0xFFFFFFFF while b != 0: carry = a & b a, b = (a ^ b) & mask, (carry << 1) & mask ret...
# Задача 1. Вариант 28 # Напишите программу, которая будет сообщать род деятельности и псевдоним под # которым скрывается Норма Бейкер. После вывода информации программа должна # дожидаться пока пользователь нажмет Enter для выхода. print("Норма Бейкер, более известная как Мэрилин Монро - американская \nкиноактриса, ...
""" Compatibility related items. """ __author__ = "Brian Allen Vanderburg II" __copyright__ = "Copyright (C) 2019 Brian Allen Vanderburg II" __license__ = "Apache License 2.0"
# -*- coding: utf-8 -*- """ Copyright () 2018 All rights reserved FILE: linked_list.py AUTHOR: tianyuningmou DATE CREATED: @Time : 2018/5/14 上午10:58 DESCRIPTION: . VERSION: : #1 CHANGED By: : tianyuningmou CHANGE: : MODIFIED: : @Time : 2018/5/14 上午10:58 """ """ 链表是线性表的一种 线性表中数据元素之间的关系是一对一的关系,即除了第一个和最后一个数...
class Memories(object): def __init__(self, memory_capacity): self.food_memories = [] self.offspring_memories = [] # No aplican a la cantidad de recuerdos y nunca se olvidan (mientras vivan) self.territory_link_memories = [] self.food_location_memories = [] self.hostile_creatu...
CONFIG = { "main_dir": "./tests/", "results_dir": "results/", "manips_dir": "manips/", "parameters_dir": "parameters/", "tikz_dir": "tikz/" }
stack = [] while True: print("1. Insert Element in the stack") print("2. Remove element from stack") print("3. Display elements in stack") print("4. Exit") choice = int(input("Enter your Choice: ")) if choice == 1: if len(stack) == 5: print("Sorry, stack is already full")...
#config 置信度阈值 SUPPORT_RATE_THRESHOLD = 0.4 # 判断 b 列表中是否包含 a 列表的所有元素 def containes(a,b): try: for i in a: # print("target: ",i) if b.index(i)>=0: continue # print("finded :",i," continue") return True except ValueError as e: # prin...
# Operations on Sets ? # Consider the following set: S = {1,8,2,3} # Len(s) : Returns 4, the length of the set S = {1,8,2,3} print(len(S)) #Length of the Set # remove(8) : Updates the set S and removes 8 from S S = {1,8,2,3} S.remove(8) #Remove of the Set print(S) # pop() : Removes an arbitrary element fro...
idade = str(input("idade :")) if not idade.isnumeric(): print("oi") else: print("passou")
CHUNK_SIZE = 16 CHUNK_SIZE_PIXELS = 256 RATTLE_DELAY = 10 RATTLE_RANGE = 3
def is_std_ref(string): """ It finds whether the string has reference in itself. """ return 'Prop.' in string or 'C.N.' in string or 'Post.' in string or 'Def.' in string def std_ref_form(ref_string): """ Deletes unnecessary chars from the string. Seperates combined references. return...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ fast , slow = head, head w...
# coding: utf-8 """ 配置公私钥 """ public_key = "" private_key = "" project_id = "" base_url = ""
def solution(string, markers): string = string.split('\n') result = '' for line in string: for character in line: if character not in markers: result += character else: result = result[:-1] break result += '\n' ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' errno.py Error Code Define Copyright: All Rights Reserved 2019-2019 History: 1 2019-07-14 Liu Yu (source@liuyu.com) Initial Version ''' SUCCESS = 'SUCC' ERROR_SUCCESS = SUCCESS FAIL = 'FAIL' ERROR = FAIL ERROR_INVALID = 'INVALID' ERROR_UNSUPPORT = 'UNSU...
# Write a Python program to add leading zeroes to a string String = 'hello' print(String.rjust(9, '0'))
RETENTION_SQL = """ SELECT datediff(%(period)s, {trunc_func}(toDateTime(%(start_date)s)), reference_event.event_date) as base_interval, datediff(%(period)s, reference_event.event_date, {trunc_func}(toDateTime(event_date))) as intervals_from_base, COUNT(DISTINCT event.target) count FROM ( {returning_even...
def dos2unix(file_path): """This is copied from Stack Overflow pretty much as is Opens a file, converts the line endings to unix, and then overwrites the file. """ # replacement strings WINDOWS_LINE_ENDING = b'\r\n' UNIX_LINE_ENDING = b'\n' with open(file_path, 'rb') as open_file: ...
class InputMode: def __init__(self): pass def GetTitle(self): return "" def TitleHighlighted(self): return True def GetHelpText(self): return None def OnMouse(self, event): pass def OnKeyDown(self, event): pass def OnKe...
# -*- coding: utf-8 -*- """Generic errors for immutable data validation.""" class ImmutableDataValidationError(Exception): def __init__(self, msg: str = None, append_text: str = None): if append_text is not None: msg = "%s %s" % (msg, append_text) super().__init__(msg) class Immutabl...
#!/usr/bin/env python3 """ String Objects """ def get_str(): """ Prompt user for a string """ valid_input = False while not valid_input: try: sample_str = input('>>> ') valid_input = True return sample_str except Exception as err: r...
src = Split(''' hal_test.c ''') component = aos_component('hal_test', src) component.add_cflags('-Wall') component.add_cflags('-Werror')
class resizable_array: def __init__(self,arraysize): self.arraysize = arraysize self.array = [None for i in range(self.arraysize)] self.temp =1 def __insert(self,value): for i in range(len(self.array)): if self.array[i] == None: self.array[i] = valu...
qt=int(input()) for i in range(qt): jogadores=input().split() nome1=str(jogadores[0]) escolha1=str(jogadores[1]) nome2 = str(jogadores[2]) escolha2 = str(jogadores[3]) numeros=input().split() numerosJ1=int(numeros[0]) numerosJ2=int(numeros[1]) if escolha1=="PAR" and escolha2=="IMP...
""" """ def copy_to_home(path, file_name): """ 万物拷贝器(除了文件夹) :param path: 拷贝到的路径 :param file_name: 要拷贝的文件名称(带格式) :return: none """ with open(file_name, "rb") as file_object: home_file = open(path + file_name, "wb") while True: line = file_object.readlines(10240)...
""" Aliyun API ========== The Aliyun API is well-documented at `dev.aliyun.com <http://dev.aliyun.com/thread.php?spm=0.0.0.0.MqTmNj&fid=8>`_. Each service's API is very similar: There are regions, actions, and each action has many parameters. It is an OAuth2 API, so you need to have an ID and a secret. You can get the...
############################################################################################### # 递归遍历所有情况,直接超时;太蠢了,这种想法是想着往LED填,来凑齐满足要求的时间 ############################################################################################### class Solution: def analyze(self, string): # 0 - 3 代表 1 2 4 8 ...
class VertexPaint: use_group_restrict = None use_normal = None use_spray = None
@app.post('/login') def login(response: Response): ... token = manager.create_access_token( data=dict(sub=user.email) ) manager.set_cookie(response, token) return response
print("Pass statement in Python"); for i in range (1,11,1): if(i==3): i = i + 1; pass; else: print(i); i = i + 1;
expressao = list() expressao.append(str(input("Informe uma expressão: "))) lado1 = expressao[0].count("(") lado2 = expressao[0].count(")") if lado1 == lado2: print("A expressão é valida") else: print("A expressão é invalida")
# Runtime error N = int(input()) X = list(map(int, input().split())) # Memory problem tot = sum(X) visited = [False for k in range(N)] currentStar = 0 while True: if currentStar < 0 or currentStar > N-1: break else: visited[currentStar] = True if X[currentStar] >= 1: if X[...
n = int(input()) for i in range(n): dieta = list(input()) cafe = list(input()) almoco = list(input()) todos = cafe + almoco cheat = False for comido in todos: if comido in dieta: dieta.remove(comido) else: cheat = True if not cheat: print("".join(sorted(dieta))) else: print("CHEATER")
first_name = input("Enter you name") last_name = input("Enter you surname") past_year = input("MS program start year?") a = 2 + int(past_year) print(f"{first_name} {last_name} {past_year} you are graduate in {a}")
# Puzzle Input with open('Day12_Input.txt') as puzzle_input: movement_list = puzzle_input.read().split('\n') # Calculate the path facing = 1 # Way it's facing, 0 -> North, 1 -> East, 2 -> West, 3 -> South coordinates = [0, 0] # Coordinates where X-axis is facing North and...
# -------------- # Code starts here class_1 = ['Geoffrey Hinton','Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio'] #print(class_1) class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes'] #print(class_2) new_class = class_1 + class_2 print(new_class) new_class.append('Peter Warden') print(new_class) new_class....
#Faça uma função que informe a quantidade de dígitos de um determinado número inteiro informado def calcula_digito(numero): numero = str(numero) return len(numero) print(calcula_digito(150123123123)) print(calcula_digito(100)) print(calcula_digito(1000)) print(calcula_digito(10000))
class Solution: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: if not pushed and not popped: return True aux = [] idx = 0 for _ in pushed: aux.append(_) while aux and aux[-1] == popped[idx]: aux.pop(...
widget = WidgetDefault() widget.border = "None" commonDefaults["GroupBoxWidget"] = widget def generateGroupBoxWidget(file, screen, box, parentName): name = box.getName() file.write(" %s = leGroupBoxWidget_New();" % (name)) generateBaseWidget(file, screen, box) writeSetStringAssetName(file, name,...
# Problem Statement Link: https://www.hackerrank.com/challenges/the-minion-game/problem def minion_game(w): s = k = 0 v = ['A', 'E', 'I', 'O', 'U'] for x in range( len(w) ): if w[x] in v: k += (len(w)-x) else: s += (len(w)-x) if s == k: print("Draw") el...
a = 10 print(a)
def stations_level_over_threshold(stations, tol): #2B part 2 stationList = [] for station in stations: if station.typical_range_consistent() and station.latest_level != None: if station.relative_water_level() > tol: stationList.append((station, station.relative_water_level()...
lanches = ['X-Bacon','X-Tudo','X-Calabresa', 'CalaFrango','X-Salada','CalaFrango','X-Bacon','CalaFrango'] lanches_finais = [] print('Estamos sem CalaFrango') while 'CalaFrango' in lanches: lanches.remove('CalaFrango') while lanches: preparo = lanches.pop() print('Preparei seu lanche de {}'.format(preparo)...
# -*- coding: utf-8 -*- # list of system groups ordered descending by rights in application groups = ['wheel', 'sudo', 'users']
def escreva(frase): a = len(frase)+2 print('~'*(a+2)) print(f' {frase}') print('~' * (a + 2)) escreva('Gustavo Guanabara') escreva('Curso de Python no YouTube') escreva('CeV')
""" Solução A solução se baseia em pegar as duas metades da string, invertelas separadamente, com a ajuda do recurdo do Python para análise de string/arrays, como o range que queremos pegar dessa string, e em qual sentido fazer a contagem. Por exemplo, [::-1], vai pegar a string inteira, porém invertida. E adicionar as...