content
stringlengths
7
1.05M
_YES_ANSWERS_ = ["y","yes"] _NO_ANSWERS_ = ["n", "no"] def getInput(_string): val = raw_input(_string) return val def getYesNoAnswer(_string): while True: val = raw_input(_string).lower() if val in _YES_ANSWERS_: return True if val in _NO_ANSWERS_: return F...
class Solution: def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 elif len(nums) == 1: return nums[0] # get all sum first all_sum = sum(nums)
#!/usr/bin/env python3 # File: xRpcFaker.py def SayHello(token): return f"Hello {token}!"
class EventInstance(object): """ Represents language-neutral information for an event log entry. EventInstance(instanceId: Int64,categoryId: int) EventInstance(instanceId: Int64,categoryId: int,entryType: EventLogEntryType) """ @staticmethod def __new__(self, instanceId, categoryId, en...
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] b = [even for even in a if even % 2 == 0] print(b) c = [even*3 for even in a] print(c)
n = int(input("Digite um número: ")) n1 = n-1 n2 = n+1 print("O antecessor e sucessor de {} são, respectivamente {} e {}".format(n, n1, n2))
""" Loop for Loop -> Estrutura de repetição. for -> Uma dessas estrututras. for item in interavel : //execução do loop Utilizamos loops para iterar sobre sequências ou sobre valores iteráveis (Pode ser escrito uma parte de cada vez) Exemplos de interáveis: - String nome = 'Geek Universi...
cont = 0 somidade = 0 mulheres = list() todos = list() while True: todos.append(dict()) todos[cont]['nome'] = str(input('Nome: ')) todos[cont]['sexo'] = str(input('Sexo: [M/F] '))[0] while todos[cont]['sexo'] not in 'mMfF': print('ERRO! Digite um valor válido!') todos[cont]['se...
class Fenwick_Tree: def __init__(self, size): self.size = size + 1 self.array = [0 for _ in range(self.size)] def __len__(self): ''' Called when len is called on object ''' return self.size def lsb(self, index:int) -> int: ''' ...
class NofieldnameField(object): pass class FieldnameField(object): fieldname = 'hello' class RepeatedFieldnameField(FieldnameField): pass
def for_one(): """ We are creating a user defined function for numerical pattern of One with "*" symbol """ row=7 col=5 for i in range(row): for j in range(col): if i==1 and j<3 or j==2 or i==6 and j<5: print("*",end=" ") else: ...
# ## ADD THIS TO YOUR .gitignore FILE ## # APPLICATION_TITLE = 'WikiGenomes' # DJango Secret key secret_key = '<django secret key>' # OAUTH Consumer Credentials---you must register a consumer at consumer_key = '<wikimedia oauth consumer key>' consumer_secret = '<wikimedia oauth consumer secret>' # Configurations f...
"""Constants.""" CACHE_NAME = 'news_lk_si' CACHE_TIMEOUT = 3600
'''Escrever um programa que permita ao usuário digitar o dia e mês de seu aniversário e a data de hoje (dia e mês); em seguida, o programa deve calcular quantos dias faltam entre a data de hoje e a data do próximo aniversário. Suponha todos os meses com 30 dias.''' dia = int(input('Digite a data de hoje:')) mes = int(...
name = 'AL_USDMaya' version = '0.0.1' uuid = 'c1c2376f-3640-4046-b55e-f11461431f34' authors = ['AnimalLogic'] description = 'USD to Maya translator. This rez package is purely an example and should be modifyed to your own needs' private_build_requires = [ 'cmake-2.8+', 'gcc-4.8', 'gdb-7.10' ] requires...
def findMatching(numbers, value): for number1 in numbers: for number2 in numbers: variables = [number1, number2] if (len(set(variables)) != len(variables)): continue if number1 + number2 == value: print("{} + {} = {}, {} * {} = {}".format(number1,number2,value,number1,number2,number1*number2)) r...
def triangle_reduce(triangle): last = triangle.pop() for i, n in enumerate(triangle[-1]): if last[i] > last[i+1]: triangle[-1][i] = triangle[-1][i] + last[i] else: triangle[-1][i] = triangle[-1][i] + last[i+1] return triangle def solve(triangle): while len(triangle) > 1: ...
class URL: """ URL config strings """ GPPRO = "https://github.com/martinpaljak/GlobalPlatformPro/releases/" \ "download/v20.01.23/gp.jar" JCALGTEST = "https://github.com/crocs-muni/JCAlgTest/releases/" \ "download/v1.8.0/AlgTest_dist_1.8.0.zip" SMARTCARD_LIST = "ht...
class GoogleCredentialsException(Exception): def __init__(self): message = "GCP_JSON or GCP_B64 env variable not set properly" super().__init__(message) class TaskNotFound(Exception): def __init__(self, name: str): message = f"Task {name} not registered." super().__init__(messa...
s = "kBNCR9joiFtdAv19AhJ0mHVKassinaPSifCT5bnIrindoudUarwnZxwclalDWjgYudhVD5Sf3Z7looEZCuKQaBIAYTEKn0kQnm2rbwp3KLYsemipalmatusENYyIr6BvCNbuYXeDPFh49tBZQg2Hhw7QrPrAVpyo4RMRRIulZUMBhVNnK1kHFdFM3wxVsvBo3Kq6." a = 23 b = 29 c = 107 d = 118 print (s[a:b + 1] + " " + s[c:d + 1])
def rotate(list, n): return list[n:] + list[:n] def filter_equal_values(lhs, rhs): return [a for a, b in zip(lhs, rhs) if a == b] def sum_as_integers(list_of_strings): return sum(map(int, list_of_strings)) def part_one(input): lhs = list(input) rhs = rotate(lhs, 1) values = filter_equal_va...
"""551. Student Attendance Record I https://leetcode.com/problems/student-attendance-record-i/ """ class Solution: def check_record(self, s: str) -> bool: l_cnt, a_cnt = 0, 0 pre = '' for c in s: if c == 'L': l_cnt += 1 if l_cnt == 3: ...
# 读取5个人的分数并输出总分以及平均分 print('计算5个人分数的总分以及平均分。') tensu1 = int(input('第1名分数:')) tensu2 = int(input('第2名分数:')) tensu3 = int(input('第3名分数:')) tensu4 = int(input('第4名分数:')) tensu5 = int(input('第5名分数:')) total = 0 total += tensu1 total += tensu2 total += tensu3 total += tensu4 total += tensu5 ...
def KSA(key): S = bytearray(range(256)) j = 0 for i in range(256): j = (j + S[i] + key[i % len(key)]) % 256 S[i], S[j] = S[j], S[i] return S def PRGA(S): i = 0 j = 0 while True: i = (i + 1) % 256 j = (j + S[i]) % 256 S[i], S[j] = S[j], S[i] ...
#------------------------------------------------------------------------------- # Part of tweedledum. This file is distributed under the MIT License. # See accompanying file /LICENSE for details. #------------------------------------------------------------------------------- """Tests."""
# 对整数1~12进行循环但跳过8(其一) for i in range(1, 13): if i == 8: continue print(i, end=' ') print()
class LRUCache: def __init__(self, limit): self.limit = limit self.hash = {} self.head = None self.end = None def get(self, key): node = self.hash.get(key) if node is None: return None self.refresh_node(node) return node.value def...
# # PySNMP MIB module ARP-Spoofing-Prevent-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ARP-Spoofing-Prevent-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:09:30 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7....
def regras(x): if x < 100: if x % 2 == 0: return x else: return (x + x) lista = [100, 200, 1000, 3000, 2, 3, 4, 5, 6, 7, 8] print(list(filter(regras,lista))) #https://pt.stackoverflow.com/q/321682/101
class WarmUpScheduler(): def __init__(self,optimizer, init_lr, d_model, n_warmup_steps): self._optimizer=optimizer self.init_lr=init_lr self.d_model=d_model self.n_warmup_steps=n_warmup_steps self._steps = 0 def step(self): r"""Update parameters""" se...
def merge(a1, a2): ma = [] i1, i2 = 0, 0 while i1 < len(a1) and i2 < len(a2): if a1[i1] < a2[i2]: ma.append(a1[i1]) i1 += 1 else: ma.append(a2[i2]) i2 += 1 while i1 < len(a1): ma.append(a1[i1]) i1 += 1 while i2 < len(a2...
def wrap(string, max_width): wrapper = textwrap.TextWrapper(width=max_width) word_list = wrapper.wrap(text=string) lastWrap = word_list[-1] for element in word_list: if element != lastWrap: print(element) return lastWrap
def flatten(some_list): """ Flatten a list of lists. Usage: flatten([[list a], [list b], ...]) Output: [elements of list a, elements of list b] """ new_list = [] for sub_list in some_list: new_list += sub_list return new_list def recursive_radix_sort(some_list, idex=None, size=...
needed_money = float(input()) owned_money = float(input()) days_counter = 0 spending_counter = 0 while True: action = input() amount = float(input()) days_counter += 1 if action == "spend": owned_money -= amount spending_counter += 1 if owned_money < 0: ...
# Tanner Bornemann # Lab00 - Python Programming - Section 001 # 2017-01-13 def twenty_seventeen(): """Come up with the most creative expression that evaluates to 2017, using only numbers and the +, *, and - operators. >>> twenty_seventeen() 2017 >>> twenty_seventeen() + twenty_seventeen() 4034...
DESCRIBE_GATEWAYS = [ { "Attachments": [ { "State": "available", "VpcId": "vpc-XXXXXXX", }, ], "InternetGatewayId": "igw-1234XXX", "OwnerId": "012345678912", "Tags": [ { "Key": "Name", ...
''' The MIT License (MIT) Copyright (c) 2016 WavyCloud Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, p...
""" Exercise 1: Write a while loop that starts at the last character in the string and works its way backwards to the first character in the string, printing each letter on a separate line, except backwards. """ fruit = 'banana' i = len(fruit) - 1 while i >= 0: print(fruit[i]) i -= 1 # for ch in fruit[::-1]:...
# Time: O(n^2); Space: O(1) def time_required_to_buy(tickets, k): time = 0 while tickets[k] > 0: for i, t in enumerate(tickets): if t > 0: time += 1 tickets[i] -= 1 if tickets[k] == 0: break return time # Time: O(n); Space:...
# -*- coding: utf-8 -*- proxies = ( # '115.229.93.123:9000', # '114.249.116.183:9000', # '14.118.252.68:6666', # '115.229.93.123:9000', )
# Django settings for yawf_sample project. DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'test.db', # Or path to database file if using sqlite3. ...
# DAY 4- ACTIVITY 3 # Program Description: This is a simple word bank program. It takes in the user's input and turns it into a string # which will then be stored into the word bank list. After the user is done inputting his desired words, the program # will print out the elements inside the word bank list. # The...
############################################################################### # Monitor plot arrays # ############################################################################### tag = "monitor" varpos = { 'time': 0, 'x': 1, 'y': 2, 'z': 3, ...
""" Description: A demo of the different forms of string Literals available. SEE: https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals """ # Raw strings; These are strings that will completely ignore special characters such as \n or \t my_string = "Hello \n\tWorld" print(my_string) ...
def greeting_user(fname,lname): print(f"Hi {fname} {lname} !") print("How are you?") print("start") greeting_user("Lois") # we can add positional argument, this means position of the argument can shifted around # greeting_user(lname= "tracy", fname="Andrew") print("end")
# -*- coding: utf-8 -*- """ Created on Sat Aug 28 10:00:47 2021 @author: qizhe """ class Solution: def findMin(self, nums) -> int: """ 二分查找找旋转数组的最小值,关键点是允许存在重复元素。 Parameters ---------- nums : TYPE DESCRIPTION. Returns ------- int ...
DEFAULT_REGION = 'us-west-1' AMAZON_LINUX_AMI_US_WEST_2 = "ami-04534c96466647bfb" # installs and starts ngnix, nothing else USER_DATA = """ #!/bin/bash sudo amazon-linux-extras install nginx1.12 -y sudo chkconfig nginx on sudo service nginx start # to generate CPU load on start up for autoscaling debugging #cat /dev/z...
# !/usr/bin/env python # -*-coding:utf-8 -*- # Warning :The Hard Way Is Easier """ ================================================================================= 【模拟工作队列】 ================================================================================= """ class JobQueue: def __init__(self, limit): ...
class Repository(object): def __init__(self, pkgs=None): """ A Repository object stores and manages packages this way, we can use multiple package indices at once. """ if pkgs is None: pkgs = {} self.pkgs = pkgs def add(self, pkg): """ ...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def flatten(self, root): if not root: return while root: if root.left: ...
print('Irei fazer algumas perguntas!') nome = input('Digite seu nome: ') print('Olá ',nome,', é um prazer te receber!') print('Digite sua data de nascimento!') dia = input('Qual o dia? ') mes = input('Qual o mês? ') ano = input('Qual o ano? ') print(nome,', você nasceu em ',dia,' de ',mes,' de ', ano,'.') numero1 = int...
#Nesting Loops in Loops outer = ['Li','Na','K'] inner = ['F', 'Cl', 'Br'] for metal in outer: for halogen in inner: print(metal + halogen)
# https://codeforces.com/contest/1327/problem/A for _ in range(int(input())): n, k = map(int, input().split()) print("YES" if n % 2 == k % 2 and n >= k * k else "NO")
__all__ = [ 'box.py', 'servers.py', 'network.py' ]
def main(): while True: text = input("Text: ") if len(text) > 0: break letter = 0 word = 1 sentence = 0 for c in text: c = c.upper() if c >= "A" and c <= "Z": letter += 1 if c == " ": word += 1 if c == "." or c == ...
print(""" 049) refaça o DESAFIO 009, mostrando a tabuada de um número que o usuário escolher, só que agora utilizando um laço for. """) print('-' * 18) n = int(input('Digite um número: ')) print('Tabuada do {}'.format(n)) for valor in range(1, 11): print('{} x {} = {}' .format(n, valor, n*valor )) print('-' * 18...
class ComposeScript: def __init__(self, name, deploy=None, ready_check=None, output_extraction=None, cleanup_on=None, unique_by=None): self.name = name self.deploy = deploy if deploy is not None else [] self.cleanup_on = cleanup_on self.unique_by = unique_by self.ready_check...
BASE_62_CHAR_SET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" def base62_to_int(part: str) -> int: """ Simple base 62 to integer computation """ t = 0 for c in part: t = t * 62 + BASE_62_CHAR_SET.index(c) return t def get_partition(url_token: str): """ ...
# Типы переменных # Марка name = 'Ford' # строка print(name, type(name)) # Возраст age = 3 print(age, type(age)) # Объём двигателя engine_volume = 1.6 print(engine_volume, type(engine_volume)) # Есть ли люк? see_sky = False print((see_sky, type(see_sky)))
# Name : BrowserCookie.py # Author : Harshavardhan (HK) # Time : 03/12/2020 12:45 pm # Desc: BrowserCookie holds all the methods to manipulate cookies class BrowserCookie: def __init__(self, context): self.context = context def delete_all_cookies(self): """ Delete all cookies in t...
class EmptyChildProxy: """ Bad because does not extends dalec.proxy.Proxy """ app = "empty_child" def _fetch(self, *args, **kwargs): print("Are you my mummy?")
class Luhn: """ Given a number determine whether or not it is valid per the Luhn formula. """ def __init__(self, card_num: str): self.card_num = card_num.replace(' ', '') self.__card_num_list = \ [int(char) for char in self.card_num if char.isdigit()] ...
while True: try: S = input() count = 0 for k in input(): if k in S: count += 1 print(count) except: break
# def main(): # x, y, z = (int(x) for x in input().strip().split()) # result = 0 # if 1 <= x <= 31 and 1 <= y <= 12: # result += 1 # if 1 <= y <= 31 and 1 <= x <= 12: # result += 1 # print(result % 2) # # # main() def main(): a, b, c = map(int, input().split()) if a == b: ...
buy_schema = { 'items': [ { 'itemKey': { 'inventoryType': 'CHAMPION', 'itemId': -1 }, 'purchaseCurrencyInfo': { 'currencyType': 'IP', 'price': -1, 'purchasable': True }, ...
#class Solution(object): # def isNumber(self, s): # """ # :type s: str # :rtype: bool # """ # if s == '': return False # if s.strip() == '.': return False # # define the Deterministic Finite Automata # dfa = [ # DFA init: q0, valid: q2,q4,q7,q8 # {'...
# -*- coding: UTF-8 -*- URL = 'http://booking.bettersoftware.it/conference/getinfo.py/empty_attendees' SUBJECT = "[Better Software 2009] dati mancanti per il tuo badge di ingresso" BODY = u"""Ciao, questa mail è inviata automaticamente dal nostro gestionale a tutti gli utenti che hanno acquistato un biglietto per Be...
''' Функция get_sum() определена следующим образом: def get_sum(x, y, z): return x + y + z print('Сумма равна', x + y + z) Что будет выведено в результате выполнения следующего программного кода? print(get_sum(1, 2, 3)) ''' def get_sum(x, y, z): return x + y + z print('Сумма равна', x + y + z) # не...
#!/usr/bin/python3 # 文件名:class.py class MyClass: """一个简单类实例""" i = 12345 def f(self): return 'hello world' # 实例化类 x = MyClass() # 访问类属性、方法 print("MyClass 类属性i为:",x.i) print("MyClass 类方法f输出为:",x.f())
class Tabs: MEMBERS = "Members" SITES = "Sites" ROLES = "Roles" DETAILS = "Details" class Details: NAME = "Name" EORI_NUMBER = "EORI number" SIC_NUMBER = "SIC code" VAT_NUMBER = "VAT number" REGISTRATION_NUMBER = "Registration number" CREATED_AT = "Created at" PRIMARY_SITE ...
def scope_test(): def do_local(): spam = 'local spam' def do_nonLocal(): nonlocal spam spam = 'non local spam' def do_global(): global spam spam = 'global spam' spam = 'test spam' do_local() print('after local assignment: ', spam) do_nonLocal() ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ SER-347 - João Felipe lista-03 Exercício 05. Faça um programa em Python que pergunte ao usuário qual a série que ele deseja calcular e em seguida imprima o nome da série escolhida. """ # Definindo as series numero = list(range(0, 5, 1)) nomes = ['Lucas', 'Pell', 'Tria...
#!/usr/bin/env python # -*- coding: utf-8 -*- class InvalidTokenTypeError(Exception): pass class InvalidNodeTypeError(Exception): pass class InvalidTargetNodeTypeError(Exception): pass
a,b,c = input().split() a,b,c = [float(a),float(b),float(c)] if a+b <= c or b+c <= a or c+a <= b: print("NAO FORMA TRIANGULO") else: if a*a == b*b+c*c or b*b == a*a+c*c or c*c == b*b+a*a: print("TRIANGULO RETANGULO") elif a*a > b*b+c*c or b*b > a*a+c*c or c*c > b*b+a*a: print("TRIANG...
""" @author: magician @date: 2019/12/13 @file: exception_demo.py """ def divide(a, b): """ divide :param a: :param b: :return: """ try: return a / b except ZeroDivisionError: return None def divide1(a, b): """ divide1 :param a: :param b: ...
def print_without_vowels(s): ''' s: the string to convert Finds a version of s without vowels and whose characters appear in the same order they appear in s. Prints this version of s. Does not return anything ''' # Your code here newString = "" for item in s: if item not in "...
expected_1 = ({ '__feature_4': [ 42., 67., 6., 92., 80., 10., 90., 5., 100., 40., 23., 44., 81., 53., 37., 7., 79., 45., 87.], '__feature_2': [ 91., 15., 36., 51., 32., 11., 38., 56., 21., 34., 75., 77., 98., 71., 95., ...
""" Physical and mathematical constants and conversion functions. """ __all__ = 'deg rad eV meV keV nanometer angstrom micrometer millimeter ' \ 'meter nm mm energy2wavelength wavelength2energy rad2deg deg2rad'.split() deg: float = 1. rad: float = 3.1415926535897932 / 180 # Energy eV: float = 1. meV: floa...
""" Class hierarchy for types of people in college campus """ class College: def __init__(self, college): self.college = college def __str__(self): return f"College: {self.college}" class Department(College): def __init__(self, college, department, **kwargs): self.department = de...
def choise_sort(seq): """Функция производит сортировку методом вставки""" for pos in range(0, len(seq)-1): for i in range(pos+1, len(seq)): if seq[i] < seq[pos]: seq[i], seq[pos] = seq[pos], seq[i] return seq #############################################################...
# inteiros idade = 22 ano = 2021 # reais altura = 1.63 saldo = 10.50 # palavras (strings) nome = 'Luisa' sobrenome = 'Moura'
def example_filter1(string): return "Example1: " + string def get_template_filter(): return example_filter1 def returns_string_passed(string): return string def title_string(string): return string.title()
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. class BotFrameworkSkill: """ Registration for a BotFrameworkHttpProtocol based Skill endpoint. """ # pylint: disable=invalid-name def __init__(self, id: str = None, app_id: str = None, skill_endpoint: st...
#Programming Part variables #kinect_add = "./x64/Release/AzureKinectDK.exe" kinect_add = "C:/Users/User/Desktop/EVCIDNet-master/x64/Release/AzureKinectDK.exe" result_add = "./AzureKinectDK/output/result.txt" flag1_add = "./AzureKinectDK/output/flag1.txt" #image capture start flag flag2_add = "./AzureKinectDK/output/fla...
film = input('Введите название фильма: ') name = input('Введите название кинотеатра: ') time = input('Введите, во сколько начнётся фильм: ') yay = lambda film, name, time: 'Билет на " ' + film + ' " в "' + name + '" на' + time + 'забронирован' print(yay(film, name, time))
#!/usr/bin/env python ########################################################################################## ########################################################################################## ########################################################################################## # IF YOU ARE DOING THE N...
#!/usr/bin/env python # -*- coding: utf-8 -*- '''conftest.py for cpac. Read more about conftest.py under: https://pytest.org/latest/plugins.html ''' # import pytest def pytest_addoption(parser): parser.addoption('--platform', action='store', nargs=1, default=[]) parser.addoption('--tag', action='store', narg...
# last data structure # Sets are unorded collection of unique objects my_set = {1, 2, 4, 4, 5, 5, 5, 4, 3, 3} print(my_set) # useful methods new_set = my_set.copy() print(new_set) my_set.add(100) print(my_set)
text = "PER" s = input() n = 0 d = 0 for i in s: if n > 2: n = 0 if i != text[n]: d += 1 n += 1 print(d)
nome = str(input('Digite o seu nome: ')) cores = {'branco':'\033[30m', 'vermelho':'\033[31m', 'verde':'\033[32m', 'amarelo':'\033[33m', 'azul':'\033[34m', 'roxo':'\033[35m', 'ciano':'\033[36m', 'cinza':'\033[37m', 'limpa':'\033[m'} if nome == 'Gabr...
def sum_list(lst): my_list = lst if len(my_list) == 1: return my_list[0] return my_list[0] + sum_list(my_list[1:]) lst = [1,2,3,4] print(sum_list(lst))
# path to folder with data BASEPATH = '/home/michal/Develop/oshiftdata/' # name of the Elasticsearch index INDEX_NAME = 'pagesbtext' # type of the Elasticsearch index INDEX_TYPE = 'page' # host address of MongoDB MONGODB_HOST = "127.0.1.1" # port of MongoDB MONGODB_PORT = 27017 # name of MongoDB database MONGODB_DB = "...
""" 8.12 – Sanduíches: Escreva uma função que aceite uma lista de itens que uma pessoa quer em um sanduíche. A função deve ter um parâmetro que agrupe tantos itens quantos forem fornecidos pela chamada da função e deve apresentar um resumo do sanduíche pedido. Chame a função três vezes usando um número diferente de arg...
num1 = int(input("Please input your num1:")) num2 = int(input("Please input your num2:")) s = num1 + num2 print(s)
class Solution(object): def islandPerimeter(self, grid): """ :type grid: List[List[int]] :rtype: int """ res = 0 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 1: if i == 0: ...
class Solution: def uniquePaths(self, m: int, n: int) -> int: if m <= 0 or n <= 0: raise Exception("Invalid Matrix Size") dp = [[0] * n for _ in range(m)] for i in range(m): for j in range(n): if i == 0 and j == 0: dp[i][j] = 1 ...
# -*- coding: utf-8 -*- """ crie um programa que tenha uma tupla com várias palavras( não usar acentos). Depois disso. você deve mostrar, para cada palavra, quais são as suas vogais. """ palavras = ('dicionario', 'abobado', 'putrefato', 'pai') print(len(palavras)) print(len(palavras[0])) i = j = 0 for i in range(0...
honored_guest = ['YULIU', 'Jim', 'Shi'] print(honored_guest[0] + ' and ' + honored_guest[1] + ' and ' + honored_guest[2] + ' ' + "eat dinner") print("Shi cannot come here to eat dinner") honored_guest.sort() print(honored_guest) honored_guest.remove('Shi') print(honored_guest)
n=[5,6,7] # Atomic valences nc=[5,6,7] # Atomic valences l=2 # Orbital angular momentum of the shel J=0.79 # Slatter integrals F2=J*11.9219653179191 from the atomic physics program, must ...
count_sum_1 = 0 count_sum_2 = 0 with open('input', 'r') as f: groups = f.read().split('\n\n') # Part One for group in groups: yes_set = set(group.strip()) if '\n' in yes_set: yes_set.remove('\n') yes_count = len(yes_set) # print(f'yes_count = {yes_count}, yes_set = {yes_set}') count_...