content
stringlengths
7
1.05M
""" coding: utf-8 Created on 09/11/2020 @author: github.com/edrmonteiro From: Hackerrank challenges Language: Python Group: Warm-up challenges Title: Sales by Match Alex works at a clothing store. There is a large pile of socks that must be paired by color for sale. Given an array of integers representing the color ...
class Solution(object): def arrayPairSum(self, nums): """ :type nums: List[int] :rtype: int """ nums = sorted(nums) res = 0 for i in range(0, len(nums), 2): res += nums[i] return res
n = int(input('Digite um número: ')) for c in range(0, n + 1): print(c) print('FIM')
customers = [ dict(id=1, total=200, coupon_code='F20'), dict(id=2, total=150, coupon_code='P30'), dict(id=3, total=100, coupon_code='P50'), dict(id=4, total=110, coupon_code='F15'), ] for customer in customers: code = customer['coupon_code'] if code == 'F20': customer['discount'] = 20.0...
def count_substring(string, sub_string): counter = 0; while (string.find(sub_string) >= 0): counter += 1 string = string[string.find(sub_string) + 1:] return counter if __name__ == '__main__': string = input().strip() sub_string = input().strip() count = count_substring(strin...
# # PySNMP MIB module ZYXEL-BRIDGE-CONTROL-PROTOCOL-TRANSPARENCY-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-BRIDGE-CONTROL-PROTOCOL-TRANSPARENCY-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:49:13 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 ...
a = int(input()) b = int(input()) c = int(input()) d = int(input()) if b == c and a in {8, 9} and d in {8, 9}: print("ignore") else: print("answer")
PREFERENCES = [ ['Delivery driver', 'Haifa', 'No experience', 'Flexible'], ['Web developer', 'Tel Aviv', '5+ years', 'Full-time'], ]
# is_prime(9); //Is a number Prime? # //H: 5 => True, 7 => True, 11 => True, 6 => False def is_prime(number): if(number < 2): return False # check if number is divisible by 2 to number - 1 for divisor in range(2,number): if number % divisor == 0: return False return True ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class HelloWorld(object): def __init__(self, id, name): self.idx = id self.namex = name def play(self): print('idx: {}, namex: {}', self.idx, self.namex) if __name__ == '__main__': HelloWorld(1, '12') print('hello world')
# 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 the ...
#! n=int(input("Enter a number")) for i in range(1,n): print(i)
#!/usr/bin/env python class Solution: def maxArea(self, height): """ :type height: List[int] :rtype: int """ i, j = 0, len(height)-1 l, r = height[i], height[j] maxArea = (j - i) * min(l, r) while j > i: if l < r: while hei...
#a stub module to have a group of functions class test_module_1(object): name = None def __init__(self, name): self.name= name def log(self, info): print('{}{}'.format('test_module_1: ',info)) def function_1(self,*args, **kwargs): self.log('args: '+'{}'.format(args)) sel...
""" Desafio 030 Problema: Crie um programa que leia um número inteiro e mostre na tela se ele é PAR ou ÍMPAR. Resolução do problema: """ numero = int(input('Informe um número: ')) print('O número {} é PAR'.format(numero) if numero % 2 == 0 else 'O número {} é ÍMPAR.'.format(numero))
# -*- coding: utf-8 -*- # @Author: Damien FERRERE # @Date: 2018-05-22 21:14:37 # @Last Modified by: Damien FERRERE # @Last Modified time: 2018-05-22 21:16:10 class IPXRelaysConfig: 'IPX800 Relays configuration class' enabled_relays = [] # List of relays user want to control names_retrieved = False # indic...
def onRequest(request, response, modules): response.send({ "urlParams": request.getQueryParams(), "bodyParams": request.getParams(), "headers": request.getHeaders(), "method": request.getMethod(), "path": request.getPath() })
WEBSOCKET_DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ" class NewDataEvent: def __init__(self, id, topic, payload, timestamp, qos): self._type = "data-sensor" self._id = id self._topic = topic self._payload = payload self._timestamp = timestamp self._qos = qos @...
class Projeto: def __init__(self, identificacao = None, custo_obra = None, area_desmatada = None, impacto_ambiental = None, status_obra = None, reducao_imp_amb = None) -> None: self.identificacao = identificacao self.custo_obra = custo_obra self.area_destada = area_desmatada ...
# ***************************************************************** # Copyright 2015 MIT Lincoln Laboratory # Project: SPAR # Authors: SY # Description: IBM TA2 circuit object superclass # # Modifications: # Date Name Modification # ---- ---- ...
a = int(input()) c = [] for i in range(a): b = [] for x in range(4): c = input().split()[-1][::-1].lower() for n in c: if n == "a" or n == "e" or n == "i" or n == "o" or n == "u": b.append(c[:c.index(n) + 1]) break if len(b) < x + 1: ...
def merge_sort(alist): print(f'Splitting {alist}') if len(alist) > 1: mid = len(alist) // 2 # slice operator is O(k), this can be avoided by passing start, end # indexes into merge sort left = alist[:mid] right = alist[mid:] # Assume list is sorted merge...
""" synonym 置き換える 置換する synonym 用いる とする synonym 取り除く 除去する synonym 表示する 出力する synonym 区切り 区切り記号 区切り文字列 セパレータ """ math = __package__ # module file = "ファイル名" # symbol s = '文字列' # symbol s2 = '文字列' # symbol len(a) # aの[長さ|大きさ|要素数|サイズ] max(a, b) # aとbの[最大値|大きい値|大きい方] max(a) # aの 最大値 math.pi # 円周率 a % 2 == 0 # a(...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 3 19:26:47 2019 @author: sercangul """ a, b = map(float, input().split()) n = float(input()) p = a/b q = 1-p result = (q**(n-1))* p print (round(result,3))
def main(): a,b = map(int,input().split()) ans = ["",0] h = ["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW","N"] a = (a*10 + 1125) // 2250 b /= 60 ans[0] = h[a] if 0 <= b and b < 0.25: ans[1] = 0 elif b < 1.55: ans[1] = 1 elif b < ...
""" LeetCode Problem: 1247. Minimum Swaps to Make Strings Equal Link: https://leetcode.com/problems/minimum-swaps-to-make-strings-equal/ Language: Python Written by: Mostofa Adib Shakib Time Complexity: O(n) Space Complexity: O(1) Explanation: 1) Use "x_y" when x in s1 at index i and y in s2 at same index i. 2) Use...
# using classes class Wing(object): #NOTE use __slots__ to avoid unintended mistakes __slots__ = ['coordroot', 'coordtip', 'span', 'sweepdeg'] def __init__(self): self.coordroot = 2 self.coordtip = 1 self.span = 20 self.sweepdeg = 30 class Fuselage(object): #NOTE use __s...
word2int_en = { "animosity":10581, "tearing":6525, "blivet":33424, "fomentation":25039, "triennial":22152, "cybercrud":33456, "flower":2250, "tlingit":29988, "invade":9976, "lamps":4886, "watercress":22874, "than":164, "woozy":28419, "lice":16885, "chirp":16036, "gracefulness":17688, "sundew":28491, "kenyan":27735, "re...
def isHappy(n): if len(str(n))==1 and n==1: return True seen=set() while n!=1: num = str(n) n=0 for i in range(len(num)): n +=int(num[i])**2 if n not in seen: seen.add(n) else: return False return True i...
# Lista de la compra. # # Este ejercicio consiste en la digitalización de una lista de la compra totalmente funcional. # Esta lista de la compra será una aplicación de consola basada en menus. # # En caso que el usuario de una opcion no valida, se debera informar que la opción no es valida # y volver a mostrar a...
# database class to manage all database related info class database: # used to setup variables with self to be used in the class def __init__(self): # student accounts self.students = [ ['anthony', 'rangers20', False, False], ["stephanie",...
entity_to_index = {} summary_to_entity = {} summary_to_entity['Shipping Date'] = 'shipped' summary_to_entity['Results Received/ NRC-PBI LIMS Request #'] = 'received' summary_to_entity['Project'] = 'project' summary_to_entity['SFF'] = 'sff' summary_to_entity['Mid Set'] = 'mid_set' summary_to_entity['Plate'] = 'plate' s...
class DirectiveImporter(): def extract(): pass
# -*- coding: utf-8 -*- X1, Y1 = map(float, input().split()) X2, Y2 = map(float, input().split()) DISTANCE = ( (X2 - X1)**2 + (Y2 - Y1)**2 ) ** (0.5) print("%.4f" % (DISTANCE))
""" 0917. Reverse Only Letters Easy Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions. Example 1: Input: "ab-cd" Output: "dc-ba" Example 2: Input: "a-bC-dEf-ghIj" Output: "j-Ih-gfE-dCba" Example 3: Input: "Te...
lista = list() while True: num = (int(input('Digite um valor: '))) if num not in lista: lista.append(num) print('Valor adicionado com sucesso....') else: print('Valor duplicado, não vou adicionar....') resp = (str(input('Quer continuar? [S/N] '))).strip()[0] while resp not in...
class Solution: def fizzBuzz(self, n: int) -> list: res = [] maps = {3: "Fizz", 5: "Buzz"} for i in range(1, n + 1): ans = "" for k, v in maps.items(): if i % k == 0: ans += v if not ans: ans = str(i) ...
# # [242] Valid Anagram # # https://leetcode.com/problems/valid-anagram/description/ # # algorithms # Easy (48.99%) # Total Accepted: 255.4K # Total Submissions: 520.2K # Testcase Example: '"anagram"\n"nagaram"' # # Given two strings s and t , write a function to determine if t is an anagram # of s. # # Example 1:...
''' Questions 1. is modulus, add, subtract, square root allowed? Observations 1. define what it means to be a power of 4 - any number of 4s must be multiplied to get that number 2. We do not need to know how many times we need to multiple 4 to get number. Only need to return true or False 3. Multiplying by 4 is the s...
''' Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. set(key, value) - Set or insert the value if the key is not alre...
# http://www.codewars.com/kata/5500d54c2ebe0a8e8a0003fd/ def mygcd(x, y): remainder = max(x, y) % min(x, y) if remainder == 0: return min(x, y) else: return mygcd(min(x, y), remainder)
# Copyright 2016 Nidium Inc. All rights reserved. # Use of this source code is governed by a MIT license # that can be found in the LICENSE file. { 'targets': [{ 'target_name': 'nidium-server', 'type': 'executable', 'product_dir': '<(nidium_exec_path)', 'dependencies': [ ...
# -*- coding: utf-8 -*- """ Created on Tue Oct 20 18:39:06 2020 @author: xyz """ hello = "hello how are you?" splitHello = hello.split() print(splitHello) joinList = " <3 ".join(splitHello) print(joinList)
def print_accuracy(cur_s, cur_ans): cur_true = cur_ans[cur_s] == 1 G_sub = G.subgraph(to_double_format(cur_ans[cur_true].index)) print("components in DESMAN subgraph:", nx.number_weakly_connected_components(G_sub)) right_answers = df_ref[cur_s] == cur_ans[cur_s] print("Accuracy on all edges: %.2f"...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def diameterOfBinaryTree(self, root): """ :type root: TreeNode :rtype: int """ ...
#!/usr/bin/env python3 grid = [[1]] def iter_ring(size): x = size - 1 y = size - 2 while y > 0: yield x, y y -= 1 while x > 0: yield x, y x -= 1 while y < size - 1: yield x, y y += 1 while x < size - 1: yield x, y x += 1 yiel...
"""Syncless: asynchronous client and server library using Stackless Python. started by pts@fazekas.hu at Sat Dec 19 18:09:16 CET 2009 See the README.txt for more information. Please import submodules to get the actual functionality. Example: import socket from syncless import coio s = coio.nbsocket(socket.AF_...
REGIONS = ( (1, "Northeast"), (2, "Midwest"), (3, "South"), (4, "West"), (9, "Puerto Rico and the Island Areas"), ) DIVISIONS = ( (0, "Puerto Rico and the Island Areas"), (1, "New England"), (2, "Middle Atlantic"), (3, "East North Central"), (4, "West North Central"), (5, "...
def foo(x,y=10): z = x * y return z print(foo(10))
# MAIOR E MENOR DA SEQUÊNCIA # Faça um programa que leia o peso de cinco pessoas. No final, mostre qual foi o maior e o menor peso lidos. maior = 0 menor = 0 for pess in range(1, 6): peso = float(input(f'Digite o peso da {pess}º pessoa: ')) if pess == 1: maior = peso menor = peso else: ...
img_enhanc_alg = "" input_img = [] with open("input/day20.txt") as inp: flag = True for vrst in inp: if flag: flag = False img_enhanc_alg = vrst[:-1] elif vrst == "\n": continue else: input_img.append(list(vrst[:-1])) def bin_to_int(b): ...
# # PySNMP MIB module COLUBRIS-SYSTEM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/COLUBRIS-SYSTEM-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:10:01 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- """ .. module:: TODO :platform: Unix :synopsis: TODO. .. moduleauthor:: Aljosha Friemann a.friemann@automate.wtf """ def walk(dictionary, root='.'): for key, value in dictionary.items(): if type(value) is dict: for subkey, subvalue in wal...
# todo: some way to automate/automatically update this algo = dict([ (0, 'Scrypt'), (1, 'SHA256'), (2, 'ScryptNf'), (3, 'X11'), (4, 'X13'), (5, 'Keccak'), (6, 'X15'), (7, 'Nist5'), (8, 'NeoScrypt'), (9, 'Lyra2RE'), (10, 'WhirlpoolX'), (11, 'Qubit'), (1...
def func(a=None, b=None, /): pass func(None, 2) func()
anchor = Input((60, 60, 3), name='anchor') positive = Input((60, 60, 3), name='positive') negative = Input((60, 60, 3), name='negative') a = shared_conv2(anchor) p = shared_conv2(positive) n = shared_conv2(negative) pos_sim = Dot(axes=-1, normalize=True)([a,p]) neg_sim = Dot(axes=-1, normalize=True)([a,n]) loss = La...
# Moving zeros to the end def move_zeros(arr): zero = 0 for elements in range(len(arr)): if arr[elements] != 0 or arr[elements] is False: arr[elements], arr[zero] = arr[zero], arr[elements] zero += 1 return arr x = [0, 1, 0, 3, False, 12, 5, 7, 0 ,12, 2, 3, 4] print(move_z...
""" Today's difficult problem is similar to challenge #64's difficult problem Baseball is very famous in the USA. Your task is write a program that retrieves the current statistic for a requested team. THIS [http://www.baseball-reference.com/] site is to be used for the reference. You are also encouraged to retrieve s...
class Question: def __init__(self,prompt,answer): self.prompt = prompt self.answer = answer
class Singleton(object): def __new__(cls): if not hasattr(cls, 'instance') or not cls.instance: cls.instance = super().__new__(cls) return cls.instance obj1 = Singleton() obj2 = Singleton() print(obj1 is obj2) # True print(obj1 == obj2) # True print(type(obj1) == type(ob...
def magic(): return 'foo' # OK, returns u''' unicode() # Not OK, no encoding supplied unicode('foo') # Also not OK, no encoding supplied unicode('foo' + 'bar') # OK, positional encoding supplied unicode('foo', 'utf-8') # OK, positional encoding and error argument supplied unicode('foo', 'utf-8', 'ignore') # N...
class Script: @staticmethod def main(): crime_rates = [749, 371, 828, 503, 1379, 425, 408, 542, 1405, 835, 1288, 647, 974, 1383, 455, 658, 675, 615, 2122, 423, 362, 587, 543, 563, 168, 992, 1185, 617, 734, 1263, 784, 352, 397, 575, 481, 598, 1750, 399, 1172, 1294, 992, 522, 1216, 815, 639, 1154, 1993, 919, 594, 11...
#__getitem__ not implemented yet #a = bytearray(b'abc') #assert a[0] == b'a' #assert a[1] == b'b' assert len(bytearray([1,2,3])) == 3 assert bytearray(b'1a23').isalnum() assert not bytearray(b'1%a23').isalnum() assert bytearray(b'abc').isalpha() assert not bytearray(b'abc1').isalpha() # travis doesn't like this #as...
"""Advent of Code Day 11 - Hex Ed""" def path(steps_string): """Find how far from the centre of a hex grid a list of steps takes you.""" # Strip and split file into a iterable list steps_list = steps_string.strip().split(',') # Break hexagon neighbours into cube coordinates x = 0 y = 0 z ...
def draw_cube(p): """ Draw green cube with side = 1, then set line color to blue """ p.set('linecolor', 'g') p.vector(0, 1) p.vector(1, 0) p.vector(0, -1) p.vector(-1, 0) p.draw() p.set('linecolor', 'b')
N = int(input()) W = list(map(int, input().split())) diff = [0 for i in range(N-1)] for i in range(N-1): S1 = sum(W[:i+1]) S2 = sum(W[i+1:]) diff[i] = abs(S1 - S2) print(min(diff))
# coding=utf-8 # *** WARNING: this file was generated by crd2pulumi. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** SNAKE_TO_CAMEL_CASE_TABLE = { "api_version": "apiVersion", "container_id": "containerID", "container_statuses": "containerStatuses", "ephemeral_conta...
""" @Author: yanzx @Date: 2021-09-16 08:43:36 @Desc: """
num, rotation = map(int, input().split()) arr = list(map(str, input().split())) if rotation < 0: value = abs(rotation) arr = arr[value:] + arr[:value] if rotation > 0: value = abs(rotation) arr = [arr[(i - value) % len(arr)] for i, x in enumerate(arr)] arr2 = [int(i) for i in arr] for i in arr2: ...
print('='*8,'Super Progressão Aritmética v3.0','='*8) pt = int(input('Digite o primeiro termo da sua PA: ')) r = int(input('Digite a razão da sua PA: ')) t = pt qt = 0 op = 10 print('Sua progressão aritmética fica:') while op != 0: print(t, end = ' => ') t += r qt += 1 op -= 1 if op == 0: p...
class MyClass: def func3(self): pass def func2(self, a): a() def func1(self, a, b): a(b) a = MyClass() a.func1(a.func2, a.func3)
def main(): my_list = [1,"hello",True,4.5] my_dict = {'fistname' : 'luis', 'lastname':'martinez'} super_list = [ {'firstname' : 'luis', 'lastname':'martinez'}, {'firstname' : 'lizette', 'lastname':'martinez'}, {'firstname' : 'dalia', 'lastname':'martinez'} ] for i in super_...
with open('../input.txt','rt') as f: cur_line = 0 cur_shift = 0 answ = 0 tree_map = list(map(lambda line: line.rstrip('\n'), f.readlines())) for line in tree_map: if line[cur_shift%len(tree_map[0])]=='#': answ+=1 cur_line+=1 cur_shift+=3 print(answ)
class IllegalStateException(Exception): """ An error when program enter an unexpected state """ def __init__(self, message): self.message = message
############################################################################################### # 遍历了一遍,官方也给了数学方法 ########### # 时间复杂度:O(log(4)n),n为输入的数值,时间复杂度为以4为底数的log # 空间复杂度:O(1) ############################################################################################### class Solution: def isPowerOfFo...
# -*- coding: utf-8 -*- """ Created on Wed Apr 10 21:40:05 2019 @author: Falble """ def reverse_pair(word_list, word): """Checks whether a reversed word appears in word_list. word_list: list of strings word: string """ rev_word = word[::-1] return in_bisect(word_list, rev_word...
""" Dictionaries containing CAT12 longitudinal segmentation output file names by key. """ #: Output file names by key. SEGMENTATION_OUTPUT = { "surface_estimation": [ "surf/lh.central.{file_name}.gii", "surf/lh.sphere.{file_name}.gii", "surf/lh.sphere.reg.{file_name}.gii", "surf/lh....
# Perform a 75% training and 25% test data split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0) # Fit the random forest model to the training data rf = RandomForestClassifier(random_state=0) rf.fit(X_train, y_train) # Calculate the accuracy acc = accuracy_score(y_test, rf.pr...
''' In this module, we implement a function which gets the intersection of two sorted arrays. ''' def intersection_sorted_arrays(arr_1, arr_2): ''' Return the intersection of two sorted arrays ''' result = [] i,j = 0,0 while i < len(arr_1) and j < len(arr_2): if arr_1[i] == arr_2[j]: result.append(arr_1[...
class User(): def __init__(self, first_name, last_name, phone_number, mail, about_me): self.first_name = first_name self.last_name = last_name self.phone_number = phone_number self.mail = mail self.about_me = about_me def describe_user(self): print(self.first_name...
def greet(): print("Hello") greet() print("------") def add_sub(x, y): c = x + y d = x - y return c, d r1, r2 = add_sub(4, 5) print(r1, r2) print("------") def sum(**three): for i, j in three.items(): print(i, j) sum(Name="'Jatin'", Age=19, Address="Delhi") # def odd_even(odd...
# -*- coding: utf-8 -*- def key_input(): """ Enter key to be used. Don't accept key shorter than 8 bytes. If key is longer than 8 bytes, cut it to 8 bytes. """ while True: key = input("Enter 8 byte key:") if len(key) < 8: print("Key should be 8 bytes long!") ...
FSenterSecretTextPos = (0, 0, -0.25) FSgotSecretPos = (0, 0, 0.46999999999999997) FSgetSecretButton = 0.059999999999999998 FSnextText = 1.0 FSgetSecret = (1.55, 1, 1) FSok1 = (1.55, 1, 1) FSok2 = (0.59999999999999998, 1, 1) FScancel = (0.59999999999999998, 1, 1) LTPDdirectButtonYesText = 0.050000000000000003 LTPDdirect...
n=int(input("enter the number")) x=[] a,b=0,1 x.append(a) x.append(b) if n==0: print(0) else: for i in range(2,n): c=a+b a=b b=c x.append(c) print(x)
# Space: O(1) # Time: O(n) class Solution: def merge(self, intervals): length = len(intervals) if length <= 1: return intervals intervals.sort(key=lambda x: (x[0], x[1])) res = [] for i in range(length): if len(res) == 0: res.append(intervals[i]) ...
x = 0 while x <= 10: print(f" 6 x {x} = {6*x}") x = x + 1
class Node: def __init__(self, value): self.value = value self.next = None class Enumerator: def __init__(self, linked_list): self._current = None self._list = linked_list def get_next(self): if (self._current == None): self._current = self._list._head ...
validSettings = { "password": ".*", "cache": "^\d+$", "allow-force": "^(true|false)$", "allow-user-unregistered": "^(true|false)$", "duration": "^(year|eternity)$", "dark-mode-default": "^(true|false)$", "show-commit-mail": "^(true|false)$" }
n = int(input()) for i in range(n): (x, y) = map(int, input().split(' ')) soma = 0 if x % 2 == 0: x += 1 j = 0 while j < y * 2: soma += x + j j += 2 print(soma)
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # 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...
""" https://leetcode.com/problems/flood-fill/ An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535). Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill" the image....
scores = [ 9.5, 8.5, 7.0, 9.5, 10, 6.5, 7.5, 9.0, 10 ] sum = 0 for score in scores: sum += score average = sum/(len(scores)) print('Average Scores: ' + str(average))
""" Utilities for handling CoMetGeNe trails. Version: 1.0 (May 2018) License: MIT Author: Alexandra Zaharia (contact@alexandra-zaharia.org) """ def span(lst): """Returns the number of unique vertices in the input list. :param lst: list of vertices in a graph or of tuples of vertices (i.e. arcs) in i...
numero = 4 fracao = 6.1 online = False texto = "Armando" if numero == 5: print("Hello 5") elif numero == 4 or online: print("Hello 4") else: print("Final") print("Ola estou online" if online else "Ola estou offline")
""" 这里是变量文件,为服务器和客户端提供参数 """ host = "127.0.0.1" # 主机地址 port = 8080 # 端口号
dna_seq1 = 'ACCT GATC' a_count = 0 c_count = 0 g_count = 0 t_count = 0 valid_count = 0 for nucl in dna_seq1: if nucl == 'G': g_count += 1 valid_count += 1 elif nucl == 'C': c_count += 1 valid_count += 1 elif nucl == 'A': a_count += 1 valid_count += 1 el...
def min_max_sum_function(sequence): sequence_int = list(map(int, sequence)) min_value = min(sequence_int) max_value = max(sequence_int) sum_value = sum(sequence_int) print (f"The minimum number is {min_value}") print(f"The maximum number is {max_value}") print(f"The sum number is: {sum_value...
# -*- coding: utf-8 -*- """ ----------Phenix Labs---------- Created on Fri Jan 29 14:07:35 2021 @author: Gyan Krishna Topic: """ class Rectangle: def __init__(self, l, b): self.length = l self.breadth = b def showArea(self): area = (self.length * self.breadth) print("area = ",...
print("Verificação de uma data") dia = int(input("Digite o dia no formato dd: ")) mes = int(input("Digite o mês no formato mm: ")) ano = int(input("Digite o dia no formato aaaa: ")) validação = False if mes == 1 or mes == 3 or mes == 5 or mes == 7 or mes == 8 or mes == 10 or mes == 12: if dia <= 31 and dia >= 1: ...
s1 = float(input('Primeiro segmento: ')) s2 = float(input('Segundo segmento: ')) s3 = float(input('Terceiro segmento: ')) if s1<s2+3 and s2<s1+s3 and s3<s1+s2: print('Os segmentos acima PODEM formar um triângulo!') else: print('Os segmentos acima NÃO conseguem formar um triângulo!')