content stringlengths 7 1.05M |
|---|
class Person:
def say_hi(self):
print('Hello, how are you?')
vinit = Person() # object created
vinit.say_hi() # object calls class method.
|
# Copyright 2020 The TensorFlow Authors. 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 required by applica... |
"""Module applying the nonlocal scattering matrix method.
This method is theoretically described in ... Here it is applied to
the calculation of reflectance and transmittance of planar heterostructures.
"""
__version__ = "0.1.0"
|
# Implementation of the queue data structure.
# A list is used to store queue elements, where the tail
# of the queue is element 0, and the head is
# the last element
class Queue:
'''
Constructor. Initializes the list items
'''
def __init__(self):
self.items = []
'''
Returns true... |
filename = 'programing.txt'
with open(filename, 'a') as f:
f.write('I also like data science\n')
f.write('I\'m James Noria.\n') #add new things
|
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = ""
services_str = "/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/RestartController.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_... |
#-- THIS LINE SHOULD BE THE FIRST LINE OF YOUR SUBMISSION! --#
def is_divisible_by(n, numbers):
if not numbers or 0 in numbers:
raise ValueError
for num in numbers:
if n % num != 0:
return False
return True
#-- THIS LINE SHOULD BE THE LAST LINE OF YOUR SUBMISSION! ---#
#... |
registry_repositories = [
{
"registry_name": "resoto-do-plugin-test",
"name": "hw",
"tag_count": 1,
"manifest_count": 1,
"latest_manifest": {
"digest": "sha256:2ce85c6b306674dcab6eae5fda252037d58f78b0e1bbd41aabf95de6cd7e4a9e",
"registry_name": "resoto-... |
# encoding: utf-8
# module System.Diagnostics.CodeAnalysis calls itself CodeAnalysis
# from mscorlib,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089,System,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089
# by generator 1.145
""" NamespaceTracker represent a CLS namespace. """
# no i... |
def OnEditApart(s1, s2):
if abs(len(s1) - len(s2)) > 1:
return False
if s1 in s2 or s2 in s1:
return True
mismatch = 0
for i in range(len(s1)):
if s1[i]!=s2[i]:
mismatch+=1
if mismatch > 1:
return False
return True
|
S = list(map(str, input()))
if '7' in S:
print('Yes')
else:
print('No') |
"""
ENUNCIADO DO EXERCICIO
Crie um programa que leia o nome de uma cidade e diga se ela começa ou não com o nome 'SANTO'
"""
c = str(input('Digite o nome de uma cidade: ')).strip()
cc = c.lower()
cc = cc.split()
print('santo' in cc[0])
|
class Instruction:
'''Clase abstracta'''
class Select(Instruction):
'''
Select recibe un array con todas los parametros
'''
def __init__(self, instrs) :
self.instrs = instrs
class From(Instruction):
'''
FROM recibe una tabla en la cual buscar los datos
'''
... |
# python3
class JobQueue:
def read_data(self):
self.num_workers, m = map(int, input().split())
self.array = [[0]*2 for i in range(self.num_workers)]
self.jobs = list(map(int, input().split()))
assert m == len(self.jobs)
self.workers = [None] * len(self.jobs)
self.sta... |
# https://leetcode.com/problems/queue-reconstruction-by-height
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people.sort(key=lambda x: (-x[0], x[1]))
output = []
for p in people:
output.insert(p[1], p)
return output
|
# Have the function KaprekarsConstant(num) take the num parameter being passed which will be a 4-digit number with at least two distinct digits. Your program should perform the following routine on the number: Arrange the digits in descending order and in ascending order (adding zeroes to fit it to a 4-digit number), a... |
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.read = 0
def describle(self):
long_name = str(self.year) + " " + self.make + " " + self.model + " "
return long_name.title()
def read(self):
p... |
try:
f = open("textfile", "r")
f.write("write a TEST LINE ")
except TypeError:
print("There was a type error")
except OSError:
print("Hey you have an OS error")
except:
print("All other exception")
finally:
print("I always run") |
def selectionSort(alist):
for slot in range(len(alist) - 1, 0, -1):
iMax = 0
for index in range(1, slot + 1):
if alist[index] > alist[iMax]:
iMax = index
alist[slot], alist[iMax] = alist[iMax], alist[slot]
|
src = Glob('*.c')
component = aos_component('libid2', src)
component.add_global_includes('include')
component.add_comp_deps('security/plat_gen', 'security/libkm')
component.add_global_macros('CONFIG_AOS_SUPPORT=1')
component.add_prebuilt_libs('lib/' + component.get_arch() + '/libid2.a')
|
my_list = [1, 2, 3, 4, 5]
def sqr(x):
return x ** 2;
def map(list_, f):
return [f(x) for x in list_]
def map_iter(list_, f):
new_list = []
for i in list_:
new_list.append(f(i))
return new_list
|
def twoStrings(s1, s2):
"""Compares two strings to find matching substring."""
for i in s1:
if i in s2:
return "YES"
return "NO"
def twoStrings(s1, s2):
"""Compares two strings to find matching substring using set."""
a = set(s1) if len(s1 >= s2) else set(s2)
for i in s1:
... |
# Faça um programa que tenha uma tupla única com nomes de produtos e seus respectivos preços na seqência
# no final mostre uma listagem e preços organizando os dados de forma tabular
print('=' * 40)
print('{:^40}'.format('LISTAGEM DE PREÇOS'))
p = ('lapis', 1.75,
'borracha', 2,
'caderno', 15.90,
'est... |
# https://www.codewars.com/kata/returning-strings/train/python
# My solution
def greet(name):
return "Hello, %s how are you doing today?" % name
# ...
def greet(name):
return f'Hello, {name} how are you doing today?'
# ...
def greet(name):
return "Hello, {} how are you doing today?".format(name)
... |
'''
Desenvolva um programa que leia o
nome, idade e sexo de quatro pessoas.
No final do programa, mostre:
- A média de idade do Grupo
- Qual é o nome do homem mais velho
- Quantas Mulheres têm menos de 20 anos.
'''
nome = ''
idade = 0
sexo = ''
totalIdades = 0
media = 0
oldMan = 0
nomeOldMan = ''
qtdMulheresMenores ... |
def envelopeHiBounds(valueList, wnd):
return envelopeBounds(valueList, wnd, 0.025)
def envelopeLoBounds(valueList, wnd):
return envelopeBounds(valueList, wnd, 0.025)
def envelopeBounds(valueList, wnd, ratio):
return valueList.ewm(wnd).mean() * (1 + ratio)
|
# Напишіть програму, яка зчитує ціле число і виводить текст, аналогічний наведеному в прикладі (прогалини важливі!). Не можна користуватися конкатенацієй рядків (використовуйте print з декількома параметрами).
## Формат введення
# Вводиться ціле число (гарантується, що число знаходиться в діапазоні від -1000 до +1000... |
# test lists
assert 3 in [1, 2, 3]
assert 3 not in [1, 2]
assert not (3 in [1, 2])
assert not (3 not in [1, 2, 3])
# test strings
assert "foo" in "foobar"
assert "whatever" not in "foobar"
# test bytes
# TODO: uncomment this when bytes are implemented
# assert b"foo" in b"foobar"
# assert b"whatever" not in b"foobar... |
def question(s):
exs = s
# 重複しないところから変換する
exs = exs.replace("eraser", "")
exs = exs.replace("erase", "")
exs = exs.replace("dreamer", "")
exs = exs.replace("dream", "")
return "YES" if (exs == "") else "NO"
|
# coding=utf-8
__author__ = 'mlaptev'
if __name__ == "__main__":
matrix = []
line = input()
while line != 'end':
matrix.append([int(i) for i in line.split()])
line = input()
for i in range(len(matrix)):
for j in range(len(matrix[i])):
print(matrix[i-1][j] + matrix[(i... |
"""
Error module holds all custom errors
for the scraper class
"""
class InvalidWebsite(Exception):
"""
An Invalid website was proided to the scraper
"""
pass
|
"""
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
... |
# -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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... |
load("@io_bazel_rules_closure//closure:defs.bzl", "closure_js_binary", "closure_js_library")
def _internal_closure_fragment_export_impl(ctx):
ctx.actions.write(
output = ctx.outputs.out,
content = """
goog.require('%s');
goog.exportSymbol('_', %s);
""" % (ctx.attr.module, ctx.attr.function),
)
... |
"""Rio-Cogeo Errors and Warnings."""
class DeprecationWarning(UserWarning):
"""Rio-cogeo module deprecations warning."""
class LossyCompression(UserWarning):
"""Rio-cogeo module Lossy compression warning."""
class IncompatibleBlockRasterSize(UserWarning):
"""Rio-cogeo module incompatible raster block/... |
print('Crie sua P.A. de 10 termos')
n1 = int(input('Digite o primeiro termo da P.A.: '))
r = int(input('Digite a razão: '))
print('A P.A. é (', end='')
for c in range(n1, r*10, r):
print('{}'.format(c), end='')
print(', ' if c < r*9 else '', end='')
print(')')
|
"""539. Move Zeroes"""
class Solution:
"""
@param nums: an integer array
@return: nothing
"""
def moveZeroes(self, nums):
# write your code here
## Practice:
l = 0
r = 0
n = len(nums)
while r < n:
if r < n and nums[r] != 0:
... |
def nonstring_iterable(obj):
try: iter(obj)
except TypeError: return False
else: return not isinstance(obj, basestring)
|
"""Faça um programa que leia uma frase pelo teclado e mostre:
Quantas vezes aparece a letra "A"
Em que posição ela aparece a primeira vez.
Em que posição ela aparece a última vez.
"""
frase = str(input('Digite uma frase: ')).strip()
quant = frase.count('A')
prim = frase.find("A")+1
ultm = frase.rfind("A")+1
print('Tem ... |
# If the list grows large, it might be worth using a dictionary
isps = ('gmail.', 'yahoo.', 'earthlink.', 'comcast.', 'att.', 'movistar.', 'hotmail.', 'mail.', 'googlemail.',
'msn.', 'bellsouth.', 'telus.', 'optusnet.', 'qq.', 'sky.', 'icloud.', 'mac.', 'sympatico.',
'xtra.', 'web.', 'cox.', 'ymail.', '... |
class Solution:
def isPalindrome(self, s: str) -> bool:
l1 = ord('a')
r1 = ord('z')
l2 = ord('A')
r2 = ord('Z')
l3 = ord('0')
r3 = ord('9')
diff = ord('a') - ord('A')
seq = [
chr(ord(ch) - diff) if l1 <= ord(ch)... |
EMOTICONS = {
u":\)": "Happy face or smiley",
u"=\)": "Happy face or smiley",
u":‑\)": "Happy face or smiley",
u":-\]": "Happy face or smiley",
u":\]": "Happy face or smiley",
u":-3": "Happy face smiley",
u":3": "Happy face smiley",
u":->": "Happy face smiley",
u":>": "Happy face smi... |
#coding: utf-8
#--------------------------------------------------------
# Um programa que recebe um nome completo e
# confirma se existe ou não "Silva" no nome.
#--------------------------------------------------------
# Buscando uma string dentro da outra - Exercício #025
#--------------------------------------... |
# -*- coding: utf-8 -*-
class ConfigFetchError(Exception):
"""Raised when we were unable to fetch the config from the server
"""
def __init__(self, msg, response):
self.msg = msg
self.response = response
super(Exception, self)
class InvalidAPICallError(Exception):
pass
class... |
# -*- coding: utf-8 -*-
__author__ = 'Audrey Roy Greenfeld'
__email__ = 'aroy@alum.mit.edu'
__version__ = '0.1.0'
|
'''
构建短字符串
描述
给定任意一个较短的子串,和另一个较长的字符串,
判断短的字符串是否能够由长字符串中的字符组合出来,且长串中的每个字符只能用一次。
输入
一行数据包括一个较短的字符串和一个较长的字符串,
用一个空格分隔,如: ab aab bb abc aa cccc uak areuok
输出
如果短的字符串可以由长字符串中的字符组合出来,
返回字符串 “true”,否则返回字符串 "false",注意返回字符串类型而不是布尔型。
输入样例
a b
aa ab
aa aab
uak areuok
输出样例
false
false
true
true
'''
"""
@param string line 为单行测试数据
@... |
def number_of_divisors(divisor: int) -> int:
global requests
global divisors
if divisor in divisors:
return divisors[divisor]
requests.add(divisor)
count = 2
for i in range(2, int(divisor**0.5) + 1):
if not (divisor % i):
count += 2
divisors[divisor] ... |
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
totalRemain = 0
remainFromStart = 0
start = None
for i in range(len(gas)):
remain = gas[i] - cost[i] # remain when cross the station
remainFromStart += remain
if ... |
"""
DESCRIPTORS: local ang global descriptors for a rectangular (part of an) image.
"""
__autor__ = 'Vlad Popovici'
|
# -*- coding: utf-8 -*- #
# Copyright 2015 Google Inc. All Rights Reserved.
"""Package marker file."""
|
# Membaca file hello.txt dengan fungsi readlines()
print(">>> Membaca file hello.txt dengan fungsi readlines()")
file = open("hello.txt", "r")
all_lines = file.readlines()
file.close()
print(all_lines)
# Membaca file hello.txt dengan menerapkan looping
print(">>> Membaca file hello.txt dengan menerapkan looping")
file ... |
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def get_person(self):
return '<Person ({0}, {1})'.format(self.name, self.age)
p = Person('Manuel', 21)
print('Type of Object: {0}, Memory Address: {1}'.format(type(p), id(p))) |
class Solution:
def countAndSay(self, n: int) -> str:
say = '1'
while n > 1 :
n -= 1
temp = say
tag = temp[0]
count = 1
say = ''
for j in range(1, len(temp)):
if temp[j] == tag:
count += 1
... |
# v1
# can only buy then sell once
def max_profit_1(prices):
if not prices: return 0
low = prices[0] # lowest price so far
profit = 0
for price in prices:
if low >= price:
low = price
else:
profit = max(profit, price - low)
return profit
# O(n) time and spac... |
# Copyright (c) 2020
# Author: xiaoweixiang
class Solution:
def similarRGB(self, color: str) -> str:
"""
看了答案才明白题目意思
:param color:
:return:
"""
def similarity(hex1, hex2) -> int:
r1, g1, b1 = hex1 >> 16, (hex1 >> 8) % 256, hex1 % 256
r2, g... |
#Crie um programa que tenha uma única função, além da principal, que receberá como parâmetro uma string não vazia s (com no máximo 50 caracteres de conteúdo) e exibirá a quantidade de caracteres de s. Observações: (a) apenas um laço de repetição; (b) sem matrizes auxiliares; (c) não usar funções prontas; (d) função ite... |
'''
Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividend by divisor.
The integer division should truncate toward zero.
Example 1:
Input: dividend = 10, divisor = 3
Output: 3
Example 2:
Input: dividend = 7, ... |
""" Python Playlist Parser (plparser)
Copyright (C) 2012 Hugo Caille
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditi... |
def preorderTraversal(root):
if root is None:
return []
nodes = []
def visit(node, nodes):
if node is None:
return
nodes.append(node.val)
visit(node.left, nodes)
visit(node.right, nodes)
visit(root, nodes)
return nodes
|
def encrypt(input, key):
encrypted = []
for i in range(0, len(input)):
a = ord(input[i])
for j in range (0, key):
a = a + 1
if (a>122):
a = 97
encrypted.append(chr(a))
return "".join(encrypted)
def decrypt(input, key):
de... |
number_of_input_bits = 1
mux_x = 0.002 # in m
mux_y = 0.0012 # in m
for i in range(number_of_input_bits):
positionx = 0.0 + mux_x * i
line = "Mux1" + str(i) + "\t" + str(mux_x) + "\t" + str(mux_y) + "\t"
line += str(round(positionx, 8)) + "\t"
positiony = 0.0
line += str(round(positiony, 8))
... |
k,s=map(int,input().split())
x=list(input())
for i in range(s):
if x[i].isalpha() and x[i].isupper():
print(chr(ord('A')+(ord(x[i])-ord('A')+k)%26),end='')
elif x[i].isalpha():
print(chr(ord('a')+(ord(x[i])-ord('a')+k)%26),end='')
else:
print(x[i],end='') |
def reverse(string):
string = "".join(reversed(string)) #used reversed function for reversing the String
return string
str = input("Enter A String:")
print ("The Entered String is : ",end="") #end is used here so that output will be in same line.
print (str)
print ("The Reversed String is : ",end... |
# Copyright 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Makes sure that injected JavaScript is clang-format clean."""
def CheckChangeOnUpload(input_api, output_api):
"""Special Top level function called by g... |
a =[int(i) for i in input().split()]
b = []
for i in range(len(a)):
if (len(a) == 1):
b = a
elif (i == (len(a)-1)):
b.append(a[i-1] + a[0])
else:
b.append(a[i-1] + a[i+1])
for j in range(len(b)):
print(b[j], end=' ')
# Оптимальное решение без обособления последнего варианта
# ... |
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashMap = {}
for idx in range(len(nums)):
currentNum = nums[idx]
difference = target-currentNum
if difference not in hashMap and currentNum not in hashMap:
hashMap[differe... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'My Farm',
'version' : '1.1',
'category': 'Services',
'installable': True,
'application': True,
'depends': ['project'],
'data': [
'data/res.country.state.csv',
'data/s... |
i = 2
S = 1
while i <= 100:
S = S + (1 / i)
i += 1
print('{:.2f}'.format(S)) |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# This is a dummy grpcio==1.35.0 package used for E2E
# testing in Azure Functions Python Worker.
__version__ = '1.35.0'
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Pieter Huycke
email: pieter.huycke@ugent.be
GitHub: phuycke
"""
#%%
my_dict = {'a':15 , 'c':35, 'b':20}
[print("Dictionary key: ", key) for key in my_dict.keys()]
print("- - - -")
[print("Dictionary value: ", val) for val in my_dict.values()]
print("-... |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( arr , n ) :
count = 0
arr.sort ( )
for i in range ( 0 , n - 1 ) :
if ( arr [ i ] != arr [ i + 1... |
"""since the cPickle module as of py2.4 uses erroneous relative imports, define the various
picklable classes here so we can test PickleType stuff without issue."""
class Foo(object):
def __init__(self, moredata):
self.data = 'im data'
self.stuff = 'im stuff'
self.moredata = moredata
d... |
board = ["-","-","-","-","-","-","-","-","-"]
gamegoing = True
winner = None
current_player = "X"
def disp_board():
print(board[0]+ "|" + board[1] + "|" + board[2])
print(board[3]+ "|" + board[4] + "|" + board[5])
print(board[6]+ "|" + board[7] + "|" + board[8])
def play_game():
disp_board()
while gamegoing... |
'''
Created on Feb 9, 2018
@author: gongyo
'''
colors = ["red", 'yellow']
colors.append("black")
def compare(c1="str", c2="str"):
return c1 < c2
compare2 = lambda c1, c2: (c1 < c2);
colors.sort(cmp=compare2, key=None, reverse=False)
|
# Write a program that reads numbers and adds them to a list if they aren’t already
# contained in the list. When the list contains ten numbers, the program displays the
# contents and quits.
# PROGRAM RUN
list = []
print("Enter numbers: ")
while len(list) < 11:
try:
inputN = float(input())
if in... |
"""
Author: Kagaya john
Tutorial 8 : Tuples
"""
"""
The tuple() Constructor
It is also possible to use the tuple() constructor to make a tuple. The len() function returns the length of the tuple."""
#Using the tuple() method to make a tuple:
thistuple = tuple(("apple", "banana", "cherry")) # note the double rou... |
def extractCwastranslationsWordpressCom(item):
'''
Parser for 'cwastranslations.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('tsifb', ... |
# version scheme: (major, minor, micro, release_level)
#
# major:
# 0 .. not all planned features done
# 1 .. all features available
# 2 .. if significant API change (2, 3, ...)
#
# minor:
# changes with new features or minor API changes
#
# micro:
# changes with bug fixes, maybe also minor API changes
#
# re... |
class UVMDefaultServer:
def __init__(self):
self.m_quit_count = 0
self.m_max_quit_count = 0
self.max_quit_overridable = True
self.m_severity_count = {}
self.m_id_count = {}
## uvm_tr_database m_message_db;
## uvm_tr_stream m_streams[string][string]; // ro.na... |
#Factorial of number
n = int(input("enter a number "))
f = 1
if (n < 0):
print("number is negative")
elif (n == 0):
print("factorial=",1)
else:
for i in range(1,n+1):
f = f * i
print("factorial =",f) |
# dimensions of our images.
img_width, img_height = 150, 150
train_data_dir = 'data/train'
validation_data_dir = 'data/validation'
nb_train_samples = 5005
nb_validation_samples = 218
epochs = 1
batch_size = 16
|
# -*- coding: utf-8 -*-
# $Id: diff.py $
"""
Diff two test sets.
"""
__copyright__ = \
"""
Copyright (C) 2010-2015 Oracle Corporation
This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free software;
you can redistribute it and/or modify it under the ... |
# -*- coding: utf-8 -
__VERSION__ = (0, 4, 7)
__SERVER_NAME__ = 'lin/{}.{}.{}'.format(*__VERSION__)
|
# coding=utf-8
UBUNTUS = ['utopic', 'vivid', 'wily', 'xenial', 'yakkety', 'zesty', 'artful', 'bionic', 'cosmic', 'eoan', 'focal']
VERSION = "99.0"
NETS = ['default']
POOL = 'default'
IMAGE = None
CPUMODEL = 'host-model'
NUMCPUS = 2
CPUHOTPLUG = False
CPUFLAGS = []
MEMORY = 512
MEMORYHOTPLUG = False
DISKINTERFACE = 'vir... |
f=open("./matrix.txt","r") #create the dictionary for the score
diz={}
matrix=[]
for line in f:
line=line.rstrip()
line=line.split()
matrix.append(line)
for i in range(len(matrix[0])):
for j in range(1,len(matrix)):
diz[matrix[0][i]+matrix[j][0]]=int(matrix[i+1][j])
mat=diz
seq1="ACACT"
seq2=... |
# Set this to your GitHub auth token
GitHubAuthToken = 'add_here_your_token'
# Set this to the path of the git executable
gitExecutablePath = 'git'
# Set this to true to download also private repos if the token has private repo rights
include_private_repos = False
# Set this to False to skip existing repos
... |
# Copyright (c) 2012 The Chromium 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',
],
'variables': {
'irt_sources': [
# irt_support_sources
'irt_entry.c',
'irt_inte... |
'''
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example:
Given num = 16, return true. Given num = 5, return false.
Follow up: Could you solve it without loops/recursion?
Credits:
Special thanks to @yukuairoy for adding this problem and creating all test cases.
'''
class... |
# b1 - bought stock once
# s1 - bought stock and then sold once
# b2 - bought stock the second time
# s2 - bought and sold twice
class Solution:
def maxProfit(self, prices: List[int]) -> int:
b1 = s1 = b2 = s2 = float('-inf')
for p in prices:
b1, s1, b2, s2 = max(b1, - p), max(s1, b1 +... |
load("//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external")
def dependencies():
import_external(
name = "org_apache_kafka_kafka_2_12",
artifact = "org.apache.kafka:kafka_2.12:1.1.1",
artifact_sha256 = "d7b77e3b150519724d542dfb5da1584b9cba08fb1272ff1e3b3d735937e22632",
... |
input = """AlphaCentauri to Snowdin = 66
AlphaCentauri to Tambi = 28
AlphaCentauri to Faerun = 60
AlphaCentauri to Norrath = 34
AlphaCentauri to Straylight = 34
AlphaCentauri to Tristram = 3
AlphaCentauri to Arbre = 108
Snowdin to Tambi = 22
Snowdin to Faerun = 12
Snowdin to Norrath = 91
Snowdin to Straylight = 121
Sno... |
nome = input('Digite seu nome: ').strip()
print('\n Nome em maiúsculas:', nome.upper())
print(' Nome em minúsculas:', nome.lower())
print(' Quantidade de letras:', len(nome.replace(' ', '')))
print(' Quantidade de letras:', len(nome)-nome.count(' ')) # 2° opção
print(' Q. de letras primeiro nome:', len(nome.split()[0]... |
(_, d) = tuple(map(int, input().strip().split(' ')))
arr = list(map(int, input().strip().split(' ')))
new_arr = arr[d:] + arr[:d]
print(' '.join(map(str, new_arr)))
|
class DebugConfig:
# base
SECRET_KEY = b'IL_PROGRAMMATORE_RESPONSABILE_MI_CAMBIERA! OVVIO AMO!'
SERVER_NAME = 'localhost:5000'
# database
MYSQL_DATABASE_HOST = 'localhost'
MYSQL_DATABASE_PORT = 3306
MYSQL_DATABASE_USER = 'root'
MYSQL_DATABASE_PASSWORD = ''
MYSQL_DATABASE_DB = 'inge... |
# Exercise 1: Squaring Numbers
numbers = [1,1,2,3,5,8,13,21,34,55]
squared_numbers = [number**2 for number in numbers]
print(squared_numbers) |
# TODO: Arrumar a versão
# A versão está errada
# Preguiça de arrumar
__version__ = "0.1.0" |
#
# @lc app=leetcode.cn id=46 lang=python3
#
# [46] 全排列
#
# https://leetcode-cn.com/problems/permutations/description/
#
# algorithms
# Medium (76.62%)
# Likes: 834
# Dislikes: 0
# Total Accepted: 169.1K
# Total Submissions: 220.7K
# Testcase Example: '[1,2,3]'
#
# 给定一个 没有重复 数字的序列,返回其所有可能的全排列。
#
# 示例:
#
# 输入: ... |
LIST_ALGORITHMS_TOPIC = 'list_algorithms'
SET_ALGORITHM_TOPIC = 'set_algorithm'
GET_SAMPLE_LIST_TOPIC = 'get_sample_list'
TAKE_SAMPLE_TOPIC = 'take_sample'
REMOVE_SAMPLE_TOPIC = 'remove_sample'
COMPUTE_CALIBRATION_TOPIC = 'compute_calibration'
SAVE_CALIBRATION_TOPIC = 'save_calibration'
CHECK_STARTING_POSE_TOPIC = 'c... |
# Time: O(n)
# Space: O(n)
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def nextLargerNodes(self, head):
"""
:type head: ListNode
:rtype: List[int]
"""
... |
"""
Here: https://leetcode.com/problems/3sum/
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
"""
def threeSum(nums):
result = set()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.