content stringlengths 7 1.05M |
|---|
"""Wrapper Exceptions"""
class ApiRequestFailed(Exception):
"""
Denotes a failure interacting with the API, such as the HTTP 4xx Series
"""
pass
class ApiRequest400(ApiRequestFailed):
"""
Denotes a HTTP 400 error while interacting with the API
"""
pass
class ImportDeleteError(ApiRequ... |
# write program reading an integer from standard input - a
# printing sum of squares of natural numbers smaller than a
# for example, for a=4, result = 1*1 + 2*2 + 3*3 = 14
a = int(input("pass a - "))
element = 1
result = 0
while element < a:
result = result + element * element
element = element + 1
print("... |
#Ex1
n1 = input("Nome: ")
i1 = int(input("Idade: "))
n2 = input("Nome: ")
i2 = int(input("Idade: "))
if i1 > i2:
print(f"{n1} é mais velho que {n2}.")
elif i2 > i1:
print(f"{n2} é mais velho que {n1}.")
else:
print(f"{n1} e {n2} possuem a mesma idade.")
#Ex2
h = float(input("Hectares: "))
p = float(input("P... |
# implement strip() to remove the white spaces in the head and tail of a string.
def strip(s):
while len(s) != 0 and (s[0] == ' ' or s[-1] == ' '):
s = s[1:] if s[0] == ' ' else s
s = s[:-1] if s[-1] == ' ' else s
return s
if __name__ == "__main__":
if strip('hello ') != 'hello':
... |
a = [1,2,3,4,5]
k =2
del a[0]
for i in range(0,len(a)):
print(a[i])
|
# Copyright (c) 2018 Lotus Load
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribu... |
"""
Exceptions
----------
"""
class FactoryException(Exception):
"""General exception for a factory being not able to produce a penalty model."""
class ImpossiblePenaltyModel(FactoryException):
"""PenaltyModel is impossible to build."""
class MissingPenaltyModel(FactoryException):
"""PenaltyModel is m... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# import pprint
# eng = r"<ffx:amp_2> Don't think it was all in vain... You saved us all. <ffx:wonder>And Kirill... I'll give him this watch and make sure he gets out of this hellhole. <ffx:neutral>You have my word."
# ru = r"Не думай, что все было зря... Ты всех на... |
# working-with-Data-structure
#union
def union(set1,set2):
return set(set1)&(set2)
# driver code
Set1={0,2,3,4,5,6,8}
Set2={1,2,3,4,5}
Print(union(set1,set2))
#intersection
def intersection(set1,set2):
return set(set1)&(set2)
#driver code
Set1={0,2,4,6,8}
Set2={1,2,4,4,5}
Print(intersection(set1,set2))
#diffe... |
class Qint(int):
def __init__(self, num):
self.qkey = None
self.parent = None
self.parental_id = None
self.name = None
self._qint = True
|
def testDoc():
"""
Test __doc__
"""
pass
print(abs.__doc__)
print(help(abs))
print(int.__doc__)
print(testDoc.__doc__)
print(help(testDoc))
|
#!/usr/bin/env python
# Analyse des accidents corporels de la circulation a partir des fichiers csv open data
# - telecharger les fichiers csv depuis :
# https://www.data.gouv.fr/en/datasets/bases-de-donnees-annuelles-des-accidents-corporels-de-la-circulation-routiere-annees-de-2005-a-2019/
# - changer la commune et l... |
# n = int(input('Enter the number of time you want to display Hello World!'))
# i = 0
##While Loop
# while i < n :
# print('Hello World\n')
# x += 1
n = input('Enter a number: ')
#Check if the input is empty
if n == "":
print('Nothing to display')
else:
#For Loop
for i in range(int(n)):
print(... |
"""
Datos de entrada
nombre-->nom-->string
monto_comra-->mc-->float
Datos de salida
nombre-->nom-->string
monto_compra-->mp-->float
monto_pagar-->mg-->float
descuento-->de-->float
"""
#Entrada
nom=str(input("Ingrese nombre del cliente: "))
mc=float(input("Ingrese el monto de compra: "))
#Caja negra
if(mc<50000):
mg... |
class MenuItem:
pass
# Buat instance untuk class MenuItem
menu_item1 = MenuItem()
|
class Vertice:
def __init__(self,rotulo):
self.rotulo = rotulo # por exemplo "A"
self.visitado = False
# def visitado(self):
# self.visitado = True
def igualA(self,r):
return r == self.rotulo
def foiVisitado(self):
... |
# Copyright 2020 Rubrik, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distri... |
"""This module demonstrates usage of if-else statements, while loop and break."""
def calculate_grade(grade):
"""Function that calculates final grades based on points earned."""
if grade >= 90:
if grade == 100:
return 'A+'
return 'A'
if grade >= 80:
return 'B'
if gra... |
"""
Write a Python program to get variable unique identification number or string.
"""
x = 100
print(format(id(x), "x")) |
class FederationClientServiceVariables:
def __init__(self):
self.FederationClientServiceStatus = ''
self.FederationClientServicePort = 9000
self.FederationClientServiceIP = None |
class Format:
def skip(self, line):
False
def before(self, line):
return s, None
def after(self, line, data):
return s
class fastText(Format):
LABEL_PREFIX = '__label__'
def before(self, line):
labels = []
_ = []
for w in line.split(' '):
... |
print('\033[32mCalcule a media de suas notas! \033[m')
nota1 = float(input('Digite sua primeira nota: '))
nota2 = float(input('Digite sua segunda nota: '))
media = (nota1 + nota2) / 2
if media < 5.0:
print(f'Sua média foi de {media:.1f}! Que pena, você foi reprovado! ')
elif media>=5.0 and media<=6.9:
print(f'S... |
# Time complexity: O(n)
# Approach: Backtracking. Similar to DP 2D array solution.
class Solution:
def findIp(self, s, index, i, tmp, ans):
if i==4:
if index >= len(s):
ans.append(tmp[1:])
return
if index >= len(s):
return
if s[index]=='0'... |
# s = '??????'
# print(s.count("?"))
# print(s.count("?"))
# a = 5
# b = 2
# print(a/b)
# import re
#
# def Find(string):
# url = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', string)
# # url = regex.findall(string)
# return url
#
# string = 'Runoob 的网页地址为:https://www.runoob.com,Google 的网页地址为:http... |
# Just to implement while loop
answer = 'no'
while answer != 'yes':
answer = input( 'Are you done?' )
print( 'Finally Exited.' );
|
base_tree = [{
'url_delete': 'http://example.com/adminpages/delete/id/1',
'list_of_pk': ('["id", 1]', ),
'id': 1,
'label': u'Hello Traversal World!',
'url_update': 'http://example.com/adminpages/update/id/1',
'children': [{
'url_delete': 'http://example.com/adminpages/delete/id/2',
... |
# 非常耗费时间,待改进
class Solution:
def sortArrayByParityII(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
odd=[]
odd_not=[]
for ele in A:
if ele%2 == 0:
odd_not.append(ele)
else:
odd.append(ele)
... |
# change this code
number = 16
second_number = 0
first_array = [1,2,3]
second_array = [1,2]
if number > 15:
print("1")
if first_array:
print("2")
if len(second_array) == 2:
print("3")
if len(first_array) + len(second_array) == 5:
print("4")
if first_array and first_array[0] == 1:
print("5")
if... |
@metadata_reactor
def add_backup_key(metadata):
return {
'users': {
'root': {
'authorized_keys': {
'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDM70gDI1cuIKu15VAEYnlWMFi3zGPf6shtQCzrHBv1nOOkfPdXlXACC4H5+MiTV5foAIA8PUaqOV9gow1w639TnWDL2DwPJ5RsT+P5g4eWszW5xQPo0zAKuvlT... |
"""
CCC '01 J1 - Dressing Up
Find this problem at:
https://dmoj.ca/problem/ccc01j1
"""
height = int(input())
# These are the two parts of the bow tie
for half in (range(1, height, 2), range(height, -1, -2)):
# Print each line accordingly
for i in half:
print('*' * i + ' ' * ((height-i)*2) + '*' * i)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
It can be verified that the sum of the numbers on the ... |
print('Cadastro de Alunos')
cadastro = input('Deseja cadastrar um aluno?(S/N)')
cadastro = cadastro.upper()
cadastro = cadastro.strip()
listaAlunos = []
while(cadastro == 'S'):
aluno = []
nome = input('Qual nome do aluno? ')
nome = nome.capitalize()
nome = nome.strip()
aluno.append(nome)
matricu... |
# This file mainly exists to allow python setup.py test to work.
# flake8: noqa
def runtests():
pass
if __name__ == '__main__':
runtests()
|
line = open("day10.txt", "r").readline()
def day10(iterate, sequence):
for i in range(iterate):
concat = ""
first = True
second = False
sameNumberCounter = 0
secondNum = 0
numCounter = 0
for num in sequence:
numCounter += 1
if second ... |
"""Base class for writing hooks."""
class BaseHook(object):
"""Base class for all hooks."""
KEY = 'hook'
NAME = 'Hook'
def __init__(self, extension):
self.extension = extension
@property
def pod(self):
"""Reference to the pod."""
return self.extension.pod
# pyli... |
# -*- coding: utf-8 -*-
a, b, c, d = input().split(' ')
a = int(a)
b = int(b)
c = int(c)
d = int(d)
if b > c and d > a and c + d > a + b and c > 0 and d > 0 and a % 2 == 0:
print('Valores aceitos')
else:
print('Valores não aceitos')
# coment
|
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/1266/B
# 相对的面和为7,所以中间骰子可见的面=14; 骰子塔可见的面=14*k+(1-6)
n = int(input())
l = list(map(int,input().split()))
[print('YES' if i>14 and (i-1)%14<6 else 'NO') for i in l]
|
# Copyright 2015-2021 Mathieu Bernard
#
# This file is part of phonemizer: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# Phonemizer is distributed ... |
a = "python"
print(a*2)
try:
print(a[-10])
except IndexError as e:
print("인덱스 범위를 초과 했습니다.")
print(e)
print(a[0:4])
print(a[1:-2])
# -10은 hi뒤로 10칸
print("%-10sjane." % "hi")
b = "Python is best choice."
print(b.find("b"))
print(b.find("B"))
try:
print(b.index("B"))
except ValueError as e:
prin... |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 25 20:03:57 2019
@Project : Python Memo
@File : fileop.py
@Function : 文件操作
@Author : yehx
@E-mail : yehxian@163.com
"""
#保存到记事本
with open("test.txt","w") as f:
f.write("string")
#读取记事本内容
with open("test.txt", "r") as f:
while True... |
#
# PySNMP MIB module ALCATEL-IND1-IPMS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALCATEL-IND1-IPMS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:02:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... |
num = int(input( "Digite um valor de 0 a 9999: "))
num1 = str(num)
num2 = num1.zfill(4)
print('Unidade: {}'.format(num2[3]))
print('Dezena: {}'.format(num2[2]))
print('Centena: {}'.format(num2[1]))
print('Milhar: {}'.format(num2[0]))
|
builder_layers = {
# P-CAD ASCII layer types:
# Signal, Plane, NonSignal
-1: "null", # LT_UNDEFINED
0: "Signal", # LT_SIGNAL
1: "Plane", # LT_POWER
2: "NonSignal", # LT_MIXED
3: "Plane" # LT_JUMPER
}
builder_padshapes = {
# P-CAD ASCII padshape types:
# padViaShapeT... |
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
temp = str.strip()
if not temp:
return 0
negative = False
resint = 0
head = temp[0]
if head == "-":
negative = True
elif h... |
def calc_no(val):
temp = val
s = 0
while temp > 0:
s += temp%10
temp //= 10
return not(val%s)
row = int(input())
arr = [] # storing input values
for i in range(row):
arr.append(list(map(int,input().split())))
bool_tab = [] # storing their resp boolean value if it is divisible by t... |
# 最简单的输出
print('Hello World!')
# 输出表达式值
print(20+10)
# print函数支持多个参数,遇到逗号输出空格。
print('Nice','to','meet','you!',999)
# 字符串连接
print('a'+'b')
# 格式化输出
print('100 + 200 =',100+200) |
def weather_conditions(temp):
if temp > 7:
print("Warm")
else:
print("Cold")
x = int(input("Enter a temparature"))
weather_conditions(x)
|
T = int(input())
for kase in range(1, T + 1):
n = int(input())
[input() for i in range(0, n + 1)]
if n & 1:
print(f'Case #{kase}: 1\n0.0')
else:
print(f'Case #{kase}: 0') |
# https://app.codility.com/demo/results/trainingUJUBFH-2H3/
def solution(X, A):
"""
DINAKAR
Clue -> Find the earliest time when the frog can jump to the other side of the river. The frog can cross only when leaves appear at every position across the river from 1 to X
[1, 3, 1, 4, 2, 3, 5, 4]
X ... |
# Atharv Kolhar
# Python Bytes
# https://www.youtube.com/channel/UC71nPTNDEG7oyusXTifvB7g?sub_confirmation=1
"""
Tuple
"""
# Declaration
var_tuple = (1, 2, 3)
print(var_tuple)
print(type(var_tuple))
var_tuple_1 = 1, 2, 3
print(var_tuple_1)
print(type(var_tuple_1))
# Function for Tuples
# Counting the element repea... |
school_class = {}
while True:
name = input("Enter the student's name: ")
if name == '':
break
score = int(input("Enter the student's score (0-10): "))
if score not in range(0, 11):
break
if name in school_class:
school_class[name] += (score,)
else:
school_... |
with open("day6_input") as infile:
cycles = [[int(x) for x in infile.readline().split('\t') if x != '\n']]
steps = 0
while True:
current_cycle = cycles[-1]
max_ = max(current_cycle)
maxindex = current_cycle.index(max_)
new_cycle = current_cycle[:]
new_cycle[maxindex] = 0
for i in range(maxi... |
pattern = []
with open('day_3.txt') as f:
for line in f:
pattern.append([line.rstrip()])
def count_trees(pattern, right, down):
'''Use dictionary to redefine positions outside base pattern,
count all trees in pattern (#) which we meet, when we follow defined number of moves to right and down'''
... |
'''
Dictionary that keeps the cost of individual parts of cars.
'''
car_body = {
'Honda' : 500,
'Nissan' : 1000,
'Suzuki' : 600,
'Toyota' : 500
}
car_tyres = {
'Honda' : 1400,
'Nissan' : 500,
'Suzuki' : 600,
'Toyota' : 1000
}
car_doors = {
'Honda' : 400,
'Nissan': 300,
'Su... |
class Solution:
def findKthPositive(self, arr: List[int], k: int) -> int:
missing = []
limit = arr[-1]
nums = set(arr)
for i in range(1,limit):
if i not in nums:
missing.append(i)
if len(missing) >= k:
return missing... |
# mendapatkan tagihan bulanan
# selamat satu unit lagi dan anda sudah membuat sebuah program! ketika
# kita bilang anda bisa membuat apa saja dengan python, kita bersungguh-sungguh!
# batas dari apa yang anda bisa bangun adalah di imajinasi anda
# terus belajar ke bab berikutnya dan akhirnya anda akan bisa membuat prog... |
def find(n, m, x, y, dx, dy):
if x < 0 or x == 20 or y < 0 or y == 20:
return -1
elif n == 0:
return 1
else:
return m[y][x] * find(n - 1, m, x + dx, y + dy, dx, dy)
directions = [None] * 8
for i in range(0, 8):
if i == 0:
directions[i] = [0, 1]
elif i == 1:
d... |
cue_words=["call it as",
"call this as",
"called as the",
"call it as",
"referred to as",
"is defined as",
"known as the",
"defined as",
"known as",
"mean by",
"concept of",
"talk about",
"called as",
"called the",
"called an",
"called a",
"call as",
"called"]
|
def nonrep():
checklist=[]
my_string={"pythonprograming"}
for s in my_string:
if s in my_string:
my_string[s]+=1
else:
my_string=1
checklist.appened(my_string[s])
for s in checklist:
if s==1:
return True
else:
F... |
# -*- coding: utf-8 -*-
"""DQ0 SDK Data Utils Package
This package contains general data helper functions.
"""
__all__ = [
'util',
'plotting'
]
|
REQUEST_BODY_JSON = """
{
"verification_details": {
"amount": 1.1,
"payment_transaction_id": "string",
"transaction_type": "PHONE_PAY",
"screenshot_url": "string"
}
}
"""
|
#!/usr/bin/env python3
CONVERSION_TABLE = {
'I': 1,
'II': 2,
'III': 3,
'IV': 4,
'V': 5,
'VI': 6,
'VII': 7,
'VIII': 8,
'IX': 9,
'X': 10,
'XX': 20,
'XXX': 30,
'XL': 40,
'L': 50,
'LX': 60,
'LXX': 70,
'LXXX': 80,
'XC': 90,
'C': 100,
'D': 500,... |
'''
This file contains any primitives for Lyanna that aren't just
borrowed from the language. Basically this is Nothing and Undefined,
which are singletons. That is, their classes are stuck here and only
selected instances are exported through __all__
'''
class NothingType(object):
def __str__(self):
retur... |
def settingDecoder(data):
# data can be:
# raw string
# list of strings
data = data.strip()
if (len(data) > 1) and (data[0] == '[') and (data[-1] == ']'):
data = [x.strip() for x in data[1:-1].split(',')]
return data
def loadSetting(filename = "SETTINGS"):
res = dict()
with open... |
resposta = input('Mamae você comprou chocolate?[sim/não] ')
if resposta == 'sim':
print('Obrigado Mainha')
elif resposta == 'não':
print('Então vou chorar ... Buá, Buá')
else:
print('Não foi o que eu perguntei') |
messages = 'game.apps.core.signals.messages.%s' # user.id
planet = 'game.apps.core.signals.planet_details.%s' # planetID_requestID
account_data = 'game.apps.core.signals.account_data.%s'
building = 'game.apps.core.signals.building.%s' # buildingID
task_updated = 'game.apps.core.signals.task_updated.%s' # user.i... |
# 39. Combination Sum
# Time: O((len(candidates))^(target/avg(candidates))) Review
# Space: O(target/avg(candidates))) [depth of recursion tree?]Review
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
result = []
self.util(candidates, target, 0 , [], ... |
class audo:
def __init__(self, form, data = None):
self.form = form
self.values = []
if data:
self.load(data)
def load(self, data):
for i in range(data.readUInt32()):
while (data.offset & 3) != 0:
data.offset += 1
data.push... |
# Copyright (C) 2012 Nippon Telegraph and Telephone Corporation.
#
# 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 ... |
"""
MainWindow.setWindowTitle('Physics')
self.centralwidget.setLayout(self.gridLayout)
version = "v1"
""" |
lst = [90, 180, 0]
empty = []
lst.append(empty)
def function_a():
for empty in lst:
if empty in lst:
print(lst)
function_b()
function_b()
print(lst)
def function_b():
for empty in lst:
if empty in lst:
... |
def options_displ():
print(
'''
weather now: Displays the current weather
weather today: Displays the weather for this day
weather tenday: Displays weather for next ten days
detailed tenday: Displays ten day weather with extended info
weather -t: Disp... |
class TimelineService(object):
@classmethod
def get_timeline(cls, officer_allegations):
allegations_date = officer_allegations\
.values_list('allegation__incident_date_only', 'start_date')\
.order_by('allegation__incident_date')
items = []
for date in allegation... |
l = [int(e) for e in input().split()]
for i in range(1, len(l), 2):
l[i], l[i - 1] = l[i - 1], l[i]
[print(n) for n in l]
|
# Description
# You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The islan... |
# 94. Binary Tree Inorder Traversal
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# recursive
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List... |
tag = list(map(str, (input())))
vowels = ['A', 'E', 'I', 'O', 'U', 'Y']
if tag[2] in vowels:
print("invalid")
else:
if (int(tag[0])+int(tag[1]))%2==0 and (int(tag[3])+int(tag[4]))%2==0 and (int(tag[4])+int(tag[5]))%2==0 and (int(tag[7])+int(tag[8]))%2==0:
print("valid")
else:
print("... |
__all__ = ['Simple']
class Simple(object):
def __init__(self, func):
self.func = func
def __call__(self, inputs, params, other):
return self.forward(inputs)
def forward(self, inputs):
return self.func(inputs), None
def backward(self, grad_out, cache):
return grad_out... |
class Stats:
def getLevelStats():
return [
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",
"Str",... |
#1. Kod
l=[[1,'a',['cat'],2],[[[3]],'dog'],4,5]
m = []
def flaten(x):
for i in x:
if type(i) == list:
flaten(i)
else:
m.append(i)
flaten(l)
print(m)
[1, 'a', 'cat', 2, 3, 'dog', 4, 5]
#2.Kod
a = [[1, 2], [3, 4], [5, 6, 7]]
l=[]
for i in range(0,len(a)):
a[i].reverse(... |
def anagramSolution(s1,s2):
c1 = {}
for i in s1:
if i in c1:
c1[i] = c1[i] + 1
else:
c1[i] = 1
for i in s2:
anagram = True
if i not in c1:
anagram = False
return anagram
return anagram
print(anagramSolution('apple','pleap... |
slimearm = Actor('alien')
slimearm.topright = 0, 10
WIDTH = 712
HEIGHT = 508
def draw():
screen.fill((240, 6, 253))
slimearm.draw()
def update():
slimearm.left += 2
if slimearm.left > WIDTH:
slimearm.right = 0
def on_mouse_down(pos):
if slimearm.collidepoint(pos):
set_alien_hurt(... |
class StringMult:
def times(self, sFactor, iFactor):
if(sFactor == ""):
return ""
elif(iFactor == 0):
return ""
elif(iFactor > 0):
return sFactor * iFactor
else:
reverse = sFactor[::-1]
return reverse * abs(iFactor)
|
#for loop + while loop看似两层循环, 但是while loop只会出现在n-1 is None的情况下 所以 整体时间复杂度O(n)
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
num_set = set(nums)
ret = 0
for num in num_set:
if num - 1 not in num_set:
cur_len = ... |
#Calculate number of distinct characters in a string using a for loop.
def unique_count(word):
k=list()
b = word.split()
b = ''.join(b)
for x in b:
if x not in k:
k.append(x)
return len(k)
enter=input()
print('унікальних символів:',unique_count(enter))
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Chapter:
def __init__(
self,
client,
json_data,
):
"""
Constructs all the necessary attributes for the Chapter object.
Parameters
----------
json_data : json
data in json format... |
numbers = [int(el) for el in input().split()]
average = sum(numbers) / (len(numbers))
top_5_list = []
current_max = 0
for num in range(5):
current_max = max(numbers)
if current_max > average:
top_5_list.append(current_max)
numbers.remove(current_max)
list(top_5_list)
if top_5_list:
print(*... |
class Solution:
def uniquePathsIII(self, grid) -> int:
start=list()
paths=set()
row=len(grid)
col=len(grid[0])
for r in range(row):
for c in range(col):
if grid[r][c]==1:
start.append(r)
start.append(c)
... |
def print_multiples(n, high):
for i in range(1, high+1):
print(n * i, end=" ")
print()
def print_mult_table(high):
for i in range(1, high+1):
print_multiples(i, i)
print_mult_table(7)
|
# -*- coding: utf-8 -*-
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort(key = str.lower)
print(thislist)
|
"""
None
"""
class Solution:
def wordsAbbreviation(self, dict: List[str]) -> List[str]:
def shorten(word, idx):
return word if idx > len(word) - 3 else \
word[:idx] + str(len(word)-1-idx) + word[-1]
res = [shorten(word, 1) for word in dict]
p... |
#!/usr/bin/python3.6
# This should be introduced in the interactive python shell. Where the arguments to print should just be passed to the shell.
# We should keep it to the 4 basic arithmetic functions at first since most kids don't get introduced to other functions until later.
print(2 + 2)
print(3 - 2)
print(2 ... |
"""
Data acquisition boards
=======================
.. todo:: Data acquisition board drivers.
Provides:
.. autosummary::
:toctree:
daqmx
"""
|
#
# PySNMP MIB module Wellfleet-SWSMDS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-SWSMDS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:41:47 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
#!/usr/bin/env python
class Edge:
"""Edge class, to contain a directed edge of a tree or directed graph.
attributes parent and child: index of parent and child node in the graph.
"""
def __init__ (self, parent, child, length=None):
"""create a new Edge object, linking nodes
with indice... |
class Session(list):
"""Abstract Session class"""
def to_strings(self, user_id, session_id):
"""represent session as list of strings (one per event)"""
user_id, session_id = str(user_id), str(session_id)
session_type = self.get_type()
strings = []
for event, product in s... |
DEVICE_NOT_KNOWN = "Device name not known"
NEED_TO_SPECIFY_DEVICE_NAME = "You need to specify device name : ?device_name=..."
INVALID_HOUR = "Provided time is invalid"
DEVICE_SCHEDULE_OK = "Device schedule was setup"
NEED_TO_SPECIFY_JOB_ID = "You need to specidy Job id you want to get removed"
DELETE_SCHEDULE_OK =... |
# Variáveis int
nota1 = int(input('Digite a primeira nota: '))
nota2 = int(input('Digite a segunda nota: '))
# Variável
media = (nota1 + nota2) / 2
# Cor
cor = {'fim': '\033[m',
'roxo': '\033[35m'}
# Print
print('A média do aluno: {}{}{}'.format(cor['roxo'], media, cor['fim']))
|
'''
name = input()
if name != 'Anton':
print(f'I am not Anton, i am {name}')
else:
print(f'I am {name}')
'''
n = 10
while n > 0:
n = n - 1
print(n)
|
# Pattern Matching (Python)
# string is already given to you. Please don't edit this string.
stringData = "qwe sdf dsld dssdfsqwe sdlcsd fdslkcsdsdk sdvnsdnvs dsvd d d dddqwelkmvl sdlksf qwelkmdsldm dsfkmsdf ds lknvnv dsdfdfnoiewqwek sdjnsdf djndsjnnqwnewefsjdc kqwj fsdfjsldnlsqwelkwnekennlksnq dlkneknqwn wqenln qlwn... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.