content
stringlengths
7
1.05M
print('-'*10, 'TABUADA', '-'*10) n = 0 while True: num = int(input('Digite um número:')) if num < 0: break for c in range(1,11): print(f'{num} x {c} = {num * c}') print('Programa Tabuada encerrado. Até mais!')
# Note: The schema is stored in a .py file in order to take advantage of the # int() and float() type coercion functions. Otherwise it could easily stored as # as JSON or another serialized format. '''This schema has been changed compared to the Udacity schema, due to missing values for attributes 'user' and 'uid'. ...
class Port: def __init__(self, mac_address, ip_address, mtu): self.mac_address = mac_address self.ip_address = ip_address self.mtu = mtu def __str__(self): return '(%s - %s - %d)' % (self.mac_address, self.ip_address, self.mtu)
class Context: def __init__(self, **kwargs): self.message = kwargs.get("message") self.command = kwargs.get("command") def print(self, content, *, indent=0, **kwargs): if indent > 0: lines = content.split("\n") for line in lines: prefix =...
''' Config! Change as needed. NOTE: Please make sure that all information (except for authentication keys) are passed in lower-case! ''' # Your twitter access tokens. These are your accounts that you will enter giveaways from. # Add as many users as you want, and please make sure to enter your username in lower case!...
class Solution(object): def evalRPN(self, tokens): """ :type tokens: List[str] :rtype: int """ stack = [] for token in tokens: if token not in "+-*/": stack.append(int(token)) else: b = stack.pop() ...
n, m = [int(x) for x in input().split()] edges = [[int(x) for x in input().split()] for _ in range(m)] if m < n - 1: print(0) exit() paths = [] start = 1 still_possible = True while still_possible: passed = [1] current = start for i in range(1, n): for e in edges: ...
def is_unique_points(points=None): if points is None: points = {} points_dict = {} for key, values in points.items(): new_key = '%s:%s' % tuple(values) is_exists = points_dict.get(new_key, None) if is_exists: return False else: points_dict[new...
def XXX(self, root: TreeNode) -> int: if root is None: return 0 m = 10 ** 5 # m为最小深度 def bfs(d, node): nonlocal m if node.left is None and node.right is None: m = min(m, d) return bfs(d + 1, node.left) if node.left else None bfs(d + 1, node.r...
""" Conditionally Yours Pseudocode: """ # Increase = Current Price - Original Price # Percent Increase = Increase / Original x 100 # Create integer variable for original_price # Create integer variable for current_price # Create float for threshold_to_buy # Create float for threshold_to_sell # Create float...
def containsDuplicate(nums): sorted = sorted(nums) for i in range(len(nums)-1): if nums[i] == nums[i+1]: return True return False
def find_max(root): if not root: return 0 if not root.left and not root.right: return root.val m = [0] helper(root, m) return m[0] def helper(n, m): if n.val > m[0]: m[0] = n.val if n.left: helper(n.left, m) if n.right: helper(n.right, m)
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # ...
# -*- coding: utf-8 -*- """ Created on Wed Dec 13 11:06:08 2017 @author: James Jiang """ def position(range_firewall, time): offset = time % (2 * (range_firewall - 1)) if offset > range_firewall - 1: return(2 * (range_firewall - 1) - offset) else: return(offset) all_lines = [line.rstrip...
#!/usr/bin/env python3 def chdir(path, folder): return path+"/"+folder def previous(path): temp = "" for i in path.split("/")[1:-1]: temp += "/"+i return temp
# Bradley Grose data = ("John", "Doe", 53.44) format_string = "Hello %s %s. Your current balance is $%s" print(format_string % data)
""" Write a Python program to count number of substrings from a given string of lowercase alphabets with exactly k distinct (given) characters """ def count_k_dist(str1, k): str_len = len(str1) result = 0 ctr = [0] * 27 for i in range(0, str_len): dist_ctr = 0 ctr = [0] * 27 for j in range(i, str_len...
def winning_score(): while True: try: winning_score = int(input("\nHow many points should " "declare the winner? ")) except ValueError: print("\nInvalid input type. Enter a positive number.") continue else: if winnin...
''' Else Statements Code that executes if contitions checked evaluates to False. '''
class Solution: def selfDividingNumbers(self, left: int, right: int) -> List[int]: ret = [] for x in range(left, right + 1): y = x while y > 0: z = y % 10 if z == 0 or x % z != 0: break; y //= 10 ...
'''Jonatan Paschoal 22/04/2020 Desafio 8 - Faça um programa que receba um valor em metros e transforme para centímetros e milímetros.''' print('=='*30) x = float(input('Digite um valor em metros: ')) cent = x / 100 mili = x / 1000 print('{:.5f} em centímetros é {:.5f} e em milímetros {:.5f}.'.format(x, cent, mili)) pri...
# -*- coding: utf_8 -*- __author__ = 'Yagg' class ShipGroup: def __init__(self, ownerName, count, shipType, driveTech, weaponTech, shieldTech, cargoTech, cargoType, cargoQuantity): self.count = count self.shipType = shipType self.driveTech = driveTech self.weaponTech = weaponTech ...
# 也是二分法 class Solution: def mySqrt(self, x: int) -> int: if x < 2: return x left, right = 2, x // 2 + 1 while left <= right: mid = left + (right - left) // 2 if mid * mid > x: right = mid - 1 elif mid * mid < x: ...
#!/usr/bin/python3 """ Analysis for a 4 load cells (2 strain gauges each) wired to give a single differential output. https://www.eevblog.com/forum/reviews/large-cheap-weight-digital-scale-options/ """ def deltav(V, R, r0, r1, r2, r3): """return the differential output voltage for the 4x load cell""" i0 = V / (4....
#!/usr/bin/env python3 # https://codeforces.com/problemset/problem/72/G # 该题目cf不支持python~~因此不放入周赛题库.. n = int(input()) if n<2: print(1) else: l = [1,1] + [0]*(n-1) for i in range(2,n+1): l[i] = l[i-1] + l[i-2] print(l[-1])
class MyHookExtension(object): def post_create_hook(self, archive, product): pass def post_ingest_hook(self, archive, product): pass def post_pull_hook(self, archive, product): pass def post_remove_hook(self, archive, product): pass _hook_extensions = { 'myhooks'...
# return a go-to-goal heading vector in the robot's reference frame def calculate_gtg_heading_vector( self ): # get the inverse of the robot's pose robot_inv_pos, robot_inv_theta = self.supervisor.estimated_pose().inverse().vector_unpack() # calculate the goal vector in the robot's reference frame goal = sel...
# Time: O(nlogn) # Space: O(n) class Solution(object): def stoneGameVI(self, aliceValues, bobValues): """ :type aliceValues: List[int] :type bobValues: List[int] :rtype: int """ sorted_vals = sorted(((a, b) for a, b in zip(aliceValues, bobValues)), key=sum, reverse=...
# pylint: disable=global-statement,missing-docstring,blacklisted-name foo = "test" def broken(): global foo bar = len(foo) foo = foo[bar]
def parse_input(): fin = open('input_day3.txt','r') inputs = [] for line in fin: inputs.append(line.strip('\n')) return inputs def plot_path(inputs, path, ref_path=None): x=0 y=0 c = 0 hits = [] for i in inputs.split(','): (d, v) = (i[0],int(i[1:])) fn =...
if __name__ == "__main__": cadena = "Hola, Mundo" print("Imprimir Cadena") print(cadena) print("Imprimir Caracter por Caracter") for caracter in cadena: print(caracter) print("Imprimir lista =>") for entero in range(10): print(entero) # Secuencias de ruptura ...
class Solution: def detectCycle(self, head): """O(n) time | O(1) space""" fast = slow = head while fast and fast.next: fast = fast.next.next slow = slow.next if fast is slow: return find_cycle(head, slow) return None def find_cycle...
# This file is imported from __init__.py and exec'd from setup.py __version__ = "1.0.0+dev" VERSION = (1, 0, 0)
#returns list of groups. group is a list of strings, a string per person. def getgroups(): with open('Day6.txt', 'r') as file: groupList = [] currgroup = [] for line in file: if line not in ['\n', '\n\n']: currgroup.append(line.strip()) else: ...
""" # Definition for a Node. class Node: def __init__(self, val, children): self.val = val self.children = children """ class Solution: def levelOrder(self, root): """ :type root: Node :rtype: List[List[int]] """ if not root: return [] ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Exits with status 0""" if __name__ == '__main__': exit(0)
# # @lc app=leetcode id=342 lang=python # # [342] Power of Four # # https://leetcode.com/problems/power-of-four/description/ # # algorithms # Easy (39.98%) # Likes: 315 # Dislikes: 141 # Total Accepted: 114.1K # Total Submissions: 283.1K # Testcase Example: '16' # # Given an integer (signed 32 bits), write a fun...
list1=['Apple','Mango',1999,2000] print(list1) del list1[2] print("After deleting value at index 2:") print(list1) list2=['Apple','Mango',1999,2000,1111,2222,3333] print(list2) del list2[0:3] print("After deleting value till index 2:") print(list2)
# -*- coding: utf-8 -*- """ Created on Wed Dec 25 22:07:19 2019 @author: penko Returns information on all maps (e.g. Hanamura) in Overwatch, with options to return only OWL modes, and unique maps only (due to a quirk of the API). """ ''' # packages used in this function import requests import numpy as np import pan...
base_vectors = [[0.001178571428571168, 1.9904285714285708, 0.0011071428571440833], [-0.013142857142857345, -0.0018571428571430015, 1.9921428571428583], [-0.0007499999999995843, 0.17799999999999994, -0.00024999999999630873], [-4.440892098500626e-16, -8.881784197001252e-16, 0.1769999999999996]] n = [8, 8, 6, 6] origin = ...
def solveProblem(inputPath): floor = 0 indexFloorInfo = 0 with open(inputPath) as fileP: valueLine = fileP.readline() for floorInfo in valueLine: indexFloorInfo += 1 if floorInfo == '(': floor += 1 elif floorInfo == ')': ...
try: tests=int(input()) k=[] for i in range(tests): z=[] count=0 find,length=[int(x) for x in input().split(" ")] list1=list(map(int,input().rstrip().split())) for i in range(len(list1)): if list1[i]==find: z.append(i+1) ...
d = int(input('Quantos dias alugados? ')) k = float(input('Quantos Km rodados? ')) v = (d*60)+(0.15*k) print('O total a pagar é de R$ {:.2f}'.format(v))
python = {'John':35,'Eric':36,'Michael':35,'Terry':38,'Graham':37,'TerryG':34} holy_grail = {'Arthur':40,'Galahad':35,'Lancelot':39,'Knight of NI':40, 'Zoot':17} life_of_brian = {'Brian':33,'Reg':35,'Stan/Loretta':32,'Biccus Diccus':45} #membership test print('Arthur' in holy_grail) if 'Arthur' not in python: prin...
class Permission: """ An object representing a single permission overwrite. ``Permission(role='1234')`` allows users with role ID 1234 to use the command ``Permission(user='5678')`` allows user ID 5678 to use the command ``Permission(role='9012', allow=False)`` denies users with role ID 9012 ...
def dict_repr(self): return self.__dict__.__repr__() def dict_str(self): return self.__dict__.__str__() def round_price(price: float, exchange_precision: int) -> float: """Round prices to the nearest cent. Args: price (float) exchange_precision (int): number of decimal digits for exch...
a, b, c = input().split(' ') a = float(a) b = float(b) c = float(c) areat = (a * c) / 2 areac = 3.14159 * c**2 areatp = (a + b) * c / 2 areaq = b * b arear = b * a print(f'TRIANGULO: {areat:.3f}') print(f'CIRCULO: {areac:.3f}') print(f'TRAPEZIO: {areatp:.3f}') print(f'QUADRADO: {areaq:.3f}') print(f'RETANGULO: {arear:....
#! python3 # aoc_05.py # Advent of code: # https://adventofcode.com/2021/day/5 # https://adventofcode.com/2021/day/5#part2 # def hello_world(): return 'hello world' class ventmap: def __init__(self, xmax, ymax): self.xmax = xmax self.ymax = ymax self.map = [[0 for i in range(xmax...
# # PySNMP MIB module RAQMON-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RAQMON-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:52:12 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:...
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Coupon_validity, obj[4]: Gender, obj[5]: Age, obj[6]: Children, obj[7]: Education, obj[8]: Occupation, obj[9]: Income, obj[10]: Bar, obj[11]: Coffeehouse, obj[12]: Restaurant20to50, obj[13]: Direction_same, obj[14]: Distance # {"feature":...
def fib(x): if x < 2: return x return fib(x - 1) + fib(x-2) if __name__ == "__main__": N = int(input()) while N > 0: x = int(input()) print(fib(x)) N = N - 1
T = int(input()) for _ in range(T): for i in range(1, 1001): print(i**2) a = int(input()) if a==0: continue else: break
"""Tiered Lists - a simple way to group items into tiers (at insertion time) while maintaining uniqueness.""" class TieredLists(object): def __init__(self, tiers): self.tiers = sorted(tiers, reverse=True) self.bags = {} for t in self.tiers: self.bags[t] = set() def get_tie...
class BaseException(object): ''' The base exception class (equivalent to System.Exception) ''' def __init__(self): self.message = None
"""Module responsible for client implementation """ class ScrollClient: """ ScrollClient ------------ Class responsible for client implementation """ def __init__(self): self._comm_channel = None @property def comm_channel(self): return self._comm_channel ...
class Name(object): def __init__(self, normal: str, folded: str): self.normal = normal self.folded = folded
#series系列の成績上位x単位分の重率をwに変更するということ def top_grades_series(s_dict, series, credits, w): s_dict_name_series = {} #seriesで指定された系列をs_dict内から抽出したもの array = [] for s in series: #辞書要素に、既にあるpoint, credit, weightに加えて、seriesを追加 for name in s_dict[s].keys(): s_dict_name_series[name] ...
a = b'hello' b = '哈哈'.encode() print(a,b) print(type(a),type(b)) c = b'haha' d = '你好'.encode() print(c) print(type(c))
#!/usr/bin/env python # -*- coding: utf-8 -*- """ author: meng.xiang date: 2019-05-08 description: """ class CAP_STYLE(object): round = 1 flat = 2 square = 3 class JOIN_STYLE(object): round = 1 mitre = 2 bevel = 3
n = int(input()) x = list(map(int, input().split())) m = 0 e = 0 c = 0 for n in x: m += abs(n) e += n ** 2 c = max(c, abs(n)) print(m) print(e ** 0.5) print(c)
""" @Author : sean cheng @Email : aya234@163.com @CreateTime : 2018/9/10 @Program : 全局变量的保存 """ class SettingVar: def __init__(self): # 颜色词典 self.COLOR_DICT = {'white': (255, 255, 255), # 白色 'ivory': (255, 255, 240), # 象牙色 ...
'''https://www.geeksforgeeks.org/minimum-edges-reverse-make-path-source-destination/ Given a directed graph and a source node and destination node, we need to find how many edges we need to reverse in order to make at least 1 path from source node to destination node. Examples: In case you wish to attend live clas...
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if len(strs) == 1: output = strs[0] if strs == []: output = "" else: output = '' j = 0 Flag = T...
""" @date: 5-14-16 Description: Creates the conflict and broad outlines of story relations """ class Conflict: def __init__(relation_outline_array=None): self.conflict_outline = relation_outline_array def add_relation(relation_outline): self.conflict_outline.append(relation_outline)
#!/usr/bin/env python3 # String to be evaluated s = "azcbobobegghakl" # Initialize count count = 0 # Vowels that will be evaluted inside s vowels = "aeiou" # For loop to count vowels in var s for letter in s: if letter in vowels: count += 1 # Prints final count to terminal print("Number of vowels in ...
class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ ls=s.split(" ") lt=[] for x in ls: x=x[::-1] lt.append(x) return " ".join(lt)
def diglet(i_buraco_origem, buracos): if buracos[i_buraco_origem] == -99: return 0 else: i_buraco_destino = buracos[i_buraco_origem] - 1 buracos[i_buraco_origem] = -99 return 1 + diglet(i_buraco_destino, buracos) def mdc_euclide(a, b): if b == 0: return a else: ...
x = ['happy','sad','cheerful'] print('{0},{1},{2}'.format(x[0],x[1].x[2])) ##-------------------------------------------## a = "{x}, {y}".format(x=5, y=12) print(a)
class UpdateContext: """ Used when updating data. Helps keeping track of whether the data was updated or not. """ data: str data_was_updated: bool = False def __init__(self, data: str): self.data = data def override_data(self, new_data: s...
""" MadQt - Tutorials and Tools for PyQt and PySide All the Code in this package can be used freely for personal and commercial projects under a MIT License but remember that because this is an extension of the PyQt framework you will need to abide to the QT licensing scheme when releasing. ## $MA...
class Book: def __init__(self,title,author): self.title = title self.author = author def __str__(self): return '{} by {}'.format(self.title,self.author) class Bookcase(): def __init__(self,books=None): self.books = books @classmethod def create_bookcase(cls,book_list)...
class FileSystemWatcher(Component): """ Listens to the file system change notifications and raises events when a directory,or file in a directory,changes. FileSystemWatcher() FileSystemWatcher(path: str) FileSystemWatcher(path: str,filter: str) """ def ZZZ(self): """hardcoded/mock instance of th...
# # Copyright (c) 2017 - The MITRE Corporation # For license information, see the LICENSE.txt file __version__ = "1.3.0"
class car(): def __init__(self, make, model, year ): self.make = make self.model = model self.year = year self.odometer = 0 def describe_car(self): long_name = str(self.year)+' '+self.make+' '+self.model return long_name.title() def read_odometer(self): ...
expected_output = { "route-information": { "route-table": [ { "active-route-count": "16", "destination-count": "16", "hidden-route-count": "0", "holddown-route-count": "0", "rt": [ { ...
""" By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? https://projecteuler.net/problem=7 """ # Cache a few primes to get the algorithm started. # Note: the odd values allow the step of 2 in next_prime() primes = [2, 3, 5] # Shortc...
command = input() numbers = [int(n) for n in input().split()] command_numbers = [] def add_command_numbers(num): if (num % 2 == 0 and command == "Even") or (num % 2 != 0 and command == "Odd"): command_numbers.append(num) for n in numbers: add_command_numbers(n) print(sum(command_number...
""" @ 컴프리핸션 (comprehension) ` 하나 이상의 이터레이터로부터 파이썬 자료구조를 만드는 컴팩트한 방법 ` 비교적 간단한 구문으로 반복문과 조건 테스트를 결합 * 리스트 컨프리핸션 [ 표현식 for 항목 in 순회가능객체 ] [ 표현식 for 항목 in 순회가능객체 if 조건 ] * 딕셔러리 컨프리핸션 { 키_표현식: 값_표현식 for 표현식 in 순회가능객체 } * 셋 컨프리핸션 { 표현식 for 표현식 in 순회가능객체 } """ # 컨프리...
class Env(object): user='test' password='test' port=5432 host='localhost' dbname='todo' development=False env = Env()
def get_phase_dir(self): """Return the Rotation direction of the stator phases Parameters ---------- self : LUT A LUT object Returns ------- phase_dir : int Rotation direction of the stator phase """ return self.output_list[0].elec.phase_dir
day09 = __import__("day-09") process = day09.process_gen rotor = { 0: {'N': 'W', 'W': 'S', 'S': 'E', 'E': 'N'}, 1: {'N': 'E', 'E': 'S', 'S': 'W', 'W': 'N'}, } diff = { 'N': (0, 1), 'E': (1, 0), 'S': (0, -1), 'W': (-1, 0), } def draw(data, panels): direction = 'N' coord = (0, 0) try: i...
# from enum import IntEnum LEVEL_UNKNOWN_DEATH = int(0) LEVEL_NOS = int(-1) LEVEL_FINISHED = int(-2) LEVEL_MAX = 21 LEVELS_PER_ZONE = 4 TOTAL_ZONES = 5 # class LevelSpecial(IntEnum): # UNKNOWN_DEATH = 0, # NOS = -1, # FINISHED = -2 # # # class Level(object): # @staticmethod # def fromstr(level_st...
class MagicalGirlLevelOneDivTwo: def theMinDistance(self, d, x, y): return min( sorted( (a ** 2 + b ** 2) ** 0.5 for a in xrange(x - d, x + d + 1) for b in xrange(y - d, y + d + 1) ) )
test = 1 while True: n = int(input()) if n == 0: break participantes = [int(x) for x in input().split()] vencedor = [participantes[x] for x in range(n) if participantes[x] == (x + 1)] print(f'Teste {test}') test += 1 print(vencedor[0]) print()
# Check if there are two adjacent digits that are the same def adjacent_in_list(li=()): for c in range(0, len(li)-1): if li[c] == li[c+1]: return True return False # Check if the list doesn't get smaller as the index increases def list_gets_bigger(li=()): for c in range(0, len(li)-1): ...
FARMINGPRACTICES_TYPE_URI = "https://w3id.org/okn/o/sdm#FarmingPractices" FARMINGPRACTICES_TYPE_NAME = "FarmingPractices" POINTBASEDGRID_TYPE_URI = "https://w3id.org/okn/o/sdm#PointBasedGrid" POINTBASEDGRID_TYPE_NAME = "PointBasedGrid" SUBSIDY_TYPE_URI = "https://w3id.org/okn/o/sdm#Subsidy" SUBSIDY_TYPE_NAME = "Subsidy...
# # @lc app=leetcode id=49 lang=python3 # # [49] Group Anagrams # # https://leetcode.com/problems/group-anagrams/description/ # # algorithms # Medium (60.66%) # Likes: 7901 # Dislikes: 277 # Total Accepted: 1.2M # Total Submissions: 1.9M # Testcase Example: '["eat","tea","tan","ate","nat","bat"]' # # Given an ar...
# Copyright (c) 2019 Pavel Vavruska # 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, publish, d...
def dijkstra(graph): start = "A" times = {a: float("inf") for a in graph.keys()} times[start] = 0 a = list(times) while a: node_selected = min(a, key=lambda k: times[k]) print("node selected", node_selected) a.remove(node_selected) for node, t in graph[node_selected...
# Nodes in lattice graph and associated modules class LatticeNode: def __init__(self, dimensions: tuple): self._parents = list() self._children = list() self._is_pruned = False self.superpattern_count = -1 self.dimensions = dimensions def is_node_pruned(self): r...
globalVar = 0 dataset = 'berlin' max_len = 1024 nb_features = 36 nb_attention_param = 256 attention_init_value = 1.0 / 256 nb_hidden_units = 512 # number of hidden layer units dropout_rate = 0.5 nb_lstm_cells = 128 nb_classes = 7 frame_size = 0.025 # 25 msec segments step = 0.01 # 10 msec time step
# new_user() # show_global_para() # run_pdf() # read_calib_file_new() # check_latest_scan_id(init_guess=60000, search_size=100) ################################### def load_xanes_ref(*arg): """ load reference spectrum, use it as: ref = load_xanes_ref(Ni, Ni2, Ni3) each spectrum is two-column array, con...
# Problem: https://docs.google.com/document/d/1D-3t64PnsEpcF6kKz5ZaquoMMB-r5UyYGyZzM4hjyi0/edit?usp=sharing def create_dict(): ''' Create a dictionary including the roles and their damages. ''' n = int(input('Enter the number of your party members: ')) party = {} # initialize a dictionary named p...
class Solution: def kthGrammar(self, n: int, k: int) -> int: if n == 1: return 0 noOfBits = (2 ** (n-1) ) / 2 if k <= noOfBits: return self.kthGrammar(n-1, k) else: return int (not self.kthGrammar(n-1, k - noOfBits))
#!/usr/bin/env python3 def execute(): with open('input.12.txt') as inp: lines = inp.readlines() return sum_plant_position([l.strip() for l in lines if len(l.strip()) > 0], 20) def sum_plant_position(program, generations): state = '...' + program[0][len('initial state: '):] + '...' offset = -3 ...
# Testing def print_hi(name): print(f'Hi, {name}') # Spewcialized max function # arr = [2, 5, 6, 1, 7, 4] def my_bad_max(a_list): temp_max = 0 counter = 0 for index, num in enumerate(a_list): for other_num in a_list[0:index]: counter = counter + 1 value = num - other_n...
""" # Definition for a QuadTree node. class Node: def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight): self.val = val self.isLeaf = isLeaf self.topLeft = topLeft self.topRight = topRight self.bottomLeft = bottomLeft self.bottomRight = bottomRig...
class ForthException(Exception): def __init__(self, msg): self.msg = msg def __str__(self): return self.msg class CompileException(ForthException): pass
print('Super gerado de PA') print('-=' * 15) primeiro = int(input('Digite o termo: ')) razao = int(input('Digite a razão: ')) c = 1 opçao = '' termo = primeiro total = 0 mais = 10 while mais != 0: total = total + mais while c <= total: print(termo, '→', end=' ') termo += razao c += 1 ...
detik_input = int(input()) jam = detik_input // 3600 detik_input -= jam * 3600 menit = detik_input // 60 detik_input -= menit * 60 detik = detik_input print(jam) print(menit) print(detik)