content stringlengths 7 1.05M |
|---|
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 8 08:54:01 2019
@author: balam
"""
|
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr) // 2
leftHalf = arr[:mid] # 56,24,93,17
rightHalf = arr[mid:] # 77,31,44,55,20
mergeSort(leftHalf)
mergeSort(rightHalf)
i = j = k = 0
while i < len(leftHalf) and j < len(rightHalf):
if leftHalf[i... |
# for循环是一种遍历列表的有效方式, 但在for循环中不应修改列表, 否则将导致Python难以跟踪其中的元素.
# 要在遍历列表的同时对其进行修改, 可使用while循环.
# 在列表之间移动元素
unconfirmed_users = ['alice', 'brian', 'candace'] # 待验证用户列表
confirmed_users = [] # 已验证用户列表
# 遍历列表对用户进行验证
while unconfirmed_users: # 当列表不为空时返回True, 当列表为空时, 返回False
current_user = unconfirmed_users.pop() # 取... |
# ask for int, report runnig total / version 1
num = 0
total = 0
while num != -1:
total = total + num
print("total so far = " + str(total))
num = int(input("next int: "))
# ask for int, report runnig total / version 2
total = 0
while True:
num = int(input("next int: "))
if num == -1:
break... |
# Given a list of lists of integers, nums, return all elements of nums in diagonal order as shown in the below images.
#
# Example 1:
#
#
#
#
# Input: nums = [[1,2,3],[4,5,6],[7,8,9]]
# Output: [1,4,2,7,5,3,8,6,9]
#
#
# Example 2:
#
#
#
#
# Input: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]
# Output: [1... |
#!/usr/bin/env python3
#################################################################################
# #
# Program purpose: Generate message based on user input. #
# Program Author : Happi Yvan <ivensteinpok... |
class Tree:
def __init__(self):
self.left = None
self.right = None
self.data = None
def init_left_child(self):
self.left = Tree()
def init_right_child(self):
self.right = Tree()
def init_both_childs(self):
self.init_left_child()
self.init_right_... |
'''
Title : Loops
Subdomain : Introduction
Domain : Python
Author : Kalpak Seal
Created : 28 September 2016
'''
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(raw_input())
for i in range(0, n):
print (i ** 2) |
local_val = 'magical creature'
def square(x):
return x * x
class User:
def __init__(self, name):
self.name = name
def say_hello(self):
return 'Hello'
# This conditional allows us to run certain blocks of code depending on which file they're in
if __name__ == "__main__":
print('the file ... |
t = int(input())
for _ in range(t):
a, b = [int(x) for x in input().split()]
print(a * b)
|
"""
アドオンのデフォルト設定を定義する。
この定義は `addons/アドオン名/settings/local.py` に記述された設定により上書きされる。
"""
# NodeSettingsモデル `models.py` の `param_1` のデフォルト値
DEFAULT_PARAM_1 = 'This is test!'
|
"""Rules to work with protoc plugins in a language agnostic manner.
"""
load("@bazel_skylib//lib:paths.bzl", "paths")
load("@rules_proto//proto:defs.bzl", "ProtoInfo")
load("//protoc:providers.bzl", "ProtocPluginInfo")
_DEFAULT_PROTOC = "@com_google_protobuf//:protoc"
def run_protoc(
ctx,
protos,
... |
# coding: utf-8
class LNode:
""" 单链表节点 """
def __init__(self, value, next_=None):
self.value = value
self.next_ = next_
def reverse_link_list(link_list):
""" 翻转单链表 """
if not link_list:
return
current = link_list.next_
link_list.next_ = None
pre = link_list
... |
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
res = []
candidates.sort()
def backtrack(pos,cur,target):
if target == 0 :
res.append(cur.copy())
if target <= 0 :
... |
class NumString:
def __init__(self, value):
self.value = str(value)
def __str__(self):
return self.value
def __int__(self):
return int(self.value)
def __float__(self):
return float(self.value)
#EXAMPLE: NumString(5) + 5 = 10
def __add__(self, other):
if '.' in self.value:
return float(self) + oth... |
# import time
def slowprint(string):
for letter in string:
print(letter, end='')
# time.sleep(.05)
|
def prob1():
sum = 0
i = 1
for i in range(1000):
if (((i % 3) == 0) or ((i % 5) == 0)):
sum = sum +i
print(sum)
print(i)
if __name__ == "__main__":
print("Project Euler Problem 1")
prob1() |
# String Formation
'''
Given an array of strings, each of the same length and a target string construct the target string using characters from the strings in the given array such that the indices of the characters in the order in which they are used to form a strictly increasing sequence. Here the index of character i... |
# colors.py
#
# GameGenerator is free to use, modify, and redistribute for any purpose
# that is both educational and non-commercial, as long as this paragraph
# remains unmodified and in its entirety in a prominent place in all
# significant portions of the final code. No warranty, express or
# implied, is made regard... |
#!/usr/bin/env python
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O',... |
# Python code to reverse a string
# using loop
def reverse(s):
str = ""
for i in s:
str = i + str
return str
s = "Geeksforgeeks"
print ("The original string is : ",end="")
print (s)
print ("The reversed string(using loops) is : ",end="")
print (reverse(s))
|
def has_line(game_result):
for l in game_result:
if l == tuple("XXX"):
return "X"
elif l == tuple("OOO"):
return "O"
return None
def has_col(game_result):
return has_line(zip(*[list(e) for e in game_result]))
def has_diag(game_result):
def check_diag(c, reverse=... |
#!/usr/bin/env python3
def validate_no_repeated(passphrase):
words = passphrase.strip().split()
return len(set(words)) == len(words)
def validate_no_anagrams(passphrase):
words = [''.join(sorted(word)) for word in passphrase.strip().split()]
return len(set(words)) == len(words)
assert validate_no_... |
def clean_number_list(numbers_to_add):
"""
Input: a List of numbers to be added together
Function will clean the list and then return the new list.
Cleaning involves conversion of string to numbers
Function will return False if an invalid value has been found
"""
# Verify that the input is ... |
linha = '-' * 30
totMais18 = 0
totHomens = 0
totMulherMenos20 = 0
while True:
print(linha)
print('{:^30}'.format('CADASTRE UMA PESSOA'))
print(linha)
idadeTXT = ' '
while not idadeTXT.isnumeric():
idadeTXT = str(input('Idade: '))
idade = int(idadeTXT)
sexo = ' '
while sexo not in... |
"""
A pangram is a sentence where every letter of the English alphabet appears at least once.
Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise.
Example 1:
Input: sentence = "thequickbrownfoxjumpsoverthelazydog"
Output: true
Explanation: sentence... |
GRAPH = {
"A": ["B","D","E"],
"B": ["A","C","D"],
"C": ["B","G"],
"D": ["A","B","E","F"],
"E": ["A","D"],
"F": ["D"],
"G": ["C"]
}
def bfs(graph, current_vertex):
queue = [] # an empty queue
visited = [] # an empty list of visited nodes
queue.append(current_vertex) ... |
# use an increment and assign operator
count = 0
while count != 5:
count += 1
print(count)
# increment count by 3
count = 0
while count <= 20:
count += 3
print(count)
# decrements count by 3
count = 20
while count >= 0:
count -= 3
print(count)
|
class Solution:
def solve(self, s):
lCount = 0
rCount = 0
choiceCount = 0
for i in s:
if i == 'L':
lCount += 1
elif i == 'R':
rCount += 1
else:
choiceCount += 1
if lCount > ... |
class Vertice:
def __init__(self, n):
self.nombre = n
class Grafo:
vertices = {}
bordes = []
indices_bordes = {}
def agregar_vertice(self, vertex):
if isinstance(vertex, Vertice) and vertex.nombre not in self.vertices:
self.vertices[vertex.nombre] = vertex
... |
#Single line concat
"Hello " "World"
#Multi line concat with line continuation
"Goodbye " \
"World"
#Single line concat in list
[ "a" "b" ]
#Single line, looks like tuple, but is just parenthesized
("c" "d" )
#Multi line in list
[
'e'
'f'
]
#Simple String
"string"
#String with escapes
"\n\n\n\n"
#Str... |
class WalletError(Exception):
"""Base Exception raised for all wallet errors."""
pass
class InsufficientFunds(WalletError):
"""Error raised when address has insufficient funds to make a transaction.
Attributes:
address: input address for which the error occurred
balance: current bala... |
num1 = 111
num2 = 222
num3 = 333333
num3 = 333
num4 = 444
num6 = 666
num5 = 555
num7 = 777
|
# True & False
limit = 5000
limit == 4000 # returns False
limit == 5000 # returns True
5 == 4 # returns False
5 == 5 # returns True
# if & else & elif
gain = 50000
limit = 50000
if gain > limit:
print("gai... |
#!/usr/bin/env python
''' THIS IS DOUBLY LINKED LIST IMPLEMENTATION '''
class Node:
def __init__(self, prev=None, next=None, data=None):
self.prev = prev
self.next = next
self.data = data
def __str__(self):
return str(self.data)
class DoublyLinkedList:
def __init__(self):... |
"""
Created on Wed Aug 25 12:52:52 2021
AI and deep learnin with Python
Data types and operators
Quiz Data types and Operators
"""
# The current volume of a water reservoir is ( in cubic meters)
reservoir_volume = 4.445e8
# The amount of rainfall from a storm (in cubic meters)
rainfall = 5e6
# Decrea... |
'''input
2
9
3 6
12
5
20
11 12 9 17 12
74
'''
# -*- coding: utf-8 -*-
# AtCoder Beginner Contest
# Problem B
if __name__ == '__main__':
ball_count = int(input())
robotB_position = int(input())
positions = list(map(int, input().split()))
total_length = 0
for i in range(b... |
S = input()
K = int(input())
for i, s in enumerate(S):
if s == "1":
if i + 1 == K:
print(1)
exit()
else:
print(s)
exit()
|
# PASSED
_ = input()
lst = sorted(list(map(int, input().split())))
output = []
if len(lst) % 2:
output.append(lst.pop(0))
while lst:
output.append(lst[-1])
output.append(lst[0])
lst = lst[1:-1]
print(*reversed(output)) |
'''
Read numbers and put in a list
one list will have the EVEN numbers
the other will have the ODD ones
SHow the result
'''
odd_list = []
even_list = []
num = int(input('Type a number: '))
if num%2 == 0:
even_list.append(num)
elif num%2 != 0:
odd_list.append(num)
while True:
opt = str(input('Do you want to... |
__version__ = "1.0.8"
def get_version():
return __version__
|
#14
def sumDigits(num):
sum = 0
for digit in str(num):
sum += int(digit)
return sum
num = int(input('Enter a 4-digit number:'))
print('Sum of the digits:', sumDigits(num))
|
# 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 findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
... |
class BinaryChunkHeader:
LUA_SIGNATURE = bytes(b'\x1bLua')
LUAC_VERSION = 0x53
LUAC_FORMAT = 0x0
LUAC_DATA = bytes(b'\x19\x93\r\n\x1a\n')
CINT_SIZE = 4
CSIZET_SIZE = 8
INST_SIZE = 4
LUA_INT_SIZE = 8
LUA_NUMBER_SIZE = 8
LUAC_INT = 0x5678
LUAC_NUM = 370.5
def __init__(self... |
data = [
'I live in a house near the mountains. I have two brothers and one sister, and I was born last. My father teaches mathematics, and my mother is a nurse at a big hospital. My brothers are very smart and work hard in school. My sister is a nervous girl, but she is very kind. My grandmother also lives with u... |
# FUNCTIONS
# Positional-Only Arguments
def pos_only(arg1, arg2, /):
print(f'{arg1}, {arg2}')
pos_only('One', 2)
# Cannot pass keyword arguments to a function of positional-only arguments
# pos_only(arg1='One', arg2=2)
# Keyword-Only Arguments
def kw_only(*, arg1, arg2):
print(f'{arg1}, {ar... |
"""
bigrange - big ranges. Really.
Only one cool iterator in Python that supports big integers.
"""
def bigrange(a,b,step=1):
"""
A replacement for the xrange iterator; the builtin class
doesn't handle arbitrarely large numbers.
Input:
a First numeric output
b Lower... |
class PM:
def __init__(self):
pass
def get_possible_state(self, filled=True):
if filled:
state = self.user_info['state']
possible_states = self.state_info[state].get('possible_states', [])
self.user_info['possible_states'] = possible_states
else:
... |
class Solution(object):
def reorderLogFiles(self, logs):
letter_log = {}
letter_logs = []
res = []
for idx, log in enumerate(logs):
if log.split(' ')[-1].isdigit():
res.append(log)
else:
letters = tuple(log.split(' ')[1:])
... |
class FiniteStateMachine:
def __init__(self, states, starting):
self.states = states
self.current = starting
self.entry_words = {} # Dictionary of states, {state.name : word}, words where words are the words used to enter the state
self.stay_words = {} # Dictionary of states, {state... |
# 1η θέση = 20€ , 2η θέση = 15€ και 3η θέση = 10€
def ektelesi():
ticket_issues = 'Y'
income = 0
pos_1 = 0 # Θα χρησιμοποιηθεί για την καταμέτρηση των εισιτηρίων, 1ηςΘΕΣΗΣ
pos_2 = 0 # Θα χρησιμοποιηθεί για την καταμέτρηση των εισιτηρίων, 2ηςΘΕΣΗΣ
pos_3 = 0 # Θα χρησιμοποιηθεί για την κα... |
# Faça um programa que leia o valor de um produto e imprima o valor com desconto,
# tendo em vista que o desconto foi de 12%
produto = float(input("Digite o valor do produto: "))
desconto = produto - (0.12 * 100)
print(f"O valor final do produto é: {desconto}")
|
class _ReadOnlyWidgetProxy(object):
def __init__(self, widget):
self.widget = widget
def __getattr__(self, name):
return getattr(self.widget, name)
def __call__(self, field, **kwargs):
kwargs.setdefault('readonly', True)
return self.widget(field, **kwargs)
def readonly_fi... |
def reverse(s):
return " ".join((s.split())[::-1])
s = input("Enter a sentence: ")
print(reverse(s)) |
fenceMap = hero.findNearest(hero.findFriends()).getMap()
def convertCoor(row, col):
return {"x": 34 + col * 4, "y": 26 + row * 4}
for i in range(len(fenceMap)):
for j in range(len(fenceMap[i])):
if fenceMap[i][j] == 1:
pos = convertCoor(i, j)
hero.buildXY("fence"... |
class Student:
pass
Jiggu = Student()
Himanshu = Student()
Jiggu.name = "Jiggu"
Jiggu.std = 12
Jiggu.section = 1
Himanshu.std = 11
Himanshu.subjects = ["Hindi","English"]
print(Jiggu.section, Himanshu.subjects)
|
#
# PySNMP MIB module NETSCREEN-VPN-PHASEONE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NETSCREEN-VPN-PHASEONE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:10:52 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
class Solution:
def xorOperation(self, n: int, start: int) -> int:
#Defining the nums array
nums=[int(start+2*i) for i in range (n)]
#Initializing the xor
xor=nums[0]
for i in range(1,len(nums)):
... |
# 定义文件夹
train_dir = 'flowers/train'
valid_dir = 'flowers/valid'
test_dir = 'flowers/test'
# 训练集
data_transforms_train = transforms.Compose([
transforms.RandomResizedCrop(244), # 此处224是图片尺寸
transforms.RandomRotation(45),
transforms.RandomHorizontalFlip(), # RandomResizedCrop
transforms.ToTensor(), # 转... |
'''
Body mass index is a measure to assess body fat. It is widely use because it is easy to calculate and can
apply to everyone. The Body Mass Index (BMI) can calculate using the following equation.
Body Mass Index (BMI) = weight / height2 (Height in meters)
If BMI is 40 or greater, the program should print Fattest.
If... |
"""
Problem:
3.2 Stack Min: How would you design a stack which, in addition to push and pop, has a function min
which returns the minimum element? Push, pop and min should all operate in 0(1) time.
Hints:#27, #59, #78
--
Algorithm
The default implementation of a Stack already has Push and Pop as operations in O(1) ... |
#!/usr/bin/env python3
# Write a program that computes the GC% of a DNA sequence
# Format the output for 2 decimal places
# Use all three formatting methods
dna = 'ACAGAGCCAGCAGATATACAGCAGATACTAT' # feel free to change
s_count = 0
for nt in dna:
if nt == "G" or nt == "C":
s_count += 1
s_frac = s_count / ... |
#[playbook(say_hi)]
def say_hi(ctx):
with open('/scratch/output.txt', 'w') as f:
print("{message}".format(**ctx), file=f)
|
class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
s=pattern
t=str.split()
return map(s.index, s) == map(t.index, t)
|
{
"targets": [
{
"target_name": "sypexgeo",
"sources": [
"src/xyz/vyvid/sypexgeo/bindings/nodejs/sypexgeo_node.cc",
"src/xyz/vyvid/sypexgeo/bindings/nodejs/sypexgeo_node.h",
"src/xyz/vyvid/sypexgeo/util/string_builder.h",
"src/xyz/vyvid/sypexgeo/uint24_t.h",
"sr... |
#
# PySNMP MIB module Unisphere-Data-AUTOCONFIGURE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Data-AUTOCONFIGURE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:23:11 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... |
# http://flask-sqlalchemy.pocoo.org/2.1/config/
SQLALCHEMY_DATABASE_URI = 'sqlite:////commandment/commandment.db'
# FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.
SQLALCHEMY_TRACK_MODIFICATIONS = False
PORT = 5443
# PLEASE! Do not take thi... |
def combine_words(word, **kwargs):
if 'prefix' in kwargs:
return kwargs['prefix'] + word
elif 'suffix' in kwargs:
return word + kwargs['suffix']
return word
print(combine_words('child', prefix='man'))
print(combine_words('child', suffix='ish'))
print(combine_words('child')) |
# -*- coding: utf-8 -*-
print('!'*30)
print(' Loja SUPER BARATÃO ')
print('!'*30)
lisProdutos = []
lisPrecos = []
precMil = 0
while True:
print('='*30)
lisProdutos.append(str(input('Nome do produto: ').strip() ).title())
precos = float(input('Preço: R$ '))
if precos >= 1000:
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 5 09:03:49 2020
@author: Okuda
"""
|
#Tuple
#ordered
#indexed
#Immutable
#Faster than list
t = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
print(t)
print(type(t))
#t.append(20) AttributeError: 'tuple' object has no attribute 'append'
print(t[2])
print(t[-1])
print(t[1:3])
print(len(t))
print(t.count("Monday"))
print(t.index("Friday")... |
# -*- coding: utf-8 -*-
PI = 3.14159
def main():
r = float(input())
area = PI * r * r
print('A=%.4f' % area)
if __name__ == '__main__':
main() |
def get_action(self, states, epsilon):
if np.random.random() < epsilon:
return np.random.choice(self.num_actions)
else:
return np.argmax(self.predict(np.atleast_2d(states))[0]) |
'-----------------------------------------------------------------------------'
#================================___ФУНКЦІЇ___================================
#Функція із рекурсією
def golden_pyramid(triangle, row=0, column=0, total=0):
if row == len(triangle) - 1:
return total + triangle[row][column]
... |
'''Crie um programa que leia o nome e o preço de vários produtos
O programa deverá perguntar se o usuário quer continuar
No final mostre
A) Qual é o total gasto na compra.
B) Quantos produtos custam mais de 1k.
C) Qual é o nome do produto mais barato.'''
print('\033[36m{:=^37}\033[m'.format('Code-Save'))
print('\033[3... |
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Time : 2019/9/17 15:01
@Author : Jay Chen
@FileName: response_code.py
@GitHub : https://github.com/cRiii
"""
class RET:
OK = 200
PARAMS_MISSING_ERROR = 2001
IMAGE_CODE_OVERDUE_ERROR = 2002
IMAGE_CODE_INPUT_ERROR = 2003
USER_LOGIN_ERR... |
class TogaLayout(extends=android.view.ViewGroup):
@super({context: android.content.Context})
def __init__(self, context, interface):
self.interface = interface
def shouldDelayChildPressedState(self) -> bool:
return False
def onMeasure(self, width: int, height: int) -> void:
# ... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
# Imports =====================================================================
# Functions & classes =========================================================
def _by_attr(xdom, attr):
"""
From `xdom` pick element with attri... |
L = list(map(int,list(input())))
i = 0
k = 1
while i < len(L):
L2 = list(map(int,list(str(k))))
j = 0
while i<len(L) and j <len(L2):
if L[i] == L2[j]:
i+=1
j+=1
k+=1
print(k-1) |
#
# PySNMP MIB module CENTILLION-ROOT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CENTILLION-ROOT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:15:30 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
l = 2
if(l == 1):
print(l)
elif(l == 2):
print(l+5)
else:
print(l+1)
|
n1, n2, n3 = map(int, input().split())
total = n1 * n2 * n3
print(total) |
class Atom:
def __init__(self, name, children):
self.name = name
self.children = children
if None in children:
raise Exception("none in lisp atom")
def __str__(self):
child_string = " ".join(
[str(e) if type(e) != str else f'"{e}"' for e in self.... |
#This algoritm was copied at 16/Nov/2018 from https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python and applied to activity sequences
delimter = "@"
def length(s):
return s.count(delimter) + 1
def enumerateSequence(s):
list = s.split(delimter)
return enumerate(list,0)
... |
# -*- Mode: Python; coding: utf-8; indent-tabs-mpythoode: nil; tab-width: 4 -*-
# CODEWARS
# https://www.codewars.com/kata/5583090cbe83f4fd8c000051
#
# "Convert number to reversed array of digits"
def digitize(n):
if n == 0:
return [0]
if n < 0:
n *= -1
arr = []
while n > 0:
... |
class Solution:
def lengthOfLastWord(self, s: str) -> int:
end = len(s) -1
c = 0
while s[end] == " ":
end -= 1
while s[end] != " " and end >= 0:
c += 1
end -= 1
return c |
class Phoneme:
def __init__(self, ptype: str):
self.ptype = ptype
class Cons(Phoneme):
def __init__(self, voice: int, ctype: str):
super().__init__("Cons")
self.voice = voice
self.ctype = ctype
class PulmCons(Cons):
def __init__(self, voice: int, pcmanner: int, pcplace: i... |
log_table = []
alpha_table = []
def multiplie(x, y, P):
if x == 0 or y == 0:
return 0
P_deg = len(bin(P)) - 3
i, j = log_table[x], log_table[y]
return alpha_table[(i + j) % ((1 << P_deg)-1)]
|
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 required by applicable law or agreed ... |
"""
auto generated test file
"""
# Create your tests here.
|
# https://leetcode.com/problems/delete-columns-to-make-sorted/
# You are given an array of n strings strs, all of the same length.
# The strings can be arranged such that there is one on each line, making a grid.
# For example, strs = ["abc", "bce", "cae"] can be arranged as:
# You want to delete the columns that ar... |
def full_query(okta_id, video_string, fan_string, limit=5000):
query = f'''
WITH
-- FIRST CTE
all_comments (
comment_id,
parent_youtube_comment_id,
youtube_fan_id,
by_creator,
content,
... |
n = int(input())
for j in range(1,n+1):
led = 0
x = input()
for i in range(0,len(x)):
if x[i] == '1':
led = led + 2
if x[i] == '2':
led = led + 5
if x[i] == '3':
led = led + 5
if x[i] == '4':
led = led + 4
if x[i] == ... |
#Write a Python program to sum of three given integers. However, if two values are equal sum will be zero
def sumif(a,b,c):
if a != b != c and c !=a:
return a+b+c
else:
return 0
print(sumif(42,5,9))
print(sumif(8,8,12))
print(sumif(9,54,9))
print(sumif(87,4,9)) |
# -*- coding: utf-8 -*-
# Copyright: (c) 2016, Charles Paul <cpaul@ansible.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
class ModuleDocFragment(object):
# Parameters for VCA modules
DOCUMENTATION = r'''
options:
username:
description:
- T... |
'''
Array Sum
You are given an array of integers of size . You need to print the sum of the elements in the array, keeping in mind that some of those integers may be quite large.
Input Format
The first line of the input consists of an integer . The next line contains space-separated integers contained in the array.
... |
DEFAULT_FPGA='VC709'
def addClock(file, FPGA=DEFAULT_FPGA):
file.write("#Clock Source\r\n")
if(FPGA=='VC709'):
file.write("set_property IOSTANDARD DIFF_SSTL15 [get_ports clk_p]\r\n")
file.write("set_property PACKAGE_PIN H19 [get_ports clk_p]\r\n")
file.write("set_property PACKAGE_PIN G1... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 30 22:11:59 2022
@author: Akshatha
"""
# recursive data structure
class TreeNode():
def __init__(self, data):
self.parent = None
self.data = data
self.children = []
def add_child(self, child):
self.children.... |
# Bucles For Each - Bucle "Para cada X"
# repite un conjunto de sentencias un determinado numero de veces. Es muy util para "recorer" listas de valores como listas, cadenas, diccionarios, rangos, etc.
# Una sentencia for comienza con la palabra clave for, seguida por una variable, seguido por la palabra clave in, segu... |
class Calculator:
def __init__(self, a: int, b: int) -> None:
self.a = a
self.b = b
def suma(self):
return self.a + self.b
def resta(self):
return self.a - self.b
def multiplicacion(self):
return self.a * self.b
def division(self):
try:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.