content stringlengths 7 1.05M |
|---|
def jogar():
print("################################")
print("###Bem Vindo ao jogo da forca###")
print("################################")
palavra_secreta = "luna"
enforcou = False
acertou = False
while(not enforcou and not acertou): #Enquanto (nao enforcou e nao acertou)
... |
result = ''
for line in DATA:
result += line + '\n'
|
# -*- coding: utf-8 -*-
"""
Model object specification and validation.
"""
|
class Solution:
def maximalRectangle(self, matrix: List[List[str]]) -> int:
dp = [[0] * len(matrix[0]) for i in range(len(matrix))]
for row_i, row in enumerate(matrix):
for col_i, col in enumerate(row):
if col == "0":
dp[row_i][col_i] = 0
... |
# variables 4
a = "abc"
b = 1
c = 1.5
d = True
e = 3 + 5j
print("a:", type(a), "b", type(b), "c:", type(c),
"d:", type(d), "e:", type(e))
|
# 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(x1, y1, x2, y2, r1, r2):
distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)
radSumSq = (r1 + r2) * (r1 + ... |
#!/usr/bin/env python
# Task 1
instructions = list()
with open("./dec_2/dec2_input.txt") as f:
instructions = [x for x in f.read().split('\n')]
start_position = [0, 0]
for direction in instructions:
info = direction.split(' ')
vector, length = info[0], int(info[1])
if vector == "forward":
star... |
a = input()
s = [int(x) for x in input().split()]
buff = 0
load = False
for num in s:
if num - buff < 0:
load = True
if num - buff >= 30:
print(buff+30)
break
else:
if load:
buff += 5
load = False
else:
buff = num + 5
else:
prin... |
"""File IO."""
def re_readable_read(file):
"""Read file and reset cursor/pointer to allow fast, simple re-read.
Side Effects:
Mutates file stream object passed as argument by moving cursor/pointer
from from position at start of function call and setting it to position
'0'. If file str... |
class OmnipyConfiguration(object):
def __init__(self):
self.mqtt_host = ""
self.mqtt_port = 1883
self.mqtt_clientid = ""
self.mqtt_command_topic = ""
self.mqtt_response_topic = ""
self.mqtt_rate_topic = ""
|
def solution(N):
num = bin(N)[2:].split('1')
if len(num[1:-1]) == 0:
return 0
return len(max(num[1:-1], key=lambda x: len(x)))
|
a = int(input())
b = int ( input ( ) )
a = int(input())
|
class Solution(object):
def shuffle(self, nums, n):
"""
:type nums: List[int]
:type n: int
:rtype: List[int]
"""
shuffled_array = []
for i in range(0, n):
shuffled_array.append(nums[i])
shuffled_array.append(nums[i+n])
return ... |
word = 'Python'
word[0] = 'M'
|
#Operator Name Example
# > Greater than x > y
x = 5
y = 3
print(x > y) # true
|
# 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 ( x , y , z ) :
c = 0
while ( x and y and z ) :
x = x - 1
y = y - 1
z = z - 1
... |
# Voting with delegation.
# Information about voters
voters: public({
# weight is accumulated by delegation
weight: num,
# if true, that person already voted
voted: bool,
# person delegated to
delegate: address,
# index of the voted proposal
vote: num
}[address])
# This is a type for a... |
load(
"@com_googlesource_gerrit_bazlets//tools:junit.bzl",
"junit_tests",
)
def tests(tests):
for src in tests:
name = src[len("tst/"):len(src) - len(".java")].replace("/", "_")
labels = []
timeout = "moderate"
if name.startswith("org_eclipse_jgit_"):
package = n... |
class Hero:
"""
kahramanların tanımlanabileceği bir yapı oluşturun
parametre olarak adi,guc,saglik
darbe,vurma adında iki fonksiyon ile secilen karakterin güçleri
ölçüsünde diğer karakterin sağlığında eksiltmesini sağlayalım
istenildiğinde tek bir fonksiyon ile karakterin durumunu görebilelim
... |
#Exam
def solution(N):
if (N > 0) and (N < 1000): #Assume that N is an integer within 1 to 1000
list_of_coded_numbers = [] #List will contain the coded numbers in descending order
while N > 0:
if (N % 2 == 0) and (N % 3 == 0) and (N % 5 == 0):
list_of_coded_numbers.append... |
#
# This file is part of stac2odc
# Copyright (C) 2020 INPE.
#
# stac2odc is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
#
__version__ = '0.0.1'
|
"""
LINK: https://leetcode.com/problems/power-of-three/
Given an integer n, return true if it is a power of three. Otherwise, return false.
An integer n is a power of three, if there exists an integer x such that n == 3x.
Example 1:
Input: n = 27
Output: true
Example 2:
Input: n = 0
Output: false
Example 3:
Inpu... |
str = 'X-DSPAM-Confidence:0.8475'
print(str)
colon = str.find(":")
fnum = float(str[colon+1:])
print("Number from string equals:", fnum)
|
# Python > Strings > String Validators
# Identify the presence of alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters in a string.
#
# https://www.hackerrank.com/challenges/string-validators/problem
#
if __name__ == '__main__':
s = input()
# any alphanumeric characters... |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
a=input()
print(a[0].upper()+a[1:]) |
DOMAIN = "airthings"
KEY_API = "api"
PLATFORMS = ("sensor",)
ERROR_LOGIN_FAILED = "login_failed"
|
'''
The MIT License (MIT)
Copyright (c) 2016 WavyCloud
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, p... |
def updatePars():
if not parent().par.Lockbuffermenu:
return
op('output_table_path').cook(force=True)
dat = op('output_table')
if dat.numRows < 2:
return
p = parent().par.Outputbuffer
p.menuNames = dat.col('name')[1:]
p.menuLabels = dat.col('label')[1:]
def onTableChange(dat):
updatePars()
def onValueChang... |
def test(name):
print("from method", name)
test("hello")
def printinfo(name, age=18):
print(name, age)
printinfo("cgy")
# 单个*号参数以数组传入
def uncertainLength(name, *args):
for x in args:
print(x, end=",")
print(name, len(args))
uncertainLength("cgy", 10, 20, 30)
# ** 2个星号参数以dict传入
def u... |
def error_Check(inputX, inputY, nSamples, initVector, minCost, alpha,
training_epochs, silent, overlap, objFunc,
keepPercent, batchSize, batching):
acceptedObjFuncs = ["", "QUAD"]
if inputX.shape[0] != inputY.shape[0]:
print("Must have the same number of labels... |
n1 = int(input('Um valor: '))
n2 = int(input('Outro valor: '))
s = n1 + n2
m = n1 * n2
d = n1 / n2
di = n1 // n2
e = n1 ** n2
su = n1 - n2
print('A soma é {}, produto é {} e a divisão {:.2f}.'.format(s, m, d), end='>>>')#exemplo -> end='' => continua na mesma linha
print('Divisão inteira é {}, a potencia é {:.2f} e a d... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 25 14:06:56 2020
Class to handle coordinates in Hive according to how they are used in the
entomology Hive position editor.
cf.
https://entomology.appspot.com/hive.html?bg=0&board=:w***@bA**@bB***@bG*@bL*@bM*@bP*@bQ**@bS***@wA**@wB***@wG*@wL*@wM*@w... |
'''
Kattis - oddgnome
theres probably a smarter way, but i really can't be bothered
Time: O(n^2 log n), Space: O(n)
'''
num_tc = int(input())
for _ in range(num_tc):
arr = list(map(int, input().split()))
n = arr.pop(0)
for i in range(1, n):
new_arr = arr[:i] + arr[i+1:]
if new_arr == s... |
def force_bytes(value):
if isinstance(value, bytes):
return value
return str(value).encode('utf-8')
|
"""
## Questions : EASY
### 1844. [Replace All Digits with Characters](https://leetcode.com/problems/replace-all-digits-with-characters/)
You are given a 0-indexed string s that has lowercase English letters in its even indices and digits in its odd indices.
There is a function shift(c, x), where c is a character and... |
"""
Event dispatcher for non-browser Events which occur on Widget state changes.
"""
class EventDispatcher(object):
"""
Base class for event notifier.
"""
def __init__(self, name):
super(EventDispatcher, self).__init__()
self.queue = []
self.name = name
def _genTargetFuncName(self):
"""
Returns the... |
# 自定义数组结构
class Array(object):
"""自定义数组类"""
def __init__(self, len, default=None):
"""
数组初始化
:param len: 数组的长度
:param default: 数组的默认值
"""
self._item = list()
for i in range(len):
self._item.append(default)
def __str__(self):
"""... |
"""
Pagamento exigido pelo total de metros cúbicos de água ao encher uma piscina.
"""
preco_m3 = float(input("Informe o custo (R$) por metro cúbico de agua:"))
print("Informe as dimensões da piscina:")
Lar = float(input("Largura [metros]:"))
Comp = float(input("Comprimento [metros]:"))
Alt = float(input("Altura [metr... |
coords = []
for ry in range(-2, 3):
for rx in range(2, -3, -1):
x = rx / 4
y = ry / 4
coords.append((x,y))
for p in range(16):
y, x = divmod(p, 4)
top_right = coords[(y+1)*5 + x]
top_left = coords[(y+1)*5 + x + 1]
bottom_left = coords[y*5 + x + 1]
bottom_right = coords[y... |
"""df[{}] = df[{}].astype({})"""
def run(dfs: dict, settings: dict) -> dict:
"""df[{}] = df[{}].astype({})"""
if 'columns' not in settings:
raise Exception('Missing columns param')
dfs[settings['df']] = dfs[settings['df']].astype(settings['columns'])
return dfs
|
# -*- coding: utf-8 -*-
__author__ = 'Bruno Paes'
__email__ = 'brunopaes05@gmail.com'
__github__ = 'https://www.github.com/Brunopaes'
__status__ = 'Finalised'
class Viginere(object):
@staticmethod
def encrypt(plaintext, key):
key_length = len(key)
key_as_int = [ord(i) for i in key]
pla... |
"""
Hash tables :: Day 1 Notes: Arrays
An array:
* Stores a sequence of elements
* Each element must be the same data type
* Occupies a contiguous block of memory
* Can access data in constant time with this equation:
`memory_address = starting_address + index * data_size`
"""
class DynamicArray:
def __init__(... |
predictor_url = 'http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2'
predictor_file = '../weights/shape_predictor_68_face_landmarks.dat'
p2v_model_gdrive_id = '1op5_zyH4CWm_JFDdCUPZM4X-A045ETex'
sample_image = '../examples/sample.jpg'
|
def main(request, response):
name = request.GET.first(b"name")
value = request.GET.first(b"value")
source_origin = request.headers.get(b"origin", None)
response_headers = [(b"Set-Cookie", name + b"=" + value),
(b"Access-Control-Allow-Origin", source_origin),
... |
# Leetcode 435. Non-overlapping Intervals
#
# Link: https://leetcode.com/problems/non-overlapping-intervals/
# Difficulty: Medium
# Solution using sorting.
# Complexity:
# O(NlogN) time | where N represent the number of intervals
# O(1) space
class Solution:
def eraseOverlapIntervals(self, intervals: List[List... |
BOARD_TILE_SIZE = 56 # the size of each board tile
BOARD_PLAYER_SIZE = 20 # the size of each player icon
BOARD_MARGIN = (10, 0) # margins, in pixels (for player icons)
PLAYER_ICON_IMAGE_SIZE = 32 # the size of the image to download, should a power of 2 and higher than BOARD_PLAYER_SIZE
MAX_PLAYERS ... |
def truncate(string, length):
"Ensure a string is no longer than a given length."
if len(string) <= length:
return string
else:
return string[:length]
|
print(':-:' * 10)
print('{:^30}'.format('Cálculo de IMC'))
print(':-:' * 10)
peso = float(input('Seu peso: '))
altura = float(input('Sua altura em metros: '))
IMC = peso / pow(altura, 2)
situacao = '';
if IMC < 18.5:
situacao = 'Magreza'
elif IMC <= 24.9:
situacao = 'Normal'
elif IMC <= 29.9:
situacao =... |
def insertionSort(arr, size):
for i in range(1, size):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
def shakerSort(arr, size):
left = 0
right = size - 1
lastSwap = 0
... |
def mergeOverlappingIntervals(intervals):
sortedIntervals = sorted(intervals, key=lambda x: x[0])
overlappingIntervals = []
left = sortedIntervals[0][0]
right = sortedIntervals[0][1]
for i in range(1, len(sortedIntervals)):
if right >= sortedIntervals[i][0]:
right = max(right, so... |
# hash
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
count_map = {}
res = []
for num in nums1:
count_map[num] = count_map.get(num, 0) + 1
for num ... |
class Pessoa:
olhos = 2
def __init__(self, *filhos,nome=None, idade = 35):
self.idade = idade
self.nome = nome
self.filhos = list(filhos)
def cumprimentar(self):
return f" Olá {id(self)}"
@staticmethod
def metodo_estatico():
return 42
@classmethod
de... |
class GameLogic:
def __int__(self):
self
def add_lander(self, lander):
self.lander = lander
def update(self, delta_time):
self.lander.update_lander(delta_time) |
data = []
with open("data.txt") as file:
data = [int(x) for x in file.read().split(",")]
def part_one(data, noun, verb):
opcode = 0
data_c = data[:]
data_c[1] = noun
data_c[2] = verb
while True:
if data_c[opcode] == 1:
data_c[data_c[opcode + 3]] = data_c[data_c[... |
# coding=utf8
"""
Prolog Grammar of ATIS
"""
GRAMMAR_DICTIONARY = {}
ROOT_RULE = 'statement -> [answer]'
GRAMMAR_DICTIONARY['statement'] = ['(answer ws)']
GRAMMAR_DICTIONARY['answer'] = [
'("answer_1(" var "," goal ")")',
'("answer_2(" var "," var "," goal ")")',
'("answer_3(" var "," var "," var "," g... |
var = 'foo'
def ex2():
var = 'bar'
print ('inside the function var is ', var)
ex2()
def ex3():
global var
var = 'bar'
print ('inside the function var is ', var)
ex3()
print ('outside the function var is ', var)
|
'''
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, which
means losing its fractional part. For example,
trun... |
code = bytearray([
0xa9, 0xff,
0x8d, 0x02, 0x60,
0xa9, 0x55, # lda #$55
0x8d, 0x00, 0x60, #sta $6000
0xa9, 0x00, # lda #00
0x8d, 0x00, 0x60, #sta $6000
0x4c, 0x05, 0x80 #jmp 8005 (#lda $55)
])
rom = code + bytearray([0xea] * (32768 - len(code)) )
rom[0x7ffc] = 0x00
rom[0x7ffd] = 0x... |
_sampler = None
def get_sampler():
return _sampler
def set_sampler(sampler):
global _sampler
_sampler = sampler
|
class Node:
def __init__(self,id,parent,val):
self.id=id
self.parent=parent
self.ch1,self.ch2=0,0
self.val=val
self.leaf=True
n=int(input())
orix=[*map(int,input().split())]
x=sorted(orix)
node=dict()
node[1]=Node(1,0,-1)
cnt=1
li=[]
for i in x:
li2=[]
root=node[1]
... |
'''
Check-for-balanced-parentheses
Problem Statement : Given an expression string x. Examine whether
the pairs and the orders of
“{“,”}”,”(“,”)”,”[“,”]” are correct in exp.
For example, the function should return
'true' for exp = “[()]{}{[(... |
print('Progressão aritmética')
print(10*'_*_')
termo = int(input('Digite o primeiro Termo '))
razao = int(input('Digite a razão de uma P.A '))
print('Os 10 primeiros termos da progressão aritmética são:')
for c in range(1,11):
print(f'{termo}')
termo = termo + razao
print('Acabou')
|
#!/usr/bin/env python
# coding=utf-8
'''
@Author: John
@Email: johnjim0816@gmail.com
@Date: 2019-11-15 13:46:12
@LastEditor: John
@LastEditTime: 2020-07-29 22:43:12
@Discription:
@Environment:
'''
class Solution:
def singleNumber(self, nums: List[int]) -> int:
seen_once = seen_twice = 0
for num in... |
res = 0
i = 0
nb = int(input())
if nb == -1:
while i != 'F':
i = input()
if i != 'F':
res += int(i)
else:
for x in range(nb):
i = int(input())
res += i
print(res) |
def tema(str):
print(str)
print('-'*20)
tema('CONTROLE DE TERRENOS')
comprimento = float(input('LARGURA (m): '))
largura = float(input('COMPRIMENTO (m): '))
def área(largura, comprimento):
calculo = comprimento * largura
print(f'A área do terreno [{largura} x {comprimento}] é {calculo}m²')
área(compr... |
#
# Example file for working with conditional statements
#
def main():
x, y = 10, 100
# conditional flow uses if, elif, else
if x < y:
print("x is smaller than y")
elif x == y:
print("x has same value as y")
else:
print("x is larger than y")
# conditional statements let you use "a if C e... |
class AreaLight:
def __init__(self, shape_id, intensity, two_sided = False):
assert(intensity.device.type == 'cpu')
self.shape_id = shape_id
self.intensity = intensity
self.two_sided = two_sided
def state_dict(self):
return {
'shape_id': self.shape_id,
... |
"""
Scaling functions that take PCB and modbus register version numbers, and convert raw
register values into real values.
"""
def scale_5v(value, reverse=False, pcb_version=0):
"""
Given a raw register value and the PCB version number, find out what scale and offset are needed, convert the raw
value to a... |
#
# PySNMP MIB module CISCO-VOICE-CAS-MODULE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VOICE-CAS-MODULE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:02:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... |
#
# PySNMP MIB module CISCOSB-rlInterfaces (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-rlInterfaces
# Produced by pysmi-0.3.4 at Wed May 1 12:24:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
def solveQuestion(inputPath):
fileP = open(inputPath, 'r')
fileLines = fileP.readlines()
fileP.close()
newPosition = []
numRows = len(fileLines)
numCols = len(fileLines[0].strip('\n'))
for line in fileLines:
currentLine = []
for grid in line.strip('\n'):
... |
"""
The trick here is that I am using the new_ls parameter as a list to append.
Since this list is created on first call to the function it is the same object that
I append to.
"""
def rc(ls, new_ls=[]):
for x in ls:
if isinstance(x, list):
rc(x, new_ls)
else:
new_ls.append(... |
n = int(input())
if n%2 != 0:
print('Weird')
else:
if n in range(2, 6):
print('Not Weird')
if n in range(6, 21):
print('Weird')
if n > 20:
print('Not Weird')
|
def add_numbers(start, end):
total=0
for i in range(start,end+1):
total=total+i
return total
test1 = add_numbers(333, 777)
print(test1)
|
MOD = 10 ** 9 + 7
n, k = map(int, input().split())
dp = [0] * (k + 1)
ans = 0
for x in range(k, 0, -1):
dp[x] = pow(k // x, n, MOD)
for i in range(2 * x, k + 1, x):
dp[x] -= dp[i]
ans += dp[x] * x
ans %= MOD
print(ans) |
# Bidirectional BFS
class Solution(object):
def minKnightMoves(self, x, y):
offsets = [(1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)]
q1 = collections.deque([(0, 0)])
q2 = collections.deque([(x, y)])
steps1 = {(0, 0): 0} #steps needed starting from (0, 0)
... |
class School:
def __init__(self):
self.list_students = list()
self.list_data = list()
def add_student(self, name, grade):
self.list_students.append({"name": name, "grade": grade})
def roster(self):
return self.sort_student_list_by_name_and_grade()
def grade(self, grad... |
#!/usr/bin/python3
# * Copyright (c) 2020-2021, Happiest Minds Technologies Limited Intellectual Property. All rights reserved.
# *
# * SPDX-License-Identifier: LGPL-2.1-only
PE1_binding_chk = 'ipv4 PE1ID/32 P1ID imp-null'
P1_binding_chk1 = 'ipv4 P1ID/32 PE1ID imp-null'
P1_binding_c... |
# Url source:
# https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list
numbers = list(range(1, 50))
for i in numbers:
if i < 20:
numbers.remove(i)
print(numbers)
|
class Solution:
def shortestPathLength(self, graph):
def dp(node, mask):
state = (node, mask)
if state in cache:
return cache[state]
if mask & (mask - 1) == 0:
# Base case - mask only has a single "1", which means
# that onl... |
# Em uma competição de salto em distância cada atleta tem direito a cinco saltos.
# O resultado do atleta será determinado pela média dos cinco valores restantes.
# Você deve fazer um programa que receba o nome e as cinco distâncias alcançadas pelo atleta em seus saltos e depois informe o nome, os saltos e a média do... |
"""
复制的次数等分解质因数的次数,分解质因数的计算,主要有两个,递归和质数求解。
这里要使用 while 进行循环,而不能使用 for 因为 n 的次数会变。
"""
class Solution:
def minSteps(self, n: int) -> int:
res = 0
if n == 1:
return res
d = 2
while n > 1:
while (n % d == 0):
res += d
n //= d
... |
def format_dict(data, sep_item=", ", sep_key_value="=", brackets=True):
output = ""
delim = ""
for key, value in data.items():
output += f"{delim}{key}{sep_key_value}{value}"
delim = f"{sep_item}"
return f"{{{output}}}" if brackets else f"{output}"
def powerdict(data): # https://stack... |
#!/usr/bin/env python3
# Copyright 2019 Google LLC
#
# 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... |
class Auxiliar:#Ira auxiliar as buscas
#--------------------------Auxilia nas Buscas sem informação-----------------------------------
def expande(self, no, problema, tipo): #Expandira o nó
Conjfilhos = [] #Conjunto de Filhos
possibilidades = problema.acoes(no, tipo) #Possibilidades de filhos
... |
class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
if grid[0][0] == 1:
return -1
def neighbor8(i, j):
n = len(grid)
for di in (-1, 0, 1):
for dj in (-1, 0, 1):
if di == dj == 0:
... |
# x_4_5
#
# 「text」を逆さ読みで表示されるように修正してください
number = 0
text = 'ももからうまれた桃太郎'
while number < 11:
print(text[number])
number += 1
|
first = "Aditya"
last = "Mhambrey"
full = first+" "+last
print(full)
full = f"{first} {last} {2+2} {len(first)}"
print(full)
course = " Python Programming"
print(course.upper())
print(course.lower())
print(course.title()) # First Letter of every Word is capital
print(course.strip()) # Getting rid of white space
prin... |
def ler_numero(minimo, maximo):
while True:
try:
n = int(input(f'Digite um número entre {minimo} e {maximo}: '))
if minimo <= n <= maximo:
return n
else:
print(f'O número deve estar entre entre {minimo} e {maximo}')
except ValueErro... |
"""
@author: acfromspace
"""
# Time complexity: O(n^2)
# Space complexity: O(n)
def bubble_sort_1(data):
for i in range(len(data)-1, 0, -1):
for j in range(i):
if data[j] > data[j+1]:
data[j], data[j+1] = data[j+1], data[j]
return data
def bubble_sort_2(data):
# %las... |
__author__ = 'วรรณพงษ์'
#import re
print("Text")
a = input("Text")
if a.find("+"):
s = a.split("+")
in1 = int(s[0])
in2 = int(s[1])
cal = in1 + in2
elif a.find("-"):
s = a.split("-")
in1 = int(s[0])
in2 = int(s[1])
cal = in1 - in2
elif a.find("*"):
s = a.split("*")
in1 = int(s[0]... |
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def has_cycle(head):
slow, fast = head, head
while fast is not None and fast.next is not None:
fast = fast.next.next
slow = slow.next
if slow == fast:
... |
#Sort an array of 0s, 1s and 2s
#It is a problem from geeksforgeeks and can be solved using python code
#Given an array A of size N containing 0s, 1s, and 2s; you need to sort the array in ascending order.
# Here t is the number of test cases,
# i is an iterative variable,
# n is the number of elements in list,
# x i... |
# list(map(int, input().split()))
# int(input())
def main():
X = int(input())
if X >= 30:
print('Yes')
else:
print('No')
if __name__ == '__main__':
main()
|
class ManageCards:
cards = {}
cards["154-98-11-133-118"] = "1"
cards["64-91-169-137-59"] = "2"
cards["46-245-168-137-250"] = "3"
cards["198-241-168-137-22"] = "4"
cards["127-72-227-41-253"] = "5"
cards["78-4-170-137-105"] = "6"
cards["119-174-226-41-18"] = "7"
cards["98-155-250-41-42"] = "8"
cards["1-112-16... |
# Copyright 2017 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
'''An e-commerce website wishes to find the lucky customer who will be eligible for full value cash back. For this purpose,a number N is fed to the system. It will return another number that is calculated by an algorithm. In the algorithm, a sequence is generated, in which each number n the sum of the preceding numbers... |
class CommonsShared:
# period, step, and episode counter
periods_counter = 1
steps_counter = 1
episode_number = 0
# number of periods considered for calculating short and long term sustainabilities
n_steps_short_term = 1
n_steps_long_term = 4
# number of agents
n_agents = 5
# ... |
"""Top-level package for CY Quant Components."""
try:
__import__('pkg_resources').declare_namespace(__name__)
except ImportError:
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
__author__ = """Gatro CY"""
__email__ = 'cragodn@gmail.com'
__version__ = '0.3.14'
|
def test_ci_placeholder():
# This empty test is used within the CI to
# setup the tox venv without running the test suite
# if we simply skip all test with pytest -k=wrong_pattern
# pytest command would return with exit_code=5 (i.e "no tests run")
# making travis fail
# this empty test is the re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.