content stringlengths 7 1.05M |
|---|
s = input()
hachi = set()
if len(s) < 3:
if int(s) % 8 == 0 or int(s[::-1]) % 8 == 0:
print("Yes")
else:
print("No")
exit()
t = 104
while t < 1000:
hachi.add(str(t))
t += 8
counter = [0 for _ in range(10)]
for i in s:
counter[int(i)] += 1
for h in hachi:
count = [0 for _ in r... |
#
# PySNMP MIB module DLINK-3100-BRIDGEMIBOBJECTS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DLINK-3100-BRIDGEMIBOBJECTS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:33:05 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pytho... |
def has_doi(bib_info):
return "doi" in bib_info
def get_doi(bib_info):
return bib_info["doi"]
def has_title(bib_info):
return "title" in bib_info
def get_title(bib_info):
return bib_info["title"]
def has_url(bib_info):
return "url" in bib_info
def get_url(bib_info):
if "url" in bib_inf... |
payload_mass=5
payload_fairing_height=1
stage1_height=7.5
stage1_burnTime=74
stage1_propellant_mass=15000
stage1_engine_mass=1779
stage1_thrust=469054
stage1_isp=235.88175331294596
stage1_coastTime=51
stage2_height=3.35
stage2_burnTime=64
stage2_propellant_mass=5080
stage2_engine_mass=527
stag... |
# Problem:
# Write a program that introduces a number n (2 ≤ n ≤ 100) and prints a cot with a size n x n.
n = int(input())
asterisk = "*"
minuses = "-"
for i in range(1, n + 1):
if n % 2 == 0 and i % 2 == 0:
asterisk = i
minuses = (n - i ) // 2
print("-" * minuses + "*" * asterisk + "-"... |
digit1 = 999
digit2 = 999
largestpal = 0 #always save the largest palindrome
#nested loop for 3digit product
while digit1 >= 1:
while digit2 >= 1:
#get string from int
p1 = str(digit1 * digit2)
#check string for palindrome by comparing first-last, etc.
for i in range(0, (len(p1) - 1)):
#no pal?... |
class InvalidMoveException(Exception):
pass
class InvalidPlayerException(Exception):
pass
class InvalidGivenBallsException(Exception):
pass
class GameIsOverException(Exception):
pass
|
while True:
try:
dinheiro = []
nota = input()
cent = input()
if(len(cent) < 2):
cent += '0'
cent = cent[::-1]
dinheiro += '.' + cent
print(dinheiro)
except EOFError:
break |
# import sys
# from io import StringIO
#
# input_1 = """3, 6
# 7, 1, 3, 3, 2, 1
# 1, 3, 9, 8, 5, 6
# 4, 6, 7, 9, 1, 0
# """
#
# sys.stdin = StringIO(input_1)
rows, columns = [int(x) for x in input().split(", ")]
matrix = []
sum_matrix = 0
for _ in range(rows):
row = [int(x) for x in input().split(", ")]
matri... |
'''
Design a HashSet without using any built-in hash table libraries.
To be specific, your design should include these functions:
add(value): Insert a value into the HashSet.
contains(value) : Return whether the value exists in the HashSet or not.
remove(value): Remove a value in the HashSet. If the value doe... |
# -*- coding: UTF-8 -*-
class MyClass(object):
def __init__(self):
pass
def __eq__(self, other):
return type(self) == type(other)
if __name__ == '__main__':
print (MyClass())
print (MyClass())
print (MyClass() == MyClass())
print (MyClass() == 42)
|
"""pandas-data-dictionary - Pandas extension adding data dictionary accessor for describing and validating data."""
__version__ = '0.1.0'
__author__ = 'Tom Couch <t.couch@ucl.ac.uk>'
__all__ = []
|
# 2020.08.02
# Problem Statement:
# https://leetcode.com/problems/substring-with-concatenation-of-all-words/
class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
# check if s is empty or words is empty
if len(s) * len(words) == 0: return []
# length is th... |
print("hello")
print("hello")
print("hello")
print("hello")
print("It's me")
print("I'm here")
|
class CourseType():
__doc__ = "Type of degree, e.g. BA, BEng, BSc"
possibleCourseTypes = ["BA", "BSc"] #TODO extend to values from http://typesofdegrees.org/
def __init__(self, name, accepts, singleHons = 0, jointHons = 0):
if self.checkName(name):
self._name = name
self.accepts = accepts
self.singleHons ... |
#Given an array of integers, return the 3rd Maximum Number in this array, if it doesn't exist, return the Maximum Number. The time complexity must be O(n) or less.
class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a=b=c=-pow(10, 18)
nums=set(nums)
for i in nums:... |
def collatz_len(n):
ct = 1
while n != 1:
if n % 2 == 0:
n = n/2
else:
n = 3*n+1
ct += 1
return ct
len_max = i_max = 0
for i in range(1, 1000001):
current_len = collatz_len(i)
if current_len > len_max:
len_max = current_len
i_max = i
... |
# Sorts a Python list in ascending order using the quick sort
# algorithm
def quickSort(theList):
n = len(theList)
recQuickSort(theList, 0, n-1)
# The recursive "in-place" implementation
def recQuickSort(theList, first, last):
# Check the base case (range is trivially sorted)
if first >= last:
... |
class Commitment(object):
"""
Abstraction from the messages.Commitment
Purpose: don't mix messaging logic with internal logic
Expect that the `protocol.send()` takes an instance of Commitment and constructs the message by itself.
On incoming messages, the protocol will use the `Commitment.from_mess... |
class Time:
max_hours = 23
max_minutes = 59
max_seconds = 59
def __init__(self, hours: int, minutes: int, seconds: int):
self.hours = hours
self.minutes = minutes
self.seconds = seconds
def set_time(self, hours, minutes, seconds):
self.hours = hours
... |
# 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 isValidBST(self, root: Optional[TreeNode]) -> bool:
def subfun(root, minimal, maximal):
... |
# Lambda funkcie
#
# Tato sekcia sluzi na precvicenie si lambda vyrazov
#
# Uloha 1:
def make_square():
return(lambda x: x*x)
# Uloha 2:
def make_upper():
return(lambda x: x.upper())
# Uloha 3:
def make_power():
return(lambda x, N: x ** N)
# Uloha 4:
def make_power2(N):
return(lambda x: x ** N)
... |
def forever2():
pass
forever(forever2) |
IMU_BUS = 2
# MPU9250 Default I2C slave address
MPU_DEFAULT_I2C_ADDR = 0x68
"""
register offsets
"""
SMPLRT_DIV = 0x19
CONFIG = 0x1A
GYRO_CONFIG = 0x1B
ACCEL_CONFIG = 0x1C
ACCEL_CONFIG_2 = 0x1D
INT_PIN_CFG = 0x37
ACCEL_XOUT_H = 0x3B
ACCEL_XOUT_L = 0x3C
ACCEL_YOUT_H = 0x3D
ACCEL_YOUT_L = 0x3E
ACCEL_ZOUT_H = 0x3F
ACCEL... |
def retrieve_page(page):
if page > 3:
return {"next_page": None, "items": []}
return {"next_page": page + 1, "items": ["A", "B", "C"]}
items = []
page = 1
while page is not None:
page_result = retrieve_page(page)
items += page_result["items"]
page = page_result["next_page"]
print(items) ... |
# A chess knight has 8 possible moves it can make, as illustrated. It can move to the nearest square but not on the same row, column, or diagonal.
# (e.g., it can move two squares horizontally, then one square vertically, or it can move one square horizontally then two squares vertically - i.e., in an "L" pattern.)
#... |
# 1) O que uma pessoa Tem? Quais as caracteristicas?
###### Atributos --- variáveis
# nome
# idade
# telefone
# sexo
# 2) O que uma pessoa faz?
###### Métodos --- (função/procedimento)
# respira
# dorme
# corre
# bebe
# come
# multiplica ###
# 3) Como a pessoa está agora?
###### Atributos de estado ---- Variáveis
... |
# Способ сократить код!
a, b = 5, 10
print("Разность:", a - b)
print()
print("StepikPyGEK001113сh02p02st04C02")
B, b = 1, 0
b, B = 2, 10
print("Если возвести", b, "в", B, "степень, то будет", b ** B)
print()
print("StepikPyGEK001113сh02p02st05C03")
a = 4
b = 3
# Выберите все подходящие ответы из списка
# a, b = 3, 4
... |
# SIEL type compliance cases require a specific control code prefixes. currently: (0 to 9)D, (0 to 9)E, ML21, ML22.
COMPLIANCE_CASE_ACCEPTABLE_GOOD_CONTROL_CODES = "(^[0-9][DE].*$)|(^ML21.*$)|(^ML22.*$)"
class ComplianceVisitTypes:
FIRST_CONTACT = "first_contact"
FIRST_VISIT = "first_visit"
ROUTINE_VISIT ... |
'''
Sort the following string alphabetically, from z to a, and assign it to the variable sorted_letters.
'''
letters = "alwnfiwaksuezlaeiajsdl"
sorted_letters = sorted(letters, reverse = True)
'''
Sort the list below, animals, into alphabetical order, a-z. Save the new list as animals_sorted.
'''
animals = ['elephan... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:
k=-1
pre=ListNode(-1000,list1)
x=List... |
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def size(self):
return len(self.items)
def get_max(self):
return ma... |
def palindrome(word, index):
left = index
right = len(word) - 1 - index
if left >= right:
return f"{word} is a palindrome"
right_letter = word[len(word)-1-index]
left_letter = word[index]
if left_letter != right_letter:
return f"{word} is not a palindrome"
return palindrome... |
#
# PySNMP MIB module CISCO-HEALTH-MONITOR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-HEALTH-MONITOR-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:59:45 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... |
class ListNode:
def __init__(self, key=None, value=None, next_node=None):
self.key = key
self.val = value
self.next = next_node
class MyHashMap:
def __init__(self):
self.size = 8
self.used = 0
self.threshold = 0.618
self.buckets = [None] * self.size
... |
DOC_CHAPTER(
header = 'If statements',
topic = 'Reference',
text = """
There are two main forms of if-statements.
1. Regular if-then with optional else-clause
$DOC_LIST_UNORDERED(
$DOC_WORD( if ) $DOC_QUOTE( [ condition ] ),
$DOC_WORD( if ) $DOC_QUOTE( [ condition ] ) $DOC_WORD( then ) $DOC_QUOTE( [ valu... |
n=int(input());ans=0
def s(x,h):
global ans
for i in range(3):
if i==0 and x==0: continue
if x==n:
if h%3==0: ans+=1;return
else:
s(x+1,h+i)
s(0,0)
print(ans)
|
def BFS(adj, s):
queue = [s]
visited = []
while queue:
vertex = queue.pop(0)
if vertex not in visited:
visited.append(vertex)
for node in graph[vertex]:
if node not in visited:
queue.append(node)
return visited
#경로탐색
def bfs_... |
# 参考大佬的代码
# 动态规划化法
class Solution:
def isMatch(self, s, p):
len_s = len(s)
# 如果p中的?和字母的数量和大于s的长度
if len(p) - p.count('*') > len_s:
return False
# dp[i]表示字符串s前i个字符是否匹配p
# dp[0]表示字符串和空字符串或者只有*的字符串匹配
dp = [True] + [False] * len_s
for i in p:
... |
def slack_escape(text: str) -> str:
"""
Escape special control characters in text formatted for Slack's markup.
This applies escaping rules as documented on
https://api.slack.com/reference/surfaces/formatting#escaping
"""
return text.replace("&", "&").replace("<", "<").replace(">", ">... |
class NoChoice(Exception):
def __init__(self):
super().__init__("Took too long.")
class PaginationError(Exception):
pass
class CannotEmbedLinks(PaginationError):
def __init__(self):
super().__init__("Bot cannot embed links in this channel.")
|
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
def isStringHTML(s):
if not isinstance(s, str):
return False
s = s.lower()
return any(... |
def notas(*num,sit = False):
"""
Esse função recebe a nota de vários alunos e as armazena em uma biblioteca
:param num: Notas dos alunos
:param sit: Situação opcional para verificar o desempenho geral da turma
:return: Retorna a biblioteca contendo a maior e menor nota, média, etc
"""
bibli... |
def assert_dict_equal(expected, actual):
message = []
equal = True
for k, v in expected.items():
if actual[k] != v:
message.append(f"For key {k} want {v}, got {actual[k]}")
equal = False
for k, v in actual.items():
if not k in expected:
message.append(f"Got extra key {k} with value {v... |
"""
:copyright: (c) 2020 Yotam Rechnitz
:license: MIT, see LICENSE for more details
"""
class Assists:
def __init__(self, js: dict):
self._defensive_assists = js["defensiveAssists"] if "defensiveAssists" in js else 0
self._healing_done = js["healing_done"] if "healing_done" in js else 0
se... |
x = int(input())
for j in range(x):
q = int(input())
print("Case", j + 1, end=": ")
for t in range(1, int(q / 2 + 1)):
if q % t == 0:
print(t, end=" ")
print(q)
|
"""
Write a Python program to replace last element in a list with another list.
"""
num1 = [1, 3, 5, 7, 9]
num2 = [2, 4, 6, 8, 0]
num1[-1:] = num2
print(num1) |
class RobotStatus:
def __init__(self):
self.status = 'init'
self.position = ''
def isAvailable(self):
if self.status == 'available':
return True
else:
return False
def isWaitEV(self):
if self.status == 'waitEV':
return True
... |
# The language mapping for 2 and 3 character language code.
language_dict = {
"kn": "kannada",
"kan": "kannada",
"hi": "hindi",
"hin": "hindi",
}
|
# Recursive Functions
def iterTest(low, high):
while low <= high:
print(low)
low=low+1
def recurTest(low,high):
if low <= high:
print(low)
recurTest(low+1, high)
|
#!/usr/bin/env python3
"""
Bradley N. Miller, David L. Ranum
Problem Solving with Algorithms and Data Structures using Python
Copyright 2005
Updated by Roman Yasinovskyy, 2017
"""
class BinaryHeap:
"""Minimal Binary Heap"""
def __init__(self):
"""Create a heap"""
self._heap = []
def _per... |
# find min. no. of sets an array (awards) can be divided into such that couple-wise difference of each element is at most k
# ex: awards=[1,5,4,6,8,9,2], k=3, o/p=3
# [1,2][4,5,6][8,9] with max diff 1,2,1 respectively
# int minimumGroups(int awards[n],int k) => o/p
def max_diff(arr):
return max(arr) - min(arr)... |
class Solution:
def countBits(self, n: int) -> List[int]:
arr = []
for i in range(n+1):
i_b = int(bin(i)[2:])
arr.append(self.calculate1(i_b))
return arr
def calculate1(self, i):
count = 0
while i >= 1:
re... |
class Heap:
def __init__(self, arr):
self.arr = arr
self.size = len(self.arr)
def max_heapify(self, current_index):
if not self.is_leaf(current_index):
left_child = (2 * current_index) + 1
right_child = (2 * current_index) + 2
if right_child < self.... |
# -*- coding: utf-8 -*-
# @Author: Wenwen Yu
# @Created Time: 7/8/2020 9:34 PM
Entities_list = [
"date_echeance",
"date_facture",
"methode_payement",
"numero_facture",
"rib",
"adresse",
"contact",
"nom_fournisseur",
"matricule_fiscale",
"total_ht",
"total_ttc"
]
# Entities_... |
""" Script to specify the config
@author: AbinayaM02
"""
# Gunicorn config
bind = '0.0.0.0:5069'
workers = 1
timeout = 0
max_requests = 1
|
data = (
'Guo ', # 0x00
'Yin ', # 0x01
'Hun ', # 0x02
'Pu ', # 0x03
'Yu ', # 0x04
'Han ', # 0x05
'Yuan ', # 0x06
'Lun ', # 0x07
'Quan ', # 0x08
'Yu ', # 0x09
'Qing ', # 0x0a
'Guo ', # 0x0b
'Chuan ', # 0x0c
'Wei ', # 0x0d
'Yuan ', # 0x0e
'Quan ', # 0x0f
'K... |
# faça um programa que leia um numero inteiro qualquer e mostre na tela a sua tabuada.
numero = int(input("Digite um numero inteiro: "))
print("A tabuada do {} é: ". format(numero))
print("{} x 1 = {}".format(numero, (numero*1)))
print("{} x 2 = {}".format(numero, (numero*2)))
print("{} x 3 = {}".format(numero, (nume... |
FEATURES = {"DEBUG_MODE": False}
def feature(feature_id: str) -> bool:
if feature_id not in FEATURES:
raise ValueError("Key not a valid feature")
return FEATURES[feature_id]
|
team_names = ['LA Chargers', 'LA Rams', 'NE Patriots', 'NY Giants',
'Chicago Bears']
locations = ['LA', 'NY', 'SF', 'CH', 'NE']
weeks = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] |
def any_lowercase(s):
""" incorrect - only checks whether first letter is lower case"""
for c in s:
if c.islower():
return True
else:
return False
def any_lowercase_fixed(s):
for c in s:
if c.islower():
return True
return Fa... |
"""
53. Maximum Subarray
Given an integer array nums, find the contiguous subarray (containing at least one
number) which has the largest sum and return its sum.
A subarray is a contiguous part of an array.
Examples
--------
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1... |
x = int(input(""))
y = int(input(""))
div = int(x/y)
print(div)
mod = int(x % y)
print(mod)
z = divmod(x, y)
print(z) |
red = 'Red'
blue = 'Blue'
green = 'Green'
spring_green = 'SpringGreen'
hot_pink = 'HotPink'
blue_violet = 'BlueViolet'
cadet_blue = 'CadetBlue'
chocolate = 'Chocolate'
coral = 'Coral'
dodger_blue = 'DodgerBlue'
firebrick = 'Firebrick'
golden_rod = 'GoldenRod'
orange_red = 'OrangeRed'
yellow_green = 'YellowGreen'
sea_gr... |
# -*- coding: utf8 -*-
__author__ = 'wangqiang'
if __name__ == "__main__":
# 四舍五入方式保留2位小数(3.14)
print("{:.2f}".format(3.1415926))
# 带符号保留2位小数(+3.14)
print("{:+.2f}".format(3.1415926))
# (-1.00)
print("{:+.2f}".format(-1))
# 四舍五入取整
print("{:.0f}".format(2.7182))
# 整数左边补零,宽度为2
pr... |
class Solution:
def numSub(self, s: str) -> int:
l = [int(i) for i in s]
res = 0
i = 0
while i < len(l):
if l[i] != 1:
i += 1
continue
count = 0
curr = 0
while i < len(l) and l[i] == 1:
i ... |
class conta_corrente:
def __Init__(self, nome):
self.nome = nome
self.email = None
self.telefone = None
self._saldo = 0
def _checar_saldo(self, valor):
return self._saldo >= valor
def depositar(self, valor):
self._saldo += valor
def sacar(self, valor):
... |
chromedriver_path='***'
from_station='***'
to_station='***'
email='***'
phone_num='***'
full_name='***'
card_num='***'
exp='***'
cvv='***' |
# terrascript/data/camptocamp/jwt.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:19:50 UTC)
__all__ = []
|
mon_fichier = open("mdp.txt" , "r")
crypt = mon_fichier.read()
mon_fichier.close()
mon_fichier = open("encrypt.txt" , "r")
decrypt1 = mon_fichier.read()
mon_fichier.close()
def encrypt(crypt):
number=input("donner une cle de cryptage (numero)")
b=list(crypt)
str(b)
c=[ord(x)for x in(b)]
... |
#1
Transformers={"Оптімус Прайм":"Грузовик Peterbilt 379","Бамблбі":"Chevrolet Camaro","Джаз":"Porsche 935 Turbo"}
for i, x in Transformers.items():
print(i,"-",x)
#2
for i in Transformers:
if i=="Оптімус Прайм":
print("Оптімус Прайм прибув")
break
#3
TransformersWeight={ "Оп... |
'''dom.py contains all referenced dom elements. Gathering all fragile dom elements in one config file makes it easier to maintain the code'''
def dom():
dom = {
'loginButton': 'html/body/div[3]/header/div/div/div/div[2]/button/span',
'einverstandenButton': 'div.c-button--bold... |
def template_expand(tool, template, output, subs, executable = False, execution_requirements = None):
"""Powerful template expansion rule.
template_expand uses the powerful golang text/template engine to expand an input template
into an output file. The subs dict provide keys and values, where the values c... |
'''
2. Write a Python Program to read the contents of a file and find how many upper case letters,
lower case letters and digits existed in the file.
'''
file = open('SampleCount.txt','r')
data = file.read()
print('Contents of a file is')
print(data)
digit = upper = lower = special = 0
for ch in data:
if ch.islo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 数値読み込み
a,b = [int(i) for i in input().split()]
if a <= 0 and b >=0:
print("Zero")
elif a<0 and b<0 and (a-b)%2==0:
print("Negative")
else:
print("Positive")
|
# Specialization: Google IT Automation with Python
# Course 01: Crash Course with Python
# Week 5 Module Part 2 Exercise 02
# Student: Shawn Solomon
# Learning Platform: Coursera.org
# Want to see this in action?
# In this code, there's a Person class that has an attribute name, which gets set when constructing... |
def solve(data):
result = 0
# Declares an unordered collection of unique elements
unique_frequencies = set()
while True:
for number in data:
result += number
# Checks if current sum(result) already exists in the collection
if result in unique_frequencies:
... |
class InMemoryStorage:
__instance = None
def __init__(self):
self.room_data = dict()
self.user_data = dict()
@classmethod
def __getInstance(cls):
return cls.__instance
@classmethod
def instance(cls, *args, **kargs):
cls.__instance = cls(*args, **kargs)
... |
class Carro:
def __init__(self, vel_max): # construtor padrão do objeto
self.vel_max = vel_max
self.vel_atual = 0
def acelerar(self, delta=5):
maxima = self.vel_max
nova = self.vel_atual + delta
self.vel_atual = nova if nova <= maxima else maxima
return self.vel... |
def next_13_numbers_product(num, start):
if start + 13 > len(num):
return 0
x = 1
for index in range(start, start + 13):
x *= int(num[index])
return x
number = "73167176531330624919225119674426574742355349194934\
96983520312774506326239578318016984801869478851843\
858615607891129494... |
class Solution:
def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
ans = []
i = 0
j = 0
while i < len(A) and j < len(B):
if A[i][0] <= B[j][0] and A[i][1] >= B[j][1]:
C = []
C.append(B[j][0])... |
def fibonacci():
a = 0
b = 1
while True: # keep going...
yield a # report value, a, during this pass
future = a + b
a = b # this will be next value reported
b = future # and subsequently this
|
X = int(input())
Y = int(input())
print(int(input())*60 + int(input()))
a = int(input())
print(a//60)
print(a%60)
x=int(input())
h=int(input())
m=int(input())
print(h+(x+m)//60)
print((x+m)%60) |
"""Warnings.
"""
__author__ = 'Md Jahidul Hamid <jahidulhamid@yahoo.com>'
__copyright__ = 'Copyright © Md Jahidul Hamid <https://github.com/neurobin/>'
__license__ = '[BSD](http://www.opensource.org/licenses/bsd-license.php)'
__version__ = '0.0.1'
class UnsupportedWarning(DeprecationWarning):
"""Base class for ... |
"""Exercício Python 060: Faça um programa que leia um número qualquer e mostre o seu fatorial.
Exemplo: 5! = 5 x 4 x 3 x 2 x 1 = 120"""
"""
from math import factorial
num = int(input("Digite um nomero para calcular seu fatorial: "))
print(f"O fatorial de {num} é {factorial(num)}")"""
"""
num = int(input("Digite um nom... |
def confusion_matrix(yreal, ypred):
n_classes = len(set(yreal))
new_matrix = []
print("len yreal: ", len(yreal))
print("len ypred: ", len(ypred))
print("n classes: ", n_classes)
for i_class in range(n_classes):
new_matrix.append([])
for _ in range(n_classes): #i_ypred
... |
#Задача 4
#Найти произведение ряда чисел от 1 до 10. Полученный результат вывести на экран.
n = 1
for i in range(1,11):
n *= i
print(n) |
#primeira solução
sexo = input('Informe seu sexo: [M/F] ').strip().upper()[0]# o zero é para pegar
cont = 1
while cont == 1:
if sexo not in 'FfMm':
sexo = input('Dados Inválidos. Por favor informe seu sexo: ').strip().upper()[0]
cont = 1
else:
cont = 0
print('\nSexo {} registrado com suc... |
def find_file(filename):
"""
尝试读取文件,将其内容打印到屏幕上。
并在文件不存在时,捕获异常,打印一
条友好的消息。
"""
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
message = "Sorry, the file " + filename + " does not exist."
print(message)
e... |
def quicksort(array):
if len(array) < 2:
return array
print(quicksort([ ])) |
'''
A non-empty array A consisting of N numbers is given. The array is sorted in non-decreasing order. The absolute distinct count of this array is the number of distinct absolute values among the elements of the array.
For example, consider array A such that:
A[0] = -5
A[1] = -3
A[2] = -1
A[3] = 0
A[4] = ... |
"""Generate a file.
In this example, the content is passed via an attribute. If you generate
large files with a lot of static content, consider using
`ctx.actions.expand_template` instead.
"""
def file(**kwargs):
_file(out = "{name}.txt".format(**kwargs), **kwargs)
def _impl(ctx):
output = ctx.outputs.out
... |
# Assign String to a Variable
a = 'Hello'
print (a,'\n')
# Multiline Strings
# using three double quotes:
b = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt."""
print(b,'\n')
# using three single quotes:
b = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed... |
#
# PySNMP MIB module Unisphere-Data-SONET-CONF (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Data-SONET-CONF
# Produced by pysmi-0.3.4 at Wed May 1 15:32:59 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... |
name1=["ales","Mark","Deny","Hendry"]
name2=name1
name3=name1[:]
name1=["Anand"]
name3=["Murugan"]
sum=0
for ls in (name1,name2,name3):
if ls[0]=="Anand":
sum+=1
pass
if ls[1]=="Murugan":
sum+=5
print(sum)
pass |
def solution():
def integers():
x = 1
while True:
yield x
x += 1
def halves():
for x in integers():
yield x / 2
def take(n, seq):
result = []
for i in range(n):
result.append(next(seq))
return result
retu... |
"""Classes for stateful data stream sampling
"""
def create_sampler(mode, **kwargs):
"""Creates a specified sampler instance
"""
if mode == 'uniform':
return UniformSampler(**kwargs)
elif mode == 'contiguous':
return ContiguousSampler(**kwargs)
else:
raise ValueError('Unkno... |
# Copyright (c) 2017 Pieter Wuille
# Copyright (c) 2018 Oskar Hladky
# Copyright (c) 2018 Pavol Rusnak
#
# 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... |
#_*_ coding: utf-8 _*_
#Python3 실습
print("hh")
def sum(a,b):
return (a+b)
print(sum(4,5))
print(sum("han"," jaegyu"))
def no_return():
print("안녕하세요")
return
print(no_return())
print(type(None))
a=None
print(a)
print(range(10))
print(list(range(10)))
def daily_sleeping_hours(hours=None):
if hours == None:
... |
class Iec6205621Exception(Exception):
"""General IEC62056-21 Exception"""
class Iec6205621ClientError(Iec6205621Exception):
"""Client error"""
class Iec6205621ParseError(Iec6205621Exception):
"""Error in parsing IEC62056-21 data"""
class ValidationError(Iec6205621Exception):
"""Not valid data erro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.