content stringlengths 7 1.05M |
|---|
occupation_names_test_data = [
{'old': 'Jx4V_6tm_fUH', 'replaced_by': 'YcvM_Gqk_6U7', 'label': 'Utvecklingsingenjör, elkraft',
'hits_old': ['24647561', '24645432', '24615762', '24504276'],
'replacing_old_concept_ids': ['Jx4V_6tm_fUH', 'YcvM_Gqk_6U7', 'Jx4V_6tm_fUH', 'Jx4V_6tm_fUH'],
'hits_replaced_by... |
class Solution:
# @param {integer[][]} grid
# @return {integer}
def minPathSum(self, grid):
n = len(grid);
m = len(grid[0]);
p = [([0] * m) for i in range(n)]
p[0][0] = grid[0][0];
for k in range (1, n):
p[k][0] = p[k-1][0]+grid[k][0];
for... |
# Cidades: Crie um dicionario chamado cities. Use os nomes de tres cidades como chaves em seu dicionario. Crie um dicionario com informacoes sobre cada cidade e inclua o pais em que a cidade esta localizada, a populacao aproximada e um fato sobre essa cidade. As chaves do dicionario de cada cidade devem ser algo como c... |
""" Problem - 239. Sliding Window Maximum
Problem statement -
You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.
Return ... |
#!/usr/bin/env python
"""Pseudocode for the OPTICS algorithm."""
def optics(objects, epsilon, min_points):
"""
Clustering.
Parameters
----------
objects : set
epsilon : float
min_points : int
"""
assert min_points >= 1
# TODO
|
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
somaPar = 0
soma3c = 0
for l in range(0, 3):
for c in range(0, 3):
matriz[l][c] = int(input(f'Digite um valor para [{l}, {c}]: '))
print('-'*30)
for x, l in enumerate(matriz):
for y, c in enumerate(l):
print(f'[{c:^5}]', end=' ')
if c % 2 == 0:
... |
# Construct a square matrix with a size N × N containing integers
# from 1 to N * N in a spiral order, starting from top-left and in
# clockwise direction.
#
# Example
#
# For n = 3, the output should be
#
# spiralNumbers(n) = [[1, 2, 3],
# [8, 9, 4],
# [7, 6, 5]]
def spiralNum... |
feedback_poly = {
2: [1],
3: [2],
4: [3],
5: [3],
6: [5],
7: [6],
8: [6, 5, 4],
9: [5],
10: [7],
11: [9],
12: [11, 10, 4],
13: [12, 11, 8],
14: [13, 12, 2],
15: [14],
16: [14, 13, 11],
17: [14],
18: [11],
19: [18, 17, 14],
20: [17],
21: [19... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
res = []
if root i... |
# Generated by h2py from /usr/include/sys/event.h
EVFILT_READ = (-1)
EVFILT_WRITE = (-2)
EVFILT_AIO = (-3)
EVFILT_VNODE = (-4)
EVFILT_PROC = (-5)
EVFILT_SIGNAL = (-6)
EVFILT_SYSCOUNT = 6
EV_ADD = 0x0001
EV_DELETE = 0x0002
EV_ENABLE = 0x0004
EV_DISABLE = 0x0008
EV_ONESHOT = 0x0010
EV_CLEAR = 0x0020
EV_SYSFLAGS = 0xF000
... |
a = 1
b = 2
c = 3
print(a)
print(b)
print(c)
|
"""
042
Set a variable called total to 0. Ask the user to enter
five numbers and after each input ask them if they
want that number included. If they do, then add the
number to the total. If they do not want it included,
don’t add it to the total. After they have entered all five
numbers, display the total.
"""
total =... |
class script(object):
START_MSG = """ <b>Hi {}
I'm a Image Editor Bot which Supports various modes
For more click help....</b>"""
HELP_MSG = """Hai, Follow these Steps..
<code>🌀 Send me any Image to Edit..</code>
<code>🌀 Select the Corresponding mode that you need</code>
<code>🌀 Your Edited Image will ... |
default_prefix = "DWB"
known_chains = {
"BEX": {
"chain_id": "38f14b346eb697ba04ae0f5adcfaa0a437ed3711197704aa256a14cb9b4a8f26",
"prefix": "DWB",
"dpay_symbol": "BEX",
"bbd_symbol": "BBD",
"vests_symbol": "VESTS",
},
"BET": {
"chain_id":
"9afbce9f... |
# RemoveDuplicatesfromSortedArray.py
# weird accepted answer that doesn't actually remove anything.
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if (len(nums)==0):
return 0
i=0
j=0
while j < len(nums):
# print(nums, i , j)
... |
# Values obtained from running against the Fuss & Navarro 2009 reference implementation
vals = [(0.3325402105490861,
0.18224585277734096,
2.0210322268188046,
0.37178992456396914,
0.7513994191503139,
1.6883221884854474,
1.0,
0.082198565245068272),
(-0.13074510229340497,
0.44696631528174735,
2.4890334... |
"""
Given a sorted array arr, two integers k and x, find the k closest elements
to x in the array. The result should also be sorted in ascending order.
If there is a tie, the smaller elements are always preferred.
Example:
Input: arr = [1,2,3,4,5], k = 4, x = 3
Output: [1,2,3,4]
Cons... |
# -*- coding: utf-8 -*-
project_list = {
"parameters": [{
"name": "project_id",
"description": "企业项目ID",
"type": "string",
"in": "path",
"required": "true"
}],
"response": {
"200": {
"description": "获取成功",
"examples": {
... |
class HourRange():
def __init__(self, start: int, end: int):
if start == end:
raise ValueError("Start and end may not be equal.")
if start < 0 or 23 < start:
raise ValueError("Invalid start value: " + str(start))
if end < 0 or 23 < end:
raise ValueError("I... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def dfs(self, root:TreeNode, sum:int, cur_sum:int):
if not root.left and not root.right:
if cur_sum + root.val == sum:
return True
else:... |
"""
Given integers x and n, find the largest integer k such that x0+x1+x2+...+xk ≤ n.
Example
For x = 2 and n = 5, the output should be
specialPolynomial(x, n) = 1.
We have 20 + 21 < 5 and 20 + 21 + 22 > 5.
"""
def specialPolynomial(x, n):
s = 0
for k in range(1000):
s += math.pow(x, k)
if ... |
ENTRY_POINT = 'will_it_fly'
#[PROMPT]
def will_it_fly(q,w):
'''
Write a function that returns True if the object q will fly, and False otherwise.
The object q will fly if it's balanced (it is a palindromic list) and the sum of its elements is less than or equal the maximum possible weight w.
Example:
... |
def moeda(p = 0, moeda = 'R$'):
return (f'{moeda}{p:.2f}'.replace('.',','))
def metade(p = 0, formato=False):
res = p/2
return res if formato is False else moeda(res)
def dobro(p = 0, formato=False):
res = p*2
return res if formato is False else moeda(res)
def aumentar(p = 0, taxa = 0, formato... |
class BookReader:
country = 'South Korea'
print(BookReader.country )
BookReader.country = 'USA'
print(BookReader.country )
|
#Faça um programa que leia o peso de cinco pessoas. No final, mopstre qual foi o maior e o menor peso lidos
vMaior = 0
vMenor = 0
for i in range (1,6):
vPeso = float(input('Digite o peso da {} pessoa: '.format(i)))
if i== 1:
vMaior = vPeso
vMenor = vPeso
else:
if vPeso > vMaior:
... |
"""
File used to test the scraping ability of the regular
expressions.
"""
# Setting up our fake functions and objects.
_ = lambda x: x
f = lambda x: x
class C(object):
pass
obj = C()
obj.blah = lambda x: x
# A single letter function that we don't want
f("_key")
# Simple function call.
_("_key")
# The chained ... |
def patxi():
tip = raw_input("Don't forget to use your new company WC as soon as possible, It's important....")
kk = """ @@X
@@@@@'
... |
# DESCRIPTION
# Given a string containing only three types of characters: '(', ')' and '*',
# write a function to check whether this string is valid.
# We define the validity of a string by these rules:
# Any left parenthesis '(' must have a corresponding right parenthesis ')'.
# Any right parenthesis ')' must ... |
lines = open('dayfivedata.txt').read().split('\n')
ids = []
for line in lines:
top = 0; bottom = 127
for _ in range(7):
if 'F' in line[_]:
bottom = (top+bottom)//2
else:
top = (top+bottom)//2 + 1
left = 0; right = 7
for _ in range(7, 10):
if 'L' in line[_]... |
"""feedshepherd
All your (fairly simple) feed needs
"""
|
def plot_confusion_matrix(cm, class_names):
"""
Returns a matplotlib figure containing the plotted confusion matrix.
Args:
cm (array, shape = [n, n]): a confusion matrix of integer classes
class_names (array, shape = [n]): String names of the integer classes
"""
figure = plt.figure(figsize=(8, 8))
... |
n=int(input())
ans=[]
used=[False for i in range(n)]
d=[i+1 for i in range(n)]
a=list(map(int,input().split()))
p=0
f=False
while True:
for i in range(n-1):
if f:
i=n-2-i
if a[i]>i+1 and a[i+1]<i+2 and not used[i]:
ans.append(i+1)
used[i]=True
a[i],a[i... |
def main():
print('Olá') |
__all__ = ["Dog", "test1", "name"]
class Animal(object):
pass
class Dog(Animal):
pass
class Cat(Animal):
pass
def test1():
print("test1")
def test2():
print("test2")
def test3():
print("test3")
name = "小明"
age = "22"
|
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: jiansenll@163.com
@file: jianzhi_offer_60.py
@time: 2019/5/9 13:54
@desc:
'''
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class... |
# Exercício Python 51: Desenvolva um programa que leia o primeiro termo e a razão de uma PA. No final, mostre os 10 primeiros termos dessa progressão.
x = int(input('Valor: '))
y = int(input('Primeiro termo: '))
z = int(input('Segundo termo: '))
r = z-y
for i in range(1,10):
a = x + (10 - 1)*r
print(a) |
'''EXCERCISSE 1: EMOJI CONVERTER'''
# def greet_me(name, message):
# words = message.split(" ") # Converts input message into list
# emojis = { # Dictionary
# ":)" : "😃",
# ":(" : "🙁",
# ":o" : "😮",
# ":|" : "😑"}
# output = "" # Can be a... |
#Exercício Python 071: Crie um programa que simule o funcionamento de um caixa eletrônico. No início, pergunte
# ao usuário qual será o valor a ser sacado (número inteiro) e o programa vai informar quantas cédulas de cada valor serão entregues.
# OBS: considere que o caixa possui cédulas de R$50, R$20, R$10 e R$1.
valo... |
# position, name, age, level, salary
se1 = ["Software Engineer", "Max", 20, "Junior", 5000]
se2 = ["Software Engineer", "Lisa", 25, "Senior", 7000]
# class
class SoftwareEngineer:
# class attributes
alias = "Keyboard Magician"
def __init__(self, name, age, level, salary):
# instance attributes
... |
##
# \breif Copula function rotation helpers
#
# These helpers must be implemented outside of
# copula_base since we need access to them in all
# our child copula classes as decorators.
#
# Rotate the data before fitting copula
#
# Always rotate data to original orientation after
# evaluation of copula functions
def r... |
class Usuario:
def __init__(self):
self.usuario=""
self.ingresos=0
def intro(self):
self.usuario=input("Ingrese el nombre del usuario:")
self.ingresos=float(input("Cantidad ingresos anual:"))
def visualizar(self):
print("Nombre:",self.usuario)
... |
a=3
b=6
a,b=b,a
print('After Swapping values of A and B are',a,b)
|
def pow(base,exponent):
"""
Given a base b and an exponent e, this function returns b^e
"""
return base**exponent |
def calculaData(horaInicial, minutoInicial, segundoInicial, horaFinal, minutoFinal, segundoFinal):
if segundoFinal < segundoInicial:
#entao a subtracao nao eh possivel, para contornar o problema pedimos emprestado para os minutos 60 segundos
minutoFinal -= 1
segundoFinal += 60
resultadoSS = segundoFin... |
class LayerManager:
""" """
def __init__(self, canvas):
self.canvas = canvas
self.current_layer = 0
self.layers = []
def set_layer(self, cid):
self.current_layer = self.canvas.find_withtag('caption-'+str(cid))[0]
print(self.current_layer)
def raise_layer(self... |
#Exercício062
termo = int(input('\033[34mDigite o primeiro termo de uma PA: \033[m'))
razao = int(input('\033[34mDigite a razão dessa PA: \033[m'))
contador = 0
contador2 = 0
contador3 = 0
print('\033[34mOs 10 primeiros termos dessa PA são: ')
resultado = termo + razao #Soma o termo com a razão pela primeira vez e já m... |
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
if not matrix:
return 0
lines = len(matrix)
lists = len(matrix[0])
mat = [[0] * lists for _ in range(lines)]
for i in range(lists):
mat[0][i] = int(matrix[0][i])
for i in ... |
class Solution:
def singleNumber(self, nums: List[int]) -> int:
d = {}
for num in nums:
if num not in d:
d[num] = 1
else:
d[num] = d[num] + 1
for k,v in d.items():
if v == 1:
return k
|
# https://leetcode.com/problems/find-the-difference/
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
s = sorted(s)
t = sorted(t)
count = 0
for i in range(len(s)):
if s[i] != t[i] :
count = 1
print(t[i])
... |
model_imports = {
"Linear Regression": "from sklearn.linear import LinearRegression",
"Decision Tree": "from sklearn.tree import DecisionTreeRegressor",
"Random Forest": "from sklearn.ensemble import RandomForestRegressor",
"Gradient Boosting": "from sklearn.ensemble import GradientBoostingRegressor",
... |
for i in range(1,5):
for j in range(1,5):
print(j,end=" ")
print( )
|
def round_off(ls2): # Function for the algorithm to obtain the desired output
final_grade = []
for value in ls2: # iterating in the list to read every student's marks
reminder = value % 5 # calculating remainder
if value < 38:
final_grade.append(value)
elif reminder >= 3: ... |
"""
Code used for the 'Singly linked list' class.
"""
class Node:
"Represents a single linked node."
def __init__(self, data, next = None):
self.data = data
self.next = None
def __str__(self):
"String representation of the node data."
return str(self.data)
def __repr_... |
n,m = map(int,input().split())
rows = [input() for _ in range(n)]
k = int(input())
for row in sorted(rows, key=lambda row: int(row.split()[k])):
print(row)
|
def validacao(cpf):
original=cpf
verificacao=False
digito2=cpf%10
cpf=cpf//10
digito1=cpf%10
cpf=cpf//10
soma=0
for i in range (2,11):
cpfSeparado=cpf%10
soma=soma+(cpfSeparado*i)
cpf=cpf//10
verificador1=soma%11
if verificador1>2:
verificador1=11-... |
def func_header(funcname):
print('\t.global %s' % funcname)
print('\t.type %s, %%function' % funcname)
print('%s:' % funcname)
def push_stack(reg):
print('\tstr %s, [sp, -0x10]!' % reg)
def pop_stack(reg):
print('\tldr %s, [sp], 0x10' % reg)
def store_stack(value, offset):
print('\tmov... |
(10 and 2)[::-5]
(10 and 2)[5]
(10 and 2)(5)
(10 and 2).foo
-(10 and 2)
+(10 and 2)
~(10 and 2)
5 ** (10 and 2)
(10 and 2) ** 5
5 * (10 and 2)
(10 and 2) * 5
5 / (10 and 2)
(10 and 2) / 5
5 // (10 and 2)
(10 and 2) // 5
5 + (10 and 2)
(10 and 2) + 5
(10 and 2) - 5
5 - (10 and 2)
5 >> (10 and 2)
(10 and 2) << 5
... |
inputA = 277
inputB = 349
score = 0
queueA = []
queueB = []
i = 0
while len(queueA) < (5*(10**6)):
inputA = (inputA*16807)%2147483647
if inputA%4 == 0: queueA.append(inputA)
while len(queueB) < (5*(10**6)):
inputB = (inputB*48271)%2147483647
if inputB%8 == 0: queueB.append(inputB)
for i in range(0,(5*(10**6... |
# Created by MechAviv
# [Magic Library Checker] | [1032220]
# Ellinia : Magic Library
if "1" not in sm.getQuestEx(25566, "c3"):
sm.setQuestEx(25566, "c3", "1")
sm.chatScript("You search the Magic Library.") |
"""
Write a Python program to find whether a given number (accept from the user) is even or odd, print out an appropriate message to the user.
"""
x = int(input("Enter a number : "))
if x%2==1:
print("The number is an even number")
else:
print("The number is an odd number")
|
class Comparable:
def __init__(self, value):
self.value = value
def __eq__(self, other):
other_value = other.value if isinstance(other, Comparable) else other
return self.value == other_value
def __ne__(self, other):
other_value = other.value if isinstance(other, Comparabl... |
def DecodeToFile(osufile, newfilename, SVLines: list):
with open(newfilename, "w+") as f:
old = open(osufile, "r")
old = old.readlines()
old_TotimingPoints = old[:old.index("[TimingPoints]\n") + 1]
old_afterTimingPoints = old[old.index("[TimingPoints]\n") + 1:]
all_file = old... |
#Program for a Function that takes a list of words and returns the length of the longest one.
def longest_word(list): #define a function which takes list as a parameter
longest=0
for words in list: #l... |
def print_a_string():
my_string = "hello world"
print(my_string)
def print_a_number():
my_number = 9
print(my_number)
# my logic starts here
if __name__ == "__main__":
print_a_string()
print_a_number()
print("all done...bye-bye") |
def hms2dec(h,m,s):
return 15*(h + (m/60) + (s/3600))
def dms2dec(d,m,s):
if d>=0:
return (d + (m/60) + (s/3600))
return (d - (m/60) - (s/3600))
if __name__ == '__main__':
print(hms2dec(23, 12, 6))
print(dms2dec(22, 57, 18))
print(dms2dec(-66, 5, 5.1)) |
#! /root/anaconda3/bin/python
"""
(base) [root@k8s-ansible file]# cat myfile.txt
1234567890
abcdefghijklmn
opqrstuvwxyz
"""
# readlines参数
file = open('myfile.txt')
print(file.readlines())
file.close()
# readlines 例子一
file = open('myfile.txt')
print(file.readlines(8))
file.close()
# readlines 例子二
file = open('myfile.t... |
class PossumException(Exception):
"""Base Possum Exception"""
class PipenvPathNotFound(PossumException):
"""Pipenv could not be located"""
class SAMTemplateError(PossumException):
"""There was an error reading the template file"""
|
no_list = [22,68,90,78,90,88]
def average(x):
#complete the function's body to return the average
length=len(no_list)
return sum(no_list)/length
print(average(no_list))
|
__lname__ = "yass"
__uname__ = "YASS"
__acronym__ = "Yet Another Subdomainer Software"
__version__ = "0.8.0"
__author__ = "Francesco Marano (@mrnfrancesco)"
__author_email__ = "francesco.mrn24@gmail.com"
__source_url__ = "https://github.com/mrnfrancesco/yass"
|
end = 1000
total = 0
for x in range(1,end):
if x % 15 == 0:
total = total + x
print(x)
elif x % 5 == 0:
total = total + x
print(x)
elif x % 3 == 0:
total = total + x
print(x)
print(f"total = {total}") |
# Section 3-16
# Question: How do we find the sum of the digits of a positive integer using recursion?
# Step 1: The recursive case
# Add the current digit to a total
# Step 2: The Base Condition
# If there are no more digits, return the total
# Step 3: The unintended cases
# If the input is not a positive integer... |
template = '''
<head>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" />
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script... |
# -*- coding: utf-8 -*-
"""This module contains two variables which will store all defined nodes models and instances
"""
model_store = {}
node_store = {}
|
'''desafio40: faça um programa de um programa ue determine o MAIOR dentre 400 números inseridos.
OBS: só é possivel mostrar o maior dos números no FINAL de todas as inserções'''
#
x = 1
z = 1
while (x<=400):
y = int(input('Insira o número {}: '.format(x)))
if (y>z):
z=y
x = x+1
print('O maior número inseri... |
def binarySearch(arr, l, r, x):
while l <= r:
mid = l + (r - l) / 2;
# Check if x is present at mid
if arr[mid] == x:
return mid
# If x is greater, ignore left half
elif arr[mid] < x:
l = mid + 1
# If x is smaller, ignore right half
... |
# Segment tree
class SegmentTree:
def __init__(self, data):
size = len(data)
t = 1
while t < size:
t <<= 1
offset = t - 1
index = [0] * (t * 2 - 1)
index[offset:offset + size] = range(size)
for i in range(offset - 1, -1, -1):
x = index[... |
'''import math #as m also can be written
a=math.pi #a=m.pi
print(a)
'''
'''
from math import pi #import only pi from math
b=2*pi
print(b)
'''
'''
from math import * #import everything from math
b=2*pi
print(b)
'''
'''
food = 'spam'
if food == 'spam':
print('Ummmm, my favourite!')
print('I feel like sa... |
def test_post_order(client, order_payload):
res = client.post("/order", json = order_payload)
assert res.status_code == 200
def test_post_game(client, game_payload):
res = client.post("/order", json = game_payload)
assert res.status_code == 200
def test_get_order(client):
res1 = client.get("/o... |
class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
hour_deg = (hour*30)%360 + (0.5)*minutes
minute_deg = ((minutes/5)*30)%360
if(abs(hour_deg-minute_deg)>180):
return 360 - abs(hour_deg-minute_deg)
else:
return abs(hour_d... |
class Solution:
def findDuplicate(self, nums: list[int]) -> int:
nums.sort()
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
return nums[i]
class Solution:
def findDuplicate(self, nums: list[int]) -> int:
# 'low' and 'high' represent the range of va... |
num = int(input(''))
hours = int(input(''))
value = float(input(''))
print('NUMBER = {:0}\nSALARY = U$ {:.2f}'.format(num, (hours * value))) |
"""
Unit tests for pyDEX project should all go in this module
author: officialcryptomaster@gmail.com
"""
|
class Solution(object):
def combinationSum2(self, candidates, target):
ret = []
self.dfs(sorted(candidates), target, 0, [], ret)
return ret
def dfs(self, nums, target, idx, path, ret):
if target <= 0:
if target == 0:
ret.append(path)
r... |
#!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Jiao Lin
# California Institute of Technology
# (C) 2007 All Rights Reserved
#
# {LicenseText}
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... |
str1 = "Udacity"
# LENGTH
print(len(str1)) # 7
# CHANGE CASE
# The `lower()` and `upper` method returns the string in lower case and upper case respectively
print(str1.lower()) # udacity
print(str1.upper()) # UDACITY
# SLICING
# string_var[lower_index : upper_index]
# Note that the upper_index is not inclusive... |
class Line:
def __init__(self,p1,p2):
if (p1[0] > p2[0]):
self.p1 = p2
self.p2 = p1
elif (p1[0] == p2[0] and p1[1] > p2[1]):
self.p1 = p2
self.p2 = p1
else:
self.p1 = p1
self.p2 = p2
print(self.p1)
prin... |
class Node:
pass
class SystemNode(Node):
def __init__(self, equations):
self.equations = equations
class EquationNode(Node):
def __init__(self, differential, expression):
self.differential = differential
self.expression = expression
class DifferentialNode(Node):
def __init_... |
"""Assignment operators
@see: https://www.w3schools.com/python/python_operators.asp
Assignment operators are used to assign values to variables
"""
def test_assignment_operator():
"""Assignment operator """
assert True
# Multiple assignment.
# The variables first_variable and second_variable simul... |
#!/usr/bin/env python
"""Tests for `tools_1c` package."""
|
"""Generate warnings for Machine statistics"""
def cpu_warning_generator(cpu_tuple):
# Returns boolean value false if used cycles is greater than idle cycles
used_time = cpu_tuple.user + cpu_tuple.nice + cpu_tuple.system
if used_time > cpu_tuple.idle:
return True
else:
return False
def ... |
frase = str(input('Digite uma frase: '))
cont = 1
for c in frase:
if cont % 2 == 0:
print(c.upper(), end='')
else:
print(c.lower(), end='')
cont += 1
|
# https://stackoverflow.com/questions/13979714/heap-sort-how-to-sort
swaps = 0
def heapify(arr, n, i):
global swaps
count = 0
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if... |
temp = {
"email": "email@email.com",
"name": "Sample Data",
"penalties": "3",
"responses": {
"101": "[1, 2, ‘hello’]",
"201": "34.000000",
"301": "27.2",
"401": "Class",
"501": "^"
},
"timestamp": "2021-01-31 13:... |
class Solution:
def solve(self, words):
groups = defaultdict(list)
for word in words:
for key in groups:
if len(word)==len(key) and any(all(word[j]==key[j-i] for j in range(i,len(word))) and all(word[j]==key[len(word)-i+j] for j in range(i)) for i in range(len(word))):
... |
# -*- coding: utf-8 -*-
streams = (
("Hitradio Ö3", "http://mp3stream7.apasf.apa.at:8000/;stream.nsv"),
("FM4", "http://mp3stream1.apasf.apa.at:8000/;stream.nsv"),
("Radio Arabella", "http://stream10.arabella-at.vss.kapper.net:8000/listen.pls"),
("Radio Wien", "http://mp3stream2.apasf.apa.at:8000/;strea... |
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]: Restaurantlessthan20, obj[15]: Re... |
pt = int(input('Digite o 1° termo da PA: '))
r = int(input('Digite a razão: '))
c = 0
v = 0
while c != 10:
c += 1
v = pt + ((c - 1) * r)
print('A{} = {}'.format(c, v)) |
#-- gestures supported by Otto
#-- OttDIY Python Project, 2020
OTTOHAPPY = const(0)
OTTOSUPERHAPPY = const(1)
OTTOSAD = const(2)
OTTOSLEEPING = const(3)
OTTOFART = const(4)
OTTOCONFUSED = const(5)
OTTOLOVE = const(6)
OTTOANGRY = const(7)
OTTOFRETFUL = const(8)
OTTOMAGIC = cons... |
products = {}
command = input()
while command != "statistics":
command = command.split(": ")
key = command[0]
value = int(command[1])
if key not in products:
products[key] = 0
products[key] += value
command = input()
print("Products in stock:")
for k, v in products.items():
print(... |
# Simple function to add values
def aFunction():
a = 1
b = 2
c = a + b
print(c)
return c
# simple loop to count up in a range
def aLoop():
count = 0
# for each item in the range
for item in range(0, 100):
print(count)
count = count + 1
return count... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.