content
stringlengths
7
1.05M
#!/usr/bin/python3 #___________________________________________________________________ #config for boot- and shutdown-logo oledBootLogo = "volumio_logo.ppm" oledShutdownLogo = "shutdown.ppm" #___________________________________________________________________ok #config for Clock/Standby: oledtext03 = 59, 4 #cl...
class AssignWorkers: def __init__(self, test_cases, n_workers): """ Assign workers, check that task required is good. Arguments: ----- `test_cases`: df containing all test cases scenario `n_workers`: number of workers required. """ self.test_cases = t...
# Author: Harsh Goyal # Date: 20-04-2020 def generate_crud(table_name, attributes): file = open('crud_{}.py'.format(table_name), 'w') attr_list = attributes.split(",") attributes_str = "" for i in attr_list: attributes_str += i attributes_str += ',' attributes_str = attributes_str[...
# https://leetcode.com/problems/reverse-nodes-in-k-group/description/ # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def reverseKGroup(self, head, k): if head is None or k < 2: ...
# "Sell All the Cars" # Alec Dewulf # April Long 2020 # Difficulty: Simple # Concepts: Greedy """ EXPLANATION The only thing really to figure out was that it is better to sell the most profitable cars first. All the cars lose one off of their values until they are sold or are valued at zero so selling the most valua...
""" Watch over a stream of numbers, incrementally learning their median. Implemented via nested lists. New numbers are added to `lst[i]` and when it fills up, it posts its median to `lst[i+1]`. Wen `lst[i+1]` fills up, it posts the medians of its medians to `lst[i+2]`. Etc. When a remedian is queried for the current m...
def pytest_addoption(parser): parser.addoption( "--skip-integration", action="store_true", dest="skip_integration", default=False, help="skip integration tests", ) def pytest_configure(config): config.addinivalue_line("markers", "integration: mark integration tests"...
class NoJsExtensionFound(Exception): pass class InvalidRegistry(Exception): pass
""" https://leetcode.com/problems/reverse-words-in-a-string/ """ class Solution: def reverseWords(self, s: str) -> str: s = s.strip() while " " in s: s = s.replace(" ", " ") return " ".join(s.split(" ")[::-1])
delete_groups_query = ''' mutation deleteGroups($groupPks: [Int!]!) { deleteGroups(input: {groupPks: $groupPks}) { succeeded failed { groupPk message code } error { message code ...
'c' == "c" # character 'text' == "text" ' " ' " ' " '\x20' == ' ' 'unicode string' '\u05d0' # unicode literal
n = int(input()) arr = list(map(int, input().split())) res = "Yes" for i in range(n): if i == 0: continue if sorted(arr)[i] != sorted(arr)[i - 1] + 1: res = "No" break print(res)
class Employee(): count = 0 def __init__(self,name,salary): self.name = name self.salary = salary Employee.count += 1 def to_string(self): return 'Name: {}\nSalary: {}'.format(self.name,self.salary) #Driver code emp1 = Employee('Birju',21100) emp2 = Employee('Harsh',25200) ...
# Gravitational constant (m3/kg.s2) G = 6.67408e-11 # ASTROPHYSICAL DATA OF CELESTIAL BODIES # Sources: International Astronomical Union Resolution B3; NASA Planetary Fact Sheet; JPL Planets and Pluto: Physical Characteristics; JPL Technical Document D-32296 Lunar Constants and Models Document # Masses (kg) dict_M = ...
a,b,c=[int(i) for i in input().split()] hangshu = c list=[] for i in range(hangshu): # list.append([int(i) for i in input().split()]) list.extend([int(i) for i in input().split()]) print(list)
class NoDataError(Exception): pass class InvalidModeError(Exception): pass
class Solution: def invertTree(self): if root: tmp = root.left root.left = self.invertTree(root.right) root.right = self.invertTree(tmp) return root
""" Model Configurations """ TASK3_A = { "name": "TASK3_A", "token_type": "word", "batch_train": 64, "batch_eval": 64, "epochs": 50, "embeddings_file": "ntua_twitter_affect_310", "embed_dim": 310, "embed_finetune": False, "embed_noise": 0.05, "embed_dropout": 0.1, "encode...
# 超参数 class Hyperparams: batch_size = 32 # alias = N lr = 0.0001 # learning rate. In paper, learning rate is adjusted to the global step. logdir = 'log' # log directory # model maxlen = 100 # Maximum number of words in a sentence. alias = T. num_blocks = 6 # number of encoder/decoder block...
# BSD 2-Clause License # # Copyright (c) 2021-2022, Hewlett Packard Enterprise # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright...
#1.1 class Person: """ Class handle with instances that includes personal data of persons """ def __init__(self, full_name = "", birth_year = None): """ Defines two parameters for Person class instances. Validate parameters value. :param full_name: Full Name of the Person should consists...
def toStr(n,base): digits = '01234567890ABCDEF' if n < base: return digits[n] return toStr(n // base,base) + digits[n % base] print("9145 in hex is ", toStr(9145,16))
#training parameters TRAIN_GPU_ID = 0 TEST_GPU_ID = 0 BATCH_SIZE = 200 VAL_BATCH_SIZE = 200 PRINT_INTERVAL = 100 VALIDATE_INTERVAL = 5000 MAX_ITERATIONS = 100000 RESTORE_ITER = 0 # iteration to restore. *.solverstate file is needed! # what data to use for training TRAIN_DATA_SPLITS = 'train' # what data to use for the...
"""Kata: Friend or foe. Make a program that filters a list of strings and returns a list with only your friends name in it. If a name has exactly 4 letters in it, you can be sure that it has to be a friend of yours! Otherwise, you can be sure he's not... - **URL**: [challenge url](https://www.codewars.com/kata/frien...
# -*- coding: utf-8 -*- def main(): n, k = map(int, input().split()) a = sorted(list(map(int, input().split())), reverse=True) total = 0 for key, ai in enumerate(a, 1): total += ai if total >= k: print(key) exit() print(-1) if __name__...
azure_credentials_schema = { "$id": "http://azure-ml.com/schemas/azure_credentials.json", "$schema": "http://json-schema.org/schema", "title": "azure_credentials", "description": "JSON specification for your azure credentials", "type": "object", "required": ["clientId", "clientSecret", "subscrip...
# Write a program that reads an integer and outputs its last digit. # print(int(input()) % 10) # another solution print(input()[-1]) # another solution print(input()[-1])
print('uPy 2') print('a long string that is not interned 2') print('a string that has unicode αβγ chars 2') print(b'bytes 1234\x01 2') print(1234567892) for i in range(5): print(i)
'''Implement a program to calculate number of digits in the given number Input Format a number from the user Constraints n>0 Output Format print number of digits in the number Sample Input 0 124 Sample Output 0 3 Sample Input 1 6789 Sample Output 1 4''' #solution n = input() print(len(n))
num = int(input("Ievadiet pozitīvu skaitli: ")) if num > 1: for i in range(2, int(num**0.5)+1): if num % i == 0: print(num, "- nav pirmskaitlis") print("jo dalās ar", i) break else: print(num, "- ir pirmskaitlis") else: print(num, "- nav pirmskaitlis")
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Ben Thomasson' __email__ = 'ben.thomasson@gmail.com' __version__ = '0.1.0'
# data= ['pran',20,10, (2022,12,13)] # # name,age,price,date = data # print(name) # print(price) # print(age) # print(date) # name='bella' # a,b,c,d,e=name # print(a,b,c,d,e) # print(a) # print(b) # print(c) # print(b) # print(e) bio=['tuna',18,'sgc', 'samsungA12',(1,2,2004)] name,age,collegename,phonenmae,birthdate...
'''Exercício Python 072: Crie um programa que tenha uma dupla totalmente preenchida com uma contagem por extenso, de zero até vinte. Seu programa deverá ler um número pelo teclado (entre 0 e 20) e mostrá-lo por extenso. ''' #criar a tupla, com os números por extenso num = ('zero', 'hum', 'dois', 'três', 'quatro'...
lista = list() for c in range(1, 6): lista.append(int(input('Digite Um Numero: '))) print(f'\nO Menor valor Foi {min(lista)} Na {lista.index(min(lista)) + 1}ª Posição') print(f'O Maior valor Foi {max(lista)} Na {lista.index(max(lista)) + 1}ª Posição')
""" 538. Convert BST to Greater Tree Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST. Example: Input: The root of a Binary Search Tree like this: 5 ...
def mul(a, b): r = [[0, 0], [0, 0]] r[0][0] = a[0][0] * b[0][0] + a[0][1] * b[1][0]; r[0][1] = a[0][0] * b[0][1] + a[0][1] * b[1][1]; r[1][0] = a[1][0] * b[0][0] + a[1][1] * b[1][0]; r[1][1] = a[1][0] * b[0][1] + a[1][1] * b[1][1]; return r; def _fib(n): if n == 0: return [[1, 0], [0, 1]] if n == 1...
""" Coalesce multiple identical call into one, preventing thundering-herd/stampede to database/other backends python port of https://github.com/golang/groupcache/blob/master/singleflight/singleflight.go This module **does not** provide caching mechanism. Rather, this module can used behind a caching abstraction ...
class base(object): def __init__ (self, T, N, lam): self.T = T self.N = N self.lam = lam def compute(self, S, A0, status_f, history, test_check_f): pass def __call__(self, S): return self.compute(S, None, None, False, None)[0] def compute_full(self, S, status_f...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: if not root: r...
matriz = [[0,0,0],[0,0,0],[0,0,0]] valor = int par = 0 coluna2 = 0 valormax= 0 for l in range(0,3): for c in range(0,3): valor = int(input(f'Digite um valor para posição [{l + 1},{c + 1}] da matriz: ')) matriz[l][c] = valor if valor % 2 == 0: par += valor if c == 1: ...
class Pessoa: olhos = 2 # este é um atributo default, se criarmos o olhos=2 dentro do __init__ junto com os demais atributos, o # python vai alocar um espaço em memória olhos=2 para cada pessoa criada no jogo, com o atributo default o python # cria apenas 1 espaço em memória para este atributo. def __in...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- MONGO_URL='localhost' MONGO_DB='meizitu' MONGO_TABLE='meizitu'
welcome = 'This bot will help you to find available slots in Zakaz.ua try to put ' \ '"start" to start monitoring or "stop" to stop it.' error_command = '🤦 Bot doesn\'t support this command, try use menu.' error_add_new = '🔐 There is no slots for adding new store, try to change exiting slots.' error_chang...
"""Constants for the Neerslag Sensor (Buienalarm / Buienradar) integration.""" DOMAIN = "neerslag" FRONTEND_SCRIPT_URL = "/neerslag-card.js" DATA_EXTRA_MODULE_URL = 'frontend_extra_module_url'
''' Add conditionals 100xp The while loop that corrects the offset is a good start, but what if offset is negative? You can try to run the sample code on the right where offset is initialized to -6, but your sessions will be disconnected. The while loop will never stop running, because offset will be further decreased ...
# -*- coding: utf-8 -*- """ Created on 08/10/2019 at 17:30 @author: Alfie Bowman """ def get_digit(n, l=None, r=None): """ Finds the `d`-th digit from the left or the `d`-th from the right, depending on how variables are called: - Returns the `d`-th digit of `n` from the left if the function was called ...
def BinaryTree(r): return [r, [], []] def insertLeft(root, newBranch): t = root.pop(1) if len(t) > 1: root.insert(1, [newBranch, t, []]) else: root.insert(1, [newBranch, [], []]) return root def insertRight(root, newBranch): t = root.pop(2) if len(t) > 1: root.in...
# Find larger of two nums a = int(input('First Number: ')) b = int(input('Second Number: ')) # if-elif-else conditional if a > b: print(a, 'is greater than', b) elif a == b: print(a, 'is equal to', b) else: print(a, 'is less than', b)
# Request websites to minimize non-essential animations and motion. c.content.prefers_reduced_motion = True # Don't send any DoNotTrack headers; they're pointless. c.content.headers.do_not_track = None # Allow JavaScript to read from or write to the clipboard. c.content.javascript.can_access_clipboard = True # Draw ...
class BedwarsProException(Exception): """Base exception. This can be used to catch all errors from this library """ class APIError(BedwarsProException): """ Raised for errors """ def __init__(self, message): self.text = message super().__init__(self.text)
def calculate_investment_value(initial_value, percentage, years): result = initial_value * (1 + percentage / 100) ** years return result
class BadRowKeyError(Exception): pass class EmptyColumnError(Exception): pass
""" 格式: 缓存: { } """ ENGINS = { "memcache": { "class": "client.memcache.MemcacheClient", "config": { "servers": [ "127.0.0.1:11211", ], "default_timeout": 600, "debug": False, } }, "redis": { "class": "client.red...
# Due to https://github.com/bazelbuild/bazel/issues/2757 # Consumers have to specify all of the transitive dependencies recursively which is not a very nice UX and pretty error # prone, this defines a function which declares all the spectator dependencies so that any Bazel project needing to # depend on spectator can j...
# print(123456) # print('Kaic', 'Pierre', 'Outra Coisa') # print('Kaic', 'Pierre', sep='-', end='') # print('Testando', 'Outras', 'Coisas', sep='-', end='') print('428', '330', '048', sep='.', end='-') print('93')
sym_text = '''Symbol|Security Name|Market Category|Test Issue|Financial Status|Round Lot Size AAIT|iShares MSCI All Country Asia Information Technology Index Fund|G|N|N|100 AAL|American Airlines Group, Inc. - Common Stock|Q|N|N|100 AAME|Atlantic American Corporation - Common Stock|G|N|N|100 AAOI|Applied Optoelectronics...
''' 86-Crie um programa que crie uma matriz de 3X3 e preencha os valores lidos pelo teclado. ______________ |____|____|___| |____|____|___| |____|____|___| No final mostre a matriz na tela com a formatação correta. ''' matriz=[[0,0,0],[0,0,0],[0,0,0]] for linha in range(0,3): for coluna in range(0,3): ma...
"""Utility functions and constants necessary for Flowdec <--> PSFGenerator validation and comparison""" # Configuration example taken from http://bigwww.epfl.ch/algorithms/psfgenerator/ DEFAULT_PSF_CONFIG = """ PSF-shortname=GL ResLateral=100.0 ResAxial=250.0 NY=256 NX=256 NZ=65 Type=32-bits NA=1.4 LUT=Fire Lambda=610...
class Solution: def minCostClimbingStairs(self, cost): """ :type cost: List[int] :rtype: int """ dp = [0] * len(cost) for i in range(2, len(cost)): dp[i] = min(cost[i - 1] + dp[i - 1], cost[i - 2] + dp[i - 2]) ans = min(cost[- 1] + dp[- 1], cost[-2...
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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 law or agreed ...
class Solution: def isPossible(self, nums): """ :type nums: List[int] :rtype: bool """ # # greedy algorithm left = collections.Counter(nums) end = collections.Counter() for num in nums: if not left[num]: continue ...
print("copie des listes : slicing") liste = [1,6,60] sousliste = liste[0:2] print("liste : ", liste) print("sousliste : ", sousliste) tuple = (1,6,60,0) soustuple = tuple[0:2] print("tuple : ", tuple) print("soustuple : ", soustuple) liste = range(5,100,10) print("liste[0] : ", liste[0]) print("liste[-1] : ", liste[-1]...
# Given a string and a list of words, find all the starting indices of substrings in the given string that are a concatenation of all the given words exactly once without any overlapping of words. It is given that all words are of the same length. # Example 1: # Input: String = "catfoxcat", Words = ["cat", "fox"] # O...
#J row=0 while row<6: col =1 while col<7: if (col==3 or row==0 ) or (row==4 and col==1)or (row==5 and col==2): print("*",end=" ") else: print(" ",end=" ") col +=1 row +=1
"""Blizzard API Constants""" "Region to use when fetching game data" BLIZZARD_REGION = 'us' "Locale to use when fetching" BLIZZARD_LOCALE = 'en_US'
'''Pygame Drawing algorithms written in Python. (Work in Progress) Implement Pygame's Drawing Algorithms in a Python version for testing and debugging. ''' # FIXME : the import of the builtin math module is broken, even with : # from __future__ import relative_imports # from math import floor, ceil, trunc # H E L P...
mes = ['janeiro', 'fevereiro', 'março', 'aril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro', 'novembro', 'dezembro'] desejado = int(input('Digite o numero de mes desejado: ')) if desejado <= 12: print(f'Voce escolheu o mes {mes[desejado]}') else: print('mes invalido')
class Solution: def rob(self, nums): rob, not_rob = 0, 0 for num in nums: rob, not_rob = not_rob + num, max(rob, not_rob) return max(rob, not_rob)
MISS_POSITION = 'miss position' OUT_OF_RANGE = 'out of range' TIME_OVER = 'time over' OUTPUT_ERROR = 'output error' RUNTIME_ERROR = 'runtime error' TYPE_ERROR = 'not correct type' GAME_ERROR = 'game error' SERVER_ERROR = 'server error'
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ n=input() k=len(n)-1 r=k*9+int(n[0])-1 n=str(int(n)-int(str(int(n[0])-1)+'9'*k)) for x in n:r+=int(x) print(r)
def arevaluesthesame(value1, value2, relative_tolerance, abs_tol=0.0): # Use math.isclose algorithm, it is better than numpy.isclose method. # See https://github.com/numpy/numpy/issues/10161 for more on the discussion # Since some python version don't come with math.isclose we implement it here directly ...
N = int(input('Número de pessoas: ')) v = [] soma = 0 for i in range(N): v.append(float(input(f'Renda da pessoa {i+1}: '))) soma += v[i] media = soma / N for i in range(N): for j in range(N-1): if v[j] > v[j+1]: temp = v[j] v[j] = v[j+1] v[j+1] = temp if N % 2 == ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Dec 31 15:45:48 2019 @author: descentis """
def insert(connection, transaction_id, item_id, item_price, transaction_amount): if not isinstance(item_price, float) or item_price < 0: raise TypeError("Argument 'transaction_id' must be a non-negative integer!") if not isinstance(transaction_amount, int) or transaction_amount < 0: raise TypeEr...
# Copyright 2017 The Bazel Authors. All rights reserved. # # 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 la...
'''instrução break e os loopings infinitos a favor das nossas estratégias de código e fstrings do Python.''' n = s = 0 while True: n = int(input('Escreva um numero [Digite 999 para somar]: ')) if n == 999: break s += n print('A soma vale {}'.format(s)) #===================== Exemplo usando fstrin...
''' Pattern: Enter number of rows: 5 1 12 123 1234 12345 1234 123 12 1 ''' print('Number of patterns: ') number_rows=int(input('Enter number of rows: ')) #upper part of the pattern for row in range(1,number_rows+1): for column in range(1,row+1): print('%-2d'%column,end='') print() #lowe part ...
{ '1': 'Identity', '2': "Narrator's responses", '2.1': 'Terror and Madness Trailer', '2.2': 'Intro cinematic', '2.3': 'Tutorial lines', '2.3.1': 'Entering a building for the first time', '2.4': 'Entering the hamlet', '2.5': 'Upgrading buildings', '2.6': 'Recruiting heroes', '2.7': 'Dismissing a hero...
file=open("demo.txt",'r') # we ave to done something with file content=file.read() print(content) # content1=file.read(10) # print(content1) # content2=file.readlines() # print(content2) # file.close() # file.write("This is a python programm") # file.close() # file=open("demo.txt",'a') # file.write("\nthis is new ...
''' <클래스의 구성 > class class_name: 펑션의 모임이 클래스 def __init__(self): 초기화 펑션, 셀프라는 파라메터는 클래스 내부에서만 사용가능 최소한의 펑션은 공유하자 라고하는게 셀프 컴퓨터는 메모리만 쳐다본다. 클래스도 부르지않으면 동작 안한다. 불러서 메모리에 올리는것을 인스턴스라한다 인스턴스 할 때 클래스를 초기화한다. 원래룰을 어기지...
#!/usr/bin/env python """ WorkQueue_t.DataStructs_t """ __all__ = []
teste = [] teste.append('Mauro') teste.append(22) galera = [] galera.append(teste[:]) # comando copiar teste[0] = 'Ximas' teste[1] = 23 galera.append(teste[:]) # galera vai receber uma copia do teste print(galera) print('-=' * 30) #---------------------------------------------------------------------------------------...
mod = 10**9 + 7 n = int(input()) include_none = 1 include_or = 0 include_and = 0 for _ in range(n): include_and = include_and*10 + include_or include_or = include_or*9 + include_none*2 include_none = include_none * 8 include_and %= mod include_or %= mod include_none %= mod print(include_and)
def pipeline_success(account,execution_id,pipeline,region, pipeline_id): tmp = "arn:aws:codepipeline:{0}:{1}:{2}".format(region, account,pipeline) arn =[tmp] chamada_api = [] chamada_api.append({"account": account, "region": region, "detail": {"execution-id": execution_id, "pipeline": pipeline, "re...
# # Copyright (C) 2017 The Android Open Source Project # # 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 la...
# We will learn to create parameterized constructor class Employee: ''' This is the version 2.0 of Employee class''' def __init__(self,name,org,salary): super().__init__() self.name = name self.organisation = org self.salary = salary def __str__(self): return 'T...
class Inversor: def __init__(self,resultado): self.resultado=resultado def dump(self): return{ 'resutlado' : self.resultado }
# https://atcoder.jp/contests/math-and-algorithm/tasks/abc075_d n, k = map(int, input().split()) xx = [0] * n yy = [0] * n for i in range(n): xx[i], yy[i] = map(int, input().split()) mins = float('inf') for x0 in xx: for x1 in xx: if x0 == x1: continue for y0 in yy: for...
entradas=input("") (a,b)=entradas.split(" ") a=int(a) b=int(b) print("entrada 1", a) print("entrada 2", b)
_end = '\x1b[0m' _grey = '\x1b[90m' _red = '\x1b[91m' _green = '\x1b[92m' # Runtime messages def printm(m: str): print(f'{_grey}[{_green}+{_grey}]{_end} {m}') # Runtime error def printe(e: str): print(f'{_grey}[{_red}!{_grey}]{_end} {e}') # Exceptions def printx(x: Exception): print(f'{_grey}[{_red}...
class LinkedList: def __init__(self): self.head = None class Node: def __init__(self, data): self.data = data self.next = None def __repr__(self): return self.data class LinkedList: def __init__(self): self.head = None def reverseLL(self): prev = N...
# Time: O(n) # Space: O(h) try: xrange # Python 2 except NameError: xrange = range # Python 3 class Solution(object): def averageOfLevels(self, root): """ :type root: TreeNode :rtype: List[float] """ result = [] q = [root] while q: ...
""" ## Frame Exploring the frame class. """ gdb.execute('file call_graph_py.out', to_string=True) gdb.execute('set confirm off') gdb.execute('rbreak .', to_string=True) gdb.execute('start', to_string=True) thread = gdb.inferiors()[0].threads()[0] while thread.is_valid(): print() frame = gdb.selected_frame() ...
# SRC: https://www.hackerrank.com/challenges/the-minion-game/problem # Functions def substring_count(string, sub): count = start = 0 while True: start = string.find(sub, start) + 1 if start > 0: count += 1 else: return count def get_player_score(string, player...
#Understand How to Convert DataType and what is function of type in python birth_year=input("Birth Year: ") print(type(birth_year)) age=2019-int(birth_year) print(type(age)) print("YOUR AGE:") print(age) #ASK A USER TO THEIR WEIGHT(IN POUNDS),CONVERT IT TO KILOGRAMS AND PRINT ON THE TERMINAL. weight=input("Ente...
class Person: def __init__(self, name): # En esta asignación, realmente estamos llamando al setter de más abajo self.name = name @property # <1> def name(self): return self._name @name.setter # <2> def name(self, value): self._name = value # Mediante el de...
def read_input(input_file): with open(input_file, "r") as f: return [i for i in f.readlines()] def parse_input(input_file: str) -> dict: data = read_input(input_file) return _build_data_dict(data) def _build_data_dict(data): data_dict = {} for line in data: line = line.replace("...
def create_md(filename,session,speaker): first_line = "# " + session + " - " + speaker rest = "## Notes \n \n \n" + "## Key Takeaways \n \n \n" + "## Other Details / Follow Up \n \n \n" full_file = first_line + "\n \n" + rest f = open(filename, "w+") f.write(full_file) f.close() # create_md("foo_bar.md", ...
# 문제: https://www.acmicpc.net/problem/15786 # 풀이: 루프 돌며 알고 있는 단어의 문자들이 순서대로 위치한 단어인지 확인 n, m = map(int, input().split()) original = input() post_it = [input() for _ in range(m)] for s in post_it: org_idx = 0 for c in s: if original[org_idx] == c: org_idx += 1 if org_idx >= n: ...
print("Hello World") print ("Ansar") print ("Ansar Ahmad") print ("Hi,I am Python.") print ("25") print ("2*2") print ("2","+","5","+","9") print ("2","+","2","+","9") print ("Hello,","I","am","Ansar") print ("Ansar","is","20","years","old") print ("Hello Ansar,"+"How are you?") print ("I am 20 years old"+"a...