text stringlengths 5 121k |
|---|
from string import ascii_uppercase
from itertools import cycle
def sequence_generator():
alphabet_list = cycle(ascii_uppercase)
number_list = cycle(range(1,27))
for i in range(100):
yield next(number_list)
yield next(alphabet_list)
print(list(sequence_generator())) |
class Solution(object):
"""
Bucket sort. Refer to:
https://leetcode.com/discuss/48670/o-n-python-using-buckets-with-explanation-10-lines
1. Each bucket i save one number, which satisfy val/(t+1) == i.
2. For each number, the possible candidate can only be
in the same bucket or the two bucke... |
class Solution:
def sortColors(self, A):
color=[0]*3
for i in A:
color[i] += 1
i = 0
for x in range(3):
for j in range(color[x]):
A[i]=x
i+=1
return A
Solution().sortColors([1,2,0,1,2,0]) |
class Solution(object):
def oddEvenList(self, head):
if not head or not head.next:
return head
odd = ListNode(0)
even = ListNode(0)
pre_head = odd
pre_mid = even
odd_even_dict = {0: even, 1: odd}
count = 0
while head:
... |
from collections import defaultdict
from typing import Counter
count = defaultdict(Counter)
count['khoo']['a'] = 1
count['khoo']['b'] = 2
print(count['swee']) |
import os
basepath = 'my_directory/'
for entry in os.listdir(basepath):
if os.path.isfile(os.path.join(basepath, entry)):
print(entry)
print()
print()
import os
basepath = 'my_directory/'
with os.scandir(basepath) as entries:
for entry in entries:
if entry.is_file():
... |
from datetime import datetime
age = int(input("What's your age? "))
year_birth = datetime.now().year - age
print("You were born back in %s" % year_birth)
|
import pytz
from datetime import datetime
MEETING_HOURS = range(6, 23)
TIMEZONES = set(pytz.all_timezones)
def within_schedule(utc, *timezones):
"""Receive a utc datetime and one or more timezones and check if
they are all within schedule (MEETING_HOURS)"""
utc = pytz.utc.localize(utc)
for time... |
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
rowIndex += 1
row_nums = [0 for i in range(rowIndex)]
row_nums[0] = 1
for i in range(1, rowIndex):
symmetry_count = (i+1)/2
... |
import random
from card import Card
class Deck:
suits = ["Spades", "Clubs", "Diamonds", "Hearts"]
def __init__(self):
self._cards = []
self.build()
def build(self):
for suit in Deck.suits:
for value in ran... |
VALID_COLORS = ['blue', 'yellow', 'red']
def my_print_colors():
"""Ask for color, lowercase it, check if 'quit' is entered, if so print
'bye' and break, next check if given color is in VALID_COLORS, if not,
continue, finally if that check passes, print the color"""
while True:
inp = inpu... |
from pymongo import MongoClient
client = MongoClient()
client = MongoClient('localhost', 27017)
client = MongoClient('mongodb://localhost:27017')
db = client.pymongo_test
db = client['pymongo_test']
posts = db.posts
post_data = {
'title': 'Python and MongoDB',
'content': 'PyMon... |
from typing import List
def common_words(sentence1: List[str], sentence2: List[str]) -> List[str]:
"""
Input: Two sentences - each is a list of words in case insensitive ways.
Output: those common words appearing in both sentences. Capital and lowercase
words are treated as the same word.
... |
class Solution(object):
def isPalindrome(self, x):
if x < 0:
return False
reversed_x = 0
original_x = x
while x > 0:
reversed_x = reversed_x * 10 + x % 10
x /= 10
return reversed_x == original_x
class Solution_2(object):
def isPa... |
class Solution:
def spiralOrder(self, matrix):
if matrix == []:
return []
res = []
maxUp = maxLeft = 0
maxDown = len(matrix) - 1
maxRight = len(matrix[0]) - 1
direct = 0
while True:
if direct == 0:
... |
import unittest
from abc import ABC
from enum import Enum
class Creature(ABC):
def __init__(self, game, attack, defense):
self.initial_defense = defense
self.initial_attack = attack
self.game = game
@property
def attack(self): pass
@property
def defense(self): pass
... |
import logging
from pprint import pprint
from sys import stdout as STDOUT
def index_words(text):
result = []
if text:
result.append(0)
for index, letter in enumerate(text):
if letter == ' ':
result.append(index + 1)
return result
address = 'Four score and seven years ag... |
import unicodedata
def filter_accents(text):
"""Return a sequence of accented characters found in
the passed in lowercased text string
"""
text = text.lower()
result = []
s = unicodedata.normalize('NFD',text).encode("ascii",'ignore').decode('utf-8')
for character_1,character_2 in zi... |
"""
与今日头条的秋招第一题差不多的题:
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input:
11110
11010
11000
000... |
from copy import deepcopy
class Matrix(object):
def __init__(self, values):
self.values = values
@property
def nrows(self):
return len(self.values)
@property
def ncols(self):
return len(self.values[0])
def __matmul__(self,other):
rows_1,cols_1... |
import unittest
from challenge import counter
class EasyTestCase(unittest.TestCase):
def test_easy_input(self):
self.assertEqual(counter('Mo'), 2)
def test_easy_input_two(self):
self.assertEqual(counter('Mohammad'), 8)
class MediumTestCase(unittest.TestCase):
def tes... |
def digit_map(num):
"""maps numbers greater than a single digit to letters (UPPER)"""
return chr(num + 55) if num > 9 else str(num)
def convert(number: int, base: int = 2) -> str:
"""Converts an integer into any base between 2 and 36 inclusive
Args:
number (int): Integer to convert
bas... |
class Solution(object):
countNQueens = 0
def totalNQueens(self, n):
self.countNQueens = 0
cols_used = [-1 for i in range(n)]
self.solveNQueens(0, cols_used, n)
return self.countNQueens
def solveNQueens(self, row, cols_used, n):
for col in range(n):
i... |
"""
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Fo... |
class Solution(object):
def longestValidParentheses(self, s):
"""
According to:
https://leetcode.com/discuss/7609/my-o-n-solution-using-a-stack
If current character is '(', push its index to the stack.
If current character is ')':
1. top of stack is '(', just fin... |
import android
app = android.Android()
app.dialogCreateAlert("Select your food items")
app.dialogSetMultiChoiceItems(['Pizza', 'Burger', 'Hot Dog'])
app.dialogSetPositiveButtonText('Done')
app.dialogShow()
app.dialogGetResponse()
response = app.dialogGetSelectedItems()
print(response)
selectedResult=response[1]
n=len... |
def avg(*list_numbers: float) -> float:
total = 0
for num in list_numbers:
if isinstance(num, (int, float)):
total += num
else:
raise TypeError("Wrong input data. Please make sure that everything is a number. ")
return total / len(list_numbers)
|
from typing import List
def pascal(N: int) -> List[int]:
current_row = [1]
for _ in range(N - 1):
new_row = [1]
for i in range(0,len(current_row) - 1):
new_row.append(current_row[i] + current_row[i +1])
new_row.append(1)
current_row = new_row
... |
from abs_state import AbsState
class Empty(AbsState):
def add_item(self):
self._cart.items += 1
print('You added the first item')
self._cart.state = self._cart.not_empty
def remove_item(self):
print('Your cart is empty! Nothing to remove!!')
def checkout(self):
pr... |
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d3 = {'e': 5, 'f': 6}
d = {**d1, **d2, **d3}
print(d)
d = {}
d.update(d1)
d.update(d2)
d.update(d3)
print(d)
from collections import ChainMap
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d3 = {'e': 5, 'f': 6}
d = ChainMap(d1, d2, d3)
print(d)
print(... |
numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
zipped = zip(numbers, letters)
zipped
type(zipped)
list(zipped)
s1 = {2, 3, 1}
s2 = {'b', 'a', 'c'}
list(zip(s1, s2))
|
import unittest
def sum_two_values(a, b):
return a + b
def power(x, n):
return x ** n
def concat_values(*args):
result = ''
for item in args:
result += str(item)
return result
def desc(x, y):
if x == 0:
raise ValueError('`x` should not be equal 0')
return y / x
clas... |
class Solution(object):
def zigzagLevelOrder(self, root):
if not root:
return []
left2right = 1
ans, stack, temp = [], [root], []
while stack:
temp = [node.val for node in stack]
stack = [child for node in stack
... |
import android
app = android.Android()
title = 'Understanding Dialog Buttons'
message = ('Do you want to Place the Order?')
app.dialogCreateAlert(title, message)
app.dialogSetPositiveButtonText('Yes')
app.dialogSetNegativeButtonText('No')
app.dialogSetNeutralButtonText('Cancel')
app.dialogShow()
response = app.dialogG... |
class Solution:
def threeSumClosest(self, numbers, target):
numbers.sort()
ans = None
for i in range(len(numbers)):
l, r = i + 1, len(numbers) - 1
while (l < r):
sum = numbers[l] + numbers[r] + numbers[i]
if ans is None or abs(s... |
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if not n:
return 1
dp = [0 for i in range(n)]
dp[0] = 1
if n > 1:
dp[1] = 2
for i in range(2, n):
dp[i] = dp[i-1] + dp[i... |
"""
Write a decorator called make_html that wraps text inside one or more html tags.
As shown in the tests decorating get_text with make_html twice should wrap the text in the corresponding html tags, so:
@make_html('p')
@make_html('strong')
def get_text(text='I code with PyBites'):
return text
- would return: <p... |
class Solution:
def reverse(self, x):
if x<0:
sign = -1
else:
sign = 1
strx=str(abs(x))
r = strx[::-1]
return sign*int(r)
Solution().reverse(123) |
value = 10
class User:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def create_new_user(first_name, last_name):
print(first_name)
return User(first_name=first_name, last_name=last_name)
user2 = create_new_user('Test1', '... |
class MonoState(object):
__data = 5
@property
def data(self):
return self.__class__.__data
@data.setter
def data(self, value):
self.__class__.__data = value
class MonoState2(object):
pass
def add_monostate_property(cls, name, initial_value):
"""
Adds a prop... |
import logging
from pprint import pprint
from sys import stdout as STDOUT
def palindrome(word):
"""Return True if the given word is a palindrome."""
return word == word[::-1]
assert palindrome('tacocat')
assert not palindrome('banana')
print(repr(palindrome.__doc__))
"""Library for testing words for v... |
"""
According to: https://leetcode.com/discuss/88153/another-python
Draw a line of length a. Then draw further lines of lengths b, c, etc.
How does the a-line get crossed?
From the left by the d-line or from the right by the f-line.
b b
+----------------+ +-... |
import traceback
import sys
from pprint import pprint
from traceback_example import produce_exception
try:
produce_exception()
except Exception as err:
print('format_exception():')
exc_type, exc_value, exc_tb = sys.exc_info()
pprint(
traceback.format_exception(exc_type, exc_value, exc_tb),
... |
"""
只能用递归不能用其他数据结构来逆序一个栈。
可以用另一个新栈的话比较容易。
"""
from GetMinStack import Stack
def reverseStack(stacks):
new_stack = Stack()
def helper(stacks):
if stacks.empty():
return
new_stack.push(stacks.pop())
helper(stacks)
helper(stacks)
return new_stack
a = range(... |
def to_upper_case(s):
return str(s).upper()
def print_iterator(it):
for x in it:
print(x, end=' ')
print('')
map_iterator = map(to_upper_case, 'abc')
print(type(map_iterator))
print_iterator(map_iterator)
map_iterator = map(to_upper_case, (1, 'a', 'abc'))
print_iterator(map_iterator)
... |
"""
Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.
You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You c... |
programmers = dict(bob=['JS', 'PHP', 'Python', 'Perl', 'Java'],
tim=['Python', 'Haskell', 'C++', 'JS'],
sara=['Perl', 'C', 'Java', 'Python', 'JS'],
paul=['C++', 'JS', 'Python'])
def common_languages(programmers):
"""Receive a dict of keys -> names and values -> a seq... |
import logging
import logging.config
logging.config.fileConfig(fname='file.conf', disable_existing_loggers=False)
logger = logging.getLogger(__name__)
logger.debug('This is a debug message')
|
class Solution(object):
def isPalindrome(self, head):
slow, fast, new_head = head, head, None
while fast and fast.next:
fast = fast.next.next
new_head, new_head.next, slow = slow, new_head, slow.next
""" More general way
... |
import shutil
shutil.copytree('data_1', 'data1_backup')
|
class Solution:
def permuteUnique(self, num):
length = len(num)
if length == 0:
return []
if length == 1:
return [num]
num.sort()
res = []
previousNum = None
for i in range(length):
if num[i] == previousNum... |
def test_case1():
list1 = [ 1, 2, 3]
list2 = [ 'a', 'b', 'c']
list3 = [ 'red', 'blue', 'green']
result = zip(list1, list2, list3)
print(type(result))
for e in result:
print(e)
print(type(e))
def test_case2():
list1 = [ 1, 2, 3]
list2 = [ 'a', 'b', 'c']
... |
from pathlib import Path
path = Path('C:/Users/Jano/Documents')
dirs = [e for e in path.iterdir() if e.is_dir()]
print(dirs)
|
def Recurgcd(a, b):
low = min(a, b)
high = max(a, b)
if low == 0:
return high
elif low == 1:
return 1
else:
return Recurgcd(low, high%low)
print(Recurgcd(12,14))
|
string = input('Enter a string: ')
if string:
print('The string is {}'.format(string))
number = int(input('Enter a number: '))
if number:
print('Число не равно нулю')
else:
print('Число равно нулю') |
class Shape:
def __init__(self, color, is_polygon, description):
self.color = color
self.is_polygon = is_polygon
self.description = description
def display_data(self):
print(f"\n=== {self.description.capitalize()} ===")
print("Color:", self.color)
print("Is the ... |
def foo(number):
return dict(sign = "positive" if number > 0 else
("negative" if number < 0 else "zero"),
parity = "odd" if number % 2 == 1 else
("even" if number % 2 == 0 else "non integer")) |
answer = [person[0] for person in ["Elie", "Tim", "Matt"]]
answer2 = [val for val in [1, 2, 3, 4, 5, 6] if val % 2 == 0]
print(answer)
answer = []
for person in ["Elie", "Tim", "Matt"]:
answer.append(person[0])
answer2 = []
for num in [1, 2, 3, 4, 5, 6]:
if num % 2 == 0:
answer2.append(num)
|
class NoMixedCaseMeta(type):
def __new__(cls, clsname, bases, clsdict):
for name in clsdict:
if name.lower() != name:
raise TypeError('Bad attribute name: ' + name)
return super().__new__(cls, clsname, bases, clsdict)
class Root(metaclass=NoMixedCaseMeta):
pass
cl... |
"""
Given two sentences that each contains words in case insensitive way, you have to check the
common case insensitive words appearing in both sentences.
If there are duplicate words in the results, just choose one. The results should be
sorted by words length.
The sentences are presented as list of words. Example:
... |
class Solution(object):
def rob(self, nums):
if not nums:
return 0
pre_rob = 0
pre_not_rob = 0
for num in nums:
cur_rob = pre_not_rob + num
cur_not_rob = max(pre_rob, pre_not_rob)
pre_rob = cur_rob
pre_not_rob = cur... |
print(type("Hey".replace("ey","i")[-1]))
print("Hey".replace("ey","i")[-1])
|
row_num = int(input("Input number of rows: "))
col_num = int(input("Input number of columns: "))
multi_list = [[0 for col in range(col_num)] for row in range(row_num)]
for row in range(row_num):
for col in range(col_num):
multi_list[row][col]= row*col
print(multi_list)
|
def concat(x, y):
return '{} {}'.format(x, y)
def sum_3_elem(a, b, c):
return a + b + c
def multiply_3_elem(a, b, c):
return a * b * c
def test_concat():
assert concat(1, 2) == '1 2'
assert concat(10, 20) == '10 20'
def test_sum_3_elem():
assert sum_3_elem(0, 2, 3) == 5
assert sum_3_... |
start = 1
stop = 10
mult_list = [ [i * j
for j in range(start, stop+1)]
for i in range(start, stop+1)]
mult_list
start = 1
stop = 10
mult_list = ( (i * j
for j in range(start, stop+1))
for i in range(start, stop+1))
mult_list
table = list(mult_list)... |
import argparse
import logging
import sys
logging.basicConfig(filename='ex2_log.log', level=logging.DEBUG)
def simple_parser():
logging.info("Command Line inputs: " + ' '.join(sys.argv[1:]))
parser = argparse.ArgumentParser()
parser.add_argument('A', type=int)
parser.add_argument('B', type=... |
class Solution(object):
def isMatch(self, s, p):
"""
Dynamic Programming
dp[i][j] represents isMatch(p[0...i], s[0...j]), default is False;
dp[i][-1] represents isMatch(p[0...i], "")
dp[-1][j] represents isMatch("", s[0...j])
"""
if not s:
... |
print('That is %s %s bird!' % (1, 'dead'))
print('The knights who say %s!' % 'exclamation')
print('%d %s %g you' % (1, 'spam', 4.0))
print('%s -- %s -- %s' % (42, 3.14159, [1, 2, 3]))
|
parent = MagicMock()
child1 = MagicMock(return_value=None)
child2 = MagicMock(return_value=None)
parent.child1 = child1
parent.child2 = child2
child1(1)
child2(2)
parent.mock_calls
mock = MagicMock()
not_a_child = MagicMock(name='not-a-child')
mock.attribute = not_a_child
mock.attrib... |
print({x: x * x for x in range(10)})
print({x * x for x in range(10)})
set(x * x for x in range(10))
print({x: x * x for x in range(10)})
print(dict((x, x * x) for x in range(10)))
res = set()
for x in range(10):
res.add(x * x)
print(res)
res = {}
for x in range(10):
res[x] = x * x
print(res)
... |
from collections import OrderedDict
d = OrderedDict()
d['z'] = 'hello'
d['y'] = 'world'
d['a'] = 'python'
d
for key in d:
print(key)
for key in reversed(d):
print(key)
d = {'a': 1, 'b': 2}
d = OrderedDict()
d['first'] = 10
d['second'] = 20
d['third'] = 30
d['last... |
class Solution(object):
def reorderList(self, head):
"""
Firstly, use two pointer to find the mid node_keep,
Then reverse the post half nodes, and merge the pre half and
post reversed half.
"""
if not head or not head.next or not head.next.next:
... |
import re
def capitalize_sentences(text: str) -> str:
'''Returns sentence with correct capitalisation.'''
def upper_it(m):
return m.group().upper()
sentence = re.split(r'([!?.])\s', text)
output = ' '.join([re.sub(r'^\w', upper_it, line) for line in sentence])
return re.sub(r'\s([?.!])', r'... |
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
nums_size = len(nums)
start = 0
end = nums_size - 1
while start <= end:
mid = (start + end) / 2
n... |
def add(x, to=1):
return x + to
def divide(x, by=2):
return x / by
def square(x):
return x ** 2
def invalid_op(x):
raise Exception("Invalid operation")
def perform_operation(x, chosen_operation, operation_args=None):
operation_args = operation_args or {}
ops = {
"add": add,... |
def count_from_zero_to_n(n):
if n < 0:
raise ValueError('Input should be a non-negative integer')
for x in range(0, n+1):
print(x) |
def titleize(string):
return ' '.join(s[0].upper() + s[1:] for s in string.split(' '))
def find_factors(num):
factors = []
i = 1
while (i <= num):
if (num % i == 0):
factors.append(i)
i += 1
return factors
def includes(item, val, start=None):
if ty... |
"""
You have a list of words and a pattern, and you want to know which words in words matches the pattern.
A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word.
(Recall that a permutation of letters is a bijectio... |
from collections import OrderedDict
def calc_median_from_dict(d: dict) -> float:
"""
:param d: dict of numbers and their occurrences
:return: float: median
Example:
{1: 2, 3: 1, 4: 2} -> [1, 1, 3, 4, 4] --> 3 is median
"""
values_sorted = dict(OrderedDict(sorted(d.items(), key=lambda t: t[... |
from collections import defaultdict
names = 'bob julian tim martin rod sara joyce nick beverly kevin'.split()
ids = range(len(names))
users = dict(zip(ids, names))
friendships = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3),
(3, 4), (4, 5), (5, 6), (5, 7), (5, 9),
(6, 8), (7, 8), (8, 9)]
... |
import re
class DomainException(Exception):
"""Raised when an invalid is created."""
class Domain:
def __init__(self, name):
self.name = name
if not re.match(r'.*\.[a-z]{2,3}$', self.name):
raise DomainException
@classmethod
def... |
def get_username():
while True:
username = input("Please type in the name 'PyBites':")
if username == "PyBites":
break
else:
print("Invalid username.") |
print("Input lengths of the triangle sides: ")
x = int(input("x: "))
y = int(input("y: "))
z = int(input("z: "))
if x == y == z:
print("Equilateral triangle")
elif x != y != z:
print("Scalene triangle")
else:
print("isosceles triangle")
|
from collections import defaultdict
_punct = '.,;?:'
def _normalize(fragment):
fragment = fragment.lower()
while len(fragment) > 0 and fragment[-1] in _punct:
fragment = fragment[:-1]
while len(fragment) > 0 and fragment[0] in _punct:
fragment = fragment[1:]
return fragment
def numwords... |
"""
Interface Segregation Principle
bad - Circle class does not need draw_rectangle and draw_square.
if we want to add new shapes, we have to change all classes.
"""
class IShape:
def draw_square(self):
raise NotImplementedError
def draw_rectangle(self):
raise NotImplementedError
def ... |
from unittest.mock import MagicMock
thing = ProductionClass()
thing.method = MagicMock(return_value=3)
thing.method(3, 4, 5, key='value')
thing.method.assert_called_with(3, 4, 5, key='value')
mock = Mock(side_effect=KeyError('foo'))
mock()
values = {'a': 1, 'b': 2, 'c': 3}
def side_effec... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
dummy = ListNode(0)
pointer = dummy
while l1 !=None and l2 !=None:
if l1.val<l2.val:
pointer.next = l1
... |
def extract_non_ascii_words(text):
"""Filter a text returning a list of non-ascii words"""
words = text.split()
result = []
for word in words:
try:
word.encode('ascii')
except Exception as e:
print(e)
result.append(word)
return result
|
def get_index_different_char(chars):
correct = [correct
for correct in str(chars)
if correct.isalnum()]
not_correct = [not_correct
for not_correct in chars
if not str(not_correct).isalnum()]
if len(correct) > len(not_correct):
not_c... |
def calculateGrade():
totalScore = midtermScore + finalScore + assignmentScore
averageScore = totalScore / 3
if averageScore >= 90:
grade = "A"
elif averageScore >= 80:
grade = "B"
elif averageScore >= 70:
grade = "C"
elif averageScore >= 60:
grade = "D"
el... |
class A(object):
def __init__(self, i, **kwargs):
super(A, self).__init__(**kwargs)
self.i = i
def run(self, value):
return self.i * value
class B(A):
def __init__(self, j, **kwargs):
super(B, self).__init__(**kwargs)
self.j = j
def run(self, value):
retu... |
import time
from random import Random
matrix_size = 200
matrix_a = [[0] * matrix_size for a in range(matrix_size)]
matrix_b = [[0] * matrix_size for b in range(matrix_size)]
result = [[0] * matrix_size for r in range(matrix_size)]
random = Random()
def generate_random_matrix(matrix):
for row in range(matri... |
import re
items = ["example (.com)", "w3resource", "github (.com)", "stackoverflow (.com)"]
for item in items:
print(re.sub(r" ?\([^)]+\)", "", item))
|
class Solution(object):
def sortColors(self, nums):
len_n = len(nums)
pos_put_0 = 0
pos_put_2 = len_n - 1
index = 0
while index <= pos_put_2:
if nums[index] == 0:
nums[index], nums[pos_put_0] = nums[pos_put_0], nums[index]
... |
print((1, 2) + (3, 4))
print((1, 2)) * 4
T = (1, 2, 3, 4)
print(T[0], T[1:3])
|
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
carry_in = 0
head = ListNode(0)
... |
from functools import wraps
def int_args(func):
@wraps(func)
def wrapper(*args):
for arg in args:
if type(arg) != int:
raise TypeError("All arguments passed in must be integers")
if arg <0:
raise ValueError("All arguments mu... |
import sqlite3
def insertMultipleRecords(recordList):
try:
sqliteConnection = sqlite3.connect('SQLite_Python.db')
cursor = sqliteConnection.cursor()
print("Connected to SQLite")
sqlite_insert_query = """INSERT INTO SqliteDb_developers
(id, name, email, joi... |
print(list(range(11)))
print(list(range(1, 16)))
print(list(range(15, 0, -1)))
import random
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(random.sample(arr, 3))
print(random.sample(range(300), 5))
|
"""
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Return:
[
[5,4,11,2],
[5,8,4,5]
]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.