content stringlengths 7 1.05M |
|---|
def gen_counter(cnt=None):
res = 0
while True:
yield res
res += 1 if cnt is None else cnt
if __name__=='__main__':
cnt = gen_counter()
print(next(cnt))
print(next(cnt))
print(next(cnt))
print(next(cnt))
print(next(cnt))
cnt = gen_counter(5)
print(next(cnt))
... |
#
# PySNMP MIB module NBS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NBS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:07:17 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)... |
"""
Date Created: 2018-03-08
Date Modified: 2018-03-08
Version: 1
Contract Hash: 1aa965c53c373ef9d3be065bdb36b234cdcab66a
Available on NEO TestNet: False
Available on CoZ TestNet: False
Available on MainNet: False
Example:
Test Invoke: ... |
def test_calculator_add_returns_correct_result():
result = calc_add(2,2)
assert result == 4
# def calc_add(x,y):
# pass
# return x+y
# if isinstance(x, number_types) and isinstance(y, number_types):
# return x + y
# else:
# raise ValueError("Non-numeric inpu... |
def getGroupCount(line):
#print("Line "+line)
curSet = set(())
for curChar in line:
curSet.add(curChar)
#print("Set: "+str(curSet))
return len(curSet)
filename = "inputs\\2020\\input-day6.txt"
with open(filename) as f:
lines = f.readlines()
group = ""
sum = 0
for line in lines:
if ... |
def up_array(arr):
if not arr:
return None
else:
string = ''
for item in arr:
if not str(item).isdigit() or item > 9:
return None
else:
string += str(item)
total = []
for char in str(int(string)+1):
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 12 10:39:07 2020
@author: BK
"""
|
#
## https://leetcode.com/problems/longest-substring-without-repeating-characters/
#
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if s is None:
raise ValueError('Parameter should be a String.')
if len(s) < 2:
return len(s)
st... |
#@title Biblioteca de funções execute este trecho após o cabeçalho
# -*- coding: utf-8 -*-
def login_Twitter(chave_consumidor, segredo_consumidor, token_acesso, token_acesso_segredo):
#gerando objeto de autenticação
autenticacao = tw.OAuthHandler(chave_consumidor, segredo_consumidor)
#gerando tokens
autenticacao.s... |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Time, obj[3]: Coupon, obj[4]: Coupon_validity, obj[5]: Gender, obj[6]: Age, obj[7]: Maritalstatus, obj[8]: Children, obj[9]: Education, obj[10]: Occupation, obj[11]: Income, obj[12]: Bar, obj[13]: Coffeehouse, obj[14]: Restaurant20to50, obj[15]: Direct... |
###Database
#database typy Option:(mongodb, mysql, redis)
DB_TYPE = 'mongdb'
#database ip
DB_HOST = 'localhost'
#database port
DB_PORT = '1'
#username
#USERNAME = None
#passward
#PASSWARD = None
#database name
DB_DBNAME = 'quickspy'
###
|
x = 1
while True:
x = input("Number:\n> ")
if int(x) == 0:
break
|
#!/usr/bin/env python
# coding: utf-8
# # *section 4: Strings*
#
# ### writer : Faranak Alikhah 1954128
# ### 12.Check Subset:
#
#
# In[ ]:
num_testCase=int(input())
for i in range(num_testCase):
num_testCase1=int(input())
a=set(input().split())
num_testCase2=int(input())
b=set(input().split())
... |
# Exercise 105 - Parsing and Generating Dictionaries
'''Write a program that has a grades() function that can receive multiple grades
from students and will return a dictionary with the following information:
- Number of notes
- The highest grade
- The lowest grade
- The class average
- The situation (optional)
Als... |
# Test case for PR#183; print of a recursive PyStringMap causes a JVM stack
# overflow.
g = globals()
print(g)
|
###########################################################################
#
# Copyright 2019 Google Inc.
#
# 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
#
# https://www.apache.org/... |
def score_hand(player_one: list, player_two: list):
if len(player_one) != 7 or len(player_two) != 7:
raise RuntimeError('invalid hands')
# pairs
player_one_pairs = player_one[1]
player_two_pairs = player_two[1]
player_one_has_pairs = len(player_one_pairs)
player_two_has_pairs = len(pla... |
'''
Title : Zipped!
Subdomain : Built-Ins
Domain : Python
Author : codeperfectplus
Created : 17 January 2020
'''
# Enter your code here. Read input from STDIN. Print output to STDOUT
n, x = map(int, input().split())
sheet = []
for _ in range(x):
sheet.append(map(float, input().split()) )
for i in zi... |
class Solution:
def minIncrementForUnique(self, A: List[int]) -> int:
ans = 0
minAvailable = 0
A.sort()
for a in A:
ans += max(minAvailable - a, 0)
minAvailable = max(minAvailable, a) + 1
return ans
|
#
# PySNMP MIB module HPN-ICF-ARP-RATELIMIT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-ARP-RATELIMIT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:37:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... |
expected_output = {'current-eta-records': 0,
'excess-packets-received': 60,
'excess-syn-received': 0,
'total-eta-fnf': 2,
'total-eta-idp': 2,
'total-eta-records': 4,
'total-eta-splt': 2,
'total-packets-out-of-order': 0,
'total-packets-received': 80,
'total-packets-retransmitted': 0}
|
class SomeSingleton(object):
__instance__ = None
def __new__(cls, *args,**kwargs):
if SomeSingleton.__instance__ is None:
SomeSingleton.__instance__ = object.__new__(cls)
return SomeSingleton.__instance__
def __init__(self,f=0,y=0):
self.f = f
self.y= y
def ... |
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1:
return 1
hw = 0
while n != 0:
if n % 2 == 1:
hw += 1
n //= 2
return hw
|
annee = int(input (f"Saisissez une année\n"))
if (annee%4 != 0):
print ("ce n'est pas une annee bissextile")
else:
if (annee%100 == 0 and annee%400 != 0):
print ("ce n'est une annee bissextile")
else :
print ("c'est une annee bissextile")
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 5 03:41:18 2019
@author: srishti
"""
print("Hello")
|
# import os
# BANK_URL = os.environ['BANK_URL']
# TRANSACTION_URL = os.environ['TRANSACTION_URL']
# UNDERWRITER_URL = os.environ['UNDERWRITER_URL']
# USER_URL = os.environ['USER_URL']
# applications_url = f"http://{UNDERWRITER_URL}/applications"
# registration_url = f"http://{USER_URL}/users/registration"
# login_url... |
# noinspection PyShadowingBuiltins,PyUnusedLocal
def compute(x, y):
"""The problem sets the parameters as integers in the range 0-100.
We'll raise an exception if we receive a type other than int, or if the value
of that int is not in the right range"""
if type(x) != int or type(y) != int:
raise... |
for _ in range(int(input())):
a=input()
b=input()
s={}
ans=0
for i in range(26):
s[a[i]]=i+1
temp=[]
for j in b:
temp.append(s[j])
for k in range(len(temp)-1):
ans+=abs(temp[k]-temp[k+1])
print(ans) |
def isPalindrome(str):
result = False
if str == str[::-1]:
result = True
return result
print("Please enter a string: ")
x = input()
flag = isPalindrome(x)
if flag:
print(x, "is a Palindrome")
else:
print(x, "is NOT a Palindrome")
|
"""
Faça uma "fabrica decoradora" que retorna um decorador que decora funções com um único argumento. A fábrica deverá receber um argumento, um
tipo, e retornar um decorador em que a função verifica se o argumento passado é do tipo correto, senão levanta um TypeError.
"""
def decorador(função, tipo):
def nova_funç... |
"""
File: similarity.py
Name: Calvin Chen
----------------------------
This program compares short dna sequence, s2,
with sub sequences of a long dna sequence, s1
The way of approaching this task is the same as
what people are doing in the bio industry.
"""
def main():
"""
First, enter a long DNA sequence and... |
class Node:
def __init__(self, val):
self.val = val
self.next = None
def add(self, val):
if not self.next:
self.next = Node(val)
else:
self.next.add(val)
def remove(self, val):
if self.next.val == val:
self.next = self.next.next
... |
"""
@author: magician
@file: getattr_demo.py
@date: 2020/1/14
"""
class LazyDB(object):
"""
LazyDB
"""
def __init__(self):
self.exists = 5
def __getattr__(self, name):
value = 'Value for %s' % name
setattr(self, name, value)
return value
class LoggingLazyDB... |
# File: factorial_recursion.py
# Purpose: Example: FActorial using recursion
# Programmer: Amal Shehu
# Course: Practice
# Date: Sunday 28th August 2016, 11:10 PM
num = int(input("Enter a number")) # Convert to an int
def factorial(num):
if (num == 0):
return
else:
re... |
UNKNOWN_WORD = "<unk>"
embedding_dimension = 50
min_count = 5
window_size = 3
sample = 1e-3
negative = 5
vocab_size = None
train_words = None
# Special parameters
MIN_SENTENCE_LENGTH = 3 |
#!/usr/bin/python
DNB_YEARLY_PERCENTAGE = 2.10 / 100
DNB_MONTHLY_PERCENTAGE = DNB_YEARLY_PERCENTAGE / 12
DNB_FEE = 50
DNB_INITIAL_PAYMENT = 10000
NORDEA_YEARLY_PERCENTAGE = 2.15 / 100
NORDEA_MONTHLY_PERCENTAGE = NORDEA_YEARLY_PERCENTAGE / 12
NORDEA_FEE = 65
NORDEA_INITIAL_PAYMENT = 0
def months_until_paid_out(credit... |
text="ANCHE TU BRUTO FIGLIO MIO?";
s=4;
result="";
text=text.upper();
for i in range(len(text)):
c = text[i];
if(c.isupper()):
result+=chr((ord(c)+s-65)%26+65);
else:
result+=chr((ord(c)+s-97)%26+97);
print(result);
|
# -*- encoding: utf-8 -*-
'''
@project : LeetCode
@File : diameterOfBinaryTree.py
@Contact : 9824373@qq.com
@Desc :
@Modify Time @Author @Version @Desciption
------------ ------- -------- -----------
2020-03-10 zhan 1.0 None
'''
# Definition f... |
#!/usr/bin/env python
# -- coding: utf-8 --
"""
Copyright (c) 2019. All rights reserved.
Created by C. L. Wang on 2020/1/9
"""
dlatents_dir = 'latent_representations'
generated_dir = 'generated_images'
result_dir = 'results'
|
render = ez.Node()
aspect2D = ez.Node()
camera = ez.Camera(parent=render)
camera.y = -20
# Create collision shapes:
# Collision Sphere:
sphere = ez.collision.shapes.Sphere(0.25, parent=render)
sphere.parent = None
sphere.parent = render
# Collide from mask 2:
ez.collision.set_mask(sphere, ez.mask[2])
# Set what sph... |
while True:
senha=int(input('digite sua senha : '))
if senha==2:
print('acesso permitido')
break
else:
print('senha invalida, tente novamente') |
#!/usr/bin/env python3
def myFunc(x, y):
if not isinstance(x, (int, float)):
raise TypeError('x has wrong type')
if not isinstance(y, (int, float)):
raise TypeError('y has wrong type')
else:
print(x + y)
myFunc(1, 3)
|
phonetic_alphabet = {"alpha": "A", "adam": "A", "boy": "B", "bravo": "B", "charlie": "C",
"delta": "D", "david": "D", "echo": "E", "edward": "E", "foxtrot": "F", "frank": "F",
"golf": "G", "george": "G", "hotel": "H", "henry": "H", "india": "I", "ida": "I",
"aida": "I", "juliette": "J", "john": "J", "kilo":... |
#ref Exercício Python 094 - Unindo dicionários e listas do Curso em vídeo
dici = {}
lista = []
mulher = []
mmedi = []
m = 0
while True:
dici['nome'] = str(input(f'Qual o nome ? '))
dici['sexo'] = str(input(f'Qual o sexo do {dici["nome"]} ? '))
dici['idade'] = int(input(f'Qual a idade do {dici["nome"]} ? '))... |
def decrypt(ciphertext, s):
pltext = ""
for i in range(len(ciphertext)):
char = ciphertext[i]
if (char.isupper()):
pltext += chr((ord(char) - s-65) % 26 + 65)
else:
pltext += chr((ord(char) - s - 97) % 26 + 97)
return pltext
ciphertext = "EXXEG... |
# -*- coding: utf-8 -*-
"""
Programa que recebe como entrada dois arquivos:
O primeiro arquivo contém nomes de alunos
O segundo arquivo contém as notas dos alunos
E será gerado um terceiro arquivo contendo as médias.
"""
def acertarNotas(aluno,nota):
f1 = open(aluno,"r") # Abre no modo leitura o arquivo com os nome... |
###############################################################################
# Copyright (c) 2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory
# Written by Francesco Di Natale, dinatale3@llnl.gov.
#
# LLNL-CODE-734340
# All rights reserved.
# This file is part ... |
# A non-empty array A consisting of N integers is given.
# A permutation is a sequence containing each element from 1 to N once, and only once.
# For example, array A such that:
# A[0] = 4
# A[1] = 1
# A[2] = 3
# A[3] = 2
# is a permutation, but array A such that:
# A[0] = 4
# A[1] = 1
# ... |
# Sequência de Collatz mais longa
# Considere a seguinte sequência iterativa definida para os números inteiros positivos:
# \begin{align}
# n &\rightarrow n/2 (n\text{ é par}) \\
# n & \rightarrow 3n+1 (n\text{ é ímpar})
# \end{align}
# Usando a regra acima e começando com o número 13, geramos a seguinte sequência:
# 1... |
ITCH_BASE = "itch.io"
ITCH_URL = f"https://{ITCH_BASE}"
ITCH_API = f"https://api.{ITCH_BASE}"
# Extracts https://user.itch.io/name to {'author': 'user', 'game': 'name'}
ITCH_GAME_URL_REGEX = r"^https:\/\/(?P<author>[\w\d\-_]+).itch.io\/(?P<game>[\w\d\-_]+)$"
ITCH_BROWSER_TYPES = [
"games",
"tools",
"game-... |
"""
Tile providers.
This file is autogenerated! It is a python representation of the leaflet
providers defined by the leaflet-providers.js extension to Leaflet
(https://github.com/leaflet-extras/leaflet-providers).
Credit to the leaflet-providers.js project (BSD 2-Clause "Simplified" License)
and the Leaflet Provider... |
class Solution:
"""
@param words: the n strings
@param target: the target string
@return: The ans
"""
def the_longest_common_prefix(self, words, target):
# write your code here
ans = 0
for word in words:
same = 0
for j in range(0, len(target)):
... |
# list to csv
def listToCSV(obj):
csv = ''
for x in obj:
csv += str(x)
csv += ','
return csv[:-1]
# csv to list
def CSVToList(csv):
obj = csv.split(',')
li = []
for x in obj:
li.append(int(x))
return li
# 更新数据库
def update_db(obj, d):
if not isinstance(d, dict)... |
class DogeyError(Exception):
""" The base Dogey Exception, expect this as the main type of Dogey-specific errors such as InvalidCredentialsError. """
pass
class DogeyCommandError(Exception):
def __init__(self, command_name: str, message: str, *args):
""" The basic Dogey exception for commands, exp... |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
n=int(input())
o=dict(zip('tminp',[0,1,1,2,3]))
a=sorted(enumerate([input().split()for _ in[0]*n]),key=lambda x:(o[x[1][1][2]],x[0]))
for x in a:print(x[1][0])
|
sys_name = "XSS'OR"
sys_copyright = "@evilcos.me"
def sys(req):
return {
'sys_name': sys_name,
'sys_copyright': sys_copyright,
}
|
instrument_familes = {
'Strings': ['Guitar', 'Banjo', 'Sitar'],
'Percussion': ['Conga', 'Cymbal', 'Cajon'],
'woodwinds': ['Flute', 'Oboe', 'Clarinet']
}
class KeyError(Exception):
def __init__(self, key):
self.key = key
def __str__(self) -> str:
return f"Key {self.key} does not exist"
def print... |
#Ejercicio 1
'''
Ejemplo del profesor
Convertir esta funsión de O(n^2) a una funsión de O(n)
'''
def greatestNumber(array):
for i in array:
isIValTheGreatest = True
for j in array:
if j > i:
isIValTheGreatest = False
if isIValTheGreatest:
return i
'... |
def intersection(l1, l2):
res = [v for v in l1 if v in l2]
return res
def divide_into_primes(num, base=2, seq=None):
if seq is None:
seq = []
if num == 1:
return seq
for i in range(base, num+1):
if not num % i:
seq.append(i)
return divide_into_primes... |
#!/usr/bin/env python
# Copyright 2016-2021 Biomedical Imaging Group Rotterdam, Departments of
# Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obt... |
def check(cmd, mf):
m = mf.findNode('uuid')
if m:
return dict(expected_missing_imports=set(['netbios', 'win32wnet']))
|
s = set()
for _ in range(int(input())):
s.add(input())
print (len(s))
# one line solution
print ( len(set([str(input()) for _ in range(int(input()))])) )
# https://www.hackerrank.com/challenges/py-set-add/problem |
params = input().split(" ")
params = [int(param) for param in params]
if params[0] == params[1]:
for i in range(1, params[0] + 1):
print(input())
exit(0)
else:
all_gnomes = set(range(1, params[0] + 1))
remaining_gnomes = []
sorted = True
prev_gnome = -1
for _ in range(params[1]):... |
"""
Write a program that, given an ASCII binary matrix of 0's and 1's like this:
0000000000000000
0000000000000000
0000011001110000
0000001111010000
0000011001110000
0000011011100000
0000000000110000
0000101000010000
0000000000000000
0000000000000000
0000000000000000
Outputs the smallest cropped sub-matrix that still... |
pointer=-1
lock=0
def setSeq(data) :
if lock == 1:
exit(2)
globals()['pointer']=-1
globals()['data']=data.split(',')
globals()['lock']=1
def raw_input() :
globals()['pointer']+=1
try:
return data[pointer]
except IndexError:
exit(0)
def open(path,mode) :
exit(3)
|
result = 0
for i in range(1000):
if i%3==0 or i%5==0:
result += i
print(result) |
#!/usr/bin/python3
year = int(input("请输入年:"))
month = int(input("请输入月份:"))
day = int(input("请输入几号:"))
leapyear = [0,31,29,31,30,31,30,31,31,30,31,30,31]
normalyear = [0,31,28,31,30,31,30,31,31,30,31,30,31]
days = 0
i = month
if year%4 == 0:
for temp in range(0,i,1):
days += leapyear[temp]
print("今年是... |
"""
Get input from user via console or command line
-----------------------------------------------
Output: (string)
"""
name = input('What is your name? ')
print('Hello {}!'.format(name)) |
text = input()
sum = 0
for symbol in text:
if symbol == "a":
sum += 1
elif symbol == "e":
sum += 2
elif symbol == "i":
sum += 3
elif symbol == "o":
sum += 4
elif symbol == "u":
sum += 5
print(sum) |
"""
Remove Item
There are several methods to remove items from a list:
"""
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
|
debt = 95000
interest_percent = .059
yearly_salary = None
hourly_salary = 20
debt_repayment_percent = .2
debt_repayment_length = 0
work_days = 261
work_hours = 8
interest = 0
if yearly_salary and hourly_salary is not None:
if yearly_salary != hourly_salary * work_days * work_hours:
raise ValueError('only y... |
max_len = 79
str_plier = 2
foo = "Oh oh oh oh you don't know, Joe."*str_plier
curr_len = len(foo)
if curr_len > max_len:
print("Danger, Will Robinson!!!")
print("Your sentiment is {} ".format(curr_len-max_len)+"characters too long!")
else:
print("What a lovely sentiment!\n"+ foo+"\nIn only {} characters!".... |
#!/usr/bin/env python3
# compute nim values using negamax and a dictionary
# that holds values already computed RBH 2019
# version 2.0 December 2020 new features
# - verbose option, showing win/loss value once it is known
# - move initialization of the start position outside the main loop
# - tidying, e.g. pad... |
TEMPERATURE = 0x01
GAS = 0x02
VOLTAGE = 0x04
DELAY = 0x10
TEST_SUCCESS = 0x3F
ERROR_RELAY_OPEN = 0x04
ERROR_RELAY_CLOSED = 0x08
MODE_CONFIG = 0x80
MODE_RUN = 0x40
MODE_ERROR = 0xC0
MODE_TIMEOUT = 0x00
WRITE = 0x20
def print_status(state):
if(state&MODE_ERROR == MODE_ERROR):
print("ERROR MODE")
elif(state&MOD... |
# TODO write docs
class SceneDrawer(object):
def __init__(self, device, register):
self.device = device
self.background_color = "black"
self.entity_register = register
def draw(self, scene):
for entity in scene.entities:
if entity.drawer is not None:
... |
# -*- coding: utf-8 -*-
"""
Solution to Project Euler problem 16
Author: Jaime Liew
https://github.com/jaimeliew1/Project_Euler_Solutions
"""
def run():
n = pow(2,1000)
digitSum = sum(int(i) for i in str(n))
return digitSum
if __name__ == "__main__":
print(run())
|
"""
Loop.
The loop() function causes draw() to execute
repeatedly. If noLoop is called in setup()
the draw() is only executed once. In this example
click the mouse to execute loop(), which will
cause the draw() to execute repeatedly.
"""
y = 100
def setup():
"""
The statements in the setup() function
r... |
"""align.py
Aligning two sequences. The elements of the sequences are stings or string like
elements, it is not clear to me what interface for the class is expected in the
latter case.
Originally written by Alex Plotnick.
"""
def align(a, b, d=-5, s=lambda x,y: x==y, key=lambda x: x, gap=None):
"""Find the glo... |
content = '''package main
import (
"context"
"github.com/qsock/qim/lib/proto/ret"
)
type Server struct{}
func (*Server) Ping(ctx context.Context, req *ret.NoArgs) (*ret.NoArgs, error) {
return new(ret.NoArgs), nil
}'''
def gen(name, srv_dir) :
with open(srv_dir+"/handle.go", "w") as f:
f.write(conte... |
a = float(input('Primeiro Segmento: '))
b = float(input('Segundo Segmento: '))
c = float(input('Terceiro Segmento: '))
if (a + b) > c and (a + c) > b and (b + c) > a:
print('Os segmentos acima PODEM FORMAR um triângulo', end=' ')
if a == b == c:
print('EQUILÁTERO!')
elif a == b or a == c or c == b:
... |
# Source : https://leetcode.com/problems/symmetric-tree/
# Author : penpenps
# Time : 2019-07-09
# Revert right node firstly, then compare with left node
# Time Complexity: O(n)
# Space Complexity: O(n)
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self... |
#!/usr/bin/python3
class MyList(list):
"""extended version of list
"""
def print_sorted(self):
"""prints the list in ascending order
"""
copy = self[:]
copy.sort()
print(copy)
|
altura= float(input('Quanto de altura a parede possui?'))
largura= float(input('Quanto de largura a parede possui?'))
area= largura * altura
litros= area/2
print('Sua parede possui uma área de {},portanto, você precisará de {}litros de tinta para pinta-la'.format(area,litros)) |
#Desafio: Aprimore o desafio anterior, mostrando no final:
# A) A soma de todos os valores pares digitados.
# B) A soma dos valores da terceira coluna.
# C) O maior valor da segunda linha.
matriz = [[], [], []]
par = soma = maior = 0
for n in range(0, 3):
for i in range(0, 3):
num = int(input(f'Digite um ... |
"""
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
self.ans = None
... |
result = [
{0: 0, 1: 'var 1'},
{0: 0, 1: 'var 2'}
]
|
result = 0
"""
i = 0
while i < 4:
nr = int(input("Please give me the number: "))
result += nr
i += 1
print("The result of adding numbers is: ", result)
"""
for i in range(1000):
if (i%2 == 0):
print(i, " is even number")
print("The result of adding numbers is: ", resu... |
# Desafio 52 - Aula 13 : Programa que leia um numero e diga se é um numero PRIMO.
conta = 0
primo = int(input('Me diga um numero: '))
for c in range(1, primo+1):
if primo % c == 0 :
print('\033[34m', end='')
conta += 1
else:
print('\033[m', end='')
print(f'{c}', end=' ')
if c... |
# https://github.com/lord63-forks/python-patterns/blob/patch-3/lazy_evaluation.py
def lazy_property(fn):
"""Decorator that makes a property lazy-evaluated."""
attr_name = '_lazy_' + fn.__name__
@property
def _lazy_property(self):
if not hasattr(self, attr_name):
setattr(self, attr_... |
description = 'memograph readout'
group = 'optional'
devices = dict(
t_in_fak40 = device('nicos_mlz.devices.memograph.MemographValue',
hostname = 'memograph02.care.frm2',
group = 1,
valuename = 'T_in MIRA',
description = 'inlet temperature memograph',
fmtstr = '%.2F',
... |
class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
print(S[0])
stack = []
for i in S:
if i=="#":
if len(stack)==0:
continue
stack.pop()
else:
s... |
# Tram, Minh
# mqt0029
# 1001540029
# 2019-05-13
#---------#---------#---------#---------#---------#--------#
class InternalError( Exception ) : pass
class LexicalError( Exception ) : pass
class SemanticError( Exception ) : pass
class SyntacticError( Exception ) : pass
#---------#---------#---------#---------#----... |
def coord(x,y):
if x > 0 and y > 0:
i = "I"
elif x > 0 and y < 0:
i = "IV"
elif x < 0 and y < 0:
i = "III"
elif x < 0 and y > 0:
i = "II"
print(f"O ponto ({x:.0f}, {y:.0f}) pertence ao quadrante: {i}")
print(" ")
def main():
a = float(input("Digite um valor p... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class HardWare(object):
def power_on(self):
print('上电')
def bootloader(self):
print('bootloader 启动')
def power_off(self):
print('断电')
class OperatingSystem(object):
def load_kernel(self):
print('加载内核')
def load_ima... |
# -*- coding: utf-8 -*-
"""
Created on 31 Dec 2020 12:18:55
@author: jiahuei
"""
__version__ = "0.4.0"
|
#!/usr/bin/env python3
m = int(input())
if m < 100:
print("00")
elif m <= 5000:
print(str(m//100).zfill(2))
elif m <= 30000:
print(m//1000 + 50)
elif m <= 70000:
print((m//1000 - 30)//5 + 80)
else:
print(89) |
# to compute modular power
# Iterative Function to calculate
# (x^y)%p in O(log y)
def power(x, y, p) :
res = 1 # Initialize result
# Update x if it is more
# than or equal to p
x = x % p
while (y > 0) :
# If y is odd, multiply
# x with result
... |
"""Utility class for formatting Slack Messages."""
def wrap_slack_code(str):
"""Format code."""
return f"`{str}`"
def wrap_code_block(str):
"""Format code block."""
return f"```\n{str}\n```"
def wrap_quote(str):
"""Format quote."""
return f"> {str}\n"
def wrap_emph(str):
"""Format em... |
"""
Programa 2
Descrição: Este programa pede a entrada de dados pelo usuário
até que o dado seja do tipo adequado.
Autor: Nelson S. dos Santos
Versão: 0.0.1
"""
# Entrada
# Atribuição de variáveis: usuários do sistema
usuario1 = "nelson"
usuario2 = "joao"
usuario3 = "juan"
usuario4 = "nathan"
while... |
#print excepation information as a msg in program
try:
print(10/0)
except ZeroDivisionError as msg:
print("the type of error:",msg.__class__)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.