content
stringlengths
7
1.05M
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: b.lin@mfm.tu-darmstadt.de """ def WriteMesh(num_f,name): inp=open("SaveSurfaceMesh.geo",'w+') val = str("SaveSurfaceMesh") for i in range(int(num_f)): inp.write(" Merge \"%s_%i.stl\"; \n" %(val,i+1)) for i in range(int(num_f)): ...
"""Solution to 1.6: String Compression.""" def compress(string): """Creates a compressed string using repeat characters. Args: string_one: any string to be compressed. Returns: A compressed version of the input based on repeat occurences Raises: ValueError: string input ...
{ "targets": [ { "target_name": "iow_sht7x", "cflags!": [ "-fno-exceptions" ], "cflags_cc!": [ "-fno-exceptions" ], "sources": [ "./src/iow_sht7x.cpp", "./src/sht7x.cpp" ], "include_dirs": [ "<!@(node -p \"require('node-addon-api').include\")", "./src/", "/usr...
# Default config_dict default_config_dict = {"MAIN": {}, "GUI": {}, "PLOT": {}} default_config_dict["MAIN"]["MACHINE_DIR"] = "" default_config_dict["MAIN"]["MATLIB_DIR"] = "" default_config_dict["GUI"]["UNIT_M"] = 1 # length unit: 0 for m, 1 for mm default_config_dict["GUI"]["UNIT_M2"] = 1 # Surface unit: 0 for m^2...
""" File: hailstone.py ----------------------- This program should implement a console program that simulates the execution of the Hailstone sequence, as defined by Douglas Hofstadter. Output format should match what is shown in the sample run in the Assignment 2 Handout. """ def main(): """ Calculate the num...
# 1. -------------------------------------- # 1. 1.1 * radiance = 1.1 # 2. 1.1 - 0.5 = 0.6 # 3. min(randiance, 0.6) = 0.6 # 4. 2.0 + 0.6 = 2.6 # 5. max(2.1, 2.6) = 2.6 # 2. -------------------------------------- radiance = 1.0 radiance = max(2.1, 2.0 + min(radiance, 1.1 * radiance - 0.5)) print(radiance)
class Solution: def bubble_sort(self, arr): bub_flag = 1 # bubbling will occur until finished i.e. until flag not set while bub_flag == 1: bub_flag = 0 # reset flag on each pass for i in range(0, len(arr)-1): # iterate over all elements j = i+1 if arr[j] < arr[i]: # IF not in ascending order ...
class Singleton( type ) : _instances = {} def __call__( aClass , * aArgs , **kwargs ) : if aClass not in aClass._instances: aClass._instances[aClass] = super(Singleton , aClass).__call__(*aArgs , **kwargs) return aClass._instances[aClass]
#leia 4 valores e guarde as em uma tupla. #mostre, qntas vezes apareceu o numero 9, #em que posição o valor 3 apareceu e quais foram os n pares. numeros = (int(input('Digite um número: ')), int(input('Digite um número: ')), int(input('Digite um número: ')), int(input('Digite um número: '))) print('Números digitados: '...
# coding=utf-8 #=============================================== #HOME INFORMATION #=============================================== pd_source_dir ='/ufrc/narayanan/desika.narayanan/pd_git/' #=============================================== #RESOLUTION KEYWORDS #=============================================== oref = 0 #...
# Krishan Patel # Bank Account Class """Chaper 14: Objects From Hello World! Computer Programming for Kids and Beginners Copyright Warren and Carter Sande, 2009-2013 """ # Chapter 14 - Try it out class BankAccount: """Creates a bank account""" def __init__(self, name, account_number): self.name = name...
mark = float(input("Inserire voto: ")) if mark < .35: print("F") elif mark < .85: print("D-") elif mark < 1.15: print("D") elif mark < 1.50: print("D+") elif mark < 1.85: print("C-") elif mark < 2.15: print("C") elif mark < 2.50: print("C+") elif mark < 2.85: print("B-") elif mark < 3.1...
class Solution: def reverseStr(self, s: str, k: int) -> str: s = list(s) head = 0 jump = 2*k while head < len(s): start, end = head, min(head + k-1, len(s)-1) while start < end: s[start], s[end] = s[end], s[start] start += 1 ...
class Solution: def multiply(self, num1: str, num2: str) -> str: n1 = len(num1) n2 = len(num2) if not n1 or not n2: return "" if n1 == 1 and num1[0] == '0': return "0" if n2 == 1 and num2[0] == '0': return "0" # arr_num1 = list(reve...
c=1 menor = 9999 while True: numero =int(input()) #condicion para obtener el menor if numero < menor and numero != 0: menor = numero #condicion para detener el bucle if numero ==0: break c=c+1 print("Menor:",menor)
#!/usr/bin/python3 """ Say my name module """ def say_my_name(first_name, last_name=""): """ Prints name """ if not isinstance(first_name, str): raise TypeError("first_name must be a string") if not isinstance(last_name, str): raise TypeError("last_name must be a string") try: ...
class Solution: def rob(self, nums: List[int]) -> int: if not nums: raise Exception("Empty Array") if len(nums) == 1: return nums[0] if len(nums) == 2: return max(nums[0], nums[1]) # loop arr[0:N - 1] dp_0 = [0] * len(nums) dp_0[0]...
numero=int(input('Diga o seu numero: ')) print('O seu numero é {} !\nO seu doblo é {} !\nOseu triplo é {}!\nA sua raiz quadrada é {} !'.format((numero), (numero*2), (numero*3), (numero**(1/2)))) #Ex Guanabara ''' n = int(input('Digite um numero: ')) d = n*2 t = n*3 r = n ** (1/2) print('O dobro de {} vale {}....
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class FreeObject(object): pass class Solution: # @param {ListNode} l1 # @param {ListNode} l2 # @return {ListNode} def addTwoNumbers(self, l1, l2): bk = l3...
# from adventofcode._2020.day11.challenge import main def test_input(): pass
def largest_prime_factor(number): factor = 2 while number != 1: if number % factor == 0: number /= factor else: factor += 1 return factor
class TempAndHumidityData: """ Captures temperature and humidity data """ def __init__(self, temperature, humidity): self.temperature = temperature self.humidity = humidity def __str__(self): return 'temperature={}, humidity={}'.format(self.temperature, self.humidity)
class Solution: def coinChange(self, coins, amount): if amount == 0: return 0 dp = [2 << 63] * (amount + 1) for coin in coins: if coin <= amount: dp[coin] = 1 for i in range(1, amount + 1): for j in range(len(coins)): ...
val = input() matsubi = val[-1:] if matsubi == "s": val2 = val + "es" else: val2 = val + "s" print(val2)
""" Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the empty string. Sample String : 'General12' Expected Result : 'Ge12' Sample String : 'Ka' Expected Result : 'KaKa' Sample String : 'K'...
begin_unit comment|'# Copyright 2010 United States Government as represented by the' nl|'\n' comment|'# Administrator of the National Aeronautics and Space Administration.' nl|'\n' comment|'# All Rights Reserved.' nl|'\n' comment|'#' nl|'\n' comment|'# Licensed under the Apache License, Version 2.0 (the "License"); ...
# -*- coding: utf-8 -*- # @Time : 2020/8/26-19:48 # @Author : TuringEmmy # @Email : yonglonggeng@163.com # @WeChat : csy_lgy # @File : height_weight.py # @Project : Happy-Algorithm def first(): times = int(input()) height = input().split() weight = input().split() heights = [int(i) ...
# Turtle topic name and type key constant KEY_TOPIC_MSG_TYPE = 'msg_type' KEY_TOPIC_NAME = 'name' # Logging frequency in seconds LOG_FREQUENCY = 10 # Publisher/Subscriber Queue size QUEUE_SIZE = 10 # Set angle and distance thresholds ANGULAR_DIST_THRESHOLD = 0.05 LINEAR_DIST_THRESHOLD = 0.05
config = { "interfaces": { "google.cloud.websecurityscanner.v1alpha.WebSecurityScanner": { "retry_codes": { "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], "non_idempotent": [], }, "retry_params": { "default": { ...
infile=open('baublesin.txt','r').readline() ro,bo,s,rp,bp=map(int,infile.split()) answer=0 r=ro-rp b=bo-bp if s==0: if r<0 or b<0: answer=0 elif r>=b: if bo==0 or bp==0: answer+=r+1 else: answer+=b+1 elif b>r: if ro==0 or rp==0: ...
# Symbol of circle required to show Celsius degree on display. circle = [ [0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], ...
# # PySNMP MIB module SONUS-NODE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SONUS-NODE-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:09:55 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2...
r""" Crystals ======== Quickref -------- .. TODO:: Write it! Introductory material --------------------- - :ref:`sage.combinat.crystals.crystals` - The `Lie Methods and Related Combinatorics <../../../../../thematic_tutorials/lie.html>`_ thematic tutorial Catalogs of crystals -------------------- - :ref:`sage.com...
# Lesson2: Operators with strings # source: code/strings_operators.py a = 'hello' b = 'class' c = '' c = a + b print(c) c = a * 5 print(c) c = 10 * b print(c)
frase = str(input('Digite uma frase: ')).upper().replace(' ', '') inverso = frase[::-1] print(f'O inverso de {frase} é {inverso}') if frase == inverso: print('A frase é um palindromo') else: print('A frase não é um palindromo')
# CPU: 0.05 s instructions = input() nop_count = 0 idx = 0 for char in instructions: if char.isupper() and idx % 4 != 0: add = 4 * (idx // 4 + 1) - idx idx += add nop_count += add idx += 1 print(nop_count)
# # PySNMP MIB module BayNetworks-AHB-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BayNetworks-AHB-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:25:19 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
a = [1, 2, 3] a.append(4) a a.extend(5) a a.extend([5]) a a.insert(10, 3) a a.insert(3, 10) a a = [1, 2, 3] a a.append(4) a a.append(5) a a.extend([6, 7]) a a.extend(8) help(a.insert) a.insert(0, 10) a a.insert(2, 12) a a.remove(10) a a.remove(12) a a.append(1) a a.remove(1) a a.remove(1) a a.pop(0) a a.pop(1) a a = [1...
# ***************************************************************************** # Copyright 2004-2008 Steve Menard # # 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 # # htt...
def run(): @_core.listen('test') def _(): print('a test 2') @_core.on('test') def _(): print('a test') _emit('test') _emit('test') _emit('test')
class TestingToolError(Exception): """ Base exception for all kind of error in the testing tool.""" pass ######################################################################## # Level 2 ######################################################################## class UnknownTestError(TestingToolError): "...
# Python3 program to generate pythagorean # triplets smaller than a given limit # Function to generate pythagorean # triplets smaller than limit def pythagoreanTriplets(limits) : c, m = 0, 2 # Limiting c would limit # all a, b and c while c < limits : # Now loop on n from 1 to m-1 for n in range(1...
# 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 to in writing, software # distributed under t...
# https://www.acmicpc.net/problem/2580 def init(): for row in range(N): for col in range(N): if data[row][col] == 0: continue row_sets[row].add(data[row][col]) for col in range(N): for row in range(N): if data[row][col] == 0: ...
# https://leetcode.com/problems/letter-case-permutation/ # Given a string s, we can transform every letter individually to be lowercase or # uppercase to create another string. # Return a list of all possible strings we could create. You can return the output # in any order. #########################################...
def sockMerchant(n, ar): # Write your code here dict_count = {i:ar.count(i) for i in ar} pairs = 0 for v in dict_count.values(): pairs+=v//2 #to get the quotient, % is used for remainder #print(pairs, dict_count) return pairs a = 9 ar= [10, 20, 20, 10, 10, 30, 50, 10, 20] print(sockMer...
# # Copyright 2018 Red Hat | Ansible # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ...
"""Apply a simple test to see if the user is old enough to rent a car.""" answer = input('Hello, who are you?\n') while not all(word.isalpha() for word in answer.split()): answer = input( "Names usually contain letters. Let's try this again.\n" "Hello, who are you?\n" ) name = answer.title().s...
"""Errors.""" class ProxyError(Exception): pass class NoProxyError(Exception): pass class ResolveError(Exception): pass class ProxyConnError(ProxyError): errmsg = 'connection_failed' class ProxyRecvError(ProxyError): errmsg = 'connection_is_reset' class ProxySendError(ProxyError): er...
# -*- coding: utf-8 -*- # ---------------------------------------------------------------------- # CISCO-PPPOE-MIB # Compiled MIB # Do not modify this file directly # Run ./noc mib make_cmib instead # ---------------------------------------------------------------------- # Copyright (C) 2007-2014 The NOC Proje...
#!/Anaconda3/python # -*- coding: UTF-8 -*- __author__ = 'pedro' def main(form, session): html = "<p> Bem-Vindo a interface CGI do canal Ignorância Zero. Escolha uma operação nos menus acima</p>" return html
rows, cols = [int(x) for x in input().split(' ')] matrix = [input().split() for _ in range(rows)] cmd = input() while cmd != 'END': cmd_args = cmd.split() if cmd_args[0] != 'swap' or len(cmd_args) != 5: print('Invalid input!') cmd = input() continue row1, col1 = int(cmd_args[1]), ...
# #1 # def last(*args): # last = args[-1] # try: # return last[-1] # except TypeError: # return last #2 def last(*args): try: return args[-1][-1] except: return args[-1]
def setup(): size(500, 500) smooth() noLoop() def draw(): background(100) stroke(142,36,197) strokeWeight(110) line(100, 150, 400, 150) stroke(203,29,163) strokeWeight(60) line(100, 250, 400, 250) stroke(204,27,27) strokeWeight(110) line(100, 350, ...
class BadGrammarError(Exception): pass class EmptyGrammarError(BadGrammarError): pass
# exceptions.py - exceptions for SQLAlchemy # Copyright (C) 2005, 2006, 2007 Michael Bayer mike_mp@zzzcomputing.com # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php class SQLAlchemyError(Exception): """Generic error class.""" pa...
# Tutorial: http://www.learnpython.org/en/Loops # Loops # There are two types of loops in Python, for and while. # The "for" loop # For loops iterate over a given sequence. Here is an example: primes = [2, 3, 5, 7] for prime in primes: print(prime) # For loops can iterate over a sequence of numbers using th...
"""Exercício Python 067: Faça um programa que mostre a tabuada de vários números, um de cada vez, para cada valor digitado pelo usuário. O programa será interrompido quando o número solicitado for negativo. """ while True: print('-------------------') n = int(input('Número: ')) if n < 0: break ...
""" Autogenerated by Django - used for admin site settings """ # uncomment when needed # from django.contrib import admin # Register your models here.
with open('recovered/arc/clusters/6.0.0_r1_acdc_clustered.rsf', encoding="utf8") as data_file: data = data_file.readlines() cluster = set() for line in data: cluster.add(line.split(" ")[1]) print(len(cluster))
# Find square of a number without using multiplication and division operator def main(): a = -10 if a < 0: a = abs(a) square = 0 for i in range(0, a): square += a print(square) if __name__ == '__main__': main()
#!/usr/bin/python3 #from node import Node # From node package import class Node class Node(object): """Represent a singly linked node.""" def __init__(self, data, next = None): self.data = data self.next = next head = None for count in range(1, 6): head = Node(count, head) #...
def func(a, b): # a is state 1 # b is state 2 # this is horrible code but it works! :^) s = r"\frac{1}{6}" s1 = r"\frac{1}{2}" s2 = r"\frac{1}{3}" if a == 19 and b != 19: return 0 if a == b: if a == 19: return 1 else: return 0 ...
""" `InverseHaar1D <http://community.topcoder.com/stat?c=problem_statement&pm=5896>`__ """ def solution (t, l): if (l == 1): # level-1 untransformation i = len(t) / 2 sums, diffs = t[:i], t[i:] ut = [] for j in range(len(sums)): # a + b = s, a - b = d ...
# This file contains the credentials needed to connect to and use the TTN Lorawan network # # Steps: # 1. Populate the values below from your TTN configuration and device/modem. # (For RAK Wireless devices the dev_eui is printed on top of the device.) # 2.Then rename the file to: creds_config.py # # Done, the file ...
""" entradas mujeres-->muj-->int hombres-->hom-->int sumatotal=tot salidas porcentajemujeres=mujp porcentajehombres=homp """ #entradas muj=int(input("Ingrese el numero de mujeres ")) hom=int(input("Ingrese el numero de hombres ")) #caja negra tot=muj+hom mujp=(muj/tot)*100 homp=(hom/tot)*100 #salidas print("El po...
def main(): n, m = [int(x) for x in input().split()] def wczytajJiro(): defs = [0]*n atks = [0]*n both = [0]*2*n defi = atki = bothi = 0 for i in range(n): pi, si = input().split() if (pi == 'ATK'): atks[atki] = int(si) ...
load_modules = { 'hw_USBtin': {'port':'auto', 'debug':2, 'speed':500}, # IO hardware module 'ecu_controls': {'bus':'BMW_F10', 'commands':[ # Music actions {'High light - blink': '0x1ee:2:20ff', 'cmd':'127'}, {'TURN LEFT and RIGHT': '0x2fc:7:31000000000000', 'cmd':'126'}, ...
#!/usr/bin/env python3 fname = input("Enter file name: ") fh = open(fname) lst = list() sorted_words = list() for line in fh: line = line.rstrip() words = line.split() for word in words: if lst.count(word) == 0: lst.append(word) lst.sort() print(lst)
# Python3 program to add two numbers number1 = input("First number: ") number2 = input("\nSecond number: ") # Adding two numbers # User might also enter float numbers sum = float(number1) + float(number2) # Display the sum # will print value in float print("The sum of {0} and {1} is {2}" .format(number1, numbe...
def extractCNovelProj(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('Please Be More Serious', 'Please Be More Serious', 'translated'), ('Still Not Wanting to Forget...
class Solution: # @param {string} a a number # @param {string} b a number # @return {string} the result def addBinary(self, a, b): # Write your code here max_len = max(len(a), len(b)) a = a.zfill(max_len) b = b.zfill(max_len) result = '' carry = 0 ...
class Solution: def dailyTemperatures(self, T: list) -> list: if len(T) == 1: return [0] else: mono_stack = [(T[0], 0)] i = 1 res = [0] * len(T) while i < len(T): if T[i] <= mono_stack[-1][0]: ...
with open("inputs_7.txt") as f: inputs = [x.strip() for x in f.readlines()] ex_inputs= [ "shiny gold bags contain 2 dark red bags.", "dark red bags contain 2 dark orange bags.", "dark orange bags contain 2 dark yellow bags.", "dark yellow bags contain 2 dark green bags.", "dark green bags contain 2 dark blue b...
#Simple calculator def add(x,y): return x+y def subs(x,y): return x-y def multi(x,y): return x*y def divide(x,y): return x/y num1 = int(input("Enter the Value of Num1 :")) num2 = int(input("Enter the Value of NUm2 :")) print("Choose 1 for '+'/ 2 for '-'/ 3 for '*'/ 4 for '/' :-") select = int(inpu...
a = 10 b = 20 soma = a + b print ("a soma dos números é",soma)
PI = float(3.14159) raio = float(input()) print("A=%0.4f" %(PI * (raio * raio)))
x = {} with open('input.txt', 'r', encoding='utf8') as f: for line in f: line = line.strip() x[line] = x.get(line, 0) + 1 lol = [(y, x) for x, y in x.items()] lol.sort() with open('output.txt', 'w', encoding='utf8') as f: if lol[-1][0] / sum(x.values()) > 0.5: f.write(lol[-1][1]) el...
""" Implementar um algoritmo para determinar se uma string possui todos os caracteres exclusivos. Premissas Podemos assumir que a string é ASCII? Sim Nota: As cadeias de caracteres Unicode podem exigir tratamento especial dependendo do seu idioma Podemos supor que há distinção entre maiúsculas e minúsculas? * Sim Pode...
{ "includes": [ "drafter/common.gypi" ], "targets": [ { "target_name": "protagonist", "include_dirs": [ "drafter/src", "<!(node -e \"require('nan')\")" ], "sources": [ "src/options_parser.cc", "src/parse_async.cc", "src/parse_sync.cc", ...
# Chalk Damage Skin success = sm.addDamageSkin(2433236) if success: sm.chat("The Chalk Damage Skin has been added to your account's damage skin collection.")
""" Key point: - Locate a '1' first and make all the right, left, up and down to '0'. - Make all the adjacent '1' to '0' so all the islands would be counted. """ class Solution: def numIslands(self, grid): if not grid: return 0 row = len(grid) col = len(grid[0]) ...
N_T = input().split() N = int(N_T[0]) T = int(N_T[1]) interactions = [] input_condition = input() conditions = list(input_condition) conditions = [int(x) for x in conditions] for x in range(T): input_line = input().split() input_line = [int(x) for x in input_line] interactions.append(input_lin...
#WAP to calculate and display the factorial of #an inputted number. num = int(input("enter the range for factorial: ")) f = 1 if num < 0: print("factorial does not exist") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1,num + 1): f = f * i print("The factorial ...
""" while / Else contadores acumuladores """ contador = 1 acumulador = 1 while contador <= 20: print(contador, acumulador) acumulador += contador contador += 1 if contador > 7: break else: print('cheguei no else') print('sai do while')
def pascal_nth_row(line_num): if line_num == 0: return [1] line = [1] last_line = pascal_nth_row(line_num - 1) for i in range(len(last_line) - 1): line.append(last_line[i] + last_line[i + 1]) line.append(1) # line here will the line at num line_num return line print(pasca...
class Product: def __init__(self): self.codigo = '' self.categoria = '' self.fabricante = '' self.nome = '' self.precoCheio = '' self.precoDesconto = '' self.totalVendas = '' self.precoVarejo = '' self.precoAtacado = '' self.resum...
# -*- coding: utf-8 -*- # @Time : 2018/7/28 下午3:34 # @Author : yidxue class Person: def __new__(cls, name, age): print('__new__ called.') return super(Person, cls).__new__(cls) def __init__(self, name, age): print('__init__ called.') self.name = name self.age = age...
#Attept a def isPerfectSquare(n): if n <= 1: return True start = 0 end = n//2 while((end - start) > 1): mid = (start + end)//2 sq = mid*mid print(mid, sq, start, end) if sq == n: return True if sq > n: end = mid if sq < ...
"""Below Python Programme demonstrate maketrans functions in a string""" #Example: # example dictionary dict = {"a": "123", "b": "456", "c": "789"} string = "abc" print(string.maketrans(dict)) # example dictionary dict = {97: "123", 98: "456", 99: "789"} string = "abc" print(string.maketrans(dict))
#!/usr/bin/env python # -*- coding: utf-8 -*- base_url = "https://es.wikiquote.org/w/api.php" quote_of_the_day_url = "https://es.wikiquote.org/wiki/Portada" def quote_of_the_day_parser(html): table = html("table")[1]("table")[0] quote = table("td")[3].text.strip() author = table("td")[5].div.a.text.strip(...
# membuat tupple buah = ('anggur', 'jeruk', 'mangga') print(buah) # output: ('anggur', 'jeruk', 'mangga')
input = """ 1 2 0 0 1 3 0 0 1 4 0 0 1 5 0 0 1 6 0 0 1 7 0 0 1 8 0 0 1 9 0 0 1 10 0 0 1 11 0 0 1 12 0 0 1 13 0 0 1 14 0 0 1 15 0 0 1 16 0 0 1 17 0 0 1 18 0 0 1 19 0 0 1 20 0 0 1 21 0 0 1 22 0 0 1 23 0 0 1 24 0 0 1 25 0 0 1 26 0 0 1 27 0 0 1 28 0 0 1 29 0 0 1 30 0 0 1 31 0 0 1 32 0 0 1 33 0 0 1 34 0 0 1 35 0 0 1 36 0 0 1...
class Solution: def searchMatrix(self, matrix: 'List[List[int]]', target: int) -> bool: m = len(matrix) if m == 0: return False n = len(matrix[0]) if n == 0: return False left, right = 0, m * n while left + 1 < right: mid = (left + ...
#Eoin Lees student = { "name":"Mary", "modules": [ { "courseName":"Programming", "grade":45 }, { "courseName":"History", "grade":99 } ] } print ("Student: {}".format(student["name"])) for module in student["modules"]: print...
# crypto_test.py 21/05/2016 D.J.Whale # # Placeholder for test harness for crypto.py #TODO: print("no tests defined") # END
def ask(name='Jack'): print(name) class Person: def __init__(self): print('Ma') my_func = ask my_func() """ Jack """ print() my_class = Person my_class() """ Ma """ print() obj_list = [] obj_list.extend([ask, Person]) for item in obj_list: print(item()) """ Jack None Ma <__main__.Person object ...
''' Given a balanced parentheses string S, compute the score of the string based on the following rule: () has score 1 AB has score A + B, where A and B are balanced parentheses strings. (A) has score 2 * A, where A is a balanced parentheses string. Example 1: Input: "()" Output: 1 Example 2: Input:...
# Modified from https://github.com/google/subpar/blob/master/debug.bzl def dump(obj, obj_name): """Debugging method that recursively prints object fields to stderr Args: obj: Object to dump obj_name: Name to print for that object Example Usage: ``` load("debug", "dump") ... dump(...
class Node: def __init__(self, data): self.data = data self.both = id(data) def __repr__(self): return str(self.data) a = Node("a") b = Node("b") c = Node("c") d = Node("d") e = Node("e") # id_map simulates object pointer values id_map = dict() id_map[id("a")] = a id_map[id("b")] = b ...