content
stringlengths
7
1.05M
def pair(relation, human_readable = None): ''' Creates a dictionary pair of a relation uri in string form and a human readable equivalent. Args: relation (str): This should be preformated so generate_uri works on it human_readable (str): a plain-text description of the uri Return: ...
# coding: utf-8 # Copyright 2020. ThingsBoard # # # 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 # # # Unl...
class InvalidTimeRangeError(Exception): """Error for invalid time ranges.""" def __init__(self, start, stop): msg = 'Start time {} exceeds stop time {}'.format( start.isoformat(), stop.isoformat() ) super(InvalidTimeRangeError, self).__init__(msg) class UnknownC...
# Number letter counts # Problem 17 # If the numbers 1 to 5 are written out in words: one, two, three, # four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in # total. # # If all the numbers from 1 to 1000 (one thousand) inclusive were # written out in words, how many letters would be used? # # # NOTE: Do n...
num = 10 num = 22 a= 2 def main(): pass if __name__ == '__main__': main() b = 3 aa = 33 ss = 334
def has_attachment(ctx): return bool(len(ctx.message.attachments)) def has_embed(ctx): return bool(len(ctx.message.embeds)) def file_type(ctx, filetype, attnum = 0): if not has_attachment(ctx): return False return ctx.message.attachments[attnum].endswith(filetype)
class ARANGODB: """ Arango DB configuration """ URL = 'http://arangodb:8529' USER = 'root' PASSWORD = '' DB_NAME = 'thesis'
'''Refaça o desafio 009, mostrando a tabuada de um número que o usuário escoher, só que agora utilizando um laço for. ''' n2 = 0 n1 = int(input('Digite uma número e veja sua tabuada de 0 a 10: ')) for n in range(0, 11): resultado = n1 * n2 print(f'{n1} x {n2} = {resultado}') n2 += 1
#!/usr/bin/python3.6 # created by cicek on 26.07.2018 22:25 def myFunc(): print("hello") myFunc() # You must define functions before they are called, in the same way that you must assign variables before using them def function(variable): variable += 1 print(variable) function(7) # print(variable) # Name...
# Every two consecutive numbers add up to 1 n = int(input()) if n % 2 == 0: print(n // 2) else: print(n // 2 + -n)
def xor_2_bytes(input1,input2): xor_bytes = b'' for b1, b2 in zip(input1, input2): xor_bytes += (bytes([b1 ^ b2])) print(xor_bytes) return xor_bytes.hex() if __name__ == "__main__": byte_string1 = bytes.fromhex('1c0111001f010100061a024b53535009181c') byte_string2 = bytes.fromhex('686974207468652062756c6c27732...
# converting vehicle age to inter def process_vehicule_age(df): ds = df.copy() ds["Vehicle_Age"] = ds["Vehicle_Age"].map( lambda x: 0 if x == "< 1 Year" else 1 if x == "1-2 Year" else 2 ) ds["Vehicle_Age"] = ds["Vehicle_Age"].astype("int") return ds # changing the column type for differe...
""" Python client for Mantis connect SOAP API """ __version__ = '0.4.0' __author__ = 'Ji Haijun' __module_name__ = 'mantisconnect2' __license__ = 'MIT'
class Solution: def lengthOfLastWord(self, s: str) -> int: p, length = len(s) - 1, 0 while p >= 0: if s[p] != ' ': length += 1 else: if length > 0: return length p -= 1 return length
""" Created on 18 Feb 2019 @author: Frank Ypma """ class FlowFile(object): """" Mock object for a nifi message, containing flowfile content and a dict of attributes For now, only string content is accepted, but that could be expanded """ def __init__(self, content="", attributes=None): a...
#!/usr/bin/python3 # author: Karel Fiala # email: fiala.karel@gmail.com # config SERVER_IP = "0.0.0.0" SERVER_PORT = 5556 CLIENT_LISTEN_IP = "dev.haut.local" CLIENT_LISTEN_PORT = 5555 BUFFER_SIZE = 1024 WEBSERVER_IP_BIND = "0.0.0.0" WEBSERVER_PORT_BIND = 5557
while True: try: entrada = int(input()) print('Y' if entrada % 6 == 0 else 'N') except: break
class Params(object): """ Unified Parameter Object for passing arguments among APIs from the algorithm frame (e.g., client_trainer.py and server aggregator.py). Usage:: >> my_params = Params() >> # add parameter >> my_params.add(name="w", param=model_weights) >> ...
# Created by Hansi at 2/14/2020 def calculate_recall(tp, n): """ :param tp: int Number of True Positives :param n: int Number of total instances :return: float Recall """ if n == 0: return 0 return tp / n def calculate_precision(tp, fp): """ :param ...
def once(function): function_has_been_called = False def wrapper(*args, **kwargs): if not function_has_been_called: function_has_been_called = True return wrapper(*args, **kwargs) return wrapper
"""This is my module docstring""" 'This is another string that has no runtime effect' b'Bytes literal' 0 1000 def test(): 'Function docstring'
'''2. Write a Python program to create a sequence where the first four members of the sequence are equal to one, and each successive term of the sequence is equal to the sum of the four previous ones. Find the Nth member of the sequence.''' num = int(input("Enter the number of terms: "))
## AUTHOR: Vamsi Krishna Reddy Satti ################################################################################## # Optimizers ################################################################################## class SGD: def __init__(self, model, lr): self.model = model self.lr = lr de...
if sm.hasQuest(2566): if sm.hasItem(4032985): sm.chatScript("You already have the Ignition Device.") else: sm.giveItem(4032985) sm.chatScript("Ignition Device. Bring ")
''' Created on June 13, 2018 @author: David Stocker ''' #classes class EmptyFileError(ValueError): '''File contains no data ''' pass class UndefinedPersistenceError(ValueError): ''' No persistence has been defined ''' pass class PersistenceQueryError(ValueError): ''' Invalid...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat May 23 17:11:21 2020 @author: ahmad """ for i in range(0, 10): storage = "" for x in range(0, i + 1): storage += "*" print(storage) # storage += "*" => storage = storage + "*" print("/////////////////////////") for i in r...
dia = input ('Dia') mes = input ('Mês') ano = input ('Ano') print ('Você nasceu no dia ', dia, ' de ', mes, ' de ', ano, '. Correto?')
my_fonts = { # 'larger': ('freesansbold.ttf', 27), # 'xl': ('freesansbold.ttf', 35), # 'display_font': ('freesansbold.ttf', 22), # 'basic': ('freesansbold.ttf', 16), # 'medium': ('freesansbold.ttf', 21), # /!\ on avait cette font partout: 'monogram.ttf' # -multiples de 16 fortement recomm...
# http://www.codewars.com/kata/554b4ac871d6813a03000035/ def high_and_low(numbers): lst = [int(num) for num in numbers.split()] return "{0} {1}".format(max(lst), min(lst))
""" For details of problem statement visit: https://www.hackerrank.com/rest/contests/master/challenges/the-minion-game/download_pdf?language=English """ def minion_game(s): # your code goes here i = len(s) t = 0 k = 0 for x in range(i): if s[x] == "A" or s[x] == "E" or s[x] == "I" or s[x...
# Coding Challenge 2 ### Chelsea Lizardo ### NRS 528 # # string = 'hi dee hi how are you mr dee' #Count the occurrence of each word, and print the word plus the count. def word_count(str): counts = dict() words = str.split() for w in words: if w in counts: counts[w] += 1 ...
def xo(s): xcount = 0 ocount = 0 for i in s.lower(): if (i == 'x'): xcount += 1 elif (i == 'o'): ocount += 1 return xcount == ocount print(xo('ooxx')) # Using count() def xo2(s): s = s.lower() return s.count('x') == s.count('o')
def print_formatted(number): width = len(str(bin(number)))-2 for num in range(1, number+1): decimal = int(num) octal = oct(num) hexadecimal = hex(num) binary = bin(num) print(str(decimal).rjust(width), octal[2:].rjust( width), hexadecimal[2:].title().rjust(wid...
# # PySNMP MIB module Nortel-Magellan-Passport-CallRedirectionMIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-CallRedirectionMIB # Produced by pysmi-0.3.4 at Wed May 1 14:26:41 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by use...
def make_adder(x): def adder(y): return x + y return adder inc = make_adder(1) plus10 = make_adder(10) ___assertEqual(inc(1), 2) ___assertEqual(plus10(-2), 8)
class Solution: def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]: if x == 1: i_max = 0 else: i_max = int(math.log(bound,x)) if y == 1: j_max = 0 else: j_max = int(math.log(bound,y)) res =...
# coding=utf-8 # # list 和 tuple # # Created by Jason Pan on 2021-01-01 20:52:48 # Copyright © 2021 Jason Pan. All rights reserved. # if __name__ == '__main__': # list是一种有序的集合,可以随时添加和删除其中的元素 classmates = ["Michael", "Bob", "Tracy"] print(len(classmates)) # 3 print(classmates) # ["Michael", "Bob", "Tracy"] ...
# Programacion orientada a objetos 1 # https://www.youtube.com/watch?v=lg9p0yWgXYk&list=PLh7JzoyIyU4JVOeKkiNYPkAWBq0Aszxc-&index=2 class Persona: def __init__(self, nombre_persona, calle=1): self.nombre = nombre_persona self.calle = calle def moverse(self, velocidad): self.calle += ...
""" Given an integer array, find three numbers whose product is maximum and output the maximum product. Example 1: Input: [1,2,3] Output: 6 IDEA: track 3 maximum numbers in desc order (max1 is the biggest) and 2 smallest """ class Solution628: pass
# simplified linked list class Node: def __init__ (self, value, next=None): self.value = value self.next = next L = Node('a', Node('b', Node('c', Node('d')))) # print('L', L.value) # print(L.next.next.value)
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def bstToGst(self, root: TreeNode) -> TreeNode: def f(root, val = 0): if root is None: ...
tokens = { "WETH": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", "DAI": "0x6B175474E89094C44Da98b954EedeAC495271d0F", "BAT": "0x0D8775F648430679A709E98d2b0Cb6250d2887EF", "WBTC": "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599", "UNI": "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984", }
# -*- coding: utf-8 -*- casos = int(input()) result = [] for i in range(casos): num1, num2, indice1, indice2 = input().split(" ") num1 = int(num1) num2 = int(num2) indice1 = float(indice1) indice2 = float(indice2) anos = 0 while num1 <= num2: num1 += int(num1*indice1/100) nu...
""" 1. Clarification 2. Possible solutions - Trie - Queue 3. Coding 4. Tests """ # T=O(n), S=O(n) class WordDictionary: def __init__(self): self.root = {} self.end_of_word = '#' def addWord(self, word: str) -> None: node = self.root for char in word: node ...
"""Constants.""" CACHE_NAME = 'infographics' CACHE_TIMEOUT = 3600
if __name__ == '__main__': arr = [] for _ in range(int(input())): name = input() score = float(input()) arr.append([name,score]) arr.sort() first = 100000 second = 100000 for i in range(len(arr)): if (arr[i][1] < first): second = first ...
num = (int(input('Digite o primeiro termo: '))) raz = (int(input('Qual a razão da PA? '))) nt = 0 for pa in range(0, 10): num = num + raz print(num, end= ' > ') print('FIM !')
# Find First and Last Position of Element in Sorted Array class Solution: def binSearch(self, nums, target): length = len(nums) left, right = 0, length - 1 while left <= right: mid = (left + right) // 2 if nums[mid] == target: while mid >= 0 and nums[...
# def find_all_index(text, pattern): # pattern_index = 0 # match = [] # # if pattern is empty, then return all indices # if pattern == '': # for index in range(len(text)): # match.append(index) # return match # for index, charc in enumerate(text): # # check if let...
def mergeSort(list): if len(list) <= 1: return list # Find the middle point and devide it middle = len(list) // 2 left_list = list[:middle] right_list = list[middle:] left_list = mergeSort(left_list) right_list = mergeSort(right_list) return merge(left_list, right_list) ...
class HTTPException(Exception): def __init__(self, request, data): msg = f"HTTP request returned {request.status} status code." self.request = request for k, v in data.items(): setattr(self, k, v) msg += f"\nIn {k}: {v}" return super().__init__(msg) ...
dados = {} dados['Nome'] = str(input('Nome: ')) dados['Nascimento'] = int(input('Ano de nascimento: ')) dados['Carteira'] = int(input('Carteira de trabalho (0 não tem): ')) if dados['Carteira'] != 0: dados['Contratação'] = int(input('Ano de contratação: ')) dados['Salario'] = float(input('Salario: ')) dados['I...
""" Sets(Conjuntos) """ """ Caracteristicas de conjuntos: 1)Não são ordenados. 2)Não aceitam elementos repetidos. 3)São representados por chaves {}, porém não possuem a relação chave->dado. Qual a vantagem de utilizar conjuntos? - Conjuntos apresentam formas otimizadas de realizar funções especificas q...
""" Supplai Version: Generated by python setup.py """ __version__ = "0.4.0"
CARD_VALUES = { '2': 1, '3': 1, '4': 1, '5': 1, '6': 1, '7': 0, '8': 0, '9': 0, '0': -1, '1': -1, 'J': -1, 'Q': -1, 'K': -1, 'A': -1, '*': -1 } DECKS = 8 def main(): count = 0 cards = 0 user_input = True decks_play...
# -*- coding: utf-8 -*- # Author: Arthur Imbert <arthur.imbert.pro@gmail.com> # License: BSD 3 clause """ Unitary tests for bigfish.detection.spot_detection module. """ # TODO test bigfish.detection.detect_spots # TODO test bigfish.detection.local_maximum_detection # TODO test bigfish.detection.spots_thresholding # T...
################### EXERCISE 1 ############################################### # Constants METER_PER_INCH = 0.0254 INCHES_PER_FEET = 12 feet = int(input('Enter the number of feet:')) inches = int(input('Enter the number of inches:')) number_meters = (feet * INCHES_PER_FEET + inches) * METER_PER_INCH print(feet,'feet',...
expected_output = { 'ikev2_session': { 'IPv4':{ 1:{ 'session_id': 3, 'status': 'UP-ACTIVE', 'ike_count': 1, 'child_count': 1, 'tunnel_id': 1, 'local_ip': '1.1.1.1',...
#!/usr/bin/python # -*- coding:UTF-8 -*- # input([prompt]) 函数和 raw_input([prompt]) 函数基本类似,但是 input 可以接收一个Python表达式作为输入,并将运算结果返回 str = input('请输入:') print('您输入的内容为:',str)
#Exercício Python 42: Refaça o DESAFIO 35 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado: #– EQUILÁTERO: todos os lados iguais #– ISÓSCELES: dois lados iguais, um diferente #– ESCALENO: todos os lados diferentes a = int(input('Informe a primeira reta: ')) b = int(input('Informe ...
class Solution: def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]: p1, p2 = len(arr1)-1, len(arr2)-1 carry = 0 result = [] while p1 >= 0 or p2 >= 0 or carry: bit_sum = 0 if p1 >= 0: bit_sum += arr1[p1] p...
""" File: anagram.py Name: Dennis Hsu ---------------------------------- This program recursively finds all the anagram(s) for the word input by user and terminates when the input string matches the EXIT constant defined at line 19 If you correctly implement this program, you should see the number of anagrams for each...
class FourCal: def setdata(self,first,second): self.first=first self.second=second def add(self): result=self.first+self.second return result def mul(self): result=self.first*self.second return result def sub(self): result=self.first-self.se...
# pyre-ignore-all-errors # TODO: Change `pyre-ignore-all-errors` to `pyre-strict` on line 1, so we get # to see all type errors in this file. # TypeVars can also take a "bound" argument. Suppose we have a class hierachy like this: class Pet: name: str def __init__(self, name: str) -> None: self.nam...
def part_1(): file = open('input.txt', 'r') highest_id = 0 for lineWithOptionNewLine in file: line = lineWithOptionNewLine.strip('\n') left = 0 right = 127 for letter in line[:-3]: mid = (left + right) // 2 if letter == "F": right = mi...
"""Add custom options to py.test.""" def pytest_addoption(parser): """Add option to recreate tox environments.""" parser.addoption( "--tox-recreate", action="store_true", default=False, help="Recreate the tox environments for click and toil modes.", ) parser.addopt...
""" Given two strings X and Y, print the shortest string that has both X and Y as subsequences. If multiple shortest supersequence exists, print any one of them. Examples: Input: X = "AGGTAB", Y = "GXTXAYB" Output: "AGXGTXAYB" OR "AGGXTXAYB" OR Any string that represents shortest supersequence of X and Y Input: X ...
fac_no_faction = 0 fac_commoners = 1 fac_outlaws = 2 fac_neutral = 3 fac_player_faction = 4 fac_player_supporters_faction = 5 fac_britain = 6 fac_france = 7 fac_prussia = 8 fac_russia = 9 fac_austria = 10 fac_kingdoms_end = 11 fac_kingdom_6 = 12 fac_kingdom_7 = 13 fac_kingdom_8 = 14 fac_kingdom_9 = 15 fac_kingdom_10 = ...
# -*- coding: utf-8 -*- def main(): one = plus(2,3) print("Hello Python!:"&str(one)) def plus(x,y): return x+y if __name__ == "__main__": main()
ingles=200 frances=170 alemao=185 matricula=120 lingua=str(input('didite o idioma q pretende estudar: ')).upper() semanas=int(input('digite a quantidade de semanas q deseja estudar: ')) if lingua=='INGLÊS' or lingua=='INGLES': print('você vai estudar {} e o valor é {}R$'.format(lingua,(ingles*semanas)+matricula))...
pkgname = "evince" pkgver = "42.1" pkgrel = 0 build_style = "meson" # dvi needs kpathsea, which is in texlive # does anyone actually need dvi? configure_args = [ "-Dintrospection=true", "-Dgtk_doc=false", "-Dcomics=enabled", "-Dps=enabled", "-Ddvi=disabled", ] hostmakedepends = [ "meson", "pkgconf", "gobjec...
def gcd(a, b): if (b == 0): return a else: return gcd(b, a%b) T = input('') for _ in xrange(T): b,a = map(int, raw_input('').split()) print(gcd(a, b))
# -*- coding: utf-8 -*- # # Copyright 2019 SoloKeys Developers # # Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or # http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or # http://opensource.org/licenses/MIT>, at your option. This file may not be # copied, modified, or distribute...
def numberOfSubarrays(nums, k: int): odd_indices = [] for idx, x in enumerate(nums): if x % 2 == 1: odd_indices.append(idx) count_over_odds = 0 for start in range(len(odd_indices) - k + 1): valid_slice = odd_indices[start: start + k] count = 1 head = ...
# Created by Egor Kostan. # GitHub: https://github.com/ikostan # LinkedIn: https://www.linkedin.com/in/egor-kostan/ def share_price(invested: int, changes: list) -> str: """ Calculates, and returns the current price of your share, given the following two arguments: 1. invested(number), the amount ...
SAMPLE_INPUT_FILE = "sample_input_day_20_aoc21.txt" PUZZLE_INPUT_FILE = "puzzle_input_day_20_aoc21.txt" NUM_ENHANCEMENTS = 50 def parse_input(dir_file: str) -> tuple[str, list]: """ Args: dir_file (str): location of .txt file to pull data from Returns: """ alg, im = '', [] with open(d...
#Question Link <https://leetcode.com/problems/trapping-rain-water/> class Solution: def trap(self, height): left, right = 0, len(height) - 1 ans = left_max = right_max = 0 while left < right: if height[left] < height[right]: left_max = max(left_max, height[left]) ...
print('{}Desafio 009{}'.format('=' * 5, '=' * 5)) n = int(input('Digite um número: ')) print('{}Tabuada do {}{}'.format('=' * 5, n, '=' * 5)) print('{} x {:2} = {:2}'.format(n, 1, n*1)) print('{} x {:2} = {}'.format(n, 2, n*2)) print('{} x {:2} = {}'.format(n, 3, n*3)) print('{} x {:2} = {}'.format(n, 4, n*4)) print('{...
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ a=[*open(0)][1].split() print(max(a.count(x)for x in{*a}))
# Project Euler #21: Amicable numbers def sum_of_divisors(n): sd = 1 # 1 is a divisors1 i = 2 i2 = i * i while i2 <= n: if n % i == 0: sd += i + n // i if i2 == n: sd -= i i += 1 i2 = i * i return sd print(sum_of_divisors(220)) print(s...
#!/usr/bin/env python3 #This program will write Hello World ! print("Hello World!")
n = 1 while n != 0: # Este é um exemplo de 'flag', uma condição de parada. n = int(input('Digite um valor: ')) print('Fim')
#!/usr/bin/python3 # -*- coding: utf8 -*- class Round: def __init__(self, x1: int, y1: int, x2: int, y2: int, context, **kwargs): """ This widget allows you to create circles or ovals :param x1: int :param y1: int :param x2: int :param y2: int :param context...
archivo = open("DDSIVClases/archivo.txt", "r") # imprime cada linea del archivo txt for linea in archivo: print(linea) #linea2 = archivo.readline(2) #print(linea2) lineas = archivo.readline()
query = """ SELECT L_SHIPMODE, sum(CASE WHEN O_ORDERPRIORITY='1-URGENT' OR O_ORDERPRIORITY='2-HIGH' THEN 1 ELSE 0 END) AS HIGH_LINE_COUNT, sum(CASE WHEN O_ORDERPRIORITY <> '1-URGENT' AND O_ORDERPRIORITY <> '2-HIGH' THEN 1 ELSE 0 END) AS LOW_LINE_COUNT FROM orders, lineitem WHERE O_ORDERKEY = L_ORDE...
tree_count = 0 with open("input.txt") as file_handler: for n, line in enumerate(file_handler): if n == 0: continue if len(line.strip()) == 0: continue charPos = n*3 if charPos > len(line.strip()): multiples = int(charPos / len(line.strip())) ...
class Solution(object): def minSwapsCouples(self, row): """ :type row: List[int] :rtype: int """ couple_num = (len(row) + 1) / 2 error_index = [] error_num = 0 for i in range(couple_num): i = i * 2 if row[i] < row[i + 1]: ...
class Solution(object): def findMissingRanges(self, nums, lower, upper): """ Find missing ranges by iterating through all nums To account for inclusivity, we add lower -1 and upper +1 to the nums array """ all = [lower -1] + nums + [upper + 1] res = [] for i...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- if __name__ == '__main__': a='test' b='test' # 比较的是两个对象的id,如果两个对象的id相同,这他们相同 print(a is b) #通常用法是判断none print(a is None)
""" FIT1008 Prac 5 Task 1 @purpose reverse.py @author Loh Hao Bin 25461257, Derwinn Ee 25216384 @modified 20140823 @created 20140821 """ def reverse(): """ @purpose: To read in a size n, then input a list of size n, then prints out in reverse order @param: none @complexity: O(N) where N is ...
ans = [] while True: try: s = s = [int(x) for x in input().split()] except EOFError: break tmp = s[0] % (2 ** s[1]) if tmp: ans.append("可惡!!算了這麼久{}竟然無法被2的{}次整除".format(s[0], s[1])) else: ans.append("YA!!終於算出{}可被2的{}次整除了!!".format(s[0], s[1])) print('\n'.join(ans))
""" Exception definitions for kastore. """ class KastoreException(Exception): """ Parent class of all Kastore specific exceptions. """ class FileFormatError(KastoreException): """ The provided file was not in the expected format. """ class StoreClosedError(KastoreException): """ Th...
class subtitle: """ Digests a YouTube subtitle file. """ def __init__(self, file): try: f = open(file, "r") self._file = f except IOError: raise Exception("Cannot open subtitle file.") def get_all_text(self): """ Parses the f...
""" Check that connecting from a non-local IP will result in an AddressBindingError """ #pragma repy localip = getmyip() localport = 12345 remoteport = 80 timeout = 0.00001 try: remoteip = gethostbyname('www.google.com') except NetworkAddressError: log("Name lookup failed for www.google.com",'\n') exitall() try...
#file = open('sample.txt','r') #contents = file.read() #file.close() #print(contents) with open('file_example.txt', 'r') as file: contents = file.read() print(contents)
#!/usr/bin/env python3 """CrooHtmlReportTracks Author: Jin Lee (leepc12@gmail.com) at ENCODE-DCC """ class CrooHtmlReportTracks(object): HEAD = """ <link rel="stylesheet" type="text/css" href=\ "http://epigenomegateway.wustl.edu/legacy/style.css" /> <script type="text/javascript" src="http://epigenom...
def buildPalindrome(st): for i in range(len(st)): sub = st[i : len(st)] if sub[::-1] == sub: missing = st[0:i] return st + missing[::-1] return st
n, k = map(int, input().split()) count = 0 for _ in range(n): a = int(input()) if a%k == 0: count +=1 print(count)
# Programa em q o usuario possa adicionar valores numericos em uma lista, Caso o numero ja exista ele nao sera adicionado # no final serao exibidos todos os valores unicos em ordem crescente lista = [] resp = '' old = 0 while True: old = int(input('Digite um valor: ')) if old in lista: print('Valor r...
male = [ 'AKIO', 'AKIRA', 'AOI', 'ARATA', 'ASUKA', 'AYUMU', 'DAICHI', 'DAIKI', 'DAISUKE', 'GORO', 'GOROU', 'HACHIRO', 'HACHIROU', 'HARU', 'HARUKA', 'HARUKI', 'HARUTO', 'HAYATE', 'HAYATO', 'HIBIKI', 'HIDEAKI', 'HIDEKI', 'HIDEYOSH...