content stringlengths 7 1.05M |
|---|
"""
Copyright 2020 Vadim Kholodilo <vadimkholodilo@gmail.com>, Iulia Durova <yulianna199820@gmail.com>
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 limit... |
"""
C 1.19
---------------------------------
Problem Statement : Demonstrate how to use Python’s list comprehension syntax to produce
the list [ a , b , c , ..., z ], but without having to type all 26 such
characters literally.
Author : Saurabh
"""
print([chr(x + 97) for x in range(26)])
|
"""lesson6/solution_simple_functions.py
Contains solutions for simple functions.
"""
# Exercise 1: Write a function that prints your name and try calling it.
# Work in this file and not in the Python shell. Defining functions in
# a Python shell is difficult. Remember to name your function something
# that indicat... |
# Link class
class Link:
## Constructor ##
def __init__(self, text = "None", url = "None", status_code = 000): # Not the keyword 'None' so it will still print something
# Dictionary of URL-related content
self.text = text
self.url = url
self.status_code = status_code
# ... |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 agreed ... |
# -*- coding: utf-8 -*-
"""Manages custom event formatter helpers."""
class FormattersManager(object):
"""Custom event formatter helpers manager."""
_custom_formatter_helpers = {}
@classmethod
def GetEventFormatterHelper(cls, identifier):
"""Retrieves a custom event formatter helper.
Args:
id... |
template_open = '{{#ctx.payload.aggregations.result.hits.hits.0._source}}'
template_close = template_open.replace('{{#','{{/')
kibana_url = (
"{{ctx.metadata.kibana_url}}/app/kibana#/discover?"
"_a=(columns:!(_source),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f,"
"index:'metr... |
c = get_config()
#Export all the notebooks in the current directory to the sphinx_howto format.
c.NbConvertApp.notebooks = ['*.ipynb']
c.NbConvertApp.export_format = 'latex'
c.NbConvertApp.postprocessor_class = 'PDF'
c.Exporter.template_file = 'custom_article.tplx'
|
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[List[int]]:
complement = {}
out = []
for i,n in enumerate(nums):
complement[target-n] = i
for i,n in enumerate(nums):
idx = complement.get(n, None)
if idx != None and idx !... |
#To solve Rat in a maze problem using backtracking
#initializing the size of the maze and soution matrix
N = 4
solution_maze = [ [ 0 for j in range(N) ] for i in range(N) ]
def is_safe(maze, x, y ):
'''A utility function to check if x, y is valid
return true if it is valid move,
return false otherwise
'''
i... |
for i in range(2):
print(i) # print 0 then 1
for i in range(4,6):
print (i) # print 4 then 5
"""
Explanation:
If only single argument is passed to the range method,
Python considers this argument as the end of the range and the default start value of range is 0.
So, it will print all the numbers starting from 0 an... |
# called concatenation sometimes..
str1 = 'abra, '
str2 = 'cadabra. '
str3 = 'i wanna reach out and grab ya.'
combo = str1 + str1 + str2 + str3
# you probably don't remember the song.
print(combo)
# you can also do it this way
print('I heat up', '\n', "I can't cool down", '\n', 'my life is spinning', '\n', 'round... |
#!/usr/bin/env python3
"""Initialize.
Turn full names into initials.
Source:
https://edabit.com/challenge/ANsubgd5zPGxov3u8
"""
def __initialize(name: str, period: bool=False) -> str:
"""Turn full name string into a initials string.
Private function used by initialize.
Arguments:
name {[str]}... |
#Funções:__________________________________________________________________
def cadastro():
resp=input(print("Deseja cadastrar alguém?"))
if resp.upper()!= "N":
while resp.upper()!= "N":
arq=open("teste.txt","a")
nome=input(print("Digite seu nome"))
arq.write("... |
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/main/LICENSE
# Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt
__version__ = "2.11.2"
version = __version__
|
def method1(X, Y):
m = len(X)
n = len(Y)
L = [[None] * (n + 1) for i in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
L[i][j] = 0
elif X[i - 1] == Y[j - 1]:
L[i][j] = L[i - 1][j - 1] + 1
els... |
def combination(n, r):
r = min(n - r, r)
result = 1
for i in range(n, n - r, -1):
result *= i
for i in range(1, r + 1):
result //= i
return result
N, A, B = map(int, input().split())
v_list = list(map(int, input().split()))
v_list.sort(reverse=True)
mean_max = sum(v_list[:A]) / A
... |
variable1 = input('Variable 1:')
variable2 = input('Variable 2:')
variable1, variable2 = variable2, variable1
print(f"Variable 1: {variable1}")
print(f"Variable 2: {variable2}") |
# Copyright 2014 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 ... |
def main():
# Manage input file
input = open(r"C:\Users\lawht\Desktop\Github\ROSALIND\Bioinformatics Stronghold\Complementing a Stand of DNA\Complementing a Stand of DNA\rosalind_revc.txt","r")
DNA_string = input.readline(); # take first line of input file for counting
# Take in input file of DNA stri... |
"""
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# ... |
"""
Crie um programa que leia vários números inteiros pelo teclado. No final da execução, mostre a média entre
todos os valores e qual foi o maior e o menor valores lidos. O programa deve perguntar ao usuário se ele
quer ou não continuar a digitar valores.
"""
resposta = 'S'
cont = soma = maior = menor = media = 0
whi... |
all_591_cities = [
{
"city": "台北市",
"id": "1"
},
{
"city": "新北市",
"id": "3"
},
{
"city": "桃園市",
"id": "6"
},
{
"city": "新竹市",
"id": "4"
},
{
"city": "新竹縣",
"id": "5"
},
{
"city": "基隆市",
"id": "2"
},
{
"city": "宜蘭縣",
"id": "21"
},
{
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def part_1(program):
i = 0
while i < len(program):
opcode, a, b, dest = program[i:i+4]
i += 4
assert opcode in {1, 2, 99}, f'Unexpected opcode: {opcode}'
if opcode == 1:
val = program[a] + program[b]
elif opcod... |
# Copyright 2021 Duan-JM, Sun Aries
# 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 agreed to in writi... |
# Copyright (C) 2007-2012 Red Hat
# see file 'COPYING' for use and warranty information
#
# policygentool is a tool for the initial generation of SELinux policy
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the ... |
"""
Compartmentalize:
[ ascii art input ]
---------------
| maybe some |
| sort of auxillary |
| drawing program |
|
|
\ /
v
[ lex/parser ] --> [ translater ]
--------- ----------
| grammar | | notes literals|
| to numerical |
... |
if __name__ == "__main__":
"""
Pobierz podstawe i wysokosc trojkata i wypisz pole.
"""
print("podaj podstawe i wysokosc trojkata:")
a = int(input())
h = int(input())
print(
"pole trojkata o podstawie ", a, " i wysokosci ", h, " jest rowne ", a * h / 2
)
"""
Pobierz dlu... |
#
# 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 agreed to in writing, software
# distributed under... |
logo = """
_____________________
| _________________ |
| | Pythonista 0. | | .----------------. .----------------. .----------------. .----------------.
| |_________________| | | .--------------. || .--------------. || .--------------. || .--------------. |
| ___ ___ ___ ___ | | | ______ | || | ... |
fd = open('f',"r")
buffer = fd.read(2)
print("first 2 chars in f:",buffer)
fd.close()
|
# from http://www.voidspace.org.uk/python/weblog/arch_d7_2007_03_17.shtml#e664
def ReadOnlyProxy(obj):
class _ReadOnlyProxy(object):
def __getattr__(self, name):
return getattr(obj, name)
def __setattr__(self, name, value):
raise AttributeError("Attributes can't be set on t... |
settings = {"velocity_min": 1,
"velocity_max": 3,
"x_boundary": 800,
"y_boundary": 800,
"small_particle_radius": 5,
"big_particle_radius": 10,
"number_of_particles": 500,
"density_min": 2,
"density_max": 20
} |
'''8. Write a Python program to count occurrences of a substring in a string.'''
def count_word_in_string(string1, substring2):
return string1.count(substring2)
print(count_word_in_string('The quick brown fox jumps over the lazy dog that is chasing the fox.', "fox")) |
test = {
"name": "q2",
"points": 1,
"hidden": True,
"suites": [
{
"cases": [
{
"code": r"""
>>> sample_population(test_results).num_rows
3000
""",
"hidden": False,
"locked": False,
},
{
"code": r"""
>>> "Test Result" in sample_population(test_results).labe... |
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if not s:
return True
stack = []
for char in s:
if char == '{' or char == '[' or char == '(':
stack.append(char)
else:
... |
def read_data():
rules = dict()
your_ticket = None
nearby_tickets = []
state = 0
with open('in') as f:
for line in map(lambda x: x.strip(), f.readlines()):
if line == '':
state += 1
continue
if line == 'your ticket:':
co... |
mapping = {
"settings": {
"index": {
"max_result_window": 15000,
"analysis": {
"analyzer": {
"default": {
"type": "custom",
"tokenizer": "whitespace",
"filter": ["english_s... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 26 15:06:57 2021
@author: user24
"""
file = "./data/tsuretsuregusa.txt"
with open(file, "r", encoding="utf_8") as fileobj:
while True:
# set line as value of the file line
line = fileobj.readline()
# removes any white space at the end of strin... |
'''
https://www.hackerrank.com/challenges/strings-xor/submissions/code/102872134
Given two strings consisting of digits 0 and 1 only, find the XOR of the two strings.
'''
def strings_xor(s, t):
res = ""
for i in range(len(s)):
if s[i] != t[i]:
res += '1'
else:
res += '0'... |
salario = float(input('Qual o seu salário? R$ '))
if salario <= 1250:
novo = salario + (salario * 15 / 100)
else:
novo = salario + (salario * 10 / 100)
print(f'Seu novo salário é R${novo :.2f}.') |
__description__ = "Gearman RPC broker"
__config__ = {
"gearmand.listen_address": dict(
description = "IP address to bind to",
default = "127.0.0.1",
),
"gearmand.user": dict(
display_name = "Gearmand user",
description = "User to run the gearmand procses as",
default... |
bot_token = ''
waiting_timeout = 5 # Seconds
admin_id = ""
channel_id = ""
bitly_access_token = ""
vars_file = ""
|
# parsetab.py
# This file is automatically generated. Do not edit.
_tabversion = '3.5'
_lr_method = 'LALR'
_lr_signature = '5E2BB3531AA676A6BB1D06733251B2F3'
_lr_action_items = {'COS':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,... |
# The following is a list of gene-plan combinations which should
# not be run
BLACKLIST = [
('8C58', 'performance'), # performance.xml make specific references to 52DC
('7DDA', 'performance') # performance.xml make specific references to 52DC
]
IGNORE = {
'history' : ['uuid', 'creationTool', 'creationD... |
#This exercise is Part 4 of 4 of the Tic Tac Toe exercise series. The other exercises are: Part 1, Part 2, and Part 3.
#
#In 3 previous exercises, we built up a few components needed to build a Tic Tac Toe game in Python:
#
# Draw the Tic Tac Toe game board
# Checking whether a game board has a winner
# Handle... |
track = dict(
author_username='alexisbcook',
course_name='Data Cleaning',
course_url='https://www.kaggle.com/learn/data-cleaning',
course_forum_url='https://www.kaggle.com/learn-forum/172650'
)
lessons = [ {'topic': topic_name} for topic_name in
['Handling missing values', #1
... |
"""
https://leetcode.com/problems/3sum/
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A... |
# !usr/bin/python
# -*- coding: UTF-8 -*-
class Image:
def __init__(self, name, path, url):
self.name = name
self.path = path
self.url = url
@property
def full_path(self):
return self.path + self.name
def __str__(self):
return self.name
def __repr__(self... |
def metade(preco,sit):
if sit==True:
return (f'R${preco/2}')
else:
return preco/2
def dobro(preco,sit):
if sit==True:
return (f'R${preco * 2}')
else:
return preco * 2
def aumentar(preco,r,sit):
if sit==True:
return (f'R${preco * (100 + r)/100}')
else:
... |
""" Test filters used by test_toolbox_filters.py.
"""
def filter_tool( context, tool ):
"""Test Filter Tool"""
return False
def filter_section( context, section ):
"""Test Filter Section"""
return False
def filter_label_1( context, label ):
"""Test Filter Label 1"""
return False
def filt... |
word=input("enter any word:")
d={}
for x in word:
d[x]=d.get(x,0)+1
for k,v in d.items():
print(k,"occured",v,"times") |
#!/usr/bin/env python3
average = 0
score = int(input('Enter first score: '))
score += int(input('Enter second score: '))
score += int(input('Enter third score: '))
average = score / 3.0
average = round(average, 2)
print(f'Total Score: {score}')
print(f'Average Score: {average}')
|
"""restrictive_growth_strings.py: Constructs the lexicographic
restrictive growth string representation of all the way to partition a set,
given the length of the set."""
__author__ = "Justin Overstreet"
__copyright__ = "oversj96.github.io"
def set_to_zero(working_set, index):
"""Given a set and an index, set ... |
"""
Author: Sean Toll
Test simulation functionality
"""
print("Test")
|
def binary_tree(r):
"""
:param r: This is root node
:return: returns tree
"""
return [r, [], []]
def insert_left(root, new_branch):
"""
:param root: current root of the tree
:param new_branch: new branch for a tree
:return: updated root of the tree
"""
t = root.pop(1)
i... |
# Copyright 2022 Huawei Technologies Co., Ltd
#
# 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 agreed to... |
def is_valid(r, c, size):
if 0 <= r < size and 0 <= c < size:
return True
return False
count_presents = int(input())
n = int(input())
matrix = []
nice_kids_count = 0
given_to_nice = 0
for _ in range(n):
data = input().split()
matrix.append(data)
nice_kids_count += data.count("V")
santa_... |
# Setup
opt = ["yes", "no"]
directions = ["left", "right", "forward", "backward"]
# Introduction
name = input("What is your name, HaCKaToOnEr ?\n")
print("Welcome to Toonslate island , " + name + " Let us go on a Minecraft quest!")
print("You find yourself in front of a abandoned mineshaft.")
print("Can yo... |
#Julian Conneely, 21/03/18
#WhileIF loop with increment
#first 5 is printed
#then it is decreased to 4
#as it is not satisfying i<=2
#it moves on
#then 4 is printed
#then it is decreased to 3
#as it is not satisfying i<=2,it moves on
#then 3 is printed
#then it is decreased to 2
#as now i<=2 has completely satisfied, ... |
MIN_CONF = 0.3
NMS_THRESH = 0.3
USE_GPU = False
MIN_DISTANCE = 50
WEIGHT_PATH = "yolov3-tiny.weights"
CONFIG_PATH = "yolov3-tiny.cfg" |
def f(x, y):
"""
Args:
x (Foo
y (Bar : description
""" |
class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
k = 0
for n in nums:
k ^= n
return k |
expected_output = {
"address_family":{
"ipv4":{
"bfd_sessions_down":0,
"bfd_sessions_inactive":1,
"bfd_sessions_up":0,
"intf_down":1,
"intf_up":1,
"num_bfd_sessions":1,
"num_intf":2,
"state":{
"all":{
"sessions":2,... |
n = int(input('Insira um número: '))
print('_' * 12)
print(f'{n} X 1 = {n*1}')
print(f'{n} X 2 = {n*2}')
print(f'{n} X 3 = {n*3}')
print(f'{n} X 4 = {n*4}')
print(f'{n} X 5 = {n*5}')
print(f'{n} x 6 = {n*6}')
print(f'{n} X 7 = {n*7}')
print(f'{n} X 8 = {n*8}')
print(f'{n} X 9 = {n*9}')
print(f'{n} X 10 = {n*10... |
class Stack():
def __init__(self):
self.items=[]
def isEmpty(self):
return self.items==[]
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def size(self):
return len(self.item... |
hola = True
adiosguillermomurielsanchezlafuente = True
if (adiosguillermomurielsanchezlafuente
and hola):
print("ok con nombre muy largo")
|
for i in range(1, int(input()) + 1):
quadrado = i ** 2
cubo = i ** 3
print(f'{i} {quadrado} {cubo}')
print(f'{i} {quadrado + 1} {cubo + 1}')
|
Scale.default = Scale.chromatic
Root.default = 0
Clock.bpm = 120
var.ch = var(P[1,5,0,3],8)
~p1 >> play('m', amp=.8, dur=PDur(3,8), rate=[1,(1,2)])
~p2 >> play('-', amp=.5, dur=2, hpf=2000, hpr=linvar([.1,1],16), sample=1).often('stutter', 4, dur=3).every(8, 'sample.offadd', 1)
~p3 >> play('{ ppP[pP][Pp]}', amp=.8,... |
def namedArgumentFunction(a, b, c):
print("the values are a: {}, b: {}, c: {}".format(a,b,c))
namedArgumentFunction(100, 200, 300) # positional arguments
namedArgumentFunction(c=3, a=1, b=2) # named arguments
#namedArgumentFunction(181, a=102, b=103) # mix of position + name error
namedArgumentFunction(101... |
# Basic String Operations (Title)
# Reading
# Iterating over a String with the 'for' Loop (section)
# General Format:
# for variable in string:
# statement
# statement
# etc.
name = 'Juliet'
for ch in name:
print(ch)
# This program counts the number of times the letter T
# ... |
height = int(input())
apartments = int(input())
is_first = True
isit = 0
for f in range(height, 0, -1):
for s in range(0, apartments, 1):
if is_first == True:
isit += 1
print(f"L{f}{s}", end=" ")
if isit == apartments:
is_first = False
cont... |
"""
Dominator Problem
by Codility
Solution by B Hamilton
An array A consisting of N integers is given.
The dominator of array A is the value that occurs in more than half of the
elements of A.
Write a function that, given an array A consisting of N integers, returns
index of any element of array A in which the ... |
#!/usr/bin/python3
# https://practice.geeksforgeeks.org/problems/twice-counter/0
def sol(words):
h = {}
res = 0
for word in words:
h[word] = h[word] + 1 if word in h else 1
for word in h:
if h[word] == 2:
res+=1
return res |
class Solution:
# Reverse Format String (Accepted), O(1) time and space
def reverseBits(self, n: int) -> int:
s = '{:032b}'.format(n)[::-1]
return int(s, 2)
# Bit Manipulation (Top Voted), O(1) time and space
def reverseBits(self, n: int) -> int:
ans = 0
for i in range(3... |
def count_frequency(a):
freq = dict()
for items in a:
freq[items] = a.count(items)
return freq
def solution(data, n):
frequency = count_frequency(data)
for key, value in frequency.items():
if value > n:
data = list(filter(lambda a: a != key, data))
... |
# Copyright 2020 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 agreed to in writing, ... |
inventory = {'croissant': 19, 'bagel': 4, 'muffin': 8, 'cake': 1}
print(f'{inventory =}')
stock_list = inventory.copy()
print(f'{stock_list =}')
stock_list['hot cheetos'] = 25
stock_list.update({'cookie' : 18})
stock_list.pop('cake')
print(f'{stock_list =}') |
#Program to change a given string to a new string where the first and last chars have been exchanged.
string=str(input("Enter a string :"))
first=string[0] #store first index element of string in variable
last=string[-1] #store last index element of string in var... |
"""
Class hierarchy for company management
"""
class Company:
def __init__(self, company_name, location):
self.company_name = company_name
self.location = location
def __str__(self):
return f"Company: {self.company_name}, {self.location}"
def __repr(self):
return f"Company... |
# Make sure to rename this file as "config.py" before running the bot.
verbose=True
api_token='0000000000:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
# Enter the user ID and a readable name for each user in your group.
# TODO make balaguer automatically collect user IDs.
# But that's only useful if the bot actuall... |
# if语句
games = ['CS GO', 'wow', 'deathStranding']
for game in games:
if game == 'wow': # 判断是否相等用'=='
print(game.upper())
# 检查是否相等
sport = 'football'
if sport == 'FOOTBALL':
print('yes')
else:
print('No') # 此处输出结果为No说明大小写不同不被认同是同一string、转化为小写在进行对比
for game in games:
if game.lower() == 'cs ... |
print ("--------------------------------------------------------")
print ("-------------Bienvenido a la Temperatura----------------")
print ("--------------------------------------------------------\n")
x = 0
while x < 10000:
print ("Elige tus opciones:")
print ("(1) Convertir de °C a °F")
print ("(2) Co... |
class GameException(Exception):
pass
class GameFlowException(GameException):
pass
class EndProgram(GameFlowException):
pass
class InvalidPlayException(GameException):
pass
|
# Copyright 2018 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
"""Partial response utilities for an Endpoints v1 over webapp2 service.
Grammar of a fields partial response string:
fields: selector [,select... |
def count_vowels(txt):
vs = "a, e, i, o, u".split(', ')
return sum([1 for t in txt if t in vs])
print(count_vowels('Hello world')) |
class GroupTransform:
"""
GroupTransform
"""
def __init__(self):
pass
def getTransform(self):
pass
def getTransforms(self):
pass
def setTransforms(self, transforms):
pass
def size(self):
pass
def push_back(self, transform):
pass
de... |
class KarmaCard(object):
info = {'type': ['number', 'wild'],
'trait': ['4', '5', '6', '7', '8', '9', 'J', 'Q', 'K', 'A', '2', '3', '10', 'draw'],
'order': ['4:4', '4:3', '4:2', '4:1', '5:4', '5:3', '5:2', '5:1', '6:4', '6:3', '6:2', '6:1',
'7:4', '7:3', '7:2', '7:1', ... |
#!/usr/bin/env python
# pylint: disable=too-few-public-methods
"""Reusable string literals."""
class DockerAuthentication:
"""
https://github.com/docker/distribution/blob/master/docs/spec/auth/token.md
https://github.com/docker/distribution/blob/master/docs/spec/auth/scope.md
"""
DOCKERHUB_URL_... |
def test_see_for_top_level(result):
assert (
"usage: vantage [-a PATH] [-e NAME ...] [-v KEY=[VALUE] ...] [--verbose] [-h] COMMAND..."
in result.stdout_
)
|
"""
Given an array of numbers sorted in ascending order, find the range of a given number ‘key’.
The range of the ‘key’ will be the first and last position of the ‘key’ in the array.
Write a function to return the range of the ‘key’. If the ‘key’ is not present return [-1, -1].
Example 1:
Input: [4, 6, 6, 6, 9], key... |
def wordBreakDP(word, dic):
n = len(word)
if word in dic:
return True
if len(dic) == 0:
return False
dp = [False for i in range(n + 1)]
dp[0] = True
for i in range(1, n + 1):
for j in range(i - 1, -1, -1):
if dp[j] == True:
substring = word[j:i... |
s = "Olá, mundo!";
print(s[::2]); # Imprime os caracteres nos índices pares.
print(s[1::2]) # Imprime os caracteres nos índices ímpares.
frase = "Mundo mundo vasto mundo"
print(frase[::-1]); #inverte a frase;
# Forma mais avançada de formatação de strings
frase_2 = "Um triângulo de base igual a {0} e altura igual a ... |
file1= "db_breakfast_menu.txt"
file2= "db_lunch_menu.txt"
file3= "db_dinner_menu.txt"
file4 = "db_label_text.txt"
retail = []
title = []
label = []
with open(file1, "r") as f:
data = f.readlines()
for line in data:
w = line.split(":")
title.append(w[1])
for line in data:
w... |
class Guesser:
def __init__(self, number, lives):
self.number = number
self.lives = lives
def guess(self,n):
if self.lives < 1:
raise Exception("Omae wa mo shindeiru")
match = n == self.number
if not match:
self.lives -= 1
return match |
def get_assign(user_input):
key, value = user_input.split("gets")
key = key.strip()
value = int(value.strip())
my_dict[key] = value
print(my_dict)
def add_values(num1, num2):
return num1 + num2
print("Welcome to the Adder REPL.")
my_dict = dict()
while True:
user_input = input("???")
... |
"""
Solution for
Sort Integers by The Power Value: https://leetcode.com/problems/sort-integers-by-the-power-value/
"""
class Solution:
def getKth(self, lo: int, hi: int, k: int) -> int:
# Can I calculate the power of an integer?
# if two ints have same power, sort by the ints
# power of 1... |
try:
for i in ['a', 'b', 'c']:
print(i ** 2)
except TypeError:
print("An error occured!")
x = 5
y = 0
try:
z = x /y
print(z)
except ZeroDivisionError:
print("Can't devide by zero")
finally:
print("All done")
def ask():
while True:
try:
val = int(input("Input a... |
NR_CLASSES = 10
hyperparameters = {
"number-epochs" : 30,
"batch-size" : 100,
"learning-rate" : 0.005,
"weight-decay" : 1e-9,
"learning-decay" : 1e-3
}
|
class DoublyLinkedList:
""" Private Node Class """
class _Node:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
def __str__(self):
return self.value
def __init__(self):
self.head = None
self.tai... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.