content stringlengths 7 1.05M |
|---|
#!/usr/bin/python3
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# With a given integral number n, write a program to generate a
# dictionary that contains (i, i*i) such that is an integral number
# between 1 and n (both included). and then the program should print the
# dictionary.
#
# Supp... |
n = [3, 5, 7]
def total(numbers):
result = 0
for i in range(len(numbers)):
result += numbers[i]
return result
print(total(n))
|
with open("input.txt") as fp:
instructions = [(line.strip('\n')[0], int(line.strip('\n')[1:]))
for line in fp]
moves = {'E': 1, 'W': -1, 'N': 1, 'S': -1, 'R': 1, 'L': -1}
sides = 'ESWN'
current_direction = 'E'
current_coords = (0, 0)
current_waypoint_offset = (10, 1)
current_waypoint_coords = (... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""WDOM: Browser-based GUI library for python."""
|
#!/usr/bin/python
command = (oiio_app("maketx") + " --filter lanczos3 "
+ parent + "/oiio-images/grid-overscan.exr"
+ " -o grid-overscan.exr ;\n")
command = command + testtex_command ("grid-overscan.exr", "--wrap black")
outputs = [ "out.exr" ]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Author:
"""
class Roboter:
pass
if __name__ == "__main__":
x = Roboter()
y = Roboter()
print(x)
print(y)
print(x == y)
|
n = int(input())
horas = n // 3600
n %= 3600
minutos = n // 60
n %= 60
segundos = n
print(f'{horas}:{minutos}:{segundos}')
|
def bot_reply(bot, contact, str):
_str = '机器人回复: '+str
bot.SendTo(contact, _str)
watch_group_name = ['创客学院管理员社群',
'VR/AR/Unity3D/C#/创客',
# '创客学院VR/AR②群',
# 'Web前端/HTML/创客学院',
# '物联网_ARM_创客学院',
# '单片机/ARM/STM3... |
# optimizer
optimizer = dict(type='AdamW', lr=0.0001, weight_decay=0.0005)
optimizer_config = dict(grad_clip=dict(max_norm=1, norm_type=2))
# learning policy
lr_config = dict(
policy='step',
warmup='linear',
warmup_iters=1000,
warmup_ratio=0.001,
step=[60000, 72000],
by_epoch=False)
# runtime se... |
#!/usr/bin/env python3
#global num_path
#num_path = 0
class Path:
num_path = 0
def __init__(self, start, end):
self.passed_by = False
self.start = start
self.end = end
def __str__(self):
return "{}-{} [{}]".format(self.start, self.end, "T" if self.passed_by else "F")
def __eq__(self, n):
retur... |
a = input('输入')
if bool(a):
aa = int(a)
else:
aa = 0
if not aa>1:
print('this way is ok')
else:
print('dame')
b = input()
print(str(b)) |
#!/usr/bin/env python3
"""
Simple python file allowing one to add a row (or multiple rows) into the
sinkhole list in one fell swoop in combination with the add_rows.py file.
Simply populate this data structure and run add_rows.py at the terminal to
add rows to the sinkhole list.
"""
# Example. Only th... |
execfile("Modified_data/data_record.dr")
trick.sim_services.exec_set_terminate_time(300.0)
|
class BaseConfig:
DEBUG = True
TESTING = False
SECRET_KEY = 'melhor isso aqui depois =D'
class Producao(BaseConfig):
SECRET_KEY = 'aqui deve ser melhorado ainda mais - de um arquivo de fora.'
DEBUG = False
class Desenvolvimento(BaseConfig):
TESTING = True
|
def regular_intervals(points, interval):
cum_distance = 0.0
first = True
for p in points:
if first:
yield p
first = False
else:
cum_distance += p['distance']
last_p = p
if cum_distance >= interval:
yield p
cum_dista... |
# Base of the number - count of digits used un that number system
# Smallest entity of data in computing is a bit - either 0 or 1
# bit = BInary digiT
# Bit to the extreme left is the MSB (Most Significant Bit)
# Bit to the extreme right is the LSB (Least Significant Bit)
class ConvertToBinary:
def __init__(self, ... |
"""**nte**
A CLI scratch pad for notes, commands, lists, etc
"""
__version__ = "0.0.7"
|
with open('2017/day_02/list.txt', encoding="utf-8") as f:
lines = f.readlines()
v = 0
for i in lines:
t = i.split('\t')
t[len(t)-1] = t[len(t)-1].split('\n')[0]
t.sort(key=int)
v += int(t[len(t)-1]) - int(t[0])
print(v) |
class Nodo():
def __init__(self, val, izq=None, der=None):
self.valor = val
self.izq = izq
self.der = der
|
x = int(input('Digite um valor:'))
print('{} x {} = {}'.format(x, 1, (x *1)))
print('{} x {} = {}'.format(x, 2, (x*2)))
print('{} x {} = {} '.format(x, 3,(x*3)))
print('{} x {} = {}'.format(x, 4, (x*4)))
print('{} x {} = {}'.format(x, 5, (x*5)))
print('{} x {} = {}'.format(x, 6, (x*6)))
print('{} x {} = {} '.format(x,... |
li = [1, 1] #_ [int,int,]
it = iter(li) #_ listiterator
tu = (1, 1) #_ (int,int,)
it = iter(tu) #_ tupleiterator
ra = range(2) #_ [int,int,]
it = iter(ra) #_ listiterator
|
# -*- encoding: utf-8 -*-
# @Time : 11/24/18 3:00 PM
# @File : settings.py
TEXTS_SIZE = 400
TEXT_NOISE_SIZE = 410
EMBEDDING_SIZE = 300
PREFIX = "/gated_fusion_network"
IMAGES_SIZE = 4
IMAGE_NOISE_SIZE = 50
LEAVES_SIZE = 300
LEAF_NOISE_SIZE = 350
EMBEDDING_MATRIX_FN = PREFIX + "/word2vec_embedding_matrix.pkl... |
class Solution(object):
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
squares = []
j = 1
while j * j <= n:
squares.append(j * j)
j += 1
level = 0
queue = [n]
visited = [False] * (n + 1)
... |
"""
@author: David Lei
@since: 21/08/2016
@modified:
Not a comparison sort, so comparison O(n log n) lower bound doesn't apply
Visualization: https://www.cs.usfca.edu/~galles/visualization/CountingSort.html
How it works: Integer sorting algorithm - it counts the number of objects
Applies when element... |
def grade(autogen, key):
n = autogen.instance
if "flag_{}_do_the_hard_work_to_make_it_simple".format(n) == key.lower().strip():
return True, "Correct!"
else:
return False, "Try Again."
|
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 17 09:27:36 2016
@author: tih
"""
def Accounts(Type=None):
User_Pass = {
'NASA': ['',''],
'GLEAM': ['', ''],
'FTP_WA': ['',''],
'MSWEP': ['', ''],
'Copernicus': ['', ''], #https://land.copernicus.vgt.vito.be/PDF/
'VITO': ['', '']} ... |
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/389/A
# 最大公约数?
# 只要有两个互质的话就可以减到1, 那所有的也都可以减到1!
# 问题=求n个数的最大公约数!!
def gcd(a,b):
if a<b:
a,b=b,a
if b==0:
return a
return gcd(b,a%b)
def f(l):
n = len(l)
g = l[0]
for i in range(1,n):
g = gcd(l[i],g)
... |
score_regular = {'A': 11, 'K': 4, 'Q': 3, 'J': 2, 'T': 10, '9': 0, '8': 0, '7': 0}
score_trump = {'A': 11, 'K': 4, 'Q': 3, 'J': 20, 'T': 10, '9': 14, '8': 0, '7': 0}
inp = input().split()
hands = int(inp[0])
trump_suite = inp[1]
score = 0
for i in range(4*hands):
hand = input()
score += score_trump[hand[0]] i... |
# A single node of a singly linked list
class Node:
# constructor
def __init__(self, data, next=None):
self.data = data
self.next = next
# Creating a single node
first = Node(3)
print(first.data)
|
def battle_bfs(arr, wolf_count, sheep_count, where, R, C):
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
while where:
x, y = where.pop()
now = []
if arr[x][y] == 'v' or arr[x][y] == 'k':
now.append((x, y))
twolf = 0
tsheep = 0
while now:
n... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Desc:
@Author: shane
@Contact: iamshanesue@gmail.com
@Software: PyCharm
@Since: Python3.6
@Date: 2019/1/9
@All right reserved
""" |
"""
Fça um programa que leia nome e peso de várias pessoas,
guardando tudo em uma lista. No final mostre:
A) Quantas pessoas foram cadastradas.
B) Uma listagem com as pessoas mais pesadas.
C) Uma listagem com as pessoas mais leves.
"""
todos = []
lista = []
maior = menor = 0
print('='*30)
print(f'{"CADASTRO DE PESSOAS"... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Author: Ssfanli
@Time : 2020/04/14 10:36 下午
@Desc :
"""
|
def get_index(flower_n):
if flower_n == "Roses":
return 0
elif flower_n == "Dahlias":
return 1
elif flower_n == "Tulips":
return 2
elif flower_n == "Narcissus":
return 3
elif flower_n == "Gladiolus":
return 4
flower = input()
count_of_flowers = int(input())
... |
# Copyright 2014 The Bazel 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 la... |
class Condor:
def __init__(self):
self.desc = 'load2: jsub_ext3.backend.condor.Condor'
class ClassWithSpecificName:
def __init__(self):
self.desc = 'load1: jsub_ext3.backend.condor.ClassWithSpecificName'
class ClassWithAnotherName:
def __init__(self):
self.desc = 'load2: jsub_ext3.... |
n=str(input())
d={"0":"zero","1":"one","2":"two","3":"three","4":"four","5":"five",
"6":"six","7":"seven","8":"eight","9":"nine"}
for i in n:
print(d[i],end=" ")
|
# -*- coding: utf-8 -*-
# Área de un círculo
def area_circulo(entRadio):
pi = 3.14159
return pi*(radio**2)
radio = 8
area_circulo = area_circulo(radio)
print("El área del círculo es ", area_circulo)
|
# -*- coding: utf-8 -*-
"""Top-level package for nider."""
__author__ = """Vladyslav Ovchynnykov"""
__email__ = 'ovd4mail@gmail.com'
__version__ = '0.5.0'
|
# Much faster and more elegant than brute force solution
def remove(array, even):
if even:
mod = 2
else:
mod = 1
return [array[i] for i in range(len(array)) if i % 3 == mod]
num_elves = 3014387
elves = [i + 1 for i in range(num_elves)]
while len(elves) > 1:
midpoint = int(len(elves) ... |
#Config
MYSQL_HOST = '45.78.57.84'
MYSQL_PORT = 3306
MYSQL_USER = 'ss'
MYSQL_PASS = 'ss'
MYSQL_DB = 'shadowsocks'
MANAGE_PASS = 'ss233333333'
#if you want manage in other server you should set this value to global ip
MANAGE_BIND_IP = '127.0.0.1'
#make sure this port is idle
MANAGE_PORT = 23333
|
def longest_palindromic_subsequence(s, subStr = False):
'''
动态规划算法的优化
时间复杂度o(n^2),将空间复杂度降低为o(2n)
用nlist存储j情况下所有的子串是否为回文子串的标志
用olist存储j-1情况下所有的子串是否为回文子串的标志
find the longest_palindromic_subsequence(lps) and the lenth of lps in s.
it can return the logestSubStr as well.
you can set subStr=T... |
numero = list(range(1, 10, 1))
print(numero)
numeros1 = list(range(10, 0, -1))
print(numeros1)
for ex in range(0, 13, 2):
print(ex, end=', ')
print('\n')
lista = ['ana', 'patricia', 'joão', 'mateus', 'jhony']
for nome in range(len(lista)):
print(nome, lista[nome])
|
class Solution:
# @param s, a string
# @return a string
def reverseWords(self, s):
b = s.rstrip().lstrip().split(' ')
b = filter(lambda x: len(x) > 0, b)
b.reverse()
return ' '.join(b) |
# Copyright (c) 2020-2022, Adam Karpierz
# Licensed under the BSD license
# https://opensource.org/licenses/BSD-3-Clause
__import__("pkg_about").about()
__copyright__ = f"Copyright (c) 2020-2022 {__author__}" # noqa
|
n=100
f=1
for i in range(1,101):
f*=i
print(f)
s=0
c=str(f)
for i in c:
s+=int(i)
print("sum is ",s)
|
"""
Homework | Exceptions
18-09-2020
Alejandro AS
"""
# how to create a custom exception
class CustomError(Exception):
# class need to extends from BaseException
# you can declare a constructor to recibe some custom values like a message
def __init__(self, *args):
""" This method inits ... |
# a terrible brute force way to get a list of values (with key) in disired order
def ez_sort(ListToSort,ListInOrder,index=0):
Ordered = []
for x in ListInOrder:
i = 0
for y in ListToSort:
if y[index] == x:
Ordered.append(y)
i = i + 1
return Ordered
... |
'''
Control:
robot.move_forward()
robot.rotate_right()
robot.rotate_left()
robot.display_color(string)
robot.finish_round()
Sensors:
robot.ultrasonic_front() -> int
robot.ultrasonic_right() -> int
robot.ultrasonic_left() -> int
robot.get_color() -> string
'''
def main():
robot.m... |
name = '{name:s}'
isins = 'isinstance(' + name + ', '
isStr = 'isinstance({name:s}, str)'
isstr = isStr + ' or {name:s} is None'
isTpl = 'isinstance({name:s}, tuple)'
istpl = isTpl + ' or {name:s} is None'
isBool = 'isinstance({name:s}, (bool, np.bool_))'
isbool = isBool + ' or {name:s} is None'
isInt = 'isinstance({n... |
class LFSR():
"""
Class that implements 'basic' Linear Feedback Shift Register (LFSR) for the generation of pseudo random numbers
"""
def __init__(self, fb_poly):
self.fb_poly = fb_poly
exponents = fb_poly.split()
self.degree = int(exponents[0])
indices = ["0"]*(self.deg... |
# keyboard input and concatenation
name = input("Enter Name: ")
color = input("What's your favorite color? ")
count = input("How many? ")
print(name + " ate " + count + ' ' + color + " dicks today.") |
# coding: utf-8
class Issue(object):
def __init__(self, api):
"""
:param api:
"""
self.api = api
def list(self, **kwargs):
"""
https://developer.nulab-inc.com/ja/docs/backlog/api/2/get-issue-list/
:param kwargs: query parameter
:return:
... |
#!/usr/bin/env python3
#
# MIT License
#
# Copyright (c) 2020-2021 EntySec
#
# 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... |
SERVER_HOST = '0.0.0.0'
SERVER_PORT = 5000
SECRET_KEY = 'ABCJKSKMKJFJIF'
DEBUG = True
|
# my_lambbdata/polos.py
# Polo Class!
# attributes / properties (NOUNS): size, style, color, texture, price
# methods (VERBS): wash, fold, pop collar
class Polo():
def __init__(self, size, color):
self.size = size
self.color = color
@property
def full_name(self):
return f"{self.si... |
'''Criar um algoritmo que leia o salario de um funcionário e mostre seu novo salario, com 15% de almento.'''
print('-'*60)
salario = float(input('Digite seu salário atual: R$ '))
aumento = (salario * (15/100)) + salario
print('Seu salário atual é R${:.2f}, mas com 15% de aumento você passa a receber R${:.2f}.'.format(... |
class IncompatibilityCause(Exception):
"""
The reason and Incompatibility's terms are incompatible.
"""
class RootCause(IncompatibilityCause):
pass
class NoVersionsCause(IncompatibilityCause):
pass
class DependencyCause(IncompatibilityCause):
pass
class ConflictCause(IncompatibilityCa... |
# Constants
IMG_SIZE = (48, 48)
EMOTIONS = {
# 'anger': 1,
# 'disgust': 2,
# 'fear': 3,
4: 'happy',
# 'sad': 5,
6: 'surprise',
}
THRESHOLDS = {
# 1: 0.5,
# 2: 0.5,
# 3: 0.5,
4: 0.80,
# 5: 0.5,
6: 0.6,
}
|
class FrontendPortName(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_frontend_port_name(idx_name)
class FrontendPortNameColumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_frontend_ports()
|
# part 1
with open("inputs/day1.txt", "r") as f:
lines = f.read().strip().split("\n")
n_increases = 0
for left, right in zip(lines[:-1], lines[1:]):
if int(right) > int(left):
n_increases += 1
print("Part 1:", n_increases)
# part 2
n_increases = 0
prevval = None
for left, middle, right in zip(lin... |
"""Madlibs Stories."""
class Story:
"""Madlibs story.
To make a story, pass a list of prompts, and the text
of the template.
>>> s = Story(["noun", "verb"],
... "I love to {verb} a good {noun}.")
To generate text from a story, pass in a dictionary-like thing
of {prompt: ans... |
#!/usr/bin/env python
# Copyright 2015 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... |
class C:
def method(self):
def foo():
def bar():
pass
# bar
# bar
# bar
# method
# class
|
class TemplateError(Exception):
pass
class TemplateSyntaxError(TemplateError):
"""Raised to tell the user that there is a problem with the template."""
def __init__(self, message, lineno=None, name=None,
source=None, filename=None, node=None):
TemplateError.__init__(self, message... |
""". regress totemp gnpdefl gnp unemp armed pop year
Source | SS df MS Number of obs = 16
-------------+------------------------------ F( 6, 9) = 330.29
Model | 184172402 6 30695400.3 Prob > F = 0.0000
Residual | 836424.129 ... |
# -*- coding: utf-8 -*-
__author__ = """Jason Emerick"""
__email__ = 'jason@mobelux.com'
__version__ = '0.3.2'
|
"""
Desafio do contador com estrutura de repetição
for / while
0 10
1 9
2 8
3 7
4 6
5 5
6 4
7 3
8 2
9 1
10 0
"""
for n1, n2 in enumerate(range(10, 0, -1)):
print(n1, n2)
|
def test_user_login_logged_in(cli_run, mock_user):
result = cli_run(['user', 'login'])
assert result.exit_code == 0
assert 'Hello' in result.output
|
class Solution:
def findMedianSortedArrays(self, nums1: [int], nums2: [int]) -> float:
if len(nums1) > len(nums2): nums1, nums2 = nums2, nums1
l, r = 0, 2 * len(nums1)
while l <= r:
m1 = (l + r) // 2
m2 = len(nums1) + len(nums2) - m1
left1 = nums1[(m1 - 1)... |
#!/usr/bin/env python3
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
... |
"""
Crie um programa que leia duas notas de um aluno e calcule sua média, mostrando uma mensagem no final, de acordo com
a média atingida:
- Média abaixo de 5.0:
REPROVADO.
- Média entre 5.0 e 6.9:
RECUPERAÇÃO
- Média 7.0 ou superior:
APROVADO.
"""
print(('\033[1m<\033[m' * 6) + ' \033[35mSISTEMA DE VERIFICAÇÃO DE MÉDI... |
class BUILD_TREE(object):
def __init__(self, **args):
self.tree = {}
def _convertargs(self, args):
for item, value in args.items():
if not ((type(value) is list) or (type(value) is dict)):
args[item] = str(value)
def populateTree(self, tag, text='', attr=None, c... |
__author__ = 'ktisha'
class A:
ccc = True
def foo(self):
self.ccc = False |
class Solution(object):
def countBattleships(self, board):
"""
:type board: List[List[str]]
:rtype: int
"""
# cycle through each point
# check surrounding
# add one
# set surroundgs to .
count = 0
for row in range(0, len(board)):
... |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
F=open('input.txt','r')
W=open('output.txt','w')
a=F.readline()
b=int(F.readline())
W.write(str('RL'[a[0]=='f'and b<2 or a[0]=='b'and b>1]))
W.close()
|
"""This problem was asked by Amazon.
Given a pivot x, and a list lst, partition the list into three parts.
• The first part contains all elements in lst that are less than x
• The second part contains all elements in lst that are equal to x
• The third part contains all elements in lst that are larger than x
Ordering w... |
#
# PySNMP MIB module ERI-DNX-SMC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ERI-DNX-SMC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:51:36 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
class File_List:
wordList=[]
def __init__(self):
self.wordList = ['.c', '.h', '.java', '.py', '.php',
'.html', '.css', '.xml', '.tcp', 'sqlite3.o',
'sqlite.o', 'sqlite2.o', '.sh', '.dat', '.josn',
'http', 'www', 'sconscript',
... |
_base_ = [
'../_base_/models/resnet50_doc_quality.py', '../_base_/datasets/doc_quality.py',
'../_base_/schedules/schedule_200.py', '../_base_/default_runtime.py'
]
|
load("//python:python_grpc_compile.bzl", "python_grpc_compile")
def python_grpc_library(**kwargs):
# Compile protos
name_pb = kwargs.get("name") + "_pb"
python_grpc_compile(
name = name_pb,
**{k: v for (k, v) in kwargs.items() if k in ("deps", "verbose")} # Forward args
)
# Pick de... |
class ChangelogError(Exception):
pass
class ChangelogParseError(ChangelogError):
pass
class ChangelogValidationError(ChangelogError):
pass
class ChangelogMissingConfigError(ChangelogError):
def __init__(self, message: str, field: str = None):
super().__init__(message)
self.field = ... |
def no_space(x):
l = []
for i in x:
if i == " " :
continue
l.append(i)
return ''.join(l)
def no_space1(x):
x = x.replace(" ", "")
return x |
# fn to generate fibonacci numbers upto a given range
def fibonacci_Series(upto):
fibonacci_list = []
x = 0
y = 1
while x < upto:
fibonacci_list.append(x)
x, y = y, x+y
return fibonacci_list
# Driver's Code
print(fibonacci_Series(100)) |
"""
Problem Description:
José is from South America and hence, Spanish is his mother tongue. He wants to travel around the world and, therefore, decides to learn various languages, starting with English. He tries to learn the alphabetical order.. You being a good teacher will help him in doing so. He said he would lear... |
# Elabore um programa que calcule o valor a ser pago por um produto,
# considerando o seu preço normal e condição de pagamento:
#
# – à vista dinheiro/cheque: 10% de desconto
#
# – à vista no cartão: 5% de desconto
#
# – em até 2x no cartão: preço formal
#
# – 3x ou mais no cartão: 20% de juros#
print('=-=' * 5, 'Loja... |
people = {'name': 'Henrique', 'sex': 'M', 'age': 24}
print(f'{people["name"]} is {people["age"]} years old')
print(people.keys())
print(people.values())
print(people.items())
for key, values in people.items():
print(f'{key} = {values}')
del people['sex']
print(people)
people['name'] = 'Gustavo'
people['weight'] ... |
try:
print(int(input()))
except:
print("Bad String")
|
def pairwise(iterable):
it = iter(iterable)
a = next(it, None)
for b in it:
yield (a, b)
a = b
num_tests = int(input())
for test in range(num_tests):
num_walls = int(input())
walls = list(map(int, input().split()))
h = l = 0
if len(walls) >= 2:
for c, n in pairwise(walls):
if n > c:
... |
# MIT License
#
# Copyright (c) 2019 Nathaniel Brough
#
# 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, me... |
#
# This file is subject to the terms and conditions defined in
# file 'LICENSE', which is part of this source code package.
#
class Menu:
def __init__(self, header=None, choices=None, on_show=None, on_invalid_choice=None, key_sep=': ', input_text='Choice: ', invalid_choice_text='Invalid input.'):
self.head... |
'''
Reversed Queue
Write a function that takes a queue as an input and returns a reversed version of it.
'''
# Solution
class LinkedListNode:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.num_elements = 0
self.head = None
... |
class Solution:
def maximalSquare(self, matrix):
if not matrix:
return 0
row = [0] * len(matrix[0])
res = 0
for i in xrange(len(matrix)):
top_left = 0
for j in xrange(len(matrix[i])):
if matrix[i][j] == "0":
... |
nome = str(input('Digite seu nome completo: ')).strip()
print(f'Muito prazer em te conhecer!')
nomes = nome.title().split()
print(f'Seu primeiro nome é {nomes[0]}')
print('Seu último nome é {}'.format(nomes[len(nomes)-1]))
|
class Ring:
"""Parent class/interface for all rings to inherit from"""
def __init__(self, name, element_type, is_commutative=False):
self.name = name
self.element_type = element_type
self.is_commutative = is_commutative
# Stuff we need to implement in child classes
def one(self... |
"""Mapping nucleoside names to its fragments."""
KB_FRAGMENTATION_INFO: dict = {
"uridine": {
# U
"comments": "precursor can not be seen in MS2 in some cases",
"references": ["Jora et al. 2018"],
"fragments": {
"uridine -Ribose": {"formula": "C(4)H(4)N(2)O(2)"}, # 113.0... |
optimizer = dict(type='Adam', lr=0.001)
optimizer_config = dict(grad_clip=None)
lr_config = dict(policy='poly', power=0.9)
total_epochs = 5000
checkpoint_config = dict(interval=10)
log_config = dict(interval=5, hooks=[dict(type='TextLoggerHook')])
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
r... |
'''
026 - Faça um programa que leia uma frase pelo teclado e mostre:
- Quantas vezes aparece a letra "A".
- Em que posição ela aparece a primeira vez.
- Em que posição ela aparece a última vez.
'''
phrase = str(input('Digite uma frase: ')).upper().strip()
print("A frase que você digitou foi: {}".format(phrase))
print(... |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Command-journalling persistence framework inspired by Prevayler.
This package is deprecated since Twisted 11.0.
Maintainer: Itamar Shtull-Trauring
"""
|
# Simple game in python
print('Hi, welcome to the Tim quiz!')
print('Try to get as many questions correct as possible...')
totalQuestions = 4
score = 0
ans = input('1. What is the name of my youtube channel? ')
if ans.lower() == 'tech with tim':
print('Correct!')
score += 1
else:
print('In... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.