content stringlengths 7 1.05M |
|---|
class Navio:
def __init__(self, nome, tamanho, direcao):
self.nome = nome
self.tamanho = tamanho
self.direcao = direcao |
description = 'GE detector setup PV values'
group = 'configdata'
EIGHT_PACKS = [
# ('ep01', 'GE-DD590C-EP'), # replaced 2015/10/29
('ep01', 'GE-DD6D8C-EP'),
('ep02', 'GE-DD5FB3-EP'),
('ep03', 'GE-DDA871-EP'),
('ep04', 'GE-DD7D29-EP'),
('ep05', 'GE-DDBA8F-EP'),
('ep06', 'GE-DD5913-EP'),
... |
# Write a program to print the pattern
'''
* *
* *
*
* *
* *
'''
n = int(input("Size: "))
s1 = 0
s2 = 2 * n - 3
i = 0
while (i < n):
if (i < n-1):
extra = "*"
else :
extra = ""
print(" " * s1 + "*" + " " * s2 + extra)
s1 += 1
s2 -= 2
i += 1
s1 -= 2
s2 += 4
i = 0
whi... |
def empty_float():
"""
>>> float()
0.0
>>> empty_float()
0.0
"""
x = float()
return x
def float_conjugate():
"""
>>> float_call_conjugate()
1.5
"""
x = 1.5 .conjugate()
return x
def float_call_conjugate():
"""
>>> float_call_conjugate()
1.5
""... |
"""
Exception module.
"""
__docformat__ = "restructuredtext en"
## Copyright (c) 2009 Emmanuel Goossaert
##
## This file is part of npy.
##
## npy is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either ver... |
# Write your solution here
def double_items(numbers):
double_numbers = []
for item in numbers:
double_numbers.append(item*2)
return double_numbers
if __name__ == "__main__":
numbers = [2, 4, 5, 3, 11, -4]
numbers_doubled = double_items(numbers)
print("original:", numbers)
print("dou... |
class SIG_REVERIESH(object):
KILL = 'SIG_REVERIESH_KILL'.encode()
PROMPT = 'SIG_REVERIESH_PROMPT'.encode()
class ascii_format:
magenta = '\033[95m'
blue = '\033[94m'
green = '\033[92m'
yellow = '\033[93m'
red = '\033[91m'
clear = '\033[0m'
bold = '\033[1m'
underline = '\033[4m'... |
#!/usr/bin/env python3
# Write a program that computes the running sum from 1..n
# Also, have it compute the factorial of n while you're at it
# No, you may not use math.factorial()
# Use the same loop for both calculations
n = 5
runsum = 0
factorial = 1
for i in range(1, n+1):
runsum += i # computes the running su... |
# -*- coding: utf-8 -*-
TOILET_CHOICES = (
('F', 'Flush'),
('PT', 'Pit toilet'),
('TPT', 'Traditional Pit toilet'),
('L', 'Latrine'),
('BF', 'Bush /Field'),
('R', 'River'),
('O', 'Others'),
)
COOKING_FACILITIES = (
('Electricity', 'Electricity'),
('Gas'... |
#
# PySNMP MIB module ZHONE-COM-IP-ZEDGE-NAT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHONE-COM-IP-ZEDGE-NAT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:41:01 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... |
# Data paths
DATA_BACKGROUND_FOLDER = "../data/background/"
DATA_GENERATED_FOLDER = "../data/generated_data/"
# General settings
IMAGES_TO_GENERATE = 500
COIN_RESIZE_RATIO_MIN = 0.4
COIN_RESIZE_RATIO_MAX = 0.6
# Background settings
BACKGROUND_RESIZE_RATIO = 400
BACKGROUND_MAX_N_COINS = 25
# Coin crop settings
MAX_CO... |
"""
This is the Blockchain
Model class implementation
"""
class Blockchain:
def __init__(self):
self.current_transactions = []
self.chain = []
self.nodes = set()
def __repr__(self):
return '<Blockchain(chain={self.chain!r}, current_transactions={self.current_transactions!r})>'.... |
#!/usr/bin/env python3
"""Helper for finding threshold values for CO alarm."""
# The calculation is based of https://github.com/ElectronicCats/MICS4514-Croquette
# and is not verified.
LOAD_RESISTOR_OHM = 47000
VSUP = 3.3
VREF = 3.3
ADC_RESOLUTION_BITS = 10
def _main():
"""Present the ppm value for each ADC raw ... |
"""
Given an array, find the nearest smaller element G[i] for every element A[i] in the array such that the element has an index smaller than i.
More formally,
G[i] for an element A[i] = an element A[j] such that
j is maximum possible AND
j < i AND
A[j] < A[i]
Elements for which no smaller element exist, ... |
"""
Faça um mini Sistema que utilize o interactive help do Python.
O usuário vai digitar o comando e o manual vai aparecer.
Quando o usuário digitar FIM, o programa se encerrará.
"""
# Funções
def ajuda(com):
help(com)
def titulo(mensagem):
tamanho = len(mensagem) + 4
print('~' * tamanho)
print(f... |
''' Crie um programa que simule o funcionamento de um caixa eletrônico. No início, pergunte ao usuário qual será o valor a ser sacado (número inteiro) e o programa vai informar quantas cédulas de cada valor serão entregues. OBS: considere que o caixa possui cédulas de R$100, R$50, R$20, R$10, R$5 e R$1. '''
valor = in... |
# Test values must be in the form [(text_input, expected_output), (text_input, expected_output), ...]
test_values = [
(
"president",
{
"n": {
"president",
"presidentship",
"presidencies",
"presidency",
"presi... |
def simulate_accuracy_vs_stoptime(sigma, stop_time_list, num_sample):
"""Calculate the average decision accuracy vs. stopping time by running
repeated SPRT simulations for each stop time.
Args:
sigma (float): standard deviation for observation model
stop_list_list (list-like object): a list of stoppi... |
def myfunc(str):
print(str)
nstr = str.lower()
for i in range(len(str)):
nstr[i+1].upper()
return nstr
print(myfunc("SlseJbKWdOEuhB")) |
'''
@Coded by TSG, 2021
Problem:
FizzBuzz is a well known programming assignment, asked during interviews.
The given code solves the FizzBuzz problem and uses the words "Solo" and "Learn" instead of "Fizz" and "Buzz".
It takes an input n and outputs the numbers from 1 to n.
For each multiple of 3, print "Solo" inst... |
#
# PySNMP MIB module HP-ICF-MLD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-MLD-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:22:09 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... |
# Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of Sick Beard.
#
# Sick Beard is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of t... |
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
start = 0
end = len(height)-1
best = 0
while start < end:
best = max(best, self.getArea(start,end,height))
if height[start] < height... |
def read_passphrases():
with open("day_04/input.txt", "r") as f:
return [line.split() for line in f.readlines()]
def part1():
return sum(len(phrase) == len(set(phrase)) for phrase in read_passphrases())
print(part1())
def anagram(passphrase):
return len(passphrase) == len(set("".join(sorted(ph... |
autoref_rst="""
Math
====
.. index ::
single: Math
This is the reference documentation for the math modules.
"""
__all__ = ['kernel'] |
"""
ID: IEV
Title: Calculating Expected Offspring
URL: http://rosalind.info/problems/iev/
"""
# 1. P(AA-AA) = 1 (AA, AA, AA, AA) = 4/4
# 2. P(AA-Aa) = 1 (AA, AA, Aa, Aa) = 4/4
# 3. P(AA-aa) = 1 (Aa, Aa, Aa, Aa) = 4/4
# 4. P(Aa-Aa) = 0.75 (AA, Aa, Aa, aa) = 3/4
# 5. P(Aa-aa) = 0.5 (Aa, Aa, aa, aa) = 2/4
# 6. P(aa-aa) =... |
def n_params(model):
"""Return the number of parameters in a pytorch model.
Args:
model (nn.Module): The model to analyze.
Returns:
int: The number of parameters in the model.
"""
pp = 0
for p in list(model.parameters()):
nn = 1
for s in list(p.size()):
... |
n = int(input())
a = sorted(list(map(int, input().split())))
if n % 2 == 1 and a[0] != 0:
print(0)
exit()
for i in range(n % 2, n, 2):
if a[i] != a[i + 1] or a[i] != i + 1:
print(0)
exit()
print(2 ** (n // 2) % (10 ** 9 + 7))
|
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
#--------------------------------------------------------------------------
# This is a placeholder file. It is deployed with inference only wheel.
pr... |
# Copyright 2010-2012 Institut Mines-Telecom
#
# 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 agre... |
'''
Basic Info
'''
__version__ = '0.1'
|
def maprange( a, b, s):
(a1, a2), (b1, b2) = a, b
return b1 + ((s - a1) * (b2 - b1) / (a2 - a1))
for s in range(11):
print("%2g maps to %g" % (s, maprange( (0, 10), (-1, 0), s)))
|
strings = {
'str NaN': 'NaN',
'str none': 'None',
'str true': 'True',
'str false': 'False',
'str 0': '0',
'str -1': '-1',
'str -1.5': '-1.5',
'str 0.42': '0.42',
'str .42': '.42',
'str 1.2E+9': '1.2E+9',
'str 1.2e8': '1.2e8',
'str 0xFF': '0xFF',
'str Inf..': 'Infinity... |
# coding: utf8
#!/usr/bin/python2
def directorymaker():
pass
|
# -------------------------------------------------#
# EXERCICIO 10 #
# -------------------------------------------------#
# Faça um programa que leia quanto dinheiro uma pessoa
# tem na carteira e mostre quantos dolares ela pode comprar
r = float(input('Digite quantos R$ voce tem na... |
ZALORA_URLS = ['https://www.zalora.co.id/women/pakaian/atasan/?from=header']
def get_start_urls():
return ZALORA_URLS
|
name0_0_0_1_0_1_0 = None
name0_0_0_1_0_1_1 = None
name0_0_0_1_0_1_2 = None
name0_0_0_1_0_1_3 = None
name0_0_0_1_0_1_4 = None |
## ⌠1 ⌠2
## ⌡-1 ⌡1 (x^2 y + x y^2) dx dy
f = lambda x, y: x**2 * y + x * y**2 # Equation to be integrated
ax = 1 # Lower limit of inner integral
bx = 2 # Upper limit of inner integral
ay = -1 # Lower limit of outer in... |
# Copyright (C) 2019-2020, TomTom (http://tomtom.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 o... |
email_info = { 'recepient' : 'a.b@c.com',
'messages' : {'TOO_LOW' : 'Hi, the temperature is too low',
'TOO_HIGH' : 'Hi, the temperature is too high'
}
}
def DefineCoolingtype_limits(coolingType):
coolingtype_limits = { 'P... |
#Задачи на циклы и оператор условия------
#----------------------------------------
'''
Задача 1
Вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована.
'''
str = '00000000000000000000000000000000'
for i in range(1,6):
print(i, '. ',str)
'''
Задача 2
Пользователь в цикле вв... |
# -*- coding: utf-8 -*-
# vim: set sw=4 ts=4 expandtab :
class ArgError(Exception):
def __init__(self, message):
if message == None:
self.message = 'node error'
else:
self.message = message
|
@PixieApp
class Test():
@route()
def main_screen(self):
return """
<button type="submit"
pd_script="call_me()"
pd_target="target{{prefix}}">
<pd_script>
self.name="some value"
print("This is a multi-line pd_script")
</pd_script>
Click me
</button>
... |
def formula_transform(formula):
"""
:param formula: dependent variable ~ covariant | fixed_effect |clusters'
:type formula: str
:return: Lists of out_col, consist_col, category_col, cluster_col, respectively.
:rtype: (list[str], list[str], list[str], list[str])
"""
phenotype = formula.repl... |
# encoding: utf-8
# module System.Custom calls itself Custom
# from Wms.RemotingObjects,Version=1.23.1.0,Culture=neutral,PublicKeyToken=null
# by generator 1.145
# no doc
# no important
# functions
def Tuple(args,kwargs): # real signature unknown
""" """
pass
# no classes
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if head is None:
return head
l = 1
tail = head
while tail.next:
... |
"""VIC Emergency Incidents constants."""
ATTR_CATEGORY1 = "category1"
ATTR_CATEGORY2 = "category2"
ATTR_DESCRIPTION = "description"
ATTR_ID = "id"
ATTR_PUB_DATE = "updated"
ATTR_SOURCE_TITLE = "sourceTitle"
ATTR_SOURCE_ORG = "sourceOrg"
ATTR_ESTA_ID = "estaid"
ATTR_RESOURCES = "resources"
ATTRIBUTION = "VICEmergency"
... |
class ApiException(Exception):
def __init__(self, response):
if response.status_code == 404:
self._rollbar_ignore = True
message = response.text
super(ApiException, self).__init__(message)
|
__author__ = 'Chirag'
x = {"Tom", 2.71, 36, 36} # is a set. REPETITION NOT ALLOWED
y = ["Tom", 2.71, 36, 36] # is a list. MUTABLE
print("x is a SET : ", x)
print("y is a LIST : ", y)
print()
#===========================================
# CREATE sets
s = {1,2,3,4,5} # direct declare
print(s)
s = set()
for i i... |
# -*- coding: utf-8 -*-
"""
File Name: countSmaller.py
Author : jynnezhang
Date: 2020/9/25 1:15 下午
Description:
https://leetcode-cn.com/leetbook/read/top-interview-questions/xajl22/
"""
class Solution:
def countSmaller(self, nums):
result = []
new_nums = nums[::-1]
for ind... |
# Python3 program to Merge Two Binary Trees
# Helper class that allocates a new node
# with the given data and None left and
# right pointers.
class newNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
# Given a binary tree, prints nodes
# in inorder
def inorder(node)... |
def find_lis(a):
T = [None]*len(a)
prev = [None]*len(a)
for i in range(len(a)):
T[i] = 1
prev[i] = -1
for j in range(i):
if a[j] <= a[i] and T[i]< T[j]+1:
T[i] = T[j]+1
prev[i] = j
longest =max(T)
i = 0
for i in range( ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 6 23:56:31 2010
@author: Alexander Tsepkov
"""
"""
This class wraps around ImageData HTML5 Canvas object and allows easier
per-pixel access
"""
class ImageData:
def __init__(self, imagedata):
self.width = imagedata.width
self.height = imagedata.heig... |
# Problem 3
# Largest prime factor
# The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143 ?
def is_prime(num):
if num == 1:
return False
i = 2
while i*i <= num:
if num % i == 0:
return False
i += 1
return True... |
# defines a mutable class
class Mutable():
def __init__(self):
self.layers = []
def getGen(self):
gen = []
for layer in self.layers:
gen += layer.getWeights()
return gen
def mutateWith(self, lover):
genSelf = self.getGen()
genLover = lover.getG... |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
__author__ = 'Florents Tselai'
REDIS_URI = '127.0.0.1'
REDIS_CAR_KEYSPACE = 'pycargr:car:{}'
SEARCH_BASE_URL = 'https://www.car.gr/classifieds/cars/'
CACHE_EXPIRE_IN = 24 * 3600
|
"""
[2015-07-06] Challenge #222 [Easy] Balancing Words
https://www.reddit.com/r/dailyprogrammer/comments/3c9a9h/20150706_challenge_222_easy_balancing_words/
# Description
Today we're going to balance words on one of the letters in them. We'll use the position and letter itself to calculate
the weight around the balan... |
a = 28
b = 1.5
c = 'hello'
d = True
e = None
print(a,b,c,d,e) |
# -*- coding: utf-8 -*-
class Fila:
def __init__(self):
self.element = list()
def inserir(self,name):
self.element.append(name)
print(f'Inserindo o elemento {name}: ' + ' '.join(self.element))
def remover(self):
self.element.pop(0)
print(f'Removendo o primeiro elemento: ' + ' '.join(... |
# 2. What is the time complexity of this code?
# La comlejidad es O(n^2), porque tiene for anidado.
def every_other(array):
# Este algoritmo imprime en consola los números del arreglo aumentados en m,
# tal que m es un número del arrelgo en una posición impar.
for i in range(len(array)):
if i % 2 == 0:
... |
load("@bazel_skylib//lib:shell.bzl", "shell")
load("@bazel_skylib//lib:paths.bzl", "paths")
AsciidocInfo = provider(
doc = "Information about the asciidoc-generated files.",
fields = {
"primary_output_path": "Path of the primary output file beneath {resource_dir}.",
"resource_dir": "File for th... |
# return the keys of a dictionary
def keys(dictionary):
return dictionary.keys()
# return the values of a dictionary
def values(dictionary):
return dictionary.values()
# return the string representation of a dictionary
def dict_to_string(d):
return str(d)
# merge two dictionaries
def merge(d1, d2):
... |
"""Questão 2.A ACME Inc., uma empresa de 500 funcionários, está tendo problemas de espaço em disco no
seu servidor de arquivos. Para tentar resolver este problema, o Administrador de Rede precisa saber
qual o espaço ocupado pelos usuários, e identificar os usuários com maior espaço ocupado. Através de
um programa, b... |
def parse_line(line):
splitted = line.strip().split()
instruction, count = splitted[0], int(splitted[1])
return instruction, count
def parse_input(filename):
with open(filename) as file:
lines = file.readlines()
return [parse_line(l) for l in lines]
def evaluate_til_repeat(instructions)... |
def runonce():
# This is only ran when OSIRIS is restarted, unlike normal live updates
return {}
def depends():
# this is list of modules to import from app
return ['testmodule', 'osirisd']
def reply(msg):
"""
code, header, and template are optional
header is another json dict thing
... |
class Data:
def __init__(self):
self.__dia = 0
self.__mes = 0
self.__ano = 0
def le_data(self):
self.dia = int(input('Digite o dia: '))
self.mes = int(input('Digite o mes: '))
self.ano = int(input('Digite o ano: '))
def formatada(self):
print(f'{self... |
"""
Given two strings A and B, return whether or not A can be shifted some number of times to get B.
For example, if A is abcde and B is cdeab, return true. If A is abc and B is acb, return false
"""
class Solution:
def rotateString(self, A, B):
N = len(A)
if N != len(B):
return False
... |
print('=========DESAFIO52=========')
numero = int(input('Digite um número: '))
if numero / 1 and numero / numero:
print('Número primo')
else:
print('Nao é um número primo')
|
#este es el ejercicio 3.1
def ejercicio01():
print ("Como saber si puedes votar por tu edad")
mensaje=""
#Ingreso de datos
edadP=int(input("ingrese la edad que tiene:"))
#Proceso
if edadP>=18:
mensaje="Usted tiene la edad necesaria para votar"
else:
mensaje="Usted no cumple con la edad minima para... |
"""Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto"""
preco = float(input('Informe o preço do produto: '))
print(f'O preço do produto com 5% de desconto será de R${preco-(preco*0.05):.2f}')
|
spam = {'name': 'Pooka', 'age': 5}
print("Before:")
print(spam)
#Traditional
if 'color' not in spam:
spam['color'] = 'black'
print("After:")
print(spam)
#With setDefault()
spam.setdefault("color", "white")
print(spam)
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count... |
"""This solution uses addition repititively
to find largest power n of 2 such that 2**n*b < a.
Then you keep subtracting these multiples of b of
the form 2**i*b for smaller powers until the remainder
is smaller than b. Each time you subtract,
take the previous quotient and multiply by two.
If there is any remaining in ... |
# Problem 2.
# Write the function subStringMatchExact. This function takes two arguments: a target string,
# and a key string. It should return a tuple of the starting points of matches of the key
# string in the target string, when indexing starts at 0. Complete the definition for
#
# def subStringMatchExact(target,ke... |
#Exercício Python 014: Escreva um programa que converta uma temperatura
# digitando em graus Celsius e converta para graus Fahrenheit.
c = float(input('Digite a temperatura em C°: '))
f = ((c*1.8)+32)
print('{} C° convertido para Fahrenheit fica em {}°F.'.format(c,f))
|
'''
Palindrome checker by python
'''
#Palindrome check for String inputs.
def palindrome (s):
r=s[::-1]
if(r==s):
print("Yes It is a palindrome")
else:
print("No It is not a palindrome")
s = input("Enter a String to check whether it is palindrome or not")
palin... |
""" Number Data types
Integers(int)
Floating Point(float)
Integer is a w
"""
|
class BaseError(Exception):
...
class InternalError(BaseError):
_default = "An internal error has occurred."
def __init__(self):
super().__init__(self._default)
|
"""
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example:
Given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
For this problem, return the maximum sum.
"""
class Solution:
# @param A : tuple of inte... |
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
dis = 0
while x != 0 or y !=0:
x,resx = x //2, x%2
y,resy = y//2, y%2
if resx!= resy:
dis +=1
return dis
class Solution:
def hammingDistance(self, x: int, y: int) -> int... |
QUERIES = {
'average_movies_per_user': (
'select avg(movies_watched) '
'from ( '
'select count(movie_id) as movies_watched '
'from views '
'group by user_id '
' ) as movies_count;'
),
'average_view_times': 'select avg(viewed_frame) from views;',
'top_20_... |
# Logic: Write a program that find the maximum positive integer from user input.
# Algorithm: append all the numbers to a list and use the built-in method 'max()' to get the highest number in the list.
num_int = int(input("Input a number: "))
num_list = []
while num_int >= 0:
num_int = int(input("Input a number: ... |
def _print_aspect_impl(target, ctx):
# Make sure the rule has a srcs attribute.
if hasattr(ctx.rule.attr, 'srcs'):
# Iterate through the files that make up the sources and
# print their paths.
for src in ctx.rule.attr.srcs:
for f in src.files.to_list():
print... |
for t in range(int(input())):
n=int(input())
k = 3 + 5**(1/2)
s = str(int(k**n))
if len(s) <3:
s = "0"*(3-len(s)) +s
print("Case #{}: {}".format(t+1,s[-3:])) |
load(
"@rules_scala3//rules:providers.bzl",
_ScalaConfiguration = "ScalaConfiguration",
_ScalaRulePhase = "ScalaRulePhase",
)
def run_phases(ctx, phases):
phase_providers = [
p[_ScalaRulePhase]
for p in [ctx.attr.scala] + ctx.attr.plugins + ctx.attr._phase_providers
if _ScalaRul... |
# Copyright 2017-2020 EPAM Systems, Inc. (https://www.epam.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 appli... |
X, Y, N = map(int, input().split())
grid = []
win = ''
for i in range(X):
grid.append([])
for j, val in enumerate(input().split()):
grid[i].append({'R':0,'B':0, 'dir':'none'})
if val != 'O':
grid[i][j][val] = 1
up, left, upleft, upright = 0, 0, 0, 0
... |
# Copied from https://rosettacode.org/wiki/Shortest_common_supersequence#Python
# Use the Longest Common Subsequence algorithm
def shortest_common_supersequence(a, b):
lcs = longest_common_subsequence(a, b)
scs = ""
# Consume lcs
while len(lcs) > 0:
if a[0]==lcs[0] and b[0]==lcs[0]:
# ... |
def extract_tib_only(csv_dump):
lines = csv_dump.strip().split('\n') # cut dump in lines
lines = [l.split(',')[1] for l in lines] # only keep the text
lines = [lines[i] for i in range(0, len(lines), 2)] # only keep the tibetan
return ''.join(lines)
def extract_all(csv_dump):
lines = csv_dump.... |
#! /usr/bin/env python3
description = """
Power digit sum
Problem 16
215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 21000?
"""
print(sum(int(x) for x in str(2**1000)))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/7/31 17:52
# @Author : Leishichi
# @File : 27.py
# @Software: PyCharm
# @Tag:
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
if len(nums)... |
# 26.05.2019
# Tuples vs Lists
# Tuples are read only
# Tuples have ( ) brackets
# Example with a List:
awesomeList= ['hello', 45, 'Marc', 89.4]
awesomeList[3] = 6
# List can be updated
print(awesomeList)
# now a tuple
awesomeTuple = ('MarcTuple', 1, 213.2, 'Hello')
print(awesomeTuple)
print(awesomeTuple[2])
... |
def dfCheckAvailability(df, baseTrackingMap):
#####
# step number -- iStep
bIStep = False if not ("iStep" in df.columns) else True
print("scan step number (iStep) availability: %s \n--" % str(bIStep))
#####
# Unix time -- epoch
bEpoch = False if not ("epoch" in df.columns) else True
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 14 13:26:18 2020
@author: abhi0
"""
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
for i in s:
if i in t:
tempIdx=t.index(i)
t=t[tempIdx+1:]
else:
return Fal... |
list1 = [1, 7, 16, 11, 14, 19, 20, 18]
list2 = [85, 111, 117, 43, 104, 127, 117, 117, 33, 110, 99, 43, 72, 95, 85, 85, 94, 66, 120, 98, 79, 117, 68, 83, 64, 94, 39, 65, 73, 32, 65, 72, 51]
ans = ''
for i in range(len(list2)):
ans += chr(list2[i] ^ list1[i % len(list1)])
print(ans)
|
"""
A nevelty COVID-19 Infections estimator function.
"""
def estimator(data):
#calculations for the currentlyInfected property
impact_ci = data['reportedCases']*10
severe_ci = data['reportedCases']*50
#calculations for the inFectedByRequestTime
if data['periodType'] == 'days':
impact_ibr... |
class Array(object):
def __init__(self, capacity, fill_value=None):
"""Capacity is the static size of the array.
fillValue is placed at each position."""
self._items = list()
for count in range(capacity):
self._items.append(fill_value)
def __len__(self):
"""-... |
f = open("Street_Centrelines.csv",'r')
def tup():
for v in f:
v = v.split(",")
t = (v[2], v[4], v[6], v[7])
print(t)
def maintenance():
h = dict()
for f2 in f:
f2 = f2.split(",")
if f2[12] not in h:
h[f2[12]] = 1
else:
h[f[12]] += 1
print(h)
... |
words = ['one', 'fish', 'two', 'fish', 'red', 'fish', 'blue', 'fish']
words2 = ['have', 'you', 'seen', 'a', 'blue', 'fish']
# what if we did the first example as a generator?
def get_word_lengths(word_list):
for word in word_list:
yield len(word)
for length in get_word_lengths(words):
print(length)
... |
# Time: O(n)
# Space: O(1)
# We are given two strings, A and B.
#
# A shift on A consists of taking string A and moving the leftmost character to the rightmost position.
# For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True
# if and only if A can become B after some number of shifts... |
def mfouri(self, oper="", coeff="", mode="", isym="", theta="", curve="",
**kwargs):
"""Calculates the coefficients for, or evaluates, a Fourier series.
APDL Command: *MFOURI
Parameters
----------
oper
Type of Fourier operation:
Calculate Fourier coefficients COEFF from... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.