content stringlengths 7 1.05M |
|---|
class HeapMax(object):
def __init__(self, *args):
self.nodes = [0]
self.size = 0
for item in args:
self.push(item)
def __len__(self):
return self.size
def __repr__(self):
return self.nodes[1:]
def move_up(self, size):
while size // 2 > 0:
... |
"""
operation.py
~~~~~~~~~~~~~
This stores the information of each individual operation in the
production line.
- name improves readability when printing
- machine is the machine in which that operation will be executed
- duration is the amount of time in which the operation will be completed
- job_model is the rad... |
def rle_encode(data):
encoding = ''
prev_char = ''
count = 1
if not data: return ''
for char in data:
# If the prev and current characters
# don't match...
if char != prev_char:
# ...then add the count and character
# to our encoding
if p... |
# https://leetcode.com/problems/excel-sheet-column-number/
class Solution:
def titleToNumber(self, s: str) -> int:
power = 0
val = 0
for i in range(len(s) - 1, -1, -1):
val += (ord(s[i]) - 64) * (26 ** power)
power += 1
return val
|
# sorting algorithm -> insertionsort
# @author unobatbayar
# Data structure Array
# Worst-case performance О(n2) comparisons and swaps
# Best-case performance O(n) comparisons, O(1) swaps
# Average performance О(n2) comparisons and swaps
# Worst-case space complexity О(n) total, O(1) auxiliary
# @author unobatbayar... |
def arithmetic_arranger(problems, flag=False):
op1Array = []
op2Array = []
lineArray = []
result = []
separator = " "
if len(problems) > 5:
return "Error: Too many problems."
for problem in problems:
op = problem.split()
lenght = max(len(op[0]), len(op[2])) + 2
if op[1] != '+' and op... |
# Source: https://codingcompetitions.withgoogle.com/kickstart/round/000000000019ffc7/00000000001d3f56#problem
# Time Complexity: O(nlogn)
# Can be improved to O(n) using count sort as the length of array is fixed and can be upto 1000.
def allocation(prices, budget):
prices.sort()
houses = 0
for price in pr... |
def filter_one(lines):
rho_threshold = 15
theta_threshold = 0.1
# how many lines are similar to a given one
similar_lines = {i: [] for i in range(len(lines))}
for i in range(len(lines)):
for j in range(len(lines)):
if i == j:
continue
rho_i, theta_i ... |
def natural_sum(x):
return x * (x + 1) // 2
def count(n):
n = n - 1
return 3 * natural_sum(n // 3) + 5 * natural_sum(n // 5) - 15 * natural_sum(n // 15)
if __name__ == "__main__":
t = int(input())
for i in range(t):
n = int(input())
result = count(n)
print(str(result)) |
# Class for an advertisement on Kijiji, to hold all ad parameters
class Ad:
def __init__(self, title: str, price: float, description: str, tags: list, image_fps: list, category_id: str):
self.category_id = category_id # the number representing the posting category.
... |
#
# PySNMP MIB module NMS-EPON-ONU-SERIAL-PORT (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NMS-EPON-ONU-SERIAL-PORT
# Produced by pysmi-0.3.4 at Wed May 1 14:21:58 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... |
# SPDX-License-Identifier: MIT
"""App-specific implementations of :class:`django.forms.Form` and related stuff like fields and widgets.
Warnings
--------
Siblings of :class:`django.forms.ModelForm` are (by definition) semantically
related to the respective implementation of :class:`django.db.models.Model`.
Thus, the... |
"""
魔术方法
如果要把自定义对象放到set或者用作dict的键
那么必须要重写__hash__和__eq__两个魔术方法
前者用来计算对象的哈希码,后者用来判断两个对象是否相同
哈希码不同的对象一定是不同的对象,但哈希码相同未必是相同的对象(哈希码冲撞)
所以在哈希码相同的时候还要通过__eq__来判定对象是否相同
"""
class Student():
__slots__ = ('stuid', 'name', 'gender')
def __init__(self, stuid, name):
self.stuid = stuid
self.name = name
... |
running = True
while running:
guess = str(input("Please enter a number:"))
isdigit = str.isdigit(guess)
if isdigit == True:
print("True")
else:
print("False")
else:
print("Done.")
|
#
# @lc app=leetcode.cn id=27 lang=python3
#
# [27] 移除元素
#
# https://leetcode-cn.com/problems/remove-element/description/
#
# algorithms
# Easy (52.65%)
# Total Accepted: 34.2K
# Total Submissions: 65K
# Testcase Example: '[3,2,2,3]\n3'
#
# 给定一个数组 nums 和一个值 val,你需要原地移除所有数值等于 val 的元素,返回移除后数组的新长度。
#
# 不要使用额外的数组空间,你必... |
class DataGridViewCellStyleContentChangedEventArgs(EventArgs):
""" Provides data for the System.Windows.Forms.DataGridView.CellStyleContentChanged event. """
def Instance(self):
""" This function has been arbitrarily put into the stubs"""
return DataGridViewCellStyleContentChangedEventArgs()
CellStyle=pro... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
"""
time: nlgn + nlgn
space: 2n
"""
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
prehead = ListNode()
heap = []
... |
__version__ = '0.1.0'
def cli():
print("Hello from parent CLI!")
|
class Speed:
def __init__(self, base_speed):
self.base_speed = base_speed
self.misc = []
def get_speed(self):
return (
self.base_speed +
sum(map(lambda x: x(), self.misc)))
|
#!/usr/bin/env python3
# For loop triangle
STAR = 9
for i in range(0, STAR):
for j in range(i):
print("*", end='')
print()
print()
# For Loop for reverse triangel
for i in range(STAR, 0, -1):
for j in range(i):
print("*", end='')
print("")
print()
# For Loop for opposite triangle
for i ... |
t = int(input())
answer = []
for a in range(t):
line = [int(i) for i in input().split()]
n = line[3]
line.pop(3)
line.sort()
a = line[0]
b = line[1]
c = line[2]
if(n<2*c-b-a):
answer.append("NO")
elif((n-2*c+b+a)%3==0):
answer.append("Yes")
else:
answer.ap... |
def decorator(f):
def wrapper():
return '<Los compas> \n' + f() + '\n<Que siempre la cotorrean>'
return wrapper
@decorator
def díHola():
return 'Un tremendo saludote :v'
#print(díHola())
#díHola = decorator(díHola)
print (díHola())
|
#
# PySNMP MIB module OMNI-gx2RX200-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OMNI-gx2RX200-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:33:46 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
"""
reader() = leitor
whiter() = escritor - Cria um objeto que permite escrever no arquivo
whiterow() = Escreve uma linha no arquivo
from csv import writer, DictWriter
# Para criar e escrever no arquivo
# Mesmas premissas de se trabalhar com arquivos .txt
with open('filmes.csv', 'w') as arq:
escritor = w... |
# -*- coding: utf-8 -*-
# Scrapy settings for code_scraper project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
AUTOTHROTTLE_ENABLED = 1
BOT_NAME = 'MsdnApiExtractor'
COO... |
name = input("What is your name?\n")
years = input("How old are you?\n")
adress = input("Where are you live?\n")
print("This is " + name)
print("It is " + years)
print("(S)he live in " + adress) |
# Created by MechAviv
# Map ID :: 302000000
# Grand Athenaeum : Grand Athenaeum
if "" in sm.getQuestEx(32666, "clear"):
sm.setQuestEx(32666, "clear", "0"); |
'''
Project: gen-abq-S9R5
Creator: Nicholas Fantuzzi
Contact: @sniis84
Version: 1.0
Date: 5-Jul-2015
To test just place 'Job-1.inp' in the Abaqus working directory and
select 'Run Script...' from the menu. A new file will be created as 'Job-1-finale.inp'.
Running that file using Abaqus/CAE or command line will result ... |
# Time: O(n)
# Space: O(1)
# 918
# Given a circular array C of integers represented by A,
# find the maximum possible sum of a non-empty subarray of C.
#
# Here, a circular array means the end of the array connects to the beginning of the array.
# (Formally, C[i] = A[i] when 0 <= i < A.length, and C[i+A.length] = C[i... |
# -*- coding: utf-8 -*-
N = int(input())
for i in range(N):
X, Y = map(int, input().split())
start = X if (X % 2 != 0) else X + 1
answer = sum(range(start, start + (2 * Y), 2))
print(answer) |
{
"targets": [
{
"target_name": "atomicCounters",
"sources": [ "src/C/atomicCounters.c" ],
"conditions": [
["OS==\"linux\"", {
"cflags_cc": [ "-fpermissive", "-Os" ]
}],
["OS=='mac'", {
"xcode_settings": {
}
}],
["OS=='win'", ... |
#!/usr/bin/env python3
n, *a = map(int, open(0).read().split())
a = [0]*3 + a
for i in range(n):
i *= 3
t, x, y = map(lambda j:abs(a[i+3+j]-a[i+j]), [0,1,2])
d = x+y
if d>t or d%2-t%2: print("No"); exit()
print("Yes") |
db = {
"European Scripts": {
"Armenian": [
1328,
1423
],
"Armenian Ligatures": [
64275,
64279
],
"Carian": [
66208,
66271
],
"Caucasian Albanian": [
66864,
66927
],
"Cypriot Syllabary": [
67584,
67647
],
"Cyrillic"... |
class Reader:
def __init__(self, stream, sep=None, buf_size=1024 * 4):
self.stream = stream
self.sep = sep
self.buf_size = buf_size
self.__buffer = None
self.__eof = False
def __iter__(self):
return self
def __next__(self):
if not self.__buffer:
... |
# Copyright 2019 Google LLC
#
# 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/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
class NeuronLayer:
def __init__(self, neurons):
self.neurons = {}
for n in neurons:
self.neurons[n] = None # Value: output
def __str__(self):
msg = "| | "
for n in self.neurons:
msg += str(n) + " | "
msg += "|"
return msg
def activat... |
class Solution:
def subsetXORSum(self, nums: List[int]) -> int:
ans = 0
n = len(nums)
for i in nums:
ans |= i
return ans * pow(2, n - 1)
|
# https://leetcode.com/problems/lru-cache/
class Node:
def __init__(self, key, val):
self.key = key
self.val = val
self.prev = None
self.next = None
class LRUCache:
"""
Uses a dictionary to cache nodes
and a doubly linked list to keep track of the least used nodes
... |
"""caching helps speed up data
MEMOIZATION - specific form of caching that involves caching the return value of func based on its paramaters, and if paramater doesnt change, then its memoized, it uses the cache version
"""
# without MEMOIZATION
def addTo80(n):
print("long time")
return n + 80
print(addTo... |
#
# PySNMP MIB module PDN-MGMT-IP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PDN-MGMT-IP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:39:08 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
'''Return a string obtained interlacing RECURSIVELY two input strings'''
__author__ = 'Nicola Moretto'
__license__ = "MIT"
def laceStringsRecur(s1, s2):
'''
Returns a new str with elements of s1 and s2 interlaced,
beginning with s1. If strings are not of same length,
then the extra elements should app... |
arr = [
[3109, 7337, 4317, 3411, 4921, 2505, 7337, 8847, 1297, 2807, 4317, 7337, 1901, 3713, 1297, 8545, 3109, 4619, 4619,
8545, 89, 3713, 7337, 2807, 89, 1599, 9753, 9451, 7337, 7337, 5223, 9753, 693, 3713, 4317, 9149, 89, 4317, 5525,
1901, 3713, 3713, 5525, 4619, 2807, 5223, 9149, 8847, 3109, 9753, 391,... |
# # 01 solution using 2 lists and 1 for loop
# lines = int(input())
# key = input()
# word_list = []
# found_match = []
# for _ in range(lines):
# words = input()
# word_list.append(words)
# if key in words:
# found_match.append(words)
# print(word_list)
# print(found_match)
# 02 solution using 1 li... |
# use shift enter on highlighted code
#
#print("Hello")
# def search (x, nums):
# # nums is a list of numbers and x is a number
# # Returns the position in the list where x occurs or -1 if
# # x is not in the list
# try:
# return nums.index(x)
# except:
# return -1
# print(search(1,[... |
# -*- coding: utf-8 -*-
"""
修改 Windows 10 壁纸
"""
|
"""
Constants for interview_generator.py
"""
# This is to workaround fact you can't do local import in Docassemble playground
class Object(object):
pass
generator_constants = Object()
# Words that are reserved exactly as they are
generator_constants.RESERVED_WHOLE_WORDS = [
'signature_date',
'docket_number',
... |
class BaseClimber(object):
"""
The Base hill-climbing class
"""
def __init__(self, tweak, quality, stop_condition,
solution):
"""
BaseClimber constructor
:param:
- `solution`: initial candidate solution
- `tweak`: callable that tweaks solutio... |
class Album:
def __init__(self, album: dict):
self.album_id = album["id"]
self.name = album["name"]
images = dict()
for image in album["images"]:
images[image["height"]] = image["url"]
self._images = tuple(images)
def image_url(self, resolution: int = 640) ->... |
__all__ = [
"__title__",
"__summary__",
"__uri__",
"__version__",
"__author__",
"__email__",
"__license__",
"__copyright__",
]
__title__ = "oommfpy"
__summary__ = (
"oommfpy reads OOMMF output files and provides a class to manipulate"
"the data using Numpy arrays"
)
__uri__ = "h... |
listagem = ('lapis', 1.75,
'borracha', 2,
'caderno', 15.90,
'estojo', 25,
'transferidor', 4.20,
'compasso', 9.99,
'Mochila', 120.32,
'canetas', 22.3,
'livro', 34.90)
print('-'*40)
print(f'{"LISTAGEM DE PREÇOS":^40}')
print('... |
# Find the number of letters "a" or "A" in a string using control flow
counter = 0
string = 'Python is a widely used high-level programming language for general-purpose programming, ' \
'created by Guido van Rossum and first released in 1991. An interpreted language, Python has a design ' \
'philos... |
'''
Author : Bhishm Daslaniya [17CE023]
"Make it work, make it right, make it fast."
– Kent Beck
'''
def reverseWord(w):
return ' '.join(w.split()[::-1])
if __name__=='__main__':
s = input("Enter sentence:")
print(reverseWord(s)) |
APPVERSION = "0.2.4"
DBVERSION = 4 # Make sure this is an integer
MANDATORY_DBVERSION = 4 # What version of the database has to be used for the application to run at all
CONFIGFILE = "config.db"
IMAGESROOT = "images"
|
#!/usr/bin/env python3
#
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... |
size = int(input())
matrix = []
for _ in range(size):
row = []
for x in input().split():
row.append(int(x))
matrix.append(row)
primary = []
secondary = []
for row in range(size):
primary.append(matrix[row][row])
secondary.append(matrix[row][size - 1 - row])
print(abs(sum(primary) - sum(s... |
class Economy(object):
def __init__(self, type_space, distribution_function, utilities):
self.type_space=type_space
self.distribution_function = distribution_function #(can be correlated)
self.utilities=utilities
# + social_value_function (and some basic -- ex-post/ex-ante)
clas... |
class Solution:
def letterCasePermutation(self, S):
"""
:type S: str
:rtype: List[str]
"""
ans = []
accus = [0, 32, -32]
def helper(work, S, ans, path):
if work == len(S):
ans.append(path)
return
for ac... |
num = [1, 2, 4.5, 6.3242321, 32434.333, 22]
print('int: ', "{0:d}".format(num[1]))
print('float: ', "{0:.2f}".format(num[3]))
print('float round: ', "{0:0f}".format(num[4]))
print('bin: ', "{0:b}".format(num[5]))
print('hex: ', "{0:x}".format(num[5]))
print('oct: ', "{0:o}".format(num[5]))
print('string: ','{1}{2}{0}'.... |
# Ask the user to enter their age.
age = int(input("Please enter your age :"))
# Depending on the age group display a different ticket price.
if age > 0 and age < 18:
print("The ticket costs : 1.50£")
elif age >= 18 and age < 65:
print("The ticket costs : 2.20£")
elif age >= 65 and age < 100:
print("The ti... |
# Faça um programa que leia um numero inteiro qualquer e peça para o usuário escolher qual será a base de conversão: 1
# para binário, 2 para octal e 3 para hexadecimal.
n = int(input('Digite um número inteiro: '))
print("""Escolha uma das bases para conversão:
[ 1 ] BINÁRIO
[ 2 ] OCTAL
[ 3 ] HEXADECIMAL""")
esc... |
#!/usr/bin/env python
"""
Merge Sort Algorithm
Author: Gianluca Biccari
Description: sort an input array of integers and return a sorted array
"""
def merge_sort(iarray):
if iarray is None or len(iarray) < 2:
return iarray
else:
return __merge_sort(iarray, 0, len(iarray)-1)
def __... |
a = input ("ingrese numero ")
a = int(a)
b = input ("ingrese numero ")
b = int(b)
c = input ("ingrese numero ")
c = int(c)
d = input ("ingrese numero ")
d = int(d)
e = input ("ingrese numero ")
e = int(e)
f = (a+b)
f = int(f)
print("la suma de a+b es:")
print (f)
g = (f-e)
g = in... |
class FinancialIndependence():
def __init__(self, in_TFSA, in_RRSP, in_unregistered, suggested_TFSA, suggested_RRSP, suggested_unregistered,
annual_budget):
"""
Initialize an Instance of Financial Independence
"""
# Possible issue is that TFSA is only 5500 ev... |
class Node:
class_id = 0
def __init__(self, id=None, position=(0,0), label="", **kwargs) -> None:
self.id = Node.class_id if not id else id
self.pos = position
self.label = label
self.attr = kwargs if len(kwargs) > 0 else {}
Node.class_id += 1
def __str__(self) -> ... |
'''
Given a boolean expression with following symbols.
Symbols
'T' ---> true
'F' ---> false
And following operators filled between symbols
Operators
& ---> boolean AND
| ---> boolean OR
^ ---> boolean XOR
Count the number of ways we can parenthesize the expression so that the value of e... |
class News:
# category = ''
# title = ''
# description = ''
# locations = []
# link = ''
# summery = ''
# date_time= ''
def __init__(self,title, description,summary,link,category,date_time):
self.category = category
self.title = title
self.description = descripti... |
def test_array_one_d_type_promotion(tmp_path, helpers):
# int + float to float
v_str = [ '1', '2', '3.0', '+4.0e0' ]
v = [1.0, 2.0, 3.0, 4.0]
helpers.do_one_d_variants(tmp_path, False, 4, v, v_str)
# int + barestring to string
v_str = [ '1', '2', 'abc', 'd']
v = ['1', '2', 'abc', 'd']
... |
def minion_game(string):
upper_string = string.upper()
vowels = 'AEIOU'
len_str = len(upper_string)
K_score, S_score = 0,0
if len_str>0 and len_str< pow(10,6):
for i in range(len_str):
if upper_string[i] in vowels:
K_score+= len(string)-i
#the score is... |
class DismissReason(object):
"""
This class represents a notification dismiss reason. It is passed to callback registered in on_dismiss parameter
of :py:func:`zroya.show` function.
You can print it to get a reason description or compare it with any of following attributes.
"""
User = 0
""... |
class Constraints(object):
def __init__(self, numberOfQueens):
self.set = set()
self.populateConstraints(self.set, numberOfQueens)
def populateConstraints(self, mySet, numberOfQueens):
self.rowConstraints(mySet, numberOfQueens)
self.diagonalConstraints(mySet, numberOfQueens)
... |
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def tippecanoe():
http_archive(
name="tippecanoe" ,
build_file="//bazel/deps/tippecanoe:build.BUILD" ,
sha256="916... |
"""
Quiz Problem 5
Write a Python function that returns the sublist of strings in aList
that contain fewer than 4 characters. For example, if
aList = ["apple", "cat", "dog", "banana"]
- your function should return: ["cat", "dog"]
This function takes in a list of strings and returns a list of
strings. Your func... |
"""Constants for the Wyze Home Assistant Integration integration."""
DOMAIN = "wyzeapi"
CONF_CLIENT = "wyzeapi_client"
ACCESS_TOKEN = "access_token"
REFRESH_TOKEN = "refresh_token"
REFRESH_TIME = "refresh_time"
WYZE_NOTIFICATION_TOGGLE = f"{DOMAIN}.wyze.notification.toggle"
LOCK_UPDATED = f"{DOMAIN}.lock_updated"
C... |
expected_output = {
"ap": {
"ayod-1815i" : {
"number_of_sgts_referred_by_the_ap": 2,
"sgts": {
"UNKNOWN(0)": {
"policy_pushed_to_ap": "NO",
"no_of_clients": 0
},
"D... |
class Node:
def __init__(self, item):
self.item = item
self.next = None
class Queue:
def __init__(self):
self.head = None
self.tail = None
def enqueue(self, item):
if self.head is None:
self.head = Node(item)
self.tail = Node(item)
else:
new_node = Node(item)
# Make referenc... |
class Solution:
"""
@param: A: An integer array.
@return: nothing
给出一个含有正整数和负整数的数组,重新排列成一个正负数交错的数组。
Example
样例 1
输入 : [-1, -2, -3, 4, 5, 6]
输出 : [-1, 5, -2, 4, -3, 6]
解释 : 或者仍和满足条件的答案
先partition 分成前面为负数,后面为正数
然后两根指针,首先判断正数多还是负数多,并把多的那一部分移到后半部分,最后两根指针分别递增二交换即可
"""
def rerange(self, A):
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2019, Silvio Peroni <essepuntato@gmail.com>
#
# Permission to use, copy, modify, and/or distribute this software for any purpose
# with or without fee is hereby granted, provided that the above copyright notice
# and this permission notice appear in all copies.
#
# THE SOFTWARE I... |
def get_attributedelta_type(attrs): # attrs: {name: func}
class ProtoAttributeDelta(object):
__slots__ = ['head', 'tail'] + list(attrs.keys())
@classmethod
def get_none(cls, element_id):
return cls(element_id, element_id, **dict((k, 0) for k in attrs)) #TODO: head and tail = ele... |
scheme = {
'base00' : '#231e18',
'base01' : '#302b25',
'base02' : '#48413a',
'base03' : '#9d8b70',
'base04' : '#b4a490',
'base05' : '#cabcb1',
'base06' : '#d7c8bc',
'base07' : '#e4d4c8',
'base08' : '#d35c5c',
'base09' : '#ca7f32',
'base0a' : '#e0ac16',
'base0b' : '#b7ba53... |
#
# PySNMP MIB module REDSTONE-DHCP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/REDSTONE-DHCP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:55:28 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
# In this file, constants are defined that are used throughout the project.
# Definition in one place prevents accidental use of different strings
battery_model_simple = 'battery_model_simple'
battery_model_height_difference = 'battery_model_height_difference'
|
class Node:
def __init__(self, value):
self.value = value
self.next = None
class BinaryNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
# Check the traversal ... |
set_name(0x801384E4, "GameOnlyTestRoutine__Fv", SN_NOWARN)
set_name(0x801384EC, "vecleny__Fii", SN_NOWARN)
set_name(0x80138510, "veclenx__Fii", SN_NOWARN)
set_name(0x8013853C, "GetDamageAmt__FiPiT1", SN_NOWARN)
set_name(0x80138B34, "CheckBlock__Fiiii", SN_NOWARN)
set_name(0x80138C1C, "FindClosest__Fiii", SN_NOWARN)
set... |
persona1 = {'first_name':'Luis','last_name':'Romero','age':21,'city':'Saltillo'}
print(persona1['first_name'])
print(persona1['last_name'])
print(persona1['age'])
print(persona1['city'])
print()
persona2 = {'first_name':'Maria','last_name':'Vazquez','age':23,'city':'Saltillo'}
print(persona2['first_name'])
print(person... |
# test builtin abs
print(abs(False))
print(abs(True))
print(abs(1))
print(abs(-1))
# bignum
print(abs(123456789012345678901234567890))
print(abs(-123456789012345678901234567890))
# edge cases for 32 and 64 bit archs (small int overflow when negating)
print(abs(-0x3fffffff - 1))
print(abs(-0x3fffffffffffffff - 1))
|
# -*- Coding: utf-8 -*-
# Base class for representing a player in a game.
class Player():
def __init__(self, name, score = 0):
self.name = name
self.score = score
def getName(self):
return self.name
def getScore(self):
return self.score
def addScore(self, value):
... |
#Escribir un programa que pregunte el nombre el un producto, su precio y un número de unidades y muestre por pantalla una cadena con el nombre del producto seguido de su precio unitario con 6 dígitos enteros y 2 decimales, el número de unidades con tres dígitos y el coste total con 8 dígitos enteros y 2 decimales.
prod... |
def request_serializer(Request) -> dict:
return {
"id": str(Request["_id"]),
"tenant_uid": Request["tenant_uid"],
"landlord_uid": Request["landlord_uid"],
"landlord_no": Request["landlord_no"],
"status": Request["status"],
"landlord_address": Request["landlord_address... |
def format_align_digits(text, reference_text):
if len(text) != len(reference_text):
for idx, t in enumerate(reference_text):
if not t.isdigit():
text = text[:idx] + reference_text[idx] + text[idx:]
return text
|
class DidaticaTech:
def __init__(self, v=10, i=1):
self.valor = v
self.incremento = i
self.valor_exponencial = v
def incrementa(self):
self.valor += self.incremento
def verifica(self):
if self.valor > 12:
print('Ultapassou 12')
else:
... |
def single_quad_function(point, x0, A, rotation):
"""
Quadratic function.
Parameters
----------
point : 1-D array with shape (d, )
A point used to evaluate the gradient.
x0 : 1-D array with shape (d, ).
A : 2-D array with shape (d, d).
Diagonal matrix.
rotation : 2-D... |
#__________________ Script Python - versão 3.8 _____________________#
# Autor |> Abraão A.da Silva
# Data |> 06 de Março de 2021
# Paradigma |> Orientado à objetos
# Objetivo |> Desenvolver um maneira pratica de calcular o raio de uma circunferência
#________________________________________________________________... |
frase = 'Curso em vídeo'
# 01234567891011121314 indice
print(frase)
print(frase[3]) # [3] Representa o indice que começa por 0
print(frase[:13]) # [:13] Indice vai do 0 a 13
print(frase[1:15:2]) # Vai do indice 0 ao 15 pulando de 2 em 2
print(frase.count('o'))
print(frase.replace('Curso', 'Alemão')) # Subst... |
class Monostate:
__estado: dict = {}
def __new__(cls, *args, **kwargs):
obj = super(Monostate, cls).__new__(cls, *args, **kwargs)
obj.__dict__ = cls.__estado
return obj
if __name__ == '__main__':
m1 = Monostate()
print(f'M1 ID: {id(m1)}')
print(m1.__dict__)
m2 = Monos... |
N = int(input())
for i in range(0,N):
print(i*i)
|
guess = int(input())
# new transcript
while guess != 0:
response = input()
higherThan = [0 for x in range(10)]
lowerThan = [0 for x in range(10)]
# build case in transcript
while response != "right on":
if response == "too low":
# set any number <= guess to 1 in lowerthan
... |
# GENERATED VERSION FILE
# TIME: Sun Aug 30 00:34:46 2020
__version__ = '1.0.0+5d75636'
short_version = '1.0.0'
|
repeat = int(input())
for x in range(repeat):
inlist = input().split()
for i in range(len(inlist) - 1):
print(inlist[i][::-1], end=" ")
print(inlist[-1][::-1])
|
def touch(*files) -> bool:
"""
Create several empty files.
:param files: The list of file paths to create.
:return: The list of created files.
"""
try:
for file in files:
open(file, 'w').close()
return True
except FileNotFoundError as e:
print('... |
def find_outlier(integers):
"""Find The Parity Outlier.
Idea: go though array, counting odd and even integers, counting numnber of
odd and even integers seen, and saving the last seen.
We can terminate early when we have >= 2 odd and one even (which will be
our outlier) or vice verse.
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.