content stringlengths 7 1.05M |
|---|
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
paths = [[1] * n for _ in range(m)]
for row in range(1, m):
for col in range(1, n):
paths[row][col] = paths[row-1][col] + paths[row][col-1]
return paths[m-1][n-1] |
# The search the 2D array for the target element where array is sorted from
# left to right and top to bottom
def search_2D_array(arr,x):
row = 0
col = len(arr[0]) - 1
while row < len(arr) and col >= 0:
if arr[col][row] == x:
return True
elif arr[row][col] < x:
row... |
n, k = map(int, input().split())
a = list(map(int, input().split()))
fre = [0] * (10 ** 5 + 5)
unique = 0
j = 0
for i in range(n):
if fre[a[i]] == 0:
unique += 1
fre[a[i]] += 1
while unique == k:
fre[a[j]] -= 1
if fre[a[j]] == 0:
print(j + 1, i + 1)
... |
"""The pyang library for parsing, validating, and converting YANG modules"""
__version__ = '2.5.3'
__date__ = '2022-03-30'
|
def fat_total(receita_estados: dict):
return sum(receita_estados.values())
def repr_percentual(receita_estados: dict):
receita_total = fat_total(receita_estados)
for estado, faturamento in receita_estados.items():
repr_percentual = (faturamento/receita_total)*100
print(
f"{estad... |
# Copyright 2018 The Bazel Authors. 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 required by applicable la... |
n = int(input())
spaces = 2*(n-1)
for i in range(1, n+1):
print(" "*spaces, end="")
if i == 1:
print("1")
else:
for j in range(i, 2*i):
print(str(j) + " ", end="")
for j in range(2*i-2, i-1, -1 ):
print(str(j) + " ", end="")
print()
spaces -= 2 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2016-12-22 10:42:23
# @Author : Jan Yang
# @Software : Sublime Text
class Email:
def __init__(self):
pass
|
# Perulangan pada string
print('=====Perulangan Pada String=====')
teks = 'helloworld'
print('teks =',teks)
hitung = 0
for i in range(len(teks)):
if 'l' == teks[i]:
hitung = hitung + 1
print('jumlah l pada teks',teks,'adalah',hitung) |
"""
APCS 106/10
Logic Operator
20220127
by Kevin Hsu
"""
iTmp = input("input three number:\n").split()
x = int(iTmp[0])
y = int(iTmp[1])
z = int(iTmp[2])
answer = [0] * 3
if x > 0:
x = 1
if y > 0:
y = 1
if ((x & y) == z):
answer[0] = 1
else:
answer[0] = 0
if ((x | y) == z):
a... |
h, m = 100, 200
h_deg, m_deg = h//2, m//3
# In Python3, // rounds down to the nearest whole number
angle = abs(h_deg - m_deg)
if angle > 180:
angle = 360 - angle
print(int(angle))
|
# Gregary C. Zweigle
# 2020
MAX_PIANO_NOTE = 88
# TODO - Should this move elsewhere?
class FileName:
def __init__(self):
self.note_number = 0
self.file_name_l = 'EMPTY_L'
self.file_name_r = 'EMPTY_R'
def initialize_file_name(self, record_start_note):
self.note_n... |
n = int(input())
s = list(map(int, input().split()))
c = [0] * 10010
res, count = 0, 0
for i in s:
c[i] += 1
if c[i] > count:
res = i
count = c[i]
elif c[i] == count:
res = min(res, i)
print(res)
|
INPUT= """2
0
0
-2
0
1
-2
-1
-6
2
-1
2
0
2
-13
0
-2
-15
-15
-3
-10
-11
1
-5
-20
-21
-14
-21
-4
-9
-29
2
-10
-5
-33
-33
-9
0
2
-24
0
-26
-24
-38
-28
-42
-14
-42
2
-2
-48
-48
-17
-19
-26
-39
0
-15
-42
-3
-19
-19
-7
-1
-11
-5
-17
-46
-15
-43
-22
-31
-... |
class ApiError(Exception):
pass
class AuthorizationFailed(Exception):
pass
|
s = 'one two one two one'
print(s.replace('one', 'two').replace('two', 'one'))
# one one one one one
print(s.replace('one', 'X').replace('two', 'one').replace('X', 'two'))
# two one two one two
def swap_str(s_org, s1, s2, temp='*q@w-e~r^'):
return s_org.replace(s1, temp).replace(s2, s1).replace(temp, s2)
print(... |
# TODO: create functions for data sending
async def send_data(event, buttons):
pass
|
n = int(input())
s = set(map(int, input().split()))
for i in range(int(input())):
c = input().split()
if c[0] == "update":
s.update(set(map(int, input().split())))
elif c[0] == "intersection_update":
s.intersection_update(set(map(int, input().split())))
elif c[0] == "difference_update":... |
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def right_view_util(root, max_level, level):
if not root:
return
if max_level[0] < level:
print(root.val)
max_level[0] = level
right_view_util(r... |
"""Tabuada de um inteiro"""
# Uso dos operadores aritméticos
num = int(input('Digite um número: '))
inicio = 'Resultado'
fim = 'Fim'
print()
print('{:=^25}'.format(inicio))
print()
print(f'{num} x 0 = {num*0}\n'
f'{num} x 1 = {num*1}\n'
f'{num} x 2 = {num*2}\n'
f'{num} x 3 = {num*3}\n'
f'{num}... |
def removeDuplicates(nums):
"""
:type nums: List[int] - sorted
:rtype: List[int]
"""
i = 0
for j in range(len(nums)):
if nums[j] != nums[i]:
i += 1
nums[i] = nums[j]
return nums[0: i + 1]
print(removeDuplicates([1, 1, 2, 3, 3, 3, 5]))
print(removeDuplicates(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# # https://oj.leetcode.com/problems/symmetric-tree
# Given a binary tree, check whether it is a mirror of itself
# (ie, symmetric around its center).
# For example, this binary tree is symmetric:
# 1
# / \
# 2 2
# / \ / \
# 3 4 4 3
#
# But the following ... |
'''
Escreva um programa que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão:
1 - binário
2 - octal
3 - hexadecimal
'''
'''
n = int(input('Número inteiro: '))
escolha = (int(input('Conversor:\n'
'1 - Binário\n'
'2 - Octal\n'
... |
# These regexes must not include line anchors ('^', '$'). Those will be added by the
# ValidateRegex library function and anybody else who needs them.
NAME_VALIDATION = r"(?P<name>[@\-\w\.]+)"
# This regex needs to exactly match the above, EXCEPT that the name should be "name2". So if the
# above regex changes, chang... |
def check(n):
sqlist = str(n**2)# list(map(int,str(n**2)))
l = len(sqlist)
if l%2 == 0: #if even
rsq = int(sqlist[l//2:])
lsq = int(sqlist[:l//2])
else:
rsq = int(sqlist[(l-1)//2:])
if l!= 1:
lsq = int(sqlist[:(l-1)//2])
else:
lsq = 0 #only lsq can have an empty list
if rsq + lsq == ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
AUTHOR = 'Ben Poile'
SITENAME = 'blog'
SITEURL = 'https://poiley.github.io'
# GITHUB_URL = 'https://github.com/poiley/poiley.github.io'
PATH = 'content'
OUTPUT_PATH = 'output'
STATIC_PATHS = ['articles', 'downloads']
ARTICLE_PATHS = ['articles',]
ARTICLE_URL = 'artic... |
class SomethingAbstract:
property_a: str
property_b: str
property_c: Optional[str]
property_d: Optional[str]
def __init__(
self,
property_a: str,
property_b: str,
property_c: Optional[str] = None,
property_d: Optional[str] = None,
) -> None:
self... |
# Modifique o programa para trabalhar com duas filas
# Para facilitar seu trabalho, considere o comando A para atendimento da fila 1; e B, para atendimento da fila 2
# O mesmo para a chegada de clientes: F para fila 1; e G, para fila 2
def line(size):
print('-' * size)
last = 10
queue1 = list(range(1, last + 1))... |
#soma=0
#for c in range(3,501,6):
# soma=soma+c
#print(soma)
#ou
soma = 0
cont = 0
for c in range(1,501,2):
if c % 3 == 0:
soma += c # soma = soma+ c
cont += 1 # cont = cont + 1
print('a soma de todos os {} valores é {}'.format(cont,soma))
|
nomeCompleto = input('Digite seu nome completo: ').strip().split()
print('O seu primeiro nome é: {}'.format(nomeCompleto[0]))
#forma 1
print('O seu último nome é: {}'.format(nomeCompleto[-1]))
#forma 2
#print('O seu último nome é: {}'.format((nomeCompleto[len(nomeCompleto)-1])))
|
text = open("subInfo.txt").read()
def findCount(sub):
count = 0
terms = open(sub).readlines()
terms = [t.strip().lower() for t in terms]
for t in terms:
if t in text:
count += 1
return count
subArr = []
subArr.append((findCount("biology_terms.txt"), "biology_ter... |
dia=input ('Dia =')
mês=input ('mês =')
ano=input ('ano =')
print ('Você nasceu no dia',dia,'de',mês,'de',ano,'.''Correto?')
|
class eAxes:
xAxis, yAxis, zAxis = range(3)
class eTurn:
learner, simulator = range(2)
class eEPA:
evaluation, potency, activity = range(3)
evaluationSelf, potencySelf, activitySelf,\
evaluationAction, potencyAction, activityAction,\
evaluationOther, potencyOther, activityOther = range(9)
... |
"""
MyMCAdmin system
"""
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author: Alan
@time: 2021/05/18
"""
|
cars=["Maruthi","Honda","TataIndica"]
x = cars[0]
print("x=\n",x)
cars[0]="Ford"
print("cars=\n",cars)
L = len(cars)
print("Length of cars=",L)
#Print each item in the car array
for y in cars:
print(y)
cars.append("BMW")
print("cars=\n",cars)
#Delete the second element of the cars array
cars.pop(1)
... |
guests = ["Mark", "Kevin", "Mellisa"]
msg = "I'd like to invite you to have a dinner with us on 5/18. Thanks, Andrew"
print(f"Hi {guests[0]}, {msg}")
print(f"Hi {guests[1]}, {msg}")
print(f"Hi {guests[2]}, {msg}")
print(f"\nSorry, {guests[1]} can't make it.\n")
guests[1] = "Ace"
print(f"Hi {guests[0]}, {msg}")
print(... |
# Problem Set 1a
# Name: Eloi Gil
# Time Spent: 1
#
balance = float(input('balance: '))
annualInterestRate = float(input('annual interest rate: '))
minMonthlyPaymentRate = float(input('minimum monthly payment rate: '))
month = 0.0
while month < 12.0:
month += 1.0
print('Month ' + str(month))
minMonthlyPay... |
s=0
for c in range(0,4):
n= int(input('Digite um valor: '))
s += n
print('Somatorio deu: {}' .format(s)) |
'''
__init__ :Python的初始化方法
'''
class Enemy:
def __init__(self):
print("this is init ")
enemy1=Enemy()
print("---------")
'''
带参的构造方法
'''
class Enemy2:
def __init__(self,x):
self.energy=x
def get_energy(self):
print(self.energy)
jsaon=Enemy2(2)
sandy=Enemy2(18)
jsaon.get_energy(... |
__title__ = 'DRF Exception Handler'
__version__ = '1.0.1'
__author__ = 'Thomas'
__license__ = 'MIT'
__copyright__ = 'Copyright 2021 Thomas'
# Version synonym
VERSION = __version__
|
{
"targets": [
{
"target_name": "boost-property_tree",
"type": "none",
"include_dirs": [
"1.57.0/property_tree-boost-1.57.0/include"
],
"all_dependent_settings": {
"include_dirs": [
"1.57.0/proper... |
def movewhile():
"""Kara geht solange einen Schritt wie kein Baum vor ihr ist"""
# Wenn vor Kara kein Baum ist geht sie einen Schritt
# und ruft danach solange sich selbst auf, wie vor
# ihr kein Baum ist.
if not kara.treeFront():
kara.move()
movewhile()
else:
pass
de... |
"""
hello_world.py
Simple Hello World program.
ECE196 Face Recognition Project
Author: Will Chen
1. Write a Write a program that prints "Hello World!" and uses the main function convention.
"""
# TODO: Write a program that prints "Hello World!" and uses a main function.
def main():
print("Hello World!")
if(__n... |
def between_markers(text,mark1,mark2):
'''
You are given a string and two markers (the initial one and final). You have to find a substring enclosed between these two markers. But there are a few important conditions.
This is a simplified version of the Between Markers mission.
The initial and final markers a... |
# Copyright (C) 2017 Tiancheng Zhao, Carnegie Mellon University
class KgCVAEConfig(object):
description= None
use_hcf = True # use dialog act in training (if turn off kgCVAE -> CVAE)
update_limit = 3000 # the number of mini-batch before evaluating the model
# how to encode utterance.
# bow: ... |
# Cast to int
x = int(100) # x will be 100
y = int(5.75) # y will be 5
z = int("32") # z will be 32
print(x)
print(y)
print(z)
print(type(x))
print(type(y))
print(type(z))
# cast to float
a = float(100) # x will be 100.0
b = float(5.75) # y will be 5.75
c = float("32") # z will be 32.0
d = float(... |
class MetadataHolder():
def set_metadata(self, key, value):
self.client.api.call_function('set_metadata', {
'entity_type': self._data['type'],
'entity_id': self.id,
'key': key,
'value': value
})
def set_metadata_dict(self, metadata_dict):
... |
"""VIMS generic errors."""
class VIMSError(Exception):
"""Generic VIMS error."""
class VIMSCameraError(VIMSError):
"""Generic VIMS Camera error."""
|
'''
Given an array of unique integers preorder, return true if it is the correct preorder traversal sequence of a binary search tree.
Example 1:
Input: preorder = [5,2,1,3,6]
Output: true
Example 2:
Input: preorder = [5,2,6,1,3]
Output: false
'''
# Convert to Inorder and check if sorted or not
# TC O(N) and Space O... |
# -*-coding:utf-8-*-
"""
진법 변환 recursive 알고리즘
2 <= n <= 16까지 가능
"""
def convert(n,t):
T = "0123456789ABCDEF"
q,r = divmod(n, t)
if q ==0:
return T[r]
else:
return convert(q, t) + T[r]
"""
def test(n,t):
answer = ''
while t//n >= 1:
re = t%n
t = t//n
an... |
'''
You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree.
If node i has no left child then leftChild[i] will equal -1, similarly for the right child.
Note that the nodes hav... |
# Nesse exemplo retorna uma lista ordenada
lista = [1,5,3,2,7,50,9]
def bubbleSort(list):
for i in range(len(list)):
for j in range(0, len(list) - 1 - i):
if (list[j] > list[j+1]):
temp = list[j]
list[j] = list[j+1]
list[j+1] = temp
return l... |
# General settings
HOST = "irc.twitch.tv"
PORT = 6667
COOLDOWN = 10 #Global cooldown for commands (in seconds)
# Bot account settings
PASS = "oauth:abcabcabcabcabcabcacb1231231231"
IDENT = "bot_username"
# Channel owner settings
CHANNEL = "channel_owner_username" #The username of your Twitch account (lowerc... |
## Exercício 14 do livro Python 3 - Conceitos e Aplicações - Uma Abordagem Didática
""" Uso de condições simples: considerando os valores fornecidos, avalie cada condição e informe se o resultado é
falso (false) ou verdadeiro (true).
Para A = 0 e B = -3 -> condição = A > B
Para X = 3.7 -> condição X <= 10.0
Para A = 9... |
class Health(object):
"""
Represents a Health object used by the HealthDetails resource.
"""
def __init__(self, status, environment, application, timestamp):
self.status = status
self.environment = environment
self.application = application
self.timestamp = timestamp
|
def generate_data_replace_string():
'''
为了将日期字符串 /2/5 转换成 0205这样,
构建一个map,key为原始字符串,value为目标字符串
:return:
date_replace_str_map
'''
ori_str_list = []
new_str_list = []
for idx in range(1,9):
str_num = '/'+str(idx);
new_str_num = '0'+str(idx);
ori_str_list.append... |
__author__ = 'shukkkur'
'''
https://codeforces.com/problemset/problem/1399/A
A. Remove Smallest
Couldn't Solve it myself, answer borrowed.
'''
for _ in range(int(input())):
n = int(input())
a = set(map(int, input().split()))
print('YES' if max(a)-min(a) < len(a) else 'NO')
|
N, *a = map(int, open(0).read().split())
i, j = 0, 0
c = 0
result = 0
while j < N:
if c <= N:
c += a[j]
j += 1
else:
c -= a[i]
i += 1
if c == N:
result += 1
while i < N:
c -= a[i]
i += 1
if c == N:
result += 1
print(result)
|
# test using cpu only
cpu = False
# type of network to be trained, can be bnn, full-bnn, qnn, full-qnn, tnn, full-tnn
network_type = 'full-qnn'
# bits can be None, 2, 4, 8 , whatever
bits=None
wbits = 4
abits = 4
# finetune an be false or true
finetune = False
architecture = 'RESNET'
# architecture = 'VGG'
dataset='C... |
# JIG code from Stand-up Maths video "Why don't Jigsaw Puzzles have the correct number of pieces?"
def low_factors(n):
# all the factors which are the lower half of each factor pair
lf = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
lf.append(i)
return lf
def jig(w,h,n,b=0):... |
class Grandpa:
basketball = 1
class Dad(Grandpa):
dance = 1
def d(this):
return f"Yes I Dance {this.dance} no of times"
class Grandson(Dad):
dance = 6
def d(this):
return f"Yes I Dance AWESOMELY {this.dance} no of times"
jo = Grandpa()
bo = Dad()
po = Grandson()
# Everything... |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Coupon_validity, obj[4]: Gender, obj[5]: Age, obj[6]: Children, obj[7]: Education, obj[8]: Occupation, obj[9]: Income, obj[10]: Bar, obj[11]: Coffeehouse, obj[12]: Restaurant20to50, obj[13]: Direction_same, obj[14]: Distance
# {"feature":... |
DOMAIN = "meross"
CONF_KEY = "key"
CONF_VALIDATE = "validate"
CONF_UUID = "uuid"
DEVICE_OFF = 0
DEVICE_ON = 1
LISTEN_TOPIC = '/appliance/{}/publish'
PUBLISH_TOPIC = '/appliance/{}/subscribe'
APP_METHOD_PUSH = "PUSH"
APP_METHOD_GET = "GET"
APP_METHOD_SET = "SET"
APP_SYS_CLOCK = "Appliance.System.Clock"
APP_SYS_ALL... |
#!/usr/bin/env python3
def main():
print( getProd2() )
print( getProd3() )
def getProd2():
with open( "expenses.txt" ) as f:
expenses = [ int( i.rstrip("\n") ) for i in f.readlines() ]
n = len( expenses )
for i in range( n ):
for j in range( i + 1, n ):
if expenses[ i ] + expenses... |
class LinkedListIterator:
def __init__(self, beginning):
self._current_cell = beginning
self._first = True
def __iter__(self):
return self
def __next__(self):
try:
getattr(self._current_cell, "value")
except AttributeError:
raise StopIteration()
else:
if self._first:
self._first = False
... |
class groupcount(object):
"""Accept a (possibly infinite) iterable and yield a succession
of sub-iterators from it, each of which will yield N values.
>>> gc = groupcount('abcdefghij', 3)
>>> for subgroup in gc:
... for item in subgroup:
... print item,
... print
...... |
'''https://practice.geeksforgeeks.org/problems/subarray-with-0-sum-1587115621/1
Subarray with 0 sum
Easy Accuracy: 49.91% Submissions: 74975 Points: 2
Given an array of positive and negative numbers. Find if there is a subarray (of size at-least one) with 0 sum.
Example 1:
Input:
5
4 2 -3 1 6
Output:
Yes
Explanat... |
all__ = ['jazPush', 'jazRvalue', 'jazLvalue', 'jazPop', 'jazAssign', 'jazCopy']
class jazPush:
def __init__(self):
self.command = "push"
def call(self, interpreter, arg):
interpreter.GetScope().stack.append(int(arg))
return None
class jazRvalue:
def __init__(self):
self.co... |
l1 = int ( input (" primeiro lado ? " ))
l2 = int ( input (" Segundo lado ? " ))
l3= int ( input (" Terceiro lado ? " ))
if (l1 + l2) < l3 or (l2 + l3) < l1 or (l1 +l3) <l2:
print ('Não pode formar triângulo ')
elif (l1 + l2) > l3 or (l2 + l3) > l1 or (l1 +l3) > l2:
print ('Pode formar triângulo')
if (l1... |
a = int(input())
length = 0
sum_of_sequence = 0
while a != 0:
sum_of_sequence += a
length += 1
a = int(input())
print(sum_of_sequence / length) |
lista = []
cont = 0
while True:
num = int(input('Digite um número: '))
cont += 1
lista.append(num)
resp = ' '
while resp not in 'SN':
resp = str(input('Deseja continuar? [S/N]: ')).upper().strip()[0]
if resp == 'N':
break
print('-=-' * 20)
print(f'Foram digitados {cont} números!!... |
def swap(i):
i = i.swapcase()
return i
if __name__ == "__main__":
s = input()
res = swap(s)
print(res)
|
"""
one area in which recursion shines is where we need to act on a problem
that has an arbitrary number of levels of depth.
A second area in which recursion shines is where
it is able to make a calculation based on a subproblem of the problem at hand.
steps to solving a recursive problem with sub-problems
1. Imagi... |
class Cell(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __lt__(self, other):
if (self.x < other.x):
return True
elif (self.x > other.x):
return False
elif (self.x == other.x):
return (self.y < other.y)
... |
#
# CAMP
#
# Copyright (C) 2017 -- 2019 SINTEF Digital
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the MIT license. See the LICENSE file for details.
#
class About:
PROGRAM = "CAMP"
VERSION = "0.7.0"
COMMIT_HASH = None
LICENSE = "MIT"
COPYRIG... |
# Marcelo Campos de Medeiros
# ADS UNIFIP 2020.1
# Patos-PB 03/04/2020
'''
Dois carros (X e Y) partem em uma mesma direção. O carro X sai com velocidade constante de 60 Km/h e
o carro Y sai com velocidade constante de 90 Km/h.
Em uma hora (60 minutos) o carro Y consegue se distanciar 30 quilômetros do carro X, ou sej... |
# SIMPLE FORMULA
# __________________________________________________________________________________________
# VARIABLE
# - Localize language: ID
textOpen=(
'Solve it! #1',
'Diketahui W=((X+YxZ)/(XxY))^Z'
)
textInX='Nilai X:'
textInY='Nilai Y:'
textInZ='Nilai Z:'
textOut='Nilai W adalah'
# ____________________... |
# I have used sieve of erato algorithm to solve this problem
def seive(Max):
primes = []
isprime = [False] * (Max)
maxN = Max
if maxN < 2:
return 0
if maxN >= 2:
isprime[0] = isprime[1] = True
for i in range(2, maxN):
if (isprime[i] is False):
for j in range... |
class FilterError(RuntimeError):
"""
This error is raised when a filter can never match on a given model class
"""
pass
class MultipleResultsError(RuntimeError):
"""
This filter is raised when multiple results are returned while a single
one was expected
"""
|
class Solution():
def isUnique(self, string: str):
'''Checks whether a given string has unique characters only
Inputs
------
string: str
string to be checked for unique chars
Assumptions
------------
Whitespace ' ' is a character
... |
class Page():
def __init__(self, parent, render):
self.__parent = parent
self.__render = render
def render(self):
return self.__render(self)
def parent(self):
return self.__parent
|
"""
* Assignment: File Write CSV
* Required: yes
* Complexity: medium
* Lines of code: 6 lines
* Time: 5 min
English:
1. Separate header from data
2. Write data to file `FILE`:
a. First line in file must be a header (first line of `DATA`)
b. For each row, convert it's values to `str`
c.... |
class Multiplication:
def __init__(self,matrix1,matrix2):
self.matrix1 = matrix1
self.matrix2 = matrix2
self.result = []
def ismultiplyable(self):
"""
INPUT: No Input
OUTPUT: ismultiplyable : bool
DESC: Can matrices be multiplied?
"""
... |
# from astra import models
#
# class UserObject(models.Model):
# def
#
#
#
class MetaDemo(type):
pass
class Demo(metaclass=MetaDemo):
pass
d = Demo()
print(d.__class__.__metaclass__)
|
#!/usr/bin/env prey
async def main():
count = int(await x("ls -1 | wc -l"))
print(f"Files count: {count}")
|
g = int(input())
if g%2 == 0:
print("no. even")
else:
print("no. is odd")
|
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 20 12:25:06 2019
@author: abhij
"""
def circle_intersection(f1 = 0, f2 = 0, o1 = 0, o2 = 0, l1 = 0, l2 = 0):
R = (f1**2 + f2**2)**(0.5)
x_cor = f1 - o1
y_cor = f2 - o2
rot1 = (l1**2 - l2**2 + R**2)/(2*R)
print("\n l is", ... |
def soma_elementos(lista):
soma = 0
for i in lista:
soma = soma + i
return soma
lista = [1,2,3,4,5,6]
print(soma_elementos(lista))
|
class str(object):
def __new__(self, *args):
if ___delta("num=", args.__len__(), 0):
return ""
else:
first_arg = ___delta("tuple-getitem", args, 0)
return first_arg.__str__()
def __init__(self, *args):
pass
def __len__(self):
int = ___id("%int")
return ___delta("strlen", se... |
# 9.2.2 Implementation with an Unsorted List
class PriorityQueueBase:
"""Abstract base class for a priority queue."""
class _Item:
"""Lightweight composite to store priority queue items."""
__slots__ = '_key','_value'
def __init__(self,k,v):
self._key = k
self.... |
#!/usr/bin/python35
fp = open('hello.txt')
print('fp.tell = %s' % (fp.tell()))
fp.seek(10, SEEK_SET)
print('fp.seek(10), fp.tell() = %s' % (fp.tell()))
# only do zero cur-relative seeks
fp.seek(0, SEEK_CUR)
print('fp.seek(0, 1), fp.tell() = %s' % (fp.tell()))
fp.seek(0, SEEK_END)
print('fp.seek(0, 2), fp.tell() = ... |
'''
Created on 02-06-2011
@author: Piotr
'''
class GeneratorInterval(object):
'''
Describes the interval in for generating the image.
@attention: DTO
'''
def __init__(self, start, stop, step=0):
'''
Constructor.
@param start: starting point of the interval
... |
with open('8.input') as inputFile:
data = [b.split(' ') for b in [a.rstrip('\n').split(' | ')[1] for a in inputFile.readlines()]]
result = 0
for d in data:
for e in d:
if len(e) in [2,3,4,7]:
result += 1
print(result)
|
def main():
message = input("Introducir Mensaje: ")
key = int(input("Key [1-26]: "))
mode = input("Cifrar o Descifrar [c/d]: ")
if mode.lower().startswith('c'):
mode = "cifrar"
elif mode.lower().startswith('d'):
mode = "descifrar"
translated = encdec(message, key, mode)
... |
# Problem statement
# write a program to swap two numbers without using third variable
x = input()
y = input()
print ("Before swapping: ")
print("Value of x : ", x, " and y : ", y)
x, y = y, x
print ("After swapping: ")
print("Value of x : ", x, " and y : ", y)
# sample input
# 10
# 20
# sample output... |
#!/bin/zsh
'''
Table Printer
Write a function named printTable()
that takes a list of lists of strings and displays it in a well-organized table
with each column right-justified.
Assume that all the inner lists will contain the same number of strings.
For example, the value could look like this:
tableData = [['ap... |
"""
String Formatting
"""
# Create a variable that contains the first 4 lines of lyrics from your favorite song. Add a comment that includes the song title and artist **each on their own line**! Now print out this variable.
"""
Dancing in the Moonlight
King Harvest
"""
fave_song = '''
We get it almost every night
Whe... |
def stable_match(a_pref: dict, b_pref: dict) -> set:
a_list = list(a_pref.keys())
match_dict = {}
while len(match_dict) != len(a_pref):
print(a_list)
for ai in a_list:
if ai in match_dict.values():
continue
print(f"{ai}")
# obtengo mejor c... |
#!/usr/bin/env python3
#errors.py
class ParserTongueError(Exception):
pass
########################
### Tokenizer Errors ###
########################
class TokenizerError(ParserTongueError):
pass
class TokenInstantiationTypeError(TokenizerError):
def __init__(self, message):
self.message = me... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.