content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Outputs string representation of a unicode hex representation
def uc(hex):
return chr(int(hex))
'''CONSONANTS. Format: Place_Manner_Voicing;
Place:
L=labial, LD=labiodental, D=dental, A=alveolar, R=retroflex,
PA=postalveolar, P=palatal, V=velar, U=uvular, PH=pharyngeal, G=glottal;
Mann... | def uc(hex):
return chr(int(hex))
'CONSONANTS. Format: Place_Manner_Voicing;\n\n Place:\n L=labial, LD=labiodental, D=dental, A=alveolar, R=retroflex,\n PA=postalveolar, P=palatal, V=velar, U=uvular, PH=pharyngeal, G=glottal;\n\n Manner:\n P=plosive, N=nasal, TR=trill, TF=tap/flap, F=fric... |
# 8.2) find path to robot in a c*r grid, robot can only move right and down.
def find_path(c, r, off_limits):
path = []
move_robot(0, 0, c, r, off_limits, path)
return path
def move_robot(x, y, c, r, off_limits, path):
if x == (c - 1) and y == (r - 1):
return
elif [x + 1, y] not in off_li... | def find_path(c, r, off_limits):
path = []
move_robot(0, 0, c, r, off_limits, path)
return path
def move_robot(x, y, c, r, off_limits, path):
if x == c - 1 and y == r - 1:
return
elif [x + 1, y] not in off_limits and x + 1 < c:
path.append([x + 1, y])
move_robot(x + 1, y, c,... |
test_cases = int(input().strip())
for t in range(1, test_cases + 1):
s = input().strip()
stack = []
bracket = {'}': '{', ')': '('}
result = 1
for letter in s:
if letter == '{' or letter == '(':
stack.append(letter)
elif letter == '}' or letter == ')':
if not ... | test_cases = int(input().strip())
for t in range(1, test_cases + 1):
s = input().strip()
stack = []
bracket = {'}': '{', ')': '('}
result = 1
for letter in s:
if letter == '{' or letter == '(':
stack.append(letter)
elif letter == '}' or letter == ')':
if not s... |
# To Find an algorithm for giving selected attributes in a formal concept analysis acc to given conditions
a,arr= [],[]
start,end = 3,5
with open('Naive Algo/Input/test2.txt') as file:
for line in file:
line = line.strip()
for c in line:
if c != ' ':
# print(int(c))
... | (a, arr) = ([], [])
(start, end) = (3, 5)
with open('Naive Algo/Input/test2.txt') as file:
for line in file:
line = line.strip()
for c in line:
if c != ' ':
a.append(int(c))
arr.append(a)
a = []
s = set()
for st in range(start, end + 1):
for i in range... |
def palin(n,m):
if n<l//2:
if arr[n]==arr[m]:
return palin(n+1,m-1)
else:
return False
else:
return True
try:
arr= []
print(" Enter the array inputs and type 'stop' when you are done\n" )
while True:
arr.append(int(input()))
except:# if th... | def palin(n, m):
if n < l // 2:
if arr[n] == arr[m]:
return palin(n + 1, m - 1)
else:
return False
else:
return True
try:
arr = []
print(" Enter the array inputs and type 'stop' when you are done\n")
while True:
arr.append(int(input()))
except:... |
__version__ = "v0.6.1-1"
__author__ = "Kanelis Elias"
__email__ = "hkanelhs@yahoo.gr"
__license__ = "MIT"
| __version__ = 'v0.6.1-1'
__author__ = 'Kanelis Elias'
__email__ = 'hkanelhs@yahoo.gr'
__license__ = 'MIT' |
## https://leetcode.com/problems/count-and-say/
## this problem seems hard at first, but that's mostly
## because it's incredibly poorly described. went to
## wikipedia and it makes sense. for ease, I went ahead
## and hard-coded in the first 5; after that, we generate
## from the previous one.
## generating the ... | class Solution:
def generate_next(self, seq: str) -> str:
char = seq[0]
count = 1
out = ''
for c in seq[1:]:
if c == char:
count = count + 1
else:
out = out + str(count) + char
char = c
count = 1... |
soma = 0
for n in range(1, 500, 2):
if n % 3 == 0:
soma = soma + n
print(soma)
| soma = 0
for n in range(1, 500, 2):
if n % 3 == 0:
soma = soma + n
print(soma) |
# Times Tables
# Ask the user to input the number they would like the times tables for
tTable = int(input("What number would you like to see the times table for? "))
# Loop through 12 times
for number in range(12):
print("{0} times {1} equals {2}" .format(number+1, tTable, (number+1) * tTable))
input()
| t_table = int(input('What number would you like to see the times table for? '))
for number in range(12):
print('{0} times {1} equals {2}'.format(number + 1, tTable, (number + 1) * tTable))
input() |
expected_output = {
"GigabitEthernet3/8/0/38": {
"auto_negotiate": True,
"counters": {
"normal": {
"in_broadcast_pkts": 1093,
"in_mac_pause_frames": 0,
"in_multicast_pkts": 18864,
"in_octets": 0,
"in_pkts": 7... | expected_output = {'GigabitEthernet3/8/0/38': {'auto_negotiate': True, 'counters': {'normal': {'in_broadcast_pkts': 1093, 'in_mac_pause_frames': 0, 'in_multicast_pkts': 18864, 'in_octets': 0, 'in_pkts': 7446905, 'in_unicast_pkts': 7426948, 'out_broadcast_pkts': 373635, 'out_mac_pause_frames': 0, 'out_multicast_pkts': 3... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
__all__ = ['SE_Block',
]
'''see: Squeeze-and-Excitation Networks'''
def SE_Block(sym, data, num_out, name):
if type(num_out) ... | __all__ = ['SE_Block']
'see: Squeeze-and-Excitation Networks'
def se__block(sym, data, num_out, name):
if type(num_out) is tuple:
num_mid = (int(sum(num_out) / 16), 0)
else:
num_mid = int(num_out / 16)
out = sym.Pooling(data=data, pool_type='avg', kernel=(1, 1), global_pool=True, stride=(1,... |
__title__ = "access-client"
__version__ = "0.0.1"
__summary__ = "Client for accessai solutions"
__uri__ = "http://accessai.co"
__author__ = "ConvexHull Technology"
__email__ = "support@accessai.co"
__license__ = "Apache 2.0"
__release__ = True
| __title__ = 'access-client'
__version__ = '0.0.1'
__summary__ = 'Client for accessai solutions'
__uri__ = 'http://accessai.co'
__author__ = 'ConvexHull Technology'
__email__ = 'support@accessai.co'
__license__ = 'Apache 2.0'
__release__ = True |
'''
Write code to remove duplicates from an unsorted linked list.
FOLLOW UP
How would you solve this problem if a temporary buffer is not allowed?
'''
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next_node = next_node
def get_data(self):
ret... | """
Write code to remove duplicates from an unsorted linked list.
FOLLOW UP
How would you solve this problem if a temporary buffer is not allowed?
"""
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next_node = next_node
def get_data(self):
ret... |
# @lc app=leetcode id=2139 lang=python3
#
# [2139] Minimum Moves to Reach Target Score
#
# https://leetcode.com/problems/minimum-moves-to-reach-target-score/
# @lc code=start
class Solution:
def minMoves(self, target: int, maxDoubles: int) -> int:
steps = 0
while maxDoubles > 0 and... | class Solution:
def min_moves(self, target: int, maxDoubles: int) -> int:
steps = 0
while maxDoubles > 0 and target > 1:
if target % 2 == 0:
target /= 2
steps = steps + 1
max_doubles -= 1
else:
target -= 1
... |
# Truncatable primes
def prime_test_list(numbers):
return all(prime_test(elem) for elem in numbers)
def prime_test(num):
try:
if num == 2:
return True
if num == 0 or num == 1 or num % 2 == 0:
return False
for i in range(3, int(num**(1/2))+1, 2):... | def prime_test_list(numbers):
return all((prime_test(elem) for elem in numbers))
def prime_test(num):
try:
if num == 2:
return True
if num == 0 or num == 1 or num % 2 == 0:
return False
for i in range(3, int(num ** (1 / 2)) + 1, 2):
if num % i == 0:
... |
class RunnerMixin(object):
def add_artifacts(self, artifacts):
url = self._url('/runner/artifacts')
data = [{'filename': d} for d in artifacts]
return self._result(self.post(url, json={
'artifacts': data
}))
def add_logs(self, logs):
url = self._url('/runner... | class Runnermixin(object):
def add_artifacts(self, artifacts):
url = self._url('/runner/artifacts')
data = [{'filename': d} for d in artifacts]
return self._result(self.post(url, json={'artifacts': data}))
def add_logs(self, logs):
url = self._url('/runner/log')
return ... |
def load(h):
return ({'abbr': 'a', 'code': 1, 'title': '70 332.5 40 10'},
{'abbr': 'b', 'code': 2, 'title': '72.5 0 50 45'},
{'abbr': 'c', 'code': 3, 'title': '57.5 345 32.5 17.5'},
{'abbr': 'd', 'code': 4, 'title': '57.5 2.5 32.5 42.5'},
{'abbr': 'e', 'code': 5, 'tit... | def load(h):
return ({'abbr': 'a', 'code': 1, 'title': '70 332.5 40 10'}, {'abbr': 'b', 'code': 2, 'title': '72.5 0 50 45'}, {'abbr': 'c', 'code': 3, 'title': '57.5 345 32.5 17.5'}, {'abbr': 'd', 'code': 4, 'title': '57.5 2.5 32.5 42.5'}, {'abbr': 'e', 'code': 5, 'title': '75 340 30 45'}, {'abbr': 'f', 'code': 6, '... |
description = 'Devices for the first detector assembly'
pvpref = 'SQ:ZEBRA:mcu3:'
excludes = ['wagen2']
devices = dict(
nu = device('nicos_ess.devices.epics.motor.EpicsMotor',
description = 'Detector tilt',
motorpv = pvpref + 'A4T',
errormsgpv = pvpref + 'A4T-MsgTxt',
precision = ... | description = 'Devices for the first detector assembly'
pvpref = 'SQ:ZEBRA:mcu3:'
excludes = ['wagen2']
devices = dict(nu=device('nicos_ess.devices.epics.motor.EpicsMotor', description='Detector tilt', motorpv=pvpref + 'A4T', errormsgpv=pvpref + 'A4T-MsgTxt', precision=0.01), detdist=device('nicos_ess.devices.epics.mot... |
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
| class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
x = person('John', 'Doe')
x.printname() |
name = "Maedeh Ashouri"
for i in name:
print(i) | name = 'Maedeh Ashouri'
for i in name:
print(i) |
# Copyright (c) 2017-2021 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
__all__ = ["ConfigError", "ConfigWarning"]
class ConfigError(ValueError):
pass
class ConfigWarning(Warning):
pass
| __all__ = ['ConfigError', 'ConfigWarning']
class Configerror(ValueError):
pass
class Configwarning(Warning):
pass |
# coding: utf-8
# In[3]:
class RuleClass:
attributes = []
attributes_value = []
attributes_cover = []
decision_cover =[]
false_cover =[]
Decision = ''
def __cmp__(self, other):
if self.strength > other.strength:
return 1
elif self.strength < other.strength:
... | class Ruleclass:
attributes = []
attributes_value = []
attributes_cover = []
decision_cover = []
false_cover = []
decision = ''
def __cmp__(self, other):
if self.strength > other.strength:
return 1
elif self.strength < other.strength:
return -1
... |
def convert_lambda_to_def(string):
args=string[string.index("lambda ")+7:string.index(":")]
name=string[:string.index(" ")]
cal=string[string.index(":")+2:]
return f"def {name}({args}):\n return {cal}" | def convert_lambda_to_def(string):
args = string[string.index('lambda ') + 7:string.index(':')]
name = string[:string.index(' ')]
cal = string[string.index(':') + 2:]
return f'def {name}({args}):\n return {cal}' |
# -*- coding: utf-8 -*-
class SigfoxBaseException(BaseException):
pass
class SigfoxConnectionError(SigfoxBaseException):
pass
class SigfoxBadStatusError(SigfoxBaseException):
pass
class SigfoxResponseError(SigfoxBaseException):
pass
class SigfoxTooManyRequestsError(SigfoxBaseException):
pass... | class Sigfoxbaseexception(BaseException):
pass
class Sigfoxconnectionerror(SigfoxBaseException):
pass
class Sigfoxbadstatuserror(SigfoxBaseException):
pass
class Sigfoxresponseerror(SigfoxBaseException):
pass
class Sigfoxtoomanyrequestserror(SigfoxBaseException):
pass |
#To find factorial of number
num = int(input('N='))
factorial = 1
if num<0:
print('Number is not accepted')
elif num==0:
print(1)
else:
for i in range(1,num+1):
factorial = factorial * i
print(factorial)
| num = int(input('N='))
factorial = 1
if num < 0:
print('Number is not accepted')
elif num == 0:
print(1)
else:
for i in range(1, num + 1):
factorial = factorial * i
print(factorial) |
income = float(input())
gross_pay = income
taxes_owed = income * .12
net_pay = gross_pay - taxes_owed
print(gross_pay)
print(taxes_owed)
print(net_pay) | income = float(input())
gross_pay = income
taxes_owed = income * 0.12
net_pay = gross_pay - taxes_owed
print(gross_pay)
print(taxes_owed)
print(net_pay) |
'''Plotting utility functions'''
def remove_top_right_borders(ax):
'''Remove top and right borders from Matplotlib axis'''
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
| """Plotting utility functions"""
def remove_top_right_borders(ax):
"""Remove top and right borders from Matplotlib axis"""
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left') |
first_wire = ['R8', 'U5', 'L5', 'D3']
second_wire = ['U7', 'R6', 'D4', 'L4']
def wire_path(wire):
path = {}
x = 0
y = 0
count = 0
dirs = {"R": 1,
"L": -1,
"U": 1,
"D": -1}
for i in wire:
dir = i[0]
mov = int(i[1:])
for _ in range(mov... | first_wire = ['R8', 'U5', 'L5', 'D3']
second_wire = ['U7', 'R6', 'D4', 'L4']
def wire_path(wire):
path = {}
x = 0
y = 0
count = 0
dirs = {'R': 1, 'L': -1, 'U': 1, 'D': -1}
for i in wire:
dir = i[0]
mov = int(i[1:])
for _ in range(mov):
count += 1
... |
class Solution:
def calculate(self, s: str) -> int:
stack = [1]
sign = 1
res = 0
i = 0
while i < len(s):
if s[i].isdigit():
val = 0
while i < len(s) and s[i].isdigit():
val = val * 10 + int(s[i])
... | class Solution:
def calculate(self, s: str) -> int:
stack = [1]
sign = 1
res = 0
i = 0
while i < len(s):
if s[i].isdigit():
val = 0
while i < len(s) and s[i].isdigit():
val = val * 10 + int(s[i])
... |
class Calculator:
def __init__(self, ss, am, fsp, sc, isp, bc, cgtr):
self.ss = ss
self.am = int(am)
self.fsp = float(fsp)
self.sc = float(sc)
self.isp = float(isp)
self.bc = float(bc)
self.cgtr = float(cgtr)
def get_pc(self):
pc = self.am * self.... | class Calculator:
def __init__(self, ss, am, fsp, sc, isp, bc, cgtr):
self.ss = ss
self.am = int(am)
self.fsp = float(fsp)
self.sc = float(sc)
self.isp = float(isp)
self.bc = float(bc)
self.cgtr = float(cgtr)
def get_pc(self):
pc = self.am * self... |
'''
https://leetcode.com/problems/maximum-length-of-pair-chain/solution/
You are given n pairs of numbers. In every pair, the first number is always smaller than the second number.
Now, we define a pair (c, d) can follow another pair (a, b) if and only if b < c. Chain of pairs can be formed in this fashion.
Given a ... | """
https://leetcode.com/problems/maximum-length-of-pair-chain/solution/
You are given n pairs of numbers. In every pair, the first number is always smaller than the second number.
Now, we define a pair (c, d) can follow another pair (a, b) if and only if b < c. Chain of pairs can be formed in this fashion.
Given a ... |
lilly_dict = {"name": "Lilly",
"age": 18,
"pets": False,
"hair_color": 'Black'}
class Person(object):
def __init__(self, name, age, pets, hair_color):
self.name = name
self.age = age
self.pets = pets
self.hair_color = hair_color
self.hungry = True
... | lilly_dict = {'name': 'Lilly', 'age': 18, 'pets': False, 'hair_color': 'Black'}
class Person(object):
def __init__(self, name, age, pets, hair_color):
self.name = name
self.age = age
self.pets = pets
self.hair_color = hair_color
self.hungry = True
def eat(self, food):
... |
startMsg = 'counting...'
endMsg = 'launched !'
count = 10
print (startMsg)
while count >= 0 :
print (count)
count -= 1
print (endMsg) | start_msg = 'counting...'
end_msg = 'launched !'
count = 10
print(startMsg)
while count >= 0:
print(count)
count -= 1
print(endMsg) |
def multiple_letter_count(string):
return {letter: string.count(letter) for letter in string}
print(multiple_letter_count('awesome'))
| def multiple_letter_count(string):
return {letter: string.count(letter) for letter in string}
print(multiple_letter_count('awesome')) |
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
print("The animal at 1. ", animals[1])
print("The third (3rd) animal. ", animals[3-1])#This is the n - 1 trick
print("The first (1st) animal. ", animals[0])
print("The animal at 3. ", animals[3])
print("The fifth (5th) animal. ", animals[4])
print... | animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
print('The animal at 1. ', animals[1])
print('The third (3rd) animal. ', animals[3 - 1])
print('The first (1st) animal. ', animals[0])
print('The animal at 3. ', animals[3])
print('The fifth (5th) animal. ', animals[4])
print('The animal at 2. ', ... |
__author__ = "Douglas Lassance"
__copyright__ = "2020, Douglas Lassance"
__email__ = "douglassance@gmail.com"
__license__ = "MIT"
__version__ = "0.1.0.dev5"
| __author__ = 'Douglas Lassance'
__copyright__ = '2020, Douglas Lassance'
__email__ = 'douglassance@gmail.com'
__license__ = 'MIT'
__version__ = '0.1.0.dev5' |
'''
Unit Test Cases for JSON2HTML
Description - python wrapper for converting JSON to HTML Table format
(c) 2013 Varun Malhotra. MIT License
'''
__author__ = 'Varun Malhotra'
__version__ = '1.1.1'
__license__ = 'MIT'
| """
Unit Test Cases for JSON2HTML
Description - python wrapper for converting JSON to HTML Table format
(c) 2013 Varun Malhotra. MIT License
"""
__author__ = 'Varun Malhotra'
__version__ = '1.1.1'
__license__ = 'MIT' |
# bubble_sort
# Bubble_sort uses the technique of comparing and swapping
def bubble_sort(lst):
for passnum in range(len(lst) - 1, 0, -1):
for i in range(passnum):
if lst[i] > lst[i + 1]:
temp = lst[i]
lst[i] = lst[i + 1]
lst[i + 1] = temp
lst = ... | def bubble_sort(lst):
for passnum in range(len(lst) - 1, 0, -1):
for i in range(passnum):
if lst[i] > lst[i + 1]:
temp = lst[i]
lst[i] = lst[i + 1]
lst[i + 1] = temp
lst = [54, 26, 93, 17, 77, 31, 44, 55, 20]
bubble_sort(lst)
print('sorted %s' % ls... |
def tip(total, percentage):
tip = (total * percentage) / 100
return tip
print(tip(24, 13))
| def tip(total, percentage):
tip = total * percentage / 100
return tip
print(tip(24, 13)) |
class Solution:
def validPalindrome(self, s: str) -> bool:
return self.isValidPalindrome(s, False)
def isValidPalindrome(self, s: str, did_delete: bool) -> bool:
curr_left = 0
curr_right = len(s) - 1
while curr_left < curr_right:
# If left and right char... | class Solution:
def valid_palindrome(self, s: str) -> bool:
return self.isValidPalindrome(s, False)
def is_valid_palindrome(self, s: str, did_delete: bool) -> bool:
curr_left = 0
curr_right = len(s) - 1
while curr_left < curr_right:
if s[curr_left] == s[curr_right]:... |
# -*- coding: utf-8 -*-
SPELLINGS_MAP={
"accessorise":"accessorize",
"accessorised":"accessorized",
"accessorises":"accessorizes",
"accessorising":"accessorizing",
"acclimatisation":"acclimatization",
"acclimatise":"acclimatize",
"acclimatised":"acclimatized",
"acclimatises":"acclimatizes",
"acclimatising":"acclimatiz... | spellings_map = {'accessorise': 'accessorize', 'accessorised': 'accessorized', 'accessorises': 'accessorizes', 'accessorising': 'accessorizing', 'acclimatisation': 'acclimatization', 'acclimatise': 'acclimatize', 'acclimatised': 'acclimatized', 'acclimatises': 'acclimatizes', 'acclimatising': 'acclimatizing', 'accoutre... |
n = int(input())
while n != -1:
prev_time = 0
total = 0
for _ in range(n):
(speed, time) = map(int, input().split(" "))
total += (time - prev_time) * speed
prev_time = time
print(total, "miles")
n = int(input())
| n = int(input())
while n != -1:
prev_time = 0
total = 0
for _ in range(n):
(speed, time) = map(int, input().split(' '))
total += (time - prev_time) * speed
prev_time = time
print(total, 'miles')
n = int(input()) |
class Node:
_fields = []
def __init__(self, *args):
for key, value in zip(self._fields, args):
setattr(self, key, value)
def __repl__(self):
return self.__str__()
# literals...
class Bool(Node):
_fields = ["value"]
def __str__(self):
string = "Boolean=" + s... | class Node:
_fields = []
def __init__(self, *args):
for (key, value) in zip(self._fields, args):
setattr(self, key, value)
def __repl__(self):
return self.__str__()
class Bool(Node):
_fields = ['value']
def __str__(self):
string = 'Boolean=' + str(self.value)
... |
def enum(**enums):
return type('Enum', (), enums)
control = enum(CHOICE_BOX = 0,
TEXT_BOX = 1,
COMBO_BOX = 2,
INT_CTRL = 3,
FLOAT_CTRL = 4,
DIR_COMBO_BOX = 5,
CHECKLIST_BOX = 6,
LISTBOX_COMBO = 7,
... | def enum(**enums):
return type('Enum', (), enums)
control = enum(CHOICE_BOX=0, TEXT_BOX=1, COMBO_BOX=2, INT_CTRL=3, FLOAT_CTRL=4, DIR_COMBO_BOX=5, CHECKLIST_BOX=6, LISTBOX_COMBO=7, TEXTBOX_COMBO=8, CHECKBOX_GRID=9, GPA_CHECKBOX_GRID=10, SPIN_BOX_FLOAT=11)
dtype = enum(BOOL=0, STR=1, NUM=2, LBOOL=3, LSTR=4, LNUM=5, ... |
'''
lanhuage: python
Descripttion:
version: beta
Author: xiaoshuyui
Date: 2020-09-15 13:53:11
LastEditors: xiaoshuyui
LastEditTime: 2020-09-22 11:20:14
'''
__version__ = '0.0.0'
__appname__ = 'show and search'
| """
lanhuage: python
Descripttion:
version: beta
Author: xiaoshuyui
Date: 2020-09-15 13:53:11
LastEditors: xiaoshuyui
LastEditTime: 2020-09-22 11:20:14
"""
__version__ = '0.0.0'
__appname__ = 'show and search' |
def contains_magic_number(list1, magic_number):
for i in list1:
if i == magic_number:
print("This list contains the magic number")
# if not add break , will run more meaningless loop
break
else:
print("This list does NOT contain the magic number")
if... | def contains_magic_number(list1, magic_number):
for i in list1:
if i == magic_number:
print('This list contains the magic number')
break
else:
print('This list does NOT contain the magic number')
if __name__ == '__main__':
contains_magic_number(range(10), 3) |
def dfs_inorder(tree):
if tree is None: return None
out = []
dfs_inorder(tree.left)
out.append(tree.value)
print(tree.value)
dfs_inorder(tree.right)
return out
def dfs_preorder(tree):
if tree is None: return None
out = []
out.append(tree.value)
print(tree.value)
dfs_... | def dfs_inorder(tree):
if tree is None:
return None
out = []
dfs_inorder(tree.left)
out.append(tree.value)
print(tree.value)
dfs_inorder(tree.right)
return out
def dfs_preorder(tree):
if tree is None:
return None
out = []
out.append(tree.value)
print(tree.val... |
def round_down(num, digits: int):
a = float(num)
if digits < 0:
b = 10 ** int(abs(digits))
answer = int(a * b) / b
else:
b = 10 ** int(digits)
answer = int(a / b) * b
assert not(not(-0.01 < num < 0.01) and answer == 0)
return answer
| def round_down(num, digits: int):
a = float(num)
if digits < 0:
b = 10 ** int(abs(digits))
answer = int(a * b) / b
else:
b = 10 ** int(digits)
answer = int(a / b) * b
assert not (not -0.01 < num < 0.01 and answer == 0)
return answer |
INPUT = {
2647: [
list("#....#####"),
list(".##......#"),
list("##......##"),
list(".....#..#."),
list(".........#"),
list(".....#..##"),
list("#.#....#.."),
list("#......#.#"),
list("#....##..#"),
list("...##....."),
],
1283: [... | input = {2647: [list('#....#####'), list('.##......#'), list('##......##'), list('.....#..#.'), list('.........#'), list('.....#..##'), list('#.#....#..'), list('#......#.#'), list('#....##..#'), list('...##.....')], 1283: [list('######..#.'), list('#.#..#.#..'), list('..#..#...#'), list('.#.##..#..'), list('#......#..... |
def solve(s):
if s==s[::-1]:
return 1
else:
return 0
s=str(input())
print(solve(s))
| def solve(s):
if s == s[::-1]:
return 1
else:
return 0
s = str(input())
print(solve(s)) |
# Copyright (c) 2017-2017 Cisco Systems, Inc.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... | path_get_nexus_type = 'api/mo/sys/ch.json'
path_vlan_all = 'api/mo.json'
body_vlan_all_beg = '{"topSystem": { "children": [ {"bdEntity":'
body_vlan_all_beg += ' { children": ['
body_vlan_all_incr = ' {"l2BD": {"attributes": {"fabEncap": "vlan-%s",'
body_vlan_all_incr += ' "pcTag": "1", "adminSt": "active"}}}'
body_vxl... |
message = [ 'e', 'k', 'a', 'c', ' ',
'd', 'n', 'u', 'o', 'p', ' ',
'l', 'a', 'e', 't', 's']
def reversed_words(message):
cur_pos = 0
end_pos = len(message)
current_word_start = cur_pos
while cur_pos < end_pos:
if message[cur_pos] == ' ':
message[current_word... | message = ['e', 'k', 'a', 'c', ' ', 'd', 'n', 'u', 'o', 'p', ' ', 'l', 'a', 'e', 't', 's']
def reversed_words(message):
cur_pos = 0
end_pos = len(message)
current_word_start = cur_pos
while cur_pos < end_pos:
if message[cur_pos] == ' ':
message[current_word_start:cur_pos] = reversed... |
class EquationClass:
def __init__(self):
pass
def calculation(self):
...
def info(self):
...
| class Equationclass:
def __init__(self):
pass
def calculation(self):
...
def info(self):
... |
class BufferFile:
def __init__(self, write):
self.write = write
def readline(self): pass
def writelines(self, l): map(self.append, l)
def flush(self): pass
def isatty(self): return 1
| class Bufferfile:
def __init__(self, write):
self.write = write
def readline(self):
pass
def writelines(self, l):
map(self.append, l)
def flush(self):
pass
def isatty(self):
return 1 |
# Class could be designed to be used in cooperative multiple inheritance
# so `super()` could be resolved to some non-object class that is able to receive passed arguments.
class Shape(object):
def __init__(self, shapename, **kwds):
self.shapename = shapename
# in case of ColoredShape the call below wil... | class Shape(object):
def __init__(self, shapename, **kwds):
self.shapename = shapename
super(Shape, self).__init__(**kwds)
class Colored(object):
def __init__(self, color, **kwds):
self.color = color
super(Colored, self).__init__(**kwds)
class Coloredshape(Shape, Colored):
... |
# Space Walk
# by Sean McManus
# www.sean.co.uk / www.nostarch.com
WIDTH = 800
HEIGHT = 600
player_x = 500
player_y = 550
def draw():
screen.blit(images.backdrop, (0, 0))
| width = 800
height = 600
player_x = 500
player_y = 550
def draw():
screen.blit(images.backdrop, (0, 0)) |
def countPaths(maze, rows, cols):
if (maze[0][0] == -1):
return 0
# Initializing the leftmost column
for i in range(rows):
if (maze[i][0] == 0):
maze[i][0] = 1
# If we encounter a blocked cell in
# leftmost row, there is no way of
# visiting any cell directly below it.
else:
break
# Si... | def count_paths(maze, rows, cols):
if maze[0][0] == -1:
return 0
for i in range(rows):
if maze[i][0] == 0:
maze[i][0] = 1
else:
break
for i in range(1, cols, 1):
if maze[0][i] == 0:
maze[0][i] = 1
else:
break
for i i... |
n,s,t=map(int,input().split())
w=c=0
for i in range(n):
w+=int(input())
c+=s<=w<=t
print(c) | (n, s, t) = map(int, input().split())
w = c = 0
for i in range(n):
w += int(input())
c += s <= w <= t
print(c) |
'''
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
'''
# find the factors of num using modulus operator
num = 600851475143
div = 2
highestFactor = 1
while num > 1:
if(num%div==0):
num = num/div
highestFactor = div
else:
di... | """
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""
num = 600851475143
div = 2
highest_factor = 1
while num > 1:
if num % div == 0:
num = num / div
highest_factor = div
else:
div += 1
print(highestFactor) |
# Problem Statement: https://www.hackerrank.com/challenges/map-and-lambda-expression/problem
cube = lambda x: x**3
def fibonacci(n):
fib = [0, 1]
for i in range(2, n):
fib.append(fib[i - 1] + fib[i - 2])
return fib[0:n] | cube = lambda x: x ** 3
def fibonacci(n):
fib = [0, 1]
for i in range(2, n):
fib.append(fib[i - 1] + fib[i - 2])
return fib[0:n] |
def multiply_by(a, b=2, c=1):
return a * b + c
print(multiply_by(3, 47, 0)) # Call function using custom values for all parameters
print(multiply_by(3, 47)) # Call function using default value for c parameter
print(multiply_by(3, c=47)) # Call function using default value for b parameter
print(multiply_by(3)) ... | def multiply_by(a, b=2, c=1):
return a * b + c
print(multiply_by(3, 47, 0))
print(multiply_by(3, 47))
print(multiply_by(3, c=47))
print(multiply_by(3))
print(multiply_by(a=7))
def hello(subject, name='Max'):
print(f'Hello {subject}! My name is {name}')
hello('PyCharm', 'Jane')
hello('PyCharm') |
############################################################################
#
# Copyright (C) 2016 The Qt Company Ltd.
# Contact: https://www.qt.io/licensing/
#
# This file is part of Qt Creator.
#
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in
# accordance with the co... | source('../../shared/qtcreator.py')
def main():
start_application('qtcreator' + SettingsPath)
if not started_without_plugin_error():
return
create_project__qt_gui(temp_dir(), 'DesignerTestApp')
select_from_locator('mainwindow.ui')
widget_index = "{container=':qdesigner_internal::WidgetBoxCa... |
# -*- coding: utf-8 -*-
# @Time : 2018/8/13 16:45
# @Author : Dylan
# @File : config.py
# @Email : wenyili@buaa.edu.cn
class Config():
train_imgs_path = "images/train/images"
train_labels_path = "images/train/label"
merge_path = ""
aug_merge_path = "deform/deform_norm2"
aug_train_path = "de... | class Config:
train_imgs_path = 'images/train/images'
train_labels_path = 'images/train/label'
merge_path = ''
aug_merge_path = 'deform/deform_norm2'
aug_train_path = 'deform/train/'
aug_label_path = 'deform/label/'
test_path = 'images/test'
npy_path = '../npydata'
result_np_save = '... |
tile_colors = {}
for _ in range(400):
path = input()
i = 0
pos_north = 0.0
pos_east = 0.0
while i < len(path):
if path[i] == 'e':
pos_east += 1.0
i += 1
elif path[i] == 'w':
pos_east -= 1.0
i += 1
elif path[i] == 'n' and path... | tile_colors = {}
for _ in range(400):
path = input()
i = 0
pos_north = 0.0
pos_east = 0.0
while i < len(path):
if path[i] == 'e':
pos_east += 1.0
i += 1
elif path[i] == 'w':
pos_east -= 1.0
i += 1
elif path[i] == 'n' and path[i ... |
# Copyright 2018 Inap.
#
# 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... | class Shellsession(object):
def __init__(self, command_processor):
self.command_processor = command_processor
self.command_processor.write('\n')
self.command_processor.show_prompt()
def receive(self, line):
self.command_processor.logger.debug('received: %s' % line)
try:... |
function_classes = {}
class RegisteringMetaclass(type):
def __new__(*args): # pylint: disable=no-method-argument
cls = type.__new__(*args)
if cls.name:
function_classes[cls.name] = cls
return cls
class Function(metaclass=RegisteringMetaclass):
name = None
min_args =... | function_classes = {}
class Registeringmetaclass(type):
def __new__(*args):
cls = type.__new__(*args)
if cls.name:
function_classes[cls.name] = cls
return cls
class Function(metaclass=RegisteringMetaclass):
name = None
min_args = None
max_args = None
def __ini... |
load("@bazel_skylib//lib:shell.bzl", "shell")
load("//:golink.bzl", "gen_copy_files_script")
def go_proto_link_impl(ctx, **kwargs):
print("Copying generated files for proto library %s" % ctx.attr.dep[OutputGroupInfo])
return gen_copy_files_script(ctx, ctx.attr.dep[OutputGroupInfo].go_generated_srcs.to_list())
... | load('@bazel_skylib//lib:shell.bzl', 'shell')
load('//:golink.bzl', 'gen_copy_files_script')
def go_proto_link_impl(ctx, **kwargs):
print('Copying generated files for proto library %s' % ctx.attr.dep[OutputGroupInfo])
return gen_copy_files_script(ctx, ctx.attr.dep[OutputGroupInfo].go_generated_srcs.to_list())
... |
#!/usr/bin/env python3
#!/usr/bin/env python
LIMIT = 32
dict1 = {}
def main():
squares()
a1 = 0
while a1 < LIMIT:
sums(a1)
a1 += 1
results()
def squares():
global dict1
for i1 in range(1, LIMIT * 2):
# print "%s" % str(i1)
s1 = i1 * i1
if not s1 in dic... | limit = 32
dict1 = {}
def main():
squares()
a1 = 0
while a1 < LIMIT:
sums(a1)
a1 += 1
results()
def squares():
global dict1
for i1 in range(1, LIMIT * 2):
s1 = i1 * i1
if not s1 in dict1:
dict1[s1] = []
dict1[s1].append(i1)
def results()... |
# -*-coding:utf-8-*-
__author__ = "Allen Woo"
DB_CONFIG = {
"redis": {
"host": [
"127.0.0.1"
],
"password": "<Your password>",
"port": [
"6379"
]
},
"mongodb": {
"web": {
"dbname": "osr_web",
"password": "<Your p... | __author__ = 'Allen Woo'
db_config = {'redis': {'host': ['127.0.0.1'], 'password': '<Your password>', 'port': ['6379']}, 'mongodb': {'web': {'dbname': 'osr_web', 'password': '<Your password>', 'config': {'fsync': False, 'replica_set': None}, 'host': ['127.0.0.1:27017'], 'username': 'root'}, 'user': {'dbname': 'osr_user... |
class NumArray:
def __init__(self):
self.__values = []
def __length_hint__(self):
print('__length_hint__', len(self.__values))
return len(self.__values)
n = NumArray()
print(len(n)) # TypeError: object of type 'NumArray' has no len()
| class Numarray:
def __init__(self):
self.__values = []
def __length_hint__(self):
print('__length_hint__', len(self.__values))
return len(self.__values)
n = num_array()
print(len(n)) |
#!/usr/bin/env python
'''XML Namespace Constants'''
#
# This should actually check for a value error
#
def xs_bool(in_string):
'''Takes an XSD boolean value and converts it to a Python bool'''
if in_string in ['true', '1']:
return True
return False
| """XML Namespace Constants"""
def xs_bool(in_string):
"""Takes an XSD boolean value and converts it to a Python bool"""
if in_string in ['true', '1']:
return True
return False |
''' teachers and centers are lists of Teacher objects and ExamCenter objects respectively
class Teacher and class ExamCentre and defined in locatable.py
Both are subclass of Locatable class
Link : https://github.com/aahnik/mapTeachersToCenters/blob/master/locatable.py '''
def sort(locatables, focal_cen... | """ teachers and centers are lists of Teacher objects and ExamCenter objects respectively
class Teacher and class ExamCentre and defined in locatable.py
Both are subclass of Locatable class
Link : https://github.com/aahnik/mapTeachersToCenters/blob/master/locatable.py """
def sort(locatables, focal_cent... |
list=[1,2,3.5,4,5]
print(list)
sum=0
for i in list:
sum=sum+i
sum/=i
print(sum)
| list = [1, 2, 3.5, 4, 5]
print(list)
sum = 0
for i in list:
sum = sum + i
sum /= i
print(sum) |
'''
PURPOSE
Analyze a string to check if it contains two of the same letter
in a row. Your function must return True if there are two identical
letters in a row in the string, and False otherwise.
EXAMPLE
The string "hello" has l twice in a row, while the string "nono"
does not have two identical ... | """
PURPOSE
Analyze a string to check if it contains two of the same letter
in a row. Your function must return True if there are two identical
letters in a row in the string, and False otherwise.
EXAMPLE
The string "hello" has l twice in a row, while the string "nono"
does not have two identical ... |
limit = int(input())
current = int(input())
multiply = int(input())
day = 0
total = current
while total <= limit:
day += 1
current *= multiply
total += current
# print('on day', day, ',', current, 'people are infected. and the total is', total)
print(day) | limit = int(input())
current = int(input())
multiply = int(input())
day = 0
total = current
while total <= limit:
day += 1
current *= multiply
total += current
print(day) |
train_sequence = ReportSequence(X_train, y_train)
validation_sequence = ReportSequence(X_valid, y_valid)
model = Sequential()
forward_layer = LSTM(300, return_sequences=True)
backward_layer = LSTM(300, go_backwards=True, return_sequences=True)
model.add(Bidirectional(forward_layer,
backward_l... | train_sequence = report_sequence(X_train, y_train)
validation_sequence = report_sequence(X_valid, y_valid)
model = sequential()
forward_layer = lstm(300, return_sequences=True)
backward_layer = lstm(300, go_backwards=True, return_sequences=True)
model.add(bidirectional(forward_layer, backward_layer=backward_layer, inpu... |
# Code generated by font-to-py.py.
# Font: dsmb.ttf
version = '0.26'
def height():
return 16
def max_width():
return 9
def hmap():
return True
def reverse():
return False
def monospaced():
return False
def min_ch():
return 32
def max_ch():
return 126
_font =\... | version = '0.26'
def height():
return 16
def max_width():
return 9
def hmap():
return True
def reverse():
return False
def monospaced():
return False
def min_ch():
return 32
def max_ch():
return 126
_font = b'\t\x00\x00\x00x\x00\x8c\x00\x0c\x00\x1c\x008\x000\x000\x000\x00\x00\x000\x00... |
orgM = cmds.ls(sl=1,fl=1)
newM = cmds.ls(sl=1,fl=1)
for nm in newM:
for om in orgM:
if nm.split(':')[0] == om.split(':')[0]+'1':
trans = cmds.xform(om,ws=1,piv=1,q=1)
rot = cmds.xform(om,ws=1,ro=1,q=1)
cmds.xform(nm,t=trans[0:3],ro=rot)
cmds.namespace(ren=((nm.split(':')[0]),(nm.split(':')[1])))
| org_m = cmds.ls(sl=1, fl=1)
new_m = cmds.ls(sl=1, fl=1)
for nm in newM:
for om in orgM:
if nm.split(':')[0] == om.split(':')[0] + '1':
trans = cmds.xform(om, ws=1, piv=1, q=1)
rot = cmds.xform(om, ws=1, ro=1, q=1)
cmds.xform(nm, t=trans[0:3], ro=rot)
cmds.name... |
class Solution:
def isValid(self, s: str):
count = 0
for i in s:
if i == '(':
count += 1
if i == ')':
count -=1
if count < 0:
return False
return count == 0
def removeInvalidParenthes... | class Solution:
def is_valid(self, s: str):
count = 0
for i in s:
if i == '(':
count += 1
if i == ')':
count -= 1
if count < 0:
return False
return count == 0
def remove_invalid_parentheses(self, s: str... |
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
DEPS = [
'chromium_tests',
'depot_tools/tryserver',
'recipe_engine/platform',
'recipe_engine/properties',
]
def RunSteps(api):
tests = []... | deps = ['chromium_tests', 'depot_tools/tryserver', 'recipe_engine/platform', 'recipe_engine/properties']
def run_steps(api):
tests = []
if api.properties.get('local_gtest'):
tests.append(api.chromium_tests.steps.LocalGTestTest('base_unittests'))
if api.properties.get('swarming_gtest'):
test... |
# -*- coding: utf-8 -*-
description = 'detectors'
group = 'lowlevel' # is included by panda.py
devices = dict(
mcstas = device('nicos_virt_mlz.panda.devices.mcstas.PandaSimulation',
description = 'McStas simulation',
),
timer = device('nicos.devices.mcstas.McStasTimer',
mcstas = 'mcstas... | description = 'detectors'
group = 'lowlevel'
devices = dict(mcstas=device('nicos_virt_mlz.panda.devices.mcstas.PandaSimulation', description='McStas simulation'), timer=device('nicos.devices.mcstas.McStasTimer', mcstas='mcstas', visibility=()), mon1=device('nicos.devices.mcstas.McStasCounter', type='monitor', mcstas='m... |
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
# Add your function here
def flatten(lists):
results = []
for i in range(len(lists)):
for j in range(len(lists[i])):
results.append(lists[i][j])
return results
print(flatten(n))
| n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(lists):
results = []
for i in range(len(lists)):
for j in range(len(lists[i])):
results.append(lists[i][j])
return results
print(flatten(n)) |
age=int(input())
washing_machine_price=float(input())
toys_price=float(input())
toys_count = 0
money_amount = 0
for years in range(1,age+1):
if years % 2 == 0:
#price
money_amount += years / 2 * 10
money_amount-=1
else:
#toy
toys_count+=1
toys_price=toys_count*... | age = int(input())
washing_machine_price = float(input())
toys_price = float(input())
toys_count = 0
money_amount = 0
for years in range(1, age + 1):
if years % 2 == 0:
money_amount += years / 2 * 10
money_amount -= 1
else:
toys_count += 1
toys_price = toys_count * toys_price
total_amoun... |
#Ejercicio
precio = float(input("Ingrese el precio: "))
descuento = precio * 0.15
precio_final = precio - descuento
print (f"el precio final a pagar es: {precio_final:.2f}")
print (descuento)
| precio = float(input('Ingrese el precio: '))
descuento = precio * 0.15
precio_final = precio - descuento
print(f'el precio final a pagar es: {precio_final:.2f}')
print(descuento) |
# write your code here
user_field = input("Enter cells: ")
game_board = []
player_1 = "X"
player_2 = "O"
def print_field(field):
global game_board
coordinates = list()
game_board = [[field[0], field[1], field[2]],
[field[3], field[4], field[5]],
[field[6], field[7], fie... | user_field = input('Enter cells: ')
game_board = []
player_1 = 'X'
player_2 = 'O'
def print_field(field):
global game_board
coordinates = list()
game_board = [[field[0], field[1], field[2]], [field[3], field[4], field[5]], [field[6], field[7], field[8]]]
def printer(board):
print('---------')
... |
# takes two inputs and adds them together as ints;
# outputs solution
print(int(input()) + int(input()))
| print(int(input()) + int(input())) |
triggers = {
'lumos': 'automation.potter_pi_spell_lumos',
'nox': 'automation.potter_pi_spell_nox',
'revelio': 'automation.potter_pi_spell_revelio'
} | triggers = {'lumos': 'automation.potter_pi_spell_lumos', 'nox': 'automation.potter_pi_spell_nox', 'revelio': 'automation.potter_pi_spell_revelio'} |
fh= open("romeo.txt")
lst= list()
for line in fh:
wds= line.split()
for word in wds:
if word in wds:
lst.append(word)
lst.sort()
print(lst)
| fh = open('romeo.txt')
lst = list()
for line in fh:
wds = line.split()
for word in wds:
if word in wds:
lst.append(word)
lst.sort()
print(lst) |
OEMBED_URL_SCHEME_REGEXPS = {
'slideshare' : r'https?://(?:www\.)?slideshare\.(?:com|net)/.*',
'soundcloud' : r'https?://soundcloud.com/.*',
'vimeo' : r'https?://(?:www\.)?vimeo\.com/.*',
'youtube' : r'https?://(?:(www\.)?youtube\.com|youtu\.be)/.*',
}
OEMBED_BASE_URLS = {
'slideshare' : 'https://w... | oembed_url_scheme_regexps = {'slideshare': 'https?://(?:www\\.)?slideshare\\.(?:com|net)/.*', 'soundcloud': 'https?://soundcloud.com/.*', 'vimeo': 'https?://(?:www\\.)?vimeo\\.com/.*', 'youtube': 'https?://(?:(www\\.)?youtube\\.com|youtu\\.be)/.*'}
oembed_base_urls = {'slideshare': 'https://www.slideshare.net/api/oembe... |
X, M = tuple(map(int,input().split()))
while X != 0 or M != 0:
print(X*M)
X, M = tuple(map(int,input().split()))
| (x, m) = tuple(map(int, input().split()))
while X != 0 or M != 0:
print(X * M)
(x, m) = tuple(map(int, input().split())) |
FLAG = 'QCTF{4e94227c6c003c0b6da6f81c9177c7e7}'
def check(attempt, context):
return Checked(attempt.answer == FLAG)
| flag = 'QCTF{4e94227c6c003c0b6da6f81c9177c7e7}'
def check(attempt, context):
return checked(attempt.answer == FLAG) |
'''
Created on Mar 3, 2014
@author: rgeorgi
'''
class EvalException(Exception):
'''
classdocs
'''
def __init__(self, msg):
'''
Constructor
'''
self.message = msg
class POSEvalException(Exception):
def __init__(self, msg):
Exception.__init__(self, msg)
| """
Created on Mar 3, 2014
@author: rgeorgi
"""
class Evalexception(Exception):
"""
classdocs
"""
def __init__(self, msg):
"""
Constructor
"""
self.message = msg
class Posevalexception(Exception):
def __init__(self, msg):
Exception.__init__(self, msg) |
class Solution:
def lengthOfLastWord(self, s: str) -> int:
n=0
last=0
for c in s:
if c==" ":
last=n if n>0 else last
n=0
else:
n=n+1
return n if n>0 else last
| class Solution:
def length_of_last_word(self, s: str) -> int:
n = 0
last = 0
for c in s:
if c == ' ':
last = n if n > 0 else last
n = 0
else:
n = n + 1
return n if n > 0 else last |
class BaseClause:
def __init__(self):
# call super as these classes will be used as mix-in
# and we want the init chain to reach all extended classes in the user of these mix-in
# Update: Its main purpose is to make IDE hint children constructors to call base one,
# as not calling it... | class Baseclause:
def __init__(self):
super().__init__() |
def get_breadcrumb(cat3):
cat2 = cat3.parent
cat1 = cat3.parent.parent
cat1.url = cat1.goodschannel_set.all()[0].url
breadcrumb = {
'cat1': cat1,
'cat2': cat2,
'cat3': cat3,
}
return breadcrumb | def get_breadcrumb(cat3):
cat2 = cat3.parent
cat1 = cat3.parent.parent
cat1.url = cat1.goodschannel_set.all()[0].url
breadcrumb = {'cat1': cat1, 'cat2': cat2, 'cat3': cat3}
return breadcrumb |
class DynamicObjectSerializer:
def __init__(self, value, many=False):
self._objects = None
self._object = None
if many:
value = tuple(v for v in value)
self._objects = value
else:
self._object = value
@property
def objects(self):
... | class Dynamicobjectserializer:
def __init__(self, value, many=False):
self._objects = None
self._object = None
if many:
value = tuple((v for v in value))
self._objects = value
else:
self._object = value
@property
def objects(self):
... |
myTup = 0, 2, 4, 5, 6, 7
i1, *i2, i3 = myTup
print(i1)
print(i2, type(i2))
print(i3) | my_tup = (0, 2, 4, 5, 6, 7)
(i1, *i2, i3) = myTup
print(i1)
print(i2, type(i2))
print(i3) |
class Color:
BACKGROUND = 236
FOREGROUND = 195
BUTTON_BACKGROUND = 66
FIELD_BACKGROUND = 238 #241
SCROLL_BAR_BACKGROUND = 242
TEXT = 1
INPUT_FIELD = 2
SCROLL_BAR = 3
BUTTON = 4
# color.py
| class Color:
background = 236
foreground = 195
button_background = 66
field_background = 238
scroll_bar_background = 242
text = 1
input_field = 2
scroll_bar = 3
button = 4 |
def smallest_positive(arr):
# Find the smallest positive number in the list
min = None
for num in arr:
if num > 0:
if min == None or num < min:
min = num
return min
def when_offered(courses, course):
output = []
for semester in courses:
for course_n... | def smallest_positive(arr):
min = None
for num in arr:
if num > 0:
if min == None or num < min:
min = num
return min
def when_offered(courses, course):
output = []
for semester in courses:
for course_names in courses[semester]:
if course_names... |
def my_abs(x):
if not isinstance(x, (int, float)):
raise TypeError('bad operand type')
if x >= 0:
return x
else:
return -x | def my_abs(x):
if not isinstance(x, (int, float)):
raise type_error('bad operand type')
if x >= 0:
return x
else:
return -x |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.