content stringlengths 7 1.05M |
|---|
# Python 3
testcases = int(input().strip())
for test in range(testcases):
string = input().strip()
ascii_string = [ord(c) for c in string]
length = len(string)
funny = True
for i in range(1, length):
if abs(ascii_string[i] - ascii_string[i - 1]) != abs(ascii_string[length - i - 1] - ascii_s... |
#!/usr/bin/env python
# CHATBOT PARAMETERS:
# CLIENT PARAMETERS:
CLIENTBUFFERSIZE = 64 # buffer size
# SERVER PARAMETERS:
SERVERBUFFERSIZE = 64 # buffer size
HOST = "127.0.0.1"
PORT = 9000
# wireprotocol PARAMETERS:
# (probably best not to change DELIM)
|
def maxSlidingWindow(nums, k):
ans = []
queue = []
for i, v in enumerate(nums):
# corner case, when front element is outside the window
if queue and queue[0] == i - k:
queue.pop(0)
# pop all elements smaller than new element to be added
# so after the new element... |
# init for sext package
""" Setuptools extensions that can be shared across projects
Typical use for these routines is as a git subtree merge
For example::
# Add a remote pointing to repository
git remote add nisext git://github.com/nipy/nisext.git
git fetch nisext
# Label nisext history as merged
... |
def leia_int(msg):
while True:
try:
num = int(input(msg))
except KeyboardInterrupt:
print('\nO usuario preferiu não digitar os números')
return 0
except:
print('\033[31mERRO: valor inteiro inválido\033[m')
else:
break
re... |
#!/usr/bin/env python3
#
# SPDX-FileCopyrightText: (c) 2020 Tristan Gingold <tgingold@free.fr>
# SPDX-License-Identifier: Apache-2.0
#
# 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
#
# h... |
#
# PySNMP MIB module ELTEX-MES-SWITCH-RATE-LIMITER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-MES-SWITCH-RATE-LIMITER-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:01:58 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using P... |
# -*- coding: utf-8 -*-
# @Time: 2020/3/8 21:21
# @Author: GraceKoo
# @File: 67_add-binary.py
# @Desc:https://leetcode-cn.com/problems/add-binary/
class Solution:
def addBinary(self, a: str, b: str) -> str:
if not a and not b:
return ""
if not a:
return b
if not b:
... |
"""
Parent class for all video processors. Functions effectively as an interface.
All video processor implementations must inherit this class to function.
"""
class video_processor_base:
def __init__(self):
pass
def scale_video(self, original_video, scaled_video, scale):
"""
Scales a video (original)... |
#!/usr/bin/env python
#------------------------------------------------------------------------
# NAME: event.py -
# HISTORY: -
# 2016-02-02 leerw@ornl.gov -
# Copied from
# http://www.valuedlessons.com/2008/04/events-in-python.html
# and reformatted.
# 2008-04-28 leerw@ornl.gov -
#-----------... |
def get_last_apriori_filter(connection):
# select to list
select_cursor = connection.cursor()
select_query = "select from_date,to_date,min_support,min_confidence from apriori_filter order by id desc limit 1"
select_cursor.execute(select_query)
record = select_cursor.fetchone()
select_curs... |
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
t = int(input())
for _ in range(t):
h, ... |
#prime number
# n=int(input("enter any number"))
# count=0
# i=1
# while (i<=n):
# if (n%i)==0:
# count=count+1
# i=i+1
# if (count==2):
# print("prime number")
# else:
# print("composite number")
i=0
b=0
while i<=100:
j=2
count=0
while j<=i//2:
if i%j==0:
count=count+1
break
j+=1
if count==... |
# 01234567890123456789012
# Mary had a little lamb.
# |--| |---------| GOLD
# |--| |-| |---| PRED
# || |---| INTERSECT
def merge_and_add(out, one, two):
a = max(one[0], two[0])
b = min(one[1], two[1])
if a <= b:
out.append([a, b])
def calculate_intersect(gold, pred):
out = []... |
# Dimmer Switch class
class DimmerSwitch():
def __init__(self, label):
self.label = label
self.isOn = False
self.brightness = 0
def turnOn(self):
self.isOn = True
# turn the light on at self.brightness
def turnOff(self):
self.isOn = False
# ... |
#func What we should get after the Module 1
chatbot_name = "Garik"
user_name = input("Hello! What's you name? ")
#1
phrase = input(chatbot_name + ": What do you think? ")
print("Yes, " + user_name + ", " + phrase)
#2
phrase = input(chatbot_name + ": What do you think? ")
print("Yes, " + user_name + ", " +... |
# For more info check out https://github.com/etianen/django-python3-ldap#available-settings
# TODO Read this info from enviornment variables
# The URL of the LDAP server.
LDAP_AUTH_URL = "ldap://localhost:389"
# Initiate TLS on connection.
LDAP_AUTH_USE_TLS = False
# The LDAP search base for looking up users.
LDAP_A... |
class Solution:
def canThreePartsEqualSum(self, A: List[int]) -> bool:
s = sum(A)
if s % 3 != 0:
return False
avg = s // 3
cnt = 0
s = 0
for i in A:
s += i
if s == avg:
cnt += 1
s = ... |
# -*- coding: utf-8 -*-
"""
Solution to Project Euler problem 4
Author: Jaime Liew
https://github.com/jaimeliew1/Project_Euler_Solutions
"""
def isPalindrome(x):
# Returns true if the integer, x is palindromic
x = str(x)
n = len(x)
if n%2 == 0:
left, right = x[:n//2], x[n//2:]
else:
... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if not hea... |
mis_juegos = 50
juegos_xbox = 25
juegos_ordenador = 25
horas_que_he_jugado_de_cada_juego_en_un_mes = 120
minutos_jugados_al_día_de_cada_juego = 5
print("Hola, una pregunta, ¿Cuantos juegos tienes?.")
print(f"Eso es facil yo tengo {mis_juegos}.")
print("¿¡Tantos!?")
print(f"No son tantos solo juego {horas_que_he_jugado... |
new = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
def to_base_64(string):
res=""
for i in string:
res+=binary(i)
if len(res)%6!=0: res=res+"0"*(6-len(res)%6)
result=""
for i in range(0,len(res),6):
result+=new[int(res[i:i+6], 2)]
return result
def from_base... |
class HostName(basestring):
"""
Host name
"""
@staticmethod
def get_api_name():
return "host-name"
|
inp = open("input/day6.txt", "r")
prvotne_ribe = [int(x) for x in inp.readline().split(",")]
inp.close()
prvotna_populacija = [0 for _ in range(9)]
for riba in prvotne_ribe:
prvotna_populacija[riba] += 1
def zivljenje(N):
populacija = prvotna_populacija
for _ in range(N):
nova_populacija = [0 for ... |
class MockLROPoller(object):
def result(self, timeout: None):
pass
class MockVirtualMachineScaleSetVMsOperations(object):
def begin_power_off(self, resource_group_name, scale_set_name, instance_id):
return MockLROPoller()
def begin_delete(self, resource_group_name, scale_set_name, instanc... |
"""
一条包含字母 A-Z 的消息通过以下方式进行了编码:
'A' -> 1
'B' -> 2
...
'Z' -> 26
给定一个只包含数字的非空字符串,请计算解码方法的总数。
示例 1:
输入: "12"
输出: 2
解释: 它可以解码为 "AB"(1 2)或者 "L"(12)。
示例 2:
输入: "226"
输出: 3
解释: 它可以解码为 "BZ" (2 26), "VF" (22 6), 或者 "BBF" (2 2 6)
"""
class Solution:
def numDecodings(self, s: str) -> int:
dp = [0] * len(s)
... |
# -*- coding: utf-8 -*-
"""
This file is adopted from Chainer official implementation with small
modifications.
https://github.com/chainer/chainer/blob/v4.2.0/chainer/training/triggers/minmax_value_trigger.py
"""
class BestValueTrigger(object):
"""Trigger invoked when specific value becomes best. This will run e... |
class VerificationProfile:
"""This class encapsulates a user profile."""
_PROFILE_ID = 'verificationProfileId'
_LOCALE = 'locale'
_ENROLLMENTS_COUNT = 'enrollmentsCount'
_REMAINING_ENROLLMENTS_COUNT = 'remainingEnrollmentsCount'
_CREATED_DATE_TIME = 'createdDateTime'
_LAST_ACTION_DATE_TIME ... |
"""
[STEPIK]
Python: основы и применение https://stepik.org/512
02_05_01 Работа с функциями: functool и лямбда функции
"""
"""
Лямбда функции предоставляют нам удобный способ создать функцию «прямо на месте».
Но иногда, когда нужно создавать много однотипных лямбда функций, еще удобнее будет создать функцию,
которая ... |
def assert_event_handler(expected_event, mocked_handler):
assert mocked_handler.call_count == 1
actual_event = mocked_handler.call_args[0][0]
assert actual_event == expected_event
|
class RoleDisabledException(Exception):
def __init__(self):
self.name = "Your role is disable."
|
def run_pg_GB(
n_iter,
min_timesteps_per_batch,
max_path_length,
animate,
logdir,
nn_baseline,
seed,
n_layers,
output_activation,
size,
save_models,
save_best_model,
run_model_only,
script_optimizing_dir... |
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
pass
def insert(self):
pass
def level_order_traversal(self):
pass
def delete(self):
pass
|
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# 首尾交换法
def reverse(list: List[int], start: int, end: int) -> None:
while start < end:
t = list[start]
... |
'''
Assignment 1
'''
#Observing the output of the following commands
emp_number = 1233
print("Employee Number",emp_number)
emp_salary = 16745.50
emp_name = "Jerry Squaris"
print("Employee Salary and Name:",emp_salary, emp_name)
emp_salary = 23450.34
print("Updated Employee Salary:",emp_salary)
|
MIN_DRIVING_AGE = 18
def allowed_driving(name, age):
"""Print '{name} is allowed to drive' or '{name} is not allowed to drive'
checking the passed in age against the MIN_DRIVING_AGE constant"""
if age >= MIN_DRIVING_AGE:
print(f'{name} is allowed to drive')
else:
print(f'{name} is n... |
"""A Task is a unit of organization in Busy"""
def create_task():
pass
class Task:
"""
A Task keeps track of a thing that has to get done. "Things" are very
complex, Busy calls them tasks. Some Tasks cannot be started until other
Tasks are completed, that task is "waiting on" those other tasks, s... |
"""4-9. Cube Comprehension: Use a list comprehension to generate a list of the
first 10 cubes."""
cubes = [num**3 for num in range(1,11)]
for cube in cubes:
print(cube) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Imports, Definitionen von Klassen, Funktionen und Variablen ab hier.
"""
text = "Hallo Welt!"
# Hauptschleife, wenn direkt aufgerufen, ab hier
if __name__ == '__main__':
print(text)
|
"""
http://community.topcoder.com/stat?c=problem_statement&pm=1675
Single Round Match 145 Round 1 - Division II, Level Two
"""
class ExerciseMachine:
def getPercentages(self, times):
h, m, s = map(int, times.split(':'))
seconds = h * 3600 + m * 60 + s
for i in [100, 50, 25, 20, 10, 5, 4, ... |
with open("output.txt") as output:
data = output.read()
produced = {}
is_producing = set()
consumed = {}
readies = 0
for line in data.splitlines():
if ("JMSBasedValueInput" in line and "produced" in line) or "to low" in line:
for robot in (part.split("]")[0][6:] for part in line.split("[")[2:]... |
H, W, Y, X = map(int, input().split())
X -= 1
Y -= 1
field = []
for i in range(H):
field.append(input())
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
ans = 1
for i in range(4):
nx = X + dx[i]
ny = Y + dy[i]
while 0 <= nx < W and 0 <= ny < H and field[ny][nx] == '.':
nx += dx[i]
ny += dy[i]
... |
#!/usr/bin/env python
def func1():
print("Hello World")
class Bogus:
my_var1 = ""
my_var2 = ""
my_var3 = ""
def hello(self):
print("Hello " + self.my_var1 + ", " + self.my_var2 + " and " + self.my_var3)
def not_hello(self):
print("Bye " + self.my_var1 + ", " + self.my_var2 +... |
def foo():
return bbb
aaa = foo() and ccc |
#Print 1 to 100 ussing a loop
num = 0
while (num < 100):
num += 1
print(num)
|
# 1. Generate ECDFs
x_high, y_high = bootcamp_utils.ecdf(xa_high)
x_low, y_low = bootcamp_utils.ecdf(xa_low)
# 2. Make smooth curves
x = np.linspace(1600, 2500, 400)
cdf_high = scipy.stats.norm.cdf(x, loc=np.mean(xa_high), scale=np.std(xa_high))
cdf_low = scipy.stats.norm.cdf(x, loc=np.mean(xa_low), scale=np.std(xa_lo... |
# PROBLEM 1
# Kullanıcıdan aldığınız bir sayının mükemmel olup olmadığını bulmaya çalışın.
#
# Bir sayının kendi hariç bölenlerinin toplamı kendine eşitse bu sayıya
# "mükemmel sayı" denir. Örnek olarak, 6 mükemmel bir sayıdır. (1 + 2 + 3 = 6)
num = int(input("Bir sayı giriniz: "))
temp = 0
i = 1
while i < num:
i... |
def generate_table():
alphabet = 'ABCDEFGHIKLMNOPQRSTUVWXYZ'
tabel = [[0] * 5 for row in range(5)]
pos = 0
for x in range(5):
for y in range(5):
tabel[x][y] = alphabet[pos]
pos += 1
return tabel
def getStr(x, format='%02s'):
return ''.join(format % i for i ... |
async def calc_cmd(bot, discord, message, botconfig, os, platform, datetime, one_result, localization, numexpr, prefix, embed_color):
args = message.content.split();
err = ""
no_args = discord.Embed(title=localization[1][9][0], description=str(localization[1][9][4]).format(prefix), color=botco... |
class CancellationException(Exception):
"""Raised when command was cancelled from the CloudShell"""
def __init__(self, message, data):
"""
:param str message:
:param dict data:
:return:
"""
# Call the base class constructor with the parameters it needs
su... |
def f():
(some_global): int
print(some_global)
|
#!/usr/bin/env python3
n = int(input())
power = 7
i = 0
while i < n:
print(power)
power = power + 7
i = i + 1
|
class Solution:
def racecar(self, target):
"""
:type target: int
:rtype: int
"""
q, cnt, used = [(0, 1)], 0, {(0, 1)}
while q:
new = []
for pos, speed in q:
if pos == target:
return cnt
elif p... |
"""
Numerically Solve the model to estimate parameters
"""
class CoronaVIRES_2(object):
"""
SERV model # 2 (_Known_Vaccination ):
Discrete approximations to Differential Equations which donot use past states of variables
Vaccination taken from data
"""
def __init__(self,N, new_vaccinati... |
def Wizard(thoughts, eyes, eye, tongue):
return f"""
{thoughts}
{thoughts}
_____
.\'* *.\'
___/_*_(_
/ _______ \\
_\\_)/___\\(_/_
/ _((\\- -/))_ \\
\\ \\())(-)(()/ /
' \\(((()))/ \'
... |
def flatten(items):
""" Flatten nested list of any recursion. """
for i in items:
if isinstance(i, list):
for ii in flatten(i):
yield ii
else:
yield i
|
ANNOTATION_NAME = "service-meta-Name"
ANNOTATION_DESCRIPTION = "service-meta-Description"
ANNOTATION_DOCS_LINK = "service-meta-DocsLink"
ANNOTATION_ENVIRONMENT = "service-meta-Environment"
ANNOTATION_FRIENDLY_NAME = "service-meta-FriendlyName"
ANNOTATION_ICON_URL = "service-meta-IconURL"
ANNOTATION_MAJOR_VERSION = "ser... |
try:
fname = open("a.txt","r")
fname.write("hello world")
except:
print("Cannot write the contents to the file")
finally:
f.close()
print("File closed")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 30 18:36:15 2020
@author: daniel
"""
def uromano(n):
return {
1:'I',
2:'II',
3:'III',
4:'IV',
5:'V',
6:'VI',
7:'VII',
8:'VIII',
9:'IX'}.get(n,'no hay valor')
def udromano(n... |
# Livro favorito: Escreva uma função chamada favorite_book() que aceite um parâmetro title. A função deve
# exibir uma mensagem como Um dos meus livros favoritos é Alice no País das Maravilhas. Chame a função e
# não se esqueça de incluir o título do livro como argumento na chamada da função:
def favorite_book(title, ... |
#
# PySNMP MIB module CISCO-SWITCH-RATE-LIMITER-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-SWITCH-RATE-LIMITER-CAPABILITY
# Produced by pysmi-0.3.4 at Wed May 1 12:13:38 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# U... |
'''
520. Detect Capital
Given a word, you need to judge whether the usage of capitals in it is right or not.
We define the usage of capitals in a word to be right when one of the following cases holds:
All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Only... |
def quickSort(arr, begin, end):
if begin < end:
p = partition(arr, begin, end)
quickSort(arr, begin, p - 1)
quickSort(arr, p + 1, end)
def partition(arr, begin, end):
pivot = (begin + end) // 2
L = begin
R = end
while L < R:
while arr[L] < arr[pivot] and L < R:
... |
#!/usr/bin/python3
# 2019-1-30
# Daniel Nicolas Gisolfi
lexemes = {
'TYPE': {
'priority': 0,
'pattern': r'^(int|string|boolean)$',
},
'BOOLEAN': {
'priority': 0,
'pattern':r'^(true|false)$',
},
'BOOL_OP':{
'priority': 2,
'pattern':r'^(!=|==)$',
},... |
# -*- coding: utf-8 -*-
def main():
low, high = list(map(int, input().split()))
n = int(input())
a = [int(input()) for _ in range(n)]
for ai in a:
if ai > high:
print(-1)
else:
print(max(0, low - ai))
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
def comp_mass_magnets(self):
"""Compute the mass of the hole magnets
Parameters
----------
self : HoleM57
A HoleM57 object
Returns
-------
Mmag: float
mass of the 2 Magnets [kg]
"""
M = 0
# magnet_0 and magnet_1 can have different mat... |
# Test file for api version checker
class SomeClient():
def __init__(self, endpoint, credential, **kwargs):
"""
:param str endpoint: Something.
:param credential: Something.
:type credential: TokenCredential.
"""
pass
|
'''A program to find the sum of all values in a dictionary!!'''
print("Program to find sum of all items in dictionary!!")
def toFindSum(myD):
s = 0
for i in myD.values():
s= s + i
print('Sum:{}'.format(s))
d = dict()
length = int(input('Enter the number of {key:value} pairs\n'))
for i in range(l... |
def peakFinding(arr):
"""
The motive of this algorithm is find the first peak in the array
and show its index.
"""
if len(arr) == 1:
return [0]
elif len(arr) == 2:
return [0] if arr[0] > arr[1] else [1]
else:
if arr[0] > arr[1]:
return [0]
elif ... |
class Node:
def __init__(self, id, neighbours):
self.id = id
self.neighbours = neighbours
self.visited = False
class Path:
def __init__(self, neighbours):
self.neighbours = neighbours
def dfs_recursive(node):
print('Node ', node.id)
node.visited = True
for next i... |
'''https: // www.geeksforgeeks.org/longest-palindromic-subsequence-dp-12/
if the given sequence is “BBABCBCAB”, then the output should be 7 as “BABCBAB” is the longest palindromic subsequence in it.
“BBBBB” and “BBCBB” are also palindromic subsequences of the given sequence, but not the longest ones.
The naive solutio... |
def get_data(fieldname, entry):
field = fieldname.split(".")
rslt = entry
for data in field:
if rslt[data]:
rslt = rslt[data]
return rslt
def cnvt_grpby_to_nested_dict(grpby, entries):
"""
Create a dict of dict of grpby arguments with sorted
entries at the end of nested... |
# 7. Lists
freinds = ["Pythobit","Boy"]
print(freinds[0]) # Output - Pythobit
print(len(freinds)) # Output - 2
freinds = [["Pythobit",20],["Boy",21]]
print(freinds[0][0]) # Output - Pythobit
print(freinds[1][1]) # Output - 21
freinds = ["Pythobit","Boy"]
freinds.append("Pythobit boy")
print(freinds) ... |
"""
While: Estructura repetitiva que nos permite realizar múltiples iteraciones
basándonos en el resultado de una expresión lógica que puede
tener como resultado un valor True o False.
"""
indice = 1
while indice < 10:
print("Valor actual: {0}".format(indice))
indice += 1
print("Hemos terminado el bucle whil... |
filename = '/Users/andrew.meyers/Documents/andy/AdventOfCode2021/Day10/input.txt'
def parseInput(filename):
lines = []
with open(filename) as f:
for line in f:
lines.append(line)
return lines
def getPoints(line):
map = {')': 3, ']': 57, '}': 1197, '>': 25137}
stack = []
... |
my_dict = {
"key":"value",
"key2":"value2"
}
# mydictの識別子「key」の値を呼び出してみよう!
print(my_dict["key"])
|
def k_wood(gb, so, x):
"""
Thermal conductivity of wood based on moisture content, volumetric
shrinkage, and basic specific gravity
.. math:: k = G_x (B + C x) + A
where :math:`k` is thermal conductivity [W/(mK)] of wood, :math:`G_x` is
specific gravity [-] based on volume at moisture content... |
# =============================================================================
# Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/
# FileName: 11052.py
# Description: UVa Online Judge - 11052
# =============================================================================
while True:... |
# CAIXA ELETRÔNICO
cinquenta = vinte = dez = um = 0
print('=' * 40)
print('{:^40}'.format('BANCO CEV'))
print('=' * 40)
while True:
value = int(input('Qual valor você quer sacar? '))
cinquenta = value // 50
vinte = (value % 50) // 20
dez = ((value % 50) % 20) // 10
um = (((value % 50) % 20) % 10)... |
def largest_exponential(file):
text_file = open(file, "r")
lines = text_file.read().splitlines()
greatest = 0
count = 0
split_list = []
for elem in lines:
seperated = elem.split(',')
split_list.append(seperated)
for i in range(0, len(split_list)):
... |
items = ["Clothes", "phones", "laptops", "Chocolates"]
if __name__ == "__main__":
while True:
try:
for index in range(0,len(items)):
print(f"{index} ")
option = int(input("Enter the number of your choice to get gift: "))
print(f"You have choosen {items[o... |
"""json format (bim file)
"name": "",
"description": "",
"columns": [...],
"partitions": [...],
"measures": [...],
"annotations": [...]
"""
def get_measures(data: dict):
print()
print(79 * '*')
print(f"Getting measures at {(data['model']['name'])} cube")
print(79 * '*')
li... |
"""
Convenience functions, etc for tests
"""
def show_and_wait(qtbot, *widgets, timeout=60000, raising=False):
"""
Helper that shows widgets and waits until they are closed (or timeout ms)
"""
for w in widgets:
w.show()
def are_closed():
for w in widgets:
if w.isVisibl... |
class Solution(object):
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
path = path.split("/")
stack = []
for p in path:
if p in ["", "."]:
continue
if p == "..":
if stack:
... |
'''
Create a function called mult that has two parameters, the first is required and should be an integer,
the second is an optional parameter that can either be a number or a string but whose default is 6.
The function should return the first parameter multiplied by the second.
'''
def mult(i, x = 6):
return i * x... |
# accept an integer and print the digits in reverse
n = int(input("Enter a positive integer: "))
print()
while (n!=0):
digit = n % 10 # extract the last digit
print(digit) # print the last digit
n = n // 10 # remove the last digit
'''
123 / 10
q = 12
r = 3
456 / 10
q = 45
r = 6
q = dividend // divis... |
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2016, 2017
class DataAlreadyExistsError(RuntimeError):
def __init__(self, label):
self.message = str("Data with label '%s' already exists and cannot be added" % (label))
def get_patient_id(d):
return d['patient']['identifier']
def get_index_... |
#
# @lc app=leetcode id=202 lang=python3
#
# [202] Happy Number
#
# @lc code=start
# class Solution:
# def isHappy(self, n: int):
# appeared = {}
# while True:
# s = 0
# while n > 0:
# s += (n % 10) * (n % 10)
# n = n//10
# if s ==... |
# Clase 12. Curso Píldoras Informáticas.
# Control de Flujo. Condicionales 3.
# Switch. Se usa cuando se evalúan muchas decisiones concatenadas. No es muy útil en Python, por lo que no está.
# Motivo: En Python se pueden concatenar operadores de comparación en condicionales.
Edad = 8
if 0 < Edad < 100:
... |
#r e razao de quantos em quantos vai pular
#pa e a subtracao da razao com o seu anterior, ex razao é 2 ,
a1= int(input('Indique o primeiro termo da PA: '))
r = int(input('Indique a razão da PA: '))
an = a1 + (10-1)*r #esse -1 é da formula
#an = 2+9*2=20
while a1 <= an:
print(a1, end=' ')
a1 += r
print('FIM')
... |
# capture discord_id to validate
@bot.command(pass_context=True)
async def example(ctx):
get_discord_id = ctx.message.author.id
user = await bot.get_user_info(get_discord_id)
print(get_discord_id)
# get username and unique ID from discord user that uses the command
@bot.command(pass_context=True)
async def... |
# -*- coding: utf-8 -*-
"""src module init.
import src.poke_env as poke_env
import cross_evaluate_random_players as cross_evaluate_random_players
import max_damage_player as max_damage_player
#import rl_with_open_ai_gym_wrapper as rl_with_open_ai_gym_wrapper
import snivy_agent as snivy_agent
import sweeper a... |
values = [23,52,59,37,48]
sum = 0
length = 10
for value in values:
sum+=value
length+=1
print("Total sum:"+str(sum)+"-Average: " + str(sum/length))
|
class Solution:
# kind of dynamic programming?
def fib(self, N):
prepared_numbers = [0, 1, 1, 2, 3, 5, 8, 13]
if N <= len(prepared_numbers) - 1:
return prepared_numbers[N]
else:
for i in range(N - len(prepared_numbers) + 1):
prepared_numbers.append... |
"""
Do Not Edit the code here unless you know
what you are doing, This is a simple tokenizer
that can form tokens of whole sentences
thereby removing any need for NLTK
Scipy or any other 3rd party Library for
tokenization purposes.
- Moses
"""
abbreviations = {'dr.': 'doctor', 'mr.': 'mister', 'bro.': 'brother', 'bro'... |
try:
num = int(input('Enter a number: '))
except Exception:
print('Some input error')
def convert_to_binary(num):
if num > 1:
convert_to_binary(num // 2)
print(num % 2, end = '')
print('Binary: ', end = '')
convert_to_binary(num) |
valores = list()
while True:
valor = int(input('Digite um valor: '))
if valor not in valores:
valores.append(valor)
print('Valor adicionado com sucesso!')
else:
print('Não vou adicionar o numero ja existe')
cont = ' '
while cont not in 'NS':
cont = str(input('Quer c... |
# from .disalexi import Image
# from .landsat import Landsat
__version__ = "0.0.3"
|
#格式1
opcode_one={"FIX":"C4","FLOAT":"C0","HIO":"F4","NORM":"C8","SIO":"F0","TIO":"F8"}
#格式2
opcode_two={"ADDR":"90","CLEAR":"B4","COMPR":"A0","DIVR":"9C","MULR":"98","RMO":"AC","SHIFTL":"A4",
"SHIFTR":"A8","SUBR":"94","SVC":"B0","TIXR":"B8"}
#格式3/4
opcode_three_four={"ADD":"18","ADDF":"58","AND":"40","... |
# Definir excepciones en Python
class Err(Exception):
def __init__(self,valor):
print("Fue el error por",valor)
try:
raise Err(4)
except Err:
print("Error escrito:")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.