content stringlengths 7 1.05M |
|---|
# Even number is divisible by 2 and odd number is not. Using the remainder of the number when divided by two we can find even or odd or using AND operation with 1.
#using % operator
a=int(input())
if a%2==0:
print("Even")
else:
print("Odd")
#using & operator
a=int(input())
if a & 1:
print("Odd")
else:
print... |
class Config(object):
max_len = 512 - 2
num_sample = 50
processed_path = "data/processed/dev.json"
def __init__(self):
pass
config = Config() |
def look_and_say(s):
output = []
i = 0
while i < len(s):
# Find a run of the form s[i:j] of length j - i > 0.
j = i + 1
while j < len(s) and s[j] == s[i]:
j += 1
output.append(str(j - i))
output.append(s[i])
i = j
return ''.join(output)
def m... |
# funkcja sprawdzająca, czy x jest liczbą pierwszą
def pierwsza(x):
if x <= 1:
return False
for i in range(2, x):
if x % i == 0:
return False
return True
# użytkownik podaje liczbę tak długo dopóki nie poda dwóch liczb naturalnych
m, n = -1, -1
while m < 0 or n < 0:... |
class DiscreteFuzzyNumberMembershipOutOfBounds(Exception):
"""
An Exception which indicates that the membership values entered are not between 0 and 1.
"""
def __init__(self, message: str = "The membership functions of the labels as well as the alpha-cuts thresholds "
... |
#
# @lc app=leetcode id=201 lang=python3
#
# [201] Bitwise AND of Numbers Range
#
# @lc code=start
class Solution:
def rangeBitwiseAnd(self, m: int, n: int) -> int:
while n > m:
n = n & (n - 1)
return n
# @lc code=end
# Accepted
# 8266/8266 cases passed(48 ms)
# Your runtime beats 9... |
#!/usr/bin/env python
# -*- coding: latin-1 -*-
"""
IdaSplode settings
"""
#
# Default color for instructions.
# Format: 0xRRGGBB
#
COLOR_INS_RESET = 0xffffff
#
# Color to set an instruction if it was executed during the run.
# Format: 0xRRGGBB
#
COLOR_INS_EXECUTED = 0xeeeeee
#
# Color to set... |
dset = [(1,'L','Cerebellum-vermis',None,True,None),
(1,'R','Cerebellum-VI',None,True,True),
(1,'L','Cingulate-posterior',None,None,True),
(1,'R','Cingulate-posterior',None,None,True),
(1,'R','IFG-pars opercularis',None,None,True),
(1,'R','IFG-pars triangularis',None,None,True),
... |
#!/usr/bin/env python
#-------------------------------------------------------------------------------
class Solution:
def floodFill(self, image, sr, sc, newColor):
"""
:type image: List[List[int]]
:type sr: int
:type sc: int
:type newColor: int
:rtype: List[List[int... |
def almostIncreasingSequence(sequence):
def helper(newArray):
# print(newArray)
if len(newArray)<2:
return True
for i in range(len(newArray)-1):
if newArray[i] >= newArray[i+1]:
return False
return True
i = 0
j = i+1
whil... |
N = int(input())
v_list = list(map(int, input().split()))
c_list = list(map(int, input().split()))
ans = 0
for i in range(N):
v = v_list[i]
c = c_list[i]
if v > c:
ans += v -c
print(ans)
|
def hoopCount(n):
""" hoop_count == PEP8 (forced mixedCase by CodeWars) """
return 'Great, now move on to tricks' if n >= 10 else\
'Keep at it until you get it'
|
# Keep track of Lexer position
class Position:
# index -> int index of the position
# ln_number -> int line number of the position
# col_number -> int column number of the position
# f_name -> string file name of the position
# f_text -> string text (input)
def __init__(self, index, ln_number, c... |
#!/usr/bin/python
# ==============================================================================
# Author: Tao Li (taoli@ucsd.edu)
# Date: May 6, 2015
# Question: 094-Binary-Tree-Inorder-Traversal
# Link: https://leetcode.com/problems/binary-tree-inorder-traversal/
# ========================================... |
test_list = []
n = None
while n != 0:
n = int(input())
if n !=0:
test_list.append(n)
c = 1
for value in test_list:
cedules = [0]*4
while 0 < value <= 10000:
if value//50 > 0:
cedules[0] += value//50
value=value%50
elif value//10 > 0:
cedul... |
# -*- coding:utf-8 -*-
"""
@author: SiriYang
@file: __init__.py
@createTime: 2021-01-22 16:12:10
@updateTime: 2021-01-22 16:12:10
@codeLines: 0
"""
|
print("\n\n\n 3. Arnoldo sigue en su búsqueda de números,"
"ahora busca números raros. Los números raros son "
"aquellos que son divisibles entre 5 y entre 3, pero"
" no entre 2. El quiere crear un programa en el cual "
" ingrese un número y le diga si es raro o no. \n")
numero = int(input("\n Escribe u... |
a,b=input().split()
bSum,ans=0,0
for i in b: bSum+=int(i)
for i in a: ans+=int(i)*bSum
print(ans) |
#Create a script that checks a list against countries_clean.txt
#and creates a list with items that were in that file
checklist = ["Portugal", "Germany", "Munster", "Spain"]
with open("countries_clean.txt", "r") as file:
content = file.readlines()
content = [i.rstrip('\n') for i in content]
checked = [i for i in... |
# import sys
# class Solution:
# def lengthOfLIS(self, nums):
# """
# :type nums: List[int]
# :rtype: int
# """
# data = nums
# memo = {}
# i = 0
# last = -1111111
# rt = self.recursion(data, i, last, memo)
# return rt
# def... |
#MenuTitle: Move All Paths Position to Left Bottom
# -*- coding: utf-8 -*-
__doc__="""
枠付きのパスを全体にフィットさせます。
"""
Glyphs.clearLog()
font = Glyphs.font
layer = font.selectedLayers[0]
asc = layer.ascender
desc = layer.descender
layerWidth = layer.width
layerHeight = layer.ascender - layer.descender
frameWidth = layer.b... |
"""Given a string,S of length N that is indexed from 0 to N-1,
print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line
Note 0 is considered to be an even index.
input format
The first line contains an integer, T (the number of test cases).
Each line i of the T subsequent lines... |
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
curre... |
def sum_multiples_of_3_or_5_below_n(n):
"""
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
"""
return sum(x for x in range(n) if (x % 3 == 0 or x % 5 == 0))
def problem001():
"""
Find the sum of al... |
# The cli_spec is used by runAM.cli to build build argparse arguments.
cli_spec = {
'__main_parser': {
'help': '=== runAM (run Arista Module) CLI help ===\n To enable autocomplete run: eval "$(register-python-argcomplete runAM)"',
'add_argument': [
{
'arg_name': '--ec... |
class Solution:
def removeInvalidParentheses(self, s):
r = []
self.remove(s, r, 0, 0, "()")
return r
def remove(self, s, r, li, lj, c):
cnt = 0
for i, e in enumerate(s[li:], start=li):
cnt += (1, -1, 0)[c.find(e)]
if cnt < 0:
for j... |
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
roomVisited = set()
keys = []
# Enter room 0
roomVisited.add(0)
for k in rooms[0]:
keys.append(k)
while keys:
# use the first key to unlock the door
... |
def read_gold_data(data_path: str):
return [
line.strip() for line in open(data_path)
]
def read_pred_data(data_str: str):
return data_str.split("\n")
|
# define acronyms
acronyms = {
'AFK': 'Away From Keyboard',
'BBIAB': 'Be Back In A Bit',
'BBL': 'Be Back Later',
'BBS': 'Be Back Soon',
'BRB': 'Be Right Back',
'IDK': 'I Dont Know',
'KISS': 'Keep It Simple Stupid',
'LOL': 'Laughing Out Loud'
}
# get acronym from user input
acr = input(... |
output_header = ["image_names", "emergency_or_not"]
# =================================================================================
# Cornell Birdcall Identification
# =================================================================================
BIRD_CODE = {
'aldfly': 0, 'ameavo': ... |
def probability(num, den):
if den == 0:
return 0
return num / den
def matrixEdges(matrx, n):
edges = dict()
mylist = []
for i in range(n):
for j in range(n):
var = matrix[i][j]
if var not in edges:
edges[var] = []
if i - 1 >= 0:
... |
class WSApiException(Exception):
"""
Webservice exception from api.
"""
pass
|
# Develop a program that reads four values from the keyboard and stores them in a tuple. At the end, show: A) How many
# times did the value 9 appear. B) In which position the first value 3 was entered. C) What were the even numbers.
numbers = (int(input('Enter a number: ')),
int(input('Enter another number... |
"""
Module to implement predicate classes.
Class of every predicate registered to ``Q`` is defined here.
"""
|
elastic_mapping = {
"mappings":{
"patients":{
"_source":{
"enabled": True
},
"properties":{
"active":{
"type":"boolean"
},
"sex":{
"type":"keyword"
},
"yr_birth":{
... |
# Language: Python 3
# Author: Konstantin Kuchenmeister
# returns the length of a linked list
def getLength(head):
arr = []
while head is not None:
arr.append(head.data)
head = head.next
return len(arr)
# Intuition: Compare the two linkedlists pair/elementwise. If the numbe... |
hutang = 10000
bayar = 5000
sisaHutang = hutang - bayar
print ("Sisa hutang anda adalah ", sisaHutang)
|
"""Top-level package for dojo-cli."""
__author__ = """Robnet Kerns"""
__email__ = "robnet@jataware.com"
__version__ = "0.1.7"
|
"""Search Engine Keywords Highlighter"""
__version__ = '0.4'
__license__ = 'BSD License'
__author__ = 'Fantomas42'
__email__ = 'fantomas42@gmail.com'
__url__ = 'https://github.com/Fantomas42/django-sekh'
|
range = xrange; input = raw_input
ans = (0, -10**5)
for i in range(int(input())):
ans = max(ans, (int(input()), -i-1))
print(-ans[1])
|
# Copyright (c) 2021 Ben Maddison. All rights reserved.
#
"""aspa.neighbors Module."""
class _BaseNeighborType(object):
def __repr__(self):
try:
return self.name
except AttributeError:
return super().__repr__()
class _Customer(_BaseNeighborType):
name = "Customer"
c... |
manifest = "path_to_manifest_containing_tsvs"
with open(manifest+"/train.tsv",'r') as train_tsv, \
open(manifest+"/valid.tsv",'r') as val_tsv,\
open(manifest+"/dict.ltr.txt",'w') as dict_ltr,\
open(manifest+"/valid.wrd",'w') as wrd_val_out,\
open(manifest+"/train.wrd",'w') as wrd_train_out,\
open(manifest+"/valid.... |
def Fibonacci(condicao):
x = y = 1
contador = 1
while contador <= condicao:
contador += 1
yield x
x, y = y, x + y
return f'Já foram retornado os {condicao} valores desejados!'
f = Fibonacci(5)
for i in f:
print(i)
|
#!/usr/bin/env python3
numRows = int( input() )
numColumns = int( input() )
rowList = []
matchRowIndexTuple = None
for rowIndex in range( numRows ):
thisRow = input()
# check for matching
for existingRowIndex, existingRowVal in enumerate( rowList ):
# print( 'thisRow = {}'.format( thisRow ) )
# print( 'existing... |
{
"includes": [
"common.gypi"
],
"targets": [
{
"target_name": "tests",
"type": "executable",
"sources": [
"<!@(find ../test/ -name '*.cpp' ! -name 'writer_tests.cpp' ! -name 'writer_test_cases.cpp' ! -name 'testcase.cpp')"
],
"include_dirs": [
"../include/"... |
class Solution(object):
def nthSuperUglyNumber(self, n, primes):
"""
:type n: int
:type primes: List[int]
:rtype: int
"""
l=len(primes)
i=[-1]*l
v=[1]*l
res=[1]*n
for k in xrange(n):
x=min(v)
res[k]=x
... |
a = [2, 3, 4, 7]
b = a #ligação entre uma lista e outra..
b = a[:] # cria uma cópia e não uma ligação.
b[2] = 8
print(f'Lista A: {a}')
print(f'Lista B: {b}') |
# Just for npm
{
"targets": [{"target_name":"nop","type":"<(library)"}],
}
|
#Chess knight moves like the letter L.
# It can move two cells horizontally and one cell vertically, or two cells vertically and one cells horizontally.
# Given two different cells of the chessboard, determine whether a knight can go from the first cell to the second in one move.
r = int(input("r =?"))
if r <1 or r >8... |
## Contiene las configuraciones para el funcionamiento del algoritmo
global RS_sum #Tamaño de RS's
RS_sum = 3
global RS_mul
RS_mul = 2
def init():
global clk #Reloj
clk = 1
global delay
delay = 1
global registro
registro = [1,2,3,4,5,6,7,8,9,10,11,12]
global registro_en_uso
registro_en_uso = [0,0,0,0,0... |
# Not available in py3
#import dateutil
# This is not exactly ISO 8601, but close.
# Unfortunately datetime can't parse its own .isoformat() output
# (d'oh!)
DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S.%f'
def datetime_to_iso(d):
#return d.isoformat()
return d.strftime(DATETIME_FORMAT)
def iso_to_datetime(s):
... |
#!/usr/bin/env python3
class Laboratory():
"""
AmesPAHdbPythonSuite laboratory class
"""
def __init__(self, d=None, **keywords):
return None
|
"""
LINK: https://leetcode.com/problems/plus-one/
Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.
You may assume the... |
def quickPower(a, n):
if n == 0:
return 1
if n == 1:
return a
if n % 2 == 0:
return quickPower(a, n / 2) * quickPower(a, n / 2)
else:
return quickPower(a, n - 1) * a
|
#! /usr/bin/env python
# -*- coding:utf-8 -*-
''' config '''
MAX_CONNECTIONS = 1
''' 数据库配置 '''
DB_CONF = {
"host":"127.0.0.1:3306",
"dbname":"test",
"user":"root",
"password":"root",
}
''' 接口对应的操作 '''
ITFC_CONF = {
"insert":{
"void":"1",
"sql_fmt":"INSERT INTO `user` (`uid`,`emai... |
class InternalServerException(Exception):
pass
class SchemaValidationException(Exception):
pass
class ObjectAlreadyExistsException(Exception):
pass
class UpdatingModelException(Exception):
pass
class DeletingModelException(Exception):
pass
class ObjectDoesNotExistException(Exception):
... |
# -*- coding: utf-8 -*-
"""Top-level package for Kawaii Reagan."""
__author__ = """Kawaii Gator"""
__email__ = 'kawaiigator@420blaze.it'
__version__ = '0.1.0'
|
# Given an integer , n and n space-separated integers as input, create
# a tuple, t of those n integers. Then compute and print the result of hash(t) .
# Note : hash() is one of the functions in the __builtins__ module,
# so it need not be imported.
if __name__ == '__main__':
n = int ( input ( ) )
t =... |
class Solution:
def isNumber(self, s: str) -> bool:
try:
float(s)
return True
except:
return False
# n : the length of input string
## Time Complexity: O( n )
#
# Although it seems O(1) at forst glimpse,
# but float(s) does che... |
with open("input", "r") as f:
lines = f.readlines()
dots = []
folds = []
dots_list_finished = False
for line in lines:
line = line.strip()
if not line:
# empty line between list of dots and fold instructions
dots_list_finished = True
continue
if not dots_list_finished:
... |
#
# PySNMP MIB module EFDMIM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EFDMIM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:44: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 2019, 09:... |
# -*- coding: utf-8 -*-
"""Top-level package for Ovito Client."""
__author__ = """Ben Lindsay"""
__email__ = 'benjlindsay@gmail.com'
__version__ = '0.3.2'
|
ageOfuser = int(input())
yeartoday = int(input())
yearOfbirthday = yeartoday - ageOfuser
count = 0
for year in range (yearOfbirthday, 2022) :
haftage = (yeartoday - year) / 2
if haftage > 0 :
print(f'Il y a {yeartoday - year} ans, tu avais la moitié de lâge que tu as aujourdhui')
else :
prin... |
SECS_IN_HOUR = 60 * 60
def secs_to_hours(value):
return '{0:.1f}'.format(value / SECS_IN_HOUR)
|
class EXTENSION_ERROR(Exception):
def __init__(self, expected_ext, given_ext, message):
self.message = message
self.expected_ext = expected_ext
self.given_ext = given_ext
super().__init__(self.message)
def __str__(self):
return "%s Expected '%s' but '%s' is given." % (... |
DEFAULT_DB = "default" # this is the managed db for auth, users
PRISMA_DB = "prisma" # this is the unmanaged db for TD models
class PrismaRouter:
"""
A router to control db operations
"""
def db_for_read(self, model, **hints):
if not model._meta.managed:
return PRISMA_DB
... |
class Graph:
def __init__(self):
self.name_to_id = {}
self.id_to_name = {}
self.node_count = 0
self.adj_list = {}
self.inv_adj_list = {}
self.dfs_current_run = 0
self.visited = {}
self.dfs_current_path = []
def add_node(self, node):
node ... |
{
"metadata": {
"name": "Random Forest Variable Importance"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "code",
"collapsed": false,
"input": [
"import pandas as pd\n",
"import numpy as np\n",
"import pylab as pl\n",
"import ra... |
f = open("shopping_list2.txt", "w+",encoding="utf-8")
#f = open("shopping_list.txt", "a+", encoding="utf-8")
f.seek(0)
s = f.read()
print("Старый список:\n" + s)
f.write("\nсахар")
f.seek(0)
s = f.read()
print("Новый список:\n" + s)
#f = open("shopping_list2.txt", "w+", encoding="utf-8") # w режим стирания всех дан... |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... |
class Solution:
def print2largest(self,A,N):
A.sort(reverse=True)
for i in range(1,N):
if A[i]!=A[i-1]:
return A[i]
return -1
t=int(input())
for i in range(t):
n=int(input())
a=list(map(int,input().split()))
ob=Solution()
print(ob.print2largest(a,... |
# Make a function that takes in the arguments height and weight and returns BMI
____
____
# Use the function to calculate the BMI of a person with height 62 inches and a weight of 105 lbs
# Save this in an object name bmi_calc
# ____ = ____
# Display the BMI
# ____
|
# coding:utf-8
# 非递归的二分查找
sss = [1, 2, 3, 4, 5, 10, 22]
# 二分查找的话,有两种实现方式,一种就是递归的实现,一种就是非递归的模式
# 递归的话,那就是自己调用自己,而非递归的话,那就是一直循环,
# 直到对所有的情况,列举完成,才可
def binSearchWhile(mylist, key):
start = 0
end = len(mylist)
while True:
if len(mylist) == 0:
print("列表的长度为0,查询不出来!")
return -1;... |
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
a, aop = 0, '+'
b, bop = 0, None
nv = 0
for c in s:
if '0' <= c <= '9': # construct the value
nv = nv * 10 + (ord(c) - ord('0'))
elif c == ' ': continue
elif c == '+':
if bop is not None:
nv = b * nv... |
class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
output = 0
index = matrix[0].index(min(matrix[0]))
temp = []
for i in range(0, len(matrix), 1):
if matrix[i].index(min(matrix[i])) == index or matrix[i].index(min(matrix[i])) == index + 1 or matr... |
class LazyString(object):
"""Behaves like a string, but no instance is created until the string is actually used.
Takes a function which should be a string factory and a set of arguments to pass
to the factory. Whenever the string is accessed or manipulated the factory is called
to create the actual st... |
# 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 ... |
class A:
def __init__(self, x):
self.x = x
def __add__(self, y):
return self.x + y
def __len__(self):
return 10
def __iter__(self):
return iter(range(10))
def __str__(self):
return "bla"
a = A(3)
assert a + 1 == 4
assert len(a) == 10
i = 0
for j in a:... |
# The words listed below will be ignored when considering thesaurizing
# They need to remain unchanged to maintain proper sentence structure
WORDS = [
"the",
"of",
"and",
"a",
"to",
"in",
"is",
"you",
"that",
"it",
"he",
"was",
"for",
"on",
"are",
"as",
"with",
"his",
"they",
"I... |
class PerformanceLogger:
def __init__(self):
self.min_valid_loss = float("inf")
self.min_valid_epoch = -1
self.min_valid_train_loss = float("inf")
self.min_valid_test_loss = float("inf")
self.min_valid_valid_acc = 0
self.min_valid_test_acc = 0
self.min_test_l... |
# -*- coding: utf-8 -*-
# A ideia é comparar a soma de cada valor usando dois loops. O primeiro loop representa cada valor na lista e o
# segundo loop é usado para comparar esse valor com cada valor que vem em sequência na lista.
# Variável para o resultado
res = 0
# Input do número de elementos na lista, valor míni... |
#Write a Python program to get a string which is n (non-negative integer) copies of a given string.
def newest(string,n):
return string*n
print(newest('odks',4))
print(newest('Gabriel',9))
print(newest('I love you',10)) |
"""
dictionary.py
Words used across the project, sorted in alphabetical order.
"""
# A
D_A_STAR = 'A*'
D_ANGLE = 'angle'
D_ANGLE_NOISE = 'angle_noise'
D_AVG = 'avg'
# C
D_CLAMPED_ABS = 'clamped_abs'
D_CLAMPED_LINEAR = 'clamped_linear'
D_COS = 'cos'
# D
D_DIST_TO_TARGET = 'distance_to_target'
D_DISTANCE = 'distance'... |
HEADERS = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Max-Age": "3600",
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0",
}
SCHEMA_NAMES = ["Recipe", "WebPage"... |
""" Lomuto Partition : We are given an array and we have to put all elements smaller than this element to left and
bigger to the right. We assume that the pivot is always the last element in the array
If we are given a pivot element we can swap the pivot ad high to use this algorithm"""
"""Implementation"""
... |
"""
Python trove classifiers and classifiers groups
"""
# pylint: disable=too-few-public-methods
class TroveClassifier:
"""
Base class for trove classifiers
"""
def __init__(self, parent, path):
self.parent = parent
self.path = path
self.name = path[-1]
def __repr__(self):... |
def get_register_class(register):
return register.name.lower() + "_reg"
def get_register_inst(register):
return register.name
def get_field_inst(field):
return field.name
|
"""
Vk reader exe - https://github.com/Moonquit/vkdreader/releases/download/1.0/vkdreader.exe
This directory contains the files used for compiling to exe. You can compile it yourself using pyinstaller:
> cd vkdreader/app
> pip install -r requirements.txt
> pyinstaller --onefile --icon=icon.ico main.py
The compiled ex... |
a = int(input())
b = int(input())
buf = "no"
for i in range(9999):
if i % 2:
if b == i:
buf = "yes"
else:
if a == i:
buf = "yes"
if buf != "no":
break
print(buf)
|
class Solution:
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
data = []
flip = lambda s: s[::-1] if len(s) <= k else s[:k][::-1] + s[k:]
for c in range(0, len(s), 2 * k):
data.append(flip(s[c:c + 2 * k]))
... |
n = int(input())
output = 0
for i in range(n):
polyhedron = input()
polyhedron = polyhedron.lower()
if polyhedron == "tetrahedron":
output += 4
elif polyhedron == "cube":
output += 6
elif polyhedron == "octahedron":
output += 8
elif polyhedron == "dodecahedron"... |
##################################################################################################
# PURPOSE: Deriving XGBoost regression moodel from example data
# WARNING: Runnig this script reguires inclusion of the following external modules (libraries):
# os, datetime (dt), time, sys, pickle, pandas (... |
x_nocollinearity = predictors.drop(['dewtemp_F','wind_mph','wind_dir','windgust_dir','SOLIN_Wm2','prec_occur'],axis=1)
x_train_bal, y_train_bal, x_test_bal, y_test_bal = dataprep_pipeline(x_nocollinearity, y, verbose=False)
# Using the same Random Forest classifier as above, just changing the training data.
forest_no... |
# python3
seq = [int(i) for i in input().split()]
search_seq = [int(i) for i in input().split()]
n = seq[0]
seq = seq[1:]
def binary_search(seq, elt, r):
l = 0
while l<=r:
m = (l+r)//2
if elt > seq[m]:
l = m + 1
elif elt < seq[m]:
r = m - 1
else:
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 23 19:02:11 2021
@author:
"""
class GenericParams(object):
def __init__(self, filename=None):
self.filename = filename
#function to map timestamp and provide mapping between Ground Truth Data and Perception Data
def TimeStamp_Mapping(inputData_LG... |
MyNumb = 12346789
Answer = False
for i in str(MyNumb):
if i == '5':
Answer = True
break
if Answer == 1:print ('YES')
else:print('NO') |
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
lis = s.split()
if len(lis)==0:
return 0
else:
return (len(lis[-1]))
|
#!python
if __name__ == '__main__':
print("ASDF not defined")
print("bye")
|
# -*- coding: utf-8 -*-
PAGSEGURO_API_URL = 'https://ws.pagseguro.uol.com.br/v2/checkout'
PAGSEGURO_PAYMENT_URL = 'https://pagseguro.uol.com.br/v2/checkout/payment.html'
PAGSEGURO_NOTIFICATION_URL = 'https://ws.pagseguro.uol.com.br/v2/transactions/notifications/'
|
num = list(map(int, input('Enter N & K: ').split()))
arr = list(map(int, input('Enter numbers: ').split()))
sum1 = 0
for i in range(num[1]):
sum1 += arr[i]
print(sum1)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.