content stringlengths 7 1.05M |
|---|
# Calculate factorial of a number
def factorial(n):
''' Returns the factorial of n.
e.g. factorial(7) = 7x76x5x4x3x2x1 = 5040.
'''
answer = 1
for i in range(1,n+1):
answer = answer * i
return answer
if __name__ == "__main__":
assert factorial(7) == 5040 |
line = input().split()
n = int(line[0])
m = int(line[1])
print(str(abs(n-m)))
|
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"c_imshow": "01_nn_utils.ipynb",
"Flatten": "01_nn_utils.ipynb",
"conv3x3": "01_nn_utils.ipynb",
"get_proto_accuracy": "01_nn_utils.ipynb",
"get_accuracy": "02_maml_pl.ipyn... |
'''
The MIT License (MIT)
Copyright (c) 2016 WavyCloud
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, p... |
entrada = input()
def fibonacci(n):
fib = [0, 1, 1]
if n > 0 and n <= 2:
return fib[1]
elif n == 0:
return fib[0]
else:
for x in range(3, n+1):
fib.append(0)
fib[x] = fib[x-1] + fib[x-2]
return fib[n]
numeros = entrada.split(' ')
numeros = l... |
#! /usr/bin/env python3
################################################################################
# File Name : l6e4.py
# Created By : Félix Chiasson (7138723)
# Creation Date : [2015-10-20 11:40]
# Last Modified : [2015-10-20 13:46]
# Descriptio... |
class AXFundAddress(object):
def __init__(self, address, alias):
self.address = address
self.alias = alias
|
class Usuario(object):
def __init__(self, email='', senha=''):
self.email = email
self.senha = senha
def __str__(self):
return f'{self.email}'
class Equipe(object):
def __init__(self, nome='', sigla='', local=''):
self.nome = nome
self.sigla = sigla
self.... |
'''
| Write a program that should prompt the user to type some sentences. It should then print number of words, number of characters, number of digits and number of special characters in it. |
|------------------------------------------------------------------------------------------------------------------------------... |
def problem1_1():
print("Problem Set 1")
pass # replace this pass (a do-nothing) statement with your code
|
"""Calculation Class"""
class Calculation:
""" calculation abstract base class"""
# pylint: disable=too-few-public-methods
def __init__(self,values: tuple):
""" constructor method"""
self.values = Calculation.convert_args_to_tuple_of_float(values)
@classmethod
def create(cls,values: ... |
#
# PySNMP MIB module CTRON-SSR-CONFIG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CTRON-SSR-CONFIG-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:15:46 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
seats = []
with open("input.txt") as f:
for line in f:
line = line.replace("\n", "")
seat = {}
seat["raw"] = line
seat["row"] = int(seat["raw"][:7].replace("F", "0").replace("B", "1"), 2)
seat["column"] = int(seat["raw"][-3:].replace("L", "0").replace("R", "1"), 2)
s... |
#!/usr/bin/env python3
# Copyright © 2012-13 Qtrac Ltd. All rights reserved.
# This program or module 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 the
# License, or (at your option)... |
class MLModelInterface:
def fit(self, features, labels):
raise NotImplementedError
def predict(self, data):
raise NotImplementedError
class KNeighborsClassifier(MLModelInterface):
def fit(self, features, labels):
pass
def predict(self, data):
pass
class LinearRegres... |
{
"targets": [
{
"target_name": "gpio",
"sources": ["gpio.cc", "tizen-gpio.cc"]
}
]
} |
songs = { ('Nickelback', 'How You Remind Me'), ('Will.i.am', 'That Power'), ('Miles Davis', 'Stella by Starlight'), ('Nickelback', 'Animals') }
# Using a set comprehension, create a new set that contains all songs that were not performed by Nickelback.
nonNickelback = {}
|
def assign_variable(robot_instance, variable_name, args):
"""Assign a robotframework variable."""
variable_value = robot_instance.run_keyword(*args)
robot_instance._variables.__setitem__(variable_name, variable_value)
return variable_value
|
file1 = open("./logs/pythonlog.txt", 'r+')
avg1 = 0.0
lines1 = 0.0
for line in file1:
lines1 = lines1 + 1.0
avg1 = (avg1 + float(line))
avg1 = avg1/lines1
print(avg1, "for Python with", lines1, "lines")
file2 = open("./logs/clog.txt", 'r+')
avg2 = 0.0
lines2 = 0.0
for line in file2:
lines2 = lines2 + 1.0
... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
if head is None:
return None
# 1 - check cycle
p1 = head
p2 = head.next
... |
#!/usr/bin/python
def add(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def div(a,b):
return a/b
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Please select operation : \n" \
"1. Addition \n" \
"2. Subtraction \n" \
... |
# The classroom scheduling problem
# Suppose you have a classroom and you want to hold as many classes as possible
# __________________________
#| class | start | end |
#|_______|_________|________|
#| Art | 9:00 am | 10:30am|
#|_______|_________|________|
#| Eng | 9:30am | 10:30am|
#|_______|_________|_____... |
class restaurantvalidator():
def valideaza(self, restaurant):
erori = []
if len(restaurant.nume) == 0:
erori.append('numele nu trb sa fie null')
if erori:
raise ValueError(erori)
|
OVERALL_CATEGORY_ID = '0x02E00000FFFFFFFF'
HERO_CATEGORY_IDS = {
'reaper': '0x02E0000000000002',
'tracer': '0x02E0000000000003',
'mercy': '0x02E0000000000004',
'hanzo': '0x02E0000000000005',
'torbjorn': '0x02E0000000000006',
'reinhardt': '0x02E0000000000007',
'pharah': '0x02E0000000000008',... |
class Section:
def get_display_text(self):
pass
def get_children(self):
pass
|
def solution(prices):
if len(prices) == 0:
return 0
# We are always paying the first price.
total = prices[0]
min_price = prices[0]
for i in range(1, len(prices)):
if prices[i] > min_price:
total += prices[i] - min_price
if prices[i] < min_price:
min_p... |
# ///////////////////////////////////////////////////////////////////////////
#
#
#
# ///////////////////////////////////////////////////////////////////////////
class GLLight:
def __init__(self, pos=(0.0,0.0,0.0), color=(1.0,1.0,1.0)):
self.pos = pos
self.color = color
self.ambient = (1.0... |
def splitbylength(wordlist):
initlen = len(wordlist[0])
lastlen = len(wordlist[-1])
splitlist = []
for i in range(initlen, lastlen+1):
curlist = []
for x in wordlist:
if len(x) == i: curlist.append(x.capitalize())
splitlist.append(sorte... |
if __name__ == '__main__':
checksum = 0
while True:
try:
numbers = input()
except EOFError:
break
numbers = map(int, numbers.split('\t'))
numbers = sorted(numbers)
checksum += numbers[-1] - numbers[0]
print(checksum)
|
#
# PySNMP MIB module ITOUCH-RADIUS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ITOUCH-RADIUS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:47:05 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 31 17:02:24 2016
@author: rmondoncancel
"""
# Deprecated
priorityList = [
{
'name': 'fistOfFire',
'group': 'monk',
'prepull': True,
'condition': {
'type': 'buffPresent',
'name': 'fistOfFire',
'compa... |
hyper_params = {
'weight_decay': float(1e-6),
'epochs': 30,
'batch_size': 256,
'validate_every': 3,
'early_stop': 3,
'max_seq_len': 10,
}
|
print("valores dos numeros pares e impares:")
lista = [[],[]]
numero =0
for c in range(0,7):
numero = int(input(f"informe o {c+1}° numero:"))
if numero %2 ==0:
lista[0].append(numero)
else:
lista[1].append(numero)
print("Dados os numeros informados:")
print("lista dos numeros pares em or... |
def topla(a, b):
toplam = a + b
if a < b:
kucuk = a
else:
kucuk = b
return (toplam, kucuk)
toplam, kucuk = topla(1, 2)
print(toplam, kucuk)
tuple1 = (1, 2, 3)
tuple2 = 1, 2, 3
tuple3 = tuple([1, 2, 3, 4, 5])
ilkSayi = tuple2[0]
ikinciSayi = tuple2[1]
ucunc... |
# 1073
n = int(input())
if 5 < n < 2000:
for i in range(2, n + 1, 2):
print("{}^{} = {}".format(i, 2, i ** 2)) |
class BinaryIndexedTree(object):
def __init__(self):
self.BITTree = [0]
# Returns sum of arr[0..index]. This function assumes
# that the array is preprocessed and partial sums of
# array elements are stored in BITree[].
def getsum(self, i):
s = 0 # initialize result
# inde... |
s = input()
t = int(input())
xy = [0, 0]
cnt = 0
for i in range(len(s)):
if s[i] == 'U':
xy[1] += 1
elif s[i] == 'D':
xy[1] -= 1
elif s[i] == 'R':
xy[0] += 1
elif s[i] == 'L':
xy[0] -= 1
else:
cnt += 1
ans = abs(xy[0]) + abs(xy[1])
if t == 1:
ans += cnt
else:
if ans >= cnt:
ans -= ... |
def is_valid_session(session: dict) -> bool:
"""
checks if passed dict has enough info to display event
:param session: dict representing a session
:return: True if it has enough info (title, start time, end time), False otherwise
"""
try:
session_keys = session.keys()
except Attri... |
class Solution:
def intToRoman(self, num: int) -> str:
convertor = [
["","M", "MM", "MMM"],
["","C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"],
["","X", "XX", "XXX", "XL", "L", "LX","LXX","LXXX", "XC"],
["","I","II","III","IV","V","VI","VII","VIII","I... |
yoo = {
"af": "Afrikaans",
"sq": "Albanian - shqip",
"am": "Amharic - አማርኛ",
"ar": "Arabic - العربية",
"hy": "Armenian - հայերեն",
"az": "Azerbaijani - azərbaycan dili",
"bn": "Bengali - বাংলা",
"bs": "Bosnian - bosanski",
"bg": "Bulgarian - български",
"ca": "Catalan - català",
"zh": "Chinese - 中文",
"zh-Hans": "Chines... |
# 2. Multiples List
# Write a program that receives two numbers (factor and count) and creates a list with length of the given count
# and contains only elements that are multiples of the given factor.
factor = int(input())
count = int(input())
list = []
for counter in range(1, count+1):
list.append(factor * cou... |
#
# PySNMP MIB module H3C-IPSEC-MONITOR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/H3C-IPSEC-MONITOR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:09:33 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... |
#
# PySNMP MIB module CISCO-CAS-IF-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-CAS-IF-CAPABILITY
# Produced by pysmi-0.3.4 at Mon Apr 29 17:35:01 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... |
"""
Copyright 2018 Arm 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 in writing, software
distribut... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CS231n Convolutional Neural Networks for Visual Recognition
http://cs231n.github.io/
Python Numpy Tutorial
http://cs231n.github.io/python-numpy-tutorial/
 ̄
python_numpy_tutorial-python-containers_dictionary.py
2019-07-03 (Wed)
"""
# Python Numpy Tutorial > Python > C... |
valor1 = int(input('Digite o primeiro valor a ser somado: '))
valor2 = int(input('Digite o segundo valor: '))
soma = valor1 + valor2
print('A soma entre {} e {} é igual a {}.'.format(valor1, valor2, soma))
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sortedArrayToBST(self, nums) -> TreeNode:
def func(left, right) -> TreeNode:
if left > right:
return None
... |
# Write a python program to search the number of Times a paricular number in a list
'''
a = []
n = int(input("Enter a no. of element: "))
for i in range(n+1): #(n+1) here I can use input function but this is different method
b = int(input("Enter element: "))
a.append(b)
print(a)
k = 0
num... |
info = {}
nome = str(input('NOME: '))
nasc = int(input('ANO DE NASCIMENTO: '))
idade = 2020 - nasc
cart = int(input('CARTEIRA DE TRABALHO (0 Se não tiver): '))
info['NOME'] = nome
info['IDADE'] = idade
info['NASCIMENTO'] = nasc
info['CTPS'] = cart
if cart == 0:
for k, v in info.items():
print(f'{k} = {v}')
... |
def msg(m):
"""
Shorthand for print statement
"""
print(m)
def dashes(cnt=40):
"""
Print dashed line
"""
msg('-' * cnt)
def msgt(m):
"""
Add dashed line pre/post print statment
"""
dashes()
msg(m)
dashes()
|
# -*- coding: utf-8 -*-
"""
Created on Tue May 10 08:18:02 2016
@author: WELG
"""
class Coordinate(object):
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
x_diff_sq = (self.x-other.x)**2
y_diff_sq = (self.y-other.y)**2
return (x_diff_sq + y... |
class Solution:
def isPalindrome(self, s: str) -> bool:
lo, hi = 0, len(s) - 1
while lo < hi:
if not s[lo].isalnum():
lo += 1
elif not s[hi].isalnum():
hi -= 1
else:
if s[lo].lower() != s[hi].lower():
... |
# Change these values and rename this file to "settings_secret.py"
# SECURITY WARNING: If you are using this in production, do NOT use the default SECRET KEY!
# See: https://docs.djangoproject.com/en/3.0/ref/settings/#std:setting-SECRET_KEY
SECRET_KEY = '!!super_secret!!'
# https://docs.djangoproject.com/en/3.0/ref/se... |
def maxPower(s: str) -> int:
if not s or len(s) == 0:
return 0
result = 1
temp_result = 1
curr = s[0]
for c in s[1:]:
if c == curr:
temp_result += 1
else:
result = max(result, temp_result)
temp_result = 1
curr = c
... |
class data:
def __init__(self):
self._ = {}
def set(self, key, data_):
self._[key] = data_
return data_
def get(self, key):
if key in self._:
return self._[key]
else:
return False
|
#This application is supposed to mimics
#a seat reservation system for a bus company
#or railroad like Amtrak or Greyhound.
class Seat:
def __init__(self):
self.first_name = ''
self.last_name = ''
self.paid = False
def reserve(self, fn, ln, pd):
self.first_name = fn
se... |
# author: elia deppe
# date 6/4/21
#
# simple password confirmation program that confirms a password of size 12 to 48, with at least: one lower-case letter
# one upper-case letter, one number, and one special character.
# constants
MIN_LENGTH, MAX_LENGTH = 8, 48 # min and max length of password
# dictionaries
LO... |
"""Constant and messages definition for MT communication."""
class MID:
"""Values for the message id (MID)"""
## Error message, 1 data byte
Error = 0x42
ErrorCodes = {
0x03: "Invalid period",
0x04: "Invalid message",
0x1E: "Timer overflow",
0x20: "Invalid baudrate",
0x21: "Invalid parameter"
}
# Stat... |
# Copyright 2010 Google Inc.
#
# 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 ... |
FORMAT_MSG_HIGH_ALERT = "High traffic generated an alert - hits = %s, triggered at %s"
FORMAT_MSG_RECOVERED_ALERT = "Traffic recovered - hits = %s, triggered at %s"
HIGHEST_HITS_HEADER = "Highest hits"
ALERTS_HEADER = "Alerts"
|
# -*- coding: utf-8 -*-
"""
@Time : 2020/3/2 14:38
@Author : 半纸梁
@File : __init__.py.py
""" |
''' 5.Faça um programa que receba o salário de um funcionário e o percentual de aumento,
calcule e mostre o valor do aumento e o novo salário. '''
salario = float(input("Digite o valor do salário: R$ "))
percentual_de_aumento = float(input("Digite a porcentagem de aumento do salario: "))
valor_do_aumento = salario * ... |
model = dict(
type='ImageClassifier',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(3, ),
style='pytorch'),
neck=dict(type='GlobalAveragePooling'),
head=dict(
type='LinearClsHead',
num_classes=1000,
in_channels=2048,
... |
float_num = 3.14159265 # float_num is a variable which has been assigned a float
print(type(float_num)) # prints the type of float_num
print(str(float_num) + " is a float") # prints "3.14159265 is a float"
print("\"Hello, I'm Leonardo, nice to meet you!\"")
|
x = 3
y = 12.5
print('The rabbit is ', x, '.', sep='')
print('The rabbit is', x, 'years old.')
print(y, 'is average.')
print(y, ' * ', x, '.', sep='')
print(y, ' * ', x, ' is ', x*y, '.', sep='') |
name = 'ConsulClient'
__author__ = 'Rodrigo Alejandro Loza Lucero / lozuwaucb@gmail.com'
__version__ = '0.1.0'
__log__ = 'Consul api client for python'
|
# Copyright 2012 Dietrich Epp <depp@zdome.net>
# See LICENSE.txt for details.
@test
def skip_this():
skip()
@test
def pass_this():
pass
@test
def skip_rest():
skip_module()
@test
def fail_this():
fail("shouldn't get here")
|
def solution(N):
str = '{0:b}'.format(N)
counter = prev_counter = 0
for c in str:
if c is '0':
counter += 1
else:
if prev_counter == 0 or counter > prev_counter:
prev_counter = counter
counter = 0
return prev_counter if prev_counter > counter else counter
|
class TransportType:
NAPALM = "napalm"
NCCLIENT = "ncclient"
NETMIKO = "netmiko"
class DeviceType:
IOS = "ios"
NXOS = "nxos"
NXOS_SSH = "nxos_ssh"
NEXUS = "nexus"
CISCO_NXOS = "cisco_nxos"
|
inf = 100000
def dijkstra(src, dest, graph: list[list], matrix: list[list]):
number_of_nodes = len(matrix)
visitors = [0 for i in range(len(matrix))]
previous = [-1 for i in range(len(matrix))]
distances = [inf for i in range(len(matrix))]
distances[src] = 0
current_node = getPriority(distan... |
# -*- coding: utf-8 -*-
__author__ = 'yi.liu'
class Solution(object):
# 递归
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if int(n) - n != 0:
return False
if n <= 0:
return False
if n == 1:
return True
... |
# Do not edit this file. It was auto-generated from the
# corresponding YAML file.
spec = {
"name": "CRF1999",
"title": "Common Reporting Format GHG emissions categories (1999)",
"comment": "Classification of green-house gas emissions and removals into categories for use in annual inventories using the Comm... |
#!/usr/bin/env python
# coding: utf-8
# In[13]:
#site: https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/
# In[7]:
# Python program for Dijkstra's single
# source shortest path algorithm. The program is
# for adjacency matrix representation of the graph
class Graph():
def __... |
# process local states
local = range(12)
# L states
L = {"x0" : [6], "x1" : [7], "x2" : [8],
"f0" : [9], "f1" : [10], "f2" : [11],
"v0" : [0, 3, 6, 9], "v1" : [1, 4, 7, 10], "v2" : [2, 5, 8, 11],
"corr0" : [0, 6], "corr1" : [1, 7], "corr2" : [2, 8]}
# receive variables
rcv_vars = ["nr0", "nr1", "nr2"]
#... |
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
l = len(nums)
if l == 1:
return 1
index = 1
num = nums[0]
for i in range(1, l):
if nums[i] == num:
continue
num = nums[i]... |
'''
Define constraints (depends on your problem)
https://stackoverflow.com/questions/42303470/scipy-optimize-inequality-constraint-which-side-of-the-inequality-is-considered
[0.1268 0.467 0.5834 0.2103 -0.1268 -0.5425 -0.5096 0.0581] . The bounds are +/-30% of this.
'''
t_base = [0.1268, 0.467, 0.5834, 0.2103, -0.1268... |
__key_mapping = {
'return' : 'enter',
'up_arrow' : 'up',
'down_arrow' : 'down',
'left_arrow' : 'left',
'right_arrow' : 'right',
'page_up' : 'pageup',
'page_down' : 'pagedown',
}
def translate_key(e):
if len(e.key) > 0:
return __key_mapping[e.key] if e.key in __key_mapping e... |
"""
sentry.pool.base
~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
class Pool(object):
def __init__(self, keyspace):
self.keyspace = keyspace
self.queue = []
def put(self, item):
self.queu... |
class Solution:
def wordPattern(self, pattern: str, str: str) -> bool:
lst = str.split()
combo = zip(pattern, lst)
return len(set(pattern)) == len(set(lst)) == len(set(combo)) and len(pattern) == len(lst) |
soma_idade=0
media_Idade=0
maior_idade_homem=0
nome_velho=''
tot_mulher_20=0
for i in range(0,4):
nome=str(input('Nome: ')).strip()
idade=int(input('Idade: '))
sexo=str(input('Sexo: ')).strip()
soma_idade+=idade
if i==1 and sexo in 'Mm':
maior_idade_homem=idade
nome_velho=nome
el... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 31 11:53:09 2020
@author: aboutet
"""
def street_pattern_before(es, infos, insert):
return {}
def street_pattern(es, infos, data, documents):
to_send = []
for json in data:
if "LINK_ID" in json.keys():
link_id = "LINK... |
"""The LinkedList code from before is provided below.
Add three functions to the LinkedList.
"get_position" returns the element at a certain position.
The "insert" function will add an element to a particular
spot in the list.
"delete" will delete the first element with that
particular value.
Then, use "Test Run" and "... |
# -*- coding: utf-8 -*-
"""Top-level package for Medzibrod."""
__author__ = """Michal Nalevanko"""
__email__ = 'michal.nalevanko@gmail.com'
__version__ = '0.1.0'
|
def AllToDec_ui():
i = int(input('Ausgangsystem (z.B. 8 für Oktal) '))
zahl = input('Ausgangszahl: ')
input('Dezimalzahl: ')
print(All2dec(zahl, i))
def All2dec(z, p):
s = ''
n = 0
for i in range(0, len(z)):
n += int(z[len(z) - (i + 1)], p) * (p ** i)
s += str(int(z[len(z) ... |
# Copyright (c) 2020 Samplasion <samplasion@gmail.com>
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
TARGET = 2020
def main():
print("=============")
print("= AoC Day 1 =")
print("=============")
print()
with open("input.txt") as f:
file = f.r... |
SCHEMA = {
# staff-and-student-information
"all_students_count": "{short_code}PETALLC",
"african_american_count": "{short_code}PETBLAC",
"african_american_percent": "{short_code}PETBLAP",
"american_indian_count": "{short_code}PETINDC",
"american_indian_percent": "{short_code}PETINDP",
"asian... |
# This problem was asked by Facebook.
# Given an array of numbers representing the stock prices of a company in chronological
# order and an integer k, return the maximum profit you can make from k buys and sells.
# You must buy the stock before you can sell it, and you must sell the stock before you can buy it again... |
def file_html(fname):
fptr=open(fname,"r")
to_send = ""
for lines in fptr:
to_send += lines;
return to_send
#file_html("myfile.html");
|
md = [0,0]
facing = "E"
def rotate(cw, val):
idx = 4 + cw * int((val/90) % 4)
mv = ['E','S','W','N']
c = mv.index(facing)
return mv[(idx + c) % 4]
def move(dr, val):
global ew
global ns
global facing
if dr == 'N':
md[1] += val
elif dr == 'S':
md[1] -= val
... |
for _ in range(int(input())):
n,x = map(int,input().split())
l = list(map(int,input().split()))
flag=2
if len(set(l)) == 1 and l[0] == x:
flag=0
elif x in l or sum([i-x for i in l])==0:
flag=1
if flag==0:
print(0)
elif flag==1:
print(1)
else:
print... |
"""
Take the block of text provided and strip off the whitespace at both ends. Split the text by newline (\n) using split.
Loop through the lines and if the first character of each (stripped) line is lowercase, split the line into words and add the last word to the (given) results list, stripping the trailing dot (.)... |
"""
domonic.constants.keyboard
====================================
"""
class KeyCode():
A = '65' #:
ALTERNATE = '18' #:
B = '66' #:
BACKQUOTE = '192' #:
BACKSLASH = '220' #:
BACKSPACE = '8' #:
C = '67' #:
CAPS_LOCK = '20' #:
COMMA = '188' #:
COMMAND = '15' ... |
#!/usr/bin/env python
# configure these settings to change projector behavior
server_mount_path = '//192.168.42.11/PiShare' # shared folder on other pi
user_name = 'pi' # shared drive login user name
user_password = 'raspberry' # shared drive login password
client_mount_path = '/mnt/pishare' # where to find the shared... |
class Solution:
def boldWords(self, words, S):
"""
:type words: List[str]
:type S: str
:rtype: str
"""
m = len(S)
flags = [False] * m
for word in words:
n = len(word)
for i in range(m - n + 1):
if S[i:i + n] == w... |
data = (
'E ', # 0x00
'Cheng ', # 0x01
'Xin ', # 0x02
'Ai ', # 0x03
'Lu ', # 0x04
'Zhui ', # 0x05
'Zhou ', # 0x06
'She ', # 0x07
'Pian ', # 0x08
'Kun ', # 0x09
'Tao ', # 0x0a
'Lai ', # 0x0b
'Zong ', # 0x0c
'Ke ', # 0x0d
'Qi ', # 0x0e
'Qi ', # 0x0f
'Yan ', # 0x10
'Fei '... |
"""Top-level package for ML Model Evaluation Toolkit."""
__author__ = """Nicolas Kaenzig"""
__email__ = "nkaenzig@gmail.com"
__version__ = "0.1.0"
|
# Author: Rémi Adon <remi.adon@gmail.com>
# License: BSD 3 clause
def binary_to_int(b):
if isinstance(b, int):
return b
else:
return int(b, 2)
def char_code(s, idx=0):
return ord(s[idx])
PHONES = [
# +--------- Confident
# |+-------- Labial
# ||+------- Liquid
# |||... |
def remove_duplicated_keep_order(value_in_tuple):
new_tuple = []
for i in value_in_tuple:
if not (i in new_tuple):
new_tuple.append(i)
return new_tuple
# return tuple(set(value_in_tuple))
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
def get_package_data():
return {
_ASTROPY_PACKAGE_NAME_ + '.tests': ['coveragerc', 'data/*.hdr'] # noqa
}
|
exp.set('total_responses', 0)
exp.set('total_correct', 0)
exp.set('total_response_time', 0)
exp.set('average_response_time', 'NA')
exp.set('avg_rt', 'NA')
exp.set('accuracy', 'NA')
exp.set('acc', 'NA')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.