content stringlengths 7 1.05M |
|---|
class Settings:
def __init__(self):
self.screen_width = 1200
self.screen_height = 600
self.screen_bg_color = (230, 230, 230)
# 飞船设置
self.ship_limit = 3
# 子弹设置
self.bullet_width = 3
self.bullet_height = 15
self.bullet_color = (60, 60, 60)
... |
DOMAIN = "dyson_cloud"
CONF_REGION = "region"
CONF_AUTH = "auth"
DATA_ACCOUNT = "account"
DATA_DEVICES = "devices"
|
class Count:
def countAndSay(self, n: int) -> str:
cou='1'
for i in range(n-1):
j=0
new_count=''
while len(cou)>j:
count=1
while j<len(cou)-1 and cou[j]==cou[j+1]:
count+=1
j+=1
... |
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... |
# -*- python -*-
load("//tools/workspace:generate_file.bzl", "generate_file")
load("@drake//tools/workspace:github.bzl", "github_archive")
# Using the `drake` branch of this repository.
_REPOSITORY = "RobotLocomotion/pybind11"
_COMMIT = "c39ede1eedd4f39aa167d7b30b53ae45967c39b7"
_SHA256 = "2281eef20037b1d18e7f790a1... |
api_url = "https://developer-api.nest.com"
cam_url = "https://www.dropcam.com/api/wwn.get_snapshot/CjZKT2ljN2JJTGxIYzd3emF2S01DRFFtbm5Na2VGZzYwOEJaaUNVcG9oX3RYaHFSdDktY1JDTlESFk01T2dKTVg3cW1CQ0NGX202eEJYYVEaNkc4SElfUUpZbmtFUFlyZmR1M3lJUXV5OFZyUjdVU0QwdWljbWlLUU1rNXRBVW93RzNHWXVfZw?auth=019N06kj4pw8zmue62OkCF8p2yhICbCoq... |
#!/usr/bin/env python3
#-*- encoding: UTF-8 -*-
def main():
time = int(input("A quanto tempo você fuma? "))
cigarros = int(input("Quantidade de cigarros fumada por dia: "))
total_fumado = (cigarros * 365) * time
lost_time = total_fumado / 144
print("Pare de fumar! Você já perdeu %d dias de vida." %... |
# coding: utf-8
"""*****************************************************************************
* Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* re... |
# AULA 1
# COMENTARIOS
"""
Vamos começar a primeira aula falando da parte mais básica, os comentarios.
Todo interpretador ou complilador de python ao pegar um arquvo com extenção .py
vai ignorar todas as linhas que se iniciarem com "#" na frente. Se trata de um
método no qual o desenvolvedor consegue documentar s... |
# Time: O(n)
# Space: O(1)
class Solution(object):
def decodeAtIndex(self, S, K):
"""
:type S: str
:type K: int
:rtype: str
"""
i = 0
for c in S:
if c.isdigit():
i *= int(c)
else:
i += 1
... |
# -*- coding: utf-8 -*-
def similar_str(str1, str2):
"""
return the len of longest string both in str1 and str2
and the positions in str1 and str2
"""
max_len = tmp = pos1 = pos2 = 0
len1, len2 = len(str1), len(str2)
for p in range(len1):
for q in range(len2):
tmp = 0
... |
nome = str(input('Qual seu nome completo? '))
print('Tem SILVA no nome?')
print('Silva' in nome)
|
def solve(n, m, k):
ncard = len(k)
for i1 in range(ncard):
n1 = k[i1]
for i2 in range(ncard):
n2 = k[i2]
for i3 in range(ncard):
n3 = k[i3]
for i4 in range(ncard):
if n1 + n2 + n3 + k[i4] == m:
... |
def edge_rotate(edge, ccw=False):
pass
def edge_split(edge, vert, fac):
pass
def face_flip(faces):
pass
def face_join(faces, remove=True):
pass
def face_split(face, vert_a, vert_b, coords=(), use_exist=True, example=None):
pass
def face_split_edgenet(face, edgenet):
pass
def face_ver... |
class ESKException(Exception):
def __init__(self, status_code, message):
self.status = status_code
self.message = message
def __str__(self) -> str:
return f"{ self.status }: { self.message }" |
''' Estes exercícios fazem parte do curso de Introdução a Algoritmos, ministrado pelo prof. Gustavo Guanabara e podem ser encontrados no site https://www.cursoemvideo.com/wp-content/uploads/2019/08/exercicios-algoritmos.pdf
86) Crie um programa que tenha um procedimento Gerador() que, quando chamado, mostre a mens... |
def requests_utils(request):
host = request.get_host()
port = request.get_port()
uri = '{}'.format(host)
real_uri = request.build_absolute_uri()
return {
'host': host,
'port': port,
'secure_uri': 'https://{}'.format(uri),
'insecure_uri': 'http://{}'.format(uri),
... |
'''
Problem description:
Write a function, which takes a non-negative integer (seconds) as input and returns
the time in a human-readable format (HH:MM:SS)
HH = hours, padded to 2 digits, range: 00 - 99
MM = minutes, padded to 2 digits, range: 00 - 59
SS = seconds, padded to 2 digits, range: 00 - 59
The maximum time... |
class Solution:
def minCost(self, costs):
"""
:type costs: List[List[int]]
:rtype: int
"""
cur = [0] * 3
for next in costs:
cur = [next[i] + min(cur[:i] + cur[i+1:]) for i in range(3)]
return min(cur)
|
# -*- coding: utf-8 -*-
# Fixed for our Hot Dog & Pizza classes
NUM_CLASSES = 2
# Fixed for Hot Dog & Pizza color images
CHANNELS = 3
IMAGE_RESIZE = 224
RESNET50_POOLING_AVERAGE = 'avg'
DENSE_LAYER_ACTIVATION = 'sigmoid'
OBJECTIVE_FUNCTION = 'binary_crossentropy'
# The name of the .h5 file containing the pretrained... |
# First Missing Positive: https://leetcode.com/problems/first-missing-positive/
# Given an unsorted integer array nums, find the smallest missing positive integer.
# You must implement an algorithm that runs in O(n) time and uses constant extra space.
# The brute force of this is to look through all of nums for each... |
# File generated by hadoop record compiler. Do not edit.
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apac... |
"""Gemini2 Exception Inheritance Tree
Gemini2Exception
G2BackendException
G2BackendCommandNotSupportedError
G2BackendFeatureNotSupportedError
G2BackendFeatureNotImplementedYetError
G2BackendCommandError
G2BackendResponseError
G2BackendReadTimeoutError
G2CommandException
G2Command... |
def solution(n, words):
answer = []
# 단어 하나씩 가져오기
for idx, word in enumerate(words):
# 현재 단어의 index보다 작으면 나왔던 단어
if(words.index(word) < idx):
answer = [idx % n + 1, idx // n + 1]
return answer
# 끝말잇기 규칙 모르는 친구
elif(idx != 0 and words[idx-1][-1] != wor... |
n = int(input())
A = list(map(int, input().split()))
abs_sum = 0
minus = 0
abs_list = []
for i in range(n):
if A[i] < 0:
minus += 1
abs_list.append(abs(A[i]))
abs_sum += abs_list[i]
if minus % 2 != 0:
abs_sum -= min(abs_list)*2
print(abs_sum)
|
def main():
_, array = input(), map(int, input().split())
A, B = (set(map(int, input().split())) for _ in range(2))
print(sum((x in A) - (x in B) for x in array))
if __name__ == '__main__':
main()
|
"""Decompose GPS Events."""
class GpsDecomposer(object):
"""GPS Decomposer."""
@classmethod
def decompose(cls, scan_document):
"""Decompose a GPS event.
Args:
scan_document (dict): Geo json from GPS device.
Returns:
list: One two-item tuple in list. Posi... |
"""
File Containing Regex for Different Uses
"""
PASSWORD_REGEX = r"^.*(?=.*[a-zA-Z])(?=.*?[!@£$%^&*()_+={}?:~\[\]])" + \
r"(?=.*?[A-Z])(?=.*\d)(?=.{8,10})[a-zA-Z0-9!@£$%^&*()_+={}?:~\[\]]+$"
UUID_REGEX = r"[0-9A-Za-z]{8}-[0-9A-Za-z]{4}-4[0-9A-Za-z]{3}" + \
r"-[89ABab][0-9A-Za-z]{3}-[0-9A-Za-z]{12}"
EMAIL_REGEX... |
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if len(strs)==1:
return strs[0]
minlen = min([len(each) for each in strs])
result=""
for i in range(minlen):
basis = strs[-1][i]
for j in range(len(strs)-1):
if ... |
#Escribir una función recursiva que encuentre el mayor elemento de una lista.
def Mayor(lista, numero, mayor, bandera):
if (lista[0] > lista[numero] and bandera == 0):
mayor = lista[numero]
bandera = bandera + 1
return Mayor(lista, numero-1, mayor, bandera)
else:
if (numero == 0 and lista[numero] > m... |
"""
PASSENGERS
"""
numPassengers = 4076
passenger_arriving = (
(5, 13, 10, 1, 1, 0, 9, 11, 11, 3, 1, 0), # 0
(3, 15, 9, 4, 1, 0, 9, 15, 6, 4, 2, 0), # 1
(5, 6, 9, 3, 4, 0, 13, 12, 9, 6, 2, 0), # 2
(5, 7, 12, 5, 1, 0, 7, 11, 7, 5, 2, 0), # 3
(3, 7, 5, 5, 4, 0, 8, 7, 7, 3, 1, 0), # 4
(4, 15, 9, 3, 1, 0, 7, ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 19 07:02:28 2021
@author: bnorthan
"""
def tomarkdown(data, racename, outname ):
markdown='## '+racename+'\n\n'
markdown+=data.to_markdown()
out_file=open(outname, "w")
out_file.write(markdown)
out_file.close()
|
def PlusOne(arr:list) -> list:
string = ''
for x in arr:
string = string + str(x)
number = int(string) + 1
new_arr = []
for x in str(number):
new_arr.append(int(x))
return new_arr
arr = [0]
new_arr = PlusOne(arr)
print(new_arr) |
a = list(map(str,input().split()))
b = []
c = 0
d = []
e = []
while a!= ['-1']:
b.append(a)
a = list(map(str,input().split()))
for i in b:
e += [[i[1],i[2]]]
if i[2] == 'right':
c += int(i[0])
for k in range(65,91):
count = 0
for l in e:
count += l.count(chr(k))
for l in e... |
#!/usr/bin/env python3
class filterParameter:
def __init__(self):
self.newData = {}
self.arrayParameter = []
def filterKeyValueParameter(self, data):
for key, value in data.items():
if "." not in key and value != '':
self.newData[key] = value
retu... |
class Module:
def __init__(self,name,lessons,course):
self.course = course
self.plataform = self.course.plataform
self.name = name
self.lessons = lessons
|
sexo = str(input("Digite o seu genero [M] ou [F] ")).strip().upper()[0]
while(sexo not in "MmFf"):
sexo = input("Dados invalidos. Digite o seu genero [M] ou [F] ").strip().upper()
print("Sexo Cadastrado com sucesso! Obrigado!")
|
numbers = [int(x) for x in list(input())]
def odd_and_even_sum():
even_sum = 0
odd_sum = 0
for current_number in numbers:
if current_number % 2 == 0:
even_sum += current_number
else:
odd_sum += current_number
print(f"Odd sum = {odd_sum}, Even sum = {even_sum}... |
#
# File: recordedfuture_consts.py
#
# Copyright (c) Recorded Future, Inc., 2019-2020
#
# This unpublished material is proprietary to Recorded Future.
# All rights reserved. The methods and
# techniques described herein are considered trade secrets
# and/or confidential. Reproduction or distribution, in whole
# or in p... |
#App.open("Yousician Launcher.app")
#wait("png/home.png", 60)
App.focus("Yousician")
click("png/settings.png")
wait("png/guitar.png")
click("png/guitar.png")
wait("png/challenges.png")
click("png/challenges.png")
wait("png/history.png")
click("png/history.png")
wait(1)
click(Location(700, 400))
wait(1)
print(Region(100... |
# 현재 설치된 구조물이 '가능한' 구조물인지 확인하는 함수
def possible(answer):
for x, y, stuff in answer:
if stuff == 0: # 설치된 것이 '기둥'인 경우
# '바닥 위' 혹은 '보의 한쪽 끝부분 위' 혹은 '다른 기둥 위'라면 정상
if y == 0 or [x - 1, y, 1] in answer or [x, y, 1] in answer or [x, y - 1, 0] in answer:
continue
... |
def sumOfDigits(n):
if n <= 9:
return n
recAns = sumOfDigits(n//10)
return recAns + (n % 10)
print(sumOfDigits(984))
|
# Faça um programa que leia um número inteiro qualquer e mostre na tela a sua tabuada
print( '=-'*7, 'DESAFIO 12', '=-'*7 )
n = int( input( 'Digite um número: ' ) )
print( 'A tabuada do número {} é: '.format( n ) )
print( '=-'*12 )
print( '{} x {:2} = {}'.format( n, 0, n * 0 ) )
print( '{} x {:2} = {}'.format( n, 1, n... |
# Source: https://github.com/Ardevop-sk/stopwords-sk
STOP_WORDS = set(
"""
a
aby
aj
ak
akej
akejže
ako
akom
akomže
akou
akouže
akože
aká
akáže
aké
akého
akéhože
akému
akémuže
akéže
akú
akúže
aký
akých
akýchže
akým
akými
akýmiže
akýmže
akýže
ale
alebo
ani
asi
avšak
až
ba
bez
bezo
bol
bola
boli
bolo
bude
budem
budem... |
'''
Module containing configuration for ExternalUrl objects.
'''
# dictionary of External URL (key, type)
EXTERNAL_URL_TYPES = {
"BLOG" : "blog",
"REPOSITORY": "repository",
"HOMEPAGE": "homepage",
"REFERENCE": "reference",
... |
def places_per_neighborhood(gfN, gf, neighborhood):
gfNeighborhood = gfN.query('nhood == @neighborhood')
nhood_places = gpd.sjoin(gf, gfNeighborhood, how="inner", op='within')
return(nhood_places)
|
name = input()
age = int(input())
town = input()
salary = float(input())
print(f"Name: {name}\nAge: {age}\nTown: {town}\nSalary: ${salary:.2f}")
age_range = None
if age < 18:
age_range = "teen"
elif age < 70:
age_range = "adult"
else:
age_range = "elder"
print(f"Age range: {age_range}")
salary_range = ... |
frogarian = """\
\033[0;34;40m :\033[0;5;33;40m%\033[0;5;34;40mX\033[0;32;40m:\033[0;31;40m.\033[0;32;40m \033[0;34;40m
\033[0;32;40m.\033[0;5;30;40m8\033[0;5;33;40mt \033[0;5;31;40mS\033[0;32;40m.\033[0;34;40m
\033[0;31;40m \033[0;1;30;40m8\033[0;5;35;40m.\033[0;1;30;47m:\03... |
# Declare second integer, double, and String variables.
a=int(input())
b=float(input())
c=input()
# Read and save an integer, double, and String to your variables.
# Print the sum of both integer variables on a new line.
print(i+a)
# Print the sum of the double variables on a new line.
print(b+d)
# Concatenate and pri... |
OUTGOING_KEY = "5a4d2016bc16dc64883194ffd9"
INCOMING_KEY = "c91d9eec420160730d825604e0"
STATE_LENGTH = 256
class RC4:
def __init__(self, key):
self.key = bytearray.fromhex(key)
self.x = 0
self.y = 0
self.state = [0] * STATE_LENGTH
self.reset()
def process(se... |
# Runtime: 328 ms, faster than 44.59% of Python3 online submissions for 4Sum II.
# Memory Usage: 34 MB, less than 86.63% of Python3 online submissions for 4Sum II.
class Solution:
def fourSumCount(self, A, B, C, D):
ab = {}
for i in A:
for j in B:
ab[i + j] = ab.get(i+j, ... |
# This problem was recently asked by Amazon:
# Given a string, return the first recurring letter that appears. If there are no recurring letters, return None.
def first_recurring_char(s):
# Fill this in.
stack = []
for i in s:
if i in stack:
return i
else:
stack.ap... |
tweets['text'] = map(lambda tweet: tweet['text'], tweets_data)
tweets['lang'] = map(lambda tweet: tweet['lang'], tweets_data)
tweets['country'] = map(lambda tweet: tweet['place']['country']
if tweet['place'] != None else None, tweets_data)
tweets_by_lang = tweets['lang'].value_counts()
fig, ax = plt.subplots(fi... |
def readFile(filename):
try:
with open(filename,"r") as f:
print(f.read())
except FileNotFoundError:
print(f"File {filename} is not Found in this Directory.")
readFile("01_i.txt")
readFile("01_ii.txt")
readFile("01_iii.txt")
# ---------------------------------------
... |
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
r = len(matrix)
c= len(matrix[0])
rows0 = set()
cols0 = set()
for i in range(r):
for j in range(c):
... |
level = 3
name = 'Cilengkrang'
capital = 'Jatiendah'
area = 30.12
|
"""
Given a string and a pattern, write a method to count the number of
times the pattern appears in the string as a subsequence.
Example 1: Input: string: “baxmx”, pattern: “ax”
Output: 2
Explanation: {baxmx, baxmx}.
Example 2:
Input: string: “tomorrow”, pattern: “tor”
Output: 4
Explanation: Following are the ... |
## \namespace cohereModels
"""
This is the PyTurbSim 'coherence models' package.
For more information or to use this module import the cohereModels.api
package, e.g.:
import pyts.cohereModels.api as cm
"""
|
# Display the DataFrame hours using print
print(hours)
# Create a bar plot from the DataFrame hours
plt.bar(hours.officer, hours.avg_hours_worked)
# Display the plot
plt.show()
# Display the DataFrame hours using print
print(hours)
# Create a bar plot from the DataFrame hours
plt.bar(hours.officer, h... |
class Dice_loss(nn.Module):
def __init__(self,type_weight=None,weights=None,ignore_index=None):
super(Dice_loss,self).__init__()
self.type_weight = type_weight
self.weights=weights
self.ignore_index=ignore_index
def forward(output, target):
"""
output : ... |
assert gradient('red', 'blue') == gradient('red', 'blue')
assert gradient('red', 'blue', start='center') == gradient('red', 'blue')
assert gradient('red', 'blue', start='left') == gradient('red', 'blue', start='left')
assert gradient('red', 'blue') != gradient('red', 'blue', start='left')
assert gradient('red', 'blue'... |
class GlobalStorage:
storage = {'design style': 'dark std',
'debugging': False}
def debug(*args):
s = ''
for arg in args:
s += ' '+str(arg)
if GlobalStorage.storage['debugging']:
print(' --> DEBUG:', s)
# yyep, that's it....
# you m... |
class ProjectHelper:
def __init__(self, app):
self.app = app
def add(self, new_project_name):
wd = self.app.wd
# go to manage project page
self.return_to_project_page()
# init project creation
wd.find_element_by_xpath("//form[@class='action-button'][@action='man... |
"""
Given an integer n, return a string array answer (1-indexed) where:
answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
answer[i] == "Fizz" if i is divisible by 3.
answer[i] == "Buzz" if i is divisible by 5.
answer[i] == i (as a string) if none of the above conditions are true.
Example 1:
Input: n = 3
Output:... |
#!/usr/bin/env python3
def calculate():
I = 10**16
subsets = [0] * 250
subsets[0] = 1
for i in range(1, 250250 +1):
offset = pow(i, i, 250)
subsets = [(val + subsets[(j - offset) % 250]) % I
for (j, val) in enumerate(subsets)]
answer = (subsets[0] - 1) % I
ret... |
s=int(input('Qual seu salario?'))
if s>1250:
p=s*0.1
ns=s+p
print('Você recebeu um aumento de {:.2f} e seu novo salaraio é {:.2f}.'.format(p, ns))
else:
p2=s*0.15
ns2=s+p2
print('Você recebeu um aumento de {:.2f} e seu novo salario é {:.2f}.'.format(p2, ns2))
|
#
# PySNMP MIB module ADTRAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADTRAN-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:13:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... |
## Regex validate PIN code
## 7 kyu
## https://www.codewars.com/kata/55f8a9c06c018a0d6e000132
def validate_pin(pin):
#return true or false
if pin.isdigit():
if len(pin) == 4 or len(pin) ==6:
return True
else:
return False
else:
return False
... |
#
# PySNMP MIB module DOCS-SUBMGT3-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DOCS-SUBMGT3-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:28:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
max_personal_participations = 5
team_size = 3
number_of_students, min_team_participations = map(int, input().split())
personal_participations = map(int, input().split())
eligible_personal_participations = len(list(filter(lambda n: n <= max_personal_participations - min_team_participations,
... |
"""
moth.py
Copyright 2013 Andres Riancho
This file is part of w3af, http://w3af.org/ .
w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
w3af is distributed in the hope that it wil... |
def extractInoveltranslationsWordpressCom(item):
'''
Parser for 'inoveltranslations.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
if item['tags'] == ['Uncategorized']:
titlemap = [
('Dual... |
def add(x,y):
'''Add two numbers'''
return(x+y)
def subtract(x,y):
'''Subtract y from x'''
return(x-y)
def multiply(x,y):
'''Multiply x and y'''
return(x*y)
def divide(x,y):
'''Divide x by y'''
if y == 0:
raise ValueError('Cannot divide by 0')
return(x/y)
|
#
# PySNMP MIB module AtiSwitch-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AtiSwitch-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:17:18 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
name = "Positional Encoding"
description = """
The positional encoding is a data augmentation strategy first developed in the natural language processing literature.
It has gained widespread adoption as a simple and effective strategy to improve the performance of neural networks in
modelling spatially resolved funct... |
# -*- coding: utf-8 -*-
class ExtendDict(dict):
def __getattr__(self, name):
return self.get(name)
|
# Created by MechAviv
# Quest ID :: 34915
# Not coded yet
sm.setSpeakerID(3001508)
sm.removeEscapeButton()
sm.flipDialogue()
sm.setBoxChat()
sm.boxChatPlayerAsSpeaker()
sm.setBoxOverrideSpeaker()
sm.flipBoxChat()
sm.flipBoxChatPlayerAsSpeaker()
sm.setColor(1)
if sm.sendAskAccept("#face2#You're gonna go save Mar? It's ... |
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = {}
self.blocked=[]
def add_edge(self, src, dest,weight):
if self.graph.get(src) == None:
self.graph[src]=[(dest,weight)]
else:
self.graph[src]=self.graph.ge... |
# Consider this dictionary.
square_dict = {num: num * num for num in range(11)}
# .items() gives a list of tuple, so if we have a list of tuple
# We should be able to convert it to a dict.
print(square_dict.items())
# list of player and scores
players = ["XXX", "YYY", "ZZZ"]
scores = [100, 98, 45]
# Players and Scor... |
#!/usr/bin/env python3.10
FILE='test_s1.txt' # in: C200B40A82 sol: 3
FILE='test_s2.txt' # in: 04005AC33890 sol: 54
FILE='test_s3.txt' # in: 880086C3E88112 sol: 7
FILE='test_s4.txt' # in: CE00C43D881120 sol: 9
FILE='test_s5.txt' # in: D8005AC2A8F0 sol: 1
FILE='test_s6.txt' # in: F600BC2D8F sol: 0
FILE='test_s7.txt' # in... |
"""caracteristicas gerais."""
a = 7
b = 'eduardo'
def func(x, y):
return x + y
print(func(7, 7))
class Pessoa:
def __init__(self, nome, idade):
self.nome = nome
self.idade = idade
def __repr__(self):
return f'Pessoa(nome="{self.nome}", idade={self.idade})'
|
class _ResourceMap:
"""
A class to represent a set of resources that a rank maps to.
This is a combination of hardware threads, cores, gpus, memory.
A rank may map to multiple cores and gpus.
"""
def __init__(self):
self.core_ids = None
self.gpu_ids = None
class _RANKMap:
"... |
def soma(a, b):
x = a + b
y = 'qualquer coisa'
if x > 5:
return x
else:
return y
def soma(a, b):
x = a + b
y = 'qualquer coisa'
yield x
yield y
def soma(a, b):
x = a + b
y = 'qualquer coisa'
return (x, y)
#https://pt.stackoverflow.com/q/331155/101
|
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
best_sum=nums[0]
current_sum=nums[0]
for i in (nums[1:]):
current_sum= max(i, current_sum + i)
best_sum=max(best_sum,current_sum)
return best_sum
|
class ArrayCodec(object):
"""
This is a default encoding to pack the data. Designed for best storage in ascii.
You can use a custom encoder for eg. larger data sizes, more felxibility, etc.
Currently, this handles arrays with no keys, and max 2**8 ids and 62**4 counts.
Originally used base64 encodi... |
# this function will return a number depending on the balance of parentheses
def is_balanced(text):
count = 0
# loops through inputted text
for char in text:
# adds one to count if there is an open paren
if char == '(':
count += 1
# subtracts one if there is a closed pa... |
class ConstraintTypesEnum(object):
PRIMARY_KEY = "PRIMARY KEY"
FOREIGN_KEY = "FOREIGN KEY"
UNIQUE = "UNIQUE"
types = [
PRIMARY_KEY,
FOREIGN_KEY,
UNIQUE,
]
@classmethod
def get_types_str(cls):
return ", ".join(cls.types)
@classmethod
def get_types_co... |
# Name:
# Date:
# proj01: A Simple Program
# Part I:
# This program asks the user for his/her name and grade.
#Then, it prints out a sentence that says the number of years until they graduate.
name = input("What is your name? ")
name = name[0].upper() + name[1:]
grade = int(input("That is a cool name. What grade are... |
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of linked list
@param x: An integer
@return: A ListNode
"""
def partition(self, head, x):
if not... |
#
# PySNMP MIB module CISCO-OAM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-OAM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:51:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
n=str(input("Enter the mail id"))
le=len(n)
st=""
for i in range(le):
if n[i]=='@':
break
else:
st+=n[i]
print(st)
|
class Account:
__accNumber = 0
__balance = 0
def __init__(self, accNumber, balance = 1000):
self.setAccNumber(accNumber) # self.__accNumber = accNumber # the double underscore hides the info
self.setBalance(balance)
def getAccountNumber(self):
return self.__accNumber
def s... |
#
# PySNMP MIB module CABH-QOS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CABH-QOS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:44:07 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... |
#1->groundBlock
groundBlock=(48,0,16,16)
#2->supriseBlock
supriseBlock=(96,16,16,16)
#3->floatingBlock
floatingBlock=(0,0,16,16)
#4->obstacleBlock
obstacleBlock=(80,0,16,16)
#5->pipes
pipes=(256,96,32,32) |
#
# @lc app=leetcode id=292 lang=python3
#
# [292] Nim Game
#
# @lc code=start
class Solution:
def canWinNim(self, n: int) -> bool:
"""
time: O(1)
space: O(1)
"""
return n % 4 != 0
# @lc code=end
|
"""
.. Dstl (c) Crown Copyright 2019
"""
class Report:
"""Report class, stores the noisified data with the faults and ground truth
for future use. Delegates all methods and attribute_readers to the observed item."""
def __init__(self, identifier, truth, triggered_faults, observed):
self.identifier... |
letter ='''Dear <|NAME|>
Greetings from VITian student. I am verry happy to tell you about your selection in our club
You are selecteed
Have a great day aheas!
Thanks and regards.
Bill
Date: <|DATE|>
'''
name = input("Enter Your Name\n")
date = input("Enter Date\n")
letter=letter.replace("<|NAME|>", name)
le... |
def clip_bbox(dataset_bounds, bbox):
"""
Clips the bbox so it is no larger than the dataset bounds.
Parameters
----------
dataset_bounds: list of lon / lat bounds. E.g., [[-108, -104], [40, 42]]
represents the extent bounded by:
* -108 deg longitude on the west
... |
"""
Get input for the following scenarios. Make sure the data is manipulatable.
1. The name of the user
2. How many children to they have?
3. How old is there oldest child, if N/A input 0
4. Are they married?
5. What is their hourly wage?
"""
name = input("What is your name?")
children = int(input("How many children d... |
def main() -> None:
N = int(input())
A = list(map(int, input().split()))
assert 1 <= N <= 100
assert len(A) == N
assert 2 <= A[0]
assert A[-1] <= 10**18
for i in range(1, N):
assert A[i - 1] < A[i]
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.