content stringlengths 7 1.05M |
|---|
class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
order_indx = {}
for idx,letter in enumerate(order):
order_indx[letter] = idx
# compare adjacent words
for i in range(len(words)-1):
word1 = words[i]
w... |
def center(win, width=100, height=100):
win.update_idletasks()
width = width
frm_width = win.winfo_rootx() - win.winfo_x()
win_width = width + 2 * frm_width
height = height
titlebar_height = win.winfo_rooty() - win.winfo_y()
win_height = height + titlebar_height + frm_width
x = win.wi... |
array = list(map(int, input('Enter the array of integers to be sorted(separated by spaces):').split()))
for i in range(len(array)):
min_idx = i
for j in range(i + 1, len(array)):
if array[min_idx] > array[j]:
min_idx = j
array[i], array[min_idx] = array[min_idx], array[i]
print("Sorted ... |
# -*- coding: utf-8 -*-
class CertstreamObject(object):
"""Base class for all the certstream data classes"""
@classmethod
def from_dict(cls, data):
"""
Returns a copy of the passed data
:param data: The dict from which an object should be created from
:return: copy of data... |
batch_size = 192*4
config = {}
# set the parameters related to the training and testing set
data_train_opt = {}
data_train_opt['batch_size'] = batch_size
data_train_opt['unsupervised'] = True
data_train_opt['epoch_size'] = None
data_train_opt['random_sized_crop'] = False
data_train_opt['dataset_name'] = 'imagenet'
... |
# -*- coding: utf-8 -*-
def main():
n = int(input())
ans = 0
for i in range(1, int(n ** 0.5) + 1):
if n % i == 0 and (i ** 2) != n:
m = n // i - 1
if n // m == n % m:
ans += m
print(ans)
if __name__ == '__main__':
main()
|
"""
Collection of lists and dicts representing types in the python C-API
"""
"""
CPython's function pointers as dict:
typename: (return_type, (args,))
"""
FUNCTIONS = {
"unaryfunc": ("PyObject*", ("PyObject*",)),
"binaryfunc": ("PyObject*", ("PyObject*", "PyObject*")),
"ternaryfunc... |
#
# PySNMP MIB module DOT3-OAM-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/DOT3-OAM-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:10:39 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)
#
( In... |
# base
class FyException(Exception):
def __init__(s, message):
s.message = '\n;;;;;\n'
s.message += s.__class__.__name__.replace('_', ' ')
s.message += '\n'
s.message += str(message)
def __str__(s):
return s.message
# exception
class a_function_cannot_be_dotted(FyException):
pass
class cannot_indent_on_... |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
load("//antlir/bzl:shape.bzl", "shape")
load("//antlir/bzl:target_helpers.bzl", "antlir_dep")
load("//antlir/bzl:target_tagger.bzl", "new_ta... |
# Palanquin (9110107) | Outside Ninja Castle (800040000)
mushroomShrine = 800000000
response = sm.sendAskYesNo("Would you like to go to #m" + str(mushroomShrine) + "m#?")
if response:
sm.warp(mushroomShrine) |
f = open("./three.txt", "r")
lines = [x.strip() for x in f.readlines()]
gamma = ""
for index in range(len(lines[0])):
bits = [line[index] for line in lines]
zeros = list(bits).count('0')
ones = list(bits).count('1')
if zeros > ones:
gamma += "0"
else:
gamma += "1"
epsilon = ""
for... |
#!/usr/bin/python
#
# Copyright 2002-2019 Barcelona Supercomputing Center (www.bsc.es)
#
# 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
... |
"""
Test group in a different order
.. pii: Group 1 - Annotation 1
.. pii_retirement: local_api, consumer_api
.. pii_types: id, name
"""
|
def bin_search_lower(a, x):
l, r = -1, len(a)
while l + 1 < r:
m = (l + r) // 2
if a[m] <= x:
l = m
else:
r = m
return l
n, k = map(int, input().split())
array = list(map(int, input().split()))
for x in map(int, input().split()):
print(bin_search_lower(... |
class State:
def __init__(self, client) -> None:
self.client = client
def get_input_command(self):
return input(f"JogoDaVelha> ").strip().split() or [""]
def handle_input_command(self, *input_command):
pass
def handle_opponent_command(self, *command):
pass
def han... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
spinMultiplicity = 2
energy = {
'CCSD(T)-F12/cc-pVTZ-F12': MolproLog('TSN09_f12.out'),
}
frequencies = GaussianLog('ts3-freq.log')
rotors = [HinderedRotor(scanLog=ScanLog('scan_0.log'), pivots=[4,10], top=[10,11,12,13,14], symmetry=1, fit='best'),
HinderedRotor(scanLog=... |
"""
Featurizers will always output arrays
but they will use structure-oriented methods
underneath to do it.
"""
|
a, b = map(int, input().split())
a = str(a)
b = str(b)
count = 0
c = int(a)
d = int(b)
for i in range(c, d + 1):
i = str(i)
if i[0] == i[4] and i[1] == i[3]:
count += 1
print(count) |
#!/usr/local/bin/python
# coding: utf-8
VERSION = '2.1.1'
# 0: CRITICAL, 1: INFO, 2: DEBUG
VERBOSE_LEVEL = 1
# 0: CONSOLE, 1: FILE, 2: CONSOLE & FILE
LOG_TYPE = 0
LOG_DIR = 'output'
HTML = False
DEBUG = True
|
class Human:
def __init__(self, name, age):
self.name = name
self.age = age
def greeting(self):
print(f"Hello {self.name}!")
def get_name(self):
return self.name
def get_age(self):
return self.age
def set_age(self, age):
self.ag... |
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
num_len = len(nums)
prefix_products, postfix_products = [1] * (num_len + 1), [1] * (num_len + 1)
prefix_product, postfix_product = 1, 1
for prefix_index in range(num_len):
prefix_product *= nu... |
CREATE_GAME = 'game_create'
JOIN_GAME = 'game_join'
LEAVE_GAME = 'game_abort'
SET_NICK = 'nickname_set'
INIT_BOARD = 'board_init'
FIRE = 'attack'
NUKE = 'special_attack'
MOVE = 'move'
SURRENDER = 'surrender'
CHAT_SEND = 'chat_send'
|
# -*- coding: utf-8 -*-
class Stack(object):
""" Implements a simple stack data structure.
Attrs:
top: object, a pointer to the top object in the stack.
count: int, a counter of the number of elements in the stack.
"""
def __init__(self):
self.top = None
self.count = 0... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1:
return l2
if not l2:
return l1
r... |
# Depth-first Search
# Given an integer array, your task is to find all the different possible increasing subsequences of the given array, and the length of an increasing subsequence should be at least 2 .
#
# Example:
# Input: [4, 6, 7, 7]
# Output: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], ... |
odds = {1, 3, 5, 7}
evens = set([0, 2, 4, 6, 8])
print(odds.union(evens))
odds.intersection()
odds.difference() |
def f1():
print(11)
yield
print(22)
yield
print(33)
def f2():
print(55)
yield
print(66)
yield
print(77)
v1 = f1()
v2 = f2()
next(v1) # v1.send(None)
next(v2) # v1.send(None)
next(v1) # v1.send(None)
next(v2) # v1.send(None)
next(v1) # v1.send(None)
next(v2) # v1.send(N... |
## Gerenators
def mygenerator(x):
for i in range(x):
yield i
values = mygenerator(100)
for i in values:
print(i)
print(next(mygenerator)) |
__author__ = 'yinjun'
#@see http://www.jiuzhang.com/solutions/longest-common-subsequence/
class Solution:
"""
@param A, B: Two strings.
@return: The length of longest common subsequence of A and B.
"""
def longestCommonSubsequence(self, A, B):
# write your code here
x = len(A)
... |
class Node:
def __init__(self, key):
self.key = key
self.child = []
def newNode(key):
temp = Node(key)
return temp
def LevelOrderTraversal(root):
if (root == None):
return;
# Standard level order traversal code
# using queue
q = [] # Create a queue
q.append(... |
'''Задача - 1
Вам необходимо создать завод по производству мягких игрушек для детей. Вам надо
продумать структуру классов, чтобы у вас был класс, который создаёт игрушки на
основании: Названия, Цвета, Типа (животное, персонаж мультфильма) Опишите
процедуры создания игрушки в трёх методах: -- Закупка сырья, пошив, окрас... |
def add_up(nums):
return sum(nums)
def test_answer():
assert add_up([1,2,2]) == 5 |
print('\033[1:33m = \033[m'*20)
velocidade = float(input('Qual foi a velocidade atingida pelo seu carro? '))
print('\033[1:33m - \033[m'*20)
multa = ( (velocidade - 80) * 7)
if velocidade<= 80:
print('Parabéns vc não ultrapassou o limite de velocidade.')
else:
print('\033[:31mVocê ultrapassou o limite de 80km/... |
#!/usr/bin/python3
def read_file(filename=""):
'''open a given file'''
with open(filename, 'r') as f:
print("{}".format(f.read()), end="")
|
class Node:
def __init__(self, x, y):
self.g = 0
self.h = 0
self.f = 0
self.parent = None
self.cost = 1
self.x = x
self.y = y
self.left_child = None
self.right_child = None
self.top_child = None
self.down_child = None
def u... |
def clever_format(num, format="%.2f"):
if num > 1e12:
return format % (num / 1e12) + "T"
if num > 1e9:
return format % (num / 1e9) + "G"
if num > 1e6:
return format % (num / 1e6) + "M"
if num > 1e3:
return format % (num / 1e3) + "K"
|
## PACKAGE THIS FUNCTION INTO MAVENN
def split_dataset(data_df,
set_col='set',
train_set_name='training',
val_set_name='validation',
test_set_name='test'):
"""
Splits dataset into
(1) `trainval_df`: training + validation set
... |
n,k=map(int,input().split())
x=sorted(list(map(int,input().split())))
a=[]
for i in range(n-k+1):
l=x[i]
r=x[i+k-1]
a.append(min(abs(l)+abs(r-l),abs(r)+abs(l-r)))
print(min(a)) |
class Cell:
def __init__(self, alive = False):
self.currentState = alive
self.futureState = alive
def updateState(self, state):
self.futureState = state
def refresh(self):
self.currentState = self.futureState
def isAlive(self):
return self.cur... |
str1 = input()
str2 = input()
a = [0 for i in range(0,27)]
for i in str1:
a[ord(i)-ord('a')] += 1
for i in str2:
a[ord(i)-ord('a')] -= 1
ans = 0
for i in a:
if ( i < 0 ):
ans += -i
else:
ans += i
print(ans) |
class GameInfo(object):
"""
holds player information for the current game
"""
def __init__(self, team_name, match_token, team_password, client_token = ''):
self.client_token = client_token
self.team_name = team_name
self.match_token = match_token
self.team_password = tea... |
looged_user = False
# if looged_user:
# msg = 'Usuário logado.'
# else:
# msg = 'Usuário não está logado.'
msg = 'Usuário logado' if looged_user else 'Usuário não está logado.'
print(msg)
|
#############################################################################
#
#
# RGB/A Colour webGenFramework module to BFA c7
#
#
#############################################################################
""" This is a rgb/a colour module for bfa colours.
Dependencies:
None
note:: Author(s): Mi... |
def serializeCgiToServer(coors): #coors is a n by 2 2D array of doubles
string = ""
for i in range(0, len(coors)):
string += str(coors[i][0]) + "," + str(coors[i][1]) # add comma between x and y coor
string += ";" # add semicolon to seperate coors
string += "\n" #ending character
return ... |
#
# PySNMP MIB module CISCOSB-SENSORENTMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-SENSORENTMIB
# Produced by pysmi-0.3.4 at Wed May 1 12:23:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
def load_assets():
assets = {}
# background do jogo
assets['background'] = pygame.image.load(r'img\spacebg.jpg').convert()
assets['background']= pygame.transform.scale(assets['background'],(largura,altura))
# tela inicial
assets['tela_init'] = pygame.image.load(r'img\screen_start1.png').... |
count = 0
fields = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]
hex_not = "1234567890abcdef"
ecls = ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]
def check_pprt(pprt):
global count
flag = True
i = 0
while flag and i < len(fields):
flag = flag and fields[i] in pprt
i = i + 1
... |
#OPERATOR PENUGASAN
#input mengisi nilai
nilai_x=int(input("masukan nilai x: "))
#operator penjumlahan
nilai_x +=20
print("hasil jumlah: ", nilai_x)
nilai_x=int(input("masukan nilai x: "))
#operator pengurangan
nilai_x -=10
print("hasil kurang:",nilai_x)
nilai_x=int(input("masukan nilai x: "))
#opera... |
#author SANKALP SAXENA
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
s = set()
for i in range(0, n) :
s.add(input())
print(len(s))
|
def find_prefix_entry(message, dictionary):
"""
Find the longest entry in dictionary which is a prefix of the given message
"""
for entry in dictionary[::-1]:
if message.startswith(entry[0]):
return dictionary.index(entry)
return -1
def lz78_encode(message, *args, **kwargs):
... |
def swap_case(s):
swapped = s.swapcase()
return swapped
|
#-----------------------------------------------------------------------------
# Runtime: 84ms
# Memory Usage:
# Link:
#-----------------------------------------------------------------------------
class Solution:
def multiply(self, num1: str, num2: str) -> str:
if num1 == '0' or num2 == '0':
... |
"""
[7/23/2014] Challenge#172 [Intermediate] Image Rendering 101...010101000101
https://www.reddit.com/r/dailyprogrammer/comments/2ba3nf/7232014_challenge172_intermediate_image_rendering/
#Description
You may have noticed from our
[easy](http://www.reddit.com/r/dailyprogrammer/comments/2ba3g3/7212014_challenge_172_ea... |
# This file is part of the DMComm project by BladeSabre. License: MIT.
"""
`dmcomm.protocol.barcode`
=========================
Functions for generating EAN-13 patterns.
"""
# https://en.wikipedia.org/wiki/International_Article_Number
_START_END = "101"
_CENTRE = "01010"
_CODES = {
"L": ["0001101", "0011001", "00100... |
# program that takes a text file as input and returns the number of words of a given text file.
def count_words(filepath):
with open(filepath) as f:
data = f.read()
data.replace(",", " ")
return len(data.split(" "))
print(count_words("words.txt")) |
#get the user input for Position
position = input("Position : ")
while position != "M" and position != "m" and position != "S" and position != "s":
print("Invalid Input")
position = input("Position : ")
#get the user input for sales amount
sales = input("Sales amount : ")
sales = float(sales)
#get the basic ... |
# Calcular o preço de um produto com % de desconto para pagamento a vista e % de juros para pagamento parcelado.
print('x=' * 80)
# AQUI FICA O VALOR DO PRODUTO.
preco = float(input('Qual o valor do produto ?R$ '))
# VALOR DO DESCONTO OU ACREŚIMO.
porcentagem = float(input('Desconto ou acréscimo para este produto em ... |
# Created by MechAviv
# Quest ID :: 23600
# Not coded yet
OBJECT_6 = sm.getIntroNpcObjectID(2159377)
sm.curNodeEventEnd(True)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(True, True, False, False)
sm.sendDelay(900)
sm.moveCamera(False, 100, -307, -41)
sm.sendDelay(2604)
sm.setSpeakerID(2159377)
sm.remove... |
"""
This package contains the portions of the library used only when
implementing an OpenID consumer.
"""
__all__ = ['consumer', 'discover']
|
rgb = input()
rgb = rgb.replace(" ", "")
if int(rgb) % 4 == 0:
print("YES")
else:
print("NO")
|
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False
# if it is a large {key: value} in dict, the list way is slower than dict way
# usedList = []
hashTable = {}
valueTable = {}
for i in... |
def main() -> None:
n = int(input())
def f(a: int, b: int) -> int:
return a**3 + (a + b) * a * b + b**3
def binary_search(a: int) -> int:
lo = -1
hi = 1 << 20
while hi - lo > 1:
# print(lo, hi)
b = (lo + hi) // 2
if f(a, b) >=... |
def raw_response(function=None):
def decorator(function):
function.raw_response = True
return function
if function:
return decorator(function)
return decorator
|
class StringBuilder(object):
def __init__(self, strr=''):
self.str_list = [s for s in strr]
def __getitem__(self, item):
return ''.join(self.str_list[item])
def __setitem__(self, key, value):
self.str_list[key] = value
def __repr__(self):
return ''.join(self.str_lis... |
#from math import hypot
co = float(input('Quanto mede o cateto oposto? '))
ca = float(input('Quanto mede o cateto adjacente? '))
hi = hypot(co, ca)
print(f'A hipotenusa vai medir {hi:.2f}')
'''
import math
co = float(input('Quanto mede o cateto oposto? '))
ca = float(input('Quanto mede o cateto adjacente? '))
hi = mat... |
class Person:
IS = None
def __init__(self, name, hours, rate):
self.name = name
self.hours = hours
self.rate = rate
def __new__(cls, *args, **kwargs):
if cls.IS == None:
cls.IS = object.__new__(Person)
return cls.IS
def pay(self):
r... |
data_matrix = [
[2, 3, 1, 1],
[1, 2, 3, 1],
[1, 1, 2, 3],
[3, 1, 1, 2]
]
def fill_zeros(data_val):
return bin(int(data_val, 16))[2:].zfill(8)
input_hex = [0xd4, 0xbf, 0x5d, 0x30]
input_bin = []
for i, bi... |
Root.default = -3
Scale.default = 'minor'
Clock.bpm=100
acordes = [(2,4,6),(-1,1,3),(0,2,4)]
escalera = P[5,4,3,2]
p1 >> space([0,0,4,2,0,0,5,2],dur=1,amp=[0,1,1,1])
d1 >> play("X ",amp=1)
pt >> play('#', dur=16,sus=4, rate=-1/2, amp=var([1,0],[16,inf],start=now))
p1 >> space([4,4,2,0,3,3,2,1],dur=1,amp=[0,1,1,1])
p... |
class Solution:
def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:
"""
[2,2,4,3,3] A = 5, B = 5 cans = 1
1
2
[1,2,4,4,5] A = 6, B = 2 cans = 3
0,3 1,1 (c-(sum%c))
... |
def main():
totalNum = 0
totalValues = {}
filename = 'day1_1_input.txt'
found = False
while not found:
userInput = open(filename, 'r')
print ("Starting from the top")
for i in userInput:
print (i)
if i[0] == '-':
totalNum -= int(i[1:])
... |
def response(hey_bob):
hey_bob = hey_bob.strip()
if _is_silence(hey_bob):
return 'Fine. Be that way!'
if _is_shouting(hey_bob):
if _is_question(hey_bob):
return "Calm down, I know what I'm doing!"
else:
return 'Whoa, chill out!'
elif _is_question(hey_bob)... |
word = input("Enter a number: ")
word = int(word)
count =10
while True:
temp = word % 10
word = word//10
if temp % 2==0:
print(temp,end="")
if word == 0:
break |
# 1表示空格,0表示墙, 2表示陷阱, 3表示火
Mazes = {
'maze7_1': [
[1., 0., 1., 1., 1., 1., 1.],
[1., 1., 1., 0., 0., 1., 0.],
[0., 0., 0., 1., 1., 1., 0.],
[1., 1., 1., 1., 0., 0., 1.],
[1., 0., 0., 0., 1., 1., 1.],
[1., 0., 1., 1., 1., 1., 1.],
[1., 1., 1., 0., 1., 1., 1.]
... |
data = input()
products = {}
while not data == "statistics":
product, quantity = data.split(": ")
quantity = int(quantity)
if product in products:
products[product] += quantity
else:
products[product] = quantity
data = input()
print("Products in stock:")
for product in products:
... |
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def createList(l: list) -> ListNode:
header = current = ListNode()
for i in range(0, len(l)):
current.next = current = ListNode(l[i])
return header.next
def printList(l: ListNode):
while l:
print(l.val)
... |
# static methods
# use the staticmethod decorator
class Human:
@staticmethod
def speak():
print("I can speak")
Human().speak()
me = Human()
me.speak() # this line will give error
# expected an error.. but there isn't any
# static methods can be called on an instance of a class
# i didn't pass self or any arg... |
# Sem passar valores pelo init
class Calculadora:
# def __init__(self):
# pass
def soma(self, valor_a, valor_b):
return valor_a + valor_b
def subtracao(self, valor_a, valor_b):
return valor_a - valor_b
def multiplicacao(self, valor_a, valor_b):
return valor_a * valor_... |
def make_album(singer, album, numbers=''):
albums = {'singer': singer, 'album': album}
if numbers:
albums['numbers'] = numbers
return albums
print(make_album('张靓颖', '终于等到你'))
print(make_album('邓丽君', '我只在乎你', 20))
print(make_album('汪小敏', '笑看风云'))
while True:
singer = input("请输入歌手:")
if not... |
def get_level(cell):
i = 0
while cell > (2*i+1)**2:
i += 1
return i
def find_coord(cell):
level = get_level(cell)
x = level
y = -level
current = (2*level+1)**2
while x != -level:
if current == cell:
return (x, y)
x-=1
current -= 1
while y !... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename: for.py
edibles = ['ham', 'spam', 'eggs', 'nuts']
for food in edibles:
if food == 'spam':
print('No more spam please!')
break
print('Great, delicious ' + food)
else:
print('I am so glad: No spam!')
print('Finally, I finished stuffing... |
class QuoteLine:
def __init__(self, lineText, lineNumber, origin):
self.lineText = lineText
self.lineNumber = lineNumber
self.origin = origin
self.renderedLine = None
def renderLine(self, font, color):
'''
Renders the line using the given font and color.
'''
self.renderedLine = font.render(self.l... |
first_str = input()
second_str = input()
while first_str in second_str:
second_str = second_str.replace(first_str, '')
print(second_str) |
#
# PySNMP MIB module CHIPFDDINET-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CHIPFDDINET-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:48:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
# class Solution(object):
# def generateParenthesis(self, n):
# """
# :type n: int
# :rtype: List[str]
# """
class Solution(object):
def generateParenthesis(self, n):
if n == 1:
return ['()']
last_list = self.generateParenthesis(n - 1)
... |
# MIT License
#
# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
print(10/3)
print(10//3)
print()
kue = 16
anak = 4
kuePerAnak = kue // anak
print ("Setiap anak akan mendapatkan kue sebanyak ", kuePerAnak)
|
class ExportUnit(Enum,IComparable,IFormattable,IConvertible):
"""
An enumerated type listing possible target units for CAD Export.
enum ExportUnit,values: Centimeter (4),Default (0),Foot (2),Inch (1),Meter (5),Millimeter (3)
"""
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx._... |
while True:
X, M = map(int, input().split())
if X == 0 and M == 0:
break
Y = X * M
print(Y) |
age = 5+(8%3)-3+(3*10)/2
greetings = "Welcome to IEEE Python Workshop 2018 edition. It's my pleasure to conduct today's workshop for you."
name = "Saurabh Mudgal"
major = "mechanical engineering"
print(greetings)
print("My name is " + name + ".")
print("I am " + str(age) + " years old and am majoring in " + major + ".... |
# -*- coding: utf-8 -*-
__title__ = 'exp_mixture_model'
__version__ = '1.0.0'
__description__ = 'Maximum likelihood estimation and model selection of EMMs'
__copyright__ = 'Copyright (C) 2019 Makoto Okada and Naoki Masuda'
__license__ = 'MIT License'
__author__ = 'Makoto Okada, Kenji Yamanishi and Naoki Masuda'
__auth... |
class Product:
def __init__(self, name, category_name, unit_price):
self.name = name
self.category_name = category_name
self.unit_price = unit_price
def __str__(self):
return f"Nazwa: {self.name} | Kategoria: {self.category_name} | Cena: {self.unit_price} PLN/szt"
|
class Shape:
def __init__(self):
self.data = ['_' for _ in range(10)]
def print_out(self):
print(''.join(self.data))
class Even(Shape):
def draw_func(self, x):
if x % 2 == 0:
return True
else:
return False
class ThirdBiggerFive(Shape):
def draw_f... |
#!/usr/bin/python3
# steinkirch at gmail.com
# astro.sunysb.edu/steinkirch
class Node(object):
def __init__(self, value=None):
self.value = value
self.next = None
class Stack(object):
def __init__(self):
self.top = None
def push(self, item):
node = Node(item)
node... |
# coding: utf-8
def naive_square_matrix_product(A, B):
""" Implementation of naive squre matrix multiplication algorithm """
n = len(A)
C = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
C[i][j] += A[i][k] * B[k][... |
def lmap(f, it):
return list(map(f, it))
def ints(it):
return lmap(int, it)
def solve(input):
l = len(input.split()[0])
xs = lmap(lambda x: int(x, 2), input.split())
a = 0
for i in range(l):
cnt = [0, 0]
for x in xs:
cnt[(x >> i) & 1] += 1
if cnt[1] > cnt[... |
__author__ = 'Roman Morozov'
def convert_name_extract(list_in: list) -> list:
tmp: list = []
for i in list_in:
i = i.title()
name = i.rpartition(' ')
tmp.append(f'Привет, {name[-1]}!')
return tmp
if __name__ == '__main__':
example_list = ['инженер-конструктор Игорь', 'главный... |
def cria_matriz(num_linhas, num_colunas):
''' (int, int) --> matriz (lista de listas)
Cria e retorna uma matriz com num_linhas linhas e num_colunas
colunas em que cada elemento é igual digitado pelo usuário.
'''
matriz = [] # lista vazia
for i in range(num_linhas):
# cria a linha i
... |
#!/usr/bin/env python3
#
# Author:
# Tamas Jos (@skelsec)
#
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_READ = 0x0010
PROCESS_VM_WRITE = 0x0020
PROCESS_VM_OPERATION = 0x0008
PROCESS_CREATE_THREAD = 0x0002
# Standard access rights
DELETE = 0x00010000
READ_CONTROL = 0x00... |
class Solution(object):
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
d = collections.defaultdict(int)
for c in s:
d[c] += 1
l = [[-d[key],key] for key in d]
l.sort()
# print l
res = ''.join(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.