content stringlengths 7 1.05M |
|---|
'''
Useful for validation: http://www.attotron.com/cybertory/analysis/trans.htm
'''
class Translator:
rna_codons = {
"UUU": "F", "CUU": "L", "AUU": "I", "GUU": "V",
"UUC": "F", "CUC": "L", "AUC": "I", "GUC": "V",
"UUA": "L", "CUA": "L", "AUA": "I", "GUA": "V",
"UUG": "L", "CUG": "L"... |
class ProjectLocation(Instance,IDisposable):
""" An object that represents a named location in a project. """
def Dispose(self):
""" Dispose(self: Element,A_0: bool) """
pass
def Duplicate(self,name):
"""
Duplicate(self: ProjectLocation,name: str) -> ProjectLocation
Generate a copy of this p... |
class NotificationBackend:
async def send_token_to_customer(
self,
chat_id: str,
username: str,
token: str
):
raise NotImplementedError()
|
'''
A python program to find gcd of two number.
GCD=greatest common divisor
a=30
b=2
30=1*2*3*5
2=1*2
GCD=multiplication of common factors
=1*2
=2
gcd1 is based on euclidean algorithm.
'''
def gcd1(a,b):
if not a:return b
return gcd1(b%a,a)
def gcd2(a,b):
while b:a,b=b,a%b
return a
pri... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"V": "V.ipynb",
"build_hierplane_tree": "V.ipynb",
"get_boto_session": "aws_utils.ipynb",
"write_json_to_s3": "aws_utils.ipynb",
"write_df_to_s3": "aws_utils.ipynb",
... |
"""
Created on Sun Aug 8 19:27:44 2021
@author: DW
"""
|
def getPostFlopBet(game_state, current_player):
cardsNumber = len(game_state['community_cards'])
bet = game_state['current_buy_in'] - current_player['bet']
stack = current_player['stack']
minRaise = game_state['minimum_raise']
table = {
1: bet,
2: bet,
3: (1/64 * stack),
4: (1/32 * stack),
... |
N, M, C = map(int, input().split())
B = list(map(int, input().split()))
result = 0
for i in range(N):
t = C
A = list(map(int, input().split()))
for j in range(M):
t += A[j] * B[j]
if t > 0:
result += 1
print(result)
|
n1 = float(input('Digite o primeiro número: '))
n2 = float(input('Digite o segundo número: '))
n3 = float(input('Digite o terceiro número: '))
maior = n1
if n2 > n1 and n2 > n3:
maior = n2
elif n3 > n2 and n3 > n1:
maior = n3
print(f'O maior número dentre os três é {maior}')
menor = n1
if n1 > n2 and ... |
def rate_trader_balances(row):
# How much BASE plus RAI in BASE is held
traders = row['rate_traders']
rp = row['target_price']
total_base = 0
base = 0
total_rai_base = 0
for trader in traders:
total_base += trader['base_balance']
total_base += trader['rai_balance'] * rp
... |
'''
2520 is the smallest number that can be divided by
each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly
divisible by all of the numbers from 1 to 20?
'''
# VERSION 1 : Works 'great' for 10 but too slow for 20
def smallest_multiple(number):
mult = 0
... |
class SnakeHitsBoundaryError(Exception):
def __init__(self):
super().__init__("Snake hits boundary!")
class SnakeHitsItselfError(Exception):
def __init__(self):
super().__init__("Snake hits itself!")
class SnakeSpeedZeroError(Exception):
def __init__(self):
super().__init__("Snak... |
cwarning_uniq = dict()
class CWarning:
def __init__(self, id, desc, source, place):
self.id = id
self.desc = desc
self.source = source
self.place = place
def write_to_book(self, worksheet, row):
worksheet.write(row, 0, self.id)
worksheet.write(row, 1, self.desc... |
PROFILES = {
"SCH" : { # default display profile for Schönherz Matrix
"profile" : "sch",
"width" : 32,
"height" : 26,
"ratio" : 1.5,
"speed" : 100,
"default" : "0",
"background-color" : "#000000",
"stage-color" : "#111111",
"border-color" : "#cccccc",
"skybox-color" : "#0f1114",... |
class Crunch42Exception(Exception):
...
__all__ = ("Crunch42Exception",)
|
f = open('12.input')
input = f.readlines()
f.close()
register = {}
for line in input:
id = line[:line.index('<')-1]
links = line[line.index('>')+1:].strip()
register[id] = links.split(', ')
id0groups = set([])
def recursiveAdd(key):
if key not in register:
return
if key in id0groups:
return
if key not in... |
alpha = "abcdefghijklmnopqrstuvwxyz"
i = 0
while i < 26:
i += 1
for lettre in alpha:
print (alpha[i])
|
"""SINGLY LINKED LIST"""
class Node:
def __init__(self, data=None, next=None) -> None:
self.data = data
self.next = next
class SinglyLinkedList:
def __init__(self) -> None:
self.head = None
def visualizeList(self):
if self.head is None:
print... |
# entrada de dados
cent = int(input('Digite o valor em centimetros: '))
# calculo de transformação centimetros em metros
metros = cent/100
# saída de dados
print('centimentos: ', cent, 'cm -- metros: ', metros, ' m') |
# NOTE that: this class contains all the changable parameters
class Config:
lr = 0.001
epochs = 100
batch_size = 32
display_epoch = 1
save_model_path = r'D:\\scripts\\models\\'
opt = Config()
|
#
# PySNMP MIB module CISCOSB-Redistribute (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-Redistribute
# Produced by pysmi-0.3.4 at Mon Apr 29 18:07:19 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
class Beam(object):
def __init__(self, beam_size):
self.beam_size = beam_size
self.candidates = []
self.scores = []
def step(self, prob, prev_beam, f_done):
pre_score = prob.new(prev_beam.scores)
score = prob + pre_score.unsqueeze(-1).expand_as(prob)
nbest_score... |
INSTALLED_APPS = [
'cacheops',
'django.contrib.auth',
'django.contrib.contenttypes',
'tests',
]
AUTH_PROFILE_MODULE = 'tests.UserProfile'
# Django replaces this, but it still wants it. *shrugs*
DATABASE_ENGINE = 'django.db.backends.sqlite3',
DATABASES = {
'default': {
'ENGINE': 'django.db.... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def partition(head: ListNode, x: int) -> ListNode:
l1 = l1_pre = ListNode(0)
l2 = l2_pre = ListNode(0)
while head :
if head.val < x :
l1.next = ListNode(head.val)
l1 = l1.next
e... |
""" This module implements filter transformer classes for different backends. These
classes typically parse the filter with Lark and produce an appropriate query for the
given backend.
"""
|
class Stop(RuntimeError): pass
def stop():
raise Stop()
|
def reverse_array(a):
n = len(a)
for i in range(n // 2):
a[i], a[n - i - 1] = a[n - i - 1], a[i]
return a
if __name__ == '__main__':
print(reverse_array([1,2,3,4,5,6])) |
#Write a Python program to test whether a passed letter is a vowel or no
def isvowel(letter):
vowels = 'aeiou'
if letter.lower() in vowels:
return True
else:
return False
print(isvowel('a'))
print(isvowel('c'))
print(isvowel('84')) |
class AutoDeployAgentException(Exception):
"""Basic exception"""
def __init__(self, msg=None):
if msg is None:
msg = "Unexpected error was triggered"
super(AutoDeployAgentException, self).__init__(msg)
class NoErrorException(AutoDeployAgentException):
"""No error whi... |
# Time: O(logn) = O(1)
# Space: O(1)
class Solution(object):
# @param {integer} num
# @return {boolean}
def isUgly(self, num):
if num == 0:
return False
for i in [2, 3, 5]:
while num % i == 0:
num /= i
return num == 1
|
GREETING = '''Привет! Я — поисковый робот TOPCREW 🕵️♂️
Я могу бесплатно искать вакансии по всем крюингам в мире. Заполни свой профиль и подпишись на интересующие тебя вакансии. Как только появится интересное для тебя предложение — я сразу же об этом напишу ✅
Ты можешь общаться со мной с помощью кнопок меню внизу эк... |
# Copyright 2019 VMware, Inc.
# SPDX-License-Indentifier: Apache-2.0
class TemplateEngineException(Exception):
"""
Exception class for template engine exceptions.
"""
pass
class InvalidReferenceException(TemplateEngineException):
"""
Exception class for invalid parameter reference.
"""
... |
'''
Created on 2015年12月3日
@author: Darren
'''
class GraphNode(object):
'''
classdocs
'''
def __init__(self,value=None):
'''
Constructor
'''
self.value=value
self.neighbor=set()
class Graph(object):
def __init__(self):
self.Nodes=set()
... |
def write_xyz(filename, points, verbose=False):
"""
Writes the points as xyz-format file. The xyz-format file can be opened and displayed for instance
in PyMol
:param filename: string
Filename the cartesian coordinates in points are written to as xyz-format file
:param points:
:param ver... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (C) 2005-2016 UC Mobile Limited. All Rights Reserved
# File : settings.py
#
# Creation : 2015/12/11 16:53
# Author : shufeng.lsf@ucweb.com
################################################... |
# What is Variable ?
# A variable is a name given to a memory location in a program. For example
# Variables - Container to store a Value
'''Keywords - Reserve Words in Python [ def,class-object orinating programming ,
false, keyword, is , in, true , and as , assert , del, if, else, or, pass, try , while,
,async, ... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
result = ListNode()
p = result
h = head
... |
hours = int(input()) * 60
minutes = int(input())
all = hours + minutes + 15
hours = all // 60
minutes = all % 60
if hours > 23:
hours = hours - 24
if minutes < 10:
print (f"{hours}:0{minutes}")
else:
print (f"{hours}:{minutes}")
|
DEFAULT_PLUGINS = [
"kolibri.plugins.coach",
"kolibri.plugins.default_theme",
"kolibri.plugins.device",
"kolibri.plugins.epub_viewer",
"kolibri.plugins.html5_viewer",
"kolibri.plugins.facility",
"kolibri.plugins.learn",
"kolibri.plugins.media_player",
"kolibri.plugins.pdf_viewer",
... |
n = list(str(input("Digite a expressão: ")))
if n.count("(") == n.count(")"):
print("A expressão está correta!")
else:
print("A expressão não está correta!") |
def pytest_addoption(parser):
parser.addoption("--assays", action="store", default="")
parser.addoption("--test_dir", help='test_dir', action="store", default="/SGRNJ03/randd/user/zhouyiqi/multi_tests/")
def pytest_generate_tests(metafunc):
# This is called for every test. Only get/set command line argume... |
#
# PySNMP MIB module ARTEM-COMPOINT-BLD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ARTEM-COMPOINT-BLD-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:25:40 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... |
def on_chat(num):
pass
def on_chat2(num: number):
pass |
#
# @lc app=leetcode id=17 lang=python3
#
# [17] Letter Combinations of a Phone Number
#
# https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/
#
# algorithms
# Medium (48.78%)
# Likes: 5494
# Dislikes: 499
# Total Accepted: 775.5K
# Total Submissions: 1.6M
# Testcase Example: '"23"'
... |
# 2 x 2 grid, has 3 choice points at 0,1,2
# At 0, there are 2 choices, at 1 there are 2 choices for both the options of 1 i.e. 0,1 and 1,0
# At level 2, there are no options 0,2 can only move in one way, 1,2 can also move in one way etc
# Therefore the options are a multiple of 2 x array size
# Let's try this
if _... |
# Кое-какие настройки для бота
# id тех, кто может менять карму без ограничений
gods = [55910350]
# Бот в текущей сборке расчитан на работу с heroku.com
# Это ссылка на приложение, для установления вебхука
url = "https://khabarabot.herokuapp.com/bot"
# Имя бота (то, которое @Karmator_bot)
bot_name = "khabara_bot"
# ... |
def handle_response(response):
if not response.status_code:
raise Exception("Response is not valid")
if response.status_code in range(200, 300):
return response.json()
elif response.status_code < 500:
raise Exception(response.json())
else:
raise Exception("Unknown ... |
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2016-Present Datadog, Inc.
API_SURFACE_PATH = "dd-sdk-android/apiSurface"
NIGHTLY_TESTS_DIRECTORY_PATH ... |
# -*- coding:utf-8 -*-
logger = logging.getLogger('M3ARPG')
class User:
pass
|
#!/usr/bin/env python3
"""
Sorting List Example 1
"""
# Get a sorted copy of a List
my_list = [9, 1, 8, 2, 7, 6, 3, 5, 4, 0]
sorted_list = sorted(my_list)
print('Original List: ', my_list)
print('Sorted List: ', sorted_list)
# Sort the original List
my_list.sort()
print('Original List (sorted): ', my_list)
# So... |
class Solution:
def maxSubArray(self, ls):
if len(ls) == 0:
raise Exception("Array empty") # should be non-empty
runSum = maxSum = ls[0]
i = 0
start = finish = 0
for j in range(1, len(ls)):
if ls[j] > (runSum + ls[j]):
runSum = ls[j... |
COUNTRIES = {
"United States": 5,
"Argentina": 29,
"Australia": 25,
"Austria": 54,
"Bahrain": 145,
"Bangladesh": 47,
"Belgium": 34,
"Bosnia-Herzegovina": 174,
"Botswana": 163,
"Brazil": 32,
"Bulgaria": 70,
"Canada": 6,
"Chile": 27,
"China": 37,
"Colombia": 122... |
# Uses python3
def edit_distance(s, t):
#write your code here
m , n = len(s) , len(t)
dp=[[0 for i in range(n+1)] for j in range(m+1)]
for i in range(m+1): dp[i][0]=i
for j in range(n+1): dp[0][j]=j;
for i in range(1,m+1):
for j in range(1,n+1):
dp[i][j]=min(dp[i-1][j-1] + (0 if s[i-1]==t[j-1] else 1) , \
... |
c1_list = list(map(int, input().split()))
c2_list = list(map(int, input().split()))
c3_list = list(map(int, input().split()))
for a1 in range(0, 101):
for a2 in range(0, 101):
for a3 in range(0, 101):
b1 = c1_list[0] - a1
b2 = c1_list[1] - a1
b3 = c1_list[2] - a1
... |
class _GTF(object):
def __init__(self, path):
""""""
self.file = open(path, "r")
self.header={}
def read(path):
""""""
... |
class ListViewAlignment(Enum,IComparable,IFormattable,IConvertible):
"""
Specifies how items align in the System.Windows.Forms.ListView.
enum ListViewAlignment,values: Default (0),Left (1),SnapToGrid (5),Top (2)
"""
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==>... |
class DrawFromEmptyServer(Exception):
"""Attempted to draw from an empty R&D (corp loses)."""
class ChoiceRequiredError(Exception):
"""A choice is required for."""
class InvalidPaymentChoice(Exception):
"""An invalid payment choice has been made."""
class CostNotSatisfied(Exception):
"""Required costs are... |
"""
Exceptions are errors
"""
def exceptionHandling():
try:
a = 10
b = 20
c = 0
d = (a + b) / c
print(d)
except:
print("In the except block")
else:
print("Because there was no exception, else is executed")
finally:
print("Finally, always ... |
"""
问题描述:给定一个非负整数N,返回N!结果的末尾为0的数量.
例如:
3!=6,结尾的末尾没有0,返回0. 5!=120,结果的末尾有1个0,返回1.
1000000000!,结果的末尾有249999998个0,返回249999998.
进阶题目:
给定一个非负整数N,如果用二进制数表达N!的结果,返回最低位的1在
哪个位置上,认为最右的位置为位置0.
例如:1!=1,最低位的1在0位置上.2!=2,最低位的1在1位置上.1000000000!,
最低位的1在999999987位置上.
"""
class AssignedNumFinder:
@classmethod
def get_0_num(cls... |
def linear_truth():
#truth1
tree = Tree(name='N1', size=3)
node2 = tree.create_node('N2',tree.root,2)
node3 = tree.create_node('N3',node2,3)
node4 = tree.create_node('N4',node3,3)
return tree
def linear_branching_truth():
#truth2
tree = Tree(name='N1', size=3)
node2 = tree.create_node('N2',tree.root,2)
node... |
def map_inputs(user, all_data, data_name, id_list):
text_input = all_data[data_name]
capitalized = text_input.upper()
return {id_list[0]:capitalized}
|
class TSGError(Exception):
pass
class FailedToParse(TSGError):
pass
|
"""
>>> clip('banana ', 6)
'banana'
>>> clip('banana ', 7)
'banana'
>>> clip('banana ', 5)
'banana'
>>> clip('banana split', 6)
'banana'
>>> clip('banana split', 7)
'banana'
>>> clip('banana split', 10)
'banana'
>>> clip('banana split', 11)
'banana'
>>> clip('... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Events',
'version': '1.1',
'category': 'Marketing/Events',
'sequence': 140,
'summary': 'Publish events, sell tickets',
'website': 'https://www.odoo.com/page/events',
'description': ... |
# Certain parameters
R = 8.314 # gas constant
T_F = 25 + 273.15 # feed temperature
E_a = 8500.0 # activation energy
delH_R = 950.0 * 1.00 # sp reaction enthalpy
A_tank = 65.0 # area heat exchanger surface jacket 65
k_0 = 7.0 * 1.00 # sp reaction rate
k_U2 = 32.0 # reaction parameter 1
k_U1 = 4.0 # reaction par... |
def make_car(manufacturer, model_name, **car_info):
car_info['manufacturer'] = manufacturer
car_info['model_name'] = model_name
return car_info
cars = make_car('suburu', 'outback', color = 'blue', tow_package = True)
print(cars) |
class Solution:
def longestMountain(self, A: List[int]) -> int:
result = base = 0
while base < len(A):
end = base
if end + 1 < len(A) and A[end] < A[end + 1]:
while end + 1 < len(A) and A[end] < A[end + 1]:
end += 1
if end +... |
class PlatformOutput(object):
# ==========================================================================
# C8200
# ==========================================================================
showVersion = {
'version': {
'chassis': 'C8200-1N-... |
# This library includes some functions for integrating arrays.
def euler(Tn, dTndt, tStep):
"""
Performs Euler integration to obtain T_{n+1}.
Arguments:
Tn: Array-like representing Temperature at time t_n.
dTndt: Array-like representing dT/dt at time t_n.
tStep: Float determining the ... |
class Checkpoints(webapp2.RequestHandler):
def get(self):
self.response.write(json.dumps({"meta": {"code": 400,
"errorType": "paramError",
"errorDetail": "Parameter 'api_key' is missing"
... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if(not head or not... |
class AccountStatus:
"""数据库字段名常量"""
# 日期
DAY = "DAY"
# 总资产
TOTAL_ASSETS = "TOTAL_ASSETS"
#资金金额
FUND_BALANCE = "FUND_BALANCE"
#股票市值
STOCK_MARKET_VALUE = "STOCK_MARKET_VALUE"
#当日盈亏
DAY_PROFIT_LOSS = "DAY_PROFIT_LOSS"
#当日盈亏比
DAY_PROFIT_LOSS_RATIO = "DAY_PROFIT_LOSS_RATI... |
#U
for row in range(6):
for col in range(10):
if ( col==0 and row!=4 and row!=5) or(col==4 and row!=4 and row!=5)or (row==4 and col==1 ) or (row==4 and col==2)or (row==4 and col==3):
print("*",end=" ")
else:
print(" ",end=" ")
print()
|
def test_unicode(testdir):
# Unicode identifyers are in fact legal Python code
string = """
```python
# Α α, Β β, Γ γ, Δ δ, Ε ε, Ζ ζ, Η η, Θ θ, Ι ι, Κ κ, Λ λ, Μ μ, Ν ν, Ξ ξ, Ο ο, Π π,
# Ρ ρ, Σ σ/ς, Τ τ, Υ υ, Φ φ, Χ χ, Ψ ψ, Ω ω
α = 1
```
"""
testdir.makefile(".md", string)
result ... |
# Write paragoo static site project files
def createproject(destinationdir):
"""Writes project files into `destinationdir`"""
return
|
#!/usr/bin/env python
class config:
def __init__(self):
self.db_user = 'DBUSERNAME'
self.db_pwd = 'DBPASSWORD'
self.db_name = 'DBNAME'
self.repo_name = "REPOSITORY"
self.user_name = "USERNAME"
self.github_api = u'https://api.github.com/repos/'
self.custom_url = "CUSTOM_URL... |
#!python
def is_sorted(items):
"""Return a boolean indicating whether given items are in sorted order.
Running time: O(n)
Memory usage: O(n)"""
if len(items) in [0, 1]:
return True
for i in range(len(items) - 1):
if items[i] > items[i + 1]:
return False
return True
def bubble_sort(items)... |
def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
sorted_arr = []
count_zero = 0
for i in input_list:
if i == 0:
sorted_arr = [i] + sorted_arr
... |
#!/usr/bin/env python3
#
# Author: Vishwas K Singh
# Email: vishwasks32@gmail.com
num1 = float(input("Enter the First Number: "))
num2 = float(input("Enter the Second Number: "))
print(num1+num2)
|
'''
Created on Apr 24, 2014
@author: Cory
'''
class Camera:
def __init__(self, location, bounds):
self.location = location
self.bounds = bounds
def set_camera_loc(self, location):
self.location = location
def bound_camera(self, map_bounds):
camx, camy = s... |
def potencia(op1, op2):
print("El resultado de la potencia es: ", op1**op2)
def redondear(op1):
print("El resultado del redondeo es: ", round(op1))
|
#! /usr/bin/env python3
user_input = input("Please enter some words separated by commas: ")
list_of_words = [word.strip() for word in user_input.split(",")]
unique_words = []
for word in sorted(list_of_words):
if word not in unique_words:
unique_words.append(word)
unique_words = set(sorted(list_of_words... |
def spiral(size):
sm = [[0]*size for k in range(size)]
i, j, el = 0, -1, 1
di, dj = [0, 1, 0, -1], [1, 0, -1, 0]
for x in range(2*size - 1):
for y in range((2*size - x) // 2):
i += di[x % 4]
j += dj[x % 4]
sm[i][j] = el
el += 1
return sm
|
# Time: O(logn) = O(32)
# Space: O(1)
class Solution(object):
# @param n, an integer
# @return an integer
def hammingWeight(self, n):
result = 0
while n:
n &= n - 1
result += 1
return result
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return self.data
class LinkedList:
def __init__(self, nodes=None):
self.head = None
if nodes is not None:
node = Node(data=nodes.pop(0))
self.head = n... |
def calculateEstimate(data, converted_time, type='impact'):
my_dict= {}
# calculate factor value
factor = 2 ** (converted_time // 3)
# my solution for challenge one
if type == 'impact':
my_dict['currentlyInfected'] = int(my_dict['reportedCases'] * 10)
my_dict['infectionsByRequestedT... |
class data():
def media(self,x):
totalx=len(x)
somatorio=0;
for x_i in x:
somatorio+=x_i
pass
return somatorio/totalx
def Quantil(self,porcent,x):
return porcent*len(x)
pass
def Correlacao(self,x,y):
for x_i in x:
x_i+=x_i
for y_i in y:
y_i+=y_i
return x... |
# coding: utf-8
def generateur():
yield "a"
yield "b"
yield "c"
i=generateur()
for v in i:
print(v)
def generateur2(n):
for i in range(n):
if i == 5:
print ("Quoi déjà 5eme tour?")
yield i+1
i=generateur2(10)
for v in i:
print(v)
#-------------------------------... |
""" Checking the height, weight and age of students in two classes (A and B) of two schools. """
class school():
def __init__(self, age, height, weight):
self.age = age
self.height = height
self.weight = weight
# Calculating the average age of students
def age_average(sel... |
"""
https://www.hackerrank.com/challenges/one-week-preparation-kit-lonely-integer/problem
"""
def _solve_method_2(a):
"""Use a dictionary."""
d = dict()
for item in a:
if not item in d:
d[item] = 1
else:
d[item] += 1
for k, v in d.items():
if v == 1:
... |
# Link: https://leetcode.com/problems/palindrome-number/
class Solution:
# @param {integer} x
# @return {boolean}
def isPalindrome(self, x):
x = str(x)
for i in range(0, len(x) / 2):
if x[i] != x[len(x) - i - 1]:
return False
return True
|
# Python Tuples (a,b)
# Immutable
# Use - passing data that does not need changing
# Faster than list
# "safer" than list
# Can be key in dict unlike list
# For Heterogeneous data - meaning mixing different data types(int,str,list et al) inside
# https://docs.python.org/3/tutorial/datastructures.html#tuples-and-... |
# TABUADA DE UM NUMERO
num = int(input('Tabuada do: '))
print('{} X 1 = {}'.format(num, (num*1)))
print('{} X 2 = {}'.format(num, (num*2)))
print('{} X 3 = {}'.format(num, (num*3)))
print('{} X 4 = {}'.format(num, (num*4)))
print('{} X 5 = {}'.format(num, (num*5)))
print('{} X 6 = {}'.format(num, (num*6)))
print('{} X... |
def filter_variance(data, lower, upper):
"""
:param data: abundance data frame
:param lower: lower percentile filter
:param upper: upper percentile filter
:return: filtered abundance data frame
"""
data['row_variance'] = data.var(axis=1)
lower_quantile = data['row_variance'].quantile(round(lower/100, 1))
up... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class Openvslam(CMakePackage):
"""OpenVSLAM is a monocular, stereo, and RGBD visual SLAM system."""
homepage = "... |
# import datetime
# from functools import wraps
# from app import datetime, Share, desc, Mail, Message, Cache, SQLAlchemy, session, request, flash, render_template, redirect, url_for, Markup
# ------------------------------------------------------------------
# helper functions to clean up app.py / view file
def get_... |
alunos = {}
alunos['nome'] = str(input('Nome: '))
alunos['media'] = float(input('Média: '))
if alunos['media'] >= 6:
alunos['status'] = 'Aprovado!'
else:
alunos['status'] = 'Reprovado!'
print(f'Nome do aluno: {alunos["nome"]}')
print(f'A média do aluno é: {alunos["media"]}')
print(f'O status do aluno é {alun... |
"""
A complex MDP, illustrating multiple possible transitions (from different
actions) as well as a non-constant discount parameter.
"""
|
del_items(0x80139B6C)
SetType(0x80139B6C, "unsigned char map_buf[61440]")
del_items(0x80148B6C)
SetType(0x80148B6C, "unsigned short *imgbuf[21]")
del_items(0x80148BC0)
SetType(0x80148BC0, "struct POLY_FT4 br[10][2][2]")
del_items(0x80149200)
SetType(0x80149200, "struct POLY_FT4 tmdc_pol[10][2][2]")
del_items(0x80149840... |
pessoas = {'nome': 'Gustavo', 'sexo': 'M', 'idade': 22}
print(pessoas)
del pessoas['sexo']
print(pessoas)
pessoas['nome'] = 'Rafael'
print(pessoas)
pessoas['peso'] = 98.5
print(pessoas) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.