content stringlengths 7 1.05M |
|---|
# -*- coding: utf-8 -*-
"""
Exceptions for Arequests
Created on Tue Nov 13 08:34:14 2018
@author: gfi
"""
class ArequestsError(Exception):
"""Basic exception for errors raised by Arequests"""
pass
class AuthorizationError(ArequestsError):
'''401 error new authentification required'''
pass
class Some... |
def transform_file(infile,outfile,templates):
with open(infile,'r') as fh:
indata = fh.read()
lines = indata.split('\n')
outlines = []
for line in lines:
if '//ATL_BEGIN' in line:
start = line.find('//ATL_BEGIN')
spacing = line[:start]
s... |
#!/usr/bin/env python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# 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 require... |
#
#
# This is Support for Drawing Bullet Charts
#
#
#
#
#
#
#
'''
This is the return json value to the javascript front end
{ "canvasName":"canvas1","featuredColor":"Green", "featuredMeasure":14.5,
"qualScale1":14.5, "qualScale1Color":"Black","titleText":"Step 1" },
... |
declerations_test_text_001 = '''
list1 = [
1,
]
'''
declerations_test_text_002 = '''
list1 = [
1,
2,
]
'''
declerations_test_text_003 = '''
tuple1 = (
1,
)
'''
declerations_test_text_004 = '''
tuple1 = (
1,
2,
)
'''
declerations_test_text_005 = '''
set1 = {
1,
}
'''
declerations_test_text_00... |
# 지수부 표현
a = 1e9
print(a) # 1000000000.0
a = 7.525e2
print(a) # 752.5
a = 3954e-3
print(a) # 3.954
|
"""
用户身份验证
Version: 0.1
Author: cjp
"""
username = input('请输入用户名: ')
password = input('请输入口令: ')
# 用户名是admin且密码是123456则身份验证成功否则身份验证失败
if username == 'admin' and password == '123456':
print('身份验证成功!')
else:
print('身份验证失败!')
"""
Python中没有用花括号来构造代码块而是使用了缩进的方式来设置代码的层次结构,
如果if条件成立的情况下需要执行多条语句,只要保持多条语句具有相同的缩进就可以了,... |
"""Build rules to create C++ code from an Antlr4 grammar."""
def antlr4_cc_lexer(name, src, namespaces = None, imports = None, deps = None, lib_import = None):
"""Generates the C++ source corresponding to an antlr4 lexer definition.
Args:
name: The name of the package to use for the cc_library.
sr... |
# -*- coding: utf-8 -*-
message_dict = {
'welcome': "Hi! TPO Baba is here to give you updates about TPO portal, set willingness reminders, ppt "\
"reminders, exam date reminders and lot more...:D \n\n"\
"To personalise your experience, I gotta register you. It's simple two step proc... |
# A 以上 B 以下の整数のうち、回文数となるものの個数を求めてください。
# ただし、回文数とは、先頭に 0 をつけない 10 進表記を文字列として見たとき、
# 前から読んでも後ろから読んでも同じ文字列となるような正の整数のことを指します。
# 文字列を逆順にして、同じ桁数の値をみる
a, b = map(int, input().split())
cnt = 0
for i in range(a, b+1):
s = str(i)
s_r = s[::-1]
n = int(len(str(s))/2)
if s[: n] == s_r[:n]:
cnt += 1
print(... |
class AnimationException(SystemException,ISerializable,_Exception):
""" The exception that is thrown when an error occurs while animating a property. """
def add_SerializeObjectState(self,*args):
""" add_SerializeObjectState(self: Exception,value: EventHandler[SafeSerializationEventArgs]) """
pass
def remov... |
file_berita = open("berita.txt", "r")
berita = file_berita.read()
berita = berita.split()
berita = [x.lower() for x in berita]
berita = list(set(berita))
berita = sorted(berita)
print (berita) |
"""
@Fire
https://github.com/fire717
"""
cfg = {
##### Global Setting
'GPU_ID': '0',
"num_workers":8,
"random_seed":42,
"cfg_verbose":True,
"save_dir": "output/",
"num_classes": 17,
"width_mult":1.0,
"img_size": 192,
##### Train Setting
'img_path':"./data/croped/img... |
k = float(input("Digite uma distância em quilometros: "))
m = k / 1.61
print("A distância digitada é de {} quilometros, essa distância convertida é {:.2f} milhas" .format(k,m)) |
aluno = {}
aluno['nome'] = str(input('Digite o nome do aluno: '))
aluno['media'] = float(input('Digite a média desse aluno: '))
if aluno['media'] >= 5:
aluno['situação'] = '\033[32mAprovado\033[m'
else:
aluno['situação'] = '\033[31mReprovado\033[m'
for k, v in aluno.items():
print(f'{k} do aluno é {v}') |
rzymskie={'I':1,'II':2,'III':3,'IV':4,'V':5,'VI':6,'VII':7,'VIII':8}
print(rzymskie)
print('Jeden element slownika: \n')
print(rzymskie['I'])
|
H, W = map(int, input().split())
A = [input() for _ in range(H)]
if H + W - 1 == sum(a.count('#') for a in A):
print('Possible')
else:
print('Impossible')
|
"""
Desafio 067
Problema: Faça um programa que mostre a tabuada de vários números,
um de cada vez, para cada valor digitado pelo usuário.
O programa será interrompido quando o número solicitado
for negativo.
Resolução do problema:
"""
print('-' * 20)
print(f'{" Tabuada v3.0 ":~^20}')
pri... |
"""
Crie um programa que leia um a frase qualquer e diga se ela é um palíndromo,
desconsiderando os espaços.
ex:
apos a sopa
a sacada da casa
a torre da derrota
o lobo ama o bolo
anotaram a data da maratona
"""
frase = input('Digite uma frase (sem acentos): ').replace(' ', '').upper()
inverso = ''
for c in range(len(fr... |
"""
Get an Etree library. Usage::
>>> from anyetree import etree
Returns some etree library. Looks for (in order of decreasing preference):
* ``lxml.etree`` (http://cheeseshop.python.org/pypi/lxml/)
* ``xml.etree.cElementTree`` (built into Python 2.5)
* ``cElementTree`` (http://effbot.org/zone/celem... |
# File: etl.py
# Purpose: To do the `Transform` step of an Extract-Transform-Load.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Thursday 22 September 2016, 03:40 PM
def transform(words):
new_words = dict()
for point, letters in words.items():
for letter in letters:
... |
def have(subj, obj):
subj.add(obj)
def change(subj, obj, state):
pass
if __name__ == '__main__':
main() |
# A bot that picks the first action from the list for the first two rounds,
# and then exists with an exception.
# Used only for tests.
game_name = input()
play_as = int(input())
print("ready")
while True:
print("start")
num_actions = 0
while True:
message = input()
if message == "tourname... |
'''
f we want to add a single element to an existing set, we can use the .add() operation.
It adds the element to the set and returns 'None'.
Example
>>> s = set('HackerRank')
>>> s.add('H')
>>> print s
set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R'])
>>> print s.add('HackerRank')
None
>>> print s
set(['a', 'c', 'e', '... |
# 6. Продолжить работу над вторым заданием. Реализуйте механизм валидации вводимых пользователем данных. Например, для
# указания количества принтеров, отправленных на склад, нельзя использовать строковый тип данных.
# Подсказка: постарайтесь по возможности реализовать в проекте «Склад оргтехники» максимум возможностей... |
class LeagueGame:
def __init__(self, data):
self.patch = data['patch']
self.win = data['win']
self.side = data['side']
self.opp = data['opp']
self.bans = data['bans']
self.vs_bans = data['vs_bans']
self.picks = data['picks']
self.vs_picks = data['vs_picks']
self.players = data['players']
class Lea... |
text1 = '''ABCDEF
GHIJKL
MNOPQRS
TUVWXYZ
'''
text2 = 'ABCDEF\
GHIJKL\
MNOPQRS\
TUVWXYZ'
text3 = 'ABCD\'EF\'GHIJKL'
text4 = 'ABCDEF\nGHIJKL\nMNOPQRS\nTUVWXYZ'
text5 = 'ABCDEF\fGHIJKL\fMNOPQRS\fTUVWXYZ'
print(text1)
print('-' * 25)
print(text2)
print('-' * 25)
print(text3)
print('-' * 25)
print(text4)
print('-' * 2... |
# unihernandez22
# https://atcoder.jp/contests/abc166/tasks/abc166_d
# math, brute force
n = int(input())
for a in range(n):
breaked = True
for b in range(-1000, 1000):
if a**5 - b**5 == n:
print(a, b)
break;
else:
breaked = False
if breaked:
break
|
T = int(input())
P = int(input())
controle = 0 #Uso para guardar o valor maior que o limite
while P != 0:
P = int(input())
if P >= T:
controle = 1 #coloquei 1 so pra ser diferente de 0
if controle == 1:
print("ALARME")
else:
print("O Havai pode dormir tranquilo") |
__all__ = [
"aggregation",
"association",
"composition",
"connection",
"containment",
"dependency",
"includes",
"membership",
"ownership",
"responsibility",
"usage"
] |
class AxisIndex(): #TODO: read this value from config file
LEFT_RIGHT=0
FORWARD_BACKWARDS=1
ROTATE=2
UP_DOWN=3
class ButtonIndex():
TRIGGER = 0
SIDE_BUTTON = 1
HOVERING = 2
EXIT = 10
class ThresHold():
SENDING_TIME = 0.5 |
#!/Users/francischen/opt/anaconda3/bin/python
#pythons sorts are STABLE: order is the same as original in tie.
# sort: key, reverse
q = ['two','twelve','One','3']
#sort q, result being a modified list. nothing is returned
q.sort()
print(q)
q = ['two','twelve','One','3',"this has lots of t's"]
q.sort(reverse=True)
pr... |
# buildifier: disable=module-docstring
load(":native_tools_toolchain.bzl", "access_tool")
def get_cmake_data(ctx):
return _access_and_expect_label_copied("@rules_foreign_cc//tools/build_defs:cmake_toolchain", ctx, "cmake")
def get_ninja_data(ctx):
return _access_and_expect_label_copied("@rules_foreign_cc//too... |
fname = input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
list = list()
f = open(fname)
count = 0
for line in f:
line = line.rstrip()
list = line.split()
if list == []: continue
elif list[0].lower() == 'from':
count += 1
print(list[1])
print("There w... |
class FollowupEvent:
def __init__(self, name, data=None):
self.name = name
self.data = data
class Response:
def __init__(self, text=None, followup_event=None):
self.speech = text
self.display_text = text
self.followup_event = followup_event
class UserInput:
def _... |
# -*- coding: utf-8 -*-
jobwords = [
'nan',
'temps plein', 'temps complet', 'mi temps', 'temps partiel', # Part / Full time
'cherche', # look for
'urgent','rapidement', 'futur',
'job', 'offre', # Job offer
'trice', 'ère', 'eur', 'euse', 're', 'se', 'ème', 'trices', # Fe... |
# Problem Name: Suffix Trie Construction
# Problem Description:
# Write a SuffixTrie class for Suffix-Trie-like data structures. The class should have a root property set to be the root node of the trie and should support:
# - Creating the trie from a string; this will be done by calling populateSuffixTrieFrom me... |
def test_list_devices(client):
devices = client.devices()
assert len(devices) > 0
assert any(map(lambda device: device.serial == "emulator-5554", devices))
def test_list_devices_by_state(client):
devices = client.devices(client.BOOTLOADER)
assert len(devices) == 0
devices = client.devices(clie... |
"""Top-level package for Goldmeister."""
__author__ = """Micah Johnson"""
__email__ = 'micah.johnson150@gmail.com'
__version__ = '0.2.0'
|
n = int(input('Digite um número: '))
if n % 2 == 0 and n % 3 == 0 and n % 5 == 0:
print('{} é um número primo!'.format(n))
else:
print('{} não é um número primo!'.format(n))
|
def si(p,r,t):
n= (p+r+t)//3
return n
|
#!/usr/bin/env python3
# This is gonna be up to you. But basically I envisioned a system where you have a students in a classroom. Where the
# classroom only has information, like who is the teacher, how many students are there. And it's like an online class,
# so students don't know who their peers are, or who their ... |
print('-'*60)
print('\33[35m[ F ] Feminino\33[m \n\33[32m[ M ] Masculino\33[m \n ')
sexo = str(input('Qual o seu sexo? ')).strip().upper()[0] # só pega a primeira letra
while sexo not in 'MF':
sexo = str(input('\33[31mDados inválidos.\33[m Por favor, informe seu sexo: ')).strip().upper()[0]
print('\nSexo {} registr... |
# https://github.com/ArtemNikolaev/gb-hw/issues/24
def multiple_of_20_21():
return (i for i in range(20, 241) if i % 20 == 0 or i % 21 == 0)
print(list(multiple_of_20_21()))
|
def cc_resources(name, data):
out_inc = name + ".inc"
cmd = ('echo "static const struct FileToc kPackedFiles[] = {" > $(@); \n' +
"for j in $(SRCS); do\n" +
' echo "{\\"$$(basename "$${j}")\\"," >> $(@);\n' +
' echo "R\\"filecontent($$(< $${j}))filecontent\\"" >> $(@);\n' +
... |
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print('Hello, my name is {} and I am {} years old'.format(self.name, self.age))
if __name__ == '__main__':
person = Person('David', 34)
print('Age: {}'.format(person.age))
... |
num= int (input("enter number of rows="))
for i in range (1,num+1):
for j in range(1,num-i+1):
print (" ",end="")
for j in range(2 and 9):
print("2","9")
for i in range(1, 6):
for j in range(1, 10):
if i==5 or i+j==5 or j-i==4:
print("*", end... |
'''
Problem:-
Given a string s, find the longest palindromic substring in s.
You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
'''
class Solution:
def longestPalindrome(self, s: str) -> str:
res = ""
resL... |
def _doxygen_archive_impl(ctx):
"""Generate a .tar.gz archive containing documentation using Doxygen.
Args:
name: label for the generated rule. The archive will be "%{name}.tar.gz".
doxyfile: configuration file for Doxygen, @@OUTPUT_DIRECTORY@@ will be replaced with the actual output dir
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDiffInBST(self, root: Optional[TreeNode]) -> int:
output=[]
stack=[root]
whil... |
PREFIX = "/video/tvkultura"
NAME = "TVKultura.Ru"
ICON = "tvkultura.png"
ART = "tvkultura.jpg"
BASE_URL = "https://tvkultura.ru/"
BRAND_URL = BASE_URL+"brand/"
# Channel initialization
def Start():
ObjectContainer.title1 = NAME
HTTP.Headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko... |
class Solution(object):
def connect(self, root):
"""
:type root: TreeLinkNode
:rtype: nothing
"""
if root == None:
return
p = root.next
while p:
if p.left != None:
p = p.left
break
elif p.righ... |
'''
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Exa... |
# Tuples
coordinates = (4, 5) # Cant be changed or modified
print(coordinates[1])
# coordinates[1] = 10
# print(coordinates[1])
|
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Compiles trivial C++ program using Goma.
Intended to be used as a very simple litmus test of Goma health on LUCI staging
environment. Linux and OSX only.... |
# ###########################################################
# ## generate menu
# ###########################################################
_a = request.application
_c = request.controller
_f = request.function
response.title = '%s %s' % (_f, '/'.join(request.args))
response.subtitle = 'admin'
response.menu = [(T('... |
__author__ = 'sibirrer'
# this file contains a class to make a Moffat profile
__all__ = ['Moffat']
class Moffat(object):
"""
this class contains functions to evaluate a Moffat surface brightness profile
.. math::
I(r) = I_0 * (1 + (r/\\alpha)^2)^{-\\beta}
with :math:`I_0 = amp`.
"""
... |
tempratures = [10,-20, -289, 100]
def c_to_f(c):
if c<-273.15:
return ""
return c* 9/5 +32
def writeToFile(input):
with open("output.txt","a") as file:
file.write(input)
for temp in tempratures:
writeToFile(str(c_to_f(temp)))
|
class VoiceClient(object):
def __init__(self, base_obj):
self.base_obj = base_obj
self.api_resource = "/voice/v1/{}"
def create(self,
direction,
to,
caller_id,
execution_logic,
reference_logic='',
count... |
class Solution(object):
def _dfs(self,num,res,n):
if num>n:
return
res.append(num)
num=num*10
if num<=n:
for i in xrange(10):
self._dfs(num+i,res,n)
def sovleOn(self,n):
res=[]
cur=1
for i in xrange(1,n+1):
... |
expected_output = {
"ospf-statistics-information": {
"ospf-statistics": {
"dbds-retransmit": "203656",
"dbds-retransmit-5seconds": "0",
"flood-queue-depth": "0",
"lsas-acknowledged": "225554974",
"lsas-acknowledged-5seconds"... |
# coding: gbk
"""
@author: sdy
@email: sdy@epri.sgcc.com.cn
Abstract distribution and generation class
"""
class ADG(object):
def __init__(self, work_path, fmt):
self.work_path = work_path
self.fmt = fmt
self.features = None
self.mode = 'all'
def distribution_assess(self):
... |
"""
This file must be kept up-to-date with Stripe, especially the slugs:
https://manage.stripe.com/plans
"""
PLANS = {}
class Plan(object):
def __init__(self, value, slug, display):
self.value = value
self.slug = slug
self.display = display
PLANS[slug] = self
FREE = Plan(1, 'f... |
N = int(input())
S = input()
if N % 2 == 1:
print('No')
exit()
if S[:N // 2] == S[N // 2:]:
print('Yes')
else:
print('No')
|
#!/usr/bin/env python
#
# Cloudlet Infrastructure for Mobile Computing
# - Task Assistance
#
# Author: Zhuo Chen <zhuoc@cs.cmu.edu>
#
# Copyright (C) 2011-2013 Carnegie Mellon University
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the... |
class Node():
def __init__(self, value=None):
self.children = []
self.parent = None
self.value = value
def add_child(self, node):
if type(node).__name__ == 'Node':
node.parent = self
self.children.append(node)
else:
raise ValueErro... |
"""Hamming Distance from Exercism"""
def distance(strand_a, strand_b):
"""Determine the hamming distance between two RNA strings
param: str strand_a
param: str strand_b
return: int calculation of the hamming distance between strand_a and strand_b
"""
if len(strand_a) != len(strand_b):
... |
#def spam():
# eggs = 31337
#spam()
#print(eggs)
"""
def spam():
eggs = 98
bacon()
print(eggs)
def bacon():
ham = 101
eggs = 0
spam()
"""
"""
# Global variables can be read from local scope.
def spam():
print(eggs)
eggs = 42
spam()
print(eggs)
"""
"""
# Local and global variables with th... |
# https://leetcode.com/problems/minimum-moves-to-equal-array-elements/
# Explanation: https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/93817/It-is-a-math-question
# Source: https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/272994/Python-Greedy-Sum-Min*Len
class Solu... |
# Given two binary strings, return their sum (also a binary string).
#
# For example,
# a = "11"
# b = "1"
# Return "100".
class Solution:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
la = len(a)
lb = len(b)
if la >= lb:
... |
# Event: LCCS Python Fundamental Skills Workshop
# Date: Dec 2018
# Author: Joe English, PDST
# eMail: computerscience@pdst.ie
# Purpose: To find (and fix) two syntax errors
# A program to display Green Eggs and Ham (v4)
def showChorus():
print()
print("I do not like green eggs and ham.")
print... |
_base_ = [
'../_base_/models/repdet_repvgg_pafpn.py',
'../_base_/datasets/coco_detection.py',
'../_base_/schedules/schedule_poly.py', '../_base_/default_runtime.py'
]
# model settings
model = dict(
type='RepDet',
pretrained='/data/kartikes/repvgg_models/repvgg_b1g2.pth',
backbone=dict(
... |
# Holy Stone - Holy Ground at the Snowfield (3rd job)
questIDs = [1431, 1432, 1433, 1435, 1436, 1437, 1439, 1440, 1442, 1443, 1445, 1446, 1447, 1448]
hasQuest = False
for qid in questIDs:
if sm.hasQuest(qid):
hasQuest = True
break
if hasQuest:
if sm.sendAskYesNo("#b(A mysterious energy surroun... |
class CustomException(Exception):
def __init__(self, *args, **kwargs):
return super().__init__(self, *args, **kwargs)
def __str__(self):
return str(self.args [1])
class DeprecatedException(CustomException):
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)... |
class solutionLeetcode_3:
def lengthOfLongestSubstring(self, s: str) -> (int, str):
if not s:
return 0
left = 0
lookup = set()
n = len(s)
max_len = 0
cur_len = 0
for i in range(n):
cur_len += 1
while s[i] in lookup:
... |
# Árvore Huffman
class node:
def __init__(self, freq, symbol, left=None, right=None):
# Frequência do Símbolo
self.freq = freq
# Símbolo (caracter)
self.symbol = symbol
# nó à esquerda do nó atual
self.left = left
# nó à direita do nó atual
self.rig... |
#==============================================================================
# Copyright 2011 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# 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 ... |
#!/usr/bin/env python
# encoding: utf-8
"""
@Author: yangwenhao
@Contact: 874681044@qq.com
@Software: PyCharm
@File: __init__.py.py
@Time: 2020/3/27 10:43 AM
@Overview:
"""
|
def f(x):
if x <= -2:
f = 1 - (x + 2)**2
return f
if -2 < x <= 2:
f = -(x/2)
return f
if 2 < x:
f = (x - 2)**2 + 1
return f
x = int(input())
print(f(x))
|
dnas = [
['jVXfX<', 37, 64, 24.67, 14, 7, -4.53, {'ott_len': 42, 'ott_percent': 508, 'stop_loss': 263, 'risk_reward': 65, 'chop_rsi_len': 31, 'chop_bandwidth': 83}],
['o:JK9p', 50, 62, 32.74, 37, 8, -0.2, {'ott_len': 45, 'ott_percent': 259, 'stop_loss': 201, 'risk_reward': 41, 'chop_rsi_len': 12, 'chop_bandwidth': 274}... |
def createArray(dims) :
if len(dims) == 1:
return [0 for _ in range(dims[0])]
return [createArray(dims[1:]) for _ in range(dims[0])]
def f(A, x, y):
m = len(A)
for i in range(m):
if A[i][x] > A[i][y]:
return 0
return 1
class Solution(object):
def minDeletionSize(self, A):
... |
lista = list(range(0,10001))
for cont in range(0,10001):
print(lista[cont])
for valor in lista:
print(valor) |
cont = 1
while True:
t = int(input('Quer saber a tabuada de que numero ? '))
if t < 0:
break
for c in range (1, 11):
print(f'{t} X {c} = {t * c}')
print('Obrigado!') |
#!/usr/bin/env python3
seq = 'ACGACGCAGGAGGAGAGTTTCAGAGATCACGAATACATCCATATTACCCAGAGAGAG'
w = 11
for i in range(len(seq) - w + 1):
count = 0
for j in range(i, i + w):
if seq[j] == 'G' or seq[j] == 'C':
count += 1
print(f'{i} {seq[i:i+w]} {(count / w) : .4f}')
|
class Rektangel:
def __init__(self, start_x, start_y, bredde, hoyde):
self.start_x = start_x
self.start_y = start_y
self.hoyde = hoyde
self.bredde = bredde
def areal(self):
return self.bredde*self.hoyde
# Endrer høyde og bredde på en slik måte at areal forblir det s... |
# Tabuada em Python
def tabuada(x):
for i in range(10):
print('{} x {} = {}'.format(x, (i + 1), x * (i + 1)))
print()
if __name__ == '__main__':
print(9
)
nro = int(input('Entre com um número: '))
print(f'\n\033[1;32mTabuada do {nro}'+'\n')
tabuada(nro)
|
# Princess No Damage Skin (30-Days)
success = sm.addDamageSkin(2432803)
if success:
sm.chat("The Princess No Damage Skin (30-Days) has been added to your account's damage skin collection.")
|
class HiddenPeople():
"""Class for holding information on people"""
def __init__(self):
self.people = {
'Paul': {'bald': False, 'beard': False, 'eyes': 'brown', 'gender': 'man', 'hair': 'white', 'hat': False,
'glasses': True, 'moustache': False},
... |
list1 = []
list2 = []
list3 = []
cont = 0
while cont < 10:
valor = int(input('Digite um numero na lista 1: '))
list1.append(valor)
valor2 = int(input('Digite um numero na lista 2: '))
list2.append(valor2)
cont = cont + 1
if cont == 10:
for i in list1:
if i in list2:
... |
# 1) count = To count how many time a particular word & char. is appearing
x = "Keep grinding keep hustling"
print(x.count("t"))
# 2) index = To get index of letter(gives the lowest index)
x="Keep grinding keep hustling"
print(x.index("t")) # will give the lowest index value of (t)
# 3) find = To get index of lett... |
# Thinking probabilistically-- Discrete variables!!
# Statistical inference rests upon probability. Because we can very rarely say anything meaningful with absolute certainty from data, we use probabilistic language to make quantitative statements about data. In this chapter, you will learn how to think probabilistical... |
# example of redefinition __repr__ and __str__ of exception
class MyBad(Exception):
def __str__(self):
return 'My mistake!'
class MyBad2(Exception):
def __repr__(self):
return 'Not calable' # because buid-in method has __str__
try:
raise MyBad('spam')
except MyBad as X:
print(X) #... |
#Q2
# “If you have an apple and I have an apple and we exchange these apples then
# you and I will still each have one apple. But if you have an idea and I have
# an idea and we exchange these ideas, then each of us will have two ideas.”
# George Bernard Shaw
class Person:
apples = 0
ideas = 0
johanna = Perso... |
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
'''
T: O(n log n) and S: O(1)
'''
n = len(nums)
sorted_nums = sorted(nums)
start, end = n + 1, -1
for i in range(n):
if nums[i] != sorted_nums[i]:
... |
# "javascript" section for javascript. see @app.route('/config.js') in app/views.py
# oauth constants
HOSTNAME = "http://hackathon.chinacloudapp.cn" # host name of the UI site
QQ_OAUTH_STATE = "openhackathon" # todo state should be constant. Actually it should be unguessable to prevent CSFA
HACkATHON_API_ENDPOINT = ... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
if not target or not original or not... |
class City:
name = "city"
size = "default"
draw = -1
danger = -1
population = [] |
def to_weird_case(string):
arr=string.split()
count=0
for i in arr:
tmp=list(i)
for j in range(len(tmp)):
if j%2==0:
tmp[j]=tmp[j].upper()
arr[count] = ''.join(tmp)
count+=1
return ' '.join(arr)
'''
一个比较不错的版本
def to_weird_case(string):
r... |
# >>> s = set("Hacker")
# >>> print s.difference("Rank")
# set(['c', 'r', 'e', 'H'])
# >>> print s.difference(set(['R', 'a', 'n', 'k']))
# set(['c', 'r', 'e', 'H'])
# >>> print s.difference(['R', 'a', 'n', 'k'])
# set(['c', 'r', 'e', 'H'])
# >>> print s.difference(enumerate(['R', 'a', 'n', 'k']))
# set(['a', 'c', 'r... |
SECRET_KEY = None
DB_HOST = "localhost"
DB_NAME = "kido"
DB_USERNAME = "kido"
DB_PASSWORD = "kido"
COMPRESSOR_DEBUG = False
COMPRESSOR_OFFLINE_COMPRESS = True
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.