content stringlengths 7 1.05M |
|---|
sum1 = 0
sum2 = 0
for i in range (1, 101, 1):
sum1 = sum1 + (i**2)
sum2 = sum2 + i
sum2 = sum2**2
answer = sum2-sum1
print(answer)
|
# day 10 challenge 1
# read input
ratings = []
with open('input.txt', 'r') as file:
for line in file:
ratings.append(int(line))
ratings.sort()
ratings.append(ratings[-1] + 3)
ratings.insert(0, 0)
one_ct = 0
thr_ct = 0
for ind, jlt in enumerate(ratings):
if ind < (len(ratings) - 1):
if (rati... |
#!/usr/bin/env python3
n = int(input())
i = 0
while i < n:
if i == 0:
print(n * "*")
elif 0 < i < n - 1:
print("*" + ((n - 2) * " ") + "*")
elif i == n - 1:
print(n * "*")
i = i + 1
|
# Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
# Only one letter can be changed at a time.
# Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
# For exampl... |
#
# PySNMP MIB module WWP-LEOS-FLOW-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WWP-LEOS-FLOW-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:37:57 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
# generated from catkin/cmake/template/cfg-extras.context.py.in
DEVELSPACE = 'FALSE' == 'TRUE'
INSTALLSPACE = 'TRUE' == 'TRUE'
CATKIN_DEVEL_PREFIX = '/root/ros_catkin_ws/devel_isolated/roslisp'
CATKIN_GLOBAL_BIN_DESTINATION = 'bin'
CATKIN_GLOBAL_ETC_DESTINATION = 'etc'
CATKIN_GLOBAL_INCLUDE_DESTINATION = 'include'
CA... |
# Definition for a binary tree node. https://leetcode.com/problems/find-mode-in-binary-search-tree/submissions/
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def findMode(self, root: TreeNode) -> Lis... |
a,b=1,0
for i in range(int(input())):
x,y,z=list(map(int,input().split()))
a=a*y//x
if z:
b=1-b
print(b,a) |
# https://www.hackerrank.com/challenges/merge-the-tools/problem
def merge_the_tools(s, n):
# your code goes here
for part in zip(*[iter(s)] * n):
d = dict()
print(''.join([d.setdefault(c, c) for c in part if c not in d]))
if __name__ == '__main__':
string, k = input(), int(input())
m... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class PodiumApplication():
def __init__(self, app_id, app_secret, podium_url=None):
self.app_id = app_id
self.app_secret = app_secret
self.podium_url = 'https://podium.live' if podium_url is None else podium_url
|
class DigAdd:
def addDigits(self, num: int) -> int:
if not num:
return 0
else:
mod = (num - 1) % 9
x = mod + 1
return x
print(DigAdd().addDigits(12))
print(DigAdd().addDigits(12836374))
print(DigAdd().addDigits(9))
print(DigAdd().addDigits(8))
|
"""Constants needed for the operation of the program."""
WHEEL_DIAMETER = 0.03
AXIS_LENGTH = 0.14
RPS_PER_PERCENTAGE = 0.083
PIXELS_PER_METER = 100
VALUE_PER_ALPHA = 1024.0 / 255.0
SENSORS = [
(-0.03, 0.01),
(-0.02, 0.02),
(-0.01, 0.03),
(0.03, 0.01),
(0.02, 0.02),
(0.01, 0.03)
]
|
# 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:
# O(n) time | O(n) space - where n is the number of the nodes in this binary tree
def maxDepth(self, roo... |
"""Programa 8_6.py
Descrição:Reescrever programa da listagem 8.8 de forma a utilizar for em vez de while
Autor:Cláudio Schefer
Data:
Versão: 001
"""
# Declaração de variáveis
L = []
# Entrada de dados
L = [1,7,2,9,15]
# Processamento
def soma(L):
total = 0
x = 0
for e in L:
total += L... |
def send_email(name: str, address: str, subject: str, body: str):
print(f"Sending email to {name} ({address})")
print("==========")
print(f"Subject: {subject}\n")
print(body)
|
# ~encoding: utf-8~
"""
main
Entry point to run evolsim simulator.
@author: Lourenço Abrunhosa Rodrigues
"""
# imports
# built-in
# local
# 3rd-party
|
# By submitting this assignment, I agree to the following:
# “Aggies do not lie, cheat, or steal, or tolerate those who do”
# “I have not given or received any unauthorized aid on this assignment”
#
# Name: Jonathan Samuel
# Section: 510
# Assignment: Lab7b
# Date: 10/11/18
def getVectors():
A = input(... |
with open('input') as f:
in_data = [line.rstrip() for line in f]
j=0
w=len(in_data[0])
tree_count=0
for i in range(1, len(in_data)):
line = in_data[i]
j=(j+3)%w
if line[j] == '#':
tree_count+=1
print(tree_count)
|
# =======================
# From the pyECC package
# =======================
#
# Predefined Elliptic Curves
# for use in signing and key exchange
#
"""
Predefined elliptic curves for use in signing and key exchange.
This Module implements FIPS approved standard curves P-192, P-224, P-256,
P-384 and P-521 along with... |
# -*- coding: utf-8 -*-
"""
118. Pascal's Triangle
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
"""
class Solution:
def generate(self, numRows):
if numRows == 0:
retur... |
def isPalindrome(word):
word = word.lower()
if word == word[::-1]:
return True
else:
return False
print(isPalindrome("DDnKnDD"))
|
for i in range(1, 1001):
print(1001 - i, end="\t")
if i % 5 == 0:
print("")
|
with open('day002.txt', 'r') as fd:
inp = fd.read()
rows = inp.split('\n')
def move(p, d):
x, y = p
if d == 'U': p = (x, max(y - 1, 0))
if d == 'D': p = (x, min(y + 1, 2))
if d == 'R': p = (min(x + 1, 2), y)
if d == 'L': p = (max(x - 1, 0), y)
return p
def key(p):
return p[0] + p[1] * 3 +... |
jvar = 0
def return_something():
return "Hi world"
def change_jvar():
jvar = 18
print(jvar)
def print_jvar():
print(jvar)
print("Called on import! Oops!")
|
# empty class for creating constants
class Constant:
pass
# constants for metrical feet
FOOT = Constant()
FOOT.DACTYL = "Dactyl"
FOOT.SPONDEE = "Spondee"
FOOT.FINAL = "Final"
APPROACH = Constant()
APPROACH.STUDENT = "version_student"
APPROACH.NATIVE_SPEAKER = "version_native_speaker"
APPROACH.FALLBACK = "versio... |
class Agencia:
def __init__(self,nombre,direccion,email):
self.nombre = nombre
self.direccion = direccion
self.email = email
def getNombre(self):
return self.nombre
def getDireccion(self):
return self.direccion
def getEmail(self):
return self.email
d... |
"""The is an attempt at creating a bowl class
to solve Exercise 2-1 in the Think Bayes book"""
class Bowl(object):
"""A bowl object that keeps track of our cookies"""
def __init__(self, bowl_name, v_cookies, c_cookies):
"""Constructor"""
self.bowl_name = bowl_name
self.v_cookies = floa... |
# Advent of Code 2017
# Day 9, Part 2
# @geekygirlsarah
# Files to run through
# input.txt being the input the puzzle provides
inputFile = "input.txt"
# inputFile = "testinput.txt"
# Process file
with open(inputFile) as f:
while True:
contents = f.readline(-1)
if not contents:
# print... |
#
# PySNMP MIB module Juniper-DVMRP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-DVMRP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:02:27 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 -*-
"""
Configuration file.
"""
# enables the debug mode of the client
# True: Exceptions will be raised
# False: Exceptions will be catched and logged
debug_mode = True
# parameter for database connection
database_connection = {
'user': 'root',
'passwd': 'Se!Ne#Ta45',
'host': 'local... |
# single_leading_underscore.py
print("""
Single leading underscore: _var
-------------------------------
1. When applied to variable and method names, it has a meaning by convention only.
2. Intended as a hint to the programmer that it is used for internal purposes, but not enforced by Python.
3. Does not affect the ... |
# -*- coding: utf-8 -*-
def factorial(number):
if (number == 0):
return 1
return number * factorial(number - 1)
if __name__ == "__main__":
print("\nCalcular el factorial")
number = int(raw_input("Escribe un número: "))
result = factorial(number)
print("El resultado de " + str(numb... |
# Given a string s consisting of small English letters, find and return the first instance of a non-repeating character in it. If there is no such character, return '_'.
# Example
# For s = "abacabad", the output should be
# first_not_repeating_character(s) = 'c'.
# There are 2 non-repeating characters in the string... |
"""
generateProductImages.py
50 products --> 50 images
10 images per category
Categories:
1. Books
2. Electronics
3. Clothing
4. Games
5. Groceries
"""
def getProductImage(category, idx):
bookImages = ["https://tinyurl.com/bdew8ewr",
"https://tinyurl.com/ycktxfjs",
"https://tiny... |
# Agenda de cumpleaños
cumpleanos = {'brian': '14-Oct', 'gabriela': '12-May', 'joel': '07-Abr'}
while True:
print('Ingrese el un nombre: (Espacio en blanco para cerrar el programa)')
nombre = input()
if nombre == '':
print('Gracias por usar el programa')
break
if nombre in cumpleanos:... |
skill = input()
while True:
command = input()
if command == 'For Azeroth' or command is None:
break
if command == 'GladiatorStance':
skill = skill.upper()
print(skill)
elif command == 'DefensiveStance':
skill = skill.lower()
print(skill)
elif comman... |
# Copyright (c) 2020 Club Raiders Project
# https://github.com/HausReport/ClubRaiders
#
# SPDX-License-Identifier: BSD-3-Clause
#
# Faction constants
#
GOVERNMENT = 'government'
MINOR_FACTION_ID = 'minor_faction_id'
MINOR_FACTION_PRESENCES = 'minor_faction_presences'
NEIGHBOR_COUNT = 'neighbor_count'
HAS_ANARCHY... |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 27 02:01:38 2020
@author: peng
"""
# nothing new
A = [1]
B = [2]
C = [3] |
class Employee:
# class variables
num_of_employees = 0
raise_amount = 1.04
def __init__(self, first, last, pay):
# instance variables
self.first = first
self.last = last
self.pay = pay
self.email = f"{first}.{last}@company.com"
Employee.num_of_employees +... |
"""
Hacker Rank Problem found here:
https://www.hackerrank.com/challenges/electronics-shop/problem?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign
1. Clarifying Questions
- are the prices on positive integers?
- will the prices alwas be unique within one array?
- is the a... |
# Constants for browser located in this file.
# CONFIG DIRECTORY NAMES
DIRECTORY_CONFIGURATIONS = 'configurations'
DIRECTORY_TOPICS = 'topics'
DIRECTORY_AVRO_SCHEMAS = 'avro_schemas'
DIRECTORY_DEPLOYMENT_SCRIPTS = 'deployment_scripts'
# CONFIG FILENAMES
FILE_MAIN_CONFIG = 'main_config.yml'
FILE_LOGGER_CONFIG = 'logge... |
""" For your information:
class Node(object):
def __init__(self, data=None):
self.data = data
self.next = None
"""
def front_back_split(source, front, back):
if not source or not front or not back or not source.next:
raise Exception()
length=0
temp=source
while source:
... |
#
# PySNMP MIB module SYMMSYNCE (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/neermitt/Dev/kusanagi/mibs.snmplabs.com/asn1/SYMMSYNCE
# Produced by pysmi-0.3.4 at Tue Jul 30 11:35:09 2019
# On host NEERMITT-M-J0NV platform Darwin version 18.6.0 by user neermitt
# Using Python version 3.7.4 (default, Jul 9 20... |
def get_head(line, releases, **kwargs):
for release in releases:
if "Django {} release notes".format(release) in line:
return release
return False
def get_urls(releases, **kwargs):
urls = []
for release in releases:
urls.append("https://raw.githubusercontent.com/django/djan... |
# Copyright - see copyright.txt
class Predicate:
"""Predicate is one specific ``if'' encountered during the program execution.
"""
def __init__(self, st, result):
self.symtype = st
self.result = result
def getVars(self):
return self.symtype.getVars()
def __eq__(self, other):
if isinstance(other, Pred... |
# Scrapy settings for news project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/topics/settings.html
#
BOT_NAME = 'news'
BOT_VERSION = '1.0'
SPIDER_MODULES = ['news.spiders']
NEWSPIDER_MODULE = 'news.spi... |
class Date(object):
def get_date(self):
return '2019-08-04'
class Time(Date): # Herda método a partir da classe Date().
def get_time(self):
return '08:11:30'
data = Date()
print(data.get_date())
tempo = Time()
print(tempo.get_time())
print(tempo.get_date())
|
# Challenge name: Fun with an interview question
# Challenge link: https://danielbmarkham.com/fun-with-an-interview-question/
# Completed by Zack Sargent on: Feb. 6th, 2021
# this was done after I did it in JavaScript.
# see ./StringToArray.js for the Javascript version.
"""
Prompt:
Input: "aaaabbbcca"
Output: [("... |
frase = str(input('Digite uma frase: ')).lower().strip()
print('Quantidade de "a/A": {}'.format(frase.count('a')))
print('Posição em que "a/A" aparece a primera vez: {}'.format(frase.find('a') + 1))
print('Posição em que "a/A" aparece a última vez: {}'.format(frase.rfind('a') + 1))
|
"""
Faça um programa que leia um numero inteiro positivo ímpar N
e imprima todos os numeros imapres de 1 ate N em ordem crescente.
"""
n = int(input('Digite um valor positivo ímpar para iniciar o programa: '))
while n % 2 == 0 or n < 0:
print('Valor invalido.')
n = int(input('Digite um valor positivo ímpar para... |
class Mapper(object):
@staticmethod
def map(enum, value):
result = None
for enum_value in enum:
if Mapper._normalize(value) == Mapper._normalize(enum_value.value):
result = enum_value
return result
@staticmethod
def _normalize(value: str):
ret... |
PARTS = {
"1-": [
"PAI", "PAD", "PAN", "PAP", "PAS", "PAO",
"PMI", "PMD", "PMN", "PMP", "PMS", "PMO",
],
"1+": [
"IAI",
"IMI",
"IEI",
],
"2-": [
"FAI", "FAN", "FAP", "FAO",
"FMI", "FMN", "FMP", "FMO",
],
"3-": [
"AAD", "AAN", "A... |
def city_country(city, country):
return(city.title() + ", " + country.title())
city = city_country('santiago', 'chile')
print(city)
city = city_country('ushuaia', 'argentina')
print(city)
city = city_country('longyearbyen', 'svalbard')
print(city)
|
# -*- coding: utf-8 -*-
description = 'setup for Beckhoff PLC mtt devices on PANDA'
group = 'lowlevel'
devices = dict(
mtt = device('nicos.devices.generic.Axis',
description = 'Virtual MTT axis that exchanges block automatically '
'(must be used in "automatic" mode).',
motor... |
def pstrip(s, prefix):
"""Prefix strip
>>> pstrip('foo_oof', 'foo_')
'oof'
>>> pstrip('baroof', 'foo_')
'baroof'
"""
i = len(prefix)
if s[:i] == prefix:
return s[i:]
return s
def sstrip(s, suffix):
"""Suffix strip
>>> sstrip('foo.oof', '.oof')
'foo'
>>> ss... |
"""
A list of particle properties.
"""
c = 3*10**8 # m/sec
pion_tau = 2.6*(10**-8) # sec
muon_tau = 2.2*(10**-6) # sec
pion_mass = 139.6 # MeV
muon_mass = 105.7 # MeV
electron_mass = 0.5 # MeV
electron_ratio = 10**4 |
class Name:
def __init__(self, name, age):
self.name = name
self.age = age
def age_next(self):
return self.age + 10
def name_len(self):
return 'Length of name is {}'.format(len(self.name))
class Education(Name):
def __init__(self, name, age, school, btech, ms):
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 12 13:32:50 2018
@author: afilbrun
"""
# Problem 4
palindrome = [];
for first in range (100,1000):
for second in range (100,1000):
num = first * second;
if str(num) == str(num)[::-1]:
palindrome.append(num)
print (max(palindrome)); |
def batch( qs, batch_size=1000 ):
"""
Returns a ( start, end, total, queryset ) tuple for each batch in the given
queryset.
Usage:
# Make sure to order your querset
article_qs = Article.objects.order_by('id')
for start, end, total, qs in batch_qs(article_qs):
print "... |
class Constants:
default_config_folder = "config"
default_modules_folder = "modules"
default_deployment_template_file = "deployment.template.json"
default_deployment_debug_template_file = "deployment.debug.template.json"
default_platform = "amd64"
deployment_template_suffix = ".template.json"
... |
# -*- coding: utf-8 -*-
def ten_sum_exists(matrix):
"""Calculate if the numbers provided can sum to 10.
:Parameter:
matrix: list
:Returns:
boolean, dict
"""
if not isinstance(matrix, list):
return
length = len(matrix)
count = 0
pointer = 0
ten_sum_count = ... |
class PIDController:
def __init__(self, kp, ki, kd, goal):
self.kp = kp
self.ki = ki
self.kd = kd
self.goal = goal
self.error = 0
self.lX = 0
self.dError = 0
self.iError = 0
def correction(self):
return (self.error * self.kp + self.iErr... |
class HWPDecryptor():
def __init__(self, filepath, key):
self.data = ''
self.key = key
with open(filepath, 'rb') as f:
data = f.read()
self.data = bytearray(data)
def decryption(self):
r = list()
for i in range(0, len(self.data)):
... |
class Solution(object):
def divisorGame(self, N):
"""
:type N: int
:rtype: bool
"""
return True if N % 2 == 0 else False |
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
n = int(input("Please enter your number"))
values = [str(fibonacci(x)) for x in range(0, n+1)]
print(",".join(values))
|
RANDOM_SEED = 7 # constant for reproducability
# for training
TRAINING_CONFIG = {
'TYPE': 'single_country', # single_country or country_held_out
'COUNTRY': 'malawi_2016', # malawi_2016, ethiopia_2015
'METRIC': 'est_monthly_phone_cost_pc' # house_has_cellphone or est_monthly_phone_cost_pc
}
# for predicti... |
# Copyright 2019 Zadara Storage, Inc.
# Originally authored by Jeremy Brown - https://github.com/jwbrown77
#
# 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... |
"""
Utility module to manipulate CSV files.
"""
__author__ = "Jenson Jose"
__email__ = "jensonjose@live.in"
__status__ = "Alpha"
class CsvUtils:
"""
Utility class containing methods for manipulating CSV files.
"""
def __init__(self):
pass
|
"""
Cutting Ribbons
You are given an integer array ribbons, where ribbons[i] represents the length of the ith ribbon, and an integer k. You may cut any of the ribbons into any number of segments of positive integer lengths, or perform no cuts at all.
For example, if you have a ribbon of length 4, you can:
Keep the r... |
class LetterSpacingKeyword:
Normal = "normal"
class LetterSpacing(
LetterSpacingKeyword,
Length,
):
pass
|
"""
Dataframes constants
"""
TRANS = "trans_m"
LIQUID = "liquid_m"
CATEG = "trans_categ"
INVEST = "invest_m"
WORTH = "worth_m"
ALL_FROM_DATA = [CATEG, LIQUID, INVEST, WORTH]
ALL = [TRANS] + ALL_FROM_DATA
|
"""Top-level package for purepython_flagser."""
__author__ = """Nicolas Ninin"""
__email__ = 'nicolas.ninin@gmail.com'
__version__ = '0.1.0'
|
# problem description: https://www.hackerrank.com/challenges/ctci-connected-cell-in-a-grid/problem
def getBiggestRegion(grid):
n_row = len(grid)
n_col = len(grid[0])
region_sizes = []
for row in range(n_row):
for col in range(n_col):
region_size = measure_region(grid, row, col)
... |
# -*- coding: utf-8 -*-
"""
History of past trials
======================
Maintain the history of past trials used by an algorithm.
"""
# pylint:disable=protected-access,too-few-public-methods
class TrialsHistory:
"""Maintain a list of all the last seen trials that are on different dependency paths"""
def ... |
outFp = None
outStr=''
outFp = open("./data1.txt","a")
num = 1
while True:
outStr=input("입력 내용 : ")
if outStr != '':
outFp.writelines(outStr + "\n")
else:
break
num += 1
outFp.close()
|
expected_output = {
"my_state": "13 -ACTIVE",
"peer_state": "1 -DISABLED",
"mode": "Simplex",
"unit": "Primary",
"unit_id": 48,
"redundancy_mode_operational": "Non-redundant",
"redundancy_mode_configured": "Non-redundant",
"redundancy_state": "Non Redundant",
"maintenance_mode": "Di... |
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
:type size: int
"""
self.nums = nums
self.reset = lambda: self.nums
def shuffle(self):
"""
Returns a random shuffling of the array.
:rtype:... |
t = int(input())
for _ in range(t):
n = int(input())
a = [int(x) for x in input().split()]
a.sort()
n *= 2
if n == 2:
print(abs(a[-1]-a[0]))
else:
print(a[n//2]-a[n//2-1])
|
# https://wiki.python.org/moin/BitManipulation
# testBit() returns a nonzero result, 2**offset, if the bit at 'offset' is one.
def testBit(int_type, offset):
mask = 1 << offset
return(int_type & mask)
# setBit() returns an integer with the bit at 'offset' set to 1.
def setBit(int_type, offset):
mask = 1... |
# Django settings for unit test project.
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'database.sqlite',
},
}
SITE_ID = 1
ROOT_URLCONF = 'parler_example.urls'
SECRET_KEY = 'secret'
# Absolute path to the directory that holds media.
# Example: "/ho... |
print ('Calculo de triângulos.... \n\n\n')
lado1 = float(input('Digite o seguimento 1 do triângulo: '))
lado2 = float(input('Digite o seguimento 2 do triângulo: '))
lado3 = float(input('Digite o seguimento 3 do triângulo: '))
if lado1 + lado2 <= lado3 or lado1 + lado3 <= lado2 or lado2 + lado3 <= lado1:
print('... |
"""
File-based help entries. These complements command-based help and help entries
added in the database using the `sethelp` command in-game.
Control where Evennia reads these entries with `settings.FILE_HELP_ENTRY_MODULES`,
which is a list of python-paths to modules to read.
A module like this should hold a global `... |
def solution(numbers):
str_nums = list(map(str, numbers))
str_nums.sort(key=lambda x: x*3, reverse=True)
answer = str(int(''.join(str_nums)))
return answer
# 생각보다 단순했던 문제
# 문자열 비교 특성을 이용해서, 같은 인덱스 중 큰 숫자를 앞으로 오게끔 하여 정렬하면 된다.
# (예: 333과 1212 비교 : 333333333 > 121212121212
# 처음 생각했던 풀이는 compare 함수를 직접 작성해... |
SCHEDULE_MODE = {
'SECONDS': 1,
'MINUTS': 2,
'HOUR': 3,
'DAY': 4
}
SCHEDULE_STATUS = {
'RUNNING': 1,
'STOPPED': 2
}
SCHEDULE_ACTIVE = {
'ACTIVE': 1,
'DEACTIVE': 2
}
def getDictKeyByName(dictObject, value):
for (key, itemValue) in dictObject.items():
if (value == itemValue):
return key
retu... |
# --------------
class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio']
class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes']
new_class = class_1 + class_2
new_class.append("Peter Warden")
print(new_class)
new_class.remove("Carla Gentry")
print(new_class)
courses = { "Math":65,"English":70,... |
jogadores = list()
while True:
jogador = dict()
jogador['Nome'] = str(input('Nome do jogador: ')).strip().title()
lst = list()
partidas = int(input(f'Quantas partidas o jogador {jogador["Nome"]} jogou? '))
for q in range(0, partidas):
lst.append(int(input(f'Quantos gols na partida {q + 1}? '... |
#
# @lc app=leetcode id=20 lang=python3
#
# [20] Valid Parentheses
#
# @lc code=start
class Solution:
def isValid(self, s: str) -> bool:
# if s == ""
if len(s) == 0:
return True
d = {
')': '(',
'}' : '{',
']' : '['
}
temp = []
... |
"""
Overview
========
This module implements the NORMAL mode that is the mode in which most
editing keycommands are implemented.
Key-Commands
============
Namespace: normal-mode
Mode: -1
Event: <Escape>
Description: Get the focused AreaVi instance in NORMAL mode.
Mode: -1
Event: <Alt-n>
Description: Get the focuse... |
# 函数
def sign(x):
if x > 0:
return 'positive'
elif x < 0:
return 'negative'
else:
return 'zero'
for x in [-1, 0, 1]:
print(sign(x))
# 定义具有可选参数函数
def hello(name, loud=False):
if loud:
print('HELLO, %s' % name.upper())
else:
print('hello, %s' % name)
h... |
total_umur_dalam_hari = 75
jumlah_hari_dalam_sebulan = 30
bulan = total_umur_dalam_hari/jumlah_hari_dalam_sebulan
hari = total_umur_dalam_hari % jumlah_hari_dalam_sebulan
print('umur bayi sekarang {} bulan dan {} hari'.format(bulan,hari))
print('umur bayi sekarang {1} bulan dan {0} hari'.format(hari,bulan))
print('um... |
graph = {
1: [2,3,4],
2: [5],
3: [5],
4: [],
5: [6, 7],
6: [],
7: [3]
}
def recursive_dfs(v, discovered = []) :
discovered.append(v)
for w in graph[v] :
if not w in discovered :
discovered = recursive_dfs(w, discovered)
return discovered
def iterative_dfs(s... |
# Copyright 2018 Road-Support - Roel Adriaans
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Github Connector - OCA extension",
"summary": "Add OCA specific information to Odoo modules",
"version": "13.0.1.0.0",
"category": "Connector",
"license": "AGPL-3",
"author": ... |
# encoding='utf-8'
'''
/**
* This is the solution of No. 647 problem in the LeetCode,
* the website of the problem is as follow:
* https://leetcode-cn.com/problems/palindromic-substrings
* <p>
* The description of problem is as follow:
* ===========================================================================... |
def initialize():
return 'initialize'
def computeTile(x, y, array):
spend_some_time()
return 'computeTile-' + str(x) + ',' + str(y)
def dispose():
return 'dispose'
def spend_some_time():
l = list(range(10000))
for i in range(10000):
l.reverse()
|
# Exibindo valores da lista com for
comidas = ['Cebola', 'Tomate', 'Cenoura', 'Ovo', 'Queijo', 'Cerveja']
print("indice - elemento")
for indice, elemento in enumerate(comidas):
print (f"{indice:<5}{elemento}")
print(1 + 1)
|
pkgname = "bsded"
pkgver = "0.99.0"
pkgrel = 0
build_style = "makefile"
pkgdesc = "FreeBSD ed(1) utility"
maintainer = "q66 <q66@chimera-linux.org>"
license = "BSD-2-Clause"
url = "https://github.com/chimera-linux/bsded"
source = f"https://github.com/chimera-linux/bsded/archive/refs/tags/v{pkgver}.tar.gz"
sha256 = "ae3... |
def load():
with open("input") as f:
yield next(f).strip()
next(f)
img = {}
for y, row in enumerate(f):
img.update({(x, y): v for x, v in enumerate(row.strip())})
yield img
def get_square(x, y, image, void_value):
for i in range(y - 1, y + 2):
for j ... |
gap_base_command = """
export PATH=/home/users/gfonseca/QUIP/build/linux_x86_64_gfortran/:$PATH
module load lang/SciPy-bundle/2019.03-intel-2019a
module load tools/binutils/2.32-GCCcore-8.2.0
source /home/users/gfonseca/anaconda3/bin/activate quippy
cd __WORK_DIR__
gap_fit at_file=__TRAIN_FILE__ \
gap={soap cut... |
#a function which formats a duration, given as a number of seconds, in a human-friendly way.
def format_duration(seconds):
if seconds is 0:
return 'now'
times = ['years', 'days', 'hours', 'minutes', 'seconds']
times_to_seconds = {'years':31536000, 'days':86400, 'hours':3600, 'minutes':60, 'seconds... |
#
# Bounce constant investigation
#
Y_BASE = 210
Y_TOP = 88
Y_MAX = 65 # maximum allowed height
TIME = 113 # time to bounce
# simulates given arc with starting VY and gravity AY
# returns (peak,time length)
def arc(vy,ay,trace=False):
p = 0
y = 0
t = 0
if (trace):
print("arc(%5d,%5d)" % (vy,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.