content stringlengths 7 1.05M |
|---|
def brute_force(numbers: list) -> int:
"""
Brute force for counting invertions
This aproach not work for a large n
:param numbers: list of numbers
:return: number of invertions
"""
count = 0
for i, number in enumerate(numbers[:-1]):
for compare in numbers[i+1:]:
if... |
#
# PySNMP MIB module TPLINK-PORTISOLATION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPLINK-PORTISOLATION-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:25:32 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... |
finput ='./AdventOfCode/Day05/invalid.txt'
finput = './AdventOfCode/Day05/valid.txt'
finput = './AdventOfCode/Day05/Input.txt'
seats =[]
def get_loc(seat):
directions = list(seat)
start = 0
stop = 0
if "R" in directions or "L" in directions:
stop = 7
else:
stop = 127
what = ... |
# Test data of test case A004
name = 'testuser01'
mail = 'tuser01@gmail.com'
passw = 'TestUser01'
title = 'User01-1.1'
what = 'User01 articel-1.1'
write = 'Ez User01 első bejegyzésének módosítása.'
tags = ['birs', "szőlő", 'mandula']
ta_nu = int(len(tags))
|
# TODO: получать курсы из базы
courses = {
'Python': 'https://stepik.org/course/67/promo\n'
'https://stepik.org/course/512/promo\n'
'https://www.coursera.org/specializations/python\n'
'https://docs.python.org/3/index.html\n',
'SQL': 'https://netology.ru/programs/sql-les... |
# coding: utf-8
# Copyright (C) 2019 Nguyen Ngoc Sang, <https://github.com/SangVn>
gamma = 1.4 # số mũ đoạn nhiệt
gamma_m1 = 0.4 # gamma - 1
R_gas = 287.052873836 # hằng số chất khí |
def votes(params):
for vote in params:
print("Possible option:" + vote)
votes(['yes', 'no', 'maybe']) |
def max_cluster(clusters):
size=len(clusters)
max_current = clusters[0]
max_finish_flag = 0
for i in range(0, size):
max_finish_flag = max_finish_flag + clusters[i]
if max_finish_flag < 0:
max_finish_flag = 0
elif (max_current < max_finish_flag):
... |
"""
Aula - 20
- Interactive Help
- docstrings
- Argumentos/ Parametros opcionais
- Escopo de variáveis
- Retorno de resultados
"""
# Interactive Help
# help(print)
# help(int)
# print(input.__doc__)
######################################################
# Docstrings
def contador(i, f, p):
"""
-> Faz uma c... |
class TaskDefinition:
""" The information necessary to run a task. Subclass with different
values for different performers and / parameters
The command will look something like:
ssh -i ~/.ssh/pemfile.pem ubuntu@ec2.24342.compute.amazon.com "ENV=XYZ performerscript.sh"
where performerscript.sh ru... |
#source: https://www.bilibili.com/video/av21540971/?p=13
class Node(object):
"""Node"""
def __init__(self, elem):
self.elem = elem
self.next = None
class SingleLinkedList(object):
"""single linked list"""
def __init__(self, node=None):
self.__head = node
def is_empty(self... |
#Write a function that accepts a filename(string) of a CSV file which contains the information about student's names
#and their grades for four courses and returns a dictionary of the information. The keys of the dictionary should be
#the name of the students and the values should be a list of floating point numbers ... |
report_config = {
'domain' : 'athagroup.in',
}
email_config = {
'email_server' : 'mail.groots.in',
'email_port' : 587,
'email_fromaddr' : 'kalpak@groots.in',
'email_toaddr' : ['email.reports@athagroup.in', 'sawkat.ali@athagroup.in', 'brijesh@groots.in', 'kalpak@groots.in'],
'email_... |
def fatorial(num=0, show=False):
"""Fatorial
Parâmetro:
num (int, optional): Valor para calcular o fatorial. Defaults to 0.
show (bool, optional): Valor booleano para saber se iremos
mostrar o processo de cálculo do fatorial ou não. Defaults to False.
Returns:
(int... |
v = int(input('Digite a velocidade que o carro passou (em Km/h): '))
multa = (v - 80) * 7
if v > 80:
print('O carro ultrapassou o limite permitido e o valor da multa é de {} reais'.format(multa))
else:
print('O carro passou dentro do limite de velocidade permitida.') |
# Default constants for the generic installation of `JAVA` on production systems.
# Please alter the below configurations to suit your environment needs.
BASE_URL = 'http://www.oracle.com'
JAVA_PACKAGE = 'server-jre'
JAVA_VERSION = 8
ARCHITECTURE_SET = 'linux-x64'
PACKAGE_EXTENSION = '.ta... |
[
{
'date': '2017-01-01',
'description': "Jour de l'an",
'locale': 'fr-FR',
'notes': '',
'region': '',
'type': 'NF'
},
{
'date': '2017-04-17',
'description': 'Lundi de Pâques',
'locale': 'fr-FR',
'notes': '',
'region': '... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Bit and bit array helpers
"""
def get_bit(data, bit_index):
"""
Get bit as integer at index bit_index from bytes array.
Order is from left to right, so bit_index=0 is MSB.
"""
if bit_index < 8 * len(data):
cur_byte = data[bit_index // 8]
... |
"""\
historybuffer.py : fixed-length buffer for a time-series of objects
Copyright (c) 2016, Garth Zeglin. All rights reserved. Licensed under the
terms of the BSD 3-clause license.
"""
class History(object):
"""Implement a fixed-length buffer for keeping the recent history of a
time-series of objects. This ... |
#!/usr/bin/env python
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2017 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ... |
#!/usr/bin/env python
# coding: utf-8
# # Min Operations
# Starting from the number `0`, find the minimum number of operations required to reach a given positive `target number`. You can only use the following two operations:
#
# 1. Add 1
# 2. Double the number
#
# ### Example:
#
# 1. For `Target = 18`... |
n1 = int(input('digite um numero: '))
d = n1 * 2
t = n1 * 3
r = n1 **(1/2)
print('o dobro de {} e {}\no triplo de {} e {}\na raiz quadrada de {} e {:.2f}.'.format(n1, d, n1, t, n1, r))
|
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... |
"""
Crie um programa que leia quanto dinheiro uma pessoa tem na carteira
e mostre quantos dólares ela pode comprar.
Considere US$1,00 = R$3,27
"""
real = float(input("Quantos reais tem na carteira? "))
dolar = real / 3.27
print(f'Com essa contia você pode comprar {dolar:.2f} Dólares. ')
|
# 30.01.2021
# level Beginner
# The point of the game is to find the water in the deser to escape Mr. Death
print('''
**********************************************************************
###
####
... |
class Solution:
def isPalindrome(self, x: int) -> bool:
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
elif x >= 10:
return str(x)[::-1] == str(x)
else:
return True
# [::-1] 一種反轉字串的 extended slice syntax
# https:/... |
def calc(should_print=False):
print("""
Name: LCM(Least common multiple)
Operation : LCM of 2 numbers
Inputs : a->int , b->int
Outputs: c=>lcm(a,b) ->int
Author : suyashsonawane
\n
""")
a = float(input("Enter a >>"))
b = float(input("Enter b >>"))
if(a > b ): # Use If con... |
"""
hello,world!
Version: 0.1
Author: gongyuandaye
"""
print('hello,world!')
#print('hello',',','world!')
print('hello','world','haha',sep=',',end='!\n')
print('hello, world',end='!\n')
|
def calculater(num1,num2,oprater):
if oprater=="add":
return num1+num2
elif oprater=="subtrate":
return num1-num2
elif oprater=="multiple":
return num1*num2
elif oprater=="divite":
return num1/num2
sum=calculater(3,4,"add")
print(sum)
print(calculater(4,4,"multiple")) |
john_wick = {"Drink": 12, "Popcorn": 15, "Menu": 19}
star_wars = {"Drink": 18, "Popcorn": 25, "Menu": 30}
jumanji = {"Drink": 9, "Popcorn": 11, "Menu": 14}
movie = input()
package = input()
count = int(input())
total_bill = 0
if movie == "John Wick":
total_bill = john_wick[package] * count
elif movie == "Star War... |
"""Try it yourself 9-5 """
class usuarios():
def __init__(self,first_name,last_name,age,job,company):
self.first_name = first_name.title()
self.last_name = last_name.title()
self.age = age
self.job = job
self.company = company
self.login_attempts = 0
def describ... |
books = ['frankenstein.txt', 'heartofdarkness.txt', 'prideandprejudice.txt']
for book in books:
with open(book) as content:
words = content.read()
lowers = words.lower()
amount = lowers.count('the')
print(amount) |
string = '0123456789012345678901234567890123456789'
cont = 10
controle = [string[i: i+cont] for i in range(0, len(string), cont)]
retorno = '.'.join(controle)
print(controle)
print(retorno) |
restconf_map = {
'openconfig_network_instance_network_instances_network_instance_protocols_protocol_bgp' :
'/restconf/data/openconfig-network-instance:network-instances/network-instance={name}/protocols/protocol={identifier},{name1}/bgp',
'openconfig_network_instance_network_instances_network_instance_p... |
class Vehicle:
licenseNumber = ""
serialCode = ""
face = ""
def turnOnAirCon(self):
print("Turn on : Air")
class Car(Vehicle):
def sayHello(self):
print("Hello World")
class Pickup(Vehicle):
pass
class Van(Vehicle):
pass
class EstateCar(Vehicle):
pass
car1 = Car()
car1.... |
"""
dataset/ 내의 각 지역 노선도 json 파일 경로를 관리합니다.
"""
BASE_DIR = "./dataset/%s.json"
DATA_PATH = {
# 수도권 노선도 정보
'capital': BASE_DIR % "capitalStations",
} |
naqt_basic_front = """
<h1>NAQT You Gotta Know</h1>
<div class='qcard'>
{{#Category}}<h2>{{Category}}</h2><br/>{{/Category}}
{{Prompt}}
<br/><br/>
<span class="answer-hidden">{{Answer}}</span>
</div>
<div class="source">
<span class="label">Source:</span> <span class="content">{{Source}}</span>
</div>
"""
naqt_bas... |
# -*- coding: utf-8 -*-
"""
Editor: Zhao Xinlu
School: BUPT
Date: 2018-04-04
算法思想:是否平衡二叉树
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isBalanced(self, root):
"... |
def is_prime(k: int) -> bool:
if isinstance(k, int) and k > 1:
for i in range(2, int((k / 2) + 1)):
if k % i == 0:
return False
else:
return True
else:
raise ValueError("Argument must be positive integer greater than 1")
def prime_unti... |
# Recursion Exercise 2
# Write a recursive function called list_sum that takes a list of numbers as a parameter.
# Return the sum of all of the numbers in the list.
# Hint, the slice operator will be helpful in solving this problem.
# Expected Output
# If the function call is list_sum([1, 2, 3, 4, 5]), then the functio... |
##
## readfile.py
##
def readFile(filename):
try:
f = open(filename)
fullFile = f.read()
print(fullFile.strip())
except FileNotFoundError as fileError:
print('Error Caught: ---> ', fileError)
finally:
print('WE ARE IN THE FINALLY BLOCK OF CODE!!!')
try:
f.close()
except UnboundLocalError as localErr... |
"""
Convex Contracts for Starfish
"""
__version__ = '0.0.2'
|
# Pairwise
# Given an array arr, find element pairs whose sum equal the second argument arg and return the sum of their indices.
# You may use multiple pairs that have the same numeric elements but different indices.
# Each pair should use the lowest possible available indices.
# Once an element has been used it cannot... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 27 19:09:43 2019
@author: florian
"""
i = 1
while (i<15):
print(i)
i+=1
print("--------")
suma = 0
for x in (2**p for p in range(1,7)):
print(x)
suma +=x
print("--------")
print(suma) |
"""
Problem Statement
The Jones Trucking Company tracks the location of each of its trucks on a grid similar to an (x, y) plane. The home office is at location (0, 0). Read the coordinates of truck A and the coordinates of truck B and determine which is closer to the office.
Input
Input contains 4 space separated inte... |
class NoScorePartException(BaseException):
"""ERROR! NO SCORE PART ID FOUND"""
class NoPartCreatedException(BaseException):
"""ERROR! PART NOT CREATED"""
class NoMeasureIDException(BaseException):
"""ERROR! NO MEASURE FOUND"""
class TabNotImplementedException(BaseException):
"""ERROR: this app... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class BitVector:
def __init__(self, bits, value):
self.bits = bits
self.mask = (2 ** self.bits) - 1
self.value = value
if self.value is not None:
assert self.mask & self.value == self.value
def __getitem__(self, index):
assert self.value is not None, "this... |
class IterableHelper:
@staticmethod
def find_single(iterable,func):
for item in iterable:
if func(item):
return item
@staticmethod
def select(iterable,func):
for item in iterable:
yield func(item) |
# These dictionaries are applied to the generated enums dictionary at build time
# Any changes to the API should be made here. attributes.py is code generated
# We are not code genning enums that have been marked as obsolete prior to the initial
# Python API bindings release
# We also do not codegen enums associated w... |
"""
Expanding Nebula
================
You've escaped Commander Lambda's exploding space station along with numerous escape pods full of bunnies.
But - oh no! - one of the escape pods has flown into a nearby nebula, causing you to lose track of it. You
start monitoring the nebula, but unfortunately, just a moment too... |
# --------------------------------------------------
# Copyright The IETF Trust 2011-2019, All Rights Reserved
# --------------------------------------------------
# Static values
__version__ = '0.6.1'
NAME = 'rfctools_common'
VERSION = [ int(i) if i.isdigit() else i for i in __version__.split('.') ]
|
#
# PySNMP MIB module H3C-EPON-DEVICE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/H3C-EPON-DEVICE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:09:03 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def append(self, data):
current = self.head
if self.head is None:
self.head = Node(data... |
"""
Car class to demonstrate Single Responsibility Principle.
The single responsibility principle says that a class should be responsible for just one thing.
"""
# Before
class Car:
def __init__(self, name):
self.name = name
def get_car_name(self):
return self.name
def save_car(self, fil... |
SELECTION_TESTS = {
'id': 'S',
'caption': 'Selection Tests',
'checkAttrs': True,
'checkStyle': True,
'styleWithCSS': False,
'Proposed': [
{ 'desc': '',
'command': '',
'tests': [
]
},
{ 'desc': 'selectall',
'command': 'sele... |
if __name__ == '__main__':
number = "73167176531330624919225119674426574742355349194934969835203127745063262395783180169848018694788518438586156078911294949545950173795833195285320880551112540698747158523863050715693290963295227443043557668966489504452445231617318564030987111217223831136222989342338030813533627661... |
with open ( "data1.txt" ) as f:
data = f.readline()
f.close()
print ( "->{}<-".format(data))
|
'''
Lista 1 - Exercício 10
Escreva um programa para calcular a redução do tempo de vida de um fumante. Pergunte a quantidade de cigarros fumados por dia e quantos anos ele já fumou. Considere que um fumante perde 10 minutos de vida a cada cigarro, calcule quantos dias de vida um fumante perderá. Exiba o total de dias.
... |
self.description = "Query ownership of file in root"
sp = pmpkg("dummy")
sp.files = ["etc/config"]
self.addpkg2db("local", sp)
self.filesystem = ["config"]
self.args = "-Qo /config"
self.addrule("PACMAN_RETCODE=1")
|
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class ActiveOperationEnum(object):
"""Implementation of the 'ActiveOperation' enum.
Specifies the active operation on the Node if there is one.
'kNone' specifies that there is no active operation on the Node.
'kDestroyCluster' specifies that the ... |
CACHE={}
def battle(hp, bosshp, boss_damage, mana, shield_turns=0, poison_turns=0, recharge_turns=0, mana_spent=0, player_turn=True):
armor = 7 if shield_turns else 0
poison = 3 if poison_turns else 0
recharge = 101 if recharge_turns else 0
assert poison_turns <= 6
assert recharge_turns <= 5
a... |
#!/usr/bin/env python
# This is a single-line comment
print("Comments are useful.")
"""
This is a multi-line Comment
which spans many lines
"""
print("You should comment your code.")
|
class Fish:
small_fish ='''${33}
${333}
${333}
__
\/ o\\
/\\__/
'''
|
# LeetCode 469. Convex Polygon
# Given a list of points that form a polygon when joined sequentially, find if this polygon is convex (Convex polygon definition).
# Note:
# There are at least 3 and at most 10,000 points.
# Coordinates are in the range -10,000 to 10,000.
# You may assume the polygon formed by given p... |
#Antonio Karlo Mijares
class BaseCharacter (object):
def __init__(self):
self.health = 100
def printName (self):
print (self.name)
class NonPlayable (BaseCharacter):
pass
class Enemy (NonPlayable):
def __init__(self):
self.attack -= 5
class Friend (NonPlayable):
pass
cla... |
# Discriminator
# Probably a VGG16 or VGG19 for Simple Image Classification pretrained on ImageNet
# Discriminator
# Probably a VGG16 or VGG19 for Simple Image Classification pretrained on ImageNet
class Discriminator(nn.Module):
def __init__(self, c1_channels=64, c2_channels=128, c3_channels=256,
... |
# Program : Check whether the number is positve or negative number.
# Input : number = -3
# Output : Negative
# Explanation : -3 is less than zero, so it is a negative number.
# Language : Python3
# O(1) time | O(1) space
def positive_or_negative(number):
# If the number is equal to zero, then it is neither posit... |
"""
Exercício 3
Escreva um programa que receba um número inteiro na entrada, calcule e imprima a soma dos dígitos deste número na saída
Exemplo:
"""
if __name__ == '__main__':
num = int(input('Digite um número inteiro: '))
soma = 0
while True:
num, resto = divmod(num, 10)
soma += resto
... |
def summarize(di, n_pa=8):
print("{} keys and {} unique values:\n".format(len(di), len(set(di.values()))))
for ke, va in list(di.items())[:n_pa]:
print("{} => {}".format(ke, va))
print("...")
|
# This pythong script contains a function to lookup product prices for passed products and a function sum these up to return the total.
#
# This is a dictionary of product prices. It is not part of any specific function below and can therefore be accessed from anywhere in the script.
productPriceDict = {'apples':1.50,'... |
class Solution:
def subsets(self, nums):
# res=[[]]
# self.dfs([],res,nums)
# return res
return self.recurse(nums)
# def dfs(self,path,res,nums):
# for n in nums:
# if n not in path:
# res.append(path+[n])
# if len(path)+1<len(... |
#
# PySNMP MIB module CONTIVITY-ID-V1-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CONTIVITY-ID-V1-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:10:59 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
frase = str(input('\033[1;93mDigite uma frase: ')).strip().upper()
palavras = frase.replace(' ', '')
inverso = palavras[::-1]
"""for letra in range(len(palavras) - 1, -1, -1):
inverso += palavras[letra]"""
print('\033[96mO inverso de {} é {}!'.format(palavras, inverso))
if inverso == palavras:
print('\n\033[92m... |
"""
Enunciado
Reto 1: Impuestos sobre el salario
Un empleado desea conocer a cuánto dinero equivalen los descuentos
al pagar los impuestos exigidos por la ley en relación con los pagos
que la compañía para la que trabaja le realiza mensualmente.
Se ha firmado un contrato que le permite trabajar 38 horas semanales.
Con... |
# Approach 1:
def Second_Largest(Arr):
Arr.remove(max(Arr))
return max(Arr)
a = []
n = int(input("How Many Elements: "))
print("Enter The Elements: ")
for i in range(0, n):
element = int(input())
a.append(element)
print(f"Second Largest: {Second_Largest(a)}")
# Approach 2:
def Se... |
class DOVError(Exception):
"""General error within PyDOV."""
pass
class OWSError(DOVError):
"""Error regarding the OGC web services."""
pass
class LayerNotFoundError(OWSError):
"""Error that occurs when a specific layer could not be found."""
pass
class MetadataNotFoundError(OWSError):
... |
# Variables to be used for developing and testing the program
INTERVALS = [[1, 2], [1, 7], [8, 11], [11, 14],
[8, 10], [32, 36], [33, 35], [105, 108]]
"""
INTERVALS = [[1, 2], [1, 7], [8, 11], [11, 14],
[8, 10], [32, 326], [33, 345], [105, 1038], [
1, 2], [1, 7], [8, 11], [1... |
with open("2021-12-01.txt") as input_file:
increasing_lines = 0
last_ints = [None, None, None]
for input_line in input_file:
if (None not in last_ints):
last_ints_sum = sum(last_ints)
else:
last_ints_sum = None
input_int = int(input_line)
_ = ... |
class instagram():
scheme = 'https'
url = 'instagram.com'
headers = {'user-agent': 'Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 1.1.4322)'}
def getHandleUrl(self, handle):
return "{}://{}/{}".format(instagram.schem... |
jibun, kimi, kanojyo = 5, 3, 2
if (kimi < jibun and jibun < kanojyo):
print(jibun)
elif (kanojyo < jibun and jibun < kimi):
print(jibun)
elif (kanojyo < kimi and kimi < jibun):
print(kimi)
elif (jibun < kimi and kimi < kanojyo):
print(kimi)
else:
print(kanjyo)
|
RUNNING_PODS = """
NAME READY
STATUS RESTARTS AGE\n
anaconda-enterprise-ap-auth-68c4f864f8-x8trs 1/1
Running 0 30m\n
anaconda-enterprise-ap-auth-api-6cb6f9595d-9c774 1/1
Running 0 30m\n
anacond... |
# 31. Next Permutation
'''
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place and use only constant... |
# WARNING: Do not edit by hand, this file was generated by Crank:
#
# https://github.com/gocardless/crank
#
class PayerAuthorisation(object):
"""A thin wrapper around a payer_authorisation, providing easy access to its
attributes.
Example:
payer_authorisation = client.payer_authorisations.get()
... |
for _ in range(int(input())):
n=int(input())
ans=0
while n>0:
ans+=n
n=n//2
print(ans) |
def convert(numerator, denominator):
integer = numerator // denominator
numerator -= integer * denominator
if 0 == numerator:
return str(integer)+"."
elif len(str(numerator/denominator)) <= 10:
return str(integer)+"."+str(numerator/denominator)[2:]
else:
dlist = []
n... |
nome = str(input('nome do aluno: '))
n1 = float(input('primeira nota do aluno: '))
n2 = float(input('segunda nota do aluno: '))
n3 = float(input('terceira nota do aluno: '))
n4 = float(input('quarta nota do aluno: '))
m = (n1 + n2 + n3 + n4) / 4
print('a media de {} e {} é igual a {}'.format(n1, n2, m))
if m >= 5.0:
... |
class User:
def __init__(self, id_, name, email, photo):
self.id = id_
self.name = name
self.email = email
self.photo = photo
@classmethod
def from_dict(cls, dict_):
return User(
id_=dict_["id"],
name=dict_["name"],
email=dict_["em... |
class Solution:
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
for i in range(n // 2):
for j in range(i, n - 1 - i):
tmp = matrix[i][j]
... |
# This file is Copyright 2007, 2009 Dean Hall.
#
# This file is part of the Python-on-a-Chip program.
# Python-on-a-Chip is free software: you can redistribute it and/or modify
# it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE Version 2.1.
#
# Python-on-a-Chip is distributed in the hope that it will be use... |
# Difficulty Level: Beginner
# Question: Calculate the sum of the values of keys a and b .
# d = {"a": 1, "b": 2, "c": 3}
# Expected output:
# 3
# Program
d = {"a": 1, "b": 2, "c": 3}
print(d["a"] + d["b"])
# Output
# shubhamvaishnav:python-bootcamp$ python3 17_dictionary_items_sum_up.py
# 3
|
class PizzaGrid:
def __init__(self, rows, cols, toppings):
n = len(toppings)
assert(rows * cols == n)
self._num_mushrooms = toppings.count('M')
self._num_tomatoes = toppings.count('T')
self._rows = rows
self._cols = cols
self._rowcols = []
k = 0
... |
# -*- coding: utf-8 -*-
# ██████╗ ██████╗ ██████╗ ██████╗ ███╗ ███╗ █████╗ ███████╗████████╗███████╗██████╗ ██████╗ ██╗ ██╗
# ██╔══██╗██╔═══██╗██╔══██╗██╔═══██╗████╗ ████║██╔══██╗██╔════╝╚══██╔══╝██╔════╝██╔══██╗██╔══██╗╚██╗ ██╔╝
# ██████╔╝██║ ██║██████╔╝██║ ██║██╔████╔██║███████║███████╗ ██║ █████╗ ██... |
"""
Given an unsorted array of size n.
Array elements are in the range from 1 to n.
One number from set {1, 2, …n} is missing and one number occurs twice in the array.
Find these two numbers.
"""
def RepMiss(arr, n):
Map = {}
max = len(arr)
for i in arr:
if not i in Map:
Map[i] = Tr... |
"""
Clausius desing to create common models accorss the messaging and database services
4 main components
- Models
- Messangers
- Storage
- Configuration
""" |
#!/usr/bin/python3
# this script reads gene annotations from the UniProtKB database
input_file = "./data/idmapping_selected.tab"
output_file = "pmid_annotations.txt"
results_file = "annotation_counts_per_gene.txt"
print("Processing UniProtKB annotations")
# open the data input file
f = open(input_file, 'r')
pmids_... |
'''
Created on Sep 27, 2019
@author: ballance
'''
class CompoundSuite():
def __init__(self, name=None):
self.name = name
self.suite_l = []
pass
def add_compound_suite(self, suite_file):
pass
def add_suite(self, suite_file):
pass
|
#!usr/bin/env python3
def character_frequency(filename):
"""counts the frequency of each character in the given file"""
#first try open the file
characters={}
try:
f=open(filename)
except FileNotFoundError: # first most detailed exception
print("File not found")
characters=... |
def actg_numbers(sub_gene):
numbers = [0, 0, 0, 0]
for letter in sub_gene:
if letter == 'A':
numbers[0] += 1
elif letter == 'C':
numbers[1] += 1
elif letter == 'T':
numbers[2] += 1
elif letter == 'G':
numbers[3] += 1
return nu... |
"""
Useful items that allow the observable pattern to be implemented on a class.
"""
class _ListenerInfo:
"""
Information on listeners.
Listeners is the set of listeners which should be informed on trigger.
last_value: the last value that was sent to the listeners
pre_trigger_function: an optional... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.