content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
print('Digite seu nome:')
nome = input()
print('Digite sua idade:')
idade = int(input())
podeVotar = idade>=16
print(nome,'tem',idade,'anos:',podeVotar)
| print('Digite seu nome:')
nome = input()
print('Digite sua idade:')
idade = int(input())
pode_votar = idade >= 16
print(nome, 'tem', idade, 'anos:', podeVotar) |
OK = '+OK\r\n'
def reply(v):
'''
formats the value as a redis reply
'''
return '$%s\r\n%s\r\n' % (len(v), v) | ok = '+OK\r\n'
def reply(v):
"""
formats the value as a redis reply
"""
return '$%s\r\n%s\r\n' % (len(v), v) |
lost_fights = int(input())
helmet_price = float(input())
sword_price = float(input())
shield_price = float(input())
armor_price = float(input())
shield_repair_count = 0
total_cost = 0
for i in range(1, lost_fights+1):
if i % 2 == 0:
total_cost += helmet_price
if i % 3 == 0:
total_co... | lost_fights = int(input())
helmet_price = float(input())
sword_price = float(input())
shield_price = float(input())
armor_price = float(input())
shield_repair_count = 0
total_cost = 0
for i in range(1, lost_fights + 1):
if i % 2 == 0:
total_cost += helmet_price
if i % 3 == 0:
total_cost += sword... |
def end_other(a, b):
a = a.lower()
b = b.lower()
if a[-(len(b)):] == b or a == b[-(len(a)):]:
return True
return False
| def end_other(a, b):
a = a.lower()
b = b.lower()
if a[-len(b):] == b or a == b[-len(a):]:
return True
return False |
class PermissionBackend(object):
supports_object_permissions = True
supports_anonymous_user = True
def authenticate(self, **kwargs):
# always return a None user
return None
def has_perm(self, user, perm, obj=None):
if user.is_anonymous():
return False
if pe... | class Permissionbackend(object):
supports_object_permissions = True
supports_anonymous_user = True
def authenticate(self, **kwargs):
return None
def has_perm(self, user, perm, obj=None):
if user.is_anonymous():
return False
if perm in ['forums.add_forumthread', 'for... |
class A:
def m():
pass
def f():
pass
| class A:
def m():
pass
def f():
pass |
# -*- encoding: utf-8 -*-
class KlotskiBoardException(Exception):
def __init__(self, piece, kind_message):
message = "Wrong board configuration: {} '{}'".format(kind_message, piece)
super().__init__(message)
class WrongPieceValue(KlotskiBoardException):
def __init__(self, x):
super()... | class Klotskiboardexception(Exception):
def __init__(self, piece, kind_message):
message = "Wrong board configuration: {} '{}'".format(kind_message, piece)
super().__init__(message)
class Wrongpiecevalue(KlotskiBoardException):
def __init__(self, x):
super().__init__(x, 'wrong piece v... |
'''
A curious problem that involves 'rotating' a number and solving a number of contraints
Author: Daniel Haberstock
Date: 05/26/2018
Sources used:
https://stackoverflow.com/questions/19463556/string-contains-any-character-in-group
'''
def rotate(x):
# split up the integer into a list of single digit strings
... | """
A curious problem that involves 'rotating' a number and solving a number of contraints
Author: Daniel Haberstock
Date: 05/26/2018
Sources used:
https://stackoverflow.com/questions/19463556/string-contains-any-character-in-group
"""
def rotate(x):
splitx = [i for i in str(x)]
splitx.reverse()
y = ''
... |
S = input()
ans = (
'YES' if S.count('x') <= 7 else
'NO'
)
print(ans)
| s = input()
ans = 'YES' if S.count('x') <= 7 else 'NO'
print(ans) |
{
"targets": [
{
"target_name": "node-hide-console-window",
"sources": [ "node-hide-console-window.cc" ]
}
]
} | {'targets': [{'target_name': 'node-hide-console-window', 'sources': ['node-hide-console-window.cc']}]} |
class Node():
left = None
right = None
def __init__(self, element):
self.element = element
def __str__(self):
return "\t\t{}\n{}\t\t{}".format(self.element, self.left, self.right)
class BinaryTree():
head = None
def __init__(self, head):
self.head = Node(head... | class Node:
left = None
right = None
def __init__(self, element):
self.element = element
def __str__(self):
return '\t\t{}\n{}\t\t{}'.format(self.element, self.left, self.right)
class Binarytree:
head = None
def __init__(self, head):
self.head = node(head)
def __... |
# n=int(input())
# n2=input()
# ar=str(n2)
# ar=ar.split()
# pair={}
# total=0
# for i in ar:
# if i not in pair:
# pair[i]=1
# else:
# pair[i]+=1
# for j in pair:
# store=pair[j]//2
# total+=store
# print (total)
n=int(input("number of socks :"))
ar=input("colors of socks :").split()... | n = int(input('number of socks :'))
ar = input('colors of socks :').split()
pair = {}
total = 0
for i in ar:
if i not in pair:
pair[i] = 1
else:
pair[i] += 1
for j in pair:
store = pair[j] // 2
total += store
print(total) |
class Solution:
def trap(self, height: List[int]) -> int:
lmax,rmax = 0,0
l,r = 0,len(height)-1
ans = 0
while l<r:
if height[l]<height[r]:
if height[l]>=lmax:
... | class Solution:
def trap(self, height: List[int]) -> int:
(lmax, rmax) = (0, 0)
(l, r) = (0, len(height) - 1)
ans = 0
while l < r:
if height[l] < height[r]:
if height[l] >= lmax:
lmax = height[l]
else:
... |
lanjut = 'Y'
kumpulan_luas_segitiga = []
while lanjut == 'Y':
alas = float(input("Masukkan panjang alas (cm) : "))
tinggi = float(input("Masukkan tinggi segitiga (cm) : "))
luas = alas * tinggi * 0.5 # / 2
print("Luas segitiganya adalah :", luas)
kumpulan_luas_segitiga.append(luas)
lanjut = input("\nMau... | lanjut = 'Y'
kumpulan_luas_segitiga = []
while lanjut == 'Y':
alas = float(input('Masukkan panjang alas (cm) : '))
tinggi = float(input('Masukkan tinggi segitiga (cm) : '))
luas = alas * tinggi * 0.5
print('Luas segitiganya adalah :', luas)
kumpulan_luas_segitiga.append(luas)
lanjut = input('\nM... |
class StringFormatter(object):
def __init__(self):
pass
def justify(self, text, width=21):
'''
Inserts spaces between ':' and the remaining of the text to make
sure 'text' is 'width' characters in length.
'''
if len(text) < width:
index = text.find... | class Stringformatter(object):
def __init__(self):
pass
def justify(self, text, width=21):
"""
Inserts spaces between ':' and the remaining of the text to make
sure 'text' is 'width' characters in length.
"""
if len(text) < width:
index = text.find('... |
input_str = "12233221"
middle_size = int(round(len(input_str) / 2) )
print(f"middle_size: {middle_size}")
end_index = -1
start_index = 0
while start_index < middle_size:
char_from_start = input_str[start_index]
char_from_end = input_str[end_index]
end_index = end_index - 1
start_index = start_index... | input_str = '12233221'
middle_size = int(round(len(input_str) / 2))
print(f'middle_size: {middle_size}')
end_index = -1
start_index = 0
while start_index < middle_size:
char_from_start = input_str[start_index]
char_from_end = input_str[end_index]
end_index = end_index - 1
start_index = start_index + 1
... |
def main(self):
def handler(message):
if message["channel"] == "/service/player" and message.get("data") and message["data"].get("id") == 5:
self._emit("GameReset")
self.handlers["gameReset"] = handler
| def main(self):
def handler(message):
if message['channel'] == '/service/player' and message.get('data') and (message['data'].get('id') == 5):
self._emit('GameReset')
self.handlers['gameReset'] = handler |
# MQTT certificates
CA_CERT = "./../keys/ca/ca.crt"
CLIENT_CERT = "./../keys/client/client.crt"
CLIENT_KEY = "./../keys/client/client.key"
TLS_VERSION = 2
# MQTT broker options
TOPIC_NAME = "sensors/Temp"
HOSTNAME = "mqtt.sandyuraz.com"
PORT = 8883
# MQTT user options
CLIENT_ID = "sandissa-secret-me"
USERNAME = "kit... | ca_cert = './../keys/ca/ca.crt'
client_cert = './../keys/client/client.crt'
client_key = './../keys/client/client.key'
tls_version = 2
topic_name = 'sensors/Temp'
hostname = 'mqtt.sandyuraz.com'
port = 8883
client_id = 'sandissa-secret-me'
username = 'kitty'
password = None
qos_publish = 2
qos_subscribe = 2 |
x,y = input().split()
a = int(x)
b = int(y)
if a < b and (b-a) == 1:
print("Dr. Chaz will have " + str(b-a) + " piece of chicken left over!")
elif a < b:
print("Dr. Chaz will have " + str(b - a) + " pieces of chicken left over!")
elif a > b and (a-b) == 1:
print("Dr. Chaz needs " + str(a - b) + " ... | (x, y) = input().split()
a = int(x)
b = int(y)
if a < b and b - a == 1:
print('Dr. Chaz will have ' + str(b - a) + ' piece of chicken left over!')
elif a < b:
print('Dr. Chaz will have ' + str(b - a) + ' pieces of chicken left over!')
elif a > b and a - b == 1:
print('Dr. Chaz needs ' + str(a - b) + ' more ... |
n=int(input())
sh=5
li=0
cum=0
for i in range(n):
li = sh // 2
sh=(li*3)
cum+=li
print(cum) | n = int(input())
sh = 5
li = 0
cum = 0
for i in range(n):
li = sh // 2
sh = li * 3
cum += li
print(cum) |
n=1
s=0
while(n<50):
cn=n
mdx=0
mposfl=0
pos=0
nod=0
while(cn>0):
ld=cn%10
nod=nod+1
if(ld>mdx):
mdx=ld
mposfl=pos
cn=cn/10
pos=pos+1
apos=nod-mposfl
i=0
sr=0
while(n>0):
if(i==apos):
contin... | n = 1
s = 0
while n < 50:
cn = n
mdx = 0
mposfl = 0
pos = 0
nod = 0
while cn > 0:
ld = cn % 10
nod = nod + 1
if ld > mdx:
mdx = ld
mposfl = pos
cn = cn / 10
pos = pos + 1
apos = nod - mposfl
i = 0
sr = 0
while n > 0:... |
class Solution:
def romanToInt(self, s: str) -> int:
num = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
val, pre = 0, 0
for key in s:
n = num[key] if key in num else 0
val += -pre if n > pre else pre
pre = n
val += pre
... | class Solution:
def roman_to_int(self, s: str) -> int:
num = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
(val, pre) = (0, 0)
for key in s:
n = num[key] if key in num else 0
val += -pre if n > pre else pre
pre = n
val += pre
... |
lb = {
"loadBalancer": {
"name": "mani-test-lb",
"port": 80,
"protocol": "HTTP",
"virtualIps": [
{
"type": "PUBLIC"
}
]
}
}
nodes = {
"nodes": [
{
... | lb = {'loadBalancer': {'name': 'mani-test-lb', 'port': 80, 'protocol': 'HTTP', 'virtualIps': [{'type': 'PUBLIC'}]}}
nodes = {'nodes': [{'address': '10.2.2.3', 'port': 80, 'condition': 'ENABLED', 'type': 'PRIMARY'}]}
metadata = {'metadata': [{'key': 'color', 'value': 'red'}]}
config = {'name': 'lbaas', 'description': 'R... |
def includeme(config):
config.add_static_view('js', 'static/js', cache_max_age=3600)
config.add_static_view('css', 'static/css', cache_max_age=3600)
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_static_view('dz', 'static/dropzone', cache_max_age=3600)
config.add_route('ad... | def includeme(config):
config.add_static_view('js', 'static/js', cache_max_age=3600)
config.add_static_view('css', 'static/css', cache_max_age=3600)
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_static_view('dz', 'static/dropzone', cache_max_age=3600)
config.add_route('ad... |
def last_minute_enhancements(nodes):
count = 0
current_node = 0
for node in nodes:
if node > current_node:
count += 1
current_node = node
elif node == current_node:
count += 1
current_node = node + 1
return count
if __name__ == "__main__"... | def last_minute_enhancements(nodes):
count = 0
current_node = 0
for node in nodes:
if node > current_node:
count += 1
current_node = node
elif node == current_node:
count += 1
current_node = node + 1
return count
if __name__ == '__main__':
... |
# Opencast server address and credentials for api user
OPENCAST_URL = 'OPENCAST_URL'
OPENCAST_USER = 'OPENCAST_API_USER'
OPENCAST_PASSWD = 'OPENCAST_PASSWORD_USER'
# Timezone for the messages and from the XML file
MESSAGES_TIMEZONE = 'Europe/Berlin'
# Capture agent Klips dictionary
#
# Here you have to put the dic... | opencast_url = 'OPENCAST_URL'
opencast_user = 'OPENCAST_API_USER'
opencast_passwd = 'OPENCAST_PASSWORD_USER'
messages_timezone = 'Europe/Berlin'
capture_agent_dict = {} |
#
# PySNMP MIB module NHRP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NHRP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:51:40 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, value_size_constraint, constraints_intersection, value_range_constraint) ... |
env_name = 'BreakoutDeterministic-v4'
input_shape = [84, 84, 4]
output_size = 4
'''
env_name = 'SeaquestDeterministic-v4'
input_shape = [84, 84, 4]
output_size = 18
'''
'''
env_name = 'PongDeterministic-v4
input_shape = [84, 84, 4]
output_size = 6
''' | env_name = 'BreakoutDeterministic-v4'
input_shape = [84, 84, 4]
output_size = 4
"\nenv_name = 'SeaquestDeterministic-v4'\ninput_shape = [84, 84, 4]\noutput_size = 18\n"
"\nenv_name = 'PongDeterministic-v4\ninput_shape = [84, 84, 4]\noutput_size = 6\n" |
# Leetcode 200. Number of Islands
#
# Link: https://leetcode.com/problems/number-of-islands/
# Difficulty: Medium
# Solution using BFS and visited set.
# Complexity:
# O(M*N) time | where M and N represent the rows and cols of the input matrix
# O(M*N) space | where M and N represent the rows and cols of the input... | class Solution:
def num_islands(self, grid: List[List[str]]) -> int:
(rows, cols) = (len(grid), len(grid[0]))
directions = ((0, 1), (0, -1), (1, 0), (-1, 0))
count = 0
visited = set()
def bfs(r, c):
q = deque()
q.append((r, c))
while q:
... |
BUNDLES = [
#! if api:
'flask_unchained.bundles.api',
#! endif
#! if mail:
'flask_unchained.bundles.mail',
#! endif
#! if celery:
'flask_unchained.bundles.celery', # move before mail to send emails synchronously
#! endif
#! if oauth:
'flask_unchained.bundles.oauth',
#! e... | bundles = ['flask_unchained.bundles.api', 'flask_unchained.bundles.mail', 'flask_unchained.bundles.celery', 'flask_unchained.bundles.oauth', 'flask_unchained.bundles.security', 'flask_unchained.bundles.session', 'flask_unchained.bundles.sqlalchemy', 'flask_unchained.bundles.webpack', 'app'] |
class RequestFailedError(Exception):
pass
class DOIFormatIncorrect(Exception):
pass
| class Requestfailederror(Exception):
pass
class Doiformatincorrect(Exception):
pass |
N, M, P, Q = map(int, input().split())
result = (N // (M * (12 + Q))) * 12
N %= M * (12 + Q)
if N <= M * (P - 1):
result += (N + (M - 1)) // M
else:
result += P - 1
N -= M * (P - 1)
if N <= 2 * M * Q:
result += (N + (2 * M - 1)) // (2 * M)
else:
result += Q
N -= 2 * M * Q
... | (n, m, p, q) = map(int, input().split())
result = N // (M * (12 + Q)) * 12
n %= M * (12 + Q)
if N <= M * (P - 1):
result += (N + (M - 1)) // M
else:
result += P - 1
n -= M * (P - 1)
if N <= 2 * M * Q:
result += (N + (2 * M - 1)) // (2 * M)
else:
result += Q
n -= 2 * M * Q
... |
# This is a line comment
'''
This is a block comment
'''
def main():
print("Hello world!\n");
main()
| """
This is a block comment
"""
def main():
print('Hello world!\n')
main() |
# global progViewWidth
ProgEntryFieldW=10
ProgButX=160
progViewWidth=60
stopProgButX=200
comportlabelx=270
comPortEntryFieldX=390
comPortEntryFieldw=12
comPortButx=495
calibration_entryjoinx=520
calibration_entrydhx=745
calibration_joinx=600
calibration_alphax=800
calibrate_buttoncol2x=210
tab1_instructionbuttonw=16
... | prog_entry_field_w = 10
prog_but_x = 160
prog_view_width = 60
stop_prog_but_x = 200
comportlabelx = 270
com_port_entry_field_x = 390
com_port_entry_fieldw = 12
com_port_butx = 495
calibration_entryjoinx = 520
calibration_entrydhx = 745
calibration_joinx = 600
calibration_alphax = 800
calibrate_buttoncol2x = 210
tab1_in... |
#########################################################################
# #
# C R A N F I E L D U N I V E R S I T Y #
# 2 0 1 9 / 2 0 2 0 #
# ... | class Gencuttingplanefile:
def __init__(self, fileName, planeName, point, normal, fields):
self.fileName = fileName
self.planeName = planeName
self.point = point
self.normal = normal
self.fields = fields
def write_cutting_plane_file(self):
cutting_plane_file = o... |
# Strings with apostrophes and new lines
# If you want to include apostrophes in your string,
# it's easiest to wrap it in double quotes.
niceday = "It's a nice day!"
print(niceday)
| niceday = "It's a nice day!"
print(niceday) |
#encoding:utf-8
subreddit = 'chessmemes'
t_channel = '@chessmemesenglish'
def send_post(submission, r2t):
return r2t.send_simple(submission)
| subreddit = 'chessmemes'
t_channel = '@chessmemesenglish'
def send_post(submission, r2t):
return r2t.send_simple(submission) |
def decodeRules(string):
rules = []
# Remove comments
while string.find('%') != -1:
subStringBeforeComment = string[:string.find('%')]
subStringAfterComment = string[string.find('%'):]
if subStringAfterComment.find('\n') != -1:
string = subStringBeforeComment + subString... | def decode_rules(string):
rules = []
while string.find('%') != -1:
sub_string_before_comment = string[:string.find('%')]
sub_string_after_comment = string[string.find('%'):]
if subStringAfterComment.find('\n') != -1:
string = subStringBeforeComment + subStringAfterComment[sub... |
APPLICATION_ID = "vvMc0yrmqU1kbU2nOieYTQGV0QzzfVQg4kHhQWWL"
REST_API_KEY = "waZK2MtE4TMszpU0mYSbkB9VmgLdLxfYf8XCuN7D"
MASTER_KEY = "YPyRj37OFlUjHmmpE8YY3pfbZs7FqnBngxX4tezk"
TWILIO_SID = "AC5e947e28bfef48a9859c33fec7278ee8"
TWILIO_AUTH_TOKEN = "02c707399042a867303928beb261e990" | application_id = 'vvMc0yrmqU1kbU2nOieYTQGV0QzzfVQg4kHhQWWL'
rest_api_key = 'waZK2MtE4TMszpU0mYSbkB9VmgLdLxfYf8XCuN7D'
master_key = 'YPyRj37OFlUjHmmpE8YY3pfbZs7FqnBngxX4tezk'
twilio_sid = 'AC5e947e28bfef48a9859c33fec7278ee8'
twilio_auth_token = '02c707399042a867303928beb261e990' |
#Assume hot dogs come in packages of 10, and hot dog buns come in packages of 8.
hotdogs_perpack = 10
hotdogs_bunsperpack = 8
#program should ask the user for the number of people attending the cookout and the number of hot dogs each person will be given.
ppl_attending = int(input('Enter the number of people atte... | hotdogs_perpack = 10
hotdogs_bunsperpack = 8
ppl_attending = int(input('Enter the number of people attending the cookout: '))
hotdogs_pp = int(input('Enter the number of hot dogs for each person: '))
hotdog_total = ppl_attending * hotdogs_pp
hotdog_packs_needed = hotdog_total / hotdogs_perpack
hotdog_bun_packs_needed =... |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'solo-tests.db',
}
}
INSTALLED_APPS = (
'solo',
'solo.tests',
)
SECRET_KEY = 'any-key'
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': '127.0.... | databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'solo-tests.db'}}
installed_apps = ('solo', 'solo.tests')
secret_key = 'any-key'
caches = {'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': '127.0.0.1:11211'}}
solo_cache = 'default' |
#Author : 5hifaT
#Github : https://github.com/jspw
#Gists : https://gist.github.com/jspw
#linkedin : https://www.linkedin.com/in/mehedi-hasan-shifat-2b10a4172/
#Stackoverflow : https://stackoverflow.com/story/jspw
#Dev community : https://dev.to/mhshifat
def binary_search(ar, value):
s... | def binary_search(ar, value):
start = 0
end = len(ar) - 1
while start <= end:
mid = (start + end) // 2
if ar[mid] == value:
return mid
if ar[mid] > value:
end = mid - 1
else:
start = mid + 1
return -1
def main():
for _ in range(int... |
###exercicio 76
produtos = ('lapis', 1.5, 'borracha', 2.00, 'caderno', 15.00, 'livro', 50.00, 'mochila', 75.00)
print ('='*60)
print ('{:^60}'.format('Lista de produtos'))
print ('='*60)
for c in range (0, len(produtos), 2):
print ('{:<50}R$ {:>7}'.format(produtos[c], produtos[c+1]))
print ('-'*60) | produtos = ('lapis', 1.5, 'borracha', 2.0, 'caderno', 15.0, 'livro', 50.0, 'mochila', 75.0)
print('=' * 60)
print('{:^60}'.format('Lista de produtos'))
print('=' * 60)
for c in range(0, len(produtos), 2):
print('{:<50}R$ {:>7}'.format(produtos[c], produtos[c + 1]))
print('-' * 60) |
# Programacion orientada a objetos (POO o OOP)
# Definir una clase (molde para crear mas objetos de ese tipo)
# (Coche) con caracteristicas similares
class Coche:
# Atributos o propiedades (variables)
# caracteristicas del coche
color = "Rojo"
marca = "Ferrari"
modelo = "Aventador"
velocidad... | class Coche:
color = 'Rojo'
marca = 'Ferrari'
modelo = 'Aventador'
velocidad = 300
caballaje = 500
plazas = 2
def set_color(self, color):
self.color = color
def get_color(self):
return self.color
def set_modelo(self, modelo):
self.modelo = modelo
def g... |
class Solution:
def calculate(self, s: str) -> int:
stacks = [[0, 1]]
val = ""
sign = 1
for i, ch in enumerate(s):
if ch == ' ':
continue
if ch == '(':
stacks[-1][-1] = sign
stacks.append([0, 1])
... | class Solution:
def calculate(self, s: str) -> int:
stacks = [[0, 1]]
val = ''
sign = 1
for (i, ch) in enumerate(s):
if ch == ' ':
continue
if ch == '(':
stacks[-1][-1] = sign
stacks.append([0, 1])
... |
# -*- coding: utf-8 -*-
urls = (
"/", "Home",
)
| urls = ('/', 'Home') |
#!/usr/bin/env python3
BUS = 'http://m.bus.go.kr/mBus/bus/'
SUBWAY = 'http://m.bus.go.kr/mBus/subway/'
PATH = 'http://m.bus.go.kr/mBus/path/'
all_bus_routes = BUS + 'getBusRouteList.bms'
bus_route_search = all_bus_routes + '?strSrch={0}'
bus_route_by_id = BUS + 'getRouteInfo.bms?busRouteId={0}'
all_low_bus_routes = B... | bus = 'http://m.bus.go.kr/mBus/bus/'
subway = 'http://m.bus.go.kr/mBus/subway/'
path = 'http://m.bus.go.kr/mBus/path/'
all_bus_routes = BUS + 'getBusRouteList.bms'
bus_route_search = all_bus_routes + '?strSrch={0}'
bus_route_by_id = BUS + 'getRouteInfo.bms?busRouteId={0}'
all_low_bus_routes = BUS + 'getLowBusRoute.bms'... |
def config_record_on_account(request,account_id):
pass
def config_record_on_channel(request, channel_id):
pass
| def config_record_on_account(request, account_id):
pass
def config_record_on_channel(request, channel_id):
pass |
def gen_primes():
current_number = 2
primes = []
while True:
is_prime = True
for prime in primes:
if prime*prime > current_number: ## This is saying it's a prime if prime * prime > current_testing_number
# print("Caught here")
break # I'd love to s... | def gen_primes():
current_number = 2
primes = []
while True:
is_prime = True
for prime in primes:
if prime * prime > current_number:
break
if current_number % prime == 0:
is_prime = False
break
if is_prime:
... |
def isPrime(x):
for i in range(2,x):
if x%i == 0:
return False
return True
def findPrime(beginning, finish):
for j in range(beginning,finish):
if isPrime(j):
return j
def encrypt():
print("Provide two integers")
x = int(input())
y = int(input())
prime1 = findPrime(x,y)
print("Provi... | def is_prime(x):
for i in range(2, x):
if x % i == 0:
return False
return True
def find_prime(beginning, finish):
for j in range(beginning, finish):
if is_prime(j):
return j
def encrypt():
print('Provide two integers')
x = int(input())
y = int(input())
... |
# Gegeven zijn twee lijsten: lijst1 en lijst2
# Zoek alle elementen die beide lijsten gemeenschappelijk hebben
# Stop deze elementen in een nieuwe lijst
# Print de lijst met gemeenschappelijke elementen
lijst1 = [1, 45, 65, 24, 87, 45, 23, 24, 56]
lijst2 = [10, 76, 34, 1, 56, 22, 33, 77, 1]
| lijst1 = [1, 45, 65, 24, 87, 45, 23, 24, 56]
lijst2 = [10, 76, 34, 1, 56, 22, 33, 77, 1] |
class iterator:
def __init__(self,data):
self.data=data
self.index=-2
def __iter__(self):
return self
def __next__(self):
if self.index>=len(self.data):
raise StopIteration
self.index+=2
return self.data[self.index]
liczby=iterator([0,1,... | class Iterator:
def __init__(self, data):
self.data = data
self.index = -2
def __iter__(self):
return self
def __next__(self):
if self.index >= len(self.data):
raise StopIteration
self.index += 2
return self.data[self.index]
liczby = iterator([0... |
class RemovedInWagtail21Warning(DeprecationWarning):
pass
removed_in_next_version_warning = RemovedInWagtail21Warning
class RemovedInWagtail22Warning(PendingDeprecationWarning):
pass
| class Removedinwagtail21Warning(DeprecationWarning):
pass
removed_in_next_version_warning = RemovedInWagtail21Warning
class Removedinwagtail22Warning(PendingDeprecationWarning):
pass |
arr = list(map(int, input().split()))
n = int(input())
for i in range(len(arr)):
one = arr[i]
for j in range(i+1,len(arr)):
two = arr[j]
s = one + two
if s == n:
print(f'{one} {two}') | arr = list(map(int, input().split()))
n = int(input())
for i in range(len(arr)):
one = arr[i]
for j in range(i + 1, len(arr)):
two = arr[j]
s = one + two
if s == n:
print(f'{one} {two}') |
def format(string):
''' Formats the docstring. '''
# reStructuredText formatting?
# Remove all \n and replace all spaces with a single space
string = ' '.join(list(filter(None, string.replace('\n', ' ').split(' '))))
return string
class DocString:
def __init__(self, strin... | def format(string):
""" Formats the docstring. """
string = ' '.join(list(filter(None, string.replace('\n', ' ').split(' '))))
return string
class Docstring:
def __init__(self, string):
self.string = format(string)
def __str__(self):
return self.string
def __add__(self, other... |
class Solution:
def longestCommonPrefix(self, strs):
if strs == []:
return ""
ans = ""
for i, ch in enumerate(strs[0]): # iterate over the characters of first word
for j, s in enumerate(strs): # iterate over the list of words
if i >= len(strs[j]) or ch != s[i]: # IF the first word is longer
re... | class Solution:
def longest_common_prefix(self, strs):
if strs == []:
return ''
ans = ''
for (i, ch) in enumerate(strs[0]):
for (j, s) in enumerate(strs):
if i >= len(strs[j]) or ch != s[i]:
return ans
ans += ch
... |
# ---------------- User Configuration Settings for speed-cam.py ---------------------------------
# Ver 8.4 speed-cam.py webcam720 Stream Variable Configuration Settings
#######################################
# speed-cam.py plugin settings
#######################################
# Calibration Settings
# =... | cal_obj_px = 310
cal_obj_mm = 4330.0
min_area = 100
x_diff_max = 200
x_diff_min = 1
track_timeout = 0.0
event_timeout = 0.4
log_data_to_csv = True
webcam = True
webcam_src = 0
webcam_width = 1280
webcam_height = 720
image_font_size = 20
image_bigger = 1 |
def busca(lista, elemento):
for i in range(len(lista)):
if lista[i] == elemento:
return i
return False
o = busca([0,7,8,5,10], 10)
print(o) | def busca(lista, elemento):
for i in range(len(lista)):
if lista[i] == elemento:
return i
return False
o = busca([0, 7, 8, 5, 10], 10)
print(o) |
gem3 = (
(79, ("ING")),
)
gem2 = (
(5, ("TH")),
(41, ("EO")),
(79, ("NG")),
(83, ("OE")),
(101, ("AE")),
(107, ("IA", "IO")),
(109, ("EA")),
)
gem = (
(2, ("F")),
(3, ("U", "V")),
(7, ("O")),
(11, ("R")),
(13, ("C", "K")),
(17, ("G")),
(19, ("W")),
(23, ("H")),
(29, ("N")),
(... | gem3 = ((79, 'ING'),)
gem2 = ((5, 'TH'), (41, 'EO'), (79, 'NG'), (83, 'OE'), (101, 'AE'), (107, ('IA', 'IO')), (109, 'EA'))
gem = ((2, 'F'), (3, ('U', 'V')), (7, 'O'), (11, 'R'), (13, ('C', 'K')), (17, 'G'), (19, 'W'), (23, 'H'), (29, 'N'), (31, 'I'), (37, 'J'), (43, 'P'), (47, 'X'), (53, ('S', 'Z')), (59, 'T'), (61, '... |
def part_1(data):
blah = {'n': (0, 1), 'ne': (1, 0), 'se': (1, -1),
's': (0, -1), 'sw': (-1, 0), 'nw': (-1, 1)}
x, y = 0, 0
for step in data.split(","):
x, y = x + blah[step][0], y + blah[step][1]
distance = (abs(x) + abs(y) + abs(-x-y)) // 2
return distance
def part_2(... | def part_1(data):
blah = {'n': (0, 1), 'ne': (1, 0), 'se': (1, -1), 's': (0, -1), 'sw': (-1, 0), 'nw': (-1, 1)}
(x, y) = (0, 0)
for step in data.split(','):
(x, y) = (x + blah[step][0], y + blah[step][1])
distance = (abs(x) + abs(y) + abs(-x - y)) // 2
return distance
def part_2(data):
... |
#!/bin/zsh
class Person:
def __init__(self, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc() | class Person:
def __init__(self, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print('Hello my name is ' + abc.name)
p1 = person('John', 36)
p1.myfunc() |
def TrimmedMean(UpCoverage):
nonzero_count = 0
for i in range(1,50):
if (UpCoverage[-i]>0):
nonzero_count += 1
total = 0
count=0
for cov in UpCoverage:
if(cov>0):
total += cov
count += 1
trimMean = 0
if nonzero_count > 0 and count >20:
#if count >20:
trimMean = total/count;
return trimMean
| def trimmed_mean(UpCoverage):
nonzero_count = 0
for i in range(1, 50):
if UpCoverage[-i] > 0:
nonzero_count += 1
total = 0
count = 0
for cov in UpCoverage:
if cov > 0:
total += cov
count += 1
trim_mean = 0
if nonzero_count > 0 and count > 2... |
N = int(input())
gradeReal = list(map(int, input().split()))
M = max(gradeReal)
gradeNew = 0
for i in gradeReal:
gradeNew += (i / M * 100)
print(gradeNew / N) | n = int(input())
grade_real = list(map(int, input().split()))
m = max(gradeReal)
grade_new = 0
for i in gradeReal:
grade_new += i / M * 100
print(gradeNew / N) |
universalSet={23,32,12,45,56,67,7,89,80,96}
subSetList=[{23,32,12,45},{32,12,45,56},{56,67,7,89},{80,96},{12,45,56,67,7,89},{7,89,80,96},{89,80,96}]
def getMinSubSetList(universalSet,subSetList):
SetDs=[[i,len(i)] for i in subSetList]
tempSet=set()
setList=[]
while(len(universalSet)!=0):
print("... | universal_set = {23, 32, 12, 45, 56, 67, 7, 89, 80, 96}
sub_set_list = [{23, 32, 12, 45}, {32, 12, 45, 56}, {56, 67, 7, 89}, {80, 96}, {12, 45, 56, 67, 7, 89}, {7, 89, 80, 96}, {89, 80, 96}]
def get_min_sub_set_list(universalSet, subSetList):
set_ds = [[i, len(i)] for i in subSetList]
temp_set = set()
set_... |
class RMCError(Exception):
def __init__(self, message):
Exception.__init__(self, message)
self.__line_number=None
def set_line_number(self, new_line_number):
self.__line_number=new_line_number
def get_line_number(self):
return self.__line_number
... | class Rmcerror(Exception):
def __init__(self, message):
Exception.__init__(self, message)
self.__line_number = None
def set_line_number(self, new_line_number):
self.__line_number = new_line_number
def get_line_number(self):
return self.__line_number
def as_nonneg_int(lite... |
TO_BIN = {'0': '0000', '1': '0001', '2': '0010', '3': '0011',
'4': '0100', '5': '0101', '6': '0110', '7': '0111',
'8': '1000', '9': '1001', 'a': '1010', 'b': '1011',
'c': '1100', 'd': '1101', 'e': '1110', 'f': '1111'}
TO_HEX = {v: k for k, v in TO_BIN.iteritems()}
def hex_to_bin(hex_stri... | to_bin = {'0': '0000', '1': '0001', '2': '0010', '3': '0011', '4': '0100', '5': '0101', '6': '0110', '7': '0111', '8': '1000', '9': '1001', 'a': '1010', 'b': '1011', 'c': '1100', 'd': '1101', 'e': '1110', 'f': '1111'}
to_hex = {v: k for (k, v) in TO_BIN.iteritems()}
def hex_to_bin(hex_string):
return ''.join((TO_B... |
def table(positionsList):
print("\n\t Tic-Tac-Toe")
print("\t~~~~~~~~~~~~~~~~~")
print("\t|| {} || {} || {} ||".format(positionsList[0], positionsList[1], positionsList[2]))
print("\t|| {} || {} || {} ||".format(positionsList[3], positionsList[4], positionsList[5]))
print("\t|| {} || {} || {} ||".... | def table(positionsList):
print('\n\t Tic-Tac-Toe')
print('\t~~~~~~~~~~~~~~~~~')
print('\t|| {} || {} || {} ||'.format(positionsList[0], positionsList[1], positionsList[2]))
print('\t|| {} || {} || {} ||'.format(positionsList[3], positionsList[4], positionsList[5]))
print('\t|| {} || {} || {} ||'.... |
def Spline(*points):
assert len(points) >= 2
return _SplineEval(points, _SplineNormal(points))
def Spline1(points, s0, sn):
assert len(points) >= 2
points = tuple(points)
s0 = float(s0)
sn = float(sn)
return _SplineEval(points, _SplineFirstDeriv(points, s0, sn))
def _IPolyMult(prod, poly):
if not pr... | def spline(*points):
assert len(points) >= 2
return __spline_eval(points, __spline_normal(points))
def spline1(points, s0, sn):
assert len(points) >= 2
points = tuple(points)
s0 = float(s0)
sn = float(sn)
return __spline_eval(points, __spline_first_deriv(points, s0, sn))
def _i_poly_mult(p... |
def find_missing_number(c):
b = max(c)
d = min(c + [0]) if min(c) == 1 else min(c)
v = set(range(d, b)) - set(c)
return list(v)[0] if v != set() else None
print(find_missing_number([1, 3, 2, 4]))
print(find_missing_number([0, 2, 3, 4, 5]))
print(find_missing_number([9, 7, 5, 8]))
| def find_missing_number(c):
b = max(c)
d = min(c + [0]) if min(c) == 1 else min(c)
v = set(range(d, b)) - set(c)
return list(v)[0] if v != set() else None
print(find_missing_number([1, 3, 2, 4]))
print(find_missing_number([0, 2, 3, 4, 5]))
print(find_missing_number([9, 7, 5, 8])) |
load("@bazel_skylib//lib:dicts.bzl", "dicts")
# load("//ocaml:providers.bzl", "CcDepsProvider")
load("//ocaml/_functions:module_naming.bzl", "file_to_lib_name")
## see: https://github.com/bazelbuild/bazel/blob/master/src/main/starlark/builtins_bzl/common/cc/cc_import.bzl
## does this still apply?
# "Library outputs ... | load('@bazel_skylib//lib:dicts.bzl', 'dicts')
load('//ocaml/_functions:module_naming.bzl', 'file_to_lib_name')
def dump_library_to_link(ctx, idx, lib):
print(' alwayslink[{i}]: {al}'.format(i=idx, al=lib.alwayslink))
flds = ['static_library', 'pic_static_library', 'interface_library', 'dynamic_library']
f... |
'''
Created on Jan 22, 2013
@author: sesuskic
'''
__all__ = ["ch_flt"]
def ch_flt(filter_k):
chflt_coe_list = {
1 : [-3, -4, 1, 15, 30, 27, -4, -55, -87, -49, 81, 271, 442, 511], # 305k BW (decim-8*3) original PRO2
# 1: [13 17 -8 -15 14 20 -27 -23... | """
Created on Jan 22, 2013
@author: sesuskic
"""
__all__ = ['ch_flt']
def ch_flt(filter_k):
chflt_coe_list = {1: [-3, -4, 1, 15, 30, 27, -4, -55, -87, -49, 81, 271, 442, 511], 2: [0, 3, 12, 22, 23, 5, -34, -72, -75, -11, 127, 304, 452, 511], 3: [4, 10, 17, 18, 5, -22, -55, -71, -47, 33, 160, 304, 417, 460], 4: [... |
N = int(input())
A = [0] + [int(a) for a in input().split()]
B = [0] + [int(a) for a in input().split()]
C = [0] + [int(a) for a in input().split()]
previous = -1
satisfaction = 0
for a in A[1:]:
satisfaction += B[a]
if previous == a-1:
satisfaction += C[a-1]
previous = a
print(satisfaction)
| n = int(input())
a = [0] + [int(a) for a in input().split()]
b = [0] + [int(a) for a in input().split()]
c = [0] + [int(a) for a in input().split()]
previous = -1
satisfaction = 0
for a in A[1:]:
satisfaction += B[a]
if previous == a - 1:
satisfaction += C[a - 1]
previous = a
print(satisfaction) |
#!/usr/bin/python
# Filename: ex_for_before.py
print('Hello')
print('Hello')
print('Hello')
print('Hello')
print('Hello')
| print('Hello')
print('Hello')
print('Hello')
print('Hello')
print('Hello') |
class Solution:
def smallestRange(self, nums: List[List[int]]) -> List[int]:
lo, hi = -100000, 100000
pq = [(lst[0], i, 1) for i, lst in enumerate(nums)]
heapq.heapify(pq)
right = max(lst[0] for lst in nums)
while len(pq) == len(nums):
mn, idx, nxt = heapq.heappop... | class Solution:
def smallest_range(self, nums: List[List[int]]) -> List[int]:
(lo, hi) = (-100000, 100000)
pq = [(lst[0], i, 1) for (i, lst) in enumerate(nums)]
heapq.heapify(pq)
right = max((lst[0] for lst in nums))
while len(pq) == len(nums):
(mn, idx, nxt) = h... |
# Copyright (C) 2021 Anthony Harrison
# SPDX-License-Identifier: MIT
VERSION: str = "0.1"
| version: str = '0.1' |
NEGATIVE_CONSTRUCTS = set([
"ain't",
"can't",
"cannot"
"don't"
"isn't"
"mustn't",
"needn't",
"neither",
"never",
"no",
"nobody",
"none",
"nothing",
"nowhere"
"shan't",
"shouldn't",
"wasn't"
"weren't",
"won't"
])
URLS = r'(https?:\/\/(?:www\.|(... | negative_constructs = set(["ain't", "can't", "cannotdon'tisn'tmustn't", "needn't", 'neither', 'never', 'no', 'nobody', 'none', 'nothing', "nowhereshan't", "shouldn't", "wasn'tweren't", "won't"])
urls = '(https?:\\/\\/(?:www\\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\\.[^\\s]{2,}|www\\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-... |
class Configuration:
port = 5672
security_mechanisms = 'PLAIN'
version_major = 0
version_minor = 9
amqp_version = (0, 0, 9, 1)
secure_response = ''
client_properties = {'client': 'amqpsfw:0.1'}
server_properties = {'server': 'amqpsfw:0.1'}
secure_challenge = 'tratata'
| class Configuration:
port = 5672
security_mechanisms = 'PLAIN'
version_major = 0
version_minor = 9
amqp_version = (0, 0, 9, 1)
secure_response = ''
client_properties = {'client': 'amqpsfw:0.1'}
server_properties = {'server': 'amqpsfw:0.1'}
secure_challenge = 'tratata' |
# -*- coding: utf-8 -*-
class MissingSender(Exception):
pass
class WrongSenderSecret(Exception):
pass
class NotAllowed(Exception):
pass
class MissingProject(Exception):
pass
class MissingAction(Exception):
pass
| class Missingsender(Exception):
pass
class Wrongsendersecret(Exception):
pass
class Notallowed(Exception):
pass
class Missingproject(Exception):
pass
class Missingaction(Exception):
pass |
# O(j +d) Time and space
def topologicalSort(jobs, deps):
# We will use a class to define the graph:
jobGraph = createJobGraph(jobs, deps)
# Helper function:
return getOrderedJobs(jobGraph)
def getOrderedJobs(jobGraph):
orderedJobs = []
# In this case, we need to take the nodes with NO prereqs
nodesWithNoP... | def topological_sort(jobs, deps):
job_graph = create_job_graph(jobs, deps)
return get_ordered_jobs(jobGraph)
def get_ordered_jobs(jobGraph):
ordered_jobs = []
nodes_with_no_prereqs = list(filter(lambda node: node.numbOfPrereqs == 0, jobGraph.nodes))
while len(nodesWithNoPrereqs):
node = nod... |
mystr = "Anupam"
newstr = ""
# Iterating the loop in backward direction.
# for char in mystr[::-1]:
for char in reversed(mystr):
newstr = newstr + char
print(newstr)
| mystr = 'Anupam'
newstr = ''
for char in reversed(mystr):
newstr = newstr + char
print(newstr) |
#
# PySNMP MIB module F3-TIMEZONE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/F3-TIMEZONE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:11:37 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (fsp150cm,) = mibBuilder.importSymbols('ADVA-MIB', 'fsp150cm')
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, value_size... |
def setup ():
size (500, 500)
smooth ()
background(255)
strokeWeight(30)
noLoop ()
def draw ():
stroke(20)
line(50*1,200,150+50*0,300)
line(50*2,200,150+50*1,300)
line(50*3,200,150+50*2,300)
| def setup():
size(500, 500)
smooth()
background(255)
stroke_weight(30)
no_loop()
def draw():
stroke(20)
line(50 * 1, 200, 150 + 50 * 0, 300)
line(50 * 2, 200, 150 + 50 * 1, 300)
line(50 * 3, 200, 150 + 50 * 2, 300) |
def validate_pin(pin):
if (len(pin) == 4 or len(pin) == 6) and pin.isdigit():
return True
else:
return False | def validate_pin(pin):
if (len(pin) == 4 or len(pin) == 6) and pin.isdigit():
return True
else:
return False |
def moveElementToEnd(array, toMove):
# Write your code here.
left = 0
right = len(array) - 1
while left < right:
if array[right] == toMove:
right -= 1
elif array[left] != toMove:
left += 1
elif array[left] == toMove:
array[left], array[right] ... | def move_element_to_end(array, toMove):
left = 0
right = len(array) - 1
while left < right:
if array[right] == toMove:
right -= 1
elif array[left] != toMove:
left += 1
elif array[left] == toMove:
(array[left], array[right]) = (array[right], array[l... |
people = [
{"name": "Harry", "house":"Gryffibdor"},
{"name": "Ron", "house":"Ravenclaw"},
{"name": "Hermione", "house":"Gryffibdor"}
]
# def f(person):
# return person["house"]
people.sort(key=lambda person: person["house"])
print(people) | people = [{'name': 'Harry', 'house': 'Gryffibdor'}, {'name': 'Ron', 'house': 'Ravenclaw'}, {'name': 'Hermione', 'house': 'Gryffibdor'}]
people.sort(key=lambda person: person['house'])
print(people) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
PIXEL_ON = '#'
PIXEL_OFF = '.'
GROWTH_PER_ITERATION = 3
ITERATIONS_PART_ONE = 2
ITERATIONS_PART_TWO = 50
def filter_to_integer(image, x, y, default_value):
# The image enhancement algorithm describes how to enhance an image by simultaneously
# converting all pixels i... | pixel_on = '#'
pixel_off = '.'
growth_per_iteration = 3
iterations_part_one = 2
iterations_part_two = 50
def filter_to_integer(image, x, y, default_value):
integer = 0
for y_local in range(y - 1, y + 2):
for x_local in range(x - 1, x + 2):
integer <<= 1
if image.get((x_local, y_... |
# FIBONACCI PROBLEM
# Write a function 'fib(N)' that takes in a number as an argument.
# The function should return the nth number of the Fibonnaci sequence.
#
# The 0th number of sequence is 0.
# The 1st number of sequence is 1.
#
# To generate the next number of the sequence,we sum the previous two.
#
# N ... | def fib_brute(N):
if N == 0:
return 0
elif N == 1:
return 1
return fib_brute(N - 1) + fib_brute(N - 2)
def fib_dp(N, cache={}):
if N in cache:
return cache[N]
if N == 0:
return 0
elif N == 1:
return 1
cache[N] = fib_dp(N - 1, cache) + fib_dp(N - 2, ca... |
#lg1009
def exp(n):
ans = 1
for i in range(2, n + 1):
ans *= i
pass
return ans
pass
n = int(input())
tot = 0
for i in range(1, n + 1):
tot += exp(i)
pass
print(tot)
| def exp(n):
ans = 1
for i in range(2, n + 1):
ans *= i
pass
return ans
pass
n = int(input())
tot = 0
for i in range(1, n + 1):
tot += exp(i)
pass
print(tot) |
'''
Problem Description:
------------------
The program takes a file name from the user and
reads the contents of the file in reverse order.
'''
print(__doc__,end="")
print('-'*25)
fileName=input('Enter file name: ')
print('-'*40)
print('Contents of text in reversed order are: ')
for line in reversed(list(o... | """
Problem Description:
------------------
The program takes a file name from the user and
reads the contents of the file in reverse order.
"""
print(__doc__, end='')
print('-' * 25)
file_name = input('Enter file name: ')
print('-' * 40)
print('Contents of text in reversed order are: ')
for line in reversed(list(open... |
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
if not list1 or not list2:
return list1 if list1 else list2
if list1.val > list2.val:
list1, list2 = list2, list1
list1.next = self.mergeTwoLists(lis... | class Solution:
def merge_two_lists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
if not list1 or not list2:
return list1 if list1 else list2
if list1.val > list2.val:
(list1, list2) = (list2, list1)
list1.next = self.mergeTwoList... |
#exercicio 97
def escreva(txt):
c = len(txt)
print ('-'*c)
print (txt)
print ('-'*c)
escreva (' Exercicio97 ')
escreva (' resolvido ') | def escreva(txt):
c = len(txt)
print('-' * c)
print(txt)
print('-' * c)
escreva(' Exercicio97 ')
escreva(' resolvido ') |
class Elemento:
dado = None
anterior = None
proximo = None
def __init__(self, dado, anterior=None, proximo=None):
self.dado = dado
self.anterior = anterior
self.proximo = proximo
class Lista:
cabeca = None
cauda = None
def __init__(self, elemento):
self.ca... | class Elemento:
dado = None
anterior = None
proximo = None
def __init__(self, dado, anterior=None, proximo=None):
self.dado = dado
self.anterior = anterior
self.proximo = proximo
class Lista:
cabeca = None
cauda = None
def __init__(self, elemento):
self.cab... |
hexN = '0x41ba0320'
print(hexN)
hexP = hexN[2:]
print (hexP[0:2])
print (hexP[2:4])
print (hexP[4:6])
print (hexP[6:8])
print(hexP)
print("{}.{}.{}.{}".format(hexP[0:2],hexP[2:4],hexP[4:6],hexP[6:8])) | hex_n = '0x41ba0320'
print(hexN)
hex_p = hexN[2:]
print(hexP[0:2])
print(hexP[2:4])
print(hexP[4:6])
print(hexP[6:8])
print(hexP)
print('{}.{}.{}.{}'.format(hexP[0:2], hexP[2:4], hexP[4:6], hexP[6:8])) |
# print('Hello, what is your name?') will type out the text in the ()
print('Hello, what is your name?')
# name = input() means that the name you typed is the answer to the question.
name = input()
# print('your name is '+name) will print the sentence plus the name you put in at name = input().
print('Your name is... | print('Hello, what is your name?')
name = input()
print('Your name is ' + name) |
n,k = map(int,input().split())
l = list(map(int,input().split()))
l.append("fake")
idx=0
ans=[l[0]]
s=set(l)
for i in range(1,n*k+1):
if i not in s:
ans.append(i)
if len(ans)==n:
print(*ans)
idx+=1
ans=[l[idx]] | (n, k) = map(int, input().split())
l = list(map(int, input().split()))
l.append('fake')
idx = 0
ans = [l[0]]
s = set(l)
for i in range(1, n * k + 1):
if i not in s:
ans.append(i)
if len(ans) == n:
print(*ans)
idx += 1
ans = [l[idx]] |
class Solution:
def maxValue(self, grid: List[List[int]]) -> int:
if not grid:
return 0
m, n = len(grid), len(grid[0])
dp = [0] * n
for idx, _ in enumerate(grid[0]):
if idx == 0:
dp[idx] = _
else:
dp[idx] = _ + dp[id... | class Solution:
def max_value(self, grid: List[List[int]]) -> int:
if not grid:
return 0
(m, n) = (len(grid), len(grid[0]))
dp = [0] * n
for (idx, _) in enumerate(grid[0]):
if idx == 0:
dp[idx] = _
else:
dp[idx] = _... |
def yes_no_query():
result = input("[y/n | yes/no]")
result = result.lower()
if result == 'y' or result == 'yes':
return True
elif result == 'n' or result == 'no':
return False
else:
print("[Please Enter yes or no]")
return yes_no_query()
def do_discussion():
# ... | def yes_no_query():
result = input('[y/n | yes/no]')
result = result.lower()
if result == 'y' or result == 'yes':
return True
elif result == 'n' or result == 'no':
return False
else:
print('[Please Enter yes or no]')
return yes_no_query()
def do_discussion():
pas... |
load(
"//rules/common:private/utils.bzl",
_action_singlejar = "action_singlejar",
)
#
# PHASE: binary_deployjar
#
# Writes the optional deploy jar that includes all of the dependencies
#
def phase_binary_deployjar(ctx, g):
main_class = None
if getattr(ctx.attr, "main_class", ""):
main_class = ... | load('//rules/common:private/utils.bzl', _action_singlejar='action_singlejar')
def phase_binary_deployjar(ctx, g):
main_class = None
if getattr(ctx.attr, 'main_class', ''):
main_class = ctx.attr.main_class
_action_singlejar(ctx, inputs=depset([ctx.outputs.jar], transitive=[g.javainfo.java_info.tran... |
def find_pattern(given):
total = len(given)
pattern = given[0]
to_compare = len(pattern)
for i in range(1, total):
for j in range(to_compare):
if given[i][j] != pattern[j]:
pattern = pattern[:j] + '?' + pattern[j + 1:]
return pattern
if __name__ == '__main__':
... | def find_pattern(given):
total = len(given)
pattern = given[0]
to_compare = len(pattern)
for i in range(1, total):
for j in range(to_compare):
if given[i][j] != pattern[j]:
pattern = pattern[:j] + '?' + pattern[j + 1:]
return pattern
if __name__ == '__main__':
... |
x = float(input())
n = int(input())
def expo(x, n):
num = 1
den = 1
sumi = 1
if n == 1:
return 1
for cnt in range(1, n):
num *= x
den *= cnt
sumi += num / den
return sumi
print("{:.3f}".format(expo(x, n) ))
| x = float(input())
n = int(input())
def expo(x, n):
num = 1
den = 1
sumi = 1
if n == 1:
return 1
for cnt in range(1, n):
num *= x
den *= cnt
sumi += num / den
return sumi
print('{:.3f}'.format(expo(x, n))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.