content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# -*- coding: utf-8 -*-
"""
1954. Minimum Garden Perimeter to Collect Enough Apples
https://leetcode.com/problems/minimum-garden-perimeter-to-collect-enough-apples/
Example 1:
Input: neededApples = 1
Output: 8
Explanation: A square plot of side length 1 does not contain any apples.
However, a square plot of side len... | """
1954. Minimum Garden Perimeter to Collect Enough Apples
https://leetcode.com/problems/minimum-garden-perimeter-to-collect-enough-apples/
Example 1:
Input: neededApples = 1
Output: 8
Explanation: A square plot of side length 1 does not contain any apples.
However, a square plot of side length 2 has 12 apples insid... |
donate_msg = """{name} is an open source project, created with the intention
of sharing a simple and easy-to-use application for the care of
information integrity, through the use of hash table files.
If you like {name}, feel free to make a donation if you think so.
Any kind of support will be immensely gratefu... | donate_msg = '{name} is an open source project, created with the intention\nof sharing a simple and easy-to-use application for the care of\ninformation integrity, through the use of hash table files.\n\nIf you like {name}, feel free to make a donation if you think so.\nAny kind of support will be immensely grateful.' |
# -*- coding: utf-8 -*-
# * ********************************************************************* *
# * Copyright (C) 2018 by xmz *
# * ********************************************************************* *
__author__ = "Marcin Zelek (marcin.zelek@gmail.com)"
__copyright__ ... | __author__ = 'Marcin Zelek (marcin.zelek@gmail.com)'
__copyright__ = 'Copyright (C) xmz. All Rights Reserved.'
class Jscsection:
"""
The JSC section data container.
"""
section_glue = '.'
global_section_name = '__GLOBAL__'
def __init__(self, name=GLOBAL_SECTION_NAME):
self.__section = ... |
# The below function calculates the BMI or Body Mass Index of a person
# Created by Agamdeep Singh / CodeWithAgam
# Youtube: CodeWithAgam
# Github: CodeWithAgam
# Instagram: @agamdeep_21, @coderagam001
# Twitter: @CoderAgam001
# Linkdin: Agamdeep Singh
def calculate_BMI():
# Get the inputs from the user
height... | def calculate_bmi():
height = float(input('Enter your height in M: '))
weight = float(input('Enter your weight in KG: '))
bmi = int(weight / height ** 2)
if BMI < 18.5:
print(f'Your BMI is {BMI}, you are underweight!')
elif BMI < 25:
print(f'Your BMI is {BMI}, you have a normal weigh... |
{
"includes": [
"common.gypi",
],
"targets": [
{
"target_name": "colony-lua",
"product_name": "colony-lua",
"type": "static_library",
"defines": [
'LUA_USELONGLONG',
],
"sources": [
'<(colony_lua_path)/src/lapi.c',
'<(colony_lua_path)/src/lauxl... | {'includes': ['common.gypi'], 'targets': [{'target_name': 'colony-lua', 'product_name': 'colony-lua', 'type': 'static_library', 'defines': ['LUA_USELONGLONG'], 'sources': ['<(colony_lua_path)/src/lapi.c', '<(colony_lua_path)/src/lauxlib.c', '<(colony_lua_path)/src/lbaselib.c', '<(colony_lua_path)/src/lcode.c', '<(colon... |
awnser = 5
print('Enter a number between 1 and 10')
for i in range(0, 4):
guess = int(input(f'You have {4-i} guesses left: '))
if guess == 5 or guess == 10:
print('You guessed correct!')
break
else:
print(f'The guess of {guess} was not correct')
if guess > awnser:
print('Your guess was too l... | awnser = 5
print('Enter a number between 1 and 10')
for i in range(0, 4):
guess = int(input(f'You have {4 - i} guesses left: '))
if guess == 5 or guess == 10:
print('You guessed correct!')
break
else:
print(f'The guess of {guess} was not correct')
if guess > awnser:
... |
"""
0606. Construct String from Binary Tree
You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.
The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don't affect the one-to-on... | """
0606. Construct String from Binary Tree
You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.
The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don't affect the one-to-on... |
class WrongInputDataType(Exception):
def __init__(self, message="Input data must be a pandas.Series."):
self.message = message
super().__init__(self.message)
class NotFittedError(Exception):
def __init__(self, message="Please call fit() before detect().", tip=""):
self.message = " ".jo... | class Wronginputdatatype(Exception):
def __init__(self, message='Input data must be a pandas.Series.'):
self.message = message
super().__init__(self.message)
class Notfittederror(Exception):
def __init__(self, message='Please call fit() before detect().', tip=''):
self.message = ' '.j... |
alpha = "abcdefghijklmnopqrstuvwxyz"
key = "xznlwebgjhqdyvtkfuompciasr"
message = input("enter the message : ")
cipher = ""
for i in message:
cipher+=key[alpha.index(i)]
print(cipher) | alpha = 'abcdefghijklmnopqrstuvwxyz'
key = 'xznlwebgjhqdyvtkfuompciasr'
message = input('enter the message : ')
cipher = ''
for i in message:
cipher += key[alpha.index(i)]
print(cipher) |
def keep(sequence, predicate):
pass
def discard(sequence, predicate):
pass
| def keep(sequence, predicate):
pass
def discard(sequence, predicate):
pass |
class Solution(object):
"""
A happy number is a number defined by the following process: Starting with any positive integer,
replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1
(where it will stay), or it loops endlessly in a cycle which does not ... | class Solution(object):
"""
A happy number is a number defined by the following process: Starting with any positive integer,
replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1
(where it will stay), or it loops endlessly in a cycle which does not ... |
# coding: utf-8
# create by tongshiwei on 2018/4/27
class Solution:
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
num_rec = {}
for n in nums:
if n not in num_rec:
num_rec[n] = 0
num_rec[n... | class Solution:
def subsets_with_dup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
num_rec = {}
for n in nums:
if n not in num_rec:
num_rec[n] = 0
num_rec[n] += 1
num_times = list(num_rec.items())
... |
n1=int(input('Digite a idade da primeira pessoa:'))
n2=int(input('Digite a idade da segunda pessoa:'))
n3=int(input('Digite a idade da terceira pessoa:'))
#Maior ou igual a 100
#menor que 100
soma = n1+ n2+ n3
if soma > 100 or soma == 100:
print('Maior ou igual a 100')
else:
print('Menor que 100')
| n1 = int(input('Digite a idade da primeira pessoa:'))
n2 = int(input('Digite a idade da segunda pessoa:'))
n3 = int(input('Digite a idade da terceira pessoa:'))
soma = n1 + n2 + n3
if soma > 100 or soma == 100:
print('Maior ou igual a 100')
else:
print('Menor que 100') |
class Solution:
"""
@param grid: a 2D array
@return: the maximum area of an island in the given 2D array
"""
def maxAreaOfIsland(self, grid):
# Write your code here
maxArea = 0
m = len(grid)
n = len(grid[0])
def dfs(r, c):
if grid[r][c] == 0:
... | class Solution:
"""
@param grid: a 2D array
@return: the maximum area of an island in the given 2D array
"""
def max_area_of_island(self, grid):
max_area = 0
m = len(grid)
n = len(grid[0])
def dfs(r, c):
if grid[r][c] == 0:
return 0
... |
print ("Angka Pertama : ")
a = int(input())
print ("Angka Kedua : ")
b = int (input())
print (hasil = a * b)
| print('Angka Pertama : ')
a = int(input())
print('Angka Kedua : ')
b = int(input())
print(hasil=a * b) |
# Stop words
STOP_WORDS = set(
"""
ke gareng ga selekanyo tlhwatlhwa yo mongwe se
sengwe fa go le jalo gongwe ba na mo tikologong
jaaka kwa morago nna gonne ka sa pele nako teng
tlase fela ntle magareng tsona feta bobedi kgabaganya
moo gape kgatlhanong botlhe tsotlhe bokana e esi
setseng mororo dinako golo ... | stop_words = set('\nke gareng ga selekanyo tlhwatlhwa yo mongwe se\nsengwe fa go le jalo gongwe ba na mo tikologong\njaaka kwa morago nna gonne ka sa pele nako teng\ntlase fela ntle magareng tsona feta bobedi kgabaganya\nmoo gape kgatlhanong botlhe tsotlhe bokana e esi\nsetseng mororo dinako golo kgolo nnye wena gago\n... |
class Solution:
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
ransomNote = list(ransomNote)
magazine = list(magazine)
r_len = len(ransomNote)
m_len = len(magazine)
if r_len... | class Solution:
def can_construct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
ransom_note = list(ransomNote)
magazine = list(magazine)
r_len = len(ransomNote)
m_len = len(magazine)
if r_l... |
'''
LC1413: Minimum Value to Get Positive Step by Step Sum
Given an array of integers nums, you start
with an initial positive value startValue.
In each iteration, you calculate the step by
step sum of startValue plus elements in nums (from left to right).
Return the minimum positive value of startValue
such that the s... | """
LC1413: Minimum Value to Get Positive Step by Step Sum
Given an array of integers nums, you start
with an initial positive value startValue.
In each iteration, you calculate the step by
step sum of startValue plus elements in nums (from left to right).
Return the minimum positive value of startValue
such that the s... |
def solve_part_one(puzzle: list) -> int:
turn = 1
numbers = []
while turn <= 2020:
if turn <= len(puzzle):
numbers.append(puzzle[turn - 1])
turn += 1
continue
# We finished the initial list. Look at the last number
last_num = numbers[-1]
if... | def solve_part_one(puzzle: list) -> int:
turn = 1
numbers = []
while turn <= 2020:
if turn <= len(puzzle):
numbers.append(puzzle[turn - 1])
turn += 1
continue
last_num = numbers[-1]
if last_num in numbers[:len(numbers) - 1]:
previous_tu... |
#
# PySNMP MIB module BNET-ATM-ATOM-AUG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BNET-ATM-ATOM-AUG-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:40:04 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_range_constraint, value_size_constraint, constraints_union) ... |
UP_KEY = 16777235
DOWN_KEY = 16777237
TAB_KEY = 16777217 | up_key = 16777235
down_key = 16777237
tab_key = 16777217 |
#author Kollen Gruizenga
#function to return all words in list L who start with letter "let"
def beginWith(L, let):
result = []
for x in L:
if (x[0] == let):
result += [x]
return result
| def begin_with(L, let):
result = []
for x in L:
if x[0] == let:
result += [x]
return result |
#!/usr/bin/env python3
"""
Check if a given number is a prime number
"""
def prime_checker(number):
if number <= 1:
return False
for i in range(2, number - 1):
if number % i == 0: # not reminder, is not a prime
return False
return True
n = int(input("Check this number: "))
r... | """
Check if a given number is a prime number
"""
def prime_checker(number):
if number <= 1:
return False
for i in range(2, number - 1):
if number % i == 0:
return False
return True
n = int(input('Check this number: '))
result = prime_checker(number=n)
print(result) |
CAMPAIGN_INCIDENT_CONTEXT = {
"EmailCampaign": {
"firstIncidentDate": "2021-11-21T14:00:07.425185+00:00",
"incidents": [
{
"emailfrom": "examplesupport@example2.com",
"emailfromdomain": "example.com",
"id": "1",
"name": "Ver... | campaign_incident_context = {'EmailCampaign': {'firstIncidentDate': '2021-11-21T14:00:07.425185+00:00', 'incidents': [{'emailfrom': 'examplesupport@example2.com', 'emailfromdomain': 'example.com', 'id': '1', 'name': 'Verify your example account 798', 'occurred': '2021-11-21T14:00:07.119800133Z', 'recipients': ['victim-... |
'''
Class to represent plant care.
'''
class Plant_Care:
'''
General representation of abstract plant care.
'''
def __init__(self,
times_monthly=2,
plant_type='Cacti',
soil_moisutre='Arid'):
self.times_monthly = times_monthly
self.plan... | """
Class to represent plant care.
"""
class Plant_Care:
"""
General representation of abstract plant care.
"""
def __init__(self, times_monthly=2, plant_type='Cacti', soil_moisutre='Arid'):
self.times_monthly = times_monthly
self.plant_type = plant_type
self.soil_moisture = so... |
# Defaults
ansi_colors = """
RESTORE=$(echo -en '\033[0m')
RED=$(echo -en '\033[00;31m')
GREEN=$(echo -en '\033[00;32m')
YELLOW=$(echo -en '\033[00;33m')
BLUE=$(echo -en '\033[00;34m')
MAGENTA=$(echo -en '\033[00;35m')
PURPLE=$(echo -en '\033[00;35m')
CYAN=$(echo -en '\033[00;36m')
LIGHTGRAY=$(echo -en '\033[00;37m')
"... | ansi_colors = "\nRESTORE=$(echo -en '\x1b[0m')\nRED=$(echo -en '\x1b[00;31m')\nGREEN=$(echo -en '\x1b[00;32m')\nYELLOW=$(echo -en '\x1b[00;33m')\nBLUE=$(echo -en '\x1b[00;34m')\nMAGENTA=$(echo -en '\x1b[00;35m')\nPURPLE=$(echo -en '\x1b[00;35m')\nCYAN=$(echo -en '\x1b[00;36m')\nLIGHTGRAY=$(echo -en '\x1b[00;37m')\n"
lo... |
#
# PySNMP MIB module NTWS-AP-CONFIG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NTWS-AP-CONFIG-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:25:33 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_union, constraints_intersection, value_range_constraint) ... |
class CarTablePage(Page):
add_car_form = AddCarForm()
car_table = CarTable()
def add_car(self, car: Car):
self.add_car_form.add_car(car)
def remove_car(self, car: Car):
self.car_table.remove_car(car)
@property
def cars(self) -> List[Car]:
return self.car_table.cars
| class Cartablepage(Page):
add_car_form = add_car_form()
car_table = car_table()
def add_car(self, car: Car):
self.add_car_form.add_car(car)
def remove_car(self, car: Car):
self.car_table.remove_car(car)
@property
def cars(self) -> List[Car]:
return self.car_table.cars |
r_0_0=[[0,1,2,3,4],[15,16,17,18,5],[14,23,34,19,6],[13,22,21,20,7],[12,11,10,9, 8]]
r_4_0=[[4,5,6,7,8],[ 3,18,19,20,9],[2,17,24,21,10],[1,16,23,22,11],[0,15,14,13,12]]
def index(s,pos):
def espelho_linhas(lst):
"""
Pega numa chave e inverte cada linha, mantendo a sua ordem na chave
"""
res=[]
for linha in ... | r_0_0 = [[0, 1, 2, 3, 4], [15, 16, 17, 18, 5], [14, 23, 34, 19, 6], [13, 22, 21, 20, 7], [12, 11, 10, 9, 8]]
r_4_0 = [[4, 5, 6, 7, 8], [3, 18, 19, 20, 9], [2, 17, 24, 21, 10], [1, 16, 23, 22, 11], [0, 15, 14, 13, 12]]
def index(s, pos):
def espelho_linhas(lst):
"""
Pega numa chave e inverte cada linha, ... |
#
# PySNMP MIB module UBNT-AirMAX-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/UBNT-AirMAX-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:28:21 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, constraints_intersection, value_range_constraint, value_size_constraint) ... |
# https://leetcode.com/explore/interview/card/top-interview-questions-easy/102/math/745/
# https://leetcode.com/problems/power-of-three/description/
# Power of Three
#
# Given an integer, write a function to determine if it is a power of three.
# ie, 45 % 3 is 0, but 45 is not power of 3
# so it is not simply "n % 3 ... | class Solution:
def is_power_of_three(self, n):
"""
:type n: int
:rtype: bool
"""
return self.check1_divide(n)
def check1_divide(self, n):
if n < 1:
return False
while n % 3 == 0:
n //= 3
return n == 1
def check4_int_... |
def handle_annotations(annotations):
new_global = {}
new_local = {}
if 'global' in annotations:
for key in annotations['global']:
key_new = key.replace('__EQUALS__', '=')
new_global[key_new] = annotations['global'][key]
if 'local' in annotations:
for key in anno... | def handle_annotations(annotations):
new_global = {}
new_local = {}
if 'global' in annotations:
for key in annotations['global']:
key_new = key.replace('__EQUALS__', '=')
new_global[key_new] = annotations['global'][key]
if 'local' in annotations:
for key in annota... |
# Fields
NAME = 'name'
NUMBER = 'number'
SET = 'set'
TYPE = 'type'
IS_INSTANT = 'is-instant'
MEDICINE = 'medicine'
PLUS_DIG = 'plus-dig'
PLUS_HUNT = 'plus-hunt'
PLUS_FIGHT = 'plus-fight'
ABILITY = 'ability'
TEXT = 'text'
# Set values
BASE = 'base'
HQ_EXP = 'hq'
RECON_EXP = 'recon'
# Type values
JUNKYARD = 'junkyard'
... | name = 'name'
number = 'number'
set = 'set'
type = 'type'
is_instant = 'is-instant'
medicine = 'medicine'
plus_dig = 'plus-dig'
plus_hunt = 'plus-hunt'
plus_fight = 'plus-fight'
ability = 'ability'
text = 'text'
base = 'base'
hq_exp = 'hq'
recon_exp = 'recon'
junkyard = 'junkyard'
contested_resource = 'contested-resour... |
class LocationFailureException(Exception):
pass
class BadLatitudeException(Exception):
pass
class BadLongitudeException(Exception):
pass
class BadAltitudeException(Exception):
pass
class BadNumberException(Exception):
pass
class GetPassesException(Exception):
pass
class AstronautFail... | class Locationfailureexception(Exception):
pass
class Badlatitudeexception(Exception):
pass
class Badlongitudeexception(Exception):
pass
class Badaltitudeexception(Exception):
pass
class Badnumberexception(Exception):
pass
class Getpassesexception(Exception):
pass
class Astronautfailureexc... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
def maxTree(nums):
... | class Solution:
def construct_maximum_binary_tree(self, nums: List[int]) -> TreeNode:
def max_tree(nums):
idx = nums.index(max(nums))
node = tree_node(nums[idx])
if len(nums[idx + 1:]) > 0:
node.right = max_tree(nums[idx + 1:])
if len(nums[:i... |
# -*- coding: utf-8 -*-
N = int(input())
A = list(map(int, input().split()))
pre = [0]*len(A)
pre[0] = A[0]
aft = [0]*len(A)
aft[-1] = A[-1]
for pos, it in enumerate(A[1:], 1):
pre[pos] = pre[pos-1]+it
for pos in range(len(A)-2, -1, -1):
aft[pos] = aft[pos+1]+A[pos]
ans = 0;
print(pre)
print(aft)
for pos in ra... | n = int(input())
a = list(map(int, input().split()))
pre = [0] * len(A)
pre[0] = A[0]
aft = [0] * len(A)
aft[-1] = A[-1]
for (pos, it) in enumerate(A[1:], 1):
pre[pos] = pre[pos - 1] + it
for pos in range(len(A) - 2, -1, -1):
aft[pos] = aft[pos + 1] + A[pos]
ans = 0
print(pre)
print(aft)
for pos in range(len(A)... |
def group(it, n):
it = iter(it)
block = []
for elem in it:
block.append(elem)
if len(block) == n:
yield block
block = []
if block:
yield block
| def group(it, n):
it = iter(it)
block = []
for elem in it:
block.append(elem)
if len(block) == n:
yield block
block = []
if block:
yield block |
"""
Copyright 2014 VoterChat
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, software
distr... | """
Copyright 2014 VoterChat
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, software
distr... |
class CriteriaBuilder():
'''Defines the CriteriaBuilder class'''
__and = None
__where = None
__or = None
__criteria = None
__cmd = None
__sql = None
@property
def AND( self ):
if self.__and is not None:
return self.__and
@property
def WHERE( self ):
... | class Criteriabuilder:
"""Defines the CriteriaBuilder class"""
__and = None
__where = None
__or = None
__criteria = None
__cmd = None
__sql = None
@property
def and(self):
if self.__and is not None:
return self.__and
@property
def where(self):
if... |
description = 'testing qmesydaq'
group = 'optional'
excludes = []
sysconfig = dict(
datasinks = ['LiveViewSink'],
)
tango_base = 'tango://localhost:10000/test/qmesydaq/'
devices = dict(
# RAWFileSaver = device('nicos.devices.datasinks.RawImageSink',
# description = 'Saves image data in RAW format',... | description = 'testing qmesydaq'
group = 'optional'
excludes = []
sysconfig = dict(datasinks=['LiveViewSink'])
tango_base = 'tango://localhost:10000/test/qmesydaq/'
devices = dict(LiveViewSink=device('nicos.devices.datasinks.LiveViewSink', description='Sends image data to LiveViewWidget'), qm_ctr0=device('nicos.devices... |
NUMBER = (1 << 15)
OPERATOR = (1 << 16)
FUNCTION = (1 << 17)
OTHER = (1 << 18)
OPERATOR_PRIORITY_1 = (1 << 10)
OPERATOR_PRIORITY_2 = (1 << 11) # Multiplication & Division
OPERATOR_PRIORITY_3 = (1 << 12) # Implicit Multiplication (0.5/2x, a/b(c))
OPERATOR_PRIORITY_4 = (1 << 13) # Root & Exponent
STUndefined = 0
ST... | number = 1 << 15
operator = 1 << 16
function = 1 << 17
other = 1 << 18
operator_priority_1 = 1 << 10
operator_priority_2 = 1 << 11
operator_priority_3 = 1 << 12
operator_priority_4 = 1 << 13
st_undefined = 0
st_number = NUMBER | 1
st_factor = NUMBER | 2
st_addition = OPERATOR | OPERATOR_PRIORITY_1 | 2
st_subtraction = ... |
# test for function notation
def helloworld(txt:dict(type=str,help='input text')):
print(txt)
if __name__ == '__main__' :
helloworld('hawken')
print(helloworld.__annotations__) | def helloworld(txt: dict(type=str, help='input text')):
print(txt)
if __name__ == '__main__':
helloworld('hawken')
print(helloworld.__annotations__) |
class Solution(object):
def shortestDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
d = {}
d[word1] = -1
d[word2] = -1
minDist = 0x7fffffff
for i,word in enumerat... | class Solution(object):
def shortest_distance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
d = {}
d[word1] = -1
d[word2] = -1
min_dist = 2147483647
for (i, word) in en... |
"""
Decorators provide a way to intercept a decorated function, method, or class.
Ultimately, the decorator accepts the function as its only argument
Decorators can then either return the original function, or another one
"""
# pattern 1: Decorator that returns the original function
def change_default(func):
"""Th... | """
Decorators provide a way to intercept a decorated function, method, or class.
Ultimately, the decorator accepts the function as its only argument
Decorators can then either return the original function, or another one
"""
def change_default(func):
"""This decorator changes the default value of a single-argumen... |
ADMINS = ()
MANAGERS = ADMINS
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_RENDERER_CLASSES': (
'rest_framewo... | admins = ()
managers = ADMINS
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}}
rest_framework = {'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',)}
allowed_hosts = []
time_zone = 'UTC... |
# Motor Controller class initialization constants
ZERO_POWER = 309 # Value to set thrusters to 0 power
NEG_MAX_POWER = 226 # Value to set thrusters to max negative power
POS_MAX_POWER = 391 # Value to set thrusters to max positive power
FREQUENCY = 49.5 # Frequency at which the i2c to pwm will be updated
POWER_THRE... | zero_power = 309
neg_max_power = 226
pos_max_power = 391
frequency = 49.5
power_thresh = 115
manipulator_pin = 15
obs_tool_pin = 14
reverse_polarity = [] |
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
for i in range(len(arr)):
for j in range(len(arr)):
if i != j and arr[i] == 2*arr[j]:
return True
return False
| class Solution:
def check_if_exist(self, arr: List[int]) -> bool:
for i in range(len(arr)):
for j in range(len(arr)):
if i != j and arr[i] == 2 * arr[j]:
return True
return False |
"""
Name : Even odd
Author : [Mayank Goyal) [https://github.com/mayankgoyal-13]
"""
num = int(input("Enter your number: "))
if num % 2 == 0:
print('The given number is even')
else:
print('The given number is odd')
| """
Name : Even odd
Author : [Mayank Goyal) [https://github.com/mayankgoyal-13]
"""
num = int(input('Enter your number: '))
if num % 2 == 0:
print('The given number is even')
else:
print('The given number is odd') |
def pattern(N):
if(N==2):
for i in range(N):
print(("#"*1+" ")*N)
if(N==3):
for i in range(N-1):
print(("#"*2+" ")*N)
if(N==4):
for i in range(N-2):
print(("#"*3+" ")*N)
pattern(2)
pattern(3)
pattern(4) | def pattern(N):
if N == 2:
for i in range(N):
print(('#' * 1 + ' ') * N)
if N == 3:
for i in range(N - 1):
print(('#' * 2 + ' ') * N)
if N == 4:
for i in range(N - 2):
print(('#' * 3 + ' ') * N)
pattern(2)
pattern(3)
pattern(4) |
def addDataSource(doc, name, url):
"""
Add a DataSource to the given InterMine items XML
Returns the item.
"""
dataSourceItem = doc.createItem('DataSource')
dataSourceItem.addAttribute('name', name)
dataSourceItem.addAttribute('url', url)
doc.addItem(dataSourceItem)
return dataSou... | def add_data_source(doc, name, url):
"""
Add a DataSource to the given InterMine items XML
Returns the item.
"""
data_source_item = doc.createItem('DataSource')
dataSourceItem.addAttribute('name', name)
dataSourceItem.addAttribute('url', url)
doc.addItem(dataSourceItem)
return dataS... |
# import numpy as np
# a = np.array([17,22,4,2,14,24,0,5,8,7,27,28,15,25,12,9,20,3,29,16,10,6,1,13,18,23,11,26,21,19])
# np.random.shuffle(a)
# print(a.tolist())
# np.random.shuffle(a)
# print(a.tolist())
# np.random.shuffle(a)
# print(a.tolist())
need_rerun = [
{'bodies': [300, 301, 302, 303, 304, 305, 306, 307,... | need_rerun = [{'bodies': [300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315], 'seed': 4, 'method': 'align'}, {'bodies': [300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315], 'seed': 6, 'method': 'random'}, {'bodies': [500, 501, 502, 503, 504, 505, 506, 507, 508, ... |
# Copyright (c) 2021 Jeff Irion and contributors
#
# This file is part of the adb-shell package.
"""ADB shell functionality.
"""
__version__ = '0.4.1'
| """ADB shell functionality.
"""
__version__ = '0.4.1' |
class _Food:
color = (107, 0, 0)
def __init__(self, pos_x, pos_y, live = 100):
self.pos_x = pos_x
self.pos_y = pos_y
self.live = live
def get_pos_x(self):
return self.pos_x
def get_pos_y(self):
return self.pos_y
def live_decrement(self):
self.live -=1 | class _Food:
color = (107, 0, 0)
def __init__(self, pos_x, pos_y, live=100):
self.pos_x = pos_x
self.pos_y = pos_y
self.live = live
def get_pos_x(self):
return self.pos_x
def get_pos_y(self):
return self.pos_y
def live_decrement(self):
self.live -=... |
""" Code to solve Lychrel number
So this is a very popular math question
The idea is to take any number as num and reverse it.
Now add the reversed number to num and repeat the process unless
a palindrome is obtained. The weird thing about this process is that
for nearly every number ends with ... | """ Code to solve Lychrel number
So this is a very popular math question
The idea is to take any number as num and reverse it.
Now add the reversed number to num and repeat the process unless
a palindrome is obtained. The weird thing about this process is that
for nearly every number ends with a pal... |
# -*- coding: utf-8 -*-
"""Test for autolag of adfuller, unitroot_adf
Created on Wed May 30 21:39:46 2012
Author: Josef Perktold
"""
# The only test from this file has been moved to test_unit_root (2018-05-04)
| """Test for autolag of adfuller, unitroot_adf
Created on Wed May 30 21:39:46 2012
Author: Josef Perktold
""" |
while True:
print('Enter you age: ')
age = input()
if age.isdecimal():
break
print('Please enter a number for age')
while True:
print('Select a new password (letters and numbers only):')
password = input()
if password.isalnum():
break
print('Passwords can only have letters and numbers') | while True:
print('Enter you age: ')
age = input()
if age.isdecimal():
break
print('Please enter a number for age')
while True:
print('Select a new password (letters and numbers only):')
password = input()
if password.isalnum():
break
print('Passwords can only have letter... |
# -*- coding: utf-8 -*-
class ApiException(Exception):
errors = []
def __init__(self, errors, code):
self.errors = errors
self.code = code
| class Apiexception(Exception):
errors = []
def __init__(self, errors, code):
self.errors = errors
self.code = code |
#
# PySNMP MIB module HP-ICF-DHCPv6-SNOOP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-DHCPv6-SNOOP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:21:15 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, value_range_constraint, constraints_union, single_value_constraint) ... |
#
# PySNMP MIB module ESI-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ESI-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:52:21 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:23:15)... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, single_value_constraint, value_size_constraint, constraints_union) ... |
# Copyright 2018 The go-python Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
doc="range"
a = range(255)
b = [e for e in a]
assert len(a) == len(b)
a = range(5, 100, 5)
b = [e for e in a]
assert len(a) == len(b)
a = range(100 ,0, 1)
... | doc = 'range'
a = range(255)
b = [e for e in a]
assert len(a) == len(b)
a = range(5, 100, 5)
b = [e for e in a]
assert len(a) == len(b)
a = range(100, 0, 1)
b = [e for e in a]
assert len(a) == len(b)
a = range(100, 0, -1)
b = [e for e in a]
assert len(a) == 100
assert len(b) == 100
doc = 'range_get_item'
a = range(3)
a... |
def selectionsort(arr):
i=0
while(i<len(arr)):
#find index of minimum number between index i and index n-1 where n=len(arr)
num,ind=arr[i],i
for j in range(i+1,len(arr)):
if(arr[j]<num):
num=arr[j]
ind=j
#swap number at ind with number at i
temp=arr[i]
arr[i]=arr[ind]
arr[ind]=temp
i+=1
re... | def selectionsort(arr):
i = 0
while i < len(arr):
(num, ind) = (arr[i], i)
for j in range(i + 1, len(arr)):
if arr[j] < num:
num = arr[j]
ind = j
temp = arr[i]
arr[i] = arr[ind]
arr[ind] = temp
i += 1
return arr
def... |
__title__ = 'road-surface-detection'
__version__ = '0.0.0'
__author__ = 'Esri Advanced Analytics Team'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2020 by Esri Advanced Analytics Team'
# add specific imports below if you want more control over what is visible
## from . import utils
| __title__ = 'road-surface-detection'
__version__ = '0.0.0'
__author__ = 'Esri Advanced Analytics Team'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2020 by Esri Advanced Analytics Team' |
ImgHeight = 32
data_roots = {
'iam_word': '/mydrive/MyDrive/khoa_luan/khoa_luan/data/'
}
data_paths = {
'iam_word': {'trnval': 'trnvalset_words%d.hdf5'%ImgHeight,
'test': 'testset_words%d.hdf5'%ImgHeight},
'iam_word_org': {'trnval': 'trnvalset_words%d_OrgSz.hdf5'%ImgHeight,
... | img_height = 32
data_roots = {'iam_word': '/mydrive/MyDrive/khoa_luan/khoa_luan/data/'}
data_paths = {'iam_word': {'trnval': 'trnvalset_words%d.hdf5' % ImgHeight, 'test': 'testset_words%d.hdf5' % ImgHeight}, 'iam_word_org': {'trnval': 'trnvalset_words%d_OrgSz.hdf5' % ImgHeight, 'test': 'testset_words%d_OrgSz.hdf5' % Im... |
# vim: set fileencoding=<utf-8> :
# Copyright 2018-2020 John Lees and Nick Croucher
'''PopPUNK (POPulation Partitioning Using Nucleotide Kmers)'''
__version__ = '2.2.1'
| """PopPUNK (POPulation Partitioning Using Nucleotide Kmers)"""
__version__ = '2.2.1' |
n=int(input())
a=list(map(int,input().split()))
a.sort()
l=list(set(a))
k=l[0]
i=0
c=0
while(i!=n and k<=max(l)):
if(k==l[i]):
k=k+1
i=i+1
c=c+1
else:
break
print(c)
| n = int(input())
a = list(map(int, input().split()))
a.sort()
l = list(set(a))
k = l[0]
i = 0
c = 0
while i != n and k <= max(l):
if k == l[i]:
k = k + 1
i = i + 1
c = c + 1
else:
break
print(c) |
#Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the #node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, #you should return NULL.
# Definition for a binary tree node.
# class TreeNode:
# def __init__... | class Solution:
def search_bst(self, root: TreeNode, val: int) -> TreeNode:
if not root:
return None
while root:
if root.val == val:
return root
elif val < root.val:
root = root.left
else:
root = root.ri... |
# Purpose: Grouping entities by DXF attributes or a key function.
# Created: 03.02.2017
# Copyright (C) 2017, Manfred Moitzi
# License: MIT License
def groupby(entities, dxfattrib='', key=None):
"""
Groups a sequence of DXF entities by an DXF attribute like 'layer', returns the result as dict. Just specify
... | def groupby(entities, dxfattrib='', key=None):
"""
Groups a sequence of DXF entities by an DXF attribute like 'layer', returns the result as dict. Just specify
argument `dxfattrib` OR a `key` function.
Args:
entities: sequence of DXF entities to group by a key
dxfattrib: grouping DXF at... |
def find_pivot_index(nums):
"""
Suppose a sorted array A is rotated at some pivot unknown to you
beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element. NOTE: The array will not contain duplicates.
"""
min_num = nums[0]
pivot_index = 0
left = 0
right =... | def find_pivot_index(nums):
"""
Suppose a sorted array A is rotated at some pivot unknown to you
beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element. NOTE: The array will not contain duplicates.
"""
min_num = nums[0]
pivot_index = 0
left = 0
right =... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 14 19:55:42 2017
@author: Zachary
"""
aList = [[1,'a',['cat'],2],[[[3]],'dog'],4,5]
def flatten(aList):
flattenedList = []
for i in range(len(aList)):
listOne = aList[i]
if type(listOne) == list:
for k in range... | """
Created on Tue Feb 14 19:55:42 2017
@author: Zachary
"""
a_list = [[1, 'a', ['cat'], 2], [[[3]], 'dog'], 4, 5]
def flatten(aList):
flattened_list = []
for i in range(len(aList)):
list_one = aList[i]
if type(listOne) == list:
for k in range(len(listOne)):
list_tw... |
class ContainerAlreadyResolved(Exception):
def __init__(self):
super().__init__("Container already resolved can't be resolved again")
class ForbiddenChangeOnResolvedContainer(Exception):
def __init__(self):
super().__init__("Container can't be modified once resolved")
class ServiceAlreadyDef... | class Containeralreadyresolved(Exception):
def __init__(self):
super().__init__("Container already resolved can't be resolved again")
class Forbiddenchangeonresolvedcontainer(Exception):
def __init__(self):
super().__init__("Container can't be modified once resolved")
class Servicealreadydef... |
'''
We are given a list schedule of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order.
Return the list of finite intervals representing common, positive-length free time for all employees, also in sorted order... | """
We are given a list schedule of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order.
Return the list of finite intervals representing common, positive-length free time for all employees, also in sorted order... |
# -*- coding: utf-8 -*-
#
# LICENCE MIT
#
# DESCRIPTION Callgraph helpers for ast nodes.
#
# AUTHOR Michal Bukovsky <michal.bukovsky@trilogic.cz>
#
class VariablesScope(object):
def __init__(self, ctx):
self.ctx, self.var_names = ctx, ctx.var_names.copy()
def __enter__(self):
re... | class Variablesscope(object):
def __init__(self, ctx):
(self.ctx, self.var_names) = (ctx, ctx.var_names.copy())
def __enter__(self):
return self
def __exit__(self, exp_type, exp_value, traceback):
for var_name in self.vars_in_scope():
self.ctx.scope.pop(var_name)
... |
dna_to_rna_map = {
"G" : "C",
"C" : "G",
"T" : "A",
"A" : "U"
}
def to_rna(dna_strand):
return "".join([dna_to_rna_map[nuc] for nuc in dna_strand]) | dna_to_rna_map = {'G': 'C', 'C': 'G', 'T': 'A', 'A': 'U'}
def to_rna(dna_strand):
return ''.join([dna_to_rna_map[nuc] for nuc in dna_strand]) |
# Design a hit counter which counts the number of hits received in the past 5 minutes.
#
# Each function accepts a timestamp parameter (in seconds granularity) and you may assume that calls are being made to the system in chronological order (ie, the timestamp is monotonically increasing). You may assume that the earli... | class Hitcounter(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.count = 0
self.queue = []
def hit(self, timestamp):
"""
Record a hit.
@param timestamp - The current timestamp (in seconds granularity).
:type... |
# Program untuk menampilkan belah ketupat
print('\n==========Belah Ketupat==========\n')
obj_1 = 1
for row_1 in range(6, 0, -1):
for col_1 in range(row_1):
print(' ', end='')
for print_obj_1 in range(obj_1):
print('#', end='')
obj_1+=2
if row_1 == 1:
obj_2 = 9
print('')... | print('\n==========Belah Ketupat==========\n')
obj_1 = 1
for row_1 in range(6, 0, -1):
for col_1 in range(row_1):
print(' ', end='')
for print_obj_1 in range(obj_1):
print('#', end='')
obj_1 += 2
if row_1 == 1:
obj_2 = 9
print('')
for row_2 in range(2, 6 + 1, 1):
... |
blocks = {
'CJK Unified Ideographs Extension A': (0x3400, 0x4DBF),
'CJK Unified Ideographs': (0x4E00, 0x9FFF),
'CJK Unified Ideographs Extension B': (0x20000, 0x2A6DF),
'CJK Unified Ideographs Extension C': (0x2A700, 0x2B73F),
'CJK Unified Ideographs Extension D': (0x2B740, 0x2B81F),
'CJK Unified Ideographs Exten... | blocks = {'CJK Unified Ideographs Extension A': (13312, 19903), 'CJK Unified Ideographs': (19968, 40959), 'CJK Unified Ideographs Extension B': (131072, 173791), 'CJK Unified Ideographs Extension C': (173824, 177983), 'CJK Unified Ideographs Extension D': (177984, 178207), 'CJK Unified Ideographs Extension E': (178208,... |
#app = faust.App('myapp', broker='kafka://localhost')
class QUANTAXIS_PUBSUBER():
def __init__(self, name, broker='rabbitmq://localhost'):
self.exchange = name
#@app.agent(value_type=Order)
def agent(value_type=order):
pass | class Quantaxis_Pubsuber:
def __init__(self, name, broker='rabbitmq://localhost'):
self.exchange = name
def agent(value_type=order):
pass |
class Util:
def __init__(self):
pass
@staticmethod
def compress_uri(uri, base_uri, prefix_map):
uri = uri.strip('<>')
if uri.startswith(base_uri):
return '<' + uri[len(base_uri):] + '>'
for prefix, prefix_uri in prefix_map.items():
if uri.startswith(p... | class Util:
def __init__(self):
pass
@staticmethod
def compress_uri(uri, base_uri, prefix_map):
uri = uri.strip('<>')
if uri.startswith(base_uri):
return '<' + uri[len(base_uri):] + '>'
for (prefix, prefix_uri) in prefix_map.items():
if uri.startswit... |
class Image(object):
"""Image.
:param src:
:type src: str
:param alt:
:type alt: str
"""
def __init__(self, data=None):
if data is None:
data = {}
self.src = data.get('src', None)
self.alt = data.get('alt', None)
| class Image(object):
"""Image.
:param src:
:type src: str
:param alt:
:type alt: str
"""
def __init__(self, data=None):
if data is None:
data = {}
self.src = data.get('src', None)
self.alt = data.get('alt', None) |
class ContactHelper:
def __init__(self, app):
self.app = app
def open_add_contact_page(self):
# open add creation new contact
wd = self.app.wd
wd.find_element_by_link_text("add new").click()
def fill_form(self, contact):
# fill contacts form
wd = self.app.w... | class Contacthelper:
def __init__(self, app):
self.app = app
def open_add_contact_page(self):
wd = self.app.wd
wd.find_element_by_link_text('add new').click()
def fill_form(self, contact):
wd = self.app.wd
self.open_add_contact_page()
wd.find_element_by_nam... |
MODEL_CONFIG = {
'unet':{
'simplenet':{
'in_channels':1,
'encoder_name':'simplenet',
'encoder_depth':5,
'encoder_channels':[32,64,128,256,512], #[1,2,4,8,16]
'encoder_weights':None,
'decoder_use_batchnorm':True,
'decoder_at... | model_config = {'unet': {'simplenet': {'in_channels': 1, 'encoder_name': 'simplenet', 'encoder_depth': 5, 'encoder_channels': [32, 64, 128, 256, 512], 'encoder_weights': None, 'decoder_use_batchnorm': True, 'decoder_attention_type': None, 'decoder_channels': [256, 128, 64, 32], 'upsampling': 1, 'classes': 2, 'aux_class... |
# Python - 3.6.0
stock = {
'football': 4,
'boardgame': 10,
'leggos': 1,
'doll': 5
}
test.assert_equals(fillable(stock, 'football', 3), True)
test.assert_equals(fillable(stock, 'leggos', 2), False)
test.assert_equals(fillable(stock, 'action figure', 1), False)
| stock = {'football': 4, 'boardgame': 10, 'leggos': 1, 'doll': 5}
test.assert_equals(fillable(stock, 'football', 3), True)
test.assert_equals(fillable(stock, 'leggos', 2), False)
test.assert_equals(fillable(stock, 'action figure', 1), False) |
# How to Find the Smallest value
largest_so_far = -1
print('Before', largest_so_far)
for the_num in [1, 99, 24, 25, 56, 4, 57, 89, 5, 94, 21] :
if the_num > largest_so_far :
largest_so_far = the_num
print(largest_so_far, the_num)
print('After', largest_so_far)
| largest_so_far = -1
print('Before', largest_so_far)
for the_num in [1, 99, 24, 25, 56, 4, 57, 89, 5, 94, 21]:
if the_num > largest_so_far:
largest_so_far = the_num
print(largest_so_far, the_num)
print('After', largest_so_far) |
"""Common utilities for dealing with paths."""
def filter_files(filetypes, files):
"""Filters a list of files based on a list of strings."""
filtered_files = []
for file_to_filter in files:
for filetype in filetypes:
filename = file_to_filter if type(file_to_filter) == "string" else file_to_filter.base... | """Common utilities for dealing with paths."""
def filter_files(filetypes, files):
"""Filters a list of files based on a list of strings."""
filtered_files = []
for file_to_filter in files:
for filetype in filetypes:
filename = file_to_filter if type(file_to_filter) == 'string' else fil... |
integers = [ 1, 6, 4, 3, 15, -2]
print("integers[0] = ", integers[0])
print("integers[1] = ", integers[1])
print("integers[2] = ", integers[2])
print("integers[3] = ", integers[3])
print("integers[4] = ", integers[4])
print("integers[5] = ", integers[5])
| integers = [1, 6, 4, 3, 15, -2]
print('integers[0] = ', integers[0])
print('integers[1] = ', integers[1])
print('integers[2] = ', integers[2])
print('integers[3] = ', integers[3])
print('integers[4] = ', integers[4])
print('integers[5] = ', integers[5]) |
#!/usr/bin/env python3
"""Find the element that appears once in sorted array.
Given a sorted array A, size N, of integers; every element appears twice except for one. Find that element
in linear time complexity and without using extra memory.
Source:
https://practice.geeksforgeeks.org/problems/find-the-element-that... | """Find the element that appears once in sorted array.
Given a sorted array A, size N, of integers; every element appears twice except for one. Find that element
in linear time complexity and without using extra memory.
Source:
https://practice.geeksforgeeks.org/problems/find-the-element-that-appears-once-in-sorted-... |
# # ###
# #
# letter = input ("Please enter a letter:\n")
# if (letter == 'i'):
# print ("am lettera vowela")
# elif (letter== 'a'):
# print("am lettera vowela")
# if (letter == 'u'):
# print ("am lettera vowela")
# elif (letter== 'e'):
# print("am lettera vowela")
# if (letter == 'o'):
# print('am ... | def check_vowels():
input_str = input('Enter string: ')
str_without_space = input_str.replace(' ', '')
if len([char for char in str_without_space if char in ['a', 'e', 'i', 'o', 'u']]) == len(input_str):
print('input contains all the vowels')
else:
print('string does not have all the vow... |
n = input()
l = list(map(int,raw_input().split()))
m = 0
mi = n-1
for i in range(n):
if l[i]> l[m]:
m=i
if l[i]<=l[mi]:
mi = i
if mi>m:
print (n+m-mi-1)
else:
print (n+m-mi-2)
| n = input()
l = list(map(int, raw_input().split()))
m = 0
mi = n - 1
for i in range(n):
if l[i] > l[m]:
m = i
if l[i] <= l[mi]:
mi = i
if mi > m:
print(n + m - mi - 1)
else:
print(n + m - mi - 2) |
class Solution(object):
def processQueries(self, queries, m):
"""
:type queries: List[int]
:type m: int
:rtype: List[int]
"""
ans=[]
P=range(1, m+1)
for i in range(len(queries)):
toPop=P.index(queries[i])
ans.append(toP... | class Solution(object):
def process_queries(self, queries, m):
"""
:type queries: List[int]
:type m: int
:rtype: List[int]
"""
ans = []
p = range(1, m + 1)
for i in range(len(queries)):
to_pop = P.index(queries[i])
ans.append(t... |
'''Bet.py
'''
class Bets:
def __init__(self):
self.win = 0
self.info = {"dealer":self.dealer, "player":self.player}
def dealer(self, dealer):
self.dealer = dealer
def player(self, player):
self.player = player
def win(self):
self.win = self.od... | """Bet.py
"""
class Bets:
def __init__(self):
self.win = 0
self.info = {'dealer': self.dealer, 'player': self.player}
def dealer(self, dealer):
self.dealer = dealer
def player(self, player):
self.player = player
def win(self):
self.win = self.odds * self.bet... |
#!/usr/bin/python
with open('INCAR', 'r') as file:
lines=file.readlines()
for n,i in enumerate(lines):
if 'MAGMOM' in i:
# print(i)
items=i.split()
index=items.index('=')
moments=items[index+1:]
# print(moments)
magmom=''
size=4
for i in ra... | with open('INCAR', 'r') as file:
lines = file.readlines()
for (n, i) in enumerate(lines):
if 'MAGMOM' in i:
items = i.split()
index = items.index('=')
moments = items[index + 1:]
magmom = ''
size = 4
for i in range(len(moments) // 3):
k = ' '.join((k for k in mome... |
class text:
def __init__(self,text,*,thin=False,cancel=False,underline=False,bold=False,Italic=False,hide=False,Bg="black",Txt="white"):
self.__color={
"black":30,
"red":31,
"green":32,
"yellow":33,
"blue":34,
"mazenta":35,
... | class Text:
def __init__(self, text, *, thin=False, cancel=False, underline=False, bold=False, Italic=False, hide=False, Bg='black', Txt='white'):
self.__color = {'black': 30, 'red': 31, 'green': 32, 'yellow': 33, 'blue': 34, 'mazenta': 35, 'cian': 36, 'white': 37}
self.underline = ''
if un... |
# 23. Merge k Sorted Lists
# Runtime: 148 ms, faster than 33.74% of Python3 online submissions for Merge k Sorted Lists.
# Memory Usage: 17.8 MB, less than 82.01% of Python3 online submissions for Merge k Sorted Lists.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None)... | class Solution:
def merge_k_lists(self, lists: list[ListNode]) -> ListNode:
def merge_two_lists(list1: ListNode, list2: ListNode) -> ListNode:
head = list_node()
curr = head
while list1 and list2:
if list1.val < list2.val:
curr.next =... |
configuration = None
def init():
global configuration
configuration = None
| configuration = None
def init():
global configuration
configuration = None |
class FileSourceDepleted(Exception):
"""Exception raised when attempting to read from a depleted source file
Attributes:
filepath(str): path to depleted file
message(str): error message
"""
def __init__(self, filepath: str, message: str = "File source is depleted"):
"""Construc... | class Filesourcedepleted(Exception):
"""Exception raised when attempting to read from a depleted source file
Attributes:
filepath(str): path to depleted file
message(str): error message
"""
def __init__(self, filepath: str, message: str='File source is depleted'):
"""Construct ... |
class ArpProperties(object):
def __init__(self, bpm, base_note, pitch_value):
self.bpm = bpm
self.base_note = base_note
self.pitch = pitch_value
| class Arpproperties(object):
def __init__(self, bpm, base_note, pitch_value):
self.bpm = bpm
self.base_note = base_note
self.pitch = pitch_value |
# Day26 of 100 Days Of Code in Python
# get common numbers from two files using list comprehension
with open("file1.txt") as file1:
file1_data = file1.readlines()
with open("file2.txt") as file2:
file2_data = file2.readlines()
result = [int(item) for item in file1_data if item in file2_data]
print(result) | with open('file1.txt') as file1:
file1_data = file1.readlines()
with open('file2.txt') as file2:
file2_data = file2.readlines()
result = [int(item) for item in file1_data if item in file2_data]
print(result) |
pricelist = []
price = ""
while price != "kolar":
print(""" \n\nThe following things are
what you can do whith this program.
0 = Exit
1 = Show pricelist
2 = Add price
3 = Delete pricelist
4 = Sort pricelist """)
choice = input(" \n Choice : ")
if choice == "0":
pr... | pricelist = []
price = ''
while price != 'kolar':
print(' \n\nThe following things are \nwhat you can do whith this program.\n \t\n \t 0 = Exit\n \t 1 = Show pricelist\n \t 2 = Add price\n \t 3 = Delete pricelist\n \t 4 = Sort pricelist ')
choice = input(' \n Choice : ')
if choice == '... |
#!/usr/bin/python3
# Problem : https://code.google.com/codejam/contest/351101/dashboard#s=p0
__author__ = 'Varun Barad'
def main():
no_of_test_cases = int(input())
for i in range(no_of_test_cases):
credit = int(input())
no_of_items = int(input())
items = input().split(' ')
for... | __author__ = 'Varun Barad'
def main():
no_of_test_cases = int(input())
for i in range(no_of_test_cases):
credit = int(input())
no_of_items = int(input())
items = input().split(' ')
for j in range(no_of_items):
items[j] = int(items[j])
for j in range(no_of_ite... |
def dibujo (base,altura):
dibujo=print("x"*base)
for fila in range (altura):
print("x"+" "*(base-2)+"x")
dibujo=print("x"*base)
dibujo(7,5)
| def dibujo(base, altura):
dibujo = print('x' * base)
for fila in range(altura):
print('x' + ' ' * (base - 2) + 'x')
dibujo = print('x' * base)
dibujo(7, 5) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.