content
stringlengths
7
1.05M
#MAP # def fahrenheit(T): # return (9/5) * T + 32 temp = [9,22,40,90,120] # for t in temp: # print(fahrenheit(t)) # print(list(map(fahrenheit, temp))) # print(list(map(lambda t:(9/5)*t+32,temp))) #FILTER pares = [1,2,3,4,8,10,11,15,16,28,24,20] # print(list(filter(lambda x: x%2 == 0, pares))) #ZIP x = ...
# # PySNMP MIB module RSVP-MIB (http://pysnmp.sf.net) # ASN.1 source http://mibs.snmplabs.com:80/asn1/RSVP-MIB # Produced by pysmi-0.0.7 at Sun Feb 14 00:27:32 2016 # On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose # Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52) # ( ObjectIden...
# Implemente uma nova classe que simule uma pilha usando apenas duas filas. class Node: def __init__(self, data, next=None): self.data = data self.next = next class MyQueue: def __init__(self): self.head = None self.tail = self.head def enqueue(self, value): if (se...
class card(): """docstring for .""" def __init__(self, name, type, cost, coins=0, vp=0): ''' Parameters: name: string type: LIST OF STRINGS cost: int coins: int vp: int Returns: None ''' ...
# 371. Sum of Two Integers # ttungl@gmail.com # Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. class Solution: def getSum(self, a, b): """ :type a: int :type b: int :rtype: int """ # sol 1: # runtime: 40ms ...
''' 199. Binary Tree Right Side View Medium Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. Example 1: Input: root = [1,2,3,null,5,null,4] Output: [1,3,4] Example 2: Input: root = [1,null,3] Output: [1,3] E...
class Content(): def __init__(self): self.content_type = "video" self.title = "sample title" self.author = {"url": "", "name": "James"} self.time_estimate = "(15 min)" self.url = "http://mim-rec-engine.heroku.com" self.thumbnail_url = "static/imgs/document.png" ...
""" diamond.clauses ~~~~~~~~~~~~~~~ :copyright: (c) 2015 Jaco Ruit :license: MIT, see LICENSE for more details """ class Node(object): def __init__(self, inner = None, condition = None): self.inner = inner self.condition = condition self.children = [] def __and__(...
__author__ = 'hs634' class Solution(): def __init__(self): pass def three_sum_zero(self, arr): arr, solution, i = sorted(arr), [], 0 while i < len(arr) - 2: j, k = i + 1, len(arr) - 1 while j < k: three_sum = arr[i] + arr[j] + arr[k] ...
print('this repo is belong to nbnitboy') print('this line is added by tangcg !') print('删除原始仓库,添加forked仓库后,提交代码 !') print('this line is added by tangcg')
class Solution: def merge(self, A, m, B, n): sm, sn, i = m - 1, n - 1, m + n - 1 while sm >= 0 and sn >= 0: if A[sm] > B[sn]: A[i] = A[sm] sm -= 1 else: A[i] = B[sn] sn -= 1 i -= 1 while sn >...
class TasksService: def __init__(self, site): self.__site = site self.__is_loaded = False def load(self): self.__is_loaded = True
class Recipe(object): def __init__(self): self.ingredients = [] # need to store lots of qty & unit & ingred per recipe. will be ordered triple self.directions = "" # how to make this food self.notes = "" # personal annotations re: this recipe self.recipe_name = "" # what's in a ...
# Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos Dólares ela pode comprar. # Considere US$1,00 = R$3,27 real = float(input('Digite quanto voçê possui na carteira e descubra quantos Dólares voçê conseguiria comprar: R$')) dolar = real / 3.27 print('Com R${:.2f} que voçê possui ...
CITIES = { 'ADAMAOUA' : 1, 'CENTRE' : 2 , 'EST' : 3, 'EXTREME-NORD' : 4, 'LITTORAL' : 5, 'OUEST' : 6, 'NORD' : 7, 'NORD-OUEST' : 8, 'SUD' : 9, 'SUD-OUEST' : 10, 'DOUALA' : 'X-22', 'YAOUNDE' : 'X-1' } MESSAGE = """ Bonjour, je suis zlight-bot (by landryjohn -> </lnjohn>...
class User: """ Class that generates new instances of users. """ list_of_users = [] def __init__(self, user_name,gender, password): self.user_name = user_name self.gender = gender self.password = password def save_user(self): ''' function that saves Use...
class GetTableInteractor(object): def __init__(self, repo): self.repo = repo def set_params(self, user, year, month, before, after): self.user = user self.year = year self.month = month self.before = before self.after = after return self def exec...
# AUTOGENERATED! DO NOT EDIT! File to edit: 13_dataproc.ipynb (unless otherwise specified). __all__ = ['dataproc_test'] # Cell def dataproc_test(test_msg): "Function dataproc" return test_msg
def parse_config(path): """ This method parses a config file and constructs a list of blocks. Each block is a singular unit in the architecture as explained in the paper. Blocks are represented as a dictionary in the list. Input: - path: path to the config file. Returns: - a list co...
todos = [ { 'id': 1, 'title': 'Workout tomorrow', 'body': 'I intend to go through some rigorous exercise targetting my abs and my lower stomach', 'completed': False, 'date': '08/12/2019' }, { 'id': 2, 'title': 'Chefs Quaters', 'body': 'I intend...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 递归函数 # 计算阶乘 def fact(n): if n == 1: return 1 else: return n * fact(n - 1) print(fact(6)) # 尾递归形式: 尾递归是指,在函数返回的时候,调用自身本身,并且,return语句不能包含表达式。 # 如果尾递归做了优化是可以解决递归调用栈溢出的 # 但是 Python标准的解释器没有针对尾递归做优化,任何递归函数都存在栈溢出的问题。 def fact1(n): return fact_i...
class Solution: def combine(self, n: int, k: int) -> List[List[int]]: ans = [] def dfs(n: int, k: int, s: int, path: List[int]) -> None: if k == 0: ans.append(path.copy()) return for i in range(s, n + 1): path.append(i) dfs(n, k - 1, i + 1, path) path.pop(...
# ----------- # User Instructions: # # Modify the the search function so that it returns # a shortest path as follows: # # [['>', 'v', ' ', ' ', ' ', ' '], # [' ', '>', '>', '>', '>', 'v'], # [' ', ' ', ' ', ' ', ' ', 'v'], # [' ', ' ', ' ', ' ', ' ', 'v'], # [' ', ' ', ' ', ' ', ' ', '*']] # # Where '>', '<', '^',...
class PID: """ Discrete PID control """ def __init__(self, P=2.0, I=0.0, D=1.0, Derivator=0, Integrator=0, Integrator_windup_max=100, Integrator_windup_min=-100): self.Kp=P self.Ki=I self.Kd=D self.Derivator=Derivator self.Integrator=Integrator self.Integrator_max=Integrator_windup_max self.Integrat...
def add_numbers(start,end): c = 0 for number in range(start,end+1): print(number) c = c + number return(c) answer = add_numbers(333,777) #print(answer) #print(add_numbers()) #add_numbers()
# CELERY CELERY_BROKER_URL = 'redis://10.16.78.86:6380' CELERY_RESULT_BACKEND = 'redis://10.16.78.86:6380' # NGINX STATIC HOME DOC_HOME = '/opt/data' # Flask-Log Settings LOG_LEVEL = 'debug' LOG_FILENAME = "/var/archives/error.log" LOG_ENABLE_CONSOLE = False # REDIS Settings REDIS_HOST = '10.16.78.86'...
X = [[12,7,3], [4,5,6], [7,8,9]] Y = [[5,8,1], [6,7,3], [4,5,9]] result = [[0,0,0], [0,0,0], [0,0,0]] print(len(X),len(Y)) # iterate through rows for i in range(0,3): # iterate through columns for j in range(0,3): result[i][j] = X[i][j] + Y[i][j] for r in result: pr...
#!/bin/python3 annee_naissance = input('t ne ou ') annee = 2025 - int(annee_naissance) print(annee) print(f'voila : {str(annee)} pewepw')
# Python program to demonstrate in-built poly- # morphic functions # len() being used for a string print(len("geeks")) # len() being used for a list print(len([10, 20, 30]))
""" PayloadGroup type/prototype containing multiple Payload objects """ class PayloadGroup(object): """ PayloadGroup Class: groups of individual Payload objects. """ def __init__(self, payloads, check_type_list=[]): """ Initialize a PayloadGroup This interface is kept similar to the interface...
class Solution: def isOneBitCharacter(self, bits): if len(bits) == 1: return True idx = 0 while True: if idx == len(bits) - 3 or idx == len(bits) - 2: break if bits[idx] == 1: idx += 2 else: idx +...
# S E # array = [8, 5, 2, 8, 5, 6, 3] # P L R # if s >= e : r # assigning p, l, r -variables # while r >= e # if l >= p & r <= p # swap # l <= p - l+ # r >= p - r- # leftsubarrayissmaller = r - 1 - s < e - (r + 1) # (p , s, r - 1) # (p, r + 1, e) # Worst : time - O(n^2),Space- O(log(n)) # in inp...
def palindrome(n): a0=n s=0 while a0>0: d=a0%10 s=s*10+d a0=a0//10 if s==n: return 1 else: return 0 n=int(input("Enter a number ")) if palindrome(n)==1: print("palindrome ...") else: print("Not palindrome..")
# coding=utf-8 # 定义类 # 定义列属性 class DataConfig(): # 用例属性: case_id = "用例ID" case_model = "模块" case_name = "接口名称" url = "请求URL" pre_exec = "前置条件" method = "请求类型" params_type = "请求参数类型" params = "请求参数" expect_result = "预期结果" actual_result = "实际结果" beizhu = "备注" ...
class Bicycle: def __init__(self, name, wheel_numbers, brake_type, gear_number): self.name = name self.wheel_numbers = wheel_numbers self.brake_type = brake_type self.gear_number = gear_number bicycle = Bicycle('single speed', '2', 'rim brake', 'free wheel') print(bicycle.n...
CELERY_IMPORTS=("app", ) CELERY_BROKER_URL="amqp://saket:fedora13@localhost//" CELERY_RESULT_BACKEND="amqp://saket:fedora13@localhost//" SQLALCHEMY_DATABASE_URI="mysql://saket:fedora13@localhost/moca" CELERYD_MAX_TASKS_PER_CHILD=10
""" File: largest_digit.py Name: Johsuan ---------------------------------- This file recursively prints the biggest digit in 5 different integers, 12345, 281, 6, -111, -9453 If your implementation is correct, you should see 5, 8, 6, 1, 9 on Console. """ def main(): print(find_largest_digit(12345)) # 5 print(f...
def ficha(nome, gols): if not gols.isnumeric(): gols = '0' if nome == '': nome = '<desconhecido>' print('O jogador {} marcou {} gol(s) no campeonato.'.format(nome, gols)) print('-' * 50) nome = str(input('Nome do jogador: ')) gols = str(input('Número de gols: ')) ficha(nome, gols)
class Restaurant: def __init__(self): self.restaurant = [] def update_location(self): pass def add(self, restaurant): self.restaurant.append(restaurant)
t = int(input()) for i in range(t): count = 0 n = int(input()) l = list(map(int, input().split())) for j in range(1,len(l)-1): if l[j-1]<l[j] and l[j+1]<l[j]: count += 1 print(f'Case #{i+1}: {count}')
def linear_search(arr, x): for i in range(len(arr)): if arr[i] == x: return i return -1 def binary_search(arr, low, high, x): if high >= 1: mid = (high + low) // 2 if arr[mid] == x: return mid elif arr[mid] > x: return binary_search(arr...
# Exercício Python 19: Crie um programa que leia duas notas de um aluno e calcule sua média, mostrando uma mensagem no final, de acordo com a média atingida: #Média abaixo de 5.0: REPROVADO #Média entre 5.0 e 6.9: RECUPERAÇÃO #Média 7.0 ou superior: APROVADO n1 = float(input('Insira sua nota 1: ')) n2 = float(input('I...
emptyForm = """ {"form": [ { "type": "message", "name": "note", "description": "Connect to graphql" }, { "name": "url", "description": "Graphql URL", "type": "string", "required": true } ]} """
""" List of image ids for the validation split of the full training set of the MPII Pose dataset. The image file ids have been randomly generated and are set to have a split of 70-30 w.r.t. all available person detections with all pose detections for the custom training and validation splits. """ val_images_ids = [...
# Used for import directories into other modules. Good for setting # project wide parameters, such as the location of the database. class settings(): db = "C:\\Users\\Andrew\\lab_project\\database\\frontiers_corpus.db" d2v = "C:\\Users\\Andrew\\lab_project\\models\\doc2vecmodels\\" d2v500 = "C:\\Users\\Andrew\...
i18 = { "en": {"title": "What's this?", "read_more": "Read more", "upload_image": "Upload your image", "try_again": "Try again"}, "pt": {"title": "O que é isso?", "read_more": "Leia mais", "upload_image": "Envie sua imagem", "try_again": "Tente n...
class OverrideRootError(Exception): def __init__(self): super().__init__(self, "Cannot override Tree root node") class TreeHeightError(Exception): def __init__(self): super().__init__(self, "Cannot add node lower than tree height")
CROCKFORD_MODIFIED = ( b"ahm6a81a59rqaub3dcn2m832e9qqevh0ctqqg83aenpq0wt0dxv6awh0ehm6a818dhgqmy994" b"1j6ytt1" ) CROCKFORD = ( b"AHM6A81A59RQATB3DCN2M832E9QQEVH0CSQQG83AENPQ0WS0DXV6AWH0EHM6A818DHGQMY994" b"1J6YSS1" ) ZBASE32 = ( b"ktwgkebkfjazk4mdpcinwednqjzzq5tyc3zzoedkqiszyh3yp75gkhtyqtwgkebeptozw...
# Script to help automation of converting a cpu/layoutX/CpuConstraintPoly.sol contract to Rust # Parses out "mload(0xDEADBEEF)" (Solidity EVM Assembley Command) from the file and replaces it with the proper Rust equivalent # Note: replace file_name.txt appropriately # file_name.txt should contain Solidity Assembly fro...
del_items(0x80137B7C) SetType(0x80137B7C, "void EA_cd_seek(int secnum)") del_items(0x80137BA4) SetType(0x80137BA4, "void MY_CdGetSector(unsigned long *src, unsigned long *dst, int size)") del_items(0x80137BD8) SetType(0x80137BD8, "void init_cdstream(int chunksize, unsigned char *buf, int bufsize)") del_items(0x80137BE8...
MONOBANK_API_TOKEN = None MONOBANK_API_BASE_URL = 'https://api.monobank.ua' MONOBANK_API_CURRENCY_ENDPOINT = MONOBANK_API_BASE_URL + '/bank/currency' MONOBANK_API_CLIENT_INFO_ENDPOINT = MONOBANK_API_BASE_URL + '/personal/client-info' MONOBANK_API_WEBHOOK_ENDPOINT = MONOBANK_API_BASE_URL + '/personal/webhook' MONOBANK_...
arquivo = open('numeros.txt', 'w') for linha in range(1, 101): arquivo.write('%d\n' % linha) arquivo.close()
""" Copyright 2017 Timothy Laskoski tree.py handles all code related to the parse tree """ def tree_append(parent, sub): "tree_append appends a sub tree to the parent tree" parent["Sub"].append(sub) # print("TREE APPEND", parent) def add_subtree(parent, token): "add_subtree adds a subtree with a toke...
def getMessage(content): firstCarrot = content.index('<') secondCarrot = content.index('>') return content[firstCarrot+3:secondCarrot] y = getMessage('GG <@!799778925936246804>, you just advanced to level 5') print(y)
# Bubble sort def sort_bubble(my_list): for i in range(len(my_list) - 1, 0, -1): for j in range(i): if my_list[j] > my_list[j + 1]: my_list[j], my_list[j + 1] = my_list[j + 1], my_list[j] return my_list print(sort_bubble([1,4,2,6,5,3,1]))
#program to enter number followed by commas and the storing those numbers in a list arr=[];r=0; a=input("ENter numbers followed by commas :") l=a.split(",") m='' for c in a: if(c!=','): m=m+c; else: arr.append(int(m)); m=''; arr.append(int(m)); print(arr);
file = open ("employees.txt" , "r") if(file.readable()): print("Success") else: print("Error") print() #read the whole file print(file.read()) #rewind file pointer file.seek(0) print() #read individual line print(file.readline()) #rewind file pointer file.seek(0) print() #read the whole file and set as l...
red_flags = { 'strony wyłączają uprawnienia [\w]+ do dochodzenia roszczeń z tytułu wad [\w]+ ujawnionych po dniu zakupu.': 'Nielegalny zapis. Sprzedawca nie może odmówić reklamacji z powodu ukrytych wad.', '[\w]+ zastrzega sobie [\w\s]*prawo do zmiany zakresu usług określonych w Regulaminie oraz możliwość zaprzestania ...
class UserOutputVariables: """The UserOutputVariables object specifies the number of user-defined output variables. Notes ----- This object can be accessed by: .. code-block:: python import material mdb.models[name].materials[name].userOutputVariables import odbMaterial ...
''' Script converts data from newline seperated values to comma seperated values ''' fName = input('Enter File Name:') with open(fName,'r') as f: lines = f.read() f.close() values = lines.splitlines() s = 'time\n' for val in values: s = s + val.strip() + '\n' print(s) with open(fName,'w') as f: f.w...
# Spiritual Release (57462) sakuno = 9130021 sm.setSpeakerID(sakuno) sm.sendNext("Kanna, please come to Momijigaoka. We have news.") sm.setPlayerAsSpeaker() sm.sendSay("I wonder what's going on? I hope Oda's Army isn't on the move.") sm.startQuest(parentID)
# 登录界面标题 LOGIN_TITLE = 'Xadmin管理后台' # 登录页面背景图序号 BACKGROUND_INDEX = 1
Theatre_1 = {"Name":'Lviv', "Seats_Number":120, "Actors_1":["Andrew Kigan","Jhon Speelberg","Alan Mask","Neil Bambino"], "Play_1":["25/03/2018","Aida",80,"Andrew Kigan","Jhon Speelberg",60,"OK"], "Play_2":["26/03/2018","War",220,"Jhon Speelberg","Jhon Speelberg","Alan...
''' Subgraphs II In the previous exercise, we gave you a list of nodes whose neighbors we asked you to extract. Let's try one more exercise in which you extract nodes that have a particular metadata property and their neighbors. This should hark back to what you've learned about using list comprehensions to find node...
""" This module contain functions which are cheking whether the given board fits the rules. Git repository: https://github.com/msharsh/puzzle.git """ def check_rows(board: list) -> bool: """ Checks if there are identical numbers in every row in the board. Returns True if not, else False. >>> check_rows(["**...
# program description # :: python # :: allows user to enter initial height of ball before dropped # :: outputs total distance traveled by ball based on number of bounces # constants bounceIndex = float(0.6) # input variables height = int(input("Enter Ball Height: ")) numberOfBounces = float(input("Enter Number Of Bal...
"""Top-level package for EnviroBot.""" __author__ = """Chris Last""" __email__ = 'chris.last@gmail.com' __version__ = '0.1.0'
class Stack: def __init__(self): self.items = [] def push(self, e): self.items = [e] + self.items def pop(self): return self.items.pop() s = Stack() s.push(5) # [5] s.push(7) # [7, 5] s.push(11) # [11, 7, 5] print(s.pop()) # returns 11, left is [7, 5] print(s.pop()) ...
i=map(int, raw_input()) c=0 for m in i: c = c+1 if m==4 or m==7 else c print("YES" if c==4 or c==7 else "NO")
class Solution: def tribonacci(self, n: int) -> int: if n <= 1: return n arr = [0 for i in range(n+1)] arr[1], arr[2] = 1, 1 for i in range(3, len(arr)): arr[i] = arr[i-1] + arr[i-2] + arr[i-3] return arr[n] s = Solution() print(s.tribonacc...
class Yo(): def __init__(self, name): self.name = name def say_name(self): print('Yo {}!'.format(self.name))
""" 1. Clarification 2. Possible solutions - dfs, bottom-up - dfs, top-down - bfs 3. Coding 4. Tests """ # 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 # T=O(n)...
# coding: utf8 """""" VOICES = { "mei-jia": "com.apple.speech.synthesis.voice.mei-jia", "ting-ting": "com.apple.speech.synthesis.voice.ting-ting", }
class AlreadyFiredError(RuntimeError): pass class InvalidBoardError(RuntimeError): pass class InvalidMoveError(RuntimeError): pass
class Solution: def canPermutePalindrome(self, s: str) -> bool: x={} k=0 for i in set(s): x[i]=s.count(i) for i,j in x.items(): if j%2!=0: k=k+1 if k>1: return False return True
# Задача №292. Максимум из двух чисел # # Входные данные # Даны два целых числа, каждое число записано в отдельной строке. # # Выходные данные # Выведите наибольшее из данных чисел. # # Примеры # входные данные # 1 # 2 # выходные данные # 2 a = int(input()) b = int(input()) if a > b : print(a) else: print(b)
def test_user_creation(faunadb_client): username = "burgerbob" created_user = faunadb_client.create_user( username=username, password="password1234" ) assert created_user["username"] == username all_users = faunadb_client.all_users() assert len(all_users) == 1
''' ## Questions ### 154. [Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/) Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). Find the minimum element....
""" Demonstrates prompting a user to enter input using the keyboard. This demonstrates two different ways to get the user's input as a string and converts the input to an int-type. The same thing can be done for floats by using the float function instead of the int function. """ number1 = input("Enter the first numbe...
numero = int(input('\nDigite um número inteiro: ')) if numero%2 == 0: print('\033[1;33mO número {} é PAR! \33[m \n' .format(numero)) else: print('\033[1;32mO número {} é IMPAR! \33[m \n' .format(numero))
class Base(object): """ Basic Session Entity is the base entity representing the data in thte session. """ def __init__(self, session_id, key, content): self._session_id = session_id self.key = key self.content = content @property def session_id(self): ...
# "Unit GCD" # Alec Dewulf # April Long 2020 # Difficulty: Simple # Concepts: Pigeonhole principle """ EXPLANATION This problem becomes very simple if you notice that there are n//2 even numbers and by pigeonhole principle each must be on a different day (they all share a factor of two). Therefore there must be n//2...
# # PySNMP MIB module CISCO-ATM-SERVICE-REGISTRY-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ATM-SERVICE-REGISTRY-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:33:26 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python ...
API_TOKEN = "465633546:AAGQNVuoqn5gouyOieqCj1yQbo2riAyebSM" WEBHOOK_HOST = '104.131.96.14' WEBHOOK_PORT = 8443 # 443, 80, 88 or 8443 (port need to be 'open') WEBHOOK_LISTEN = '0.0.0.0' # In some VPS you may need to put here the IP addr WEBHOOK_SSL_CERT = '/home/gorec/Shefflera/db_and_certs/webhook_cert.pem' # Path...
""" Copyright (c) Facebook, Inc. and its affiliates. """ class StopCondition: def __init__(self, agent): self.agent = agent def check(self) -> bool: raise NotImplementedError("Implemented by subclass") class NeverStopCondition(StopCondition): def __init__(self, agent): super()._...
# ------------------------------ # 144. Binary Tree Preorder Traversal # # Description: # Given a binary tree, return the preorder traversal of its nodes' values. # Example: # Input: [1,null,2,3] # 1 # \ # 2 # / # 3 # Output: [1,2,3] # # Follow up: Recursive solution is trivial, could you do it ite...
salir="s" while salir!="Salir": try: seguir_ordenando="s" cantidad_total_producto=[0,0,0] cantidad_producto=[0,0,0] producto=["Papas","Hamburguesas","Tacos"] total=0 print("Bienvenido al Restaurante Rapi-Comidas\nEl menú de hoy es: \n\t1. Papas \t\tValor: 600 ...
# 函数名作为变量名 a, b, c = 3, 7, 5 max = max(a, b, c) # 第一次执行:OK (max = 7) print('a、b和c中的最大值是', max, '。') max = max(a, b, c) # 第二次执行:错误(max = 7(a, b, c))
def set_partitions(iterable, k=None): """ Yield the set partitions of *iterable* into *k* parts. Set partitions are not order-preserving. >>> iterable = 'abc' >>> for part in set_partitions(iterable, 2): ... print([''.join(p) for p in part]) ['a', 'bc'] ['ab', 'c'] ['b', 'ac'] ...
def is_anagram(first, second): return sorted(list(first)) == sorted(list(second)) def main(): valid = 0 with open('day_4.in', 'r') as f: for l in f.readlines(): split = l.strip().split(' ') valid_passphrase = True for start in range(0, len(split) - 1): ...
# joint class definitions class TripleJoint(object): """ Describing the relations and dowel placement between 3 beams. """ def ___init___(self, beam_set, type_def, loc_para = 0): """ Initialization of a triple-joint isinstance :param beam_set: Which beams to conside...
#!/usr/bin/env python """ Desafio do vídeo "Entrada de Dados": Reescreva o programa conta Segundos para imprimir também a quantidade de dias, ou seja, faça um programa em Python que dada a quantidade de segundos, o programa "quebra" esse valor em dias, horas, minutos e segundos. A saída deve estar ...
APP_KEY = 'u5lo5mX6IzAyv9TQJZG5tErDP' APP_SECRET = 'pJ294qcsbwcEty3ePPbGYVbD9sTL2J7dgC7BDdQ4KyoupmAxHS' OAUTH_TOKEN = '1285969065996095488-WqwqIQPP69TovfaCISoY6DkWWgwajY' OAUTH_TOKEN_SECRET = 'PIC1rTAs9Q9HD8zpGV7dMC5FMXpWmM5yn5WFhpJHt3li5' ## Your Telegram Channel Name ## channel_name = 'uchihacommunity' ## Telegram A...
''' 62-Melhore o desafio 061,perguntando para o usuário se ele quer mostrar mais alguns termos.O programa encerrará quando ele disser que quer mostrar 0 termos. ''' primeirotermo=int(input('Digite o primeiro termo: ')) razao=int(input('Digite a razao: ')) i=1 termo=10 total=0 while termo != 0: total=total+termo ...
n1 = int(input('Digite um numero: ')) n2 = int(input('Digite um numero: ')) if n1 > n2: print('{} é maior que o {}.'.format(n1, n2)) elif n1 < n2: print('{} é maior que o {}.'.format(n2, n1)) else: print('Os numeros são iguais!!')
""" cmd.do('stereo walleye; ') cmd.do('set ray_shadow, off; ') cmd.do('#draw 3200,2000;') cmd.do('draw ${1:1600,1000}; ') cmd.do('png ${2:aaa}.png') cmd.do('${0}') """ cmd.do('stereo walleye; ') cmd.do('set ray_shadow, off; ') cmd.do('#draw 3200,2000;') cmd.do('draw 1600,1000; ') cmd.do('png aaa.png') # Description: ...
""" 闭包: 闭包指延伸了作用域的函数,其中包含函数定义体中引用、但是不在定义体中定义的非全局变量。 函数是不是匿名的没关系,关键是它能访问定义体之外定义的非全局变量。 """ def make_averager(): """ 闭包 """ # 局部变量(非全局变量)(自由变量) series = [] def averager(new_value): series.append(new_value) total = sum(series) return total / len(series) retu...
#Programa analisador #Dado um certo tipo de informação, o programa analisa e mostra na tela algumas informações sobre ela. dado = input("Digite aqui uma informação para ela ser analisada: ") print(f'O tipo primitivo Dessa informação é: {type(dado)}') print("A informação é Numerico? {}".format(dado.isnumeric())) print("...
""" Lecture 10: Dynamic Programming Alternating Coin Game --------------------- Consider a game where you have a list with an even number of coins with positive integer values v_0, v_1, ..., v_i, ..., v_(n - 1) Each player alternates picking either the leftmost or rightmost coin until there are no coins left. Whichev...
""" author : @akash kumar github : https://github/Akash671 string fun: string.replace(sub_old_string,new_sub_string,count) string.count(your_string) """ def solve(): #n,m=map(int,input().split()) #n=int(input()) #a=list(map(int,input().split()[:n])) #s=str(input()) #a,b=input().split() s=str(input(...