content stringlengths 7 1.05M |
|---|
'''
Settings for generating synthetic images using code for
Cut, Paste, and Learn Paper
'''
# Paths
BACKGROUND_DIR = '/scratch/jnan1/background/TRAIN'
BACKGROUND_GLOB_STRING = '*.png'
INVERTED_MASK = False # Set to true if white pixels represent background
# Parameters for generator
NUMBER_OF_WORKERS = 4
BLENDING_LIS... |
# https://adventofcode.com/2019/day/4
def is_valid_password(i: int, version: int = 1) -> bool:
i_digits = [int(digit) for digit in str(i)]
is_increasing, repeats = True, False
for k in range(len(i_digits) - 1):
if i_digits[k] > i_digits[k+1]:
is_increasing = False
elif version ... |
class Solution:
def minArray(self, numbers: List[int]) -> int:
left = 0
right = len(numbers) - 1
# 注意这里和labuladong模板有区别,循环是left<right,而不是left<=right
while left < right:
mid = left + (right - left) // 2
# 注意这里比较的是mid和right,而不是mid和left
# 右边有序,最小值一定在左... |
"""
Module: 'pybricks.uev3dev.sound' on LEGO EV3 v1.0.0
"""
# MCU: sysname=ev3, nodename=ev3, release=('v1.0.0',), version=('0.0.0',), machine=ev3
# Stubber: 1.3.2
INT32 = 671088640
class Mixer:
''
_attach = None
_close = None
_find_selem = None
_load = None
_open = None
_selem_get_playback... |
"""
Fill out the file src/visualization/visualize.py with this (as minimum, feel free to add more vizualizations)
loads a pre-trained network,
extracts some intermediate representation of the data (your training set) from your cnn. This could be the features just before the final classification layer
Visualize feature... |
#---Criar um arquivo txt
#---ler do console
#---Armazenar numa variavel
arquivo = open('exercicio.txt', 'a')
#----- Coloquei o for para a pessoa escrever mais vezes seguidas sem ter que executar o programa de novo
#-----Eu poderia colocar o input dentro do arquivo.write pra não precisar criar uma variavel(porém prest... |
def astore_url(package, uid, instance = "https://astore.corp.enfabrica.net"):
"""Returns a URL for a particular package version from astore."""
if not package.startswith("/"):
package = "/" + package
return "{}/d{}?u={}".format(
instance,
package,
uid,
)
def _astore_uplo... |
number = int(input("Podaj liczbę naturalną: "))
if number > 0:
def silnia(number):
first = 1
for i in range(2, number + 1):
first *= i
return first
resolve = str(silnia(number))
for words in range(1, len(resolve) + 1):
if resolve[-words] != "0":
print... |
# -*- coding: utf-8 -*-
"""
Datary Api python sdk Operations Limits files.
"""
class DataryOperationLimits():
"""
Datary OperationLimits module class
"""
_DEFAULT_LIMITED_DATARY_SIZE = 9500000
|
#Function which finds 45 minutes before current time
def alarm_clock(h, m):
#Finding total minutes passed
total_minutes = h * 60 + m
ans = []
#Subtracting 45 minutes
if total_minutes >= 45:
answer_minutes = total_minutes - 45
else:
answer_minutes = total_minutes - 45 + 1440
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 25 22:37:47 2018
@author: JinJheng
"""
def compute():
x=int(input())
if x<=1:
print('Not Prime')
else:
for i in range(2,x+1):
if x%i==0:
print('Not Prime')
else:
print('Pr... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 13 17:02:29 2017
@author: taichi
"""
file = open("sample_data\poem.txt", "a" );
file.write("How can a clam cram in a clean cream can?")
file.close() |
'''
Crie um programa que tenha um tupla com várias palavras (não usar acentos). Depois disso,
você deve mostrar, para cada palavra, quais são suas vogais.
'''
palavras = ('arroz', 'computador', 'piscina', 'copo', 'dentista',
'lazer', 'mouse', 'telefone', 'vestido', 'bermuda', 'aspirador')
for p in palavra... |
class TypeValidator(object):
def __init__(self, *types, **options):
self.types = types
self.exclude = options.get('exclude')
def __call__(self, value):
if self.exclude is not None and isinstance(value, self.exclude):
return False
if not isinstance(value, self.types... |
class ImageArea:
def __init__(self, width, height):
self.width = width
self.height = height
def get_area(self):
area = self.width * self.height
return area
def __gt__(self, other):
return self.get_area() > other.get_area()
def __ge__(self, other):
retur... |
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
found = {}
max_length = 0
start_pos = -1
for pos, char in enumerate(s):
if char in found and start_pos <= found[char]:
start_pos = found[char]
else:
max_length =... |
#!/usr/bin/env python3
def meg_bisect(ng, ok, func):
# 二分探索・二分法 O(logn)
# 半開区間 (ng, ok] / [ok, ng)
# func: 単調増加関数
while abs(ok - ng) > 1:
mid = (ok + ng) // 2
if func(mid):
ok = mid
else:
ng = mid
return ok
f = lambda k: sum(a * (k ** r) for r, a in ... |
num = []
quant = 1
print('\033[30m-'*45)
while True:
num.append(int(input('Digite um número: ')))
resp = ' '
while resp[0] not in 'SN':
resp = str(input('Quer continuar? [S/N] ')).upper().strip()
if resp[0] == 'N':
break
quant += 1
print('-'*45)
print(f'Você digitou {quant} números.'... |
try:
raise ArithmeticError
except Exception:
print("Caught ArithmeticError via Exception")
try:
raise ArithmeticError
except ArithmeticError:
print("Caught ArithmeticError")
try:
raise AssertionError
except Exception:
print("Caught AssertionError via Exception")
try:
raise AssertionError
... |
# The directory where jobs are stored
job_directory = "/fred/oz988/gwcloud/jobs/"
# Format submission script for specified scheduler.
scheduler = "slurm"
# Environment scheduler sources during runtime
scheduler_env = "/fred/oz988/gwcloud/gwcloud_job_client/bundles/unpacked/fbc9f7c0815f1a83b0de36f957351c93797b2049/ven... |
# Node: Gate G102 (1096088604)
# http://www.openstreetmap.org/node/1096088604
assert_has_feature(
16, 10487, 25366, 'pois',
{ 'id': 1096088604, 'kind': 'aeroway_gate' })
# Node: Gate 1 (2618197593)
# http://www.openstreetmap.org/node/2618197593
assert_has_feature(
16, 10309, 22665, 'pois',
{ 'id': 2618... |
"""def splitText(text, lineLength, tabCount):
lastSpace = 0
cnt = 0
if(len(text) <= lineLength):
return text
for(i in range(len(text)))
if(cnt > lineLength)
if(text[i] == ' '):
last"""
def writeBinaryData(file, data, length):
itr = 0
for i in range(length):
if itr % 16 == 0:
file.writeNo... |
c = 'Caixa Eletrônico'
print('='*40)
print(f'{c:^40}')
print('='*40)
saque = int(input('Valor do Saque R$'))
total = saque
ced = 200
totced = 0
while True:
if total >= ced:
total -= ced
totced += 1
else:
if totced > 0:
print(f'{totced} de cédulas de R${ced}')
if ced =... |
# Leo colorizer control file for io mode.
# This file is in the public domain.
# Properties for io mode.
properties = {
"commentStart": "*/",
"indentCloseBrackets": ")",
"indentOpenBrackets": "(",
"lineComment": "//",
"lineUpClosingBracket": "true",
}
# Attributes dict for io_main rule... |
# Copyright 2019 Open Source Robotics Foundation
# Licensed under the Apache License, version 2.0
"""Colcon event handler extensions for analyzing sanitizer outputs."""
|
x = int(input())
ar = list(map(int,input().split()))
ar = sorted(ar)
if(ar[0]<=0):
print(False)
else:
chk = False
for i in ar:
s = str(i)
if (s==s[::-1]):
chk = True
break
print(chk) |
#!/bin/zsh
'''
Extending the Multiclipboard
Extend the multiclipboard program in this chapter so that it has a delete <keyword>
command line argument that will delete a keyword from the shelf. Then add a delete
command line argument that will delete all keywords.
'''
|
"""
5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'.
Once 'done' is entered, print out the largest and smallest of the numbers.
If the user enters anything other than a valid number catch it with a try/except and
put out an appropriate message and ignor... |
# Copyright 2021 Google LLC
#
# 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, ... |
class CityNotFoundError(Exception):
pass
class ServerError(Exception):
pass
class OWMApiKeyIsNotCorrectError(ServerError):
pass
|
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
l = 0
r = len(numbers) - 1
while l < r:
sum = numbers[l] + numbers[r]
if sum == target:
return [l + 1, r + 1]
if sum < target:
l += 1
else:
r -= 1
|
ano = int(input('Diga um ano: '))
if ano % 4 == 0 and ano % 100 != 0 or ano % 400 == 0:
print('Esse é um ano bissexto!')
else:
print('Esse não é um ano bissexto!')
print('--- FIM ---')
|
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
REDEFINED = "\033[0;0m"
PROCESS = "\033[1;37;42m"
def message_information(text):
print(OKBLUE + str(text) + REDEFINED)
def message_sucess(text):
pri... |
class SensorStatusJob:
on = 'ON'
off = 'OFF'
broken = 'BROKEN'
charge_low = 'CHARGE_LOW'
discharged = 'DISCHARGED'
class SensorStatusSituation:
null = 'NULL'
stable = 'STABLE'
fire = 'FIRE'
warning = 'WARNING'
class ObjectStatusJob:
on = 'ON'
off = 'OFF'
defect = 'DEF... |
"""
# @Time : 2020/6/24
# @Author : Jimou Chen
"""
class Stack:
def __init__(self):
self.elem = []
def pop(self):
self.elem.pop()
def push(self, obj):
self.elem.append(obj)
def get_pop(self):
return self.elem[-1]
def is_empty(self):
if len(self.ele... |
print('Digite um número inteiro, que irá aparecer a soma do sucessor de seu triplo com o antecessor de seu dobto')
num = int(input('Número: '))
s = num * 3
a = num * 2
soma = s + a
print(f'A soma do sucessor de seu triplo com o antecessor de seu dobto é: {soma} e o número escolhido foi: {num}') |
'''
5. 使用filter筛选序列中所有回文数,假定序列是[132, 12321, 11, 9989, 666]
'''
def ishuiwen(num):
l=list(str(num))
l.reverse()
newnum=int(''.join(l))
if newnum==num:
return num
else:
return 0
l=[132,12321,11,9989,666]
f=filter(ishuiwen,[x for x in l])
print(list(f))
|
"""Given two arrays a and b write a function comp(a, b) (orcompSame(a, b)) that checks whether the two arrays have the "same" elements, with the same multiplicities.
"Same" means, here, that the elements in b are the elements in a squared, regardless of the order.
Examples
Valid arrays
a = [121, 144, 19, 161, 19, 144,... |
# Misc general coloring tips
# Color organization: highlighted, neutral, and low-lighted/background
# Red and green in center of screen
# Blue, black, white, and yellow in periphery of screen
# http://www.awwwards.com/flat-design-an-in-depth-look.html
# main actions such as "Submit," "Send," "See More," should have v... |
subprocess.Popen('/bin/ls *', shell=True) #nosec (on the line)
subprocess.Popen('/bin/ls *', #nosec (at the start of function call)
shell=True)
subprocess.Popen('/bin/ls *',
shell=True) #nosec (on the specific kwarg line)
|
'''
Single point of truth for version information
'''
VERSION_NO = '1.1.7'
VERSION_DESC = 'VAWS' + VERSION_NO
|
#! python39
class TwistEncrypt:
"""TwistEncrypt
Classe para implementar criptografia Twist
Baseado em um trabalho pedido em cursos da USP pelo Departamento de Ciência da
Computação (DCC)
"""
_transCodigo =['_']+ list([chr(i) for i in range(ord('a'),ord('z')+1)])+['.']
_nTransCo... |
# 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
slow = fast = head
meet = None
while fast and fas... |
# Create a string variable with your full name
name = "Boris Johnson"
# Split the string into a list
names = name.split(" ")
# Print out your surname
surname = names[-1]
print("Surname:", surname)
# Check if your surname contains the letter 'e'
pos = surname.find("e")
print("Position of 'e':", pos)
# or contains th... |
# Demonstration von Properties
class MyClassVanilla:
""" Klasse mit einfachem Attribut (ohne Propertie) """
def __init__(self):
self.value = 0
class MyClassProperties:
""" Klasse mit Propertie, das im Setter überprüft wird.
Entscheidendes Kriterium: Eine nachträgliche Abstraktion
... |
numeros = list()
for x in range(0, 5):
numeros.append(int(input(f'Digite um número para a posição {x}: ')))
print(f'Você digitou os valores {numeros}')
###################################################################################
print(f'O maior valor digitado foi {max(numeros)} nas posições ', end = '')... |
""" Max() Function
Write a program that can take two numbers from user and then pass these numbers as arguments to function called max(a, b) where a is the first number and b is the second number. This finction should print the maximum number.
"""
def Max(a, b): # He used 'M' capital in Max() because ... |
# Bit Manipulation
# Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
#
# Example 1:
#
# Input: 11
# Output: 3
# Explanation: Integer 11 has binary representation 00000000000000000000000000001011
# Example 2:
#
# Input: 128
# Output: 1
# Expl... |
value = 'some' #modify this line
if value == 'Y' or value == 'y':
print('yes')
elif value == 'N' or value == 'n':
print('no')
else:
print('error')
|
class BasicBlock(object):
def __init__(self):
self.start_addr = 0
self.end_addr = 0
self.instructions = []
self.successors = []
def __str__(self):
return "0x%x - 0x%x (%d) -> [%s]" % (self.start_addr, self.end_addr, len(self.instructions), ", ".join(["0x%x" % ref for ... |
events = input().split("|")
energy = 100
coins = 100
is_bankrupt = False
for event in events:
args = event.split("-")
name = args[0]
value = int(args[1])
if name == "rest":
gained_energy = 0
if energy + value < 100:
gained_energy = value
energy += value
... |
to_name = {
"TA": "TA",
"D": "dependent",
"TC": "tile coding",
"RB": "random binary",
"R": "random real-valued",
"P": "polynomial",
"F": "fourier",
"RC": "state aggregation",
}
|
# https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/
# split a array into 3 equal subarray
def canThreePartsEqualSum(self, A):
"""
:type A: List[int]
:rtype: bool
"""
s= sum(A)
if s%3!=0:
return False
each_sum = s/3
... |
class Pessoa:
olhos = 2 #atributo de classe
def __init__(self, *filhos, nome=None, idade=35):
self.idade = idade
self.nome = nome
self.filhos = list(filhos)
def cumprimentar(self):
return f'Olá {id(self)}'
if __name__ == '__main__':
diego = Pessoa(nome='Diego') #objeto
... |
# -*- coding:utf-8 -*-
class Solution:
def IsPopOrder(self, pushV, popV):
# write code here
imi = [pushV.pop(0)]
while imi:
cur = popV.pop(0)
while imi[-1] != cur:
if not pushV: return False
imi.append(pushV.pop(0))
imi.pop(... |
colors_file = None
try:
colors_file = open("colors2.txt", "r")
for color in colors_file:
print(color.rstrip())
except IOError as exc:
print(exc)
finally:
if colors_file:
colors_file.close()
# print(dir(colors_file))
|
'''
import html2text
html = input('')
text = html2text.html2text(html)
print(text)
input()
'''
teste = input("Digite:")
if teste == "1":
print("1")
elif teste == "2":
print("2")
else:
print("3") |
d = {'name':'mari','age':19,'gender':'feminine'}
del d['age']
print(d.values())
# .keys()
# .items()
for k,v in d.items():
print(f'[{k}]:[{v}]')
print(d)
e = {}
br = []
for c in range(0,2):
e['uf'] = str(input('estado: '))
e['cidade'] = str(input('cidade: '))
br.append(e.copy())
print(br)
|
class MultiplesOf3And5:
def execute(self, top):
result = 0
for multiple in [3, 5]:
result += sum(self.get_multiples(multiple, top))
return result
def get_multiples(self, multiple, top):
value = 0
while value < top:
yield value
... |
#
# PROBLEM INTERPRETATION | MY INTERPRETATION
# |
# West | West
# _______ | ... |
class UtezenDigraf:
"Prostorska zahtevnost: O(n^2)"
def __init__(G):
"Časovna zahtevnost: O(1)"
G.A = {}
def dodajVozlisce(G, u):
"Časovna zahtevnost: O(n)"
if u in G.A:
return
G.A[u] = {w: float('inf') for w in G.A}
for w in G.A:
... |
# Why does this file exist, and why not put this in `__main__`?
#
# You might be tempted to import things from __main__ later,
# but that will cause problems: the code will get executed twice:
#
# - When you run `python -m poetry_issue_2369` python will execute
# `__main__.py` as a script. That means there won't be a... |
class YRangeConfigurator:
"""
"""
def __init__(self, config):
"""
:param config: The config parameter is a dictionary containing all of the Dataspot basic configurations. An
example of the basic structure can be found in examples/dataspot_config_example.json
... |
# ПРИМЕР:
# import random
# my_list = []
# Сгенерили список:
# for _ in range(10):
# my_list.append(random.randint(0, 100))
# А теперь проверяем больше ли оно 10 и добавляет его:
# my_sum = 0
# for element in my_list:
# if element > 10:
# my_sum = my_sum + element
# print(my_sum)
# Задание 1:
# li... |
{
"task": "tabular",
"core": {
"data": {
"bs": 64, #Default
"val_bs": null, #Default
"device": null, #Default
"no_check": false, #Default
"num_workers": 16,
"validation": {
"method": "none", # [spl... |
__author__ = 'saeedamen' # Saeed Amen / saeed@thalesians.com
#
# Copyright 2015 Thalesians Ltd. - http//www.thalesians.com / @thalesians
#
# 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://... |
def find_best_step(v):
"""
Returns best solution for given value
:param v: value
:return: best solution or None when no any solutions available
"""
s = bin(v)[2:]
r = s.find("0")
l = len(s) - r
if (r == -1) or ((l - 1) < 0):
return None
return 1 << (l - 1)
def play_ga... |
# -*- coding: utf-8 -*-
"""
@ created by zejiran
"""
def crear_libro(nom: str, cod: str, autor: int, adp: int, cant: int, pdv: float, cpu: float) -> dict:
dic_libro = {"nombre": nom,
"codigo": cod,
"autor": autor,
"añoPublicacion": adp,
"cantidad... |
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
seen = {}
for i in nums:
if i in seen:
return True
seen[i] = 1
return False |
class Node(object):
def __init__(self, val=None):
self.val = val
self.next = None
class SinglyLinkedList(object):
def __init__(self):
self.head = None
def traverse_list(self):
"""."""
root = self.head
while root is not None:
print(root.val)... |
d = {"a": 1, "b": 2, "c": 3}
sum=0
for i in d:
sum+=d.get(i)
print(sum) |
def triple_sum(nums):
result = []
for i in nums:
for j in nums:
for k in nums:
j_is_unique = j != i and j != k
k_is_unique = k != i
sum_is_zero = (i + j + k) == 0
if j_is_unique and k_is_unique and sum_is_zero:
... |
class Solution:
def tribonacci(self, n: int) -> int:
# fib = [0]*41
# fib[0] = 0
# fib[1] = 1
# fib [2] = 1
# for i in range(n+1):
# fib[i+3] = fib[i] + fib[i+1] + fib[i+2]
# return fib[n]
dp ... |
s=str(input())
n1,n2=[int(e) for e in input().split()]
j=0
for i in range(len(s)):
if j<n1-1:
print(s[j],end="")
j+=1
elif j>=n1-1:
j=n2
if j>=n1:
print(s[j],end="")
j-=1
elif j<=k:
print(s[j],end="")
j+=1
k=n2-1
|
def mapDict(d, mapF):
result = {}
for key in d:
mapped = mapF(key, d[key])
if mapped != None:
result[key] = mapped
return result
withPath = mapDict(houseClosestObj, lambda house, obj: {
"target": obj, "path": houseObjPaths[house][obj]})
with open("houseClose... |
# rounds a number to the nearest even number
# Author: Isabella Doyle
num = float(input("Enter a number: "))
round = round(num)
print('{} rounded is {}'.format(num, round)) |
def main():
print('This is printed from testfile.py')
if __name__=='__main__':
main()
|
"""Lexicon exceptions module"""
class ProviderNotAvailableError(Exception):
"""
Custom exception to raise when a provider is not available,
typically because some optional dependencies are missing
"""
|
def _get_main(ctx):
if ctx.file.main:
return ctx.file.main.path
main = ctx.label.name + ".py"
for src in ctx.files.srcs:
if src.basename == main:
return src.path
fail(
"corresponding default '{}' does not appear in srcs. ".format(main) +
"Add it or override de... |
#----------------------------------------------------------------------------------------------------------
#
# AUTOMATICALLY GENERATED FILE TO BE USED BY W_HOTBOX
#
# NAME: Copy Hue/Sat
#
#----------------------------------------------------------------------------------------------------------
ns = nuke.selectedNode... |
loader="""
d = dict(locals(), **globals())
exec(self.payload, d, d)
"""
|
#!/usr/bin/env python
temp = 24
Farenheint = temp * 1.8 + 32
print(Farenheint)
|
# Copyright 2013 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.
class ProjectConfig(object):
"""Contains information about the benchmark runtime environment.
Attributes:
top_level_dir: A dir that contains benchm... |
expected_output = {
'id':{
101: {
'connection': 0,
'name': 'grpc-tcp',
'state': 'Resolving',
'explanation': 'Resolution request in progress'
}
}
}
|
dolares = input('Cuantos dolares tienes?: ')
dolares = float(dolares)
valor_dolar = 0.045
peso = dolares / valor_dolar
peso = round(peso,2)
peso = str(peso)
print('Tienes $' + peso + ' Pesos') |
class dforest(object):
"""union-find with union-by-rank and path compression"""
def __init__(self,cap=100):
"""creates a disjoint forest with the given capacity"""
self.__parent = [ i for i in range(cap) ]
self.__rank = [ 0 for i in range(cap) ]
self.__count = [ 1 for i in range(cap) ]
self.__c... |
load(":collect_export_declaration.bzl", "collect_export_declaration")
load(":collect_header_declaration.bzl", "collect_header_declaration")
load(":collect_link_declaration.bzl", "collect_link_declaration")
load(":collect_umbrella_dir_declaration.bzl", "collect_umbrella_dir_declaration")
load(":collection_results.bzl", ... |
# 参考: https://github.com/benoitc/gunicorn/blob/master/examples/example_config.py
workers = 4
backlog = 2048
# 指定每个工作的线程数
threads = 2
# 监听端口8000
bind = '0.0.0.0:8000'
# 守护进程,将进程交给supervisor管理
daemon = 'false'
# 工作模式协程
worker_class = 'gevent'
# 最大并发量
worker_connections = 2000
# 进程文件
# pidfile = '/var/run/gunicorn... |
# GEPPETTO SERVLET MESSAGES
class Servlet:
LOAD_PROJECT_FROM_URL = 'load_project_from_url'
RUN_EXPERIMENT = 'run_experiment'
CLIENT_ID = 'client_id'
PING = 'ping'
class ServletResponse:
PROJECT_LOADED = 'project_loaded'
GEPPETTO_MODEL_LOADED = 'geppetto_model_loaded'
EXPERIMENT_LOADED ... |
# 2. Using the dictionary created in the previous problem, allow the user to enter a dollar amount
# and print out all the products whose price is less than that amount.
print('To stop any phase, enter an empty product name.')
product_dict = {}
while True:
product = input('Enter a product name to assign with a pr... |
reservation_day = int(input())
reservation_month = int(input())
accommodation_day = int(input())
accommodation_month = int(input())
leaving_day = int(input())
leaving_month = int(input())
discount = 0
price_per_night = 0
discount_days = accommodation_day - 10
days_staying = abs(accommodation_day - leaving_day)
if r... |
# wordcount.py
"""Contains the wc(file) function."""
def wc(file):
"""Return the newline, word and character number."""
file = open(file, "r")
nl, w, ch = 0, 0, 0
for line in file:
nl += 1
w += line.count(" ") + 1
ch += len(line)
return nl, w, ch
|
s, a, A = list(input()), list('abcdefghijklmnopqrstuvwxyz'), 26
s1, s2 = s[0:len(s) // 2], s[len(s) // 2:len(s)]
s1_r, s2_r = sum([a.index(i.lower()) for i in s1]), sum([a.index(i.lower()) for i in s2])
for i in range(len(s1)):
s1[i] = a[(s1_r + a.index(s1[i].lower())) % A]
for i in range(len(s2)):
s2[i] = a[(s2... |
def test():
print('hello world')
c = color(1,0.2,0.2, 1)
print(c)
print(c.r)
print(c.g)
print(c.b)
print(c.a)
c.a = 0.5
print(c.a)
c.b += 0.1
print(c.b)
d = c.darkened( 0.9 )
print(d)
test() |
out = []
digits =[ "0000001",
"1001111", #1
"0010010",
"0000110", #3
"1001100",
"0100100", #5
"1100000",
"0001111", #7
"0000000",
"0001100", #9
]
for i in range(10000):
s = "{:04d}".format(i)
out += ["{... |
def factorial(n):
"""Does this function work? Hint: no."""
n_fact = n
while n > 1:
n -= 1
n_fact *= n
return n_fact
|
def isIPv4Address(inputString):
# Method 1
if len(inputString.split(".")) != 4:
return False
for x in inputString.split("."):
if not x or not x.isnumeric() or (x.isnumeric() and int(x) > 255):
return False
return True
# # Method 2
# # Same as method 1, but with Pyt... |
# ------------------------------
# 155. Min Stack
#
# Description:
# Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
# push(x) -- Push element x onto stack.
# pop() -- Removes the element on top of the stack.
# top() -- Get the top element.
# getMin() -- Retrieve the m... |
########
# autora: danielle8farias@gmail.com
# repositório: https://github.com/danielle8farias
# Descrição: Usuário informa vários números inteiros que serão guardados em uma lista. O programa retorna os valores pares em uma lista separada e ímpares em outra lista. Ao final, as três listas são exibidas.
########
num_... |
"""
Project Euler - Problem Solution 023
Copyright (c) Justin McGettigan. All rights reserved.
https://github.com/jwmcgettigan/project-euler-solutions
"""
def sum_of_divisors(n):
# reused from problem 021
if n == 0: return 0
total = 1 # start at one since 1 is also a divisor
for i in range(2, int(n**0.5)+1):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.