content stringlengths 7 1.05M |
|---|
"""
Module for KeywordsADT, a custom ADT in this project. You can read more about it
in the Wiki page on our GitHub profile.
"""
class KeywordsADT:
"""
This class represents all Keywords in list
"""
def _check(self, word):
"""
Check if somebody already uses this word.
:param wo... |
def add(x, y):
total = x + y
return total
print(add(5, 10))
def add(x, y=3):
total = x + y
return total
print(add(5))
print(add(5, 7))
print(add(x=2))
print(add(x=8, y=4))
print(1, 2, 3, 4, 5)
print(1, 2, 3, 4, 5, sep=' - ')
# The default value is stored at the definition of the function
# as sho... |
matrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
spar = mai = scol = 0
for l in range(0, 3):
for c in range(0, 3):
matrix[l][c] = int(input(f'Digite um valor para [{l}, {c}]: '))
print('-=' * 15)
for l in range(0, 3):
for c in range(0, 3):
print(f'[{matrix[l][c]:^5}] ', end='')
if matrix[l][... |
a=int(input("Enter the first term of the GP: "))
r=int(input("Enter the common ratio: "))
n=int(input("Enter the number of terms: "))
sum=0
product=1
for i in range(n):
term=a*pow(r,i)
sum=sum+term
product=product*term
print("Sum of",n,"terms=",sum)
print("Product of",n,"terms=",product)
|
"""Various utils dealing with classes."""
def overrides_method(method_name, obj, base):
"""
Return True if the named base class method is overridden by obj.
Parameters
----------
method_name : str
Name of the method to search for.
obj : object
An object that is assumed to inh... |
def get_starting_params():
num_players = int(input("Enter Number of Players : ")) # it takes user input
deck_size = 48
if num_players == 2:
hand_size = 10
points_threshold = 5
number_starting_common_cards = 8
elif num_players == 3:
hand_size = 8
points_threshol... |
class Benchmark:
@classmethod
def get_train_tasks(cls, sample_all=False):
return cls(env_type='train', sample_all=sample_all)
@classmethod
def get_test_tasks(cls, sample_all=False):
return cls(env_type='test', sample_all=sample_all)
|
def includeme(config):
# settings = config.registry.settings
config.add_route('processes', '/processes')
config.add_route('processes_list', '/processes/list')
config.add_route('processes_execute', '/processes/execute')
config.include('phoenix.processes.views.actions')
|
class ColumnStyle(TableLayoutStyle):
"""
Represents the look and feel of a column in a table layout.
ColumnStyle(sizeType: SizeType,width: Single)
ColumnStyle()
ColumnStyle(sizeType: SizeType)
"""
@staticmethod
def __new__(self,sizeType=None,width=None):
"""
__new__(cls: type)
__new__(c... |
special_sum = 0
n_minus_1 = n_minus_2 = 1
fib_n = 0
while fib_n < 1000000:
fib_n, n_minus_1, n_minus_2 = n_minus_1, n_minus_2, n_minus_1 + n_minus_2
if fib_n % 2 == 0: special_sum += fib_n
print(special_sum)
|
test = { 'name': 'q0_1',
'points': 1,
'suites': [ { 'cases': [ {'code': ">>> flavor_count.labels == ('Flavor', 'count')\nTrue", 'hidden': False, 'locked': False},
{'code': '>>> flavor_count.take(0).column("count").item(0) == 4\nTrue', 'hidden': False, 'locked': False},... |
EXPECTED_TOKEN = "eyJhbGciOiJSUzI1NiIsImtpZCI6Ijk0OTRhZDc1LTNmNTQtNDE1NS04NGZhLWMxYTE3ZGEyMmIzNSIsInR5cCI6IkpXVCJ9.eyJhbGxvdyI6eyIqIjoiKiJ9LCJkZW55Ijp7fX0.nDqCxO2Q1iXpxzbH7syxuyqw7kCY0sDfi9RX-VSUMTRN5aWTLt1bcPw4oN_jx89-YHBzDwnwBc07RsMgpFuo4zz2LU9PF0ciYxMNX-atTNsaIn05NkXT08au2AYb0DRCDS76MZ4QNi-4mRpLrj1SD4mSCwGtc2WNw9f0J... |
# Copyright 2020 The Maritime Whale Authors. All rights reserved.
# Use of this source code is governed by an MIT-style license that can be
# found in the LICENSE.txt file.
#
# Handles log writing.
def log(filename, msg):
"""Append message to specified logfile."""
f = open(filename, "a")
f.write(msg + "\n"... |
# Floyed Loop
# Double linked List definition
class DListNode(object):
def __init__(self):
# self.value = x
self.next = None
self.prev = None
class Floyed(object):
def __init__(self):
self.head = None
# super(Floyed, self).__init__()
self.slow = DListNode()
... |
#!/usr/bin/env python
"""
__init__
Module containing methods for daemonizing
applications.
"""
|
def parse_app_id(app_id, method):
if app_id is not None and "/" in app_id:
# This is the normal case - narrative methods
app_id_parts = app_id.split("/")
app_type = "narrative"
elif method is not None:
# Here we use the method for non-narrative methods.
app_id_parts = met... |
filename = 'test.txt'
filehandle = open('test.txt')
row = 1
filelist = list()
for item in filehandle:
print(item)
if item.startswith('4'):
item = item.strip()
item = int(item)
if item == row:
filelist.append(item)
row = row + 1
else:
... |
a = 0
b = 67 # 1
c = b # 2
d = 0
e = 0
f = 0
g = 0
h = 0
# count the number of mul
# smoke test for asm translation correctness
count = 0
# jumps > 0: if-else
# jumps < 0: do-while
if a != 0: # 2, 5
b *= 100 # 5
b += 100000 # 6
c = b # 7
c += 17000 # 8
while True: # 32
f = 1 # 9 - flag registe... |
#Create a histogram from a given list of integers
def histogram( items ):
for n in items:
output = ''
times = n
while( times > 0 ):
output += ' @ '
times = times - 1
print(output)
histogram([2, 3, 6, 5])
|
# coding=utf-8
#
# for using a COCO model to finetuning with DIVA data.
targetClass1to1 = {
"Vehicle":"car",
"Person":"person",
"Parking_Meter":"parking meter",
"Tree":"potted plant",
"Other":None,
"Trees":"potted plant",
"Construction_Barrier":None,
"Door":None,
"Dumpster":None,
"Push_Pulled_Object":"suitc... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 5 22:50:19 2020
@author: xg7
"""
def convert_to_Roman_numeral(A):
# can be improved
rome_dict = {(2**(num//2))*(5**(num//2 + num%2)): lett for num, lett in enumerate('IVXLCDMGH')}
res = ''
for num, ln in enumerate(map(int, str(A)),... |
# Write a short Python function, is even(k), that takes an integer value and
# returns True if k is even, and False otherwise. However, your function
# cannot use the multiplication, modulo, or division operators
def is_even(k):
even_nums = [0, 2, 4, 6, 8]
string_k = str(k)
string_list = [c for c in string... |
'''
Faça um programa que tenha uma função chamada “escreva()”,
que recebe um texto qualquer como parâmetro e mostre uma mensagem com tamanho variável.
'''
def escreva(palavra):
print('~' * n)
print(f' {palavra}')
print('~' * n)
palavra = str(input('Digite algo: '))
n = len(palavra) + 4
escreva(palavra) |
"""Crie um programa que tenha uma tupla única com nomes de produtos e seus respectivos preços, na sequencia.
No final, mostre uma listagem de preços, organizando os dados m forma tabular."""
produtos = ('Acucar', '8,60', 'Feijão', '10,20', 'Arroz', '19,00', 'Macarrão', '6,50', 'Nescal', '11,90',
'Detergent... |
#Exercício Python 022: Crie um programa que leia o nome completo de uma pessoa e mostre:
#– O nome com todas as letras maiúsculas e minúsculas;
#– Quantas letras ao todo (sem considerar espaços);
#– Quantas letras tem o primeiro nome.
n = str(input('Digite seu nome! ')).strip()
frase = n
div = frase.split()
#div2 = di... |
numb1 = int(input('Digite um valor: '))
numb2 = int(input("Digite outro valor: "))
tot = numb1 + numb2
print('A soma entre {} e {} é igual a {}'.format(numb1, numb2, tot))
print('''
A soma entre {} e {} é igual a: {}.
'''.format(numb1, numb2, tot)) |
# Sample Test passing with nose and pytest
def test_pass():
assert True, "Sample test"
|
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
ans = []
def dfs(root: TreeNode, sum: int, path: List[int]) -> None:
if root is None:
return
if root.val == sum and root.left is None and root.right is None:
ans.append(path + [root.val])
retur... |
"""API endpoints."""
API_BASE = "https://osu.ppy.sh/api"
USER = API_BASE + "/get_user"
USER_BEST = API_BASE + "/get_user_best"
USER_RECENT = API_BASE + "/get_user_recent"
SCORES = API_BASE + "/get_scores"
BEATMAPS = API_BASE + "/get_beatmaps"
MATCH = API_BASE + "/get_match"
|
class Address:
def __init__(self, street, city, pincode) -> None:
self.street = street
self.city = city
self.pincode = pincode
class Student:
def __init__(self,name, email, street, city, pincode) -> None:
self.name = name
self.email = email
self.address = Address... |
h , m = map(int, input().split())
if m < 45 :
if h==0:
h = 23
else:
h-=1
m += 15
else:
m -= 45
print(h,m) |
text = """
//------------------------------------------------------------------------------
// Explict instantiation.
//------------------------------------------------------------------------------
#include "SolidSPHHydroBase.cc"
#include "SolidSPHEvaluateDerivatives.cc"
#include "Geometry/Dimension.hh"
namespace Sph... |
"""
1. Clarification
2. Possible solutions
- Bit Manipulation, Maths
3. Coding
4. Tests
"""
# T=O(1), S=O(1)
class Solution:
def getSum(self, a: int, b: int) -> int:
mask = 0xffffffff
while b & mask != 0:
carry = (a & b) << 1
a = a ^ b
b = carry
retu... |
# pyfc4
# version info
__version_info__ = ('0', '1')
__version__ = '.'.join(__version_info__)
|
CONTRACT_RECEIVE_FUNCTION_SOURCE = '''
pragma solidity ^0.6.0;
contract Receive {
string text;
fallback() external payable {
text = 'fallback';
}
receive() external payable {
text = 'receive';
}
function getText() public view returns (string memory) {
return text;
... |
# Define a function that takes in two non-negative integers a and b and returns the last decimal digit of a^b.
# Note that a and b may be very large!
# For example, the last decimal digit of 9^7 is 9, since 9^7=4782969.
# The last decimal digit of (2^200)^2300, which has over 10^92 decimal digits, is 6.
# Also, plea... |
num = int(input("Input: "))
count = 0
squareLength = 3
while squareLength * squareLength < num:
squareLength += 2
squareLength -= 2
cornerValue = squareLength * squareLength
diff = num - cornerValue
midPoint = (squareLength + 1) / 2
# # Walk right one
# diff += 1
# # Walk north
# if squareLength > diff:
# dif... |
# 음양 더하기
def solution(absolutes, signs):
return sum([x if y else -x for x, y in zip(absolutes, signs)])
'''
테스트 1 〉 통과 (0.11ms, 10.2MB)
테스트 2 〉 통과 (0.12ms, 10.2MB)
테스트 3 〉 통과 (0.11ms, 10.2MB)
테스트 4 〉 통과 (0.11ms, 10.3MB)
테스트 5 〉 통과 (0.12ms, 10.3MB)
테스트 6 〉 통과 (0.11ms, 10.2MB)
테스트 7 〉 통과 (0.10ms, 10.2MB)
테스트 8 〉 통과... |
#Python program to Find ASCII value of character
def main():
x=input("Enter a character")
print("The ASCII value of",x,"is",ord(x))
if __name__=='__main__':
main()
|
class BinarySearch:
def __init__(self, data, item) -> None:
self.data = data
self.item = item
def binary_search(self):
"""_summary_"""
low = 0
high = len(self.data) - 1
while low <= high:
middle_number_index = (low + high) // 2
guess =... |
class ViewFamily(Enum,IComparable,IFormattable,IConvertible):
"""
An enumerated type that corresponds to the type of a Revit view.
enum ViewFamily,values: AreaPlan (110),CeilingPlan (111),CostReport (106),Detail (113),Drafting (108),Elevation (114),FloorPlan (109),GraphicalColumnSchedule (119),ImageView (1... |
{
"cells": [
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The max value = 5\n",
"The min value = -3\n",
"The max squared value = 25\n",
"The length of the list = 7\n",
"T... |
"""
A module with a function to show off positional for-loops.
This function has been fully implemented, and is correct.
Author: Walker M. White
Date: April 15, 2019
"""
def partition(s):
"""Returns: a list splitting s in two parts
The 1st element of the list consists of all characters in even
positi... |
class TestClass(object):
def test_eken(self):
eken = 'diq'
assert eken == 'diq'
def test_gman(self):
gman_is_g = True
assert gman_is_g is True
def test_t(self):
tys_biceps_circumference = 5*1000
assert tys_biceps_circumference > 1000
|
load("//:plugin.bzl", "ProtoPluginInfo")
load(
"//internal:common.bzl",
"ProtoCompileInfo",
"copy_file",
"descriptor_proto_path",
"get_int_attr",
"get_output_filename",
"strip_path_prefix",
)
ProtoLibraryAspectNodeInfo = provider(
fields = {
"output_files": "The files generated ... |
# def foo (arg1, arg2, arg3):
# print (arg1,arg2,arg3)
# foo(
# arg2 = 'second',
# arg3 = 'third',
# arg1 = ['name1','name2']
# )
# string1 = ('{} part'.format('first'))
# string2 = 'second part'
# print (string1+string2)
def create_table(name,columns,datatype,key): #columns is a list containing col... |
chave_certa = 2002
while True:
senha = int(input())
if senha == chave_certa:
print("Acesso Permitido")
break
print("Senha Invalida") |
#!/usr/bin/python3
def max_integer(my_list=[]):
my_list.sort()
if my_list:
return my_list[len(my_list) - 1]
else:
return None
|
"""
Assignment operators are used to assign values to variables
Documentation - https://www.w3schools.com/python/python_operators.asp
"""
x = 3
y = 5
x = y # Means the value of x is equal to y (Assignment, 5)
x += y # Means the value of x is x + y (Addition Assignment, 8)
x -= y # Means the value of x is x - y (Subt... |
class Jogador():
def __init__(self):
self.cartas = []
self.soma = 0
self.turnos = 0 |
"""
Contain Edge class for use in a graph
"""
class Edge():
"""
Edge class
"""
def __init__(self, src, dest, **options):
self.src = src
self.dest = dest
self.options = options
def __repr__(self):
options = "\n".join(
[f' {key}="{value}"' for key, value... |
# -*- coding: utf-8 -*-
"""
Stub ui to allow debug on PC
"""
AUTOCAPITALIZE_NONE = 0
def measure_string(*args, **kwargs):
return 12.0
def in_background(func):
return func
def get_screen_size():
return 100, 100
class View(object):
def __init__(self, *args, **kwargs):
self.on_screen = Tru... |
load("@bazel_skylib//lib:unittest.bzl", "asserts", "unittest")
load(":include_tools.bzl", "CommandLineToTemplateString", "ProccessResponse")
def _proccess_response_test_impl(ctx):
response = """clang version 6.0.0-1ubuntu2 (tags/RELEASE_600/final)
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/... |
feature_dict = {
'VMAF_feature': ['vif_scale0', 'vif_scale1', 'vif_scale2', 'vif_scale3', 'adm2', 'motion', ],
}
model_type = "LIBSVMNUSVR"
model_param_dict = {
# ==== preprocess: normalize each feature ==== #
# 'norm_type': 'none', # default: do nothing
'norm_type': 'clip_0to1', # rescale to within... |
class NumberParsingError(Exception):
pass
def handle_even_number(number_str):
try:
number = int(number_str)
except ValueError:
raise NumberParsingError("Przekazany argument nie jest poprawną liczbą")
if number % 2 != 0:
raise NumberParsingError("To nie jest liczba parzysta!")... |
class Operation(dict):
def __init__(self, operationType=None, operationName=None, listOfInputMessages=None, listOfOutputMessages=None):
dict.__init__(self, operationType=operationType, operationName=operationName
, listOfInputMessages=listOfInputMessages, listOfOutputMessages=listOfOut... |
'''(Partitioning Arrays: Dutch Flag [M]): Dutch National Flag Problem:
Given an array of integers A and a pivot, rearrange A in the following order:
[Elements less than pivot, elements equal to pivot, elements greater than pivot]
For example, if A = [5,2,4,4,6,4,4,3] and pivot = 4 -> result = [3,2,4,4,4,4,6,5]'''... |
"""
Copyright 2019, SICK AG, Waldkirch
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 to in writing, softwa... |
# copying a large dictionary
a = {i: 2 * i for i in range(1000)}
b = a.copy()
for i in range(1000):
print(i, b[i])
print(len(b))
|
class Parser():
def __init__(self, file):
content = [line.strip() for line in file.readlines()]
content = [line.split('//')[0].strip() for line in content if not line.startswith('//') and line is not '']
self.source_code: list = content
self.current_command: int = 0
def _comman... |
pkgname = "ninja"
pkgver = "1.10.2"
pkgrel = 0
hostmakedepends = ["python"]
pkgdesc = "Small build system with a focus on speed"
maintainer = "q66 <q66@chimera-linux.org>"
license = "Apache-2.0"
url = "https://ninja-build.org"
sources = [f"https://github.com/ninja-build/ninja/archive/v{pkgver}.tar.gz"]
sha256 = ["ce358... |
fonts = AllFonts()
for font in fonts:
min = 0
max = 0
for glyph in font:
if glyph.bounds != None:
if glyph.bounds[1] < min:
min = glyph.bounds[1]
if glyph.bounds[3] > max:
max = glyph.bounds[3]
print(min,max)
capSpace = m... |
def palindrome():
largest = 0
for a in range(999, 99, -1):
for b in range(999, 99, -1):
# use an awesome extended slice to reverse string
# https://docs.python.org/2/whatsnew/2.3.html#extended-slices
# print(a, b, a*b, str(a*b)[::-1])
if a*b == int(str(a*b... |
'''
Probem Task : Create a function that, given a number, returns the corresponding Fibonacci number.
Problem Link : https://edabit.com/challenge/8Ko5tPg8Ch5SRCAhA
Examples:
fibonacci(3) ➞ 3
fibonacci(7) ➞ 21
fibonacci(12) ➞ 233
'''
def fibonacci(num):
if num < 2:
return 1
else:
return ... |
class MaxHeap:
def __init__(self):
self.data = []
def root_node(self):
return self.data[0]
def last_node(self):
return self.data[-1]
def left_child_index(self, index):
return 2 * index + 1
def right_child_index(self, index):
return 2 * index + 2
def ... |
#!/usr/bin/python3
# round(x)返回浮点数x的四舍五入的值(实际是五舍六入)
# round(2.5)会返回2,round(2.6)会返回3
round(3.1415926) # 默认取整
#>> 3
round(3.1415926, 1) # 保留1位浮点数
#>> 3.1
round(3.1415926, 4) # 保留4位浮点数
#>> 3.1416
|
"""
============
proyecto IER
============
Para el proyecto de IER
"""
|
wt9_2_10 = {'192.168.122.110': [5.7108, 8.5399, 6.3325, 4.9405, 4.3064, 5.4196, 4.7852, 4.852, 5.5112, 6.0472, 5.987, 5.9324, 5.9693, 5.9885, 5.9521, 5.9517, 5.9214, 5.8912, 6.1639, 6.1483, 6.1269, 6.1008, 6.0684, 6.0465, 6.0183, 5.9975, 6.094, 6.0673, 6.0838, 6.2445, 6.2204, 6.1954, 6.1722, 6.1532, 6.1334, 6.1211, 6.... |
index = 0
def register(name, func):
global index
index += 1
func_name = name + str(index)
globals()[func_name] = func
return func_name |
def search(data):
string = ""
number = ""
last_i = ""
for el in data:
if el.isdigit():
number += el
last_i = data.index(el)
continue
elif number == "":
string += el
else:
break
return string, number, last_i
dat... |
# -*- coding: utf-8 -*-
'''
>>> from opem.Dynamic.Padulles_Hauer import *
>>> import shutil
>>> Test_Vector={"T":343,"E0":0.6,"N0":5,"KO2":0.0000211,"KH2":0.0000422,"KH2O":0.000007716,"tH2":3.37,"tO2":6.74,"t1":2,"t2":2,"tH2O":18.418,"B":0.04777,"C":0.0136,"Rint":0.00303,"rho":1.168,"qMethanol":0.0002,"CV":2,"i-start":... |
class Strategy:
"""A combination of alternative and its belief."""
def __init__(self, alternative, belief):
self.alternative = alternative
self.belief = belief
|
bag = dict()
bag["mathTextBook"] = 12.5
bag["nameTag"] = "Winston"
bag.update({"nameTag": "Grace"})
print(bag) |
M = 10**9 + 7
def solve(n):
a = n
i = 1
while i < n:
k = n // i
j = min(n // k + 1, n)
a += k * (j - i) * n - k * (k + 1) * (j - i) * (i + j - 1) // 4
a %= M
i = j
return a
for _ in range(int(input())):
n = int(input())
print(solve(n))
|
"""Extra, simple, "builtin-like" functions."""
def subclasstree(cls):
"""Return dictionary whose first key is the class and whose
value is a dict mapping each of its subclasses to their
subclass trees recursively.
"""
classtree = {cls: {}}
for subclass in type.__subclasses__(cls): # long vers... |
string = input('enter string from which vowels are need to be remove ')
string = string.lower()
vowels = ('a','e','i','o','u')
for c in string:
if string in vowels:
new_str = string.replace(c,'')
print(new_str)
|
#
# PySNMP MIB module EdgeSwitch-DOT1X-ADVANCED-FEATURES-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EdgeSwitch-DOT1X-ADVANCED-FEATURES-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:56:10 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4... |
#!/usr/bin/python
class User(object):
def __init__(self,conn, addr,name=None):
self.name = name
self.conn = conn
self.addr = addr
class Player(User):
def __init__(self,conn,addr,name=None):
super(Player,self).__init__(conn,addr,name)
self.passwd = None
self.scor... |
# Given a binary tree and a number ‘S’,
# find all paths in the tree such that the sum of all the node values of each path equals ‘S’.
# Please note that the paths can start or end at any node
# but all paths must follow direction from parent to child(top to bottom).
# worst: O(N^2) best:O(NlogN)
# space: O(N)
clas... |
"""
PYTHON LIST SLICING: FLAT LIST
"""
__author__ = 'Sol Amour - amoursol@gmail.com'
__twitter__ = '@solamour'
__version__ = '1.0.0'
# SYNTAX: [ startCut : endCut ]
# startCut = This is the first item included in the Slice
# endCut = This is the last item included in the Slice
# NOTES:
# All parameters h... |
def pkcs_7_padding(block,N=16):
if N >= 256:
raise Exception('N is too large.')
num_remaining = N - len(block) % N
return block + (chr(num_remaining) * num_remaining).encode('utf-8')
if __name__ == '__main__':
print(pkcs_7_padding(b'YELLOW SUBMARINE', 20)) |
#
# @lc app=leetcode id=487 lang=python3
#
# [487] Max Consecutive Ones II
#
# @lc code=start
class Solution:
def findMaxConsecutiveOnes(self, nums):
curzero = 0
lp = 0
rp = 0
mxlen = 0
while rp < len(nums):
if nums[rp] == 0:
curzero += 1
... |
"""Simple dummy generator for the Pairsum problem, outputting a trivial instance."""
n = 0
with open("input", "r") as input:
n = int(input.readline())
with open("output", "w") as output:
output.write(" ".join("1" for i in range(n)))
output.write("\n")
output.write("0 1 2 3")
|
input = """
1 2 2 1 3 4
1 3 2 1 2 4
1 4 0 0
0
3 b
2 a
0
B+
0
B-
1
0
1
"""
output = """
{b}
{a}
"""
|
number1 = int (input())
number2 = int (input())
if number1 >= number2:
print('Greater number: ', number1)
elif number2 > number1:
print('Greater number: ', number2)
else:
print() |
# header
"""
#Format\tALLC
#Species\thuman
#Genome\thg19
#MethylomeType\tsingle-cell
#Technology\tsnmC-seq2
#ContextLength\t3
#MethylationBase\t0
#mCContent\tCNN
#Generator\tALLCools
""" |
# -*- coding: utf-8 -*-
name = 'turret_resolver'
version = '1.1.3.0'
authors = ['wen.tan',
'ben.skinner',
'daniel.flood']
build_requires = ['python']
build_command = 'rez env python -c "python {root}/rezbuild.py {install}"'
requires = ['pgtk', 'tk_core']
def commands():
env.PYTHONPATH.... |
def sum(num):
return num + num
def squre(num):
return num * num |
# lextab.py. This file automatically created by PLY (version 2.2). Don't edit!
_lextokens = {'HEADER_NAME': None, 'IDENTIFIER': None, 'PP_NUMBER': None, 'CHARACTER_CONSTANT': None, 'STRING_LITERAL': None, 'OTHER': None, 'PTR_OP': None, 'INC_OP': None, 'DEC_OP': None, 'LEFT_OP': None, 'RIGHT_OP': None, 'LE_OP': None,... |
num_students = int(input())
students = {}
for _ in range(num_students):
name, grade = input().split(' ')
if name not in students:
students[name] = []
students[name].append(float(grade))
for name, grades in students.items():
average_grade = sum(grades) / len(grades)
grades = [f'{... |
#Paula Duffy 2018-02-06
#Collatz Conjecture - Week 3 Exercise
n = int(input("Please enter an integer: "))
while n > 1:
if n % 2 == 0:
n = n // 2 #divide by 2 if integer is even
print (n)
elif n % 2 == 1:
n = (n * 3) + 1 #multiply by 3 and add 1 if integer is not even
print (n)
|
n = float(input('Digite um valor: '))
if n % 2 == 0:
print(f'{n} é PAR!')
else:
print(f'{n} é ÍMPAR!')
|
def add(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def div(a,b):
return a/b
print(__name__) |
class Node(object):
def __init__(self, data):
"""Initialize this node with the given data."""
self.data = data
self.next = None
self.prev = None
def __repr__(self):
"""Return a string representation of this node."""
return 'Node({!r})'.format(self.data)
class D... |
class LatchApp(object):
def __init__(self, appid, secret):
"""
Class constructor
:param appid: App ID
:param secret: Secret code
"""
self._appid = appid
self._secret = secret
self._proxy = None
@property
def appid(self):
"""
Returns App ID
:return: App ID
"""
r... |
class ObjectView(dict):
def __init__(self, *args, **kwargs):
super(ObjectView, self).__init__(**kwargs)
for arg in args:
if not arg:
continue
elif isinstance(arg, dict):
for key, val in arg.items():
self[key] = val
... |
"""
Author: Marcos Oliveira
Github: https://github.com/the-physicist
Date: 18/10/21
"""
# 7 - Faça um Programa que calcule a área de um quadrado, em seguida mostre o dobro desta área para o usuário.
lado = float(input("Qual o comprimento do lado do quadrado? \n"))
area = lado * lado
area_dobro = area * 2
print("... |
def fermat(num):
"""Runs a number through 1 simplified iteration of Fermat's test."""
if ((2 ** num) - 2) % num == 0:
return True
else: return False
def gen_primes(maxnum):
"""Generates primes using fermat"""
if maxnum % 2 == 0: # finds odd number
maxnum -= 1
num = maxnum
wh... |
# Problem:
# Write a program that reads a number of integer numbers entered by the user and sums them.
num_of_loops = int(input())
sum = 0;
for i in range(1, num_of_loops + 1):
num = int(input())
sum += num
print(sum)
|
#!/usr/bin/env python
scores = {
"pullups": [(4,20), (5,23), (5,23), (5,23), (5,21), (5,20), (5,19), (4,19)],
"crunches": [
(70,105),
(70,110),
(70,115),
(70,115),
(70,110),
(65,105),
(50,100),
(40,100),
],
"run": [
(18 * 60,27 * 6... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.