content
stringlengths
7
1.05M
#!/usr/bin/env python # encoding: utf-8 """ delete-node-in-a-linked-list.py Created by Shuailong on 2016-02-04. https://leetcode.com/problems/delete-node-in-a-linked-list/. """ # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None cl...
""" dhtxmpp_component is a Python implementation of a DHT XMPP component. """ version_info = (0, 1) version = '.'.join(map(str, version_info))
class mask: """ flatpak mask command """ def mask(self): cmd = "flatpak mask {}".format(app.getAppId()) result=subprocess.run(cmd, shell=True, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if result.returncode == 0: return True e...
distances_from_sofia = [ ('Bansko', 97), ('Brussels', 1701), ('Alexandria', 1403), ('Nice', 1307), ('Szeged', 469), ('Dublin', 2479), ('Palermo', 987), ('Oslo', 2098), ('Moscow', 1779), ('Madrid', 2259), ('London', 2019) ] # variable to store the filtered list of distance tu...
class DocumentTagsMetadataMixin: """ Adds metadata support in form of tags on SSM document. """ def __init__(self, metadata=None, *args, **kwargs): super().__init__(*args, **kwargs) self.tags = metadata or [] def get_metadata(self): return {**{tag.name: tag.value for tag in...
firstWord = input().lower() secondWord = input().lower() if firstWord == secondWord: print("yes") else: print("no")
class TreeNode: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def construct(inorder, level_order): def helper(inorder): if inorder is None: return None root = TreeNode(level_order.pop(0)) mid = in...
android_desired_caps = { "build": "Python Android", 'device': 'Google Pixel', 'os_version': '7.1', 'appPackage': 'com.auth0.samples', 'appActivity': 'com.auth0.samples.MainActivity', 'app': 'Auth0', 'chromeOptions': { 'androidPackage': 'com.android.chrome' } } android_desired_cap...
""" Given the availability time slots arrays slots1 and slots2 of two people and a meeting duration duration, return the earliest time slot that works for both of them and is of duration duration. If there is no common time slot that satisfies the requirements, return an empty array. The format...
""" coding: utf-8 Created on 02/11/2020 @author: github.com/edrmonteiro From: Codility Lessons """ # MaxDoubleSliceSum # Find the maximal sum of any double slice. # A non-empty array A consisting of N integers is given. # A triplet (X, Y, Z), such that 0 ≤ X < Y < Z < N, is called a double slice. # The sum of doub...
class BaseConsumer(object): """ This class sets the blueprint for all the log event consumers """ @staticmethod def process(log_line, log_group, log_stream): pass
def to_arabic(roman): table = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000} n = len(roman) number = 0 for i in range(n): if i < n - 1 and table[roman[i]] < table[roman[i + 1]]: number -= table[roman[i]] else: number += table[roman[i]] return numb...
n = int(input()) students_bellow_3 = 0 students_3_4 = 0 students_4_5 = 0 students_above_5 = 0 all_student_scores = 0 for i in range(1, n + 1): student_score = float(input()) all_student_scores += student_score if 2.00 <= student_score <= 2.99: students_bellow_3 += 1 elif 3.00 <= student_score ...
#Ingresar un numero de 4 digitos; Crea un algoritmo para sumar us digitos. Numero=int(input("Ingresa el Valor: ")) D1=Numero//1000 r1=Numero%1000 D2=r1//100 r2=r1%100 D3=r2//10 D4=r2%10 Suma=D1+D2+D3+D4 print("El resultado es:",Suma) print("orden: ",D1,D2,D3,D4) print("reves",D4,D3,D2,D1)
fname = 'se.zone.txt' names = set() with open(fname, 'r') as f: for line in f: line = line.partition(';')[0].strip() if len(line) == 0: continue domain, *_ = line.split() domain = domain[:-1] # remove trailing dot domain = domain.split('.') if len(do...
#!/usr/bin/env python # -*- coding: utf-8 -*- class Hint(): def __init__(self, label, value): self.label = label self.value = value def __repr__(self): return '<Hint %r>' % self.label def serialize(self): return { 'label': self.label, 'value': sel...
# Hacer una suma, # si el resultado está en un rango de 1 a 100 imprimir resultado, # si no mandar un mensaje de error. num1 = float(input("Número 1: ")) num2 = float(input("Número 2: ")) res = num1 + num2 if (res > 0 and res <= 100): print(f"El resultado es {res}") else: print("Error")
""" [API] Contains exceptions that may be exposed to the library client. """ class CachedMethodFailedException(Exception): pass
def pre_order(visitor, node): visitor(node) if node.l: pre_order(visitor, node.l) if node.r: pre_order(visitor, node.r) def in_order(visitor, node): if node.l: in_order(visitor, node.l) visitor(node) if node.r: in_order(visitor, node.r) def post_order(visitor, node): if node.l: post...
#Collect name from the user name = input("What is your name? ") #Display the name print(name) #Update the value name = "Mary" print(name) #Create a friendly name firstName = input("What is your first name? " ) lastName = input("What is your first name? " ) print("Hello " + firstName + " " + lastName)
def LeiaInt(msg): valor = False resultado = 0 while True: n = (input(msg)) if n.isnumeric(): resultado = int(n) valor = True else: print('ERROR: Digite novamente.') if valor: break return resultado # PROGRAMA n = L...
# This script converts a multiple sequence alignment into a matrix # of pairwise sequence identities. # # Aleix Lafita - June 2018 # Input alignment and output identity matrix files alignment_file = "PF06758_A0A87WZJ2.sto" matrix_file = "PF06758_A0A87WZJ2_matrix.tsv" with open(alignment_file, 'r') as input, open(mat...
#email slicer program email=[] username=[] mail_server=[] top_level_domain=[] n=int(input("ENTER THE NUMBER OF EMAILS : ")) print("\n") for i in range(1,n+1): name=input("PLEASE ENTER THE EMAIL ID : ").strip() email.append(name) for j in email: a=j[:j.index('@')] b=j[j.index('@')+1:j...
list_of_inputs = open("./input.txt").readlines() cleaned_list = [] for item in list_of_inputs: cleaned_list.append(item.strip()) correct_passwords_count = 0 for item in cleaned_list: chCorrect = 0 pCurrent = item.split(" ") pInfo = pCurrent[0] pTimesMin, pTimesMax = pInfo.split ("-") pLetter ...
# Advent Of Code 2017, day 12, part 1 # http://adventofcode.com/2017/day/12 # solution by ByteCommander, 2017-12-12 with open("inputs/aoc2017_12.txt") as file: links = {} for line in file: src, dests = line.split(" <-> ") links[int(src)] = [int(dest) for dest in dests.split(", ")] visited...
stocks = { 'GOOG' : 434, 'AAPL' : 325, 'FB' : 54, 'AMZN' : 623, 'F' : 32, 'MSFT' : 549 } print(min(zip(stocks.values(), stocks.keys())))
# Purpose: Define standard linetypes, text styles # Created: 23.03.2016 # Copyright (C) 2016, Manfred Moitzi # License: MIT License def linetypes(): """ Creates a list of standard line types. """ # dxf linetype definition # name, description, elements: # elements = [total_pattern_length, elem1, el...
""" The file defines the some Greek letters as pre-defined constants that have to be used within the application. All letters are defined using the unicode encoding """ OMEGA_UNICODE = u"\u03C9" MU_UNICODE = u"\u03BC" NU_UNICODE = u"\u03B7" XI_UNICODE = u"\u03BE" KAPPA_UNICODE = u"\u03BA" BETA_UNICODE = u"\u03B2" SIGM...
def format_positive_integer(number): l = list(str(number)) c = len(l) while c > 3: c -= 3 l.insert(c, '.') return ''.join(l) def format_number(number, precision=0, group_sep='.', decimal_sep=','): number = ('%.*f' % (max(0, precision), number)).split('.') integer_part = ...
# MIT License # # # Copyright (c) 2022 by exersalza # # # 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, co...
# Escreva um programa que pergunta a quantidade de Km percorridos por um carro alugado # e a quantidade de dias pelos quais ele foi alugado . Calcule o preço a pagar. sabendo # que o carro custa R460 por dia e R4 0,15 por km rodado. dias = int(input('Quantos dias Alugados?')) km = float(input('Quantos Km rodados:')) p...
#!/usr/bin/env python3 NUM_SOCKET = 2 NUM_PHYSICAL_CPU_PER_SOCKET = 12 SMT_LEVEL = 2 OS_CPU_ID = {} # socket_id, physical_cpu_id, smt_id OS_CPU_ID[0,0,0] = 0 OS_CPU_ID[0,0,1] = 24 OS_CPU_ID[0,1,0] = 1 OS_CPU_ID[0,1,1] = 25 OS_CPU_ID[0,2,0] = 2 OS_CPU_ID[0,2,1] = 26 OS_CPU_ID[0,3,0] = 3 OS_CPU_ID[0,3,1] = 27 OS_CPU_ID...
# The first two are treated as literal blocks. def example(): """ This is a paragraph:: With a literal block. While this one has trailing space:: So is this a literal block? And this one has trailing chars:: ! - So this clearly isn't a literal block. """ return 1
def notas(*n, sit=False): r = dict() r['total'] = len(n) r['maior'] = max(n) r['menor'] = min(n) r['média'] = sum(n) / len(n) if sit: if r['média'] >= 7: r['Situação'] = "boa" elif r['média'] >= 5: r["Situação"] = 'Razoavel' else: r["Si...
''' Created on Aug 13, 2018 @author: david avalos ''' class Person: def __init__(self, name): self.name = name def talk(self, words): print(words) def hobby(self): print("My hobby is to watch movies") class Teacher(Person): def __init__(self, name, ...
# description: Generate PaseCliAsync_gen.c # command: python gen.py PaseSqlCli_file = "./gen_cli_template.c" # =============================================== # utilities # =============================================== def parse_sizeme( st ): sz = '4' if 'SMALL' in st: sz = '2' elif '*' in st: ...
VERSION = (0, 1, 0) __author__ = 'Ivan Sushkov <comeuplater>' __version__ = '.'.join(str(x) for x in VERSION)
def zero_matrix(matrix): points = [] for row in range(len(matrix)): for col in range(len(matrix[row])): val = matrix[row][col] if val == 0: points.append((row, col)) for point in points: update_row(matrix, point[0]) update_col(matrix, point[1...
Aa,Va=input().split() Ab,Vb=input().split() Aa,Va,Ab,Vb=int(Aa),int(Va),int(Ab),int(Vb) Fb=Ab-Vb while Fb>0 and Va>0: Vb+=1 Va-=1 Fb-=1 print(Va,Vb)
class NoGeometry(RuntimeError): pass class NoSuperelements(RuntimeError): pass
a = 1 b = 2 c =2 a = 2 class info(): def __init__(self): self.color="red"
# SPDX-FileCopyrightText: no # SPDX-License-Identifier: CC0-1.0 # # Stubs for part of the Python API from libcalamares # (although the **actual** API is presented through # Boost::Python, not as a bare C-extension) so that # pylint doesn't complain about libcalamares internals. VERSION_SHORT="1.0"
lista = [] while True: nome = input('Nome: ') n1 = float(input('Nota 1: ')) n2 = float(input('Nota 2: ')) media = (n1+n2)/2 lista.append([nome, [n1, n2], media]) resposta = input('Quer continuar? [S/N] ') if resposta in 'Nn': print('-=' * 30) break print(f'{"Nº.":<4}{"NOME":<...
def bound_coordinate(corrdinate,max): if corrdinate < 0 : corrdinate = 0 if corrdinate > max: corrdinate = max - 2 return int(corrdinate) def process_text(text,img,conf_dict,coord,language): try: f_text = float(text) if f_text == int(f_text) or len(conf_dict['conf'])==0: coord[0,0]=c...
''' Sorting is useful as the first step in many different tasks. The most common task is to make finding things easier, but there are other uses as well. In this case, it will make it easier to determine which pair or pairs of elements have the smallest absolute difference between them. For example, if you've got th...
def _combinators(_handle, items, n): if n==0: yield [] return for i, item in enumerate(items): this_one = [ item ] for cc in _combinators(_handle, _handle(items, i), n-1): yield this_one + cc def combinations(items, n): ''' take n distinct items, order matters ''...
'''6. Write a Python program to count the number of equal numbers from three given integers. Sample Output: 3 2 0 3''' def count(num): if num[0]==num[1] and num[0]==num[2]: ans = 3 elif num[0]==num[1] or num[1]==num[2] or num[0]==num[2]: ans = 2 else: ans = 0 return ans print(cou...
#!/usr/bin/env python3 """Lists and tuples.""" MONTHS_TUPLE = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December') MONTHS_LIST = list(MONTHS_TUPLE) print('MONTHS_TUPLE is {}.'.format(type(MONTHS_TUPLE))) print('MONTHS_...
class Sources: ''' News class to define News sources Objects ''' def __init__(self, id, name, description): self.id = id self.name = name self.description = description class Articles: ''' Headlines to define News articles class ''' def __init__(self, source, ...
# LEETCODE 121: Best Time to Buy and Sell Stock # # https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ # # Say you have an array for which the ith element is the price of a given stock on day i. # # If you were only permitted to complete at most one transaction # (i.e., buy one and sell one share of the s...
def test_view(invoke, secret): invoke(['decrypt']) decrypted = invoke(['view', secret.encrypted.as_posix()]) plaintext = secret.decrypted.read_text().splitlines() assert decrypted == plaintext
# Copyright (c) 2015 OpenStack Foundation. # 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...
{ 'variables': { 'external_libmediaserver%' : '<!(echo $LIBMEDIASERVER)', 'external_libmediaserver_include_dirs%' : '<!(echo $LIBMEDIASERVER_INCLUDE)', }, "targets": [ { "target_name": "medooze-audio-codecs", "cflags": [ "-march=native", "-fexceptions", "-O3", "-g", "-Wno-unus...
""" Define constants for Nary task. """ EMB_INIT_RANGE = 1.0 # vocab PAD_TOKEN = '<PAD>' PAD_ID = 0 UNK_TOKEN = '<UNK>' UNK_ID = 1 VOCAB_PREFIX = [PAD_TOKEN, UNK_TOKEN] POS_TO_ID = {PAD_TOKEN: 0, UNK_TOKEN: 1, 'PRP': 2, 'NN': 3, 'VBZ': 4, '``': 5, '-LRB-': 6, 'JJR': 7, 'LS': 8, 'MD': 9, 'JJ': 10, 'PRP$': 11, 'RB': ...
#python n tem arrays, tem listas #vamos ver as listas aninhadas que correspodem a Matrizes #representa uma matriz 3x3 lista=[[1,2,3],[4,5,6],[7,8,9,]] #Acesso de dados #print(lista[0]) #acessa a primeira lista #print(lista[0][1]) #Acessando o 2 elemento da lista 1 #metodos de acesso e iteração da matriz #for...
def a(m,limit): turn=len(m) last_spoken = m[-1] while turn < 2020: turn += 1 try: distance = list(reversed(m[:-1])).index(last_spoken)+1 except ValueError: distance = 0 m.append(distance) last_spoken = distance return(m[-1]) def ab(m, lim...
# Title : TODO # Objective : TODO # Created by: Wenzurk # Created on: 2018/2/10 # alien_0 = {'color': 'green', 'point': '5'} # alien_1 = {'color': 'yellow', 'point': '10'} # alien_2 = {'color': 'red', 'point': '15'} # # aliens = [alien_0, alien_1, alien_2] # # for alien in aliens: # print(alien) aliens = [] ...
class Fruit: def eat(self): print("Eating..") f=Fruit() f.eat()
# Aula 018: '''Nessa aula, vamos aprender o que são LISTAS e como utilizar listas em Python. As listas são variáveis compostas que permitem armazenar vários valores em uma mesma estrutura, acessíveis por chaves individuais.''' # Listas compostas: teste = [] teste.append('Gustavo') teste.append(40) print(teste) galer...
iterable = range(5) # range is the iterable iterator = iter(iterable) # extract iterator from iterable while True: try: n = next(iterator) # Code inside "for" loop print(n, end=" ") n = 5 # Will be overridden by line 5 in next iteration except StopIteration: # iterator signal...
""" Write the pseudocode for a function which returns the highest perfect square which is less or equal to its parameter (a positive integer). Implement this in a programming language of your choice. """ def power(number): x = 1 """ check if every square number going up from 1 fits. """ while x * x < ...
#coding: utf-8 """ Faça um programa que leia um número indeterminado de valores, correspondentes a notas, encerrando a entrada de dados quando for informado um valor igual a -1 (que não deve ser armazenado). Após esta entrada de dados, faça: a. Mostre a quantidade de valores que foram lidos; b. Exiba todos os valo...
#!/usr/bin/env python # Copyright 2016 Cisco Systems, Inc. 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....
class dir: misc = "misc/" datasets = "datasets/" kerasModels = misc + "kerasModels/" autoencoders = kerasModels + 'autoencoder/' @staticmethod def get_autoencoder_dir_of_latent_size(latentSize): return dir.autoencoders + "ae" + str(latentSize) + '/' class dataset: _directory = dir...
print(8%10) x = 'abc_%(key)s_' x %= {'key':'value'} print(x) x = 'Sir %(Name)s ' x %= {'Name':'Lancelot'} print(x)
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: hashmap = {} for x in jewels: hashmap[x] = 0 for x in stones: if x in hashmap: hashmap[x] += 1 return sum(hashmap.values()) class Solution(object): def numJewel...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = N...
h, w, n = map(int, input().split()) li = list(map(int, input().split())) curw = 0 for i in range(n): if curw + li[i] <= w: curw += li[i] else: print('NO') exit(0) if curw == w: curw %= w h -= 1 if not h: print('YES') exit(0) print('NO')
"""Tests for the button component""" def test_button_is_setup(generate_main): """ When the button is set in the yaml file if should be registered in main """ # Given # When main_cpp = generate_main("tests/component_tests/button/test_button.yaml") # Then assert "new wake_on_lan::WakeO...
tax_table = [(10000, 0.1), (20000, 0.2), (None, 0.3)] def get_tax(init_salary, tax_table): tax = 0 salary = init_salary previous_limit = 0 for limit, ratio in tax_table: if limit is None or init_salary < limit: tax += salary * ratio return tax current_salary = l...
nome = input ('Qual o seu nome?') print ('Olá',nome,'! Que bom que apareceu') nome = input ('Qual o seu nome?') print ('Olá',nome,'!' 'Que bom que apareceu')
fhand = open(input("Enter file name: ")) schools = dict() for ln in fhand: if not ln.startswith('From '): continue ln = ln.split() mailer = ln[1] pos = mailer.find('@') school = mailer[pos+1:] schools[school] = schools.get(school,0) + 1 print(schools)
""" Converting an postfix expression into output value""" def check_precedence(op): operators = ['(', ')', '^', '*', '/', '+', '-'] has_op = {'(': 0, ')': 0, '^': 3, '*': 2, '/': 2, '+': 1, '-': 1} for i in range(len(operators)): if op == operators[i]: return has_op[operators[i]] r...
def prod2sum(a, b, c, d): firstPair = [abs(a*c + b*d), abs(b*c - a*d)] firstPair.sort() secondPair = [abs(a*c - b*d), abs(b*c + a*d)] secondPair.sort() delta = firstPair[0] - secondPair[0] if delta < 0: return [firstPair, secondPair] elif delta > 0: return [secondPair, firstP...
# list example list_test = ["item", 10, "item"] print(list_test) print(list_test[0]) # append item in list list_test.append("testappend") print(list_test) # remove item list list_test.remove("testappend") ## using value, not position print(list) # declaring tuples # tuples are imutables lists # dont possible concatena...
# -*- coding: utf-8 -*- ''' 本模块主要实现控制器相关功能 主要包括:容器与命名空间的映射(通过容器所在的主机一级容器所对应的交换机接口进行) 数据流量的规划(通过数据包的目的地址与目的端口进行,如果是ARP协议,则直接将arp包随机传向同一命名空间的任一可用容器) 容器的迁移(流程见例图) 访问控制(可由用户配置) 部分数据结构 : container : id dpid portId mac hostid netn...
class MaterialGameSettings: alpha_blend = None face_orientation = None invisible = None physics = None text = None use_backface_culling = None
class Dinglemouse(object): def __init__(self, queues, capacity): self.queues = list(map(list, queues)) self.cap = capacity self.passengers = [] def theLift(self): queues = self.queues cap = self.cap floors = len(queues) floors_v...
class DotNotationDict(dict): ''' Dictionary subclass that allows attribute access using dot notation, eg: >>> dnd = DotNotationDict({'test': True}) >>> dnd.test True ''' def __getattr__(self, key): try: return self[key] except KeyError: raise At...
class Solution(object): def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ ## storing unique elements in a list unique = [] for i in nums: ## if element not in the list, add it to the list if i not in unique: ...
''' Condition group where conditions are set ''' class ConditionGroup(): def __init__(self): self.conditions = [] self.success = 'success' self.failed = 'failed' def add_condition(self, l1, optn, arg, then, else_value): input_json = {'l1': l1, 'optn': optn, 'arg': arg, 'then':...
#!/usr/bin/python # -*- coding: utf-8 -*- # # FILE: stop_words.py # # Simple routine that removes stop words from a string # # Copyright by Author. All rights reserved. Not for reuse without # express permissions. # def remove_stops(text=None): new_text = "" nt2 = [] text_list = text.split("\n") ...
class Error(Exception): def __init__(self, s, context=None, exception=None): Exception.__init__(self, s) self.context = context self.exception = exception
print("Enter 'quit' when done\n") while True: # ask for card number credit_num = input("Number: ") # allow user to end program if credit_num.casefold() == "quit": break # if input given isn't numeric re-ask for number while not credit_num.isdigit(): print("\nEnte...
class Solution: def winnerOfGame(self, colors: str) -> bool: # print(colors[:-1]) count1, count2 = 0, 0 for i in range(1, len(colors)-1): if colors[i-1] == colors[i] == colors[i+1] == "A": count1 += 1 elif colors[i-1] == colors[i] == colors[i+1] == "...
#!/usr/bin/env python3 #!/usr/bin/python print(" this".strip())
# Super Plumber # # November 26, 2020 # By Robin Nash # November 26 2020 # y,x = r,c = 6,5 data = [] ##for i in range(y): ## data.append(input()) ##data = ['..3.......', '..........', '..7.**....', '.9**...1..', '..8..9....'] grid = [\ '.**.1',\ '.*9..',\ '.5...',\ '.....',\ '.....',\ '.....',...
가격 = float(input('가격?')) 부가세율 = 0.1 print(가격*부가세율) 부가가치세 = 가격*부가세율 print(부가가치세) 열린파일 = open("results.txt", "a") 열린파일.write(str(부가가치세)+'\n') 열린파일.close()
# Copyright (c) 2013 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'includes': [ '../../../../build/common.gypi', ], 'conditions': [ ['target_arch=="ia32" or target_arch=="x64"', { 'targets': [...
# Runtime: 156 ms # Beats 72.62% of Python submissions # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def increasingBST(self, root): """ :type root: TreeNode :...
def popup_element(value, title=None, format=None): """Helper function for quickly adding a popup element to a layer. Args: value (str): Column name to display the value for each feature. title (str, optional): Title for the given value. By default, it's the name of the value. format (st...
# Create a list of strings: fellowship fellowship = ['frodo', 'samwise', 'merry', 'aragorn', 'legolas', 'boromir', 'gimli'] # Create list comprehension: new_fellowship new_fellowship = [member if len(member) >= 7 else "" for member in fellowship] # Print the new list print(new_fellowship)
# Exercício Python 035: Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo. straight_line = [] for x in range(0,3): line = float(input('Enter the size of the line: ')) straight_line.append(line) ab = straight_line[0] + straight_line[1] bc = strai...
#string literals print('this is a sample string') #concatenation - The print() function inserts a space between elements separated by a comma. name = "Zen" print("My name is", name) #The second is by concatenating the contents into a new string, with the help of +. name = "Zen" print("My name is " + name) number = 5 ...
EXPIRED_UPDATE = 240 CLUMP_TIMEOUT = 1 ACTIVE_TIMEOUT = 0.005 BULK_BOUND = 4
KEEP_RATE = 0.8 #Rate of dropping out in the dropout layer LOG_DIR = "../ops_logs" #Directory where the logs would be stored for visualization of the training #Neural network constants cat1_dir = "../categories/treematter/ingroup/" cat2_dir = "../categories/plywood/ingroup/" cat3_dir ...
class Solution: def numDistinct(self, s: str, t: str) -> int: dp = [] for i in range(len(s) + 1): dp.append([0] * (len(t) + 1)) dp[0][0] = 1 for i in range(len(s) + 1): dp[i][0] = 1 for a in range(1, len(t) + 1): for b in range(a, len(s) + ...
class Solution: def peakIndexInMountainArray(self, A): """ :type A: List[int] :rtype: int """ # return A.index(max(A)) return max(range(len(A)), key=A.__getitem__)
expected_output = { "outside": { "ipv4": { "neighbors": { "10.10.1.1": { "ip": "10.10.1.1", "link_layer_address": "aa11.bbff.ee55", "age": "alias", }, "10.10.1.1/1": { ...
def Reverse(l): newL = [] for i in range(len(l)): index = len(l) - i - 1 #Trying to make for(int i=l.length()-1; i>=0; i--) but in python newL.insert(i, l[index]) return newL l = [1,2,3,4,5,6,7,8,9,10] new_l = Reverse(l) print(new_l)