content stringlengths 7 1.05M |
|---|
# PRIMER EJERCICIO
# Escribe la siguiente expresion algoritmica en una función
# (a**3 *(b**2 - 2*a*c) / 2*b)
print("CONGRATULATIONS!! Welcome to the first math program to solve algorithmic expressions")
a = float(input("Write the variable a --> "))
b = float(input("Write the variable b --> "))
c = float (input ("W... |
class fcf(object):
nr_cortes = None
coef_vf = None
termo_i = None
estagio = None
def __init__(self, estagio):
self.nr_cortes = 0
self.coef_vf = []
self.termo_i = []
self.estagio = estagio
def add_corte(self, coeficientes, constante, volume, nr_estagios):
... |
def Neighbors(row: int, col: int, data: list) -> list:
adjacents = []
for i in range(row - 1, row + 2):
for j in range(col - 1, col + 2):
if i == row and j == col or i < 0 or i >= len(data) or j < 0 or j >= len(data[0]):
continue
adjacents.append((i, j))
retur... |
class QuadraticEquation(object):
def __init__(self, a1, a2, c, eq=0):
"""
:param a1: X**2 Square index.
:param a2: X Meddule index.
:param c: C Constants
:param eq: Mostly equal to zero
"""
self.a1 = a1
if self.a1 == 0:
raise ... |
# Decorator for triggers
# A trigger is an event that we can watch.
# We expect it to return True if the event has happened and False if not.
# If it has 'required_arg_types', then the trigger will request those arguments in the console
# and will be passed them at runtime.
class Trigger():
def __init__(self, name, de... |
print('='*8,'Maior e Menor da Sequência','='*8)
pmaior = 0
pmenor = 0
for pess in range(1, 6):
p = float(input('Peso da pessoa número {} em kg: '.format(pess)))
if pess == 1:
pmaior = p
pmenor = p
else:
if p > pmaior:
pmaior = p
if p < pmenor:
pmenor ... |
# coding: utf-8
# BlackSmith mark.2
# exp_name = "session_stats" # /code.py v.x6
# Id: 10~4c
# Code © (2010-2012) by WitcherGeralt [alkorgun@gmail.com]
class expansion_temp(expansion):
def __init__(self, name):
expansion.__init__(self, name)
def command_exc_info(self, stype, source, body, disp):
if body:
... |
# Convert 1024 to binary
print(bin(1024))
print(hex(1024))
# 2 palce round of 5.23222
print(round(5.23222,2))
# check if every letter in str is lowercase
s='hello how are you Mary,are you feeling okay'
print(s.islower())
# how many time w showup
s = 'twywywtwywbwhsjhwuwshshwuwwwjdjdid'
print(s.count('w'))
#... |
# Stats for each item in the game
# 0-attack, 1-defense, 2-price, 3-type, 4-Pclass, 5-HP, 6-count, 7-lvl
Items = {'sword': list((10, 0, 10, 'weapon', 'swordsman', 0, 0, 1)),
'bronze sword': list((15, 0, 15, 'weapon', 'swordsman', 0, 0, 5)),
'iron sword': list((20, 0, 20, 'weapon', 'swordsman', 0, 0, 1... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
def rec(s,t):
if s is No... |
def f(a, b, c):
return (a, b, c)
___assertEqual(f(*[0, 1, 2]), (0, 1, 2))
___assertEqual(f(*"abc"), ('a', 'b', 'c'))
___assertEqual(f(*range(3)), (0, 1, 2))
|
def is_leap(year):
leap = False
# Write your logic here
if year%4 == 0 and year%100 != 0:
leap = True
elif year%400 == 0:
leap = True
return leap
year = int(input("Enter the year"))
print(is_leap(year))
|
floor_lenght = float(input())
tile_wight = float(input())
tile_lenght = float(input())
bench_wight = float(input())
bench_lenght = float(input())
speed = 0.2
bench_area = bench_lenght * bench_wight
tile_area = (tile_wight * tile_lenght)
floor_area = floor_lenght * floor_lenght - bench_area
print("%.2f" % (floor_area... |
print("give me two numbers, and I'll divide them.")
print("enter 'q' to quit.")
while True:
first_number = input("\nFirst Number:")
if first_number == 'q':
break
second_number = input("\nSecond Number:")
if second_number == 'q':
break
try:
answer = int(first_number)/int(secon... |
def convert_adjacent_matrix_to_adjacent_list(graph: list, vertices: list) -> dict:
result_graph = {}
for v in vertices:
result_graph[v] = []
rows, cols = len(graph), len(graph[0])
for i in range(rows):
for j in range(cols):
if graph[i][j] == 1:
result_graph[v... |
class Settlement:
def __init__(self,
node: int = None,
tx: float = 0,
ty: float = 0,
tz: float = 0,
rx: float = 0,
ry: float = 0,
rz: float = 0
) -> None:
"""Creates an ins... |
ANDHRA_TRACK_DIR = '/Users/jalend15/PycharmProjects/electoral_rolls/andhra/andhra_pdfs'
ANDHRA_PDF_ENGLISH_DIR = '/Users/jalend15/PycharmProjects/electoral_rolls/andhra/andhra_pdfs/english'
ANDHRA_PDF_TELUGU_DIR = '/Users/jalend15/PycharmProjects/electoral_rolls/andhra/andhra_pdfs/telugu' |
class shapes:
Count_Cylinder=0
Count_Cone=0
def __init__(self,rad,height):
self.rad=rad
self.height=height
def disp(self):
return self.rad+","+self.height
class Cone(shapes):
def __init__(self,rad,height):
shapes.__init__(self,rad,height)
self.slen=pow((pow(self.rad,2)+pow(self.height,2)),0.5)
self.Vo... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def verticalTraversal(self, root):
result = collections.defaultdict(list)
stack = [(root, 0)]
while stack... |
"""
<+$FILENAME$+>
Copyright (c) <+$YEAR$+> Idiap Research Institute, http://www.idiap.ch/
Written by Weipeng He <weipeng.he@idiap.ch>
"""
|
def metodoBloqueioMovimento(x, y, mapaAtual, direcao, item_select):
if x > -1 and x < 750 and y >-1 and y < 560:
if mapaAtual == 1:
if direcao == 'direita':
if y < 330 and y > 200:
if (x+10>350 or x+10<270):
return True
... |
class Team:
def __init__(self, dmg=0, heal=0, cast=0, kills=0):
self.dmg = dmg
self.heal = heal
self.casts = cast
self.kills = kills
class Teamfight:
"""Used to store data of a Teamfight in a Match"""
def __init__(self):
# Player is in teamfight
self.is_in = False
self.result = ""
self.players = []... |
def fun(n):
if n%2==0:
return '.'
return '*'
l=[[fun(j) for j in range(5)] for i in range(5)]
print(l) |
# -*- coding: utf-8 -*-
"""
Created on Fri May 15 00:32:55 2020
@author: Dilay Ercelik
"""
# Practice
# Given two strings, a and b, return the result of putting them together in the order abba,
# e.g. "Hi" and "Bye" returns "HiByeByeHi".
# Examples:
## make_abba('Hi', 'Bye') → 'HiByeByeHi'
## m... |
'''
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... |
"""
A class for delayed evaluation
"""
class Delayed(object):
"""A delayed evaluation tree.
"""
def __init__(self, function, *args, **kwargs):
self.function = function
self.args = args
self.kwargs = kwargs
def __str__(self):
return '({}, {}, {})'.format(self.function,... |
class Stack:
"""A class that implements a stack.
Stack is a LIFO data structure where each new item is settled on top compared to others.
Requires O(n) memory to store items and O(n) time to search an item.
Requires O(1) time to push and to pop an item."""
def __init__(self) -> No... |
class Work:
__id = None
__artist = None
__artist_name = None
__name = None
__created = None
__description = None
__tags = []
__forks = 0
__likes = 0
__allow_download = False
__allow_sketch = False
__allow_fork = False
__address = None
def set_address(self, addres... |
"""
http://www.geeksforgeeks.org/merge-sort/
https://www.programiz.com/dsa/merge-sort
"""
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
L = arr[:mid]
R = arr[mid:]
merge_sort(L)
merge_sort(R)
i = j = k = 0
if i < len(L) and j < len(R):
... |
class Solution:
def splitArray(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
# (0, i - 1), (i + 1, j - 1), (j + 1, k - 1) and (k + 1, n - 1)
# P[i] = P[j] - P[i+1] = P[k] - P[j+1] = P[-1] - P[k+1]
P = [0]
for x in nums: P.append(P[-1] + x)
... |
#
# @lc app=leetcode id=938 lang=python3
#
# [938] Range Sum of BST
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rangeSumBST(self... |
protists_chlorophyta = ["volvox", "actinastrum", "hydrodictyon", "spirogyra"]
print("The first three items in the list are:")
for protist in protists_chlorophyta[:3]:
print(protist.title())
protists_chlorophyta = ["volvox", "actinastrum", "hydrodictyon", "spirogyra"]
print("The items in the middle of the list are:... |
#This program demonstrates creation of bank account using OOP
#Reference: https://www.udemy.com/the-python-mega-course/learn/v4/t/lecture/5170352?start=0
class Account:
def __init__(self, filepath): #filepath stands for a value that is taken from balance.txt
self.fp=filepath #this makes filepath an in... |
def fuel(mass):
try:
mass_int = int(mass)
return max(int(mass_int / 3) - 2, 0)
except ValueError:
return 0
def fuel_recursive(mass):
try:
mass_int = int(mass)
fuel_mass = fuel(mass_int)
fuel_total = fuel_mass
while fuel_mass > 0:
fuel_ma... |
# The test
# For (3,4,5) representing (a,b,c)
# For (3,4,5) a + b + c = 12 is true
# a < b < c is true for (3,4,5)
# a2 + b2 = c2 is true for (3,4,5)
# For (3,4,5) a + b + c = 12
# Ultimately, fink the product abc.
# - Iterate through (a,b) until a^2 + b^2 = c^2
# - Test if a < b < c
# - Test if a + b + c = 1000
# (... |
ntos = {
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'fifteen',
16: 'sixteen',
17: 'seventeen',
18: 'eighteen',
19... |
#Ler o nome, idade e sexo de 4 pessoas e mostrar no final, a média das idades, o nome do homem mais
#velho e quantas mulheres tem menos de 20 anos
somaidades = 0;
conthomem = 0;
maisvelho = 0;
contmulhermenoridade = 0;
contpessoas = 0;
for c in range(0, 4):
nome = str(input(f"Digite o nome da {c+1} pess... |
# A python module for example purposes
myName = "mymod module for examples"
def add(a,b):
return a + b
def multiply(a,b):
return a * b
|
#Setting Directory
morsealpha={
"A" : ".-",
"B" : "-...",
"C" : "-.-.",
"D" : "-..",
"E" : ".",
"F" : "..-.",
"G" : "--.",
"H" : "....",
"I" : "..",
"J" : ".---",
"K" : "-.-",
"L" : ".-..",
"M" : "--",
"N" :... |
nome = input("Digite seu nome: ")
s = input("Digite seu sexo(M/N): ").upper()
while s != 'M' != 'F':
s = input("Digite seu sexo novamente: ").upper()
|
class HelloWorld:
""" HelloWorld class will tell you hello!
"""
def __init__(self, firstname, lastname):
""" initialize HelloWorld class
Args:
firstname (str): first name of user
lastname (str): last name of user
"""
self.firstname = firstname
... |
# THIS FILE IS AUTO-GENERATED. PLEASE DO NOT MODIFY# version file for ldap3
# generated on 2020-09-07 08:48:35.409733
# on system uname_result(system='Windows', node='ELITE10GC', release='10', version='10.0.19041', machine='AMD64', processor='Intel64 Family 6 Model 58 Stepping 9, GenuineIntel')
# with Python 3.8.5 - ('... |
def parse_bool(val, default):
if not val:
return default
if type(val) == bool:
return val
if type(val) == str:
if val.lower() in ["1", "true"]:
return True
if val.lower() in ["0", "false"]:
return False
raise ValueError(f"{val} can not be interpret... |
class RhinoObjectEventArgs(EventArgs):
# no doc
ObjectId = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: ObjectId(self: RhinoObjectEventArgs) -> Guid
"""
TheObject = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Get: TheO... |
'''
SPIMI-Invert(Token_stream)
output.file=NEWFILE()
dictionary = NEWHASH()
while (free memory available)
do token <-next(token_stream) //逐一处理每个词项-文档ID对
if term(token) !(- dictionary
/*如果词项是第一次出现,那么加入hash词典,同时,建立一个新的倒排索引表*/
then postings_list = AddToDictionary(dictionary,term(token))
... |
def ficha(nome='<desconhecido>', gol=0):
print(f'O jogador {nome} fez {gol} gol(s) no campeonato.')
#programa principal
n = str(input('Digite o nome do jogador: '))
g = str(input('Quantos gols no campeonato: '))
if g.isnumeric():
g = int(g)
else:
g = 0
if n.strip() == '':
ficha(gol=g)
else:
ficha(n... |
count=0
while count<5 :
print(count, "is less than 5")
count= count +1
else :
print(count, "is greater than 5")
|
def merge(x, y):
if len(x) == 0:
return y
if len(y) == 0:
return x
if x[0] <= y[0]:
return [x[0]] + merge(x[1:], y)
else:
return [y[0]] + merge(x, y[1:])
#Solution without slice and concat, which are O(n) in python
def merge2(x, y):
if len(x) == 0:
retu... |
#!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Jiao Lin
# California Institute of Technology
# (C) 2007 All Rights Reserved
#
# {LicenseText}
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... |
try:
user_number = int(input("Enter a number: "))
res = 10/user_number
except ValueError:
print("You did not enter a number!")
except ZeroDivisionError:
print("Enter a number different from zero (0)!")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "nebula"
class RabbitmqCtx(object):
_instance = None
def __init__(self):
self._amqp_url = "amqp://guest:guest@localhost:5672/"
@property
def amqp_url(self):
return self._amqp_url
@amqp_url.setter
def amqp_url(self, ... |
# coding:utf-8
'''
類義語を見つけて変換する
'''
SYN_PATH = "./engine/data/refer/synonyms.txt"
def find_synonym(search_word):
search_word = search_word.lower()
word_str = open(SYN_PATH).read()
if search_word not in word_str:
return search_word
synonym = search_word
words = word_str.split("\n")
words... |
class Item:
def __init__(self, kind, variable):
super(Item, self).__init__()
self.variable = variable
self.kind = kind
class Request:
def __init__(self, operation, length):
super(Request, self).__init__()
self.operation = operation
self.length = length
class Schedule:
"""
operations represents list of... |
# Truth and guesses should be lists of (commit_id, classification_id)
def score(truth, guesses):
truth = dict(truth)
correct_matches = 0
incorrect_matches = 0
for commit_id, classification_id in guesses:
assert(commit_id in truth)
if truth[commit_id] == classification_id:
correct_matches += 1
... |
class MyQueue(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.data = []
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: None
"""
stack = [x]
tmp = []
... |
#coding:utf-8
# Define no-op plugin methods
def pre_build_page(page, context, data):
"""
Called prior to building a page.
:param page: The page about to be built
:param context: The context for this page (you can modify this, but you must return it)
:param data: The raw body for this page (you can... |
class A(object):
def __init__(self):
pass
def _internal_use(self):
pass
def __method_name(self):
pass
|
#https://leetcode.com/explore/learn/card/queue-stack/239/conclusion/1393/
# According to Trial 68 ms and 14.5 mb
# 95.45% time and 21.71% space
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
stack = [(sr,sc)]
visited = {}
val... |
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'feature_defines': [
'ENABLE_CHANNEL_MESSAGING=1',
'ENABLE_DATABASE=1',
'ENABLE_DATAGRID=1',
'ENABLE_DASHB... |
l, h = [int(input()), int(input())]
t = [ord(c.lower()) - 97 if c.isalpha() else 26 for c in input()]
for _ in range(h):
row = input()
print("".join(row[j * l:(j + 1) * l] for j in t))
|
"""
Radix Sort
In computer science, radix sort is a non-comparative integer sorting
algorithm that sorts data with integer keys by grouping keys by the
individual digits which share the same significant position and value.
A positional notation is required, but because integers can represent
strings of characters ... |
# Worker: Microsoft
GET_ANOMALY = {
"type": "get",
"endpoint": "/getAnomaly",
"call_message": "{type} {endpoint}",
"error_message": "{type} {endpoint} {response_code}"
} |
"""
Write a function that accepts 2 strings (first_name, last_name).
The function should concatenate these two strings by inserting a space in between the strings and then reverse the resultant string.
Example:
first_name = 'Allen'
last_name = 'Brown'
Expected output = 'nworB nellA'
"""
def string_reverse(first_... |
n=int(input())
res=[]
grade=[]
for i in range(n):
name=input()
mark=float(input())
res.append([name,mark])
grade.append(mark)
grade=sorted(set(grade)) #sorted and remove the duplicates
m=grade[1]
name=[]
for val in res:
if m==val[1]:
name.append(val[0])
name.sort()
... |
def adapt_routes_object(object):
lat_north = object['routes'][0]['bounds']['northeast']['lat']
long_east = object['routes'][0]['bounds']['northeast']['long']
lat_south = object['routes'][0]['bounds']['southwest']['lat']
long_west = object['routes'][0]['bounds']['southwest']['long']
|
def get_aggregation(**kwargs):
field_name = ''
for k, v in kwargs.items():
field_name = v.replace('.keyword', '')+'_'+k
return {
field_name : {
k: {
'field': v
}
}
}
|
short = {}
def printShort1(word, i):
words = word.split()
words[i] = "[" + words[i][0] + "]" + words[i][1:]
print(" ".join(words))
def printShort2(cmd, i):
print(cmd[:i] + "[" + cmd[i] + "]" + cmd[i + 1:])
for i in range(ord('a'), ord('z') + 1):
short[chr(i)] = False
n = int(input())
cmds = []
f... |
#!/usr/bin/env python
# coding: utf-8
# # Day 4 Assignment
# In[1]:
num1 = 1042000
num2 = 702648265
for num in range(num1, num2 + 1):
order = len(str(num))
total = 0
temp = num
while temp > 0:
digit = temp % 10
total += digit ** order
temp //= 10
if num == total:
... |
print('-'*30) # Decoration
print(' '*5,'Fibonnaci sequence') # Title
print('-'*30) # Decoration
n = int(input('How many terms do you want to show? ')) # Question
t1 = 0 ... |
m = float (input("请输入身高(m)"))
k = float(input("请输入体重(kg)"))
m = m ** 2
BMI = k / m
if BMI < 18.5:
print("{:.2f} 你这么瘦,可以肆无忌惮的大吃大喝啦".format(BMI))
elif 18.5 <= BMI < 25:
print("{:.2f} 兄弟!你立模特就差八块腹肌了".format(BMI))
elif 25 <= BMI < 30:
print("%s 控制你自己哦!脂肪有点多啦" % BMI)
elif BMI >= 30:
print("%s 不能再吃了!跑几圈去吧,你也可以是男神" % BM... |
"""
Custom exceptions for things that can go wrong in the
execution of changesets.
These are used more for documentation than functionality
at the moment.
"""
class ChangesetException(Exception):
pass
class NotEnoughApprovals(ChangesetException):
pass
class NotPermittedToApprove(ChangesetException):
... |
def simple_math(first, second):
return f"""{first} + {second} = {first + second}
{first} - {second} = {first - second}
{first} * {second} = {first * second}
{first} / {second} = {int(first / second)}"""
if __name__ == '__main__':
f = int(input('What is the first number?'))
s = int(input('What is the secon... |
# 1736. 替换隐藏数字得到的最晚时间
#
# 20210724
# huao
class Solution:
def maximumTime(self, time: str) -> str:
h1 = time[0]
h2 = time[1]
m1 = time[3]
m2 = time[4]
if h1 == '?' and h2 == '?':
h1 = '2'
h2 = '3'
elif h1 == '?':
h2 = int(h2)
... |
#THIS IS TO PLACTICE CLASS AND METHODS
##CREATE A BANK CLASS AND METHODTS TO DEPOSIT AND WITHDRAW MONEY FROM THE
##ACCOUNT, IF THE ACCOUNT DOES NOT HAVE ENOUGH FUND, PREVENT WITHDRAWAL
class Bank_Account():
#bank account has owner and balance attributes
def __init__(self, owner, balance =0):
sel... |
class ReverseOrderIterator():
def __init__(self, n):
self.n = n
def __iter__(self):
return self
def __next__(self):
list = []
for element in range(self.n, -1, -1):
list.append(element)
return list
def next(self):
return... |
# !/usr/bin/env python
# !-*- coding:utf-8 -*-
# !@Time : 2022/1/26 9:13
# !@Author : DongHan Yang
# !@File : tfc.py
class Tfc:
def __init__(self, n, gates, name):
control = []
self.name = name
for i in range(n - 1, -1, -1):
cline = "c" + str(i)
control.append(cli... |
''' setting api config '''
''' base config class '''
class Config(object):
DEBUG=False
SECRET_KEY="secret"
''' testing class configurations '''
class Testing(Config):
DEBUG=True
TESTING=True
''' dev class configurations '''
class Development(Config):
DEBUG=True
''' staging configurations '''
c... |
expected_output = {
'application': 'TEMPERATURE',
'temperature_sensors': {
'CPU board': {
'id': 0,
'history': {
'11/10/2019 05:35:04': 51,
'11/10/2019 05:45:04': 51,
'11/10/2019 06:35:04': 49,
'11/10/2019 06:40:... |
a = float(input())
b = float(input())
media = ((a*3.5) + (b*7.5)) / 11
print('MEDIA = {:.5f}'.format(media)) |
while True:
print('Pirmais lietotajs -\n Ievadiet tekstu:')
text = str(input())
if text.isnumeric() == False: # isnumeric() var lietot try except vietā
text = text.lower()
break
else:
print("Nav pareizi!")
secret_text = text
for letter in range(0,len(secret_text)):
print(... |
class Node():
def __init__(self, x, y, r):
self.x = x
self.y = y
self.r = r
self.next = None
self.prev = None
pass
@classmethod
def from_np(cls, index, pos):
return cls(pos[index][0], pos[index][1], pos[index][2])
def __str__(self):
retu... |
def decrypt_fun(input_string,k):
st=""
for i in range(len(input_string)):
if input_string.islower():
shift=97 #ord(97)=a
else:
shift=65 #ord(65)=A
s=(((ord(input_string[i]))-(ord(k[i])))%26)+shift #here we need to subtract the ord(key) rest is same as ... |
N, K, M = map(int, input().split())
P = list(map(int, input().split()))
E = list(map(int, input().split()))
A = list(map(int, input().split()))
H = list(map(int, input().split()))
P.sort()
E.sort()
A.sort()
H.sort()
result = 0
for x in zip(P, E, A, H):
y = sorted(x)
result += pow(y[-1] - y[0], K, M)
resul... |
#!/usr/bin/env python
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Lic... |
(a, b) = map(str, input().split(" "))
a = len(a)
b = len(b)
if a<b:
g = a
else:
g = b
l = []
for i in range(1,g+1):
if a%i==0 and b%i==0:
l.append(str(i))
if (len(l) == 1) and ('1' in l):
print("yes")
else:
print("no")
|
# Enumerate instead of parsing so we pick up errors if a host is added/changed
ver_lookup = {
"postgresql-96-c7": ("9.6", "centos"),
"postgresql-10-c7": ("10", "centos"),
"postgresql-11-c7": ("11", "centos"),
"postgresql-12-c7": ("12", "centos"),
"postgresql-96-u1804": ("9.6", "ubuntu"),
"postg... |
"""
The Participant class represents a participant in a specific match.
It can be used as a placeholder until the participant is decided.
"""
class Participant:
"""
The Participant class represents a participant in a specific match.
It can be used as a placeholder until the participant is decided.
"""
... |
#%%
payments = 0
interest = (1 + rpi + 0.03) ** (1 / 12)
for i in range(0, 30*12):
repayment = (monthly_income(i) - base_monthly_income(i)) * 0.09
temp = debt * interest - repayment
if temp < 0:
payments = payments + debt * interest
debt = 0
break
debt = temp
payments = ... |
print("Welcome To even / odd Check: ")
num = int(input("Enter Number: "))
if num % 2 != 0:
print("This is Odd Number")
else:
print("This is an Even Number")
|
class Solution:
def maxSubArray(self, nums: [int]) -> int:
max_ending = max_current = nums[0]
for i in nums[1:]:
max_ending = max(i, max_ending + i)
max_current = max(max_current, max_ending)
return max_current
|
#
# PySNMP MIB module DATASMART-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DATASMART-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:21:38 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
# List of base-map providers
class Providers:
MAPBOX = "mapbox"
GOOGLE_MAPS = "google_maps"
|
class Person:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello, I'm {self.name}")
class Child(Person):
def __init__(self, name, school):
super().__init__(name)
self.school = school
def learn(self):
print(f"I'm learning a lot at {self.s... |
def test_get_links_nsdi():
"""
>>> from diamond_miner.test import url
>>> from diamond_miner.queries import GetLinks
>>> rows = GetLinks().execute(url, 'test_nsdi_example')
>>> links = [(row["near_addr"], row["far_addr"]) for row in rows]
>>> sorted(links)[:3]
[('::ffff:150.0.1.1', '::ffff:1... |
#!/usr/bin/python3
# https://practice.geeksforgeeks.org/problems/finding-middle-element-in-a-linked-list/1
def findMid(head):
"""
Start two pointers, one that moves a step, the other takes two steps
When the other reaches end the first will be in the mid
Works for both even and odd lengths
"""
... |
__author__ = 'Yifei'
HEADER_OFFSET = 0
INDEX_OFFSET = 4
LENGTH_OFFSET = 5
CHECKSUM_OFFSET = 6
PACKET_CONSTANT_OFFSET = 7
OPERAND_OFFSET = 7
PAYLOAD_OFFSET = 8
MAX_PAYLOAD_LENGTH = 255
MIN_PACKET_LENGTH = 4 + 1 + 1 + 1
PROTOSBN1_HEADER_BYTES = [0x53, 0x42, 0x4e, 0x31]
|
# -*- coding: utf-8 -*-
"""
ParaMol Parameter_space subpackage.
Contains modules related to the ParaMol representation of QM engines.
"""
__all__ = ['amber_wrapper',
'dftb_wrapper',
'ase_wrapper',
'qm_engine']
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""application not found exception
design for application not found exception
created: 2016/3/17
author: smileboywtu
"""
class AppNotFound(Exception):
"""app not found
"""
def __init__(self, msg, *args, **kwargs):
"""init the object
"""
... |
#code=input("Enter customer code:")
while True:
print("")
code=input("Enter customer code:")
bill_float = 0
bill = float(bill_float)
if code == "r":
begin_int=input("Enter beginning meter reading:")
begin = float(begin_int)
end_int=input("Enter ending meter reading:")
... |
class ExperimentorException(Exception):
pass
class ModelDefinitionException(ExperimentorException):
pass
class ExperimentDefinitionException(ExperimentorException):
pass
class DuplicatedParameter(ExperimentorException):
pass |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.