content
stringlengths
7
1.05M
# Define the class as author class Author: # The function is in it and the __ is a special function in python. properties in the brackets are what # is being passed in the function def __init__(self, name, firstName, nationality): # Define the attributes in the class self.name = name ...
db = { "users": [ { "id": 2, "username": "marceline", "name": "Marceline Abadeer", "bio": "1000 year old vampire queen, musician" } ], "threads": [ { "id": 2, "title": "What's up with the Lich?", "cr...
class LogEntry(dict): """ Log message and info for jobs and services Fields: - ``id``: Unique ID for the log, string, REQUIRED - ``code``: Error code, string, optional - ``level``: Severity level, string (error, warning, info or debug), REQUIRED - ``message``: Error message,...
""" from django import forms from .models import Item class AddForm(forms.ModelForm): class Meta: model = Item fields = ('created_by', 'title', 'image', 'description', 'price', 'pieces', 'instructions', 'labels', 'label_colour', 'slug') """
''' http://pythontutor.ru/lessons/for_loop/problems/sum_of_n_numbers/ Дано несколько чисел. Вычислите их сумму. Сначала вводите количество чисел N, затем вводится ровно N целых чисел. Какое наименьшее число переменных нужно для решения этой задачи? ''' inp = int(input()) s = 0 for _ in range(inp): s += int(input()...
# "Strange Number" # Alec Dewulf # April Long 2020 # Difficulty: Easy # Prerequisities: Number Theory """ OVERVIEW This solution is based on the idea that the number of prime factors (k) must be less than the total prime factors (max_k). The number of factors can be calculated by adding one to each exponent in a nu...
class Node: def __init__(self, data=None): self.val = data self.next = None class LinkedList: def __init__(self): self.head=None def push(self,val): new_node=Node(val) #case 1 if self.head is None: self.head=new_node self.head.next=None return ...
def crossingSum(matrix, a, b): return sum(matrix[a]) + sum([x[b] for i, x in enumerate(matrix) if i != a]) if __name__ == '__main__': input0 = [[[1,1,1,1], [2,2,2,2], [3,3,3,3]], [[1,1], [1,1]], [[1,1], [3,3], [1,1], [2,2]], [[100]], [[1,2], [3,4]], [[1,2,3,4]], [[1,2,3,4,5], [1,2,2,2,2], [1,2,2,2,2], [1,2,2,2,2], [...
r,x,y,z=open("ads\\1Plumber\\Ad.txt").read().split("\n", 3) print(y)
""" MAD LIBS Objetivo: Completar as frases com palavras. """ ### 1 print("""1- Rosas são _______(1) _______ são azuis(2) Eu amo _______(3) Quais seriam as palavras?""") pri=input("1: ") seg=input("2: ") ter=input("3: ") print(f"Então ficaria assim!\n\nRosas são {pri}\n{seg} são azuis\nEu amo {ter}...
ENTRY_POINT = 'circular_shift' #[PROMPT] def circular_shift(x, shift): """Circular shift the digits of the integer x, shift the digits right by shift and return the result as a string. If shift > number of digits, return digits reversed. >>> circular_shift(12, 1) "21" >>> circular_shift(12, 2) ...
#Crie um programa que simule o funcionamento de um caixa eletrônico. No início, pergunte ao usuário qual será o valor a ser sacado (número inteiro) e o programa vai informar quantas cédulas de cada valor serão entregues. #OBS: considere que o caixa possui cédulas de R$50, R$20, R$10 e R$1. totalCedula = 0 cedula = 50 ...
# A collection of quality of life functions that may be used in many places # A silly function to set a defatul value if not in kwargs def kwarget(key, default, **kwargs): if key in kwargs: return kwargs[key] else: return default
nome = str(input('\033[33;44mDigite o nome de uma cidade:\033[m ')).strip().capitalize().split() print('O nome da cidade começa com a palavras "Santo"?: {}'.format(nome[0] == 'Santo')) # Forma como o Gustavo Guanabara resolveu, mas tem uma falha, se digitar "santos" ele considera True, pois # o programa só está lendo ...
def salary_net_uah(salary_usd, currency, taxes, esv): # What salary in UAH after paying taxes salary_uah = salary_usd*currency salary_minus_taxes = salary_uah - salary_uah*taxes/100 result_uah = salary_minus_taxes - esv return result_uah def salary_net_usd(salary_usd, currency, taxes, esv): # ...
n = int(input("Enter Height : ")) if(n%2==0): print("Invalid Input") else: half = n//2 for i in range(half+1): for j in range(i+1): print("*",end="") print() for i in range(half): for j in range(half-i): print("*",end="") print()
class User: def __init__(self, username): self.username = username def __repr__(self): return self.username class ListWithUsers: def __init__(self): self.users = [] def add_user(self, user: User): self.users.append(user) def remove_user(self, username: str): ...
splitString = 'Hello\nWorld' print(splitString) # While writing """ or ''' python interpreter waits for next three " or ' to end vars anotherSplitString = '''Multiline in Single variable and i don't need to escape single or double " quote :)''' print(anotherSplitString) # Escaping \ from string # escape \ with anothe...
class Fight: """ Parameters ----------- id: `int` ID of the fight number (including trash packs) boss: `int` ID of the boss start_time: `int` Start time of the figth in milliseconds end_time: `int` End time of the fight in mill...
class NoTargetFoundError(Exception): def __init__(self): super().__init__("Received attack action without target set. Check correctness") class IllegalTargetError(Exception): def __init__(self, agent): super().__init__( "The chosen target with id {0} can not be attacked/healed by a...
mod = 10**9+7 def extgcd(a, b): r = [1,0,a] w = [0,1,b] while w[2] != 1: q = r[2]//w[2] r2 = w w2 = [r[0]-q*w[0], r[1]-q*w[1], r[2]-q*w[2]] r = r2 w = w2 return [w[0], w[1]] def mod_inv(a,m): x = extgcd(a,m)[0] return ( m + x%m ) % m def main(): ...
#=============================================================================== # #=============================================================================== # def Sum(chunks, bits_per_chunk): # assert bits_per_chunk > 0 # return sum( map(lambda (i, c): c * (2**bits_per_chunk)**i, enumerate(chunks)) ) d...
class Material(): def __init__(self, E, v, gamma): self.E = E self.v = v self.gamma = gamma self.G = self.E/2/(1+self.v)
"""Kata url: https://www.codewars.com/kata/57a5c31ce298a7e6b7000334.""" def bin_to_decimal(inp: str) -> int: return int(inp, 2)
number = str(input('Digite um numero de 4 digitos: ')) print('Analisando {}....'.format(number)) number.split(" ") print(number) print('Tem {} Milhar'.format(number[0])) print('Tem {} Centenas'.format(number[1])) print('Tem {} Dezenas'.format(number[2])) print('Tem {} Unidades'.format(number[3]))
class GanException(Exception): def __init__(self, error_type, error_message, *args, **kwargs): self.error_type = error_type self.error_message = error_message def __str__(self): return u'({error_type}) {error_message}'.format(error_type=self.error_type, ...
populationIn2012 = 1000 populationIn2013 = populationIn2012 * 1.1 populationIn2014 = populationIn2013 * 1.1 populationIn2015 = populationIn2014 * 1.1
# If you want your function to accept more than one parameter def f(x, y, z): return x + y + z result = f(1, 2, 3) print(result)
'''input 100 99 9 SSSEEECCC 96 94 3 2 3 SEC 1 1 2 4 6 SSSEEE 0 1 0 3 6 SEECEE 0 0 ''' # -*- coding: utf-8 -*- # bitflyer2018 qual # Problem B if __name__ == '__main__': a, b, n = list(map(int, input().split())) x = input() for xi in x: if xi == 'S' and a > 0:...
"""This problem was asked by LinkedIn. Given a string, return whether it represents a number. Here are the different kinds of numbers: - "10", a positive integer - "-10", a negative integer - "10.1", a positive real number - "-10.1", a negative real number - "1e5", a number in scientific notation And here are ex...
print("hello world") def get_array(file_name: str): with open(file_name) as f: array = [[x for x in line.split()] for line in f] return(array) def card_to_tuple(card: str): faces = { "A" : 14, "K" : 13, "Q" : 12, "J" : 11, "T" : 10, ...
# -*- coding: utf-8 -*- """ Created on Thu Dec 31 12:37:52 2020 @author: SethHarden Heap Sorting a List """ # Data structure for Max Heap # return left child of A[i] def LEFT(i): return 2 * i + 1 # return right child of A[i] def RIGHT(i): return 2 * i + 2 # Utility function to swap two indices in the...
# -*- coding: utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def __eq__(self, other): return ( other is not None and self.val == other.val and self.left == other.left and self.rig...
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.m...
#!/usr/bin/python # -*- coding: utf-8 -*- """ @author: rainsty @file: decorator.py @time: 2019-12-30 13:34:29 @description: decorator """
class DeviceConsent: def __init__( self, id: int, location_capture: bool, location_granular: bool, camera: bool, calendar: bool, photo_sharing: bool, push_notification: bool, created_at, updated_a...
def deleteDuplicate(elements): del_duplicates = set(elements) return list(del_duplicates) if __name__ == '__main__': list_with_Duplicate = [1,2,34,2,3,1,5,6,3,1,2,6,5,4,3] print(deleteDuplicate(list_with_Duplicate))
# Challenge 8 : Create a function named max_num() that takes a list of numbers named nums as a parameter. # The function should return the largest number in nums # Date : Sun 07 Jun 2020 09:19:45 AM IST def max_num(nums): maximum = nums[0] for i in range(len(nums)): if maximum < nums[i]: ...
#!/usr/bin/env python # encoding:utf-8 # file: homework1.py # 列表中找元素 # TODO 用哈希表实现元素查找 def find1(lst, elem): """方法1:遍历 """ for i in lst: if elem == i: return 1 else: return 0 def find2(lst, elem): """方法2:内置方法 """ return 1 if elem in lst else 0 if __name__ =...
class FetchMinAllotments: ''' Uses a state or territory and a household size to fetch the min allotment, returning None if the household is not eligible for a minimum allotment. In 2020, only one- and two- person households are eligible for a minimum allotment amount. ''' def __init__(self...
#Hi, here's your problem today. This problem was recently asked by Twitter: #Given a binary tree and an integer k, filter the binary tree such that its leaves don't contain the value k. Here are the rules: #- If a leaf node has a value of k, remove it. #- If a parent node has a value of k, and all of its children are...
SECTOR_SIZE = 40000 def pixels2sector(x, y): return str(int(x/SECTOR_SIZE+.5)) + ":" + str(int(-y/SECTOR_SIZE+.5)) def sector2pixels(sec): x, y = sec.split(":") return int(x)*SECTOR_SIZE, -int(y)*SECTOR_SIZE
# returns unparenthesized character string def balanced_parens(s): open_parens = len(s) - len(s.replace("(", "")) closed_parens = len(s) - len(s.replace(")", "")) if (open_parens == closed_parens): return True else: return False
def get_data(): # get raw data for modeling print('Get data..') return
""" Definition for classes used to represent models generated by Swagger. """ class Error: def __init__(self): self.code = 200 self.message = "OK" def __str__(self): return self.code+ " : " +self.message class Evidence: def __init__(self): self.evidenceSource = [] ...
## Problem: Print details def printOwing(self, amount): self.printBanner() # print details print("name: ", self._name) print("amount: ", amount) def printLateNotice(self, amount): self.printBanner() self.printLateNoticeHeader() # print details print("name: ", self._name) print("amou...
lower = list(range(3,21,1)) upper = list(range(21,39,1)) output = "" count = 0 for i in range(len(lower)): for j in range(len(lower)): if j != i and j != i-1 and j != i+1: count += 1 output += "\t" + str(lower[i]) + "\t" + str(lower[j]) + "\n" for i in range(len(upper)): for ...
extensions = ["sphinx.ext.autodoc", "sphinx_markdown_builder"] master_doc = "index" project = "numbers-parser" copyright = "Jon Connell"
#Ex1072 Intervalo 2 entrada = int(input()) cont = 1 intervalo = 0 fora = 0 while cont <= entrada: numeros = int(input()) if numeros >= 10 and numeros <= 20: intervalo = intervalo + 1 else: fora = fora + 1 cont = cont + 1 print('{} in\n{} out'.format(intervalo, fora))
class ROBConfig(Config): """Configuration for training on the toy shapes dataset. Derives from the base Config class and overrides values specific to the toy shapes dataset. """ # Give the configuration a recognizable name NAME = "rob" # Train on 1 GPU and 8 images per GPU. We can put multi...
#!/usr/bin/python3 DATABASE = "./vocabulary.db" WORD_TYPE_CUTOFFED = 1 WORD_TYPE_CUTOFF = 0 WORD_RIGHT_YES = 1 WORD_RIGHT_NO = 0 # wrong words review frequency, N means wrong words will occur each N times. WRONG_WORDS_REVIEW_FREQUENCY = 3 # highlight and with font color red. RECITE_PRINT_FORMAT = "[{}...
# -*- coding: utf-8 -*- # """ Partie arithmetique du module lycee. """ def pgcd(a, b): """Renvoie le Plus Grand Diviseur Communs des entiers ``a`` et ``b``. Arguments: a (int) : un nombre entier b (int) : un nombre entier """ if a < 0 or b < 0: return pgcd(abs(a), abs(b)) ...
def is_number_tryexcept(s): """ Returns True is string is a number. """ try: int(s) return True except ValueError: return False def get_valid_k_input(list_length): while True: k = input('podaj k: ') if not is_number_tryexcept(k): print('podana warto...
def findComplement(self, num: int) -> int: x = bin(num)[2:] z = "" for i in x: z+=str(int(i) ^ 1) return int(z, 2)
class Fancy: def __init__(self): self.data=[] self.add=[] self.mult=[] def append(self, val: int) -> None: self.data.append(val) if len(self.mult)==0: self.mult.append(1) self.add.append(0) self.mult.append(self.mult[-1]) ...
class Logger(object): ''' Utility class responsible for logging all interactions during the simulation. ''' # TODO: Write a test suite for this class to make sure each method is working # as expected. # PROTIP: Write your tests before you solve each function, that way you can # test them one by one...
""" Title - Trie Data Structure Data structure to insert and search word efficiently time complexity - O(n) where n=len(word) """ class LL: # Linked List Data structure to store level wise nodes of Trie def __init__(self, val): self.val = val self.next = {} self.completed = False class...
#layout notes: # min M1 trace width for M1-M2 via: 0.26um # min M2 trace width for Li -M2 via: 0.23um trace with 0.17um x 0.17um contact class LogicCell: def __init__(self, name, width): self.width = width self.name = name inv1 = LogicCell("sky130_fd_sc_hvl__inv_1", 1.44) inv4 = LogicCell("sky130_fd_sc_hvl...
num1 = 5 num2 = 25 print('num1 is: ', str(num1)) print('num2 is: ', str(num2)) for i in range(num1, num2 + 1, 5): print('i is currently: ', str(i)) print(str(i) + ' ', end='') print() print()
# -*- coding: utf-8 -*- for i in range(1,3): print(i)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: Zeyuan Shang # @Date: 2015-11-19 20:43:07 # @Last Modified by: Zeyuan Shang # @Last Modified time: 2015-11-19 20:43:21 class Solution(object): def shortestPalindrome(self, s): """ :type s: str :rtype: str """ ss = s...
#!/usr/bin/env python # -*- coding: utf-8 -*- class QLTecnica(object): u"""Técnica para Q-Learning""" def __init__(self, parametro=None, paso_decremento=0, intervalo_decremento=0): super(QLTecnica, self).__init__() self._paso_decremento = paso_decremento self._intervalo_decremento = in...
# Summation of primes # The Sum of the primes below 10 is 2 + 3+ 5 +7 = 17. # # Find the sum of all the primes below two million. if __name__ == "__main__": prime = False prime_numbers = [2] counter = 3 while (counter < 2000000): for i in range(2,counter): if counter % i == 0: ...
def get_frequency(numbers): return sum(numbers) def get_dejavu(numbers): frequencies = {0} frequency = 0 while True: for n in numbers: frequency += n if frequency in frequencies: return frequency frequencies.add(frequency) if __name__ == "...
def prime(x): limit=x**.5 limit=int(limit) for i in range(2,limit+1): if x%i==0: return False return True print("Not prime") a=int(input("N=")) result=prime(a) print(result)
# !/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2021/9/29 # @Author : MashiroF # @File : HT_account.py # @Software: PyCharm ## 账号管理样本 # { # 'user':'', # 备注,必要 # 'CK':'', # Cookie,必要(建议全部粘贴) # 'UA':'' # User-Agent,必要 # }, ## 账号管理 accounts = [ {...
# # PySNMP MIB module EdgeSwitch-TIMEZONE-PRIVATE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EdgeSwitch-TIMEZONE-PRIVATE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:57:00 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Pytho...
class Solution: def generateMatrix(self, n: int) -> List[List[int]]: res = [[0]*n for i in range(n)] left,right,top,bot = 0,n,0,n num = 1 while left < right and top < bot: for i in range(left, right): res[top][i] = num ...
""" This function appends index.html to all request URIs with a trailing slash. Intended to work around the S3 Origins for Cloudfront, that use Origin Access Identity. """ def lambda_handler(event, _): # pylint: disable=C0116 request = event["Records"][0]["cf"]["request"] old_uri = request["uri"] # If U...
__all__ = ['mpstr'] def mpstr(s): return '$<$fff' + s + '$>'
''' PROGRAM TO FOR A GIVEN LIST OF STUDENTS, MARKS FOR PHY, CHEM, MATHS AND BIOLOGY FORM A DICTIONARY WHERE KEY IS SRN AND VALUES ARE DICTIONARY CONTAINING PCMB MARKS OF RESPECTIVE STUDENT.''' #Given lists srns = ["PECS001","PECS015","PECS065","PECS035","PECS038"] p_marks = [98,99,85,92,79] c_marks = [91,90,...
# change_stmt() accepts the number of bills/coins you want to return and # creates the appropriate string def change_stmt(twenties, tens, fives, ones, quarters, dimes, nickels, pennies): if twenties == 0 and tens == 0 and fives == 0 and ones == 0 and quarters == 0 and dimes == 0 and nickels == 0 and pennies == 0: ...
# 🚨 Don't change the code below 👇 height = input("enter your height in m: ") weight = input("enter your weight in kg: ") # 🚨 Don't change the code above 👆 #Write your code below this line 👇 heightNum= float(height) weightNum=float(weight) print(str(int(weightNum/heightNum**2)))
# Write an implementation of the classic game hangman # fill in the implementation in this program bones if __name__ == '__main__': print("Welcome to hangman!!") #to-do: choos the hidden word: it can be a constant or random choosed from a list or dowloaded from an api #to-do: choose how many tries are...
class GoCardlessError(Exception): pass class ClientError(GoCardlessError): """Thrown when there was an error processing the request""" def __init__(self, message, errors=None): self.message = message if errors is not None: self.message += self._stringify_errors(errors) ...
dia1 = int(input().split()[1]) h1, m1, s1 = map(int, input().split(' : ')) dia2 = int(input().split()[1]) h2, m2, s2 = map(int, input().split(' : ')) segs = (s2+(86400*dia2)+(3600*h2)+(60*m2))-(s1+(86400*dia1)+(3600*h1)+(60*m1)) print(segs//86400, 'dia(s)') print(segs%86400//3600, 'hora(s)') print(segs%86400%3600//60...
###################################################### # Interpreter | CLCInterpreter #----------------------------------------------------- # Interpreting AST (Abstract Syntax Tree) ###################################################### class CLCInterpreter: def __init__(self,ast,storage): self.r = 0 ...
""" File type enumaration. """ IMAGE = 'image' VIDEO = 'video' FILE = 'file'
def separa(texto, sep): ''' Recebe uma string e a separa de acordo com o caracter separador recebido ''' lista = texto.split(sep) return lista def maior_palavra(): texto = input("Digite palavras separadas por vírgula: ") list_words = separa(texto, ",") length_word = 0 bigger_word = "...
def capture(matrix, r, c, size): possible_moves = [(x, y) for x in range(-1, 2) for y in range(-1, 2)] for move in possible_moves: first_step_row = r + move[0] first_step_col = c + move[1] next_row = first_step_row next_col = first_step_col while 0 <= next_row < size and ...
# # PySNMP MIB module ELTEX-MES-IpRouter (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-MES-IpRouter # Produced by pysmi-0.3.4 at Wed May 1 13:01:34 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
#!/usr/bin/env python3 # Closure def outer_function(msg): def inner_function(): print(msg) return inner_function # Decorator Function def decorator_function(original_function): def wrapper_function(*args, **kwargs): print('Wrapper executed this before {}'.format(original_function.__name_...
# Corrigido # Usando a formatação no bloco de saída nome = 'Guanabara' print() print('Muito prazer em te conhecer, {}{}{}!'.format( '\033[4;34m', nome, '\033[m')) print()
""" Investigating Ulam sequences """
# -*- coding: utf-8 -*- """ Created on Fri Sep 27 11:31:56 2019 @author: Kieran """ def shortest_distance_of_cluster(cluster): """ given an input NumpyArray cluster, it computes the shortest distance between any pair of atoms. It returns the shortest_distance and the closest atoms. shortes...
# 词汇表 dist = {'python': 'lift is bab,I use python.', 'php': 'php is the best language in the world.'} for k, v in dist.items(): print(k + ':' + v)
{ "targets": [ { "target_name": "jspmdk", "sources": [ "jspmdk.cc", "persistentobjectpool.cc", "persistentobject.cc", "persistentarraybuffer.cc", "internal/memorymanager.cc", "internal/pmdict.cc", "internal/pmarray.cc", "internal/...
""" 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(intege...
################################################################################ # Author: Fanyang Cheng # Date: 2/26/2021 # This program asks user for a number and send back all the prime numbers from 2 # to that number. ################################################################################ def is_prim...
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: if not nums or k < 1: return False used = {} flag = False for i, v in enumerate(nums): if v in used and not flag: flag = (i - used[v] <= k) used[v] ...
# Copyright 2020 The Google Earth Engine Community Authors # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
#MIT License #Copyright (c) 2017 Tim Wentzlau # 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, publ...
""" 给定一个字符串 S 和一个字符串 T,计算在 S 的子序列中 T 出现的个数。 一个字符串的一个子序列是指,通过删除一些(也可以不删除)字符且不干扰剩余字符相对位置所组成的新字符串。(例如,"ACE" 是 "ABCDE" 的一个子序列,而 "AEC" 不是) 示例 1: 输入: S = "rabbbit", T = "rabbit" 输出: 3 解释: 如下图所示, 有 3 种可以从 S 中得到 "rabbit" 的方案。 (上箭头符号 ^ 表示选取的字母) rabbbit ^^^^ ^^ rabbbit ^^ ^^^^ rabbbit ^^^ ^^^ 示例 2: 输入: S = "babgbag", T =...
class min_PQ(object): def __init__(self): self.heap = [] def __repr__(self): heap_string = '' for i in range(len(self.heap)): heap_string += str(self.heap[i]) + ' ' return heap_string # check each non-root node is >= its parent def check_invariant(self): ...
dados = dict() totg = list() cont = gol = 0 dados['nome'] = (str(input('Informe o nome do jogador: '))).strip().title() part = (int(input('Informe a quantidade de partidas do jogador: '))) for c in range(1, part + 1): gols = (int(input(f'Quantos gols foram marcados no {c}ª partidada? '))) totg.append(gols) dado...
#! /usr/bin/env python3 """ example module: extra.good.omega """ def FunO(): return "Omega" if __name__ == "__main__": print("I prefer to be a module")
"""练习 1:遍历商品控制器""" class Graphiciterator: def __init__(self, date): self.date = date self.index = -1 def __next__(self): self.index += 1 if self.index > len(self.date) - 1: raise StopIteration return self.date[self.index] class GraphicController: def ...
c=2;r='' while True: s=__import__('sys').stdin.readline().strip() if s=='Was it a cat I saw?': break l=len(s) for i in range(0, l, c): r+=s[i] c+=1;r+='\n' print(r, end='')
# Go to http://apps.twitter.com and create an app. # The consumer key and secret will be generated for you after CONSUMER_KEY="FILL ME IN" CONSUMER_SECRET="FILL ME IN" # After the step above, you will be redirected to your app's page. # Create an access token under the the "Your access token" section ACCESS_TOKEN="FIL...
class ColorCode: def getOhms(self, code): d = { 'black': ('0', 1), 'brown': ('1', 10), 'red': ('2', 100), 'orange': ('3', 1000), 'yellow': ('4', 10000), 'green': ('5', 100000), 'blue': ('6', 1000000), 'violet': (...