content stringlengths 7 1.05M |
|---|
print('Welcome to Number Guessing Mania - Game in Python')
while(True):
n = int(input('Enter a number :\n'))
if n == 18:
print('Yes you got it !!! \n')
break
elif n > 30:
print(f'Sorry, your entered number {n} is greater than expected.')
continue
elif n < ... |
df = pd.DataFrame(
np.random.randint(1, 7, 6000),
columns = ['one'])
df['two'] = df['one'] + np.random.randint(1, 7, 6000)
ax = df.plot.hist(bins=12, alpha=0.5)
|
_options = {
"cpp_std": "c++11",
"optimize": "3",
}
def set_option(name, value):
global _options
_options[name] = value
def get_option(name, default=None):
global _options
return _options.get(name, default)
|
load(
"@bazel_tools//tools/build_defs/repo:http.bzl",
"http_archive",
"http_file",
)
load("@com_google_protobuf//:protobuf_deps.bzl", "protobuf_deps")
########################################
# bazel_toolchains_repositories
########################################
#
# This rule configures the following rep... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
"""
Pre-order DFS
O(N) time and O(N) space
"""
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:t... |
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
result = ""
base = 26
digits = 1
while n > base:
n -= base
base = base * 26
digits += 1
n = n - 1
for i in range(... |
class Repeater:
def __init__(self, value):
if callable(value):
self._value = value
else:
self._value = lambda: value
def __iter__(self):
return self
def __next__(self):
return self._value()
|
while True:
command = input(">")
if command == 'help':
print("1) start")
print("2) stop")
print("3) quiet")
elif command == 'start':
print("Car started....Ready to Go")
elif command == 'stop':
print("Car stopped")
elif command == 'quiet':
print("Car te... |
def hcf(x, y):
divisor = 1
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller + 1):
if (x % i == 0) and (y % i == 0):
divisor = i
return divisor
num1 = int(input('Enter the first number: '))
num2 = int(input("Enter the second number: "))
print(nu... |
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Class for holding the data of a root of a Coxeter group
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
class Root(object):
def __init__(self, coords=(), index=None, mat=None):
"""
:param coords : coefficients of this root as... |
class DiscordanceReportResolution:
ONGOING = None
CONCORDANT = 'C'
CONTINUED_DISCORDANCE = 'D'
CHOICES = (
(CONCORDANT, 'Concordant'),
(CONTINUED_DISCORDANCE, 'Continued Discordance')
)
class ContinuedDiscordanceReason:
UNRESPONSIVE = 'U'
DIFFERENT_CURATION_METHODS = 'D'
... |
if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
L = [[a,b,c] for a in range(x+1) for b in range(y+1) for c in range(z+1)]
L = list(filter(lambda x : sum(x) != n, L))
print(L)
|
#Parameters
def say_hello(name, age):
print(f'Hello, I am {name} and I am {age} years old.')
#Default Parameters
def say_something(name='Andrei', age=20):
print(f'Hello, I am {name} and I am not {age} years old.')
say_something()
#Positional Arguments
say_hello('Elena', 14)
say_hello('John', 10)
#Keyword Ar... |
def find_numbers(lst, test):
numbers = []
for x in lst:
if test(x):
numbers.append(x)
return numbers
def is_even(n):
return n % 2 == 0
def is_big(n):
return n > 500
numbers = [2, 1, 3, 4, 1000, 10001, 1002, 100, -5, -101, -1]
print(find_numbers(numbers, is_big))
def negate(... |
'''import requests
# IDs of the datasets we want to query --> TODO: complete, maybe list in separate file?
datasets_interesting = ['S1084_80_2_409', 'S2060_83_4_435_ENG', 'S2140_87_1_459_ENG', 'S2212_91_3_490_ENG']
# Directory for output/RDF data
dir_processed_eb_rdf = 'data/processed_data/special_eb/metadata/'
def... |
N, T, *A = map(int, open(0).read().split())
t = 10 ** 9 + 1
d = {}
for a in A:
t = min(t, a)
d.setdefault(a - t, 0)
d[a - t] += 1
print(d[max(d)])
|
"""
Entradas --> 3 Valores float que son el valor de diferentes monedas
Chelines autriacos --> float --> x
Dramas griegos --> float --> z
Pesetas --> float --> w
Salidas --> 4 valores float que es la conversión de las anteriores monedas
Pesetas --> float --> x
Francos franceses --> float --> z
Dolares --> float --... |
mondey_temparature = [9.1, 8.8, 7.6]
for temparature in mondey_temparature:
print(round(temparature))
for letter in "helllo":
print(letter) |
def checkdata(b):
clear_output()
display(button0)
print('Initial Data Condition:')
#checkdata = pd.read_excel('story_'+ story.value+'/story'+ story.value+'.xlsx', sheet_name='sample')
checkdata = pd.read_excel('story_0/story0'+'.xlsx', sheet_name='sample')
checkdata['FC_Start_Date'] = checkdata[... |
major = 1
minor = 3
build = 6
version = f"{major}.{minor}.{build}"
|
def sortPositions(positions):
sorted_positions = {}
for eachposition in positions:
chromosome=eachposition.split(".")[0]
start,end = eachposition.split(":")[-1].split("-")
start,end=int(start),int(end)
sorted_positions[chromosome] = [start,end]
sorted_positions_new={} ... |
"""Buffer module to store constants and settings."""
DISP_MSEC = 50 # Delay between display cycles
CAMERA_NUM = 1
GPIO_UV_LED = 32
GPIO_COLOR_LED = 18
COLOR_LED_NUM = 40
CAMERA_RESOLUTION = (3040, 3040)
DISPLAY_RESOLUTION = (480, 480)
RED_GAIN = 4575
BLUE_GAIN = 918
TEST_IMAGE_NAME = "testImag... |
def array_advance(A):
furthest_reached = 0
i=0
lastIndex = len(A)-1
# If furthest reach still has range and we have not reached goal
while i <= furthest_reached and furthest_reached < lastIndex:
furthest_reached = max(furthest_reached, A[i]+i)
i += 1
return furthest_reached >= ... |
class ComputeRank(object):
def __init__(self, var_name):
self.var_name = var_name
def __call__(self, documents):
for i, document in enumerate(documents, 1):
document[self.var_name] = i
return documents
|
class Statistics:
"""
Represents the state of some players statistics.
Abstracts stat modifications (such as dealing damage).
"""
MAX_HP = 100.0
INITIAL_ARMOUR = 0.0
MAX_ARMOUR = 20.0
def __init__(self):
self.hp = self.MAX_HP
self.armour = self.INITIAL_ARMOUR
def de... |
"""
URLify: Write a method to replace all spaces in a string with '%20: You may assume that the string
has sufficient space at the end to hold the additional characters, and that you are given the "true"
length of the string. (Note: If implementing in Java, please use a character array so that you can
perform this o... |
"""Module containing dummy code objects for testing the Squirrel program with.
"""
def dummyfunc(word: str):
"""I do things"""
print(f'Hello {word}!')
return 0
class DummyClass():
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def __str__(self):
ret... |
output = """
[DEFAULT]
# the DEFAULT section is where you create variables
# that can be used in later sections
control_network = 192.168.10
test_network = 192.168.20
[TEST]
output_folder = data_{t}
# The data files will be appended with .iperf
data_file = %(output_folder)s
# This is the number of times to repeat the ... |
# Description: Functions in Python
# Defining a function
# 1. The keyword def introduces a function definition, followed by a function name.
# 2. The body of the function MUST start at the next line, and MUST be indented.
# 3. The first statement of the function body can OPTIONALLY be a string literal to describe the ... |
stocks = pd.read_csv('all_stocks_SP500.csv')
stocks = stocks.T
stocks.columns = stocks.iloc[0]
stocks = stocks[1:]
stocks['condition1'] = (stocks['price'] > stocks['200 MA']) & (stocks['price'] > stocks['150 MA'])
stocks['condition2'] = stocks['150 MA'] > stocks['200 MA']
#3 The 200-day moving average line is trending... |
"""PodmanPy Tests."""
# Do not auto-update these from version.py,
# as test code should be changed to reflect changes in Podman API versions
BASE_SOCK = "unix:///run/api.sock"
LIBPOD_URL = "http://%2Frun%2Fapi.sock/v3.2.1/libpod"
COMPATIBLE_URL = "http://%2Frun%2Fapi.sock/v1.40"
|
# pylint: disable=missing-docstring, unused-variable, pointless-statement, too-few-public-methods, useless-object-inheritance
class WrapperClass(object):
def method(self):
var = +4294967296
self.method.__code__.co_consts
|
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
# Version requirements for various tools. Checked by tooling (e.g. fusesoc),
# and inserted into the documentation.
#
# Entries are keyed by tool name. The value is either ... |
# physical constants in cgs
# Fundamental constants taken from NIST's 2010 CODATA recommended values
c = 2.99792458e10 # speed of light
h = 6.62606957e-27 # Planck constant
hbar = 1.054571726e-27 #
G = 6.67428e-8 # Gravitational constant
e = 4.80320451e-10 # Electron charge
... |
#
# PySNMP MIB module NOKIA-ALCHEMYOS-HARDWARE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NOKIA-ALCHEMYOS-HARDWARE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:23:17 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python vers... |
# Input contains a number of pairs of parentheses, extract each group seperately
stack = []
pairs = []
s = "Outer (First inner (first nested group) group) parentheses (another group)"
for i, char in enumerate(s):
if char == "(":
stack.append(i)
elif char == ")":
pairs.append((stack.pop(), i))... |
# TODO: Add import statements
# Assign the data to predictor and outcome variables
# TODO: Load the data
train_data = None
X = None
y = None
# Create polynomial features
# TODO: Create a PolynomialFeatures object, then fit and transform the
# predictor feature
poly_feat = None
X_poly = None
# Make and fit the polyno... |
#
# @lc app=leetcode id=53 lang=python
#
# [53] Maximum Subarray
#
# https://leetcode.com/problems/maximum-subarray/description/
#
# algorithms
# Easy (42.84%)
# Total Accepted: 471.5K
# Total Submissions: 1.1M
# Testcase Example: '[-2,1,-3,4,-1,2,1,-5,4]'
#
# Given an integer array nums, find the contiguous subarr... |
DB_VALUE_PREPROCESSING = "Calls or returns the specified input value's attribute when saved to the database"
FIXED_KWARGS = "Fixed run method keyword arguments"
IS_CONFIGURATION = "Whether this definition represents a configuration of the analysis (rather than data input)"
MAX_PARALLEL = "Maximal number of parallel exe... |
# Title : Print Prime Number till the specified limit
# Author : Kiran raj R.
# Date : 16:10:2020
userInput = int(input("Enter the limit of the prime number : "))
def primeLimit(limit):
for num in range(2, limit):
for i in range(2, num):
if num % i == 0:
break
else... |
built_modules = list(name for name in
"Core;Gui;Widgets;PrintSupport;Sql;Network;Test;Concurrent;WinExtras;Xml;XmlPatterns;Help;Multimedia;MultimediaWidgets;OpenGL;OpenGLFunctions;Positioning;Location;Qml;Quick;QuickControls2;QuickWidgets;RemoteObjects;Scxml;Script;ScriptTools;Sensors;SerialPort;TextToSpeech;Charts... |
"""
Given a floor of dimensions 2 x W and tiles of dimensions 2 x 1, the task is to find the number of ways the floor can be tiled. A tile can either be placed horizontally i.e as a 1 x 2 tile or vertically i.e as 2 x 1 tile. 4
Print the answer modulo 109+7.
Let “count(n)” be the count of ways to place tiles on a “2... |
class DelegateFake(object):
""" DelegateFake() """
def EditMacro(self,FileName):
""" EditMacro(self: DelegateFake,FileName: str) -> int """
pass
def ExplodeBentPlate(self,partId):
""" ExplodeBentPlate(self: DelegateFake,partId: int) -> int """
pass
def ExportAddComponentAttributeToStack(self,pAttr):
""" E... |
# Collaborators: none
#
# Write a program that asks for the user's name and another piece of information.Then prints a response using both of the inputs.
x= input("Your name: ")
print ("Hello there, " + x + "!")
y= input("How are you, " + x + "?: ")
print (y + " huh, okay thank you " + x + ", for letting me know!") |
class Solution:
def isMonotonic(self, A):
"""
:type A: List[int]
:rtype: bool
"""
is_asc = True
is_desc = True
for i in range(1, len(A)):
if A[i-1] < A[i]:
is_asc = False
if A[i-1] > A[i]:
is_des... |
#!/usr/bin/constants
""" Collection of physical constants
Main source: http://physics.nist.gov/cuu/Constants/index.html
"""
def AMU():
""" Atomic mass unit, kg """
return 1.660538782e-27
def AVOGADRO():
""" Avogadro constant, mol^-1 """
return 6.02214179e23
def BOLTZMANN():
""" Boltzmann constan... |
"""
Yatao (An) Bian <yatao.bian@gmail.com>
yataobian.com
May 13, 2019.
"""
# Fold ids
all_folds = [1,2,3,4,5,6,7,8,9,10]
amazon_categories = ('furniture', #0
'media', #1
'diaper', #2
'feeding', #3
'gear', #4
... |
t = int(input())
for _ in range(t):
l = list(map(str, input().split()))
for i in range(len(l) - 1):
l[i] = l[i][0].upper() + "."
l[len(l) - 1] = l[len(l) - 1][0].upper() + l[len(l) - 1][1:].lower()
print(" ".join(l)) |
# Time complexity: ?
# Space Complexity: ?
def newman_conway(num):
""" Returns a list of the Newman Conway numbers for the given value.
Time Complexity: O(n^2)
Space Complexity: O(n)
"""
if num == 0:
raise ValueError("ValueError")
if num == 1:
return '1'
s='1 1'
... |
num = 10
if num < 10:
print("number is less than 10")
elif num > 10:
print("number is greater than 10")
else:
print("the number is equal to 10")
|
"""Definition of chips."""
AM33XX = "AM33XX"
DRA74X = "DRA74X"
IMX6ULL = "IMX6ULL"
IMX8MX = "IMX8MX"
BCM2XXX = "BCM2XXX"
ESP8266 = "ESP8266"
EXYNOS5422 = "EXYNOS5422"
RYZEN_V1202B = "RYZEN_V1202B"
RYZEN_V1605B = "RYZEN_V1605B"
SAMD21 = "SAMD21"
SUN8I = "SUN8I"
S805 = "S805"
S905 = "S905"
S905X3 = "S905X3"
S922X = "S922... |
# Copyright 2018 Zhao Xingyu & An Yuexuan. 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... |
class Action(object):
def __init__(self, actionroot):
self.name = actionroot.find('./name').text
argumentLists = None
if len(actionroot.findall('./argumentList/argument')) > 0:
argumentLists = actionroot.findall('./argumentList/argument')
else:
argumentLists ... |
description = 'detector setup'
group = 'lowlevel'
devices = dict(
monitor = device('nicos.devices.generic.VirtualCounter',
description = 'simulated monitor',
fmtstr = '%d',
type = 'monitor',
visibility = (),
),
timer = device('nicos.devices.generic.VirtualTimer',
de... |
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
'''
T: O(n log k) and S: O(k)
result = []
for i in range(len(nums) - k + 1):
numsK = nums[i: i + k]
heapq._heapify_max(numsK)
result.append(numsK[0])
... |
# Marc's Cakewalk
# Developer: Murillo Grubler
# Link: https://www.hackerrank.com/challenges/marcs-cakewalk/problem
# Function O(n)
def must_walk(n, arr):
count = 0
for i in range(n):
count = count + (arr[i] * (2 ** i))
return count
n = int(input().strip())
calories = sorted(list(map(int, inpu... |
class LinkedListException(Exception):
pass
class Node(object):
def __init__(self, value, next_node, previous_node=None):
self.value = value
self.next_node = next_node
self.previous_node = previous_node
class _LinkedList(object):
def __init__(self):
self.last_nod... |
# começar com letra maiúscula o nome
class Conta:
def __init__(self, numero, titular, saldo, limite=1000.0) -> object:
print('[INFO] Endereço alocado: {}'.format(self))
self.__numero = numero
self.__titular = titular
self.__saldo = saldo
self.__limite = limite
... |
def encrypt(text,s):
# Cipher(n) = De-cipher(26-n)
s=s
text =text.replace(" ","")
result="" #empty string
for i in range(len(text)):
char=text[i]
if(char.isupper()): #if the text[i] is in upper case
result=result+chr((ord(char)+s-65)%26+65)
else... |
class Contact:
def __init__(self, first_name=None, last_name=None, id=None, all_phones_from_home_page=None,
all_emails_from_home_page=None, address=None, email=None, email2=None, email3=None,
home_phone=None, mobile_phone=None, work_phone=None, secondary_phone=None):
sel... |
tags = db.Table('tags',
db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'), primary_key=True),
db.Column('page_id', db.Integer, db.ForeignKey('page.id'), primary_key=True)
)
class Page(db.Model):
id = db.Column(db.Integer, primary_key=True)
tags = db.relationship('Tag', secondary=tags, lazy='sub... |
# -*- mode:python; coding:utf-8 -*-
# Copyright (c) 2020 IBM Corp. 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
#
#... |
# import pytest
# import calculator_cha2ds2 as cal
# import validation_cha2ds2 as val
# import fetch_data_cha2ds2 as fd
class TestCalculator:
def test_calculate(self):
assert True
class TestFetchData:
def test_fetch_data(self):
assert True
def test_create_connection(self):
asser... |
allPoints = []
epsilon = 0
def setup():
global rdp
size(400, 400)
for x in range(width):
xval = map(x, 0, width, 0, 5);
yval = exp(-xval) * cos(TWO_PI*xval);
y = map(yval, -1, 1, height, 0);
allPoints.append(PVector(x, y));
def draw():
global epsilon
bac... |
#
# PySNMP MIB module HP-ICF-BRIDGE (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-BRIDGE
# Produced by pysmi-0.3.4 at Mon Apr 29 19:20:52 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... |
rows = int(input("Enter number of rows: "))
k = 0
count=0
count1=0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(" ", end="")
count+=1
while k!=((2*i)-1):
if count<=rows-1:
print(i+k, end=" ")
count+=1
else:
... |
# faça um algoritmo que leia o salario de um funcionario e mostre seu novo salario, com 15% de
# aumento
salario_funcionario = float(input('\nInforme o seu salário atual R$ '))
salario = salario_funcionario
aumento = 15
novo_salario = salario + (salario * aumento / 100)
print('\nO seu salário anterior ao aumento de ... |
# -*- coding: utf-8 -*-
# ********************************************************
# Author and developer: Aleksandr Suvorov
# --------------------------------------------------------
# Licensed: BSD 3-Clause License (see LICENSE for details)
# --------------------------------------------------------
# Url: https://git... |
#!/usr/bin/env python
#
# Copyright (C) 2017 ShadowMan
#
class MaxSubSequenceSum(object):
def __init__(self, sequence: list):
self._sequence = sequence
self._sum = sequence[0]
self._left_index = 0
self._right_index = 0
def brute_force(self):
for start_i... |
def factorial(num):
sum = 1
for i in range(1,num+1):
sum=sum*i
print(sum)
num = int(input("enter the number"))
factorial(num)
|
class Solution:
def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:
res = []
for restaurant in restaurants:
i, r, v, p, d = restaurant
if veganFriendly == 1:
if v == 1 and p <= maxPrice a... |
if __name__ == '__main__':
zi = int(input('Enter a number:\n'))
n1 = 1
c9 = 1
m9 = 9
sum = 9
while n1 != 0:
if sum % zi == 0:
n1 = 0
else:
m9 *= 10
sum += m9
c9 += 1
print('%d \'9\' could to be divisible by %d' % (c9, zi))
r ... |
# A. donuts
def donuts(count):
if count < 10:
st="Number of donuts: " + str(count)
else:
st="Number of donuts: many"
return st
# B. both_ends
def both_ends(s):
if len(s) < 2:
st=""
else:
st=s[0]+s[1]+s[-2]+s[-1]
return st
# C. fix_start
def fix_start(s):
i=... |
def FreqToArfcn(band, tech, freq):
LTE_arfcn_table = {
'Band1':{'FDL_low':2110, 'NOffs-DL':0, 'FUL_low': 1920, 'NOffs-UL':18000, 'spacing': 190},
'Band2':{'FDL_low':2110, 'NOffs-DL':0, 'FUL_low': 1920, 'NOffs-UL':18000, 'spacing': 80},
'Band3':{'FDL_low':2110, 'NOffs-DL':0, 'FUL_low': 1920,... |
"""
Application Version.
Created on 12 Sep 2020
:author: semuadmin
:copyright: SEMU Consulting © 2020
:license: BSD 3-Clause
"""
__version__ = "1.1.5"
|
# Function chunks sourced from
# https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i + n]
def portfolio_input():
global port... |
def rawify_url(url):
if url.startswith("https://github.com"):
urlparts = url.replace("https://github.com", "", 1).strip('/').split('/') + [None] * 5
ownername, reponame, _, refvalue, *filename_parts = urlparts
filename = '/'.join([p for p in filename_parts if p is not None])
assert o... |
vertical_tile_number = 14
tile_size = 16
screen_height = vertical_tile_number*tile_size *2
screen_width = 800 |
# -*- coding: ascii -*-
u"""
:Copyright:
Copyright 2006 - 2017
Andr\xe9 Malo or his licensors, as applicable
:License:
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.... |
def test_pythagorean_triplet(a, b, c):
return a**2 + b**2 - c**2 == 0
for a in range(1, 1000):
for b in range(1, 1000):
if test_pythagorean_triplet(a, b, 1000-(a+b)):
print("Product of a*b*c:", a*b*(1000-a-b))
|
def cavityMap(grid):
m, n = len(grid[0]), len(grid)
if n < 3 or m < 3:
return grid
for i in range(1, m-1):
for j in range(1, n-1):
adjacent = [grid[i-1][j], grid[i+1][j],
grid[i][j+1], grid[i][j-1]]
if "X" in adjacent:
continue... |
"""
Custom Exception module.
This module contains custom exceptions used throughout the wappsto module.
"""
class DeviceNotFoundException(Exception):
"""
Exception to signify Device not being found.
This custom Exception extends the Exception class and implements no
custom methods.
Attributes:
... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
new_head, ... |
for row in range(7):
for col in range(4):
if col==3 or row==3 and col in {0,1,2} or row in {0,1,2} and col<1:
print('*',end=' ')
else:
print(' ',end=' ')
print()
### Method-4
for i in range(6):
for j in range(6):
if j==3 or i+j==3 or i==3:
print('*',end=... |
try:
type('abc', None, None)
except TypeError:
print(True)
else:
print(False)
try:
type('abc', (), None)
except TypeError:
print(True)
else:
print(False)
try:
type('abc', (1,), {})
except TypeError:
print(True)
else:
print(False)
|
def binary_search(list, key):
#Returns the position of key in the list if found, -1 otherwise.
#List must be sorted:
list.sort()
left = 0
right = len(list) - 1
while left <= right:
middle = (left + right) // 2
#print("começar com: ", middle)
if list[middle] == key:
... |
def mergeSort(myList):
if len(myList) > 1:
mid = len(myList) // 2
left = myList[:mid]
right = myList[mid:]
mergeSort(left)
mergeSort(right)
i,j,k = 0,0,0
while i < len(left) and j < len(right):
if left[i] < right[j]:
... |
#pylint: disable=unnecessary-pass
class Error(Exception):
"""Base class for exceptions in this module."""
class StatusCodeNotEqualException(Error):
"""Raises if status_code of url is not equal to 200"""
pass
class DriverVersionInvalidException(Error):
"""Raises if current driver version is not equal t... |
# Dictionary labels
txtTitle = "Who\'s talking"
txtBot = "Bot name"
txtAuth= "OAUTH token"
txtChannel = "Channel name"
txtNotConnd = "Not Connected"
txtListChat = "\nList of chatters"
txtIgnore = "Ignore"
txtConnd = "Connected"
txtStart = "Start"
txtStop = "Stop"
txtClear = "Clear"
txtConnect = "Connect"
txtDisconnect ... |
class Solution:
def largestAltitude(self, gain: List[int]) -> int:
altitude = 0; maxAltitude = 0
for g in gain:
altitude += g
maxAltitude = max(maxAltitude, altitude)
return maxAltitude |
"""
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
"""
# Definition for a binary tre... |
# Copyright 2013 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.
{
'variables': {
'chromium_code': 1,
},
'targets': [
{
'target_name': 'extensions_common',
'type': 'static_library',
'depende... |
def write(query):
query_list = filter(None, query.decode("utf-8").split('\r\n'))
for q in query_list:
print(q)
return str()
|
# -*- coding: utf-8 -*-
description = 'GALAXI motors'
group = 'optional'
tango_base = 'tango://phys.galaxi.kfa-juelich.de:10000/galaxi/'
s7_motor = tango_base + 's7_motor/'
devices = dict(
detz = device('nicos.devices.entangle.MotorAxis',
description = 'Detector Z axis',
tangodevice = s7_motor +... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 28 14:43:21 2018
@author: USER
"""
# global control atomic form factor
global_atomic_form_factor = 'factor' |
class Solution:
def majorityElement(self, nums: List[int]) -> int:
a=int(len(nums)/2)
b=list(set(nums))
for x in b:
if nums.count(x)>a:
return x
|
class TimeOutSettings(object):
"""Manages timeout settings for different work states:
- pending : work has not yet started and is waiting for resources
- starting : resources have been allocated and the work is being launched
- progress : work is active and computing"""
def __init__(sel... |
texto = input('Digite algo: ')
print('O tipo primitivo desse valor é {}', type(texto))
print('Só tem espaços? {}'.format(texto.isspace()))
print('É um número? {}'.format(texto.isnumeric()))
print('É alfabético? {}'.format(texto.isalpha()))
print('É alfanumérico? {}'.format(texto.isalnum()))
print('Está em maiúscula? {}... |
DEPOSIT_TYPE = 'deposit'
WITHDRAW_TYPE = 'withdraw'
TRANSFER_TYPE = 'transfer'
S3_SERVICE = 's3'
AWS_REGION = 'us-east-1'
|
# Copyright 2017 Istio 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 applicable law or... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.