content stringlengths 7 1.05M |
|---|
"""
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Solution:
1. Sort
... |
SHORT_DESCRIPTION = "Sorter organises/sorts files using a customised search function to group those that have similar characteristics into a single folder. Similar characteristics include file type, file name or part of the name and file category. You can put all letters documents into one folder, all images with the w... |
n=int(input ('veverite'))
if n %2==0: print ('par')
else: print ('impar')
print('par' if n%2==0 else 'impar')
|
# pylint: disable=missing-class-docstring, disable=missing-function-docstring, missing-module-docstring/
#$ header class Point(public)
#$ header method __init__(Point, double, double)
#$ header method __del__(Point)
#$ header method translate(Point, double, double)
class Point(object):
def __init__(self, x, y):
... |
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'leftPLUSMINUSleftTIMESDIVIDEleftPOWERrightUMINUSCOMMA DATA DEF DIM DIVIDE END EQUALS FLOAT FOR GE GOSUB GOTO GT ID IF INTEGER LE LET LIST LPAREN LT MINUS NE NEW NEWLINE... |
#-*- coding: utf8 -*-
class P3PMiddleware(object):
def process_response(self, request, response):
response['P3P'] = 'CP="CAO PSA OUR"'
return response
|
N, M = 510, 10010
big_num = 0x3F3F3F3F
dist = [big_num] * N
def bf():
# 初始化
dist[1] = 0
# 遍历k次,更新所有边
for _ in range(k):
bak = dist[:] # 备份一下距离,防止被错误更新(copylist的方式还有 bak=list(dist))
for j in range(m):
a, b, w = edge[j]
dist[b] = min(dist[b], bak[a] + w)
# ... |
#!/usr/bin/env python
# Exercicio 3.3 - Complete a tabela a seguir utilizando a = True, b = false e c = True
print (' ')
a = True
b = False
c = True
# Expressões e resultados
a1 = a and a
b1 = b and b
c1 = not c
d1 = not b
e1 = not a
f1 = a and b
g1 = b and c
h1 = a or c
i1 = b or c
j1 = c or a
k1 = c or b
l1 = c o... |
# Copyright 2018 Databricks, Inc.
VERSION = '0.7.0.dev'
|
#!/usr/bin/env python
'''
This script prints Hello World!
'''
print('Hello, World!')
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def main():
""" Повторите строку столько раз, сколько в ней символов. """
# Code goes over here.
a = str(input())
for i in range(len(a)):
print(a)
return 0
if __name__ == "__main__":
main()
|
__all__ = ["InvalidECFGFormatException"]
class InvalidECFGFormatException(Exception):
pass
|
r=int(input('banyaknya angka:'))
data=[]
for i in range (r): #v
n=int(input("Enter Integer {}:".format(i+1))) #v
data.append(n) #v
m=10**(r-1)
for i in range (r):
y=int(data[i]*m)
print(y)
m=m/10
#print(r);
|
def define_display_nodes(tree,nodemap,unscoped_vectors=False,looped_definition=False):
if unscoped_vectors:
s = ''
else:
s = '\t\t\tstd::vector<MPILib::NodeId> display_nodes;\n'
display_nodes = tree.findall('.//Display')
for dn in display_nodes:
node_id = str(nodemap[dn.attrib[... |
def factorial(n):
if n==0:
return 1
else:
return factorial(n-1)*n
print(factorial(80))
|
# two_tasks.py
def task_reformat_temperature_data():
"""Reformats the raw temperature data file for easier analysis"""
return {
'file_dep': ['UK_Tmean_data.txt'],
'targets': ['UK_Tmean_data.reformatted.txt'],
'actions': ['python reformat_weather_data.py UK_Tmean_data.txt > UK_... |
#Make sure that we handle keyword-only arguments correctly
def f(a, *varargs, kw1, kw2="has-default"):
pass
#OK
f(1, 2, 3, kw1=1)
f(1, 2, kw1=1, kw2=2)
#Not OK
f(1, 2, 3, kw1=1, kw3=3)
f(1, 2, 3, kw3=3)
#ODASA-5897
def analyze_member_access(msg, *, original, override, chk: 'default' = None):
pass
def ok(... |
class Parser():
def __init__(self, config):
self._config_args = config
@property
def experiment_args(self):
return self._config_args["Experiment"]
@property
def train_dataset_args(self):
return self._config_args["Dataset - metatrain"]
@property
def valid_dataset_ar... |
# -*- coding: utf-8 -*-
"""
__author__ = "Jani Yli-Kantola"
__copyright__ = ""
__credits__ = ["Harri Hirvonsalo", "Aleksi Palomäki"]
__license__ = "MIT"
__version__ = "1.3.0"
__maintainer__ = "Jani Yli-Kantola"
__contact__ = "https://github.com/HIIT/mydata-stack"
__status__ = "Development"
"""
schema_sl_init_sink = {... |
'''
According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."
Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizonta... |
class X:
def __init__(self,x):
print("Inside X ", x)
class Y:
def __init__(self):
print("Inside Y")
class Z(X,Y):
def __init__(self):
super().__init__(10)
print("Inside Z")
obj = Z()
|
# -*- coding: utf-8 -*-
valor = float(input())
if 0 < valor <= 25:
print('Intervalo [0, 25]')
elif 25 < valor <= 50:
print('Intervalo (25, 50]')
elif 50 < valor <= 75:
print('Intervalo (50, 75]')
elif 75 < valor <= 100:
print('Intervalo (75, 100]')
else:
print('Fora de intervalo')
|
"""
Consider the following:
A string,
, of length where
.
An integer,
, where is a factor of
.
We can split
into subsegments where each subsegment, , consists of a contiguous block of characters in . Then, use each to create string
such that:
The characters in
are a subsequence of the characters in
... |
# Write your code below this line 👇
def prime_checker(number):
prime = True
for a in range(2, number):
if number % a == 0:
prime = False
if prime == True:
print(f"{number} is a prime number")
else:
print(f"{number} isn't a prime number")
# Write your code above thi... |
# -*- coding: utf-8 -*-
"""
Transcriptions and targets for the parser
"""
# Example (1) most simple full sign transcription:
# one dominant hand, one orientation (must have two symbols), one location,
# one movement
{
" ": # segmented into types
{
"symmetry": "",
"dominant_hand": "", # hamfinger2... |
# SPDX-FileCopyrightText: Copyright (C) 2020-2021 Ryan Finnie
# SPDX-License-Identifier: MIT
def numfmt(
num,
fmt="{num.real:0.02f} {num.prefix}",
binary=False,
rollover=1.0,
limit=0,
prefixes=None,
):
"""Formats a number with decimal or binary prefixes
num: Input number
fmt: Form... |
# Aula 13 - Desafio 47: Contagem de numeros pares
# Mostrar na tela todos os numeros pares entre 1 e 50
print('Entre 1 e 50, sao numeros pares:')
for n in range(2, 51, 2):
print(n, end=' ')
|
word1=input()
word2=input()
dict={}
alphabet="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
for char in alphabet:
dict[char]=0
for ch in word1:
dict[ch]+=1
for ch in word2:
dict[ch]-=1
flag=False
sum=0
for char in dict:
count=dict[char]
sum+=count
if count == 1:
flag=True
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Source code meta data
__author__ = 'Dalwar Hossain'
__email__ = 'dalwar.hossain@protonmail.com'
|
tm20 = toi = h = 0
print('-' * 25)
print(' CADASTRANDO PESSOAS ')
print('-' * 25)
while True:
id = int(input('digite a idade '))
sex = ' '
while sex not in 'MF':
sex = str(input('digite o sexo')).upper()
if id >= 18:
toi += 1
if sex == 'M':
h += 1
if sex == 'f' and id <... |
# vim: set encoding=utf-8
# Copyright (c) 2016 Intel Corporation
#
# 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 require... |
# De uitwerking van 4-autoencoder.py moet hiervoor gedraaid worden!
voorspeller = tf.keras.models.Sequential([
tf.keras.layers.Dense(200, activation=tf.nn.relu),
tf.keras.layers.Dense(50, activation=tf.nn.relu),
tf.keras.layers.Dense(50, activation=tf.nn.relu),
tf.keras.layers.Dense(10, activation=tf.nn.softma... |
# -*- coding: utf-8 -*-
u"""
Levenshtein Distance
The Levenshtein distance between two words is the minimal number of
edits that turn one word into the other. Here, "edit" means a
single-letter addition, single-letter deletion, or exchange of a
letter with another letter.
http://en.wikipedia.org/wiki/Levenshtein_dist... |
# Time: O(logn)
# Space: O(1)
class Solution(object):
def fixedPoint(self, A):
"""
:type A: List[int]
:rtype: int
"""
left, right = 0, len(A)-1
while left <= right:
mid = left + (right-left)//2
if A[mid] >= mid:
right = mid-1
... |
# -*- coding: utf-8 -*-
def get_m2_name(self):
"""Return the name of the current area unit
Parameters
----------
self : Unit
A Unit object
Returns
-------
unit_name : str
Name of the current unit
"""
if self.unit_m2 == 1:
return "mm²"
else:
ret... |
# model settings
model = dict(
type='ImageClassifier',
pretrained=None,
backbone=dict(
type='OmzBackboneCls',
mode='train',
model_path='public/mobilenet-v2/FP32/mobilenet-v2.xml',
last_layer_name='relu6_4',
normalized_img_input=True
),
neck=dict(
type=... |
class Environment(object):
def __init__(self):
pass
def act(self, state, action):
pass
def end_state(self, state):
return True
def reset(self):
pass
def available_actions(self):
return None
|
class NodeCalculator:
@staticmethod
def calculate_node_size(node, relationships):
linked_tables = list()
size = 0
for table_key, table_value in relationships.items():
if table_key == node:
for table in relationships[table_key]:
linked_ta... |
# Question(#1143): Given two strings text1 and text2, return the length of their longest common subsequence.
# Solution: Use the longest common susequence dynamic programming algorithm
def longestCommonSubsequence(text1: str, text2: str) -> int:
grid = [[0 for _ in range(len(text2)+1)] for _ in range(len(text1)+1)... |
"""
gnmi_tools - Basic GNMI operations on a device
"""
__copyright__ = "Copyright (c) 2020 Cisco Systems, Inc. and/or its affiliates"
__version__ = "0.1"
__author__ = "Marcelo Reis"
__email__ = "mareis@cisco.com"
__url__ = "https://github.com/reismarcelo/gnmi_hello"
|
class Setting:
""" Сущность: данные настроек """
def __init__(self, **kwargs):
self.day_change_time = kwargs.get('day_change_time')
self.hello_message = dict()
self.memo = dict()
self.hello_message['EN'] = kwargs.get('hello_message_EN')
self.hello_message['RU'] = kwargs.g... |
print("Let's do Factorial") #printing the operation what we are performing
def factorial(number): #defining the factorial method
result = 1 # result is intially defined with 1. if we define initially with ... |
name = "glew"
version = "2.1.0"
authors = [
"Milan Ikits",
"Marcelo Magallon",
"Nigel Stewart"
]
description = \
"""
The OpenGL Extension Wrangler Library (GLEW) is a cross-platform open-source C/C++ extension loading library.
"""
requires = [
"cmake-3+",
"gcc-6+"
]
variants = [
... |
#!/usr/bin/env python
include = "$chrs".replace("[", "").replace("]", "").replace(" ", "").split(",")
ref = "$reference"
with open(ref) as ifh, open("include.bed", "w") as ofh:
for line in ifh:
toks = line.strip().split("\\t")
if toks[0] in include:
print(toks[0], 0, toks[1], sep="\\t"... |
# Modify the program to show the numbers from 50 to 100
x=50
while x<=100:
print(x)
x=x+1 |
# Number of queens
print("Enter the number of queens")
N = int(input())
# chessboard
# NxN matrix with all elements 0
board = [[0]*N for _ in range(N)]
def is_attack(i, j):
# checking if there is a queen in row or column
for k in range(0, N):
if board[i][k] == 1 or board[k][j] == 1:
... |
class Device(object):
"""Device.
:param id: Unique identifier for the device.
:type id: str
:param name: The name of the device.
:type name: str
"""
def __init__(self, data=None):
if data is None:
data = {}
self.id = data.get('id', None)
self.name = dat... |
#
# @lc app=leetcode id=297 lang=python3
#
# [297] Serialize and Deserialize Binary Tree
#
# https://leetcode.com/problems/serialize-and-deserialize-binary-tree/description/
#
# algorithms
# Hard (46.18%)
# Likes: 2721
# Dislikes: 136
# Total Accepted: 300.9K
# Total Submissions: 651K
# Testcase Example: '[1,2,3... |
start_inventory = 20
num_items = start_inventory
while num_items > 0:
print("We have " + str(num_items) + " items in inventory.")
user_purchase = input("How many would you like to buy? ")
if int(user_purchase) > num_items:
print("Not Enough Stock")
else:
num_items = num_items... |
#AULA 7: OPERADORES ARITMÉTICOS
nome = input('Qual é o seu nome?\n')
print('Prazer em te conhecer, {:20}.' .format(nome))
#Com :20, posso fazer 20 espaços (centralizado).
#Além disso, posso informar a direção desses espaços com :> (direita) ou :< (esquerda).
n1 = int(input('Um valor: '))
n2 = int(input('Outro número:... |
# Users: Make a class called User. Create two attributes called first_name and last_name,
# and then create several other attributes that are typically stored in a user profile.
# Make a method called describe_user() that prints a summary of the user’s information.
# Make another method called greet_user() that pri... |
first_list = range(11)
second_list = range(1,12)
ziplist = list(zip(first_list, second_list))
def square(a, b):
return (a*a) + (b*b) + 2 * a * b
# output = [square(item[0], item[1]) for item in ziplist]
output = [square(a, b) for a, b in ziplist]
print(output)
def square2(pair):
a = pair[0]
b = pair[1]
... |
class Quest:
def __init__(self, dbRow):
self.id = dbRow[0]
self.name = dbRow[1]
self.description = dbRow[2]
self.objective = dbRow[3]
self.questType = dbRow[4]
self.category = dbRow[5]
self.location = dbRow[6]
self.stars = dbRow[7]
self.zenny = dbRow[8]
def __repr__(self):
return f"{self.__dict... |
r"""
cgtasknet is a library for training spiking neural
networks with cognitive tasks
"""
|
termination = 4000000
previous = 1
current = 2
total = 2
while(True):
new = current+ previous
previous = current
current = new
if(current >= termination):
break
if(current % 2 == 0):
total = total + current
print(total)
|
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... |
__inner_signs__ = ['{', '}', '[', ']', '(', ')', ',', '', ':']
class __Str:
"""
the class contain string methods
"""
@staticmethod
def space_encoder(_str: str):
"""
will encode spaces inside list in string.
:param _str: list in string
:return: return encoded string
... |
def assign_ROSCO_values(wt_opt, modeling_options, control):
# ROSCO tuning parameters
wt_opt['tune_rosco_ivc.PC_omega'] = control['pitch']['PC_omega']
wt_opt['tune_rosco_ivc.PC_zeta'] = control['pitch']['PC_zeta']
wt_opt['tune_rosco_ivc.VS_omega'] = control['torque']['VS_omega']
wt_o... |
# Tuples
# Assignment 1
tuple_numbers = (1, 2, 3, 4, 5)
tuple_groceries = ('coconuts', 'bananas', 'onions', 'spinach', 'tomatoes', 'cilantro', 'milk')
groceries_inventory = ('coconuts', 'tomatoes', 'onions', 'coconuts', 'bananas', 'onions', 'spinach', 'tomatoes', 'cilantro', 'milk', 'spinach', 'tomatoes', 'cilantro', ... |
class QueryToken:
"""A placeholder token for dry-run query output"""
def __str__(self) -> str:
return "?"
def __repr__(self) -> str:
return "?"
|
class Solution:
def minMeetingRooms(self, intervals: list[list[int]]) -> int:
start = sorted([i[0] for i in intervals])
end = sorted(i[1] for i in intervals)
result = count = 0
s, e = 0, 0
while s < len(intervals):
if start[s] < end[e]:
s += 1
... |
def sum_multidimensional_list_v1(lst):
sum_nums = 0
for row in range(len(lst)):
for col in range(len(lst[row])):
sum_nums += lst[row][col]
return sum_nums
def sum_multidimensional_list_v2(lst):
sum_nums = 0
for row in lst:
for col in row:
sum_nums += col
... |
__version_info__ = ('3', '5', '1')
__version__ = '.'.join(__version_info__)
class TwilioException(Exception):
pass
class TwilioRestException(TwilioException):
def __init__(self, status, uri, msg="", code=None):
self.uri = uri
self.status = status
self.msg = msg
self.code = c... |
#!/usr/bin/env python3
#-*-coding:UTF-8-*-
def CinDico(caractere, dictionnaire):
"""
Fonction permettant de détecter la présence d'un code dans le dictionnaire construit par Decompress.
:param caractere: Paramètre correspondant au code d'un caractère ou d'une suite de caractères compressé.
:... |
"""
URL: https://codeforces.com/problemset/problem/112/A
Author: Safiul Kabir [safiulanik at gmail.com]
"""
s1 = input().lower()
s2 = input().lower()
if s1 == s2:
print(0)
elif s1 < s2:
print(-1)
else:
print(1)
|
###exercicio 50
s = 0
for c in range (0, 6):
n = int(input('Digite um numero: '))
if n%2 == 0:
s += n
print ('{}'.format(s))
print ('Fim!!!') |
valor1 = 16
valor2 = 61
if valor1 > valor2:
print('{} é maior.'.format(valor1))
else:
print('{} é maior.'.format(valor2)) |
total = 0
for number in range(1, 10 + 1):
print(number)
total = total + number
print(total)
|
#Using the range function we create a list of numbers from 0 to 99 https://docs.python.org/2/library/functions.html#range
#Each number in the list is FizzBuzz tested
#If the number is a multiple of 3 and a multiple of 5 - print "FizzBuzz"
#If the number is only a multiple of 3 - print "Fizz"
#If the number is onl... |
'''面试题55-2:平衡二叉树
输入一棵二叉树的根节点,判断该树是不是平衡二叉树。
如果某二叉树中任意节点的左、右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
'''
class Node(object):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
class BST(object):
def __init__(self):
self.root = None
... |
class Foo:
[mix_Case, var2] = range(2)
def bar():
'''
>>> class Foo():
... mix_Case = 0
'''
pass
|
n = 0
while True:
n = int(input('Digite o número que deseja ver a tabuada (negativo para parar): '))
if n < 0:
print('-=' * 40)
print('Programa de tabuada encerrando. Volte sempre!')
break
for i in range(1,11):
print(f'{n} x {i} = {i*n}')
print('-='*40)
|
""" TEMPORARY FIX """
def pause(*args):
print("TRYING TO PAUSE")
def stop(*args):
print("TRYING TO STOP") |
def print_to_file(file, cases):
print(len(cases), file=file)
for arr in cases:
print(len(arr), file=file)
print(*arr, file=file)
|
# Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre a sua média
print('***Calculadora de Notas***\n')
n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
nf = (n1+n2)/2
print('-'*20)
print('A média do aluno é {:.1f}.'.format(nf))
if (nf>=5):
print... |
FEATURES = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": [
[-122.3141965, 47.6598870],
[-122.3132940, 47.6598762],
],
... |
#
# Nidan
#
# (C) 2017 Michele <o-zone@zerozone.it> Pinassi
class Config: pass
|
class CyclicDependencyError(ValueError):
pass
def topological_sort_as_sets(dependency_graph):
"""
Variation of Kahn's algorithm (1962) that returns sets.
Take a dependency graph as a dictionary of node => dependencies.
Yield sets of items in topological order, where the first set conta... |
#Faça um program que leia o nome completo de uma pessoa, mostrando em seguinda o primeiro e último nome separados.
#EX: Ana Maria de Sousa/ primeiro = Ana/ segundo = Sousa
nome = str(input('Digite seu nome completo: ')).strip().upper()
nomes = nome.split()
print('Muito prazer em te conhecer!')
print('Seu primeiro nome ... |
# Given a binary matrix A, we want to flip the image horizontally, then invert
# it, and return the resulting image.
# To flip an image horizontally means that each row of the image is reversed.
# For example, flipping [1, 1, 0] horizontally results in [0, 1, 1].
# To invert an image means that each 0 is replaced by ... |
'''
This problem was asked by Google.
Given two singly linked lists that intersect at some point, find the intersecting node. The lists are non-cyclical.
For example, given A = 3 -> 7 -> 8 -> 10 and B = 99 -> 1 -> 8 -> 10, return the node with value 8.
In this example, assume nodes with the same value are the exact ... |
def lazyproperty(fn):
attr_name = '__' + fn.__name__
@property
def _lazyprop(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, fn(self))
return getattr(self, attr_name)
return _lazyprop
|
stud = {
'Madhan':24,
'Raj':30,
'Narayanan':29
}
for s1 in stud.keys():
print(s1)
phone_numbers = {"John Smith": "+37682929928", "Marry Simpons": "+423998200919"}
for key,value in phone_numbers.items():
print("{} has phone number {}".format(key,value))
names = {
'Girija':53,
'Subramania... |
"""load gtest third party"""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def repo():
http_archive(
name = "com_google_googletest",
sha256 = "353571c2440176ded91c2de6d6cd88ddd41401d14692ec1f99e35d013feda55a",
urls = ["https://github.com/google/googletest/archive/refs... |
# -*- coding: utf-8 -*-
latest_posts = db(Posts).select(orderby=~Posts.created_on, limitby=(0,5))
most_liked = db(Posts).select(orderby=~Posts.likes, limitby=(0,5))
all_categories = db(Categories).select(limitby=(0,5)) |
spam = ['cat', 'bat', 'rat', 'elephant']
print(spam[2])
spam2 = [['fish', 'shark'], 'bat', 'rat', 'elephant']
print(spam2[0])
print(spam2[0][1])
spam[2:4] = ['CAT', 'MOOSE', 'BEAR']
print(spam)
del spam[2]
print(spam)
print('MOOSE' in spam)
# Iterate over lists by item or index
for item in spam:
print(item)... |
class Node():
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree():
def __init__(self, root):
self.root = Node(root)
def print_tree(self, traversal_type):
if traversal_type == "preorder":
return self.preord... |
def pattern(n):
if n==0:
return ""
res=[]
for i in range(n-1):
res.append(" "*(n-1)+str((i+1)%10))
temp="".join(str(i%10) for i in range(1, n))
res.append(temp+str(n%10)+temp[::-1])
for i in range(n-1, 0, -1):
res.append(" "*(n-1)+str(i%10))
return "\n".join(res)+"\n... |
# ------------------------------
# 63. Unique Paths II
#
# Description:
# Follow up for "Unique Paths":
#
# Now consider if some obstacles are added to the grids. How many unique paths would there be?
# An obstacle and empty space is marked as 1 and 0 respectively in the grid.
# For example,
# There is one obstacle i... |
lista = [3, 41, 12, 9, 74, 15]
maior_numero = None
for x in lista:
if maior_numero is None or x > maior_numero:
maior_numero = x
print("A lista é composta por estes números: " + str(lista))
print("O maior número da lista é o " + str(maior_numero) + ".")
|
class Config:
gateId = 0
route = ""
port = "COM3"
def __init__(self, gateId, route):
self.gateId=gateId
self.route=route
|
# linked list class
# class for "node" or in common terms "element"
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None # points to the head of the linked list
def insert_at_begining(self, d... |
"""
https://www.youtube.com/watch?v=UflHuQj6MVA&list=RDCMUCnxhETjJtTPs37hOZ7vQ88g&index=2
https://www.geeksforgeeks.org/longest-palindrome-substring-set-1/
"""
def longest_palindromic_substring(s):
n = len(s)
table = [[0 for x in range(n)] for y in range(n)]
# all strings of length 1 are palindrome
s... |
n = int(input())
matrix = [list(map(int, input().split(" "))) for _ in range(n)]
total = 0
for i in range(n):
value = matrix[i][i]
total += value
print(total) |
PROBLEM_PID_MAX_LENGTH = 32
PROBLEM_TITLE_MAX_LENGTH = 128
PROBLEM_SECTION_MAX_LENGTH = 4096
PROBLEM_SAMPLE_MAX_LENGTH = 1024 |
__author__ = 'shukkkur'
'''
https://codeforces.com/problemset/problem/200/B
'''
n = int(input())
props = list(map(int, input().split()))
total = sum([p/100 for p in props])
print((total/n)*100)
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
prev = None
curr = head
length = 0
while curr:
curr = cur... |
#!/usr/bin/env python3
"""
Initializaiton
+--------------------------------------------------------------------------+
| Copyright 2019 St. Jude Children's Research Hospital |
| |
| Licensed under a modified version of the Apa... |
students = []
class Student:
# Python 没有权限控制, 所有的方法都是 public ,可以通过规范命名去说明
# class property
school_name = "SHICHENGZHOGNXUE"
def __init__(self, name, stu_id=110):
# instance property
self.name = name
self.stu_id = stu_id
students.append(self)
def get_name_capita... |
# Learn python - Full Course for Beginners [Tutorial]
# https://www.youtube.com/watch?v=rfscVS0vtbw
# freeCodeCamp.org
# Course developed by Mike Dane.
# Exercise: While Loop
# Date: 30 Aug 2021
# A while loop is a structure that allows code to be executed multiple times until condition is false
# a loop condition , ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.