blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
e1ebae30cf58ae268c07ffa4f088c1b5dc3fe644 | gersongroth/maratonadatascience | /Semana 01/01 - Estruturas Sequenciais/10.py | 121 | 3.921875 | 4 | celsius = float(input("Informe a temperatura em celsius: "))
f = celsius * 9 / 5 + 32
print("%.1f graus Farenheit" % f) |
b2612751a0971f2191f1d65bd3e987ce611e9fb9 | DabicD/Studies | /The_basics_of_scripting_(Python)/Exercise2.py | 853 | 3.8125 | 4 | # Exercise description:
#
# "Napisz program drukujący na ekranie kalendarz na zadany miesiąc dowolnego roku
# (użytkownik wprowadza informację postaci: czerwiec 1997–nazwa miesiąca w języku polskim)."
#
##############################################################################################
import locale
locale.setlocale(locale.LC_ALL, 'pl')
import calendar
polishMonths = {
"styczen": 1,
"luty": 2,
"marzec": 3,
"kwiecien": 4,
"maj":5,
"czerwiec":6,
"lipiec":7,
"sierpien":8,
"wrzesien":9,
"pazdziernik":10,
"listopad":11,
"grudzien":12
}
try:
x1 = int(input("Year:"))
x2 = input("Month:")
cal = calendar.TextCalendar(calendar.MONDAY)
text = cal.formatmonth(x1, polishMonths[x2])
print(text)
except:
print("Wrong input")
|
b5a42001ab9ec5ec13c1c0538824fdcc1d9e4b83 | MarinaSergeeva/Algorithms | /day02_dijkstra.py | 1,301 | 3.78125 | 4 | import heapq
from math import inf
def dijkstra(graph, source):
visited = set([source])
distances = {v: inf for v in graph}
# parents = {v: None for v in graph}
distances[source] = 0
for (v, w) in graph[source]:
distances[v] = w
# parents[v] = source
vertices_heap = [(w, v) for (v, w) in graph[source]]
heapq.heapify(vertices_heap)
while len(visited) != len(graph):
(weight, next_vertex) = heapq.heappop(vertices_heap)
while next_vertex in visited:
(weight, next_vertex) = heapq.heappop(vertices_heap)
distances[next_vertex] = weight
visited.add(next_vertex)
for (v, w) in graph[next_vertex]:
if v not in visited:
new_distance = w + distances[next_vertex]
if new_distance < distances[v]:
distances[v] = new_distance
# parents[v] = next_vertex
heapq.heappush(vertices_heap, (new_distance, v))
return distances
def test_dijkstra():
graph = {0: [(1, 1), (2, 8), (3, 2)],
1: [(4, 6)],
2: [(4, 1)],
3: [(2, 3)],
4:[]}
res = {0: 0, 1: 1, 3: 2, 2: 5, 4: 6}
assert dijkstra(graph, 0) == res
if __name__ == "__main__":
test_dijkstra()
|
578a7c30e7e0df3e7e086223575e1a682f4c200e | MarinaSergeeva/Algorithms | /day12_median_maintenance.py | 1,415 | 3.765625 | 4 | import heapq
class MedianMaintainer:
def __init__(self):
self._minheap = [] # for smallest half of fthe array, uses negated numbers
self._maxheap = [] # for largest half of the array
self.median = None # if similar number of elements - use value form maxheap
def insert_element(self, el):
if len(self._minheap) == 0 and len(self._maxheap) == 0:
self._maxheap.append(el)
self.median = el
else:
if el >= self._maxheap[0]:
heapq.heappush(self._maxheap, el)
if len(self._maxheap) > len(self._minheap) + 1:
el_to_move = heapq.heappop(self._maxheap)
heapq.heappush(self._minheap, -el_to_move)
else:
heapq.heappush(self._minheap, -el)
if len(self._minheap) > len(self._maxheap):
el_to_move = - heapq.heappop(self._minheap)
heapq.heappush(self._maxheap, el_to_move)
self.median = self._maxheap[0]
def get_median(self):
return self.median
def test_maintain_median():
myMedianMaintainer = MedianMaintainer()
input_array = [1, 5, 7, 3, 4]
expected_medians = []
for el in input_array:
myMedianMaintainer.insert_element(el)
expected_medians.append(myMedianMaintainer.get_median())
assert expected_medians == [1, 5, 5, 5, 4]
|
023911c5beb0dc2cdb8b29f5f4447b6198a85b33 | MarinaSergeeva/Algorithms | /day07_quicksort.py | 757 | 3.921875 | 4 | def partition(array, low, high):
# uses array[low] element for the partition
pivot = array[low]
repl_index = low
for i in range(low + 1, high):
if array[i] < pivot:
repl_index += 1
array[i], array[repl_index] = array[repl_index], array[i]
array[low], array[repl_index] = array[repl_index], array[low]
return repl_index
def quick_sort(array, low=0, high=None):
if high is None:
high = len(array)
if low < high - 1:
partition_index = partition(array, low, high)
quick_sort(array, low, partition_index)
quick_sort(array, partition_index + 1, high)
def test_quicksort():
my_list = [3, 8, 1, 5, 2]
quick_sort(my_list)
assert my_list == [1, 2, 3, 5, 8]
|
5d185a1960ee3b49934bf30e2e03a48c5ac09db7 | HSabbir/Python-Challange | /day 1.py | 155 | 4.15625 | 4 | ## Print Multiplication table
number = int(input("Enter Your Number: "))
for i in range(10):
print(str(i+1)+' * '+str(number)+' = '+str(number*(i+1))) |
348084b89a6dda4fd185da2863c05cb4cb3b4a3f | Vrittik/LINEAR_REGRESSION_FROM_SCRATCH | /SLR_By_calc.py | 772 | 3.6875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from statistics import mean
from ML_library import mlSkies
dataset=pd.read_csv("Salary_Data.csv")
X=dataset.iloc[:,0].values
y=dataset.iloc[:,1].values
X_train,X_test,y_train,y_test = mlSkies.train_test_split(X,y,split_index=0.2)
X_train=np.array(X_train , dtype=np.float64)
X_test=np.array(X_test, dtype=np.float64)
y_train=np.array(y_train , dtype=np.float64)
y_test=np.array(y_test , dtype=np.float64)
m,b=mlSkies.linear_regression(X_train,y_train)
mlSkies.plot_regression_line(X_train,y_train,m,b)
y_pred=mlSkies.linear_regression_predict(7,m,b)
print("The estimated salary for",7,"years of experience is",y_pred,"rupees")
|
89c3903452e5ee6c194159e3a3311fbe2d6ba04d | davidlowryduda/pynt | /pynt/base.py | 4,086 | 4.03125 | 4 | """
base.py
=======
Fundamental components for a simple python number theory library.
License Info
============
(c) David Lowry-Duda 2018 <davidlowryduda@davidlowryduda.com>
This is available under the MIT License. See
<https://opensource.org/licenses/MIT> for a copy of the license,
or see the home github repo
<https://github.com/davidlowryduda/pynt>.
"""
from typing import List, Tuple, Union
from itertools import product as cartesian_product
import numpy
def gcd(num1: int, num2: int) -> int:
"""
Returns the greatest common divisor of `num1` and `num2`.
Examples:
>>> gcd(12, 30)
6
>>> gcd(0, 0)
0
>>> gcd(-1001, 26)
13
"""
if num1 == 0:
return num2
if num2 == 0:
return num1
if num1 < 0:
num1 = -num1
if num2 < 0:
num2 = -num2
# This is the Euclidean algorithm
while num2 != 0:
num1, num2 = num2, num1 % num2
return num1
def smallest_prime_divisor(num: int, bound: Union[int, None] = None) -> int:
"""
Returns the smallest prime divisor of the input `num` if that divisor is
at most `bound`. If none are found, this returns `num`.
Input:
num: a positive integer
bound: an optional bound on the size of the primes to check. If not
given, then it defaults to `num`.
Output:
The smallest prime divisor of `num`, or `num` itself if that divisor is
at least as large as `bound`.
Raises:
ValueError: if num < 1.
Examples:
>>> smallest_prime_divisor(15)
3
>>> smallest_prime_divisor(1001)
7
"""
if num < 1:
raise ValueError("A positive integer is expected.")
if num == 1:
return num
for prime in [2, 3, 5]:
if num % prime == 0:
return prime
if bound is None:
bound = num
# Possible prime locations mod 2*3*5=30
diffs = [6, 4, 2, 4, 2, 4, 6, 2]
cand = 7
i = 1
while cand <= bound and cand*cand <= num:
if num % cand == 0:
return cand
cand += diffs[i]
i = (i + 1) % 8
return num
# primesfrom2to(n) from
# https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n
def primes(limit):
"""
Returns the numpy array of primes up to (and not including) `limit`.
Examples:
>>> primes(10)
array([2, 3, 5, 7])
"""
sieve = numpy.ones(limit // 3 + (limit % 6 == 2), dtype=numpy.bool)
for i in range(1, int(limit ** 0.5) // 3 + 1):
if sieve[i]:
k = (3 * i + 1) | 1
sieve[k * k // 3::2 * k] = False
sieve[k * (k - 2 * (i & 1) + 4) // 3:: 2 * k] = False
return numpy.r_[2, 3, ((3 * numpy.nonzero(sieve)[0][1:] + 1) | 1)]
def factor(num: int) -> List[Tuple[int, int]]:
"""
Returns the factorization of `num` as a list of tuples of the form (p, e)
where `p` is a prime and `e` is the exponent of that prime in the
factorization.
Input:
num: an integer to factor
Output:
a list of tuples (p, e), sorted by the size of p.
Examples:
>>> factor(100)
[(2, 2), (5, 2)]
>>> factor(-7007)
[(7, 2), (11, 1), (13, 1)]
>>> factor(1)
[]
"""
if num in (-1, 0, 1):
return []
if num < 0:
num = -num
factors = []
while num != 1:
prime = smallest_prime_divisor(num)
exp = 1
num = num // prime
while num % prime == 0:
exp += 1
num = num // prime
factors.append((prime, exp))
return factors
def factors(num: int) -> List[int]:
"""
Returns the list of factors of an integer.
Examples:
>>> factors(6)
[1, 2, 3, 6]
>>> factors(30)
[1, 2, 3, 5, 6, 10, 15, 30]
"""
factorization = factor(num)
primes_, exps = zip(*factorization)
exp_choices = cartesian_product(*[range(exp+1) for exp in exps])
ret = []
for exp_choice in exp_choices:
val = 1
for prime, exp in zip(primes_, exp_choice):
val *= (prime**exp)
ret.append(val)
return sorted(ret)
|
0685f7856c0b7032a146198548e1db5dc3a0bbad | numblr/glaciertools | /test/treehash/algorithm_test.py | 2,242 | 3.53125 | 4 | #!/usr/bin/python
from pprint import pprint
def next_itr(last):
for i in range(1, last + 1):
yield str(i)
def calculate_root(level, itr):
# Base case level
if level == 0:
return next(itr, None)
left = calculate_root(level - 1, itr)
right = calculate_root(level - 1, itr)
return combine(left, right) if right else left
def calculate_hash(left, level, itr):
if not left:
left = calculate_root(0, itr)
return calculate_hash(left, 0, itr) if left else None
right = calculate_root(level, itr)
return calculate_hash(combine(left, right), level + 1, itr) if right else left
def combine(a, b):
return "[" + ",".join([a,b]) + "]"
if __name__ == '__main__':
def assertEquals(a, b):
if not a == b:
raise ValueError(a + " - " + b)
assertEquals(calculate_hash(None, 0, next_itr(2)), "[1,2]")
assertEquals(calculate_hash(None, 0, next_itr(3)), "[[1,2],3]")
assertEquals(calculate_hash(None, 0, next_itr(4)), "[[1,2],[3,4]]")
assertEquals(calculate_hash(None, 0, next_itr(5)), "[[[1,2],[3,4]],5]")
assertEquals(calculate_hash(None, 0, next_itr(6)), "[[[1,2],[3,4]],[5,6]]")
assertEquals(calculate_hash(None, 0, next_itr(7)), "[[[1,2],[3,4]],[[5,6],7]]")
assertEquals(calculate_hash(None, 0, next_itr(8)), "[[[1,2],[3,4]],[[5,6],[7,8]]]")
assertEquals(calculate_hash(None, 0, next_itr(9)), "[[[[1,2],[3,4]],[[5,6],[7,8]]],9]")
assertEquals(calculate_hash(None, 0, next_itr(10)), "[[[[1,2],[3,4]],[[5,6],[7,8]]],[9,10]]")
assertEquals(calculate_hash(None, 0, next_itr(11)), "[[[[1,2],[3,4]],[[5,6],[7,8]]],[[9,10],11]]")
assertEquals(calculate_hash(None, 0, next_itr(12)), "[[[[1,2],[3,4]],[[5,6],[7,8]]],[[9,10],[11,12]]]")
assertEquals(calculate_hash(None, 0, next_itr(13)), "[[[[1,2],[3,4]],[[5,6],[7,8]]],[[[9,10],[11,12]],13]]")
assertEquals(calculate_hash(None, 0, next_itr(14)), "[[[[1,2],[3,4]],[[5,6],[7,8]]],[[[9,10],[11,12]],[13,14]]]")
assertEquals(calculate_hash(None, 0, next_itr(15)), "[[[[1,2],[3,4]],[[5,6],[7,8]]],[[[9,10],[11,12]],[[13,14],15]]]")
assertEquals(calculate_hash(None, 0, next_itr(16)), "[[[[1,2],[3,4]],[[5,6],[7,8]]],[[[9,10],[11,12]],[[13,14],[15,16]]]]")
|
5f4b7dc66789528b881bc081632e8b54fc6192f3 | bubblegumsoldier/kiwi | /kiwi-user-manager/app/lib/username_validator.py | 333 | 3.546875 | 4 | import re
username_min_string_length = 5
username_max_string_length = 30
username_regex = "^[a-zA-Z0-9_.-]+$"
def validate(username):
if not username_min_string_length <= len(username) <= username_max_string_length:
return False
if not re.match(username_regex, username):
return False
return True |
2280d3663399e1dcd1dc76de2ee713c3416c484d | ash-fu/coursera-algo | /Assign2.py | 1,711 | 3.703125 | 4 | count = 0
def mergeSort(alist):
# print("Splitting ",alist)
global count
# count = 0
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
# splitSort(lefthalf, righthalf,count)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
# print('inversion discover: ',len(lefthalf))
count=count+ (len(lefthalf) - i)
# print('count', count)
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
# print("Merging ",alist)
# def splitSort(left, right):
# i = 0
# j = 0
# k = 0
fname = 'list_67.txt'
with open(fname) as f:
content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
alist = [x.strip() for x in content]
# print alist
# alist = [ 4, 80, 70, 23, 9, 60, 68, 27, 66, 78, 12, 40, 52, 53, 44, 8, 49, 28, 18, 46, 21, 39, 51, 7, 87, 99, 69, 62, 84, 6, 79, 67, 14, 98, 83, 0, 96, 5, 82, 10, 26, 48, 3, 2, 15, 92, 11, 55, 63, 97, 43, 45, 81, 42, 95, 20, 25, 74, 24, 72, 91, 35, 86, 19, 75, 58, 71, 47, 76, 59, 64, 93, 17, 50, 56, 94, 90, 89, 32, 37, 34, 65, 1, 73, 41, 36, 57, 77, 30, 22, 13, 29, 38, 16, 88, 61, 31, 85, 33, 54 ]
mergeSort(alist)
# print(alist)
print count |
f3ae407a822f0cd36fdfb490b705e35cd2a275d6 | SaraZ3964/Python | /pybank.py | 420 | 3.625 | 4 | import pandas as pd
file = "budget_data.csv"
data_df = pd.read_csv(file)
data_df.head()
Months = data_df["Date"].count()
Sum = data_df["Profit/Losses"].sum()
Ave = data_df["Profit/Losses"].mean()
Max = data_df["Profit/Losses"].max()
Min = data_df["Profit/Losses"].min()
print("Months:" + str(Months))
print("Total: " + str(Sum))
print("Average: "+ str(Ave))
print("Maximum: " + str(Max))
print("Minmium:" + str(Min))
|
37238eb1a843fb3a7d5e1d36364bf3f0b1bbd7ee | kylehovey/kylehovey.github.io | /spel3o/files/geohash.py | 2,354 | 3.8125 | 4 | import webbrowser
import math
ImTheMap = input("would you like a map site to look up your coordinates? ")
if ImTheMap == "yes":
print('look up your current location on this website')
webbrowser.open("https://csel.cs.colorado.edu/~nishimot/point.html")
else:
print('''okay then, let's continue''')
Lat = input('''Please input your current LATITUDE with spaces inbetween,
and zeros as placeholders. (ex: 32 05 12.20) ''')
if len(Lat) != 11:
print("entered incorrectly, quitting")
raise IOError('Wrong coordinate format')
else:
LatDeg = float(Lat[:2])
LatMin = float(Lat[3:5])
LatSec = float(Lat[6:])
Long = input('''Please input your current LONGITUDE with spaces inbetween,
and zeros as placeholders. (ex: 120 05 12.20) ''')
if len(Long) == 11:
LongDeg = float(Long[:2])
LongMin = float(Long[3:5])
LongSec = float(Long[7:])
elif len(Long) == 12:
LongDeg = float(Long[:3])
LongMin = float(Long[4:6])
LongSec = float(Long[6:])
else:
print("entered incorrectly, quitting")
raise IOError('Wrong coordinate format')
Cal = input("please enter the current date in MM/DD/YY format (ex: 03/06/11) ")
mm = int(Cal[:2])
dd = int(Cal[3:5])
yy = int(Cal[6:])
Prank = input("please confess yourself of all mortal sins ")
Prank = input('''oh come on, be honest ;) ''')
print('''haha.. just joking ;) Now, let's continue.''')
Prank = 0
val = (dd - mm) * yy
if val <= 48:
val = (val/60)*10
elif val >= 48:
val = (val/60)*4
if dd % 2 == 0:
val = -val
else:
val = val
longval = val * 0.18526362353047317310282957646406309593963452838196423660508102562977229905562196608078556292556795045922591488273554788881298750625
longval = round(longval, 1)
if val >= 8:
val = 8;
else:
val = val
lad = LatDeg
lam = LatMin + round(val, 1)
las = LatSec + val * 10
lod = LongDeg
lom = LongMin + round(val, 1)
los = LongSec + val*10
jumpthegun = 0
jumpthegunlong = 0
if las >= 60:
jumpthegun = 1
las = 59
else:
las = las
if los >= 60:
jumpthegunlong = 1
los = 59
else:
los = los
lam = round(lam, 1) + jumpthegun
lom = round(lom, 1) + jumpthegunlong
lom = lom - 5
las = round(las, 2)
los = round(los, 2)
final = input('''hit enter to see results ''')
print('''Your local geohash of the day is:''')
print('Latitude:')
print(lad, lam, las)
print('Longitude:')
print(lod, lom, los)
|
06abfdc014c7ef45be7f8c1ac53007c49983062c | TheAutomationWizard/learnPython | /pythonUdemyCourse/Concepts/General Concepts/slicing.py | 543 | 4.09375 | 4 | list = [1, 2, 34, 4, 56, 7, 8, 99, 2]
def various_slicing_in_python(list_object):
"""
slicing operations in python
:param list_object:
:return:
slice (Start, end , step)
"""
# Using slice method
print(list_object[slice(0, 4, 1)])
# Using index slicing +==> [start : stop+1 : steps]
# Step sign(+ or -), must be sign of stop+1 -start
print(list_object[::-1])
# Negative Indexing to slice
print(list_object[-1:-4:-1])
if __name__ == '__main__':
various_slicing_in_python(list)
|
4bf52a9a6adb7f222b981d2c48c51cd912324faa | TheAutomationWizard/learnPython | /pythonUdemyCourse/Concepts/OOPS/Inheritance/FiguresExample.py | 1,227 | 3.953125 | 4 | class Quadrilateral:
def __init__(self, length, height):
self.length = length
self.height = height
def quad_area(self):
area_ = self.length * self.height
print(f'Area of Quadrilateral with length {self.length} and height : {self.height} is = {area_}')
return area_
class Square(Quadrilateral):
def __init__(self, length):
super().__init__(length, length)
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
area_ = 3.14 * self.radius * self.radius
print(f'Area of circle with radius {self.radius} is = {area_}')
return area_
class Cylinder(Circle, Square):
def __init__(self, radius, height , *args, **kwargs):
self.radius = radius
self.height = height
def area(self):
base_area1 = super().area() * 2
base_length = 3.14 * self.radius * 2 * self.height
self.length = self.radius
quad_area = super().quad_area()
return base_area1 + base_length
radius = 2
height = 5
myCylinder = Cylinder(radius=radius, height=height)
print(myCylinder.area())
# print(2 * 3.14 * radius * (radius + height))
# print(2 * 3.14 * radius * height)
|
18d811c538e2db5846bdf7caf92fbca0eaac8f44 | TheAutomationWizard/learnPython | /pythonUdemyCourse/Concepts/OOPS/Inheritance/PythonicInheritance.py | 1,119 | 4.03125 | 4 | class A(object):
def __init__(self, a, *args, **kwargs):
print('I (A) am called from B super()')
print("A", a)
class B(A):
def __init__(self, b, *args, **kwargs):
print('As per inverted flow, i am called from class A1 super()')
super(B, self).__init__(*args, **kwargs)
print("B", b)
class A1(A):
def __init__(self, a1, *args, **kwargs):
print('A1 super will call, B super now! But without positional parameter "b" in super()')
super(A1, self).__init__(*args, **kwargs)
print("A1", a1)
class B1(A1, B):
def __init__(self, b1, *args, **kwargs):
super(B1, self).__init__(*args, **kwargs)
print("B1", b1)
B1(a1=6, b1=5, b="hello", a=None)
# *************************************
# Understand flow of kwargs & args
# *************************************
def ab(x, a=10, a1=20, **kwargs):
print(f'Value of x : {x}')
print(f'Value of a : {a}')
print(f'Value of a1 : {a1}')
print('value of kwargs')
print(kwargs)
kwarg_dict = {'x': 200, 'a': 50, 'a1': 100, 'b': 1000, 'c': 101}
ab(**kwarg_dict)
|
cc1812713296f1e020d7a5d426397c2f54622232 | fanying2015/algebra | /algebra/quadratic.py | 407 | 3.78125 | 4 |
def poly(*args):
"""
f(x) = a * x + b * x**2 + c * x**3 + ...
*args = (x, a, b)
"""
if len(args) == 1:
raise Exception("You have only entered a value for x, and no cofficients.")
x = args[0] # x value
coef = args[1:]
results = 0
for power, c in enumerate(coef):
results += c * (x ** (power + 1))
return results |
38d2e2e55b3ac7a05246a18367a4c82c4bd95cc8 | BOUYAHIA-AB/DeepSetFraudDetection | /split_data.py | 4,321 | 3.5 | 4 | """Build vocabularies of words and tags from datasets"""
from collections import Counter
import json
import os
import csv
import sys
import pandas as pd
def load_dataset(path_csv):
"""Loads dataset into memory from csv file"""
# Open the csv file, need to specify the encoding for python3
use_python3 = sys.version_info[0] >= 3
data = pd.load_csv(path_csv)
with (open(path_csv, encoding="windows-1252") if use_python3 else open(path_csv)) as f:
csv_file = csv.reader(f, delimiter=';')
dataset = []
words, tags = [], []
# Each line of the csv corresponds to one word
for idx, row in enumerate(csv_file):
if idx == 0: continue
sentence, word, pos, tag = row
# If the first column is non empty it means we reached a new sentence
if len(sentence) != 0:
if len(words) > 0:
assert len(words) == len(tags)
dataset.append((words, tags))
words, tags = [], []
try:
word, tag = str(word), str(tag)
words.append(word)
tags.append(tag)
except UnicodeDecodeError as e:
print("An exception was raised, skipping a word: {}".format(e))
pass
return dataset
def save_dataset(dataset, save_dir):
"""Writes sentences.txt and labels.txt files in save_dir from dataset
Args:
dataset: ([(["a", "cat"], ["O", "O"]), ...])
save_dir: (string)
"""
# Create directory if it doesn't exist
print("Saving in {}...".format(save_dir))
if not os.path.exists(save_dir):
os.makedirs(save_dir)
# Export the dataset
with open(os.path.join(save_dir, 'sentences.txt'), 'w') as file_sentences:
with open(os.path.join(save_dir, 'labels.txt'), 'w') as file_labels:
for words, tags in dataset:
file_sentences.write("{}\n".format(" ".join(words)))
file_labels.write("{}\n".format(" ".join(tags)))
print("- done.")
def save_dict_to_json(d, json_path):
"""Saves dict to json file
Args:
d: (dict)
json_path: (string) path to json file
"""
with open(json_path, 'w') as f:
d = {k: v for k, v in d.items()}
json.dump(d, f, indent=4)
def update_vocab(txt_path, vocab):
"""Update word and tag vocabulary from dataset
Args:
txt_path: (string) path to file, one sentence per line
vocab: (dict or Counter) with update method
Returns:
dataset_size: (int) number of elements in the dataset
"""
with open(txt_path) as f:
for i, line in enumerate(f):
vocab.update(line.strip().split(' '))
return i + 1
def build_vocab(path_dir, min_count_word=1, min_count_tag=1) :
# Build word vocab with train and test datasets
print("Building word vocabulary...")
words = Counter()
size_train_sentences = update_vocab(os.path.join(path_dir, 'train/sentences.txt'), words)
#size_dev_sentences = update_vocab(os.path.join(path_dir, 'dev/sentences.txt'), words)
#size_test_sentences = update_vocab(os.path.join(path_dir, 'test/sentences.txt'), words)
print("- done.")
# Save vocabularies to file
print("Saving vocabularies to file...")
save_vocab_to_txt_file(words, os.path.join(path_dir, 'words.txt'))
save_vocab_to_txt_file(tags, os.path.join(path_dir, 'tags.txt'))
save_vocab_to_txt_file(tags_count, os.path.join(path_dir, 'tags_count.txt'))
print("- done.")
# Save datasets properties in json file
sizes = {
'train_size': size_train_sentences,
'dev_size': size_dev_sentences,
'test_size': size_test_sentences,
'max_size_size': len(words),
'number_of_features': len(tags),
}
save_dict_to_json(sizes, os.path.join(path_dir, 'dataset_params.json'))
# Logging sizes
to_print = "\n".join("- {}: {}".format(k, v) for k, v in sizes.items())
print("Characteristics of the dataset:\n{}".format(to_print))
if __name__ == '__main__':
print("Building vocabulary for science dataset...")
build_vocab("data/science", 1, 1)
print("Building vocabulary for disease dataset...")
build_vocab("data/disease", 1, 1)
|
c742ba20728912aac3293cf456bc83fe88a588cf | Danisaura/phrasalVerbs | /main.py | 6,114 | 3.703125 | 4 | from random import shuffle
# printing the welcome message
print("\n" + "---------------------------------------------------" + "\n" +
"Welcome! this is a script to practice phrasal verbs." + "\n" + "\n" +
"You will be shown sentences with blank spaces inside," + "\n" +
"try to fill them with the correct phrasal verb." "\n" + "\n" +
"You can ask for a hint in any moment typing 'hint'" + "\n" +
"instead of the requested solution, and you can see your" + "\n" +
"current mark by typing 'mark'." + "\n" + "\n"
"Let's start! Good luck! :)" + "\n"
"---------------------------------------------------" + "\n" + "\n")
# declaring variables
marks = 0
total = 0
final_mark = 0
used_hints = 0
shuffled_list = [x for x in range(0, 31)]
shuffle(shuffled_list)
sentences = {0: "Brian finally was brave enough to _ Judy _ ",
1: "The car was about to run over me when she shouted: _ _!",
2: "We have _ _ of clinex again... I'll buy more tomorrow.",
3: "You are too special, I can't __ on us.",
4: "I'm in a hurry! I have to __ these exercises to my teacher by tomorrow morning!",
5: "Only thing I disliked about the hotel was that we had to __ _ before 12am...",
6: "My grandma always tells the same story where a bottle of gas __ in her face.",
7: "I've been ____ __ about the topic, but nobody knows shit.",
8: "My expenses in burgers this month _ $350... omg...",
9: "Don't worry Gorra, we will __ you on this! -told we before leaving him alone again-.",
10: "I just ___ __ when I got the bad news: Gorra had died in horrible suffering.",
11: "It was a well secured building, but we managed to ___ __ the room and steal the money.",
12: "I'm so sad my grandpa ____ __ so soon.",
13: "This new push-up jeans hurt me! I have to ___ them __",
14: "I'm young, but not stupid. You have to stop _____ __ on me.",
15: "He is secluded at home today. His parents forced him to __ _ his little sister.",
16: "We were angry again this morning, but we __ fast because we had things to do.",
17: "Yesterday I _ __ an old school-friend. It was scary, I think he's a drug dealer now.",
18: "Hey, I'm sure you'll like arepas. C'mon, let's _ them _.",
19: "I hate this kind of formal events. I really don't want to _ for them, I hate suits!",
20: "It was sad they had to ___ because of the distance. They were a great couple.",
21: "I will never fail you, you always can ___ me.",
22: "You are still mad. You have to __ __ to drive the car, please.",
23: "__ there, soon everything will be OK!",
24: "Oh shit, I forgot my phone at the pub, __ here for a second, will be right back!",
25: "If you __ this marks , you will pass the english exam easily.",
26: "I'm sorry to ___ , but I have some information about Gorra that might help.",
27: "Please, don't _ me __. I'm fed up of being sad.",
28: "He only bought that fucking car to __ _ and prove he is richer than me.",
29: "Don't worry, she always __ _ when she smokes these Holland joints.",
30: "Everyone loves and _ _ with Gorra, but at the same time, everyone do bad to him..."}
solutions = {0: "ask out",
1: "watch out",
2: "run out",
3: "give up",
4: "hand in",
5: "check out",
6: "blew up",
7: "asking around",
8: "add up to",
9: "back up",
10: "broke down",
11: "break into",
12: "passed away",
13: "break down",
14: "look down",
15: "look after",
16: "made up",
17: "ran into",
18: "try out",
19: "dress up",
20: "break up",
21: "count on",
22: "calm down",
23: "hang in",
24: "hang on",
25: "keep up",
26: "break in",
27: "let down",
28: "show off",
29: "pass out",
30: "get along"}
hints = {0: "as_ _",
1: "ten cuidado!",
2: "r _",
3: "g_ ",
4: "h_ ",
5: "esta te la sabes tia",
6: "Explotar. b_ . Ojo al tiempo verbal.",
7: "He estado informandome. I've been as__ aro___",
8: "add ",
9: "Apoyar, estar ahi. Es igual que 'copia de seguridad'.",
10: "Cuando no puedes mas, cuando te ROMPES",
11: "Colarse: br___ ",
12: "Palmarla. En pasado. pa__ __",
13: "br_ something __, significa adecuar ropa a tu cuerpo... no se como se dice en espanol :P",
14: "Menospreciar. lo___ __",
15: "(secluded == recluido) __ after",
16: "tambien significa maquillaje",
17: "Encontrarse a alguien inesperadamente. Tambien puede ser toparse con algo. r__ __",
18: "Probar. t _",
19: "Vestirse formal. dr_ ",
20: "Cortar, romper con alguien. br_ ",
21: "Contar con!",
22: "Calmarse, tranquilizarse",
23: "Uh, este era dificil. Significa mantenerse positivo, aguantar con buena onda. ha_ ",
24: "h_ on",
25: "Mantener algo. k___ up",
26: "br___ ",
27: "l d___",
28: "Creo que es la traduccion mas cerca a FLIPARSE. s___ f",
29: "ahhhh que recuerdos... p_ _",
30: "Llevarse bien. g _"}
for x in range(0, len(shuffled_list)):
print(sentences[shuffled_list[x]])
sol = input()
if sol == "hint":
print(hints[shuffled_list[x]])
used_hints += 1
sol = input()
if sol == solutions[shuffled_list[x]]:
print("correct!")
marks += 1
total += 1
else:
print("wrong, the correct answer is: ", solutions[shuffled_list[x]])
total += 1
|
e6536e8399f1ceccd7eb7d41eddcc302e3dda66b | guv-slime/python-course-examples | /section08_ex04.py | 1,015 | 4.4375 | 4 | # Exercise 4: Expanding on exercise 3, add code to figure out who
# has the most emails in the file. After all the data has been read
# and the dictionary has been created, look through the dictionary using
# a maximum loop (see chapter 5: Maximum and Minimum loops) to find out
# who has the most messages and print how many messages the person has.
# Enter a file name: mbox-short.txt
# cwen@iupui.edu 5
# PASSED
# Enter a file name: mbox.txt
# zqian@umich.edu 195
# PASSED
# file_name = 'mbox-short.txt'
file_name = 'mbox.txt'
handle = open(file_name)
email_dic = dict()
for line in handle:
if line.startswith('From'):
words = line.split()
if len(words) < 3:
continue
else:
email_dic[words[1]] = email_dic.get(words[1], 0) + 1
most_mail = None
for email in email_dic:
if most_mail is None or email_dic[most_mail] < email_dic[email]:
# print('DA MOST AT DA MOMENT =', email, email_dic[email])
most_mail = email
print(most_mail, email_dic[most_mail])
|
f93dd7a14ff34dae2747f7fa2db22325e9d00972 | guv-slime/python-course-examples | /section08_ex03.py | 690 | 4.125 | 4 | # Exercise 3: Write a program to read through a mail log, build a histogram
# using a dictionary to count how many messages have come from each email
# address, and print the dictionary.
# Enter file name: mbox-short.txt
# {'gopal.ramasammycook@gmail.com': 1, 'louis@media.berkeley.edu': 3,
# 'cwen@iupui.edu': 5, 'antranig@caret.cam.ac.uk': 1,
# 'rjlowe@iupui.edu': 2, 'gsilver@umich.edu': 3,
# 'david.horwitz@uct.ac.za': 4, 'wagnermr@iupui.edu': 1,
# 'zqian@umich.edu': 4, 'stephen.marquard@uct.ac.za': 2,
# 'ray@media.berkeley.edu': 1}
file_name = 'mbox-short.txt'
handle = open(file_name)
email_dic = dict()
for line in handle:
if line.startswith('From'):
words = line.split()
if len(words) < 3:
continue
else:
email_dic[words[1]] = email_dic.get(words[1], 0) + 1
print(email_dic)
|
995c34fb8474004731ba29407120537d9612529f | tacyi/tornado_overview | /chapter01/coroutine_test.py | 787 | 3.953125 | 4 | # 1.什么是协程
# 1.回调过深造成代码很难维护
# 2.栈撕裂造成异常无法向上抛出
# 协程,可被暂停并且切换到其他的协程运行的函数
from tornado.gen import coroutine
# 两种协程的写法,一种装饰器,一种3.6之后的原生的写法,推荐async
# @coroutine
# def yield_test():
# yield 1
# yield 2
# yield 3
#
# yield from yield_test()
#
# return "hello"
async def yield_test():
yield 1
yield 2
yield 3
async def main():
# await 只能写在 async下面
await yield_test()
async def main2():
# await 只能写在 async下面
# 按顺序执行,上面 遇到暂停,就进入此处的 await
await yield_test()
my_yield = yield_test()
for item in my_yield:
print(item)
|
cc7a0230928450b5bb71fa5fa6e57429a6e25882 | lmtjalves/CPD | /scripts/gen_random_big_parse_tests.py | 1,160 | 3.609375 | 4 | #!/bin/python
import sys, argparse, random
def test_rand(t):
if t == "both":
return random.randint(0,1)
elif t == "positive":
return 0
else:
return 1
parser = argparse.ArgumentParser(description="problem gen. clauses might be duplicate and have repeated variables")
parser.add_argument('min_num_vars', type=int)
parser.add_argument('max_num_vars', type=int)
parser.add_argument('min_clauses', type=int)
parser.add_argument('max_clauses', type=int)
parser.add_argument('min_vars_per_clause', type=int)
parser.add_argument('max_vars_per_clause', type=int)
parser.add_argument('--type', default="both", choices=["positive", "negative"])
args = parser.parse_args()
num_vars = random.randint(args.min_num_vars, args.max_num_vars)
num_clauses = random.randint(args.min_clauses, args.max_clauses)
print("{0} {1}".format(num_vars, num_clauses))
for i in range(1, num_clauses + 1):
num_clause_vars = random.randint(args.min_vars_per_clause, args.max_vars_per_clause)
print(" ".join([str(v) if test_rand(args.type) == 0 else str(-v) for v in [ random.randint(1, num_vars) for _ in range(num_clause_vars)]])+ " 0")
|
6214901ec8317a2ead9409991548282f5ce33c57 | bobgautier/rjgtoys-config | /examples/translate.py | 590 | 3.890625 | 4 | """
examples/translate.py: translate words using a dictionary
"""
import argparse
import os
from typing import Dict
from rjgtoys.config import Config, getConfig
class TranslateConfig(Config):
words: Dict[str, str]
cfg = getConfig(TranslateConfig)
def main(argv=None):
p = argparse.ArgumentParser()
cfg.add_arguments(p, default='translate.yaml', adjacent_to=__file__)
args, tail = p.parse_known_args(argv)
for word in tail:
result = cfg.words.get(word, "I don't know that word")
print(f"{word}: {result}")
if __name__ == "__main__":
main()
|
2d7724e5786f00b9f2c1e2f8640ebde7138f7c85 | maryamkh/MyPractices | /Find_Nearest_Smaller_Element.py | 1,930 | 3.90625 | 4 | '''
Given an array, find the nearest smaller element G[i] for every element A[i] in the array such that the element has an index smaller than i.
Elements for which no smaller element exist, consider next smaller element as -1.
Output: An array of prev .smaller value of each item or -1(if no smaller value exists for one item.)
Example:
Input 1:
A = [4, 5, 2, 10, 8]
Output 1:
G = [-1, 4, -1, 2, 2]
Explaination 1:
index 1: No element less than 4 in left of 4, G[1] = -1
index 2: A[1] is only element less than A[2], G[2] = A[1]
index 3: No element less than 2 in left of 2, G[3] = -1
index 4: A[3] is nearest element which is less than A[4], G[4] = A[3]
index 4: A[3] is nearest element which is less than A[5], G[5] = A[3]
'''
class NearestSmallerElement:
# @param array : list of integers
# @return a list of integers
def prevSmaller(self, array):
nearestIndex = []
nearestIndex.append(-1) #first item in array does not have any item in its back==> no smaller value in its back
if len(array) == 1:
return nearestIndex
nearestItem = 0
for pivot in range(1,len(array)):
stack = array[:pivot]#array[:pivot]
while len(stack) > 0:
nearestItem = stack.pop()
if nearestItem < array[pivot]: #pivot:
nearestIndex.append(nearestItem) #len(stack) + 1
break
if len(nearestIndex) < pivot + 1: #array[i] has no value smaller than itself in its left side.===> inser -1 in nearestIndex array
nearestIndex.append(-1)
return nearestIndex
def main():
previousSmaller = NearestSmallerElement()
array = [2,7,-1,9,12,-3]
result = previousSmaller.prevSmaller(array)
print result
if __name__ == '__main__':
main()
|
ff2ac738c1718fa12bd84e447ddc9b0e1080420a | maryamkh/MyPractices | /Min_Sum_Path_Bottom_Up.py | 4,255 | 4.375 | 4 | #!usr/bin/python
'''
The approach is to calculate the minimum cost for each cell to figure out the min cost path to the target cell.
Assumpthion: The movementns can be done only to the right and down.
In the recursive approach there is a lot of redundent implementation of the sub-problems. With Dynamic programming we optimize the implementation. Dynamic programming is done by bottom-up approach in an iterative loop.
Main function: calMinCost()
'''
class MinCostPath:
def calMinCost(self, matrix, inRow, inCol):
if len(matrix) == len(matrix[0]) == 1:
return matrix[0][0]
#initialize the tracker matrix with 0
cost = [[0 for col in range(inCol)] for row in range(inRow)]
print 'cost after init...', cost
# In the first row and first column the min cost to reach each cell is equal of the cost of the cell + cost of passing all the previous cells
cost[0][0] = matrix[0][0]
#if row == 0:
#for col in range(1, len(matrix[0])):
for col in range(1, inCol):
cost[0][col] = cost[0][col-1] + matrix[0][col]
#print 'matrix[0][col]...', matrix[0][col]
#if col == 0:
#for row in range(1,len(matrix)):
for row in range(1,inRow):
cost[row][0] = cost[row-1][0] + matrix[row][0]
#print 'matrix[row][0]..', matrix[row][0]
print cost
# To calculate the min cost of other cells, for each cell we calculate the cost of reaching the cell above the target cell and the cell on the left side of the target cell (since the movements can be done only to the down and right) and choose the one which has min cost.
#for row in range(1,len(matrix)):
#for col in range(1,len(matrix[0])):
for row in range(1,inRow):
for col in range(1,inCol):
print 'row...col...', row, col
above = cost[row-1][col]
print 'above...', above
left = cost[row][col-1]
cost[row][col] = min(above, left) + matrix[row][col]
print 'cost[row][col]...,,,...', cost[row][col]
print 'row...col....cost[row-1][col-1]...', cost[row-1][col-1]
return cost[inRow-1][inCol-1]
#######################################################
def findPath(self, matrix, row, col):
print 'in function...'
if len(matrix) == len(matrix[0]) == 1:
return mtrix[0][0]
sum = 0
#untraversed rows/cols:
if row >= len(matrix)-1 or col >= len(matrix[0])-1:
while row < len(matrix) - 1: #we are in the last col of the matrix and should travers all the remaining rows till reaching the bottom-right corner
sum += matrix[row+1][-1]
print 'sum in row travers...', sum
row += 1
while col < len(matrix[0]) - 1: #we are on the last row of the matrix and should travers all the remaining columns to reach the bottom-right corner of the matrix
sum += matrix[-1][col+1]
print 'sum in column travers...', sum
col += 1
return sum
if row < len(matrix)-1 and col < len(matrix[0])-1:
if matrix[row][col+1] < matrix[row+1][col]: #make a right step
#sum += math.min(matrix[row][col+1], matrix[row+1][col])
#sum += matrix[row][col+1]
#col = col + 1
print 'matrix[row+1][col] in righ move...', matrix[row][col+1]
sum = matrix[row][col+1] + self.findPath(matrix, row, col+1)
else: #make a down step
#sum += matrix[row+1][col]
#row = row + 1
print 'matrix[row+1][col] in down step...', matrix[row+1][col]
sum = matrix[row+1][col] + self.findPath(matrix, row+1, col)
sum = sum + matrix[0][0]
return sum
def main():
#matrix = [[1,3], [5,2]]
matrix = [[1,7,9,2],[8,6,3,2],[1,6,7,8],[2,9,8,2]]
minPath = MinCostPath()
#result = minPath.calMinCost(matrix, 4, 4)
result = minPath.findPath(matrix, 1, 1)
print result
if __name__ == '__main__':
main()
|
bd745cc83163bd91f36ab2f2d034f7f0a02093c0 | maryamkh/MyPractices | /Pow_function_recursive.py | 697 | 3.921875 | 4 | '''
Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
Example:
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Time Complexity: O(log(n))===> In this solution n is reduce to half and therefore this is the time cimplexity
Spcae Complexity: We need to do the computation for O(logn) times, so the space complexity is O(logn)
'''
class Solution:
def myPow(self, x: float, n: int) -> float:
if n < 0:
x = 1/x
n = abs(n)
if n==0:
return 1
res = self.myPow(x, n//2)
if n%2 == 0:
return res*res
else:
return res*res*x
|
d1917f2bd44d327224cfb121c1d18f68c5de2383 | maryamkh/MyPractices | /Stairs.py | 2,092 | 4.09375 | 4 | #!usr/bin/python
'''
Find the numbers of ways we can reach the top of the stairs if we can only clime 1 or 2 steps each time?
Input: Integer: The stair number in which we should reach to
Output: Integer: The numebr of ways we can clime up to reach target stair
Reaching any stair with only 1 step climing or 2 steps climing means that we should first reach either:
1- A stair one step below the target step them make 1 step climing to reach the target step or
2- Two steps below the target step and then make a 2 steps climing to reach the target
===> this means that the function to each step is a fonction of its pervious step + 1 OR the functions of its 2nd previous step + 2: f(n) = f(n-1) + f(n-2)==> This is the fibonnachi series
Note: For making steps of 1, 2 or 3 climings the function is: f(n) = f(n-1) + f(n-2) + f(n-3)
Solution:
1- the problem can be solved recursively which contanins many redundent of the implementation of the subproblems.
2- the second way is to do dynamic programming using buttom-up solution and solve the problem in linear time complexity.
'''
class StairsSteps:
def calSteps(self, stairs):
checkedSteps = []
for i in range(stairs+1): #init the array with 0
checkedSteps.append(0)
if stairs == 1 or stairs == 0:
checkedSteps[stairs] = 1
return 1
for step in range(2, stairs+1):
if checkedSteps[step] == 0:
checkedSteps[step] = self.calSteps(step-1) + self.calSteps(step-2)
else:
return checkedSteps[step]
return checkedSteps[step]
###############################################################
def calStepsRecursive(self, stairs):
if stairs == 0 or stairs == 1:
return 1
return self.calStepsRecursive(stairs-1) + self.calStepsRecursive(stairs-2)
def main():
steps = StairsSteps()
result = steps.calSteps(4)
#result = steps.calStepsRecursive(5)
print result
if __name__ == '__main__':
main()
|
f9a66f5b0e776d063d812e7a7185ff6ff3c5615f | maryamkh/MyPractices | /ReverseLinkedList.py | 2,666 | 4.3125 | 4 | '''
Reverse back a linked list
Input: A linked list
Output: Reversed linked list
In fact each node pointing to its fron node should point to it back node ===> Since we only have one direction accessibility to a link list members to reverse it I have to travers the whole list, keep the data of the nodes and then rearrange them backward.
Example:
Head -> 2-> 3-> 9-> 0
Head -> 0-> 9-> 3-> 2
Pseudocode:
currentNode = Head
nodeSet = set ()
While currentNode != None:
nodeSet.add(currentNode.next)
currentNode = currentNode.next
reversedSet = list(reverse(set))
currentNode = Head
while currentNode != None:
currentNode.value = reversedSet.pop()
currentNode = currentNode.next
Tests:
Head -> None
Head -> 2
Head -> 0-> 9-> 3-> 2
'''
class node:
def __init__(self, initVal):
self.data = initVal
self.next = None
def reverseList(Head):
currNode = Head
nodeStack = []
while currNode != None:
#listSet.add(currNode)
#nodeStack.append(currNode.data)
nodeStack.append(currNode)
currNode = currNode.next
# currNode = Head
# print (nodeStack)
# while currNode != None:
# #currNode.value = listSet.pop().value
# currNode.value = nodeStack.pop().data
# print (currNode.value)
# currNode = currNode.next
if len(nodeStack) >= 1:
Head = nodeStack.pop()
currNode = Head
#print (currNode.data)
while len(nodeStack) >= 1:
currNode.next = nodeStack.pop()
#print (currNode.data)
currNode = currNode.next
#print (currNode.data)
def showList(Head):
#print(f'list before reverse: {Head}')
while Head != None:
print(f'{Head.data}')
Head = Head.next
print(f'{Head}')
#Head = None
#print(f'list before reverse:\n')
#showList(Head)
#reverseList(Head)
#print(f'list after reverse:\n')
#showList(Head)
def reverse(Head):
nxt = Head.next
prev = None
Head = reverseList1(Head,prev)
print(f'new head is: {Head.data}')
def reverseList1(curr,prev):
#Head->2->3->4
#None<-2<-3<-4
if curr == None:
return prev
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return reverseList1(curr, prev)
n1 = node(2)
Head = n1
#print(f'list before reverse:\n')
#showList(Head)
#reverseList(Head)
#print(f'list after reverse:\n')
#showList(Head)
n2 = node(0)
n3 = node(88)
n4 = node(22)
n1.next = n2
n2.next = n3
n3.next = n4
Head = n1
print(f'list before reverse:\n')
showList(Head)
##reverseList(Head)
reverse(Head)
Head = n4
print(f'n1 value: {Head.data}')
showList(Head)
|
145413092625adbe30b158c21e5d27e2ffcfab50 | maryamkh/MyPractices | /Squere_Root.py | 1,838 | 4.1875 | 4 | #!/usr/bin/python
'''
Find the squere root of a number. Return floor(sqr(number)) if the numebr does not have a compelete squere root
Example: input = 11 ===========> output = 3
Function sqrtBinarySearch(self, A): has time complexity O(n), n: given input: When the number is too big it becomes combursome
'''
class Solution:
def sqrt(self, A):
n = 1
while n*n <= A:
n += 1
if A == n*n: return n
elif n < (n-.5) * (n-.5): return n-1
else: return n+1
def sqrtBinarySearch(self, A):
searchList = []
#print range(A)
for i in range(A):
searchList.append(i+1)
for i in range(len(searchList)):
mid = len(searchList)/2
#if mid > 0:
number = searchList[mid-1]
sqrMid = number * number
sqrMidPlus = (number+1) * (number+1)
#print 'sqrMid...sqrMidPlus...', sqrMid, sqrMidPlus
if sqrMid == A: return number
elif sqrMid > A: #sqrt is in the middle left side of the array
searchList = searchList[:mid]
#print 'left wing...', searchList
elif sqrMid < A and sqrMidPlus > A: # sqrMid< sqrt(A)=number.xyz <sqrMidPlus==> return floor(number.xyz)
print
if (number + .5) * (number + .5) > A: return number
return number+1
else:
searchList = searchList[mid:]
#print 'right wing...', searchList
def main():
inputNum = int(input('enter a number to find its squere root: '))
sqroot = Solution()
result = sqroot.sqrt(inputNum)
result1 = sqroot.sqrtBinarySearch(inputNum)
print result
print result1
if __name__ == '__main__':
main()
|
55ab2d3473fb7ff9485f1ff835dd599d427e0a5d | hokiespider/win_probability | /win_probability.py | 4,054 | 3.734375 | 4 | #!/usr/bin/env python
# coding: utf-8
import pandas as pd
import requests
import json
# What school are you analyzing?
school = "Virginia Tech"
# Get data from the API
df = pd.DataFrame()
for x in range(2013, 2020, 1): # Line data is only available 2013+
parameters = {
"team": school,
"year": x
}
response = requests.get("https://api.collegefootballdata.com/lines", params=parameters)
# Import the data into a pandas DataFrame
temp = pd.DataFrame(response.json()) # Create a DataFrame with a lines column that contains JSON
# need to fill NA line lists for 2020
temp = temp.explode('lines') # Explode the DataFrame so that each line gets its own row
temp = temp.reset_index(drop=True) # After explosion, the indices are all the same - this resets them so that you can align the DataFrame below cleanly
lines_df = pd.DataFrame(temp.lines.tolist()) # A separate lines DataFrame created from the lines JSON column
temp = pd.concat([temp, lines_df], axis=1) # Concatenating the two DataFrames along the vertical axis.
df = df.append(temp)
df = df[df.provider == 'consensus']
df['spread'] = df.spread.astype('float')
# Add Win/Loss columns
home_games = df[df.homeTeam == school].copy()
home_games['score_diff'] = home_games['homeScore'] - home_games['awayScore']
home_games['home_away'] = "Home"
home_games.loc[home_games['score_diff'] > 0, 'wins'] = 1
home_games.loc[home_games['score_diff'] < 0, 'losses'] = 1
away_games = df[df.awayTeam == school].copy()
away_games['score_diff'] = away_games['awayScore'] - away_games['homeScore']
away_games['home_away'] = "away"
away_games.loc[away_games['score_diff'] > 0, 'wins'] = 1
away_games.loc[away_games['score_diff'] < 0, 'losses'] = 1
away_games['spread'] = away_games['spread'] * -1
df = home_games.append(away_games)
#records = df.groupby(['season'])['wins', 'losses'].sum()
# Import the odds of winning
filename = '/Users/appleuser/Documents/win_probability/odds_of_winning_lines.csv'
odds = pd.read_csv(filename)
odds = odds.melt(id_vars='Spread', value_vars=['Favorite', 'Underdog'], var_name='Type', value_name="Expected Wins")
odds.loc[odds['Spread'] == '20+', 'Spread'] = 20
odds['Spread'] = odds.Spread.astype('float')
odds.loc[odds['Type'] == "Favorite", 'Spread'] = odds['Spread'] * -1
df.loc[df['spread'] >= 20, 'spread'] = 20
df.loc[df['spread'] <= -20, 'spread'] = -20
df = df.merge(odds, how='left', left_on='spread', right_on='Spread')
df.loc[df['spread'] < 0, 'spread_group'] = '3. 0.5-6.5 Favorites'
df.loc[df['spread'] < -6.5, 'spread_group'] = '2. 7-14 Favorites'
df.loc[df['spread'] < -13.5, 'spread_group'] = ' 1. 14+ Favorites'
df.loc[df['spread'] == 0, 'spread_group'] = '4. pick-em'
df.loc[df['spread'] > 0, 'spread_group'] = '5. 0.5-6.5 Dogs'
df.loc[df['spread'] > 6.5, 'spread_group'] = '6. 7-14 Dogs'
df.loc[df['spread'] > 13.5, 'spread_group'] = '7. 14+ Dogs'
df.loc[df['season'] >= 2016, 'Coach'] = 'Fuente 2016-2019'
df.loc[df['season'] < 2016, 'Coach'] = 'Beamer 2013 - 2015'
groups = df.groupby(['Coach', 'spread_group'])['wins', 'losses', 'Expected Wins'].sum().round(2)
groups['win_perc'] = groups.apply(lambda x: x['wins'] / (x['wins'] + x['losses']), axis=1).round(2)
groups['wins vs expectation'] = groups['wins'] - groups['Expected Wins'].round(2)
groups
groups.to_clipboard()
coaches = df.groupby(['Coach'])['wins', 'losses', 'Expected Wins'].sum().round(2)
coaches['win_perc'] = coaches.apply(lambda x: x['wins'] / (x['wins'] + x['losses']), axis=1).round(2)
coaches['wins vs expectation'] = coaches['wins'] - coaches['Expected Wins'].round(2)
coaches
years = df.groupby(['season', 'spread_group'])['wins', 'losses', 'Expected Wins'].sum().round(2)
years['win_perc'] = years.apply(lambda x: x['wins'] / (x['wins'] + x['losses']), axis=1).round(2)
years['wins vs expectation'] = years['wins'] - years['Expected Wins'].round(2)
years.reset_index()
years = years.drop(['wins', 'losses', 'Expected Wins', 'win_perc'], axis=1)
years = years.unstack('spread_group')
years
years.to_clipboard()
|
65256d3f3d66a41bd69be4dc55bb89b2c643036e | DaniRyland-Lawson/CP1404-cp1404practicals- | /prac_06/demo_program.py | 1,784 | 3.75 | 4 | """CP1404 Programming II demo program week 6 prac
0. Pattern based programming
1. Names based on problem domain
2. Functions at the same leve of abstraction( main should "look" the same
Menu- driven program
load products
- L_ist products
- S_wap sale status (get product number with error checking)
- Q_uit (save file)
"""
PRODUCTS_FILE = "products.csv"
MENU_STRING = ">>>"
def main():
products = load_products()
print(products)
print(MENU_STRING)
menu_selection = input(">").upper()
while menu_selection != "Q":
if menu_selection == "L":
list_products(products)
elif menu_selection == "S":
swap_sale_status(products)
else:
print("Invalid")
print(MENU_STRING)
menu_selection = input(">").upper()
save_products(products)
print("Finished")
def load_products():
print("loading")
products = [["Phone", 340, False], ["PC", 1420.95, True], ["Plant", 24.50, True]]
return products
def list_products(products):
print("list")
for product in products:
print(product)
def swap_sale_status(products):
list_products(products)
is_valid_input = False
while not is_valid_input:
try:
number = int(input("? "))
if number < 0:
print("Product must be >= 0")
else:
is_valid_input = True
except ValueError:
print("Invalid (not an integer)")
print(products[number])
# make CSV from list of lists
def save_products(products):
with open("products.csv", "r") as output_file:
for product in output_file:
sale_status = 'y' if product[2] else 'n'
print("{}, {}, {}".format(product[0], product[1], sale_status))
main()
|
e47f166763aad48f70da971a79953db8875531b7 | DaniRyland-Lawson/CP1404-cp1404practicals- | /prac_07/miles_to_kms.py | 1,154 | 3.53125 | 4 | """CP1404 Programming II Week 7 Kivy - Gui Program to convert Miles to Kilometres."""
from kivy.app import App
from kivy.lang import Builder
from kivy.app import StringProperty
MILES_TO_KM = 1.60934
class MilesToKilometres(App):
output_km = StringProperty()
def build(self):
self.title = "Convert Miles to Kilometres"
self.root = Builder.load_file('miles_to_kms.kv')
return self.root
def handle_convert(self, text):
"""handle calculation """
# print("handle calculation")
miles = self.convert_to_number(text)
self.update_result(miles)
def handle_increment(self, text, change):
"""handle button press up and down"""
# print("handle adding")
miles = self.convert_to_number(text) + change
self.root.ids.input_miles.text = str(miles)
def update_result(self, miles):
# print("update")
self.output_km = str(miles * MILES_TO_KM)
@staticmethod
def convert_to_number(text):
try:
value = float(text)
return value
except ValueError:
return 0.0
MilesToKilometres().run()
|
4a20f0a4d156b03c5e658e0073f8086ab5ca0b95 | DaniRyland-Lawson/CP1404-cp1404practicals- | /prac_08/unreliable_car_test.py | 676 | 3.640625 | 4 | """CP1404 Programming II
Test to see of UnreliableCar class works."""
from prac_08.unreliable_car import UnreliableCar
def main():
"""Test for UnreliableCars."""
# Create some cars for reliability
good_car = UnreliableCar("Good Car", 100, 90)
bad_car = UnreliableCar("Bad Car", 100, 10)
# Attempts to drive the cars multiple times
# Output is what the drove in kms
for i in range(1, 10):
print("Attempting to drive {}km: ".format(i))
print("{:10} drove {:2}km".format(good_car.name, good_car.drive(i)))
print("{:10} drove {:2}km".format(bad_car.name, bad_car.drive(i)))
print(good_car)
print(bad_car)
main()
|
de7b30a4f51727085b556dc01763180a3fdedffd | Monkin6/yarygin | /hm4.py | 132 | 3.5 | 4 | n = int(input())
maximum = -1
while n != 0:
if n % 10 > maximum:
maximum = n % 10
n = n // 10
print(maximum)
|
c0c510cbebedb03947bb2b9ed16c16efa23a4956 | Sahil-k1509/Python_and_the_Web | /Scripts/Miscellaneous/Email_extractor/extract_emails.py | 407 | 3.78125 | 4 | #!/usr/bin/env python3
import re
print("Enter the name of the input file: ")
file=str(input())
try:
f = open(file,"r")
except FileNotFoundError:
print("File does not exists")
email={}
for i in f:
em = re.findall('\S+@\S+\.\S+',i)
for j in em:
email[j]=email.get(j,0)+1
f.close()
for i in email:
if(email[i]>=2):
print(i,email[i])
else:
print(i)
|
d99e28fea0f6d213659694f220451d12930dcd84 | Mertvbli/JustTry | /CW_filter_list_7kyu.py | 363 | 3.640625 | 4 | def filter_list(l):
new_list = []
for number in l:
if str(number).isdigit() and str(number) != number:
new_list.append(number)
return new_list # or [number for number in l if isinstance(number, int)
print(filter_list([1,2,'a','b']))
print(filter_list([1,'a','b',0,15]))
print(filter_list([1,2,'aasf','1','123',123]))
|
ddbfeec96361f4c3576874c2ff007d88717f1566 | CodingDojoDallas/python_sep_2018 | /austin_parham/product.py | 948 | 3.671875 | 4 | class Product:
def __init__(self,price,item_name,weight,brand):
self.price = price
self.item_name = item_name
self.weight = weight
self.brand = brand
self.status = "for sale"
self.display_info()
def sell(self):
self.status = "sold"
return self
def add_tax(self,x):
self.price = (self.price * x) + self.price
self.display_info()
def return_item(self,reason_for_return):
if "like new" in reason_for_return:
self.status = "for sale"
else:
if "opened" in reason_for_return:
self.status = "used"
self.price = self.price - (self.price * .2)
else:
self.status = reason_for_return
self.price = 0
self.display_info()
def display_info(self):
print("Price:",self.price)
print("Name:",self.item_name)
print("Weight:",self.weight)
print("Brand",self.brand)
print("Status:",self.status)
print('*' * 80)
shoes = Product(45,"shoes","2kg","adidas")
shoes.sell()
shoes.return_item("opened") |
13dac1bd992f843d432a94f266a283671e39c2fa | CodingDojoDallas/python_sep_2018 | /Solon_Burleson/Basics.py | 370 | 3.796875 | 4 | # def allOdds():
# for x in range(3001):
# if x % 2 != 0:
# print (x)
# allOdds()
# def Iterate(arr):
# for x in arr:
# print (x)
# Iterate([1,2,3,4,5])
# def Sumlist(arr):
# sum = 0
# for x in arr:
# sum += x
# return sum
# print(Sumlist([1,2,3,4,5]))
list = [3,5,1,2]
for i in range(len(list)):
print(i) |
bb488183c87ed750f3cd459bda9d758416b5613e | CodingDojoDallas/python_sep_2018 | /austin_parham/func_intermediate_1.py | 819 | 3.828125 | 4 | def randInt():
import random
hold = (random.random()*100)
hold = int(hold)
print(hold)
randInt()
def randInt():
import random
hold = (random.random()*50)
hold = int(hold)
print(hold)
randInt()
def randInt():
import random
hold = (random.uniform(50,100))
hold = int(hold)
print(hold)
randInt()
def randInt(): #alternate method without uniform
import random
hold = (random.random()*100)
hold = int(hold)
while hold < 50:
hold = (random.random()*100)
hold = int(hold)
print(hold)
randInt()
def randInt():
import random
hold = (random.uniform(50,500))
hold = int(hold)
print(hold)
randInt()
def randInt(): #alternate method without uniform
import random
hold = (random.random()*500)
hold = int(hold)
while hold < 400:
hold = (random.random()*500)
hold = int(hold)
print(hold)
randInt() |
8b9f850c53a2a020b1deea52e301de0d2b6c47c3 | CodingDojoDallas/python_sep_2018 | /austin_parham/user.py | 932 | 4.15625 | 4 | class Bike:
def __init__(self, price, max_speed, miles):
self.price = price
self.max_speed = max_speed
self.miles = miles
def displayInfo(self):
print(self.price)
print(self.max_speed)
print(self.miles)
print('*' * 80)
def ride(self):
print("Riding...")
print("......")
print("......")
self.miles = self.miles + 10
def reverse(self):
print("Reversing...")
print("......")
print("......")
self.miles = self.miles - 5
# def reverse(self):
# print("Reversing...")
# print("......")
# print("......")
# self.miles = self.miles + 5
# Would use to not subtract miles from reversing
bike1 = Bike(200,120,20000)
bike1.ride()
bike1.ride()
bike1.ride()
bike1.reverse()
bike1.displayInfo()
bike2 = Bike(600,150,5000)
bike2.ride()
bike2.ride()
bike2.reverse()
bike2.reverse()
bike2.displayInfo()
lance = Bike(4000,900,60000)
lance.reverse()
lance.reverse()
lance.reverse()
lance.displayInfo()
|
60abefff5fa43ad4a30bee1e102f3a31a08c15b6 | CodingDojoDallas/python_sep_2018 | /albert_garcia/python_oop/slist.py | 1,276 | 3.78125 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
class SList:
def __init__(self, value):
node = Node(value)
self.head = node
def Addnode(self, value):
node = Node(value)
runner = self.head
while (runner.next != None):
runner = runner.next
runner.next = node
def PrintAllValues(self, msg=""):
runner = self.head
print("\n\nhead points to head")
print("Printing the values in the list ---", msg,"---")
while (runner.next != None):
print("runner =", runner.value)
runner = runner.next
print("runner =", runner.value)
def RemoveNode(self, value):
runner = self.head
if self.head.value == value:
self.head = self.head.next
holder = runner
while runner.next != None:
if runner.value == value:
holder.next = runner.next
holder = runner
runner = runner.next
if runner.value == value and runner.next == None:
holder.next = None
return self
list = SList(5)
list.Addnode(7)
list.Addnode(9)
list.Addnode(1)
list.PrintAllValues()
list.RemoveNode(9) .PrintAllValues("Attempt 1") |
189bd9eb0029b856f348e9ff86f32ceb6f99d84b | CodingDojoDallas/python_sep_2018 | /Solon_Burleson/RunCode.py | 380 | 3.703125 | 4 | class MathDojo:
def __init__(self):
self.value = 0
def add(self, *nums):
for i in nums:
self.value += i
return self
def subtract(self, *nums):
for i in nums:
self.value -= i
return self
def result(self):
print(self.value)
x = MathDojo().add(2).add(2,5,1).subtract(3,2).result()
print(x)
|
ab847b8b4d3b115f88b96b560b41f076a7bd6bdc | CodingDojoDallas/python_sep_2018 | /Solon_Burleson/FunctionsIntermediateI.py | 195 | 3.65625 | 4 | import random
def randInt(max=0, min=0):
if max == 0 and min == 0:
print(int(random.random()*100))
else:
print(int(random.random()*(max-min)+min))
randInt(max=500,min=50)
|
36a4f28b97be8be2e7f6e20965bd21f554270704 | krismosk/python-debugging | /area_of_rectangle.py | 1,304 | 4.6875 | 5 | #! /usr/bin/env python3
"A script for calculating the area of a rectangle."
import sys
def area_of_rectangle(height, width = None):
"""
Returns the area of a rectangle.
Parameters
----------
height : int or float
The height of the rectangle.
width : int or float
The width of the rectangle. If `None` width is assumed to be equal to
the height.
Returns
-------
int or float
The area of the rectangle
Examples
--------
>>> area_of_rectangle(7)
49
>>> area_of_rectangle (7, 2)
14
"""
if width:
width = height
area = height * width
return area
if __name__ == '__main__':
if (len(sys.argv) < 2) or (len(sys.argv) > 3):
message = (
"{script_name}: Expecting one or two command-line arguments:\n"
"\tthe height of a square or the height and width of a "
"rectangle".format(script_name = sys.argv[0]))
sys.exit(message)
height = sys.argv[1]
width = height
if len(sys.argv) > 3:
width = sys.argv[1]
area = area_of_rectangle(height, width)
message = "The area of a {h} X {w} rectangle is {a}".format(
h = height,
w = width,
a = area)
print(message)
|
dda3e4ff366d47cea012f9bfede9819fac448af9 | BlueAlien99/minimax-reversi | /app/gui/utils.py | 8,441 | 3.515625 | 4 | import enum
import pygame
from typing import List
import pygame.freetype
from pygame_gui.elements.ui_drop_down_menu import UIDropDownMenu
from pygame_gui.elements.ui_text_entry_line import UITextEntryLine
import time
class Color(enum.Enum):
NO_COLOR = -1
BLACK = "#212121"
WHITE = "#f5f5f5"
GREEN = "#388e3c"
ORANGE = "#ffc107"
BROWN = "#795548"
class State(enum.Enum):
""" Different states of the board tile
UNCHECKED -- tile is unchecked (GREEN)
BLACK -- checked black
WHITE -- checked white """
UNCHECKED = 0
BLACK = 1
WHITE = 2
class Board:
""" Represents tiled game board """
class Tile:
""" Represents single board tile """
"""
big_rect is always black it is used to display border around tiles
if tile is in POSSIBLE_CHECK state:
* normal_rect is orange
* small rect is green
else:
* normal_rect is green
* small_rect is not displayed
"""
def __init__(self, screen, x: int, y: int):
self.screen = screen
self.x = x
self.y = y
self.big_rect = pygame.Rect(
self.x - Board.tile_size,
self.y - Board.tile_size,
2 * Board.tile_size,
2 * Board.tile_size
)
self.normal_rect = pygame.Rect(
self.x - Board.tile_size + Board.tile_b_size,
self.y - Board.tile_size + Board.tile_b_size,
2 * Board.tile_size - 2 * Board.tile_b_size,
2 * Board.tile_size - 2 * Board.tile_b_size
)
self.small_rect = pygame.Rect(
self.x - Board.tile_size + Board.tile_b_size2,
self.y - Board.tile_size + Board.tile_b_size2,
2 * Board.tile_size - 2 * Board.tile_b_size2,
2 * Board.tile_size - 2 * Board.tile_b_size2
)
def draw(self, state: State, is_possible_check: bool):
""" Draws a tile """
pygame.draw.rect(self.screen, Color.BLACK.value, self.big_rect)
if is_possible_check:
pygame.draw.rect(self.screen, Color.ORANGE.value, self.normal_rect)
pygame.draw.rect(self.screen, Color.GREEN.value, self.small_rect)
else:
pygame.draw.rect(self.screen, Color.GREEN.value, self.normal_rect)
if state == State.BLACK:
pygame.draw.circle(self.screen, Color.BLACK.value, (self.x, self.y),
Board.tile_size - Board.tile_padding)
elif state == State.WHITE:
pygame.draw.circle(self.screen, Color.WHITE.value, (self.x, self.y),
Board.tile_size - Board.tile_padding)
def is_clicked(self, x, y):
""" Returns True if tile was clicked """
return self.big_rect.collidepoint((x, y))
tile_size = 40
tile_padding = 10
# outer tile border size
tile_b_size = 2
# border size of the orange indicator displayed when there is possible move on the tile
tile_b_size2 = 6
rows = 8
cols = 8
def __init__(self, screen, board_x=0, board_y=0):
""" Creates tiled board of size 8x8 """
self.tiles = [
[
Board.Tile(screen, board_x + (2*c + 1)*self.tile_size, board_y + (2*r + 1)*self.tile_size)
for c in range(self.cols)
]
for r in range(self.rows)
]
def draw(self, board_state, valid_moves):
y = 0
for row in self.tiles:
x = 0
for tile in row:
tile.draw(State(board_state[x][y]), valid_moves[x][y] < 0)
x += 1
y += 1
def is_clicked(self, mouse_x, mouse_y) -> (int, int):
""" Checks if any tile was clicked
If a tile was clicked returns its coordinates
Returns (-1, -1) otherwise """
y = 0
for row in self.tiles:
x = 0
for tile in row:
if tile.is_clicked(mouse_x, mouse_y):
return x, y
x += 1
y += 1
return -1, -1
class Text:
""" Simple text field """
def __init__(self, screen, x: int, y: int, text: str, color: Color = Color.BLACK):
self.font = pygame.freetype.SysFont('Comic Sans MS', 24)
self.x = x
self.y = y
self.screen = screen
self.text = text
self.color = color
def set_text(self, text: str):
self.text = text
def draw(self):
text_surface, rect = self.font.render(self.text, self.color.value)
self.screen.blit(text_surface, (self.x, self.y))
class DropDownWithCaption:
""" Dropdown list with caption """
def __init__(self, screen, ui_manager, x: int, y: int,
options_list: List[str], starting_option: str, caption_text: str):
self.x = x
self.y = y
self.screen = screen
self.caption = Text(screen, x, y, caption_text)
self.current_option = starting_option
self.dropdown = UIDropDownMenu(options_list=options_list,
starting_option=starting_option,
relative_rect=pygame.Rect((x, y+24), (140, 40)),
manager=ui_manager)
def set_caption(self, caption_text: str):
self.caption.set_text(caption_text)
def update_current_option(self, option: str):
self.current_option = option
def get_current_option(self) -> str:
return self.current_option
def draw(self):
self.caption.draw()
class TextBoxWithCaption:
""" Text input box with caption """
def __init__(self, screen, ui_manager, x: int, y: int, caption_text: str, initial_value: str = "1"):
self.x = x
self.y = y
self.screen = screen
self.caption = Text(screen, x+7, y, caption_text)
self.text_box = UITextEntryLine(relative_rect=pygame.Rect((x, y+24), (30, 30)),
manager=ui_manager)
self.text_box.set_text(initial_value)
def get_int(self) -> int:
""" Returns the text that is currently in the box. Returns 1 if it is empty """
text = self.text_box.get_text()
if text == "":
return 1
else:
return int(self.text_box.get_text())
def __validate_input(self):
text = ""
try:
text = self.text_box.get_text()
val = int(text)
if val > 10:
self.text_box.set_text("10")
elif val <= 0:
self.text_box.set_text("1")
except ValueError:
if text == "":
self.text_box.set_text(text)
else:
self.text_box.set_text("1")
def draw(self):
self.__validate_input()
self.caption.draw()
class Timer:
""" Timer that displays minutes and seconds in mm:ss format """
def __init__(self, screen, x: int, y: int):
self.font = pygame.freetype.SysFont('Comic Sans MS', 24)
self.x = x
self.y = y
self.screen = screen
self.seconds = 0
self.minutes = 0
self.started = False
def tick(self):
if self.started:
self.seconds += 1
if self.seconds == 60:
self.minutes += 1
self.seconds = 0
def reset(self):
self.minutes = self.seconds = 0
self.started = False
def start(self):
self.started = True
def draw(self):
t = (2009, 2, 17, 17, self.minutes, self.seconds, 1, 48, 36)
t = time.mktime(t)
text = time.strftime("%M:%S", time.gmtime(t))
text_surface, rect = self.font.render(text, (0, 0, 0))
self.screen.blit(text_surface, (self.x, self.y))
""" Utility functions """
def draw_arrow(screen, x: int, y: int, size_x: int, size_y: int, color: Color = Color.BLACK):
pygame.draw.polygon(screen, color.value,
((x, y + 2*size_y), (x, y + 4*size_y), (x + 4*size_x, y + 4*size_y),
(x + 4*size_x, y + 6*size_y), (x + 6*size_x, y + 3*size_y),
(x + 4*size_x, y), (x + 4*size_x, y + 2*size_y)))
|
dacaf7998b9ca3a71b6b90690ba952fb56349ab9 | Kanthus123/Python | /Design Patterns/Creational/Abstract Factory/doorfactoryAbs.py | 2,091 | 4.1875 | 4 | #A factory of factories; a factory that groups the individual but related/dependent factories together without specifying their concrete classes.
#Extending our door example from Simple Factory.
#Based on your needs you might get a wooden door from a wooden door shop,
#iron door from an iron shop or a PVC door from the relevant shop.
#Plus you might need a guy with different kind of specialities to fit the door,
#for example a carpenter for wooden door, welder for iron door etc.
#As you can see there is a dependency between the doors now,
#wooden door needs carpenter, iron door needs a welder etc.
class Door:
def get_descricao(self):
raise NotImplementedError
class WoodenDoor(Door):
def get_descricao(self):
print('Eu sou uma porta de Madeira')
def IronDoor(Door):
def get_descricao(self):
print('Eu sou uma porta de Ferro')
class DoorFittingExpert:
def get_descricao(self):
raise NotImplementedError
class Welder(DoorFittingExpert):
def get_descricao(self):
print('Eu apenas posso colocar portas de ferro')
class Carpenter(DoorFittingExpert):
def get_descricao(self):
print('Eu apenas posso colocar portas de madeira')
class DoorFactory:
def fazer_porta(self):
raise NotImplementedError
def fazer_profissional(self):
raise NotImplementedError
class WoodenDoorFactory(DoorFactory):
def fazer_porta(self):
return WoodenDoor()
def fazer_profissional(self):
return Carpenter()
class IronDoorFactory(DoorFactory):
def fazer_porta(self):
return IronDoor()
def fazer_profissional(self):
return Welder()
if __name__ == '__main__':
wooden_factory = WoodenDoorFactory()
porta = wooden_factory.fazer_porta()
profissional = wooden_factory.fazer_profissional()
porta.get_descricao()
profissional.get_descricao()
iron_factory = IronDoorFactory()
porta = iron_factory.fazer_porta()
profissional = iron_factory.fazer_profissional()
porta.get_descricao()
profissional.get_descricao()
|
ab049070f8348f4af8caeb601aee062cc7a76af2 | Kanthus123/Python | /Design Patterns/Structural/Decorator/VendaDeCafe.py | 1,922 | 4.46875 | 4 | #Decorator pattern lets you dynamically change the behavior of an object at run time by wrapping them in an object of a decorator class.
#Imagine you run a car service shop offering multiple services.
#Now how do you calculate the bill to be charged?
#You pick one service and dynamically keep adding to it the prices for the provided services till you get the final cost.
#Here each type of service is a decorator.
class Cofe:
def get_custo(self):
raise NotImplementedError
def get_descricao(self):
raise NotImplementedError
class CafeSimples(Cafe):
def get_custo(self):
return 10
def get_descricao(self):
return 'Cafe Simples'
class CafeComLeite(self):
def __init__(self, cafe):
self.cafe = cafe
def get_custo(self):
return self.cafe.get_custo() + 2
def get_descricao(self):
return self.cafe.get_descricao() + ', leite'
class CafeComCreme(Cafe):
def __init__(self, cafe):
self.cafe = cafe
def get_custo(self):
return self.cafe.get_custo() + 5
def get_descricao(self):
return self.cafe.get_descricao() + ', creme'
class Capuccino(Cafe):
def __init__(self, cafe):
self.cafe = cafe
def get_custo(self):
return self.cafe.get_custo() + 3
def get_descricao(self):
return self.cafe.get_descricao() + ', chocolate'
if __name__ == '__main__':
cafe = CafeSimples()
assert cafe.get_custo() == 10
assert coffee.get_description() == 'Cafe Simples'
cafe = CafeComLeite(cafe)
assert coffee.get_cost() == 12
assert coffee.get_description() == 'Cafe Simples, Leite'
cafe = CafeComCreme(cafe)
assert coffee.get_cost() == 17
assert coffee.get_description() == 'Cafe Simples, Leite, Creme'
cafe = Capuccino(cafe)
assert coffee.get_cost() == 20
assert coffee.get_description() == 'Cafe Simples, Leite, Chocolate'
|
4bcdaa732a2a499c3e52a902911b1a6cbc6636bf | Kanthus123/Python | /Design Patterns/Behavioral/Strategy/main.py | 817 | 3.671875 | 4 | #Strategy pattern allows you to switch the algorithm or strategy based upon the situation.
#Consider the example of sorting, we implemented bubble sort but the data started to grow and bubble sort started getting very slow.
#In order to tackle this we implemented Quick sort. But now although the quick sort algorithm was doing better for large datasets,
#it was very slow for smaller datasets. In order to handle this we implemented a strategy where for small datasets,
#bubble sort will be used and for larger, quick sort.
from order import Order
from calculate_shipping import CalculateShipping
from shippings import Default, Express
calculate_shipping = CalculateShipping()
order = Order(500)
calculate_shipping.execute_calculation(order, Default())
calculate_shipping.execute_calculation(order, Express())
|
478e6714f68fb421aff714cf178486c60d46980b | russellgao/algorithm | /dailyQuestion/2020/2020-05/05-14/python/solution.py | 376 | 3.78125 | 4 | from functools import reduce
# 位运算 写法1
def singleNumber1(nums: [int]) -> int:
return reduce(lambda x, y: x ^ y, nums)
# 位运算 写法2
def singleNumber2(nums: [int]) -> int :
result = nums[0]
for i in range(1,len(nums)) :
result ^= nums[i]
return result
if __name__ == "__main__" :
nums = [2,3,4,3,2]
print(singleNumber2(nums)) |
ba0c5f0469a2b8ef74c669af85355c81c4a40eb6 | russellgao/algorithm | /dailyQuestion/2020/2020-10/10-10/python/solution.py | 891 | 4 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def partition(head: ListNode, x: int) -> ListNode:
first = first_head = ListNode(0)
second = second_head = ListNode(0)
while head:
if head.val < x:
first.next = head
first = first.next
else:
second.next = head
second = second.next
head = head.next
second.next = None
first.next = second_head.next
return first_head.next
if __name__ == "__main__" :
node = ListNode(1)
node.next = ListNode(4)
node.next.next = ListNode(3)
node.next.next.next = ListNode(2)
node.next.next.next.next = ListNode(5)
node.next.next.next.next.next = ListNode(2)
result = partition(node,3)
while result :
print(result.val)
result = result.next |
a6f65dc2d6ac9f5f160229c2dc76b2d74c150550 | russellgao/algorithm | /dailyQuestion/2020/2020-07/07-29/python/solution_n.py | 263 | 3.890625 | 4 |
# 一次遍历
def missingNumber(nums: [int]) -> int:
for i,v in enumerate(nums) :
if i != v :
return i
return nums[-1] + 1
if __name__ == "__main__" :
nums = [0,1,2,3,4,5,6,7,9]
result = missingNumber(nums)
print(result) |
1587894d5e65ee725de94d02e15cd0ec84f1987b | russellgao/algorithm | /dailyQuestion/2020/2020-06/06-02/python/solution.py | 445 | 3.515625 | 4 |
def lengthOfLongestSubstring(s: str) -> int:
tmp = set()
result = 0
j = 0
n = len(s)
for i in range(n) :
if i != 0 :
tmp.remove(s[i-1])
while j < n and s[j] not in tmp :
tmp.add(s[j])
j += 1
result = max(result, j - i)
return result
if __name__ == "__main__" :
a = [23,4,5,6]
s = "abcabcbb"
result = lengthOfLongestSubstring(s)
print(result)
|
47ddbc6c436d80ff4ba68199da5e803edabf3402 | russellgao/algorithm | /dailyQuestion/2020/2020-05/05-22/python/solution_dlinknode.py | 2,137 | 3.84375 | 4 | # 双向链表求解
class DlinkedNode():
def __init__(self):
self.key = 0
self.value = 0
self.next = None
self.prev = None
class LRUCache():
def __init__(self, capacity: int):
self.capacity = capacity
self.size = 0
self.cache = {}
self.head = DlinkedNode()
self.tail = DlinkedNode()
self.head.next = self.tail
self.tail.prev = self.head
def _add_node(self, node):
""" 始终放在head的右边 """
node.prev = self.head
node.next = self.head.next
self.head.next.prev = node
self.head.next = node
def _remove_node(self, node):
"""删除一个节点"""
_prev = node.prev
_next = node.next
_prev.next = _next
_next.prev = _prev
def _move_to_head(self, node):
"""
先删除再增加
:param node:
:return:
"""
self._remove_node(node)
self._add_node(node)
def _pop_tail(self):
"""
删除最后一个节点的前一个
:return:
"""
res = self.tail.prev
self._remove_node(res)
return res
def get(self, key: int) -> int:
node = self.cache.get(key, None)
if not node:
return -1
self._move_to_head(node)
return node.value
def put(self, key: int, value: int) -> None:
node = self.cache.get(key, None)
if not node:
node = DlinkedNode()
node.key = key
node.value = value
self.size += 1
self.cache[key] = node
self._add_node(node)
if self.size > self.capacity:
tail = self._pop_tail()
del self.cache[tail.key]
self.size -= 1
else:
node.value = value
self._move_to_head(node)
if __name__ == "__main__" :
lru = LRUCache(2)
lru.put(1,1)
lru.put(2,2)
a = lru.get(1)
lru.put(3,3)
b = lru.get(2)
lru.put(4,4)
c = lru.get(1)
d = lru.get(3)
e = lru.get(4)
print()
|
98786826bd97d037c30c7f2b4244b7101ccd963e | russellgao/algorithm | /data_structure/heap/python/002.py | 1,317 | 4.03125 | 4 | # 堆排序
def buildMaxHeap(lists):
"""
构造最大堆
:param lists:
:return:
"""
llen = len(lists)
for i in range(llen >> 1, -1, -1):
heapify(lists, i, llen)
def heapify(lists, i, llen):
"""
堆化
:param lists:
:param i:
:return:
"""
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < llen and lists[left] > lists[largest]:
largest = left
if right < llen and lists[right] > lists[largest]:
largest = right
if largest != i :
swap(lists, i, largest)
heapify(lists, largest, llen)
def swap(lists, i, j):
"""
交换列表中的两个元素
:param lists:
:param i:
:param j:
:return:
"""
lists[i], lists[j] = lists[j], lists[i]
def heapSort(lists):
"""
堆排序,从小到大进行排序
需要构造一个最大堆,然后首位交换,然后lists 的长度-1, 重复这个过程,直至lists中只剩一个元素
:param lists:
:return:
"""
llen = len(lists)
buildMaxHeap(lists)
for i in range(len(lists)-1, 0, -1):
swap(lists, 0, i)
llen -= 1
heapify(lists, 0, llen)
return lists
if __name__ == "__main__":
arr = [8, 3, 5, 1, 6, 4, 9, 0, 2]
b = heapSort(arr)
print(b)
|
77ec5582550e18cce771f24058e78bc18686ec9a | russellgao/algorithm | /dailyQuestion/2020/2020-04/04-29/python/solution.py | 1,683 | 3.84375 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 方法一
# 递归,原问题可以拆分成自问题,并且自问题和原问题的问题域完全一样
# 本题以前k个listnode 为原子进行递归
def reverseKGroup1(head: ListNode, k: int) -> ListNode:
cur = head
count = 0
while cur and count!= k:
cur = cur.next
count += 1
if count == k:
# 以k个进行递归
cur = reverseKGroup1(cur, k)
while count:
# 在k个单位内进行反转
tmp = head.next
head.next = cur
cur = head
head = tmp
count -= 1
head = cur
return head
# 方法二
def reverseKGroup2(head: ListNode, k: int) -> ListNode:
dummy = ListNode(0)
dummy.next = head
pre = dummy
tail = dummy
while True:
count = k
while count and tail:
count -= 1
tail = tail.next
if not tail:
break
head = pre.next
while pre.next != tail:
cur = pre.next # 获取下一个元素
# pre与cur.next连接起来,此时cur(孤单)掉了出来
pre.next = cur.next
cur.next = tail.next # 和剩余的链表连接起来
tail.next = cur # 插在tail后面
# 改变 pre tail 的值
pre = head
tail = head
return dummy.next
if __name__ == "__main__" :
node = ListNode(1)
node.next = ListNode(2)
node.next.next = ListNode(3)
node.next.next.next = ListNode(4)
node.next.next.next.next = ListNode(5)
result = reverseKGroup2(node,2)
print()
|
30cea365bbb1ea986b435692edfb5eb4118249cc | russellgao/algorithm | /dailyQuestion/2020/2020-08/08-06/python/solution_dict.py | 1,341 | 3.71875 | 4 | def palindromePairs(words: [str]) -> [[int]]:
indices = {}
result = []
n = len(words)
def reverse(word):
_w = list(word)
n = len(word)
for i in range(n >> 1):
_w[i], _w[n - 1 - i] = _w[n - i - 1], _w[i]
return "".join(_w)
def isPalindromes(word: str, left: int, right:int) -> bool:
for i in range(right - left + 1):
if word[left + i] != word[right - i]:
return False
return True
def findWord(word, left, right):
v = indices.get(word[left:right+1])
if v is not None :
return v
return -1
for i in range(n):
indices[reverse(words[i])] = i
for i in range(n):
word = words[i]
m = len(word)
for j in range(m + 1):
if isPalindromes(word, j, m - 1) :
leftid = findWord(word, 0 , j-1)
if leftid != -1 and leftid != i :
result.append([i,leftid])
if j > 0 and isPalindromes(word, 0,j-1) :
leftid = findWord(word,j,m-1)
if leftid != -1 and leftid != i :
result.append([i,leftid])
return result
if __name__ == "__main__" :
words = ["abcd", "dcba", "lls", "s", "sssll"]
result = palindromePairs(words)
print(result)
|
32c5ca8e7beb18feafd101e6e63da060c3c47647 | russellgao/algorithm | /data_structure/binaryTree/preorder/preoder_traversal_items.py | 695 | 4.15625 | 4 |
# 二叉树的中序遍历
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# 迭代
def preorderTraversal(root: TreeNode) ->[int]:
result = []
if not root:
return result
queue = [root]
while queue:
root = queue.pop()
if root:
result.append(root.val)
if root.right:
queue.append(root.right)
if root.left:
queue.append(root.left)
return result
if __name__ == "__main__":
root = TreeNode(1)
root.right = TreeNode(2)
root.right.left = TreeNode(3)
result = preorderTraversal(root)
print(result)
|
5723367d25964f32d4f5bc67a99e3f824309f639 | russellgao/algorithm | /dailyQuestion/2020/2020-10/10-01/python/solution.py | 927 | 4.03125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def increasingBST(root: TreeNode) -> TreeNode:
result = node = TreeNode(0)
queue = []
while root or len(queue) > 0 :
while root :
queue.append(root)
root = root.left
root = queue[len(queue)-1]
queue = queue[:len(queue)-1]
node.right = TreeNode(root.val)
node = node.right
root = root.right
return result.right
if __name__ == "__main__" :
node = TreeNode(3)
node.left = TreeNode(5)
node.right = TreeNode(1)
node.left.left = TreeNode(6)
node.left.right = TreeNode(2)
node.left.right.left = TreeNode(7)
node.left.right.right = TreeNode(4)
node.right.left = TreeNode(0)
node.right.right = TreeNode(8)
result = increasingBST(node)
print(result) |
b8189f9da4e8491b8871a75225d4376c9ea2cc0c | russellgao/algorithm | /dailyQuestion/2020/2020-06/06-06/python/solution.py | 476 | 3.796875 | 4 |
def longestConsecutive(nums: [int]) -> int:
nums = set(nums)
longest = 0
for num in nums:
if num - 1 not in nums:
current = num
current_len = 1
while current + 1 in nums:
current += 1
current_len += 1
longest = max(longest, current_len)
return longest
if __name__ == "__main__" :
nums = [100, 4, 200, 1, 3, 2]
result = longestConsecutive(nums)
print(result)
|
cb8bdd7d8b00d9b6214787b82fe5766228741eee | russellgao/algorithm | /data_structure/sort/tim_sort.py | 2,031 | 3.734375 | 4 | import time
def binary_search(the_array, item, start, end): # 二分法插入排序
if start == end:
if the_array[start] > item:
return start
else:
return start + 1
if start > end:
return start
mid = round((start + end) / 2)
if the_array[mid] < item:
return binary_search(the_array, item, mid + 1, end)
elif the_array[mid] > item:
return binary_search(the_array, item, start, mid - 1)
else:
return mid
def insertion_sort(the_array):
l = len(the_array)
for index in range(1, l):
value = the_array[index]
pos = binary_search(the_array, value, 0, index - 1)
the_array = the_array[:pos] + [value] + the_array[pos:index] + the_array[index + 1:]
return the_array
def merge(left, right): # 归并排序
if not left:
return right
if not right:
return left
if left[0] < right[0]:
return [left[0]] + merge(left[1:], right)
return [right[0]] + merge(left, right[1:])
def timSort(the_array):
runs, sorted_runs = [], []
length = len(the_array)
new_run = []
for i in range(1, length): # 将序列分割成多个有序的run
if i == length - 1:
new_run.append(the_array[i])
runs.append(new_run)
break
if the_array[i] < the_array[i - 1]:
if not new_run:
runs.append([the_array[i - 1]])
new_run.append(the_array[i])
else:
runs.append(new_run)
new_run = []
else:
new_run.append(the_array[i])
for item in runs:
sorted_runs.append(insertion_sort(item))
sorted_array = []
for run in sorted_runs:
sorted_array = merge(sorted_array, run)
print(sorted_array)
arr = [45, 2.1, 3, 67, 21, 90, 20, 13, 45, 23, 12, 34, 56, 78, 90, 0, 1, 2, 3, 1, 2, 9, 7, 8, 4, 6]
t0 = time.perf_counter()
timSort(arr)
t1 = time.perf_counter()
print('共%.5f秒' % (t1 - t0))
|
a4d555397fb194beb604dd993a6b08c746409046 | russellgao/algorithm | /dailyQuestion/2020/2020-07/07-11/python/solution.py | 546 | 3.828125 | 4 | def subSort(array: [int]) -> [int]:
n = len(array)
first,last = -1,-1
if n == 0 :
return [first,last]
min_a = float("inf")
max_a = float("-inf")
for i in range(n) :
if array[i] >= max_a :
max_a = array[i]
else :
last = i
if array[n-1-i] <= min_a :
min_a = array[n-1-i]
else :
first = n-i-1
return [first,last]
if __name__ == "__main__" :
array = [1,2,4,7,10,11,7,12,6,7,16,18,19]
result = subSort(array)
print(result) |
c836d3a26bb6d7432f734c7a771df38e8aaec095 | russellgao/algorithm | /dailyQuestion/2020/2020-07/07-18/python/solution_recurse.py | 708 | 3.875 | 4 | def isInterleave(s1, s2, s3):
"""
:type s1: str
:type s2: str
:type s3: str
:rtype: bool
"""
m = len(s1)
n = len(s2)
t = len(s3)
if m + n != t:
return False
dp = [[False] * (n + 1) for _ in range(m + 1)]
dp[0][0] = True
for i in range(m + 1):
for j in range(n + 1):
if i > 0:
dp[i][j] = dp[i][j] or (dp[i - 1][j] and s1[i - 1] == s3[i + j - 1])
if j > 0:
dp[i][j] = dp[i][j] or (dp[i][j - 1] and s2[j - 1] == s3[i + j - 1])
return dp[m][n]
if __name__ == "__main__" :
s1 = "aabcc"
s2 = "dbbca"
s3 = "aadbbbaccc"
result = isInterleave(s1,s2,s3)
print(result)
|
bd9249d9d6593d652adca04e69220e3326615cd4 | russellgao/algorithm | /dailyQuestion/2020/2020-06/06-14/python/solution_vertical.py | 432 | 3.96875 | 4 | def longestCommonPrefix(strs: [str]) -> str:
if not strs:
return ""
length, count = len(strs[0]), len(strs)
for i in range(length):
c = strs[0][i]
if any(i == len(strs[j]) or strs[j][i] != c for j in range(1, count)):
return strs[0][:i]
return strs[0]
if __name__ == "__main__":
strs = ["flower", "flow", "flight"]
result = longestCommonPrefix(strs)
print(result)
|
ff3ce63ef2e076344a7e1226b9fadf5a37a5653b | russellgao/algorithm | /dailyQuestion/2021/2021-03/03-20/python/solution.py | 961 | 3.515625 | 4 | class Solution:
def evalRPN(self, tokens: [str]) -> int:
stack = []
for i in range(len(tokens)) :
tmp = tokens[i]
if tmp == "+" :
num1 = stack.pop()
num2 = stack.pop()
stack.append(num2 + num1)
elif tmp == "-" :
num1 = stack.pop()
num2 = stack.pop()
stack.append(num2 - num1)
elif tmp == "*" :
num1 = stack.pop()
num2 = stack.pop()
stack.append(num2 * num1)
elif tmp == "/" :
num1 = stack.pop()
num2 = stack.pop()
stack.append(int(num2 / num1))
else :
stack.append(int(tmp))
return stack[0]
if __name__ == "__main__" :
tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
s = Solution()
res = s.evalRPN(tokens)
print(res)
|
9d4fa8524fe6b0b3172debd49bf081e98f5a0282 | russellgao/algorithm | /dailyQuestion/2020/2020-06/06-09/python/solution_mod.py | 335 | 3.6875 | 4 | # 动态求余法
def translateNum(num: int) -> int:
f_1 = f_2 = 1
while num:
pre = num % 100
f = f_1 + f_2 if pre >= 10 and pre <= 25 else f_1
f_2 = f_1
f_1 = f
num = num // 10
return f_1
if __name__ == '__main__' :
num = 12258
result = translateNum(num)
print(result)
|
861fab844f5dcbf86c67738354803e27a0a303e9 | russellgao/algorithm | /dailyQuestion/2020/2020-05/05-31/python/solution_recursion.py | 950 | 4.21875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# 递归
def isSymmetric(root: TreeNode) -> bool:
def check(left, right):
if not left and not right:
return True
if not left or not right:
return False
return left.val == right and check(left.left, right.right) and check(left.right, right.left)
return check(root, root)
if __name__ == "__main__":
# root = TreeNode(1)
# root.left = TreeNode(2)
# root.right = TreeNode(2)
#
# root.left.left = TreeNode(3)
# root.left.right = TreeNode(4)
#
# root.right.left = TreeNode(4)
# root.right.right = TreeNode(3)
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(2)
root.left.left = TreeNode(3)
root.right.right = TreeNode(3)
result = isSymmetric(root)
print(result)
|
21f1cf35cd7b3abe9d67607712b62bfa4732e4ce | russellgao/algorithm | /dailyQuestion/2020/2020-05/05-01/python/solution.py | 944 | 4.125 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def reverseList(head):
"""
递归 反转 链表
:type head: ListNode
:rtype: ListNode
"""
if not head :
return None
if not head.next :
return head
last = reverseList(head.next)
head.next.next = head
head.next = None
return last
def reverseList_items(head) :
"""
迭代 反转 链表
:type head: ListNode
:rtype: ListNode
"""
pre = None
current = head
while current:
tmp = current.next
current.next = pre
pre = current
current = tmp
return pre
if __name__ == '__main__':
node = ListNode(1)
node.next = ListNode(2)
node.next.next = ListNode(3)
node.next.next.next = ListNode(4)
node.next.next.next.next = ListNode(5)
result = reverseList(node)
print() |
86bee5da92c7b029a182b67d9e3aa4bb2eb1b949 | franztrierweiler/maths_python | /exercices_02mars.py | 2,000 | 3.8125 | 4 | from fractions import *
def somme():
S = 1
for i in range (1,21):
S = S + pow(Fraction(1,3),i)
# Converts fraction to float
# and returns the result
return float(S);
def compte_espaces(phrase):
nbre = 0
for caractere in phrase:
if caractere==" ":
nbre=nbre+1
return nbre
def Syracuse(n):
resultat = n
while (resultat!=1):
if (resultat % 2) == 0:
resultat = resultat // 2
else:
resultat = (3 * resultat) + 1
return resultat
def Syracuse2(n):
resultat = n
compteur = 0
while (resultat!=1):
compteur = compteur + 1
if (resultat % 2) == 0:
resultat = resultat // 2
else:
resultat = (3 * resultat) + 1
return compteur
def Maximum(n):
# We are looking for the value between 0 and n for which
# Syracuse2(n) is the greatest.
i = 1
candidat = i
temps_vol = 1
while (i <= n):
# Check if new flight length is greater than previous one !
if (Syracuse2(i) > temps_vol):
temps_vol = Syracuse2(i)
candidat = i
i = i + 1
return candidat
def produit_impairs(i):
P = 1
for k in range (1, i):
P = P * (2*k - 1)
return P
print ("Somme = " + str(somme() ))
la_phrase = "Voici une phrase pour le programmeur Badie"
print ("Il y a " + str(compte_espaces(la_phrase)) + " espaces dans la phrase - " + la_phrase + "-")
N=5000
print("Temps de vol le plus haut entre 1 et N = " + str(N) + " est pour n = " + str(Maximum(N)))
print("Il vaut " + str(Syracuse2(Maximum(N))))
n=10000000000
print("Syracuse(" + str(n) + ") = " + str(Syracuse(n)) + " avec un temps de vol de " + str(Syracuse2(n)))
N=2
print ("Produit des " + str(N) + "-1 premiers nombres impairs = " + str(produit_impairs(N)))
N=5
print ("Produit des " + str(N) + "-1 premiers nombres impairs = " + str(produit_impairs(N))) |
407273956e8e87a116912ee44dc192e8233f5fac | swainsubrat/Haw | /Dependencies/DataFrameBuilder.py | 5,313 | 3.9375 | 4 | """
Structures dataframes for plotting
"""
import re
import pandas as pd
from io import StringIO
from pandas.core.frame import DataFrame
def basicDataFrameBuilder(FILE: StringIO) -> DataFrame:
"""
Function to pre-process the raw text file and format it
to get a dataframe out of it
1. Datetime extraction.
2. Name extraction.
Args:
FILE(StringIO): File containing raw extracted text.
Returns:
df(DataFrame): Dataframe of the messages.
"""
lines = FILE.readlines()
list_df = []
for line in lines:
line = line.rstrip('\n').split(" - ")
if re.search(r"\d\d\/\d\d\/\d\d\d\d, (\d\d|\d):\d\d", line[0]):
name_message = line[1].split(": ")
if len(name_message) <= 1:
continue
date, time = line[0].split(", ")
name = name_message[0]
message = ""
for i in range(1, len(name_message)):
message += name_message[i]
list_df.append([date, time, name, message])
else:
try:
for item in line:
list_df[-1][-1] += item
except Exception as e:
print("Exception:", e)
df = DataFrame(list_df, columns=['Date', 'Time', 'Name', 'Message'])
df['Day'] = pd.DatetimeIndex(df['Date']).day
df['Month'] = pd.DatetimeIndex(df['Date']).month
df['Month_Year'] = pd.to_datetime(df['Date']).dt.to_period('M')
df['Year'] = pd.DatetimeIndex(df['Date']).year
return df
def messageDataFrameBuilder(FILE: StringIO,
TOP: int=10) -> dict:
"""
Function to process the messages of the members
1. Message count, group by Name.
2. Message count, group by Date.
3. Message count, group by Month.
4. Message count, group by Year.
Args:
FILE(StringIO): File containing raw extracted text.
TOP(int): Top n names to show and show others as Others.
Returns:
dfm(dict(DataFrame)): Dataframes after processing
"""
df = basicDataFrameBuilder(FILE=FILE)
dfm = df.groupby('Name').Message.count().\
reset_index(name="Message Count")
dfm.sort_values(
by="Message Count",
ascending=False,
inplace=True,
ignore_index=True
)
dfm.loc[dfm.index >= TOP, 'Name'] = 'Others'
dfm = dfm.groupby(
"Name"
)["Message Count"].sum().reset_index(name="Message Count")
dfm.sort_values(
by="Message Count",
ascending=False,
inplace=True,
ignore_index=True)
# dfmD = df.groupby('Date').Message.count().\
# reset_index(name='Count')
# dfmMY = df.groupby('Month_Year').Message.count().\
# reset_index(name='Count')
dfmY = df.groupby('Year').Message.count().\
reset_index(name='Count')
DFM = {
"dfm": dfm,
# "dfmD": dfmD,
# "dfmMY": dfmMY,
"dfmY": dfmY
}
return DFM
def emojiDataFrameBuilder(FILE: StringIO,
TOP: int=10) -> dict:
"""
Function to process the emojis of the members
1. Emoji count, group by Name.
2. Emoji count, group by Date.
3. Emoji count, group by Month.
4. Emoji count, group by Year.
5. Emoji count, group by Type.
Args:
FILE(StringIO): File containing raw extracted text.
TOP(int): Top n names to show and show others as Others.
Returns:
dfm(dict(DataFrame)): Dataframes after processing
"""
df = basicDataFrameBuilder(FILE=FILE)
import emoji
total = 0
count = {}
emoji_cnt = []
for message in df['Message']:
emoji_cnt.append(emoji.emoji_count(message))
emoji_list = emoji.emoji_lis(message)
for item in emoji_list:
if (item["emoji"] in count):
count[item["emoji"]] += 1
else:
count[item["emoji"]] = 1
total += emoji.emoji_count(message)
columns = ['Emojis', 'Count']
dfe = pd.DataFrame(columns=columns)
for key, value in count.items():
data = {'Emojis': key, 'Count': value}
dfe = dfe.append(data, ignore_index=True)
dfe.sort_values(by="Count",
ascending=False,
inplace=True,
ignore_index=True)
dfe.loc[dfe.index >= TOP, 'Emojis'] = 'Others'
dfe = dfe.groupby("Emojis")["Count"].sum().reset_index(name="Count")
df.insert(loc=6, column='Emoji Count', value=emoji_cnt)
# dfeD = df.groupby('Date')['Emoji Count'].sum().\
# reset_index(name='Count')
# dfeMY = df.groupby('Month_Year')['Emoji Count'].sum().\
# reset_index(name='Count')
dfeY = df.groupby('Year')['Emoji Count'].sum().\
reset_index(name='Count')
dfeg = df.groupby('Name')['Emoji Count'].sum().\
reset_index(name="Count")
dfeg.sort_values(
by="Count",
ascending=False,
inplace=True,
ignore_index=True
)
dfeg.loc[dfeg.index >= TOP, 'Name'] = 'Others'
dfeg = dfeg.groupby("Name")["Count"].sum().reset_index(name="Count")
DFE = {
"dfe": dfe,
"dfeg": dfeg,
# "dfeD": dfeD,
# "dfeMY": dfeMY,
"dfeY": dfeY
}
return DFE
|
fc94459d32944d0e67d1870d0b2e864263dc8319 | Narusi/Python-Kurss | /Uzdevums Lists.py | 3,209 | 4.1875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Klases Uzdevumi - Lists
# ## 1.a Vidējā vērtība
# Uzrakstīt programmu, kas liek lietotājam ievadīt skaitļus(float).
# Programma pēc katra ievada rāda visu ievadīto skaitļu vidējo vērtību.
# PS. 1a var iztikt bez lists
#
# 1.b Programma rāda gan skaitļu vidējo vērtību, gan VISUS ievadītos skaitļus
# PS Iziešana no programmas ir ievadot "q"
#
# 1.c Programma nerāda visus ievadītos skaitļus bet gan tikai TOP3 un BOTTOM3 un protams joprojām vidējo.
# In[2]:
numbs = []
while True:
numberStr = input("\nIevadiet skaitli: ")
if "q" not in numberStr.lower():
if "," in numberStr:
numberStr = numberStr.replace(',','.').strip()
numbs.append(float(numberStr))
print("Vidējā vērtība:",sum(numbs)/len(numbs))
numbs.sort()
print("Visi ievadītie skaitļi:",numbs)
if len(numbs) >= 6:
print("TOP3 un BOTTOM3:",numbs[:3] + numbs[-3:])
print("Pēdējais ievadītais skaitlis:",float(numberStr))
else:
break
# ## 2. Kubu tabula
# Lietotājs ievada sākumu (veselu skaitli) un beigu skaitli.
# Izvads ir ievadītie skaitļi un to kubi
# <br>Piemēram: ievads 2 un 5 (divi ievadi)
# <br>Izvads
# <br>2 kubā: 8
# <br>3 kubā: 27
# <br>4 kubā: 64
# <br>5 kubā: 125
# <br>Visi kubi: [8,27,64,125]
# <br><br>PS teoretiski varētu iztikt bez list, bet ar list būs ērtāk
# In[1]:
pirmaisSk = int(input("Ievadiet sākotnējo skaitli: "))
otraisSk = int(input("Ievadiet noslēdzošo skaitli: "))
kubi = []
for i in range(pirmaisSk, otraisSk+1):
print("{} kubā: {}".format(i, i**3))
kubi.append(i**3)
print('Visi kubi:', kubi)
# ## 3. Apgrieztie vārdi
# Lietotājs ievada teikumu.
# Izvadam visus teikuma vārdus apgrieztā formā.
# <br>Alus kauss -> Sula ssuak
# <br>PS Te varētu noderēt split un join operācijas.
# In[3]:
teikums = input("Ievadiet teikumu: ")
smukiet = []
jaunsTeik = True
for vards in teikums.split(" "):
if "." in vards:
smukiet.append(vards[:-1][::-1].lower()+".")
jaunsTeik = True
elif "!" in vards:
smukiet.append(vards[:-1][::-1].lower()+"!")
jaunsTeik = True
elif "?" in vards:
smukiet.append(vards[:-1][::-1].lower()+"?")
jaunsTeik = True
else:
if jaunsTeik:
smukiet.append(vards[::-1].title())
jaunsTeik = False
else:
smukiet.append(vards[::-1].lower())
print(" ".join(smukiet))
# ## 4. Pirmskaitļi
# šis varētu būt nedēļas nogales uzdevums, klasē diez vai pietiks laika
# Atrodiet un izvadiet pirmos 20 (vēl labāk iespēja izvēlēties cik pirmos pirmskaitļus gribam) pirmskaitļus saraksta veidā t.i. [2,3,5,7,11,...]
# In[5]:
numbCount = int(input("Ieavadiet pirmskaitļu skaitu: "))
nCount = 2
numb = 3
pirmsskaitli = [1, 2]
while nCount <= numbCount:
irPSkaitlis = True
for i in range(2,numb):
if numb % i == 0:
irPSkaitlis = False
if irPSkaitlis:
nCount += 1
pirmsskaitli.append(numb)
numb += 1
print(pirmsskaitli)
# In[ ]:
|
d278d8c5efedbd61317118887461b052690dd605 | wulinlw/leetcode_cn | /常用排序算法/quicksort.py | 828 | 3.8125 | 4 | #!/usr/bin/python
#coding:utf-8
# 快速排序
def partition(arr,low,high):
i = ( low-1 ) # 最小元素索引
pivot = arr[high]
for j in range(low , high):
# 当前元素小于或等于 pivot
if arr[j] <= pivot:
i = i+1
arr[i],arr[j] = arr[j],arr[i]
# print(i,arr)
arr[i+1],arr[high] = arr[high],arr[i+1]#交换下i+1he结尾,用于下次基准比较
# print(arr)
return ( i+1 )
# 快速排序函数
# arr[] --> 排序数组
# low --> 起始索引
# high --> 结束索引
def quickSort(arr,low,high):
if low < high:
pi = partition(arr,low,high)
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)
return arr
arr = [1,2,5,3,4]
arr = [10, 7, 8, 9, 1, 5]
n = len(arr)
re = quickSort(arr,0,n-1)
print(re) |
8beaa095846c553f6c970e062494b068733a5d6a | wulinlw/leetcode_cn | /leetcode-vscode/671.二叉树中第二小的节点.py | 2,205 | 3.734375 | 4 | #
# @lc app=leetcode.cn id=671 lang=python3
#
# [671] 二叉树中第二小的节点
#
# https://leetcode-cn.com/problems/second-minimum-node-in-a-binary-tree/description/
#
# algorithms
# Easy (45.43%)
# Likes: 61
# Dislikes: 0
# Total Accepted: 8.5K
# Total Submissions: 18.6K
# Testcase Example: '[2,2,5,null,null,5,7]'
#
# 给定一个非空特殊的二叉树,每个节点都是正数,并且每个节点的子节点数量只能为 2 或
# 0。如果一个节点有两个子节点的话,那么这个节点的值不大于它的子节点的值。
#
# 给出这样的一个二叉树,你需要输出所有节点中的第二小的值。如果第二小的值不存在的话,输出 -1 。
#
# 示例 1:
#
#
# 输入:
# 2
# / \
# 2 5
# / \
# 5 7
#
# 输出: 5
# 说明: 最小的值是 2 ,第二小的值是 5 。
#
#
# 示例 2:
#
#
# 输入:
# 2
# / \
# 2 2
#
# 输出: -1
# 说明: 最小的值是 2, 但是不存在第二小的值。
#
#
#
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 最小的是root
# dfs查找,
# 边界条件是
# 1.到空节点还没发现比root大的,就是都相等,返回-1
# 2.找到立即返回
# 左边都小于root,那就在右边有大于的
# 右边都小于root,那就在左边有大于的
# 左右都大于就返回较小的
def findSecondMinimumValue(self, root: TreeNode) -> int:
if not root: return -1
minval = root.val
def dfs(root):
nonlocal minval
if not root :return -1
if root.val>minval:
return root.val
l = dfs(root.left)
r = dfs(root.right)
if l<0:return r
if r<0:return l
return min(l,r)
return dfs(root)
# @lc code=end
t1 = TreeNode(2)
t2 = TreeNode(2)
t3 = TreeNode(5)
t4 = TreeNode(5)
t5 = TreeNode(7)
root = t1
root.left = t2
root.right = t3
t3.left = t4
t3.right = t5
o = Solution()
print(o.findSecondMinimumValue(root)) |
8504344ee52ab7c26d4e0a926e97ad8a8874308f | wulinlw/leetcode_cn | /程序员面试金典/面试题01.05.一次编辑.py | 1,707 | 3.75 | 4 | #!/usr/bin/python
#coding:utf-8
# 面试题 01.05. 一次编辑
# 字符串有三种编辑操作:插入一个字符、删除一个字符或者替换一个字符。 给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑。
# 示例 1:
# 输入:
# first = "pale"
# second = "ple"
# 输出: True
# 示例 2:
# 输入:
# first = "pales"
# second = "pal"
# 输出: False
# https://leetcode-cn.com/problems/one-away-lcci/
from typing import List
class Solution:
#编辑距离 类似题目,动态规划
#这题没有动态规划
def oneEditAway(self, first: str, second: str) -> bool:
if abs(len(first)-len(second)) > 1: #长度差大于1,false
return False
replace_count = 0
if len(first) == len(second): #长度相等,不同字符>2,false
for i in range(len(first)):
if first[i] != second[i]:
replace_count += 1
if replace_count >= 2:
return False
return True
#相差1的情况下,长串去掉当前字符,看看是否和短串一样
if len(second) > len(first): #长的放前面
first,second = second, first
if len(first) > len(second):
for i in range(len(first)): #遍历长的,每次取走一个,剩下的和second比是否一样
if first[0:i] + first[i+1:] == second:
return True
return False
first = "pale"
second = "ple"
o = Solution()
print(o.oneEditAway(first, second)) |
539c0e8e5f78fb080ec39bf80e69aa14161cbc3c | wulinlw/leetcode_cn | /剑指offer/55_2_平衡二叉树.py | 1,298 | 3.609375 | 4 | #!/usr/bin/python
#coding:utf-8
# // 面试题55(二):平衡二叉树
# // 题目:输入一棵二叉树的根结点,判断该树是不是平衡二叉树。如果某二叉树中
# // 任意结点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 归并的套路,先拿到子结果的集,在处理资结果的集
def IsBalanced(self, root):
if not root :return True, 0 #结束的时候是0
left, left_depth = self.IsBalanced(root.left)
right, right_depth = self.IsBalanced(root.right)
if left and right:
depth = left_depth - right_depth
if 1>=depth and depth>=-1: #高度不超过1
depth = 1+max(left_depth,right_depth)
return True,depth
return False,None
# 测试树
# 6
# 2 8
# 1 4 7 9
t1 = TreeNode(1)
t2 = TreeNode(2)
t4 = TreeNode(4)
t6 = TreeNode(6)
t7 = TreeNode(7)
t8 = TreeNode(8)
t9 = TreeNode(9)
root = t6
root.left = t2
root.right = t8
t2.left = t1
t2.right = t4
t8.left = t7
t8.right = t9
obj = Solution()
print(obj.IsBalanced(root)) |
28cb62abf374b9a10b964d944b5b858474c2422c | wulinlw/leetcode_cn | /leetcode-vscode/872.叶子相似的树.py | 1,729 | 3.921875 | 4 | #
# @lc app=leetcode.cn id=872 lang=python3
#
# [872] 叶子相似的树
#
# https://leetcode-cn.com/problems/leaf-similar-trees/description/
#
# algorithms
# Easy (62.23%)
# Likes: 49
# Dislikes: 0
# Total Accepted: 9.7K
# Total Submissions: 15.5K
# Testcase Example: '[3,5,1,6,2,9,8,null,null,7,4]\n' +
# '[3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]'
#
# 请考虑一颗二叉树上所有的叶子,这些叶子的值按从左到右的顺序排列形成一个 叶值序列 。
#
#
#
# 举个例子,如上图所示,给定一颗叶值序列为 (6, 7, 4, 9, 8) 的树。
#
# 如果有两颗二叉树的叶值序列是相同,那么我们就认为它们是 叶相似 的。
#
# 如果给定的两个头结点分别为 root1 和 root2 的树是叶相似的,则返回 true;否则返回 false 。
#
#
#
# 提示:
#
#
# 给定的两颗树可能会有 1 到 100 个结点。
#
#
#
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool:
def dfs(root,re):
if not root :return None
if not root.left and not root.right:
re.append(root.val)
dfs(root.left,re)
dfs(root.right,re)
return re
r1=dfs(root1,[])
r2=dfs(root2,[])
return r1==r2
# @lc code=end
# 2
# 2 5
# 5 7
t1 = TreeNode(2)
t2 = TreeNode(2)
t3 = TreeNode(5)
t4 = TreeNode(5)
t5 = TreeNode(7)
root = t1
root.left = t2
root.right = t3
t2.left = t4
t2.right = t5
o = Solution()
print(o.leafSimilar(root,root)) |
efcf849ffdf2209df24b021a2dff59c5138618aa | wulinlw/leetcode_cn | /程序员面试金典/面试题05.04.下一个数.py | 5,329 | 3.515625 | 4 | # #!/usr/bin/python
# #coding:utf-8
#
# 面试题05.04.下一个数
#
# https://leetcode-cn.com/problems/closed-number-lcci/
#
# 下一个数。给定一个正整数,找出与其二进制表达式中1的个数相同且大小最接近的那两个数(一个略大,一个略小)。
# 示例1:
#
#
# 输入:num = 2(或者0b10)
# 输出:[4, 1] 或者([0b100, 0b1])
#
#
# 示例2:
#
#
# 输入:num = 1
# 输出:[2, -1]
#
#
# 提示:
#
#
# num的范围在[1, 2147483647]之间;
# 如果找不到前一个或者后一个满足条件的正数,那么输出 -1。
#
#
#
# Medium 39.5%
# Testcase Example: 2
#
# 提示:
# 下一步:从每个蛮力解法开始。
# 下一个:想象一个二进制数,在整个数中分布一串1和0。假设你把一个1翻转成0,把一个0翻转成1。在什么情况下数会更大?在什么情况下数会更小?
# 下一步:如果你将1翻转成0,0翻转成1,假设 0 -> 1位更大,那么它就会变大。你如何使用这个来创建下一个最大的数字(具有相同数量的1)?
# 下一步:你能翻转0到1,创建下一个最大的数字吗?
# 下一步:把0翻转为1将创建一个更大的数字。索引越靠右,数字越大。如果有一个1001这样的数字,那么我们就想翻转最右边的0(创建1011)。但是如果有一个1010这样的数字,我们就不应该翻转最右边的1。
# 下一步:我们应该翻转最右边但非拖尾的0。数字1010会变成1110。完成后,我们需要把1翻转成0让数字尽可能小,但要大于原始数字(1010)。该怎么办?如何缩小数字?
# 下一步:我们可以通过将所有的1移动到翻转位的右侧,并尽可能地向右移动来缩小数字(在这个过程中去掉一个1)。
# 获取前一个:一旦你解决了“获取后一个”,请尝试翻转“获取前一个”的逻辑。
#
#
from typing import List
class Solution:
# 比 num 大的数:从右往左,找到第一个 01 位置,然后把 01 转为 10,右侧剩下的 1 移到右侧的低位,右侧剩下的位清0。
# 比 num 小的数:从右往左,找到第一个 10 位置,然后把 10 转为 01,右侧剩下的 1 移到右侧的高位,右侧剩下的位置0。
# https://leetcode-cn.com/problems/closed-number-lcci/solution/wei-yun-suan-by-suibianfahui/
def findClosedNumbers(self, num: int) -> List[int]:
mn, mx = 1, 2147483647
def findLarge(n):
# 从右开始找到第1个1
# 然后记录1的个数ones直到再遇到0或到最高位
# 然后将这个0变成1
# 然后右边的位数用000...111(ones-1个1)填充
checkMask = 1
bits = 0
while checkMask <= n and checkMask & n == 0: #找到左边第一个1为止
checkMask <<= 1
bits += 1 #右边0的个数
ones = 0
while checkMask <= n and checkMask & n != 0: #找到第一个0
ones = (ones << 1) + 1 #左边1的个数
checkMask <<= 1
bits += 1 #找到01,一共左移了多少位,
ones >>= 1 #因为ones初始化为1, 所以ones需要右移一位
n |= checkMask #01变10
# print("{:0>32b}".format(n))
n = (n >> bits) << bits #右边都变成0了
n |= ones #将右边填充上ones
return n if mn <= n <= mx else -1
def findSmall(n):
# 从右开始找到第1个0, 记录此过程1的个数ones
# 然后继续往左找直到再遇到1
# 然后将这个1变成0, ones也要左移一位(也可以初始化为1)
# 然后右边的位数用高位ones个1填充, 即构造出111...000, 可以直接基于ones构造
# 注意如果全为1的话是无解的, 直接返回-1
checkMask = 1
bits = 0
ones = 1
while checkMask <= n and checkMask & n != 0: #找到第一个0
checkMask <<= 1
bits += 1
ones = (ones << 1) + 1 #记录有多少1
if checkMask > n:
# 全部是1
return -1
while checkMask <= n and checkMask & n == 0: #在找第一个1
checkMask <<= 1
bits += 1
ones <<= 1
# print("{:0>32b}".format(ones))
ones >>= 1 #因为ones初始化为1, 所以ones需要右移一位
n &= ~checkMask #10变01
n = (n >> bits) << bits #右边都变成0了
n |= ones #将右边填充上ones
return n if mn <= n <= mx else -1
return [findLarge(num), findSmall(num)]
o = Solution()
print(o.findClosedNumbers(2)) |
c8eab7467ee25294d227d9d16ef6cea5f97d7ab2 | wulinlw/leetcode_cn | /程序员面试金典/面试题02.07.链表相交.py | 3,147 | 3.6875 | 4 | #!/usr/bin/python
#coding:utf-8
# 面试题 02.07. 链表相交
# 给定两个(单向)链表,判定它们是否相交并返回交点。请注意相交的定义基于节点的引用,而不是基于节点的值。换句话说,如果一个链表的第k个节点与另一个链表的第j个节点是同一节点(引用完全相同),则这两个链表相交。
# 示例 1:
# 输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
# 输出:Reference of the node with value = 8
# 输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
# 示例 2:
# 输入:intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
# 输出:Reference of the node with value = 2
# 输入解释:相交节点的值为 2 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [0,9,1,2,4],链表 B 为 [3,2,4]。在 A 中,相交节点前有 3 个节点;在 B 中,相交节点前有 1 个节点。
# 示例 3:
# 输入:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
# 输出:null
# 输入解释:从各自的表头开始算起,链表 A 为 [2,6,4],链表 B 为 [1,5]。由于这两个链表不相交,所以 intersectVal 必须为 0,而 skipA 和 skipB 可以是任意值。
# 解释:这两个链表不相交,因此返回 null。
# 注意:
# 如果两个链表没有交点,返回 null 。
# 在返回结果后,两个链表仍须保持原有的结构。
# 可假定整个链表结构中没有循环。
# 程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。
# https://leetcode-cn.com/problems/intersection-of-two-linked-lists-lcci/
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def initlinklist(self, nums):
head = ListNode(nums[0])
re = head
for i in nums[1:]:
re.next = ListNode(i)
re = re.next
return head
def printlinklist(self, head):
re = []
while head:
re.append(head.val)
head = head.next
print(re)
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
if not headA or not headB:return None
l1,l2=headA,headB
while l1!=l2:
l1=l1.next if l1 else headB
l2=l2.next if l2 else headA
return l1
#
n1 = ListNode(1)
n2 = ListNode(2)
n3 = ListNode(3)
n4 = ListNode(4)
n5 = ListNode(5)
n1.next = n2
n2.next = n3 #第一个公共节点
n3.next = n4
n4.next = n5
n2_1 = ListNode(1)
n2_2 = ListNode(2)
n2_1.next = n2_2
n2_2.next = n3 #第一个公共节点
#测试用例需要造一个公共节点,ListNode内存地址是同一个
#不能用2个独立创建的链表
h = o.getIntersectionNode(n1, n2_1)
print(h.val)
# o.printlinklist(h)
|
b282517a21d331b04566b1697602e99244800f48 | wulinlw/leetcode_cn | /leetcode-vscode/15.三数之和.py | 2,939 | 3.546875 | 4 | #
# @lc app=leetcode.cn id=15 lang=python3
#
# [15] 三数之和
#
# https://leetcode-cn.com/problems/3sum/description/
#
# algorithms
# Medium (25.70%)
# Likes: 2228
# Dislikes: 0
# Total Accepted: 241.9K
# Total Submissions: 874.9K
# Testcase Example: '[-1,0,1,2,-1,-4]'
#
# 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0
# ?请你找出所有满足条件且不重复的三元组。
#
# 注意:答案中不可以包含重复的三元组。
#
#
#
# 示例:
#
# 给定数组 nums = [-1, 0, 1, 2, -1, -4],
#
# 满足要求的三元组集合为:
# [
# [-1, 0, 1],
# [-1, -1, 2]
# ]
#
#
#
from typing import List
# @lc code=start
class Solution:
# 特判,对于数组长度 nn,如果数组为 nullnull 或者数组长度小于 33,返回 [][]。
# 对数组进行排序。
# 遍历排序后数组:
# 若 nums[i]>0nums[i]>0:因为已经排序好,所以后面不可能有三个数加和等于 00,直接返回结果。
# 对于重复元素:跳过,避免出现重复解
# 令左指针 L=i+1L=i+1,右指针 R=n-1R=n−1,当 L<RL<R 时,执行循环:
# 当 nums[i]+nums[L]+nums[R]==0nums[i]+nums[L]+nums[R]==0,执行循环,判断左界和右界是否和下一位置重复,去除重复解。并同时将 L,RL,R 移到下一位置,寻找新的解
# 若和大于 00,说明 nums[R]nums[R] 太大,RR 左移
# 若和小于 00,说明 nums[L]nums[L] 太小,LL 右移
# https://leetcode-cn.com/problems/3sum/solution/pai-xu-shuang-zhi-zhen-zhu-xing-jie-shi-python3-by/
def threeSum(self, nums: List[int]) -> List[List[int]]:
n=len(nums)
res=[]
if(not nums or n<3):
return []
nums.sort() #先排序
res=[]
for i in range(n):
if(nums[i]>0): #当前大于0,后面的都大于他,和不可能为0,直接返回结果
return res
if(i>0 and nums[i]==nums[i-1]): #连续相同的跳过
continue
L=i+1 #初始化l为下一个,r为最右
R=n-1
while(L<R):
if(nums[i]+nums[L]+nums[R]==0):
res.append([nums[i],nums[L],nums[R]]) #找到了,下面跳过左右指针的相同值
while(L<R and nums[L]==nums[L+1]):
L=L+1
while(L<R and nums[R]==nums[R-1]):
R=R-1
L=L+1
R=R-1
elif(nums[i]+nums[L]+nums[R]>0): #大于0右边-1,反之左边+1
R=R-1
else:
L=L+1
return res
# @lc code=end
|
c1de2f72e8609e27c4c06ec7c843559d6ae6e447 | wulinlw/leetcode_cn | /程序员面试金典/面试题08.03.魔术索引.py | 1,651 | 3.84375 | 4 | # #!/usr/bin/python
# #coding:utf-8
#
# 面试题08.03.魔术索引
#
# https://leetcode-cn.com/problems/magic-index-lcci/
#
# 魔术索引。 在数组A[0...n-1]中,有所谓的魔术索引,满足条件A[i] = i。给定一个有序整数数组,编写一种方法找出魔术索引,若有的话,在数组A中找出一个魔术索引,如果没有,则返回-1。若有多个魔术索引,返回索引值最小的一个。
# 示例1:
#
# 输入:nums = [0, 2, 3, 4, 5]
# 输出:0
# 说明: 0下标的元素为0
#
#
# 示例2:
#
# 输入:nums = [1, 1, 1]
# 输出:1
#
#
# 提示:
#
#
# nums长度在[1, 1000000]之间
#
#
#
# Easy 65.5%
# Testcase Example: [0, 2, 3, 4, 5]
#
# 提示:
# 先试试蛮力算法。
# 蛮力算法的运行时间可能为O(N)。如果试图击败那个运行时间,你认为会得到什么运行时间。什么样的算法具有该运行时间?
# 你能以O(log N)的时间复杂度来解决这个问题吗?
# 二分查找有O(log n)的运行时间。你能在这个问题中应用二分查找吗?
# 给定一个特定的索引和值,你能确定魔术索引是在它之前还是之后吗?
#
#
from typing import List
class Solution:
def findMagicIndex(self, nums: List[int]) -> int:
if not nums:return -1
n = len(nums)
i = 0
while i<n:
if nums[i] == i:
return i
if nums[i] > i:
i = nums[i]
else:
i += 1
return -1
nums = [0, 2, 3, 4, 5]
nums = [1, 1, 1]
nums = [0, 0, 2]
nums = [1,2,6,7,8,9,10]
o = Solution()
print(o.findMagicIndex(nums)) |
57d4e31c32391b66289da0fe14c29017a35a1973 | wulinlw/leetcode_cn | /初级算法/array_8.py | 1,668 | 3.8125 | 4 | #!/usr/bin/python
#coding:utf-8
# https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/1/array/28/
# 移动零
# 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
# 示例:
# 输入: [0,1,0,3,12]
# 输出: [1,3,12,0,0]
# 说明:
# 必须在原数组上操作,不能拷贝额外的数组。
# 尽量减少操作次数。
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
l = len(nums)
zeroIndex = False
moveIndex = []
f = False
for i in range(l):
if nums[i] == 0:
f = True
if type(zeroIndex) == bool:
zeroIndex = i
elif f == True:
moveIndex.append(i)
# print(zeroIndex)
# print(moveIndex)
# sys.exit()
if type(zeroIndex) == bool:
return
zl = len(moveIndex)
p = 0
while(p < zl):
nums[zeroIndex+p] = nums[moveIndex[p]]
p +=1
start = zeroIndex+zl
while(start<l):
nums[start] = 0
start+=1
def moveZeroes2(self, nums):
# 变量j用来保存已遍历过部位0的值。
j = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[j], nums[i] = nums[i], nums[j]
j += 1
# print(nums)
return nums
nums = [0,1,0,3,12]
s = Solution()
n = s.moveZeroes2(nums)
print('return', n)
|
cc15abee5c3b984f0655422e058e242d235553c3 | wulinlw/leetcode_cn | /leetcode-vscode/817.链表组件.py | 2,469 | 3.671875 | 4 | #
# @lc app=leetcode.cn id=817 lang=python3
#
# [817] 链表组件
#
# https://leetcode-cn.com/problems/linked-list-components/description/
#
# algorithms
# Medium (55.78%)
# Likes: 31
# Dislikes: 0
# Total Accepted: 5.1K
# Total Submissions: 9K
# Testcase Example: '[0,1,2,3]\n[0,1,3]'
#
# 给定一个链表(链表结点包含一个整型值)的头结点 head。
#
# 同时给定列表 G,该列表是上述链表中整型值的一个子集。
#
# 返回列表 G 中组件的个数,这里对组件的定义为:链表中一段最长连续结点的值(该值必须在列表 G 中)构成的集合。
#
# 示例 1:
#
#
# 输入:
# head: 0->1->2->3
# G = [0, 1, 3]
# 输出: 2
# 解释:
# 链表中,0 和 1 是相连接的,且 G 中不包含 2,所以 [0, 1] 是 G 的一个组件,同理 [3] 也是一个组件,故返回 2。
#
# 示例 2:
#
#
# 输入:
# head: 0->1->2->3->4
# G = [0, 3, 1, 4]
# 输出: 2
# 解释:
# 链表中,0 和 1 是相连接的,3 和 4 是相连接的,所以 [0, 1] 和 [3, 4] 是两个组件,故返回 2。
#
# 注意:
#
#
# 如果 N 是给定链表 head 的长度,1 <= N <= 10000。
# 链表中每个结点的值所在范围为 [0, N - 1]。
# 1 <= G.length <= 10000
# G 是链表中所有结点的值的一个子集.
#
#
#
from typing import List
# @lc code=start
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def initlinklist(self, nums):
head = ListNode(nums[0])
re = head
for i in nums[1:]:
re.next = ListNode(i)
re = re.next
return head
def printlinklist(self, head):
re = []
while head:
re.append(head.val)
head = head.next
print(re)
def numComponents(self, head: ListNode, G: List[int]) -> int:
# 当前节点在G中,下一个节点不在,组件+1
gset = set(G)
re = 0
cur = head
while cur:
nxtval = cur.next.val if cur.next else None #可能没有下一个节点,需要判断
if cur.val in gset and nxtval not in gset:
re += 1
cur = cur.next
return re
# @lc code=end
nums = [0,1,2,3,4]
g = [0,3,1,4]
o = Solution()
head = o.initlinklist(nums)
# o.printlinklist(head1)
h = o.numComponents(head, g)
print(h)
# o.printlinklist(h) |
20cff1c9700d9009a225c7413e248a2ee1c48322 | wulinlw/leetcode_cn | /leetcode-vscode/912.排序数组.py | 5,906 | 3.84375 | 4 | #
# @lc app=leetcode.cn id=912 lang=python3
#
# [912] 排序数组
#
# https://leetcode-cn.com/problems/sort-an-array/description/
#
# algorithms
# Medium (53.09%)
# Likes: 68
# Dislikes: 0
# Total Accepted: 29.9K
# Total Submissions: 52.7K
# Testcase Example: '[5,2,3,1]'
#
# 给你一个整数数组 nums,将该数组升序排列。
#
#
#
#
#
#
# 示例 1:
#
# 输入:nums = [5,2,3,1]
# 输出:[1,2,3,5]
#
#
# 示例 2:
#
# 输入:nums = [5,1,1,2,0,0]
# 输出:[0,0,1,1,2,5]
#
#
#
#
# 提示:
#
#
# 1 <= nums.length <= 50000
# -50000 <= nums[i] <= 50000
#
#
#
from typing import List
# @lc code=start
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
#冒泡排序
def bubble(nums):
for i in range(len(nums)):
for j in range(len(nums)):
if nums[i]<nums[j]:
nums[i],nums[j] = nums[j],nums[i]
return nums
#选择排序
def select(nums):
for i in range(len(nums)):
idx = i
for j in range(i, len(nums)):
if nums[i]>nums[j]:
idx = j
nums[i],nums[idx] = nums[idx],nums[i]
return nums
#插入排序
def insert(nums):
for i in range(len(nums)):
pre = i-1
cur = nums[i]
while pre>=0 and nums[pre]>cur:
nums[pre+1] = nums[pre]
pre -= 1
nums[pre+1] = cur
return nums
#快速排序
def quick(nums, l, r):
if l<r:
pivot = postition(nums, l, r)
quick(nums, l, pivot-1) #不包含pivot
quick(nums, pivot+1, r)
return nums
def postition(nums, l, r):
i = l-1
pivot = nums[r]
for j in range(l, r):
if nums[j] < pivot:
i += 1
nums[i],nums[j] = nums[j],nums[i]
nums[i+1],nums[r] = nums[r],nums[i+1]
return i+1
#归并排序
def merge(nums):
if len(nums)==1:return nums
mid = len(nums)//2
return _merge(merge(nums[:mid]), merge(nums[mid:]))
def _merge(n1, n2):
re = []
while n1 and n2:
if n1[0]<n2[0]:
re.append(n1.pop(0))
else:
re.append(n2.pop(0))
while n1:
re.append(n1.pop(0))
while n2:
re.append(n2.pop(0))
return re
#桶排序
def bucket(nums):
maxval = max(nums)
bucket = [0] * (maxval+1)
for i in nums:
bucket[i] += 1
re = []
for i in range(len(bucket)):
while bucket[i]>0:
re.append(i)
bucket[i] -= 1
return re
#奇数排序
def count(nums):
re = [0] * len(nums)
for i in range(len(nums)):
cnt = 0
dup = 0
for j in range(len(nums)):
if nums[i] > nums[j]:
cnt += 1
elif nums[i] == nums[j]:
dup += 1
for k in range(cnt, cnt+dup):
re[k] = nums[i]
return re
#希尔排序
def shell(nums):
gap = len(nums)//2
while gap>0:
for i in range(len(nums)):
j = i
cur = nums[i]
while j-gap>=0 and nums[j-gap]>cur:
nums[j] = nums[j-gap]
j -= gap
nums[j] = cur
gap //=2
return nums
def heapify(nums, n, i):
largest = i
l = 2*i + 1
r = 2*i + 2
if l<n and nums[i] < nums[l]:
largest = l
if r<n and nums[largest] < nums[r]:
largest = r
if largest != i:
nums[i],nums[largest] = nums[largest],nums[i]
heapify(nums, n, largest)
#堆排序
def heap(nums):
n = len(nums)
for i in range(n, -1, -1):
heapify(nums, n, i)
for i in range(n-1, 0, -1):
nums[i],nums[0] = nums[0],nums[i]
heapify(nums, i, 0)
return nums
#基数排序
def radix_sort(s):
i = 0 # 记录当前正在排拿一位,最低位为1
max_num = max(s) # 最大值
j = len(str(max_num)) # 记录最大值的位数
while i < j:
bucket_list =[[] for _ in range(10)] # 初始化桶数组
for x in s:
bucket_list[int(x / (10**i)) % 10].append(x)# 找到位置放入桶数组
s.clear()
# print(bucket_list)
for x in bucket_list: # 放回原序列
for y in x:
s.append(y)
# print(s)
i += 1
return s
# return bubble(nums)
# return select(nums)
# return insert(nums)
# return quick(nums, 0, len(nums)-1)
# return merge(nums)
# return bucket(nums)
# return count(nums)
# return shell(nums)
return heap(nums)
# return radix(nums)
# @lc code=end
nums = [5,1,1,2,0,0]
o = Solution()
print(o.sortArray(nums)) |
3e400e6a75eb427dc43cce66ff23c5e6bf40a9a2 | wulinlw/leetcode_cn | /初级算法/mathematics_1.py | 1,133 | 3.875 | 4 | #!/usr/bin/python
#coding:utf-8
# https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/25/math/60/
# Fizz Buzz
# 写一个程序,输出从 1 到 n 数字的字符串表示。
# 1. 如果 n 是3的倍数,输出“Fizz”;
# 2. 如果 n 是5的倍数,输出“Buzz”;
# 3.如果 n 同时是3和5的倍数,输出 “FizzBuzz”。
# 示例:
# n = 15,
# 返回:
# [
# "1",
# "2",
# "Fizz",
# "4",
# "Buzz",
# "Fizz",
# "7",
# "8",
# "Fizz",
# "Buzz",
# "11",
# "Fizz",
# "13",
# "14",
# "FizzBuzz"
# ]
class Solution(object):
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
re = []
for i in range(1,n+1):
# print(i)
if (i%3 + i%5) ==0:
re.append("FizzBuzz")
elif i%3==0 and i%5!=0:
re.append("Fizz")
elif i%3!=0 and i%5==0:
re.append("Buzz")
else:
re.append(str(i))
return re
n=12
s = Solution()
re = s.fizzBuzz(n)
print("deep:",re) |
6719f2cc32c1a8cd9f06575e3c730105c15b3fc5 | wulinlw/leetcode_cn | /字节跳动/array-and-sorting_8.py | 2,455 | 3.890625 | 4 | #!/usr/bin/python
#coding:utf-8
# https://leetcode-cn.com/explore/interview/card/bytedance/243/array-and-sorting/1036/
# 朋友圈
# 班上有 N 名学生。其中有些人是朋友,有些则不是。他们的友谊具有是传递性。如果已知 A 是 B 的朋友,B 是 C 的朋友,那么我们可以认为 A 也是 C 的朋友。所谓的朋友圈,是指所有朋友的集合。
# 给定一个 N * N 的矩阵 M,表示班级中学生之间的朋友关系。如果M[i][j] = 1,表示已知第 i 个和 j 个学生互为朋友关系,否则为不知道。你必须输出所有学生中的已知的朋友圈总数。
# 示例 1:
# 输入:
# [[1,1,0],
# [1,1,0],
# [0,0,1]]
# 输出: 2
# 说明:已知学生0和学生1互为朋友,他们在一个朋友圈。
# 第2个学生自己在一个朋友圈。所以返回2。
# 示例 2:
# 输入:
# [[1,1,0],
# [1,1,1],
# [0,1,1]]
# 输出: 1
# 说明:已知学生0和学生1互为朋友,学生1和学生2互为朋友,所以学生0和学生2也是朋友,所以他们三个在一个朋友圈,返回1。
# 注意:
# N 在[1,200]的范围内。
# 对于所有学生,有M[i][i] = 1。
# 如果有M[i][j] = 1,则有M[j][i] = 1。
class Solution(object):
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
"""
算法:DFS
思路:
可以将题目转换为是在一个图中求连通子图的问题,给出的N*N的矩阵就是邻接矩阵,建立N个节点的visited数组,
从not visited的节点开始深度优先遍历,遍历就是在邻接矩阵中去遍历,如果在第i个节点的邻接矩阵那一行中的第j
个位置处M[i][j]==1 and not visited[j],就应该dfs到这个第j个节点的位置,
复杂度分析:
时间:ON2?遍历所有节点
空间:ON,visited数组
"""
if M == [] or M[0] == []:
return 0
n = len(M)
visited = [False] * n
def dfs(i):
visited[i] = True
for j in range(n):
if M[i][j] == 1 and not visited[j]:
dfs(j)
counter = 0
for i in range(n):
if not visited[i]:
dfs(i)
counter += 1
return counter
M = [[1,1,0],
[1,1,0],
[0,0,1]]
s = Solution()
n = s.findCircleNum(M)
print(n)
|
177cb9cffdfe5c9fe8035ec10664006982f49606 | wulinlw/leetcode_cn | /初级算法/other_2.py | 1,212 | 4.0625 | 4 | #!/usr/bin/python
#coding:utf-8
# https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/26/others/65/
# 汉明距离
# 两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。
# 给出两个整数 x 和 y,计算它们之间的汉明距离。
# 注意:
# 0 ≤ x, y < 231.
# 示例:
# 输入: x = 1, y = 4
# 输出: 2
# 解释:
# 1 (0 0 0 1)
# 4 (0 1 0 0)
# ↑ ↑
# 上面的箭头指出了对应二进制位不同的位置。
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
# x^y是异或运算,不同为1,相同为0,bin()的结果是01字符串,求结果01字符串中的'1'字符的个数,就是hamming distance。
return bin(x^y).count("1")
def hammingDistance2(self, x, y):
print("{:0>32b}".format(x))
print("{:0>32b}".format(y))
print("{:0>32b}".format(x^y))
v = x^y
c=0
while v!=0 :
if v&1 ==1:
c+=1
v=v>>1
return c
x=11
y=2
s = Solution()
re = s.hammingDistance2(x,y)
print("deep:",re) |
c842b9d5b5342e91b9e84dbeecf698e1a8ce8570 | wulinlw/leetcode_cn | /初级算法/mathematics_2.py | 1,763 | 3.984375 | 4 | #!/usr/bin/python
#coding:utf-8
# https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/25/math/61/
# 计数质数
# 统计所有小于非负整数 n 的质数的数量。
# 示例:
# 输入: 10
# 输出: 4
# 解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
# 厄拉多塞筛法
# 西元前250年,希腊数学家厄拉多塞(Eeatosthese)想到了一个非常美妙的质数筛法,
# 减少了逐一检查每个数的的步骤,可以比较简单的从一大堆数字之中,筛选出质数来,这方法被称作厄拉多塞筛法(Sieve of Eeatosthese)。
# 具体操作:
# 先将 2~n 的各个数放入表中,然后在2的上面画一个圆圈,然后划去2的其他倍数;
# 第一个既未画圈又没有被划去的数是3,将它画圈,再划去3的其他倍数;
# 现在既未画圈又没有被划去的第一个数 是5,将它画圈,并划去5的其他倍数……
# 依次类推,一直到所有小于或等于 n 的各数都画了圈或划去为止。
# 这时,表中画了圈的以及未划去的那些数正好就是小于 n 的素数。
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
if n < 3:
return 0
prime = [1] * n
prime[0] = prime[1] = 0
for i in range(2, int(n**0.5) +1):#根号N后面的都会被划掉
if prime[i] == 1:#没有划去的值为1
# print(i,prime[i*i:n:i])
prime[i*i:n:i] = [0]*len(prime[i*i:n:i])#划去I的倍数,值设为0
# print(i,prime[i*i:n:i])
return sum(prime)#最后留下的都是质数,值为1
n=12
s = Solution()
re = s.countPrimes(n)
print("deep:",re) |
8930fdd2af4503f19f5eea56e0e004319275a342 | wulinlw/leetcode_cn | /程序员面试金典/面试题16.16.部分排序.py | 2,042 | 4.03125 | 4 | # #!/usr/bin/python
# #coding:utf-8
#
# 面试题16.16.部分排序
#
# https://leetcode-cn.com/problems/sub-sort-lcci/
#
# 给定一个整数数组,编写一个函数,找出索引m和n,只要将索引区间[m,n]的元素排好序,整个数组就是有序的。注意:n-m尽量最小,也就是说,找出符合条件的最短序列。函数返回值为[m,n],若不存在这样的m和n(例如整个数组是有序的),请返回[-1,-1]。
# 示例:
# 输入: [1,2,4,7,10,11,7,12,6,7,16,18,19]
# 输出: [3,9]
#
# 提示:
#
# 0
#
#
#
# Medium 44.1%
# Testcase Example: []
#
# 提示:
# 在开始和结束时知道最长的排序序列会有帮助吗?
# 我们可以把这个数组分成3个子数组:LEFT、MIDDLE和RIGHT。LEFT和RIGHT都是有序的。MIDDLE的元素顺序是任意的。我们需要展开MIDDLE,直到可以对这些元素排序并使整个数组有序。
# 考虑3个子数组:LEFT、MIDDLE和RIGHT。只关注这个问题:是否可以排序MIDDLE以使整个数组有序?如何进行验证?
# 为了能够对MIDDLE进行排序并对整个数组进行排序,需要MAX(LEFT) <= MIN(MIDDLE, RIGHT)和MAX(LEFT, MIDDLE) <= MIN(RIGHT)。
# 你能把中间部分展开直到满足前面的条件吗?
# 你应该能在O(N)时间内解出来。
#
#
from typing import List
class Solution:
def subSort(self, array: List[int]) -> List[int]:
n = len(array)
maxval, minval = -10000000, 10000000
l, r = -1, -1
for i in range(n): #从左往右找最大值,出现小的,那这里就需要排序
if array[i] < maxval:
r = i
else:
maxval = array[i]
for i in range(n-1, -1, -1): #从右往左找最小值,出现大的,就要排序
if array[i] > minval:
l = i
else:
minval = array[i]
return [l, r]
array = [1,2,4,7,10,11,7,12,6,7,16,18,19]
o = Solution()
print(o.subSort(array)) |
a7a068cb60a7c34934ca3980b45ab240ac077b7e | wulinlw/leetcode_cn | /leetcode-vscode/892.三维形体的表面积.py | 1,718 | 3.671875 | 4 | #
# @lc app=leetcode.cn id=892 lang=python3
#
# [892] 三维形体的表面积
#
# https://leetcode-cn.com/problems/surface-area-of-3d-shapes/description/
#
# algorithms
# Easy (55.73%)
# Likes: 68
# Dislikes: 0
# Total Accepted: 8.6K
# Total Submissions: 14.3K
# Testcase Example: '[[2]]'
#
# 在 N * N 的网格上,我们放置一些 1 * 1 * 1 的立方体。
#
# 每个值 v = grid[i][j] 表示 v 个正方体叠放在对应单元格 (i, j) 上。
#
# 请你返回最终形体的表面积。
#
#
#
#
#
#
# 示例 1:
#
# 输入:[[2]]
# 输出:10
#
#
# 示例 2:
#
# 输入:[[1,2],[3,4]]
# 输出:34
#
#
# 示例 3:
#
# 输入:[[1,0],[0,2]]
# 输出:16
#
#
# 示例 4:
#
# 输入:[[1,1,1],[1,0,1],[1,1,1]]
# 输出:32
#
#
# 示例 5:
#
# 输入:[[2,2,2],[2,1,2],[2,2,2]]
# 输出:46
#
#
#
#
# 提示:
#
#
# 1 <= N <= 50
# 0 <= grid[i][j] <= 50
#
#
#
from typing import List
# @lc code=start
class Solution:
def surfaceArea(self, grid: List[List[int]]) -> int:
re = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]>0:
re += grid[i][j] * 4 + 2 #上和下,4个面*个数
re -= min(grid[i-1][j], grid[i][j]) * 2 if i>0 else 0 #减去与上面相邻的面积,较少的*2
re -= min(grid[i][j-1], grid[i][j]) * 2 if j>0 else 0 #减去与左边相邻的面积,较少的*2
return re
# @lc code=end
grid = [[2]]
grid = [[1,2],[3,4]]
grid = [[1,0],[0,2]]
grid = [[1,1,1],[1,0,1],[1,1,1]]
grid = [[2,2,2],[2,1,2],[2,2,2]]
o = Solution()
print(o.surfaceArea(grid)) |
2a7878e20f2170d581b6defd02672e1d886cf7e6 | wulinlw/leetcode_cn | /程序员面试金典/面试题02.04.分割链表.py | 1,492 | 3.921875 | 4 | #!/usr/bin/python
#coding:utf-8
# 面试题 02.04. 分割链表
# 编写程序以 x 为基准分割链表,使得所有小于 x 的节点排在大于或等于 x 的节点之前。如果链表中包含 x,x 只需出现在小于 x 的元素之后(如下所示)。
# 分割元素 x 只需处于“右半部分”即可,其不需要被置于左右两部分之间。
# 示例:
# 输入: head = 3->5->8->5->10->2->1, x = 5
# 输出: 3->1->2->10->5->5->8
# https://leetcode-cn.com/problems/partition-list-lcci/
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def initlinklist(self, nums):
head = ListNode(nums[0])
re = head
for i in nums[1:]:
re.next = ListNode(i)
re = re.next
return head
def printlinklist(self, head):
re = []
while head:
re.append(head.val)
head = head.next
print(re)
def partition(self, head: ListNode, x: int) -> ListNode:
i, j = head, head
while j:
if j.val < x: # 如果等于 x 不做处理
i.val, j.val = j.val, i.val #链表中的替换,原位置的next不变
i = i.next
j = j.next
return head
nums = [3,5,8,5,10,2,1]
x = 5
o = Solution()
head = o.initlinklist(nums)
o.printlinklist(head)
h = o.partition(head, x)
# print(h)
o.printlinklist(h)
|
ecfa4146a927249cf7cb510dbf14432cd2bb84a7 | wulinlw/leetcode_cn | /剑指offer/30_包含min函数的栈.py | 1,296 | 4.125 | 4 | #!/usr/bin/python
#coding:utf-8
# // 面试题30:包含min函数的栈
# // 题目:定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的min
# // 函数。在该栈中,调用min、push及pop的时间复杂度都是O(1)。
class StackWithMin:
def __init__(self):
self.stack = []
self.min_stack = []
def push(self, node):
# write code here
self.stack.append(node)
if not self.min_stack:
self.min_stack.append(node)
else:
if self.min_stack[-1] < node:
self.min_stack.append(self.min_stack[-1])
else:
self.min_stack.append(node)
def pop(self):
# write code here
self.stack.pop(-1)
self.min_stack.pop(-1)
def top(self):
# write code here
if self.stack:
return self.stack[-1]
else:
return []
def min(self):
# write code here
return self.min_stack[-1]
def debug(self):
print(self.stack)
print(self.stack_min)
print("\n")
s = StackWithMin()
s.push(2.98)
s.push(3)
s.debug()
s.pop()
s.debug()
s.push(1)
s.debug()
s.pop()
s.debug()
s.push(1)
s.push(2)
s.push(3)
s.debug()
s.push(0)
s.debug() |
9e2c9cc88b442a408d79363289c2cfc3905d13c4 | wulinlw/leetcode_cn | /剑指offer/17_打印1到最大的n位数.py | 1,245 | 3.6875 | 4 | #!/usr/bin/python
#coding:utf-8
# 打印1到最大的n位数
# 输入数字n, 按顺序打印从1最大的n位十进制数
# 比如输入3, 则打印出1、2、3、到最大的3位数即999
class Solution:
def Print1ToMaxOfNDigits(self, n):
for i in range(10): #套路写法,生产每一位的0-9,从最左边开始生成
self.recursion(str(i), n, 0) #每个数字的开头
# s 数字开头
# n 几位数
# index 当前第几位
def recursion(self, s, n, index):
if index==n-1: #达到位数,开始输出
# print(s)
self.printNum(s)
return
for i in range(10): #和上面一样套路,生成下一位的数0-9
self.recursion(s+str(i), n, index+1)
def printNum(self, num):
isBeginning0 = True
nLength = len(num)
for i in range(nLength):
if isBeginning0 and num[i] != '0':
isBeginning0 = False
if not isBeginning0:
print('%s' % num[i], end='') #格式化字符及其ASCII码
print('')
obj = Solution()
obj.Print1ToMaxOfNDigits(2)
|
1292292f8f86615a11e933a7234211ad43a71da8 | wulinlw/leetcode_cn | /top-interview-quesitons-in-2018/dynamic-programming_1.py | 1,113 | 3.953125 | 4 | #!/usr/bin/python
#coding:utf-8
# https://leetcode-cn.com/explore/featured/card/top-interview-quesitons-in-2018/272/dynamic-programming/1174/
# 至少有K个重复字符的最长子串
# 找到给定字符串(由小写字符组成)中的最长子串 T , 要求 T 中的每一字符出现次数都不少于 k 。输出 T 的长度。
# 示例 1:
# 输入:
# s = "aaabb", k = 3
# 输出:
# 3
# 最长子串为 "aaa" ,其中 'a' 重复了 3 次。
# 示例 2:
# 输入:
# s = "ababbc", k = 2
# 输出:
# 5
# 最长子串为 "ababb" ,其中 'a' 重复了 2 次, 'b' 重复了 3 次。
# https://blog.csdn.net/weixin_41303016/article/details/88686110
class Solution(object):
def longestSubstring(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
for i in set(s):#去重
if s.count(i) < k: # 找出不满足k次的字母,将其作为分割点进行分治
return max(self.longestSubstring(m, k) for m in s.split(i))
return len(s)
ss = "aaabbc"
k = 3
s = Solution()
res = s.longestSubstring(ss, k)
print(res) |
fcc7f51524ae8699c60101b37ff9bbcffdfa1263 | wulinlw/leetcode_cn | /剑指offer/44_数字序列中某一位的数字.py | 2,798 | 3.75 | 4 | #!/usr/bin/python
#coding:utf-8
# // 面试题44:数字序列中某一位的数字
# // 题目:数字以0123456789101112131415…的格式序列化到一个字符序列中。在这
# // 个序列中,第5位(从0开始计数)是5,第13位是1,第19位是4,等等。请写一
# // 个函数求任意位对应的数字。
class Solution:
def digitAtIndex(self, index):
if index < 0:
return -1
digits = 1
while True:
length = self.digitsLength(digits) #n位数的长度
if index < length*digits: #长度在n位数的范围内
return self.findIndex(index, digits)
index -= length*digits #超过了这个长度,减去已知的长度
digits += 1
# 计算n位数有多少个 ,1-10 2-90 3-900 4-9000
def digitsLength(self, digits):
if digits==1:
return 10
c = pow(10, digits-1)
return 9 * c
# 从第n位中找出index的位数
def findIndex(self, index, digits):#索引 位数
first = 0
if index==1:
first = 0
else:
first = pow(10, digits-1) #n位数的第一个数
num = first + index//digits #位数除以长度=第xx位数
indexFromRight = digits - index % digits#位数-第几位== 从右边要找的那个位
for _ in range(1,indexFromRight):
num = num//10
return num % 10 #取一位
def findNthDigit(self, n: int) -> int:
# 首先判断target是几位数,用digits表示
base = 9
digits = 1
while n - base * digits > 0:
n -= base * digits
base *= 10
digits += 1
# 计算target的值
idx = n % digits # 注意由于上面的计算,n现在表示digits位数的第n个数字
if idx == 0:
idx = digits
number = 1
for i in range(1,digits):
number *= 10
if idx == digits:
number += n // digits - 1
else:
number += n // digits
# 找到target中对应的数字
for i in range(idx,digits):
number //= 10
return number % 10
# 作者:z1m
# 链接:https://leetcode-cn.com/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof/solution/zhe-shi-yi-dao-shu-xue-ti-ge-zhao-gui-lu-by-z1m/
# 来源:力扣(LeetCode)
# 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
obj = Solution()
print(obj.digitAtIndex(13))
print(obj.digitAtIndex(1001))
print(obj.digitAtIndex(1002))
print(obj.digitAtIndex(1003))
print(obj.digitAtIndex(1004))
print(obj.digitAtIndex(1005))
|
93980a2f1b9d778ff907998b6fb722722ec28d73 | wulinlw/leetcode_cn | /递归/recursion_1_1.py | 1,304 | 4.15625 | 4 | #!/usr/bin/python
#coding:utf-8
# https://leetcode-cn.com/explore/orignial/card/recursion-i/256/principle-of-recursion/1198/
# 反转字符串
# 编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。
# 不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
# 你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。
# 示例 1:
# 输入:["h","e","l","l","o"]
# 输出:["o","l","l","e","h"]
# 示例 2:
# 输入:["H","a","n","n","a","h"]
# 输出:["h","a","n","n","a","H"]
class Solution(object):
# 递归
def reverseString(self, s):
def recur(tmp):
if len(tmp)<=1:
return tmp
else:
return recur(tmp[1:])+[tmp[0]]
s[:] = recur(s)
# 递归+双指针
def reverseString2(self, s):
"""
:type s: str
:rtype: str
"""
def recur_(s, i,j):
if i>=j:
return
else:
s[i],s[j] = s[j],s[i]
recur_(s,i+1,j-1)
recur_(s,0,len(s)-1)
s = ["h","e","l","l","o"]
S = Solution()
deep = S.reverseString2(s)
print("deep:",deep)
|
b3328bb716cac18bf8e375f48de6ae5d67faa44b | wulinlw/leetcode_cn | /中级算法/tree_6.py | 2,059 | 3.796875 | 4 | #!/usr/bin/python
#coding:utf-8
# https://leetcode-cn.com/explore/interview/card/top-interview-questions-medium/32/trees-and-graphs/90/
# 岛屿的个数
# 给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。
# 示例 1:
# 输入:
# 11110
# 11010
# 11000
# 00000
# 输出: 1
# 示例 2:
# 输入:
# 11000
# 11000
# 00100
# 00011
# 输出: 3
class Solution(object):
# 遍历二维数组每一个元素,找到一块陆地后遍历寻找与这块陆地相连的所有陆地并将找到的陆地全部改为"0",
# 每一个1,岛屿数量加一
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
n = len(grid)#列数
if n == 0: return 0
m = len(grid[0])#行数
if m == 0: return 0
res = 0
# 遍历每一个字符
for i in range(n):
for j in range(m):
# 如果遍历字符是陆地"1"
if grid[i][j] == "1":
res += 1
# 递归查找与这块陆地相连的所有陆地 并将他们改为零
self.change(grid, i, j)
return res
def change(self, grid, i, j):
grid[i][j] = "0"
# 判断上方字符
if i > 0 and grid[i - 1][j] == "1":
self.change(grid, i - 1, j)
# 判断左方字符
if j > 0 and grid[i][j - 1] == "1":
self.change(grid, i, j - 1)
# 判断下方字符
if i < len(grid) - 1 and grid[i + 1][j] == "1":
self.change(grid, i + 1, j)
# 判断右方字符
if j < len(grid[0]) - 1 and grid[i][j + 1] == "1":
self.change(grid, i, j + 1)
grid = [
[1, 1, 0, 0, 0],
[0, 1, 0, 0, 1],
[0, 0, 0, 1, 1],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 1]
]
s = Solution()
r = s.numIslands(grid)
print(r) |
bacfbc3a4a068cf87954be2a53e0a6ab44ba41bc | wulinlw/leetcode_cn | /链表/linked-list_5_3.py | 2,469 | 4.125 | 4 | #!/usr/bin/python
# coding:utf-8
# https://leetcode-cn.com/explore/learn/card/linked-list/197/conclusion/764/
# 扁平化多级双向链表
# 您将获得一个双向链表,除了下一个和前一个指针之外,它还有一个子指针,可能指向单独的双向链表。这些子列表可能有一个或多个自己的子项,依此类推,生成多级数据结构,如下面的示例所示。
# 扁平化列表,使所有结点出现在单级双链表中。您将获得列表第一级的头部。
# 示例:
# 输入:
# 1---2---3---4---5---6--NULL
# |
# 7---8---9---10--NULL
# |
# 11--12--NULL
# 输出:
# 1-2-3-7-8-11-12-9-10-4-5-6-NULL
# 以上示例的说明:
# 给出以下多级双向链表:
# 我们应该返回如下所示的扁平双向链表:
# Definition for a Node.
class Node(object):
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
class Solution(object):
def list_generate(self, lst):
"""
生成链表
"""
if not lst:
return None
list_node = Node(lst[0])
if len(lst) == 1:
list_node.next = None
else:
list_node.next = self.list_generate(lst[1:])
return list_node
# 测试打印
def printList(self, list_node):
re = []
while list_node:
re.append(list_node.val)
list_node = list_node.next
print(re)
def flatten(self, head):
"""
:type head: Node
:rtype: Node
"""
p = rst = Node(None, None, None, None) # 初始化结果链表及其指针
visited = head and [head] # 初始化栈
while visited:
vertex = visited.pop()
if vertex.next:
visited.append(vertex.next)
if vertex.child:
visited.append(vertex.child)
p.next = vertex # pop出来的节点就是所需节点
p, p.prev, p.child = p.next, p, None # 设定节点属性
# p = p.next后相当于右移一位后,p.prev就是p了
if rst.next:
rst.next.prev = None # rst是要返回的头,rst.next的prev属性要设为None
return rst.next
l = [1, 2, 6, 3, 4, 5, 6]
node = 6
obj = Solution()
head = obj.list_generate(l)
obj.printList(head)
r = obj.flatten(head)
obj.printList(r)
|
43d875814e422cab3a1d28b38b8862ef137e70ae | wulinlw/leetcode_cn | /剑指offer/28_对称的二叉树.py | 2,014 | 3.671875 | 4 | #!/usr/bin/python
#coding:utf-8
# // 面试题28:对称的二叉树
# // 题目:请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和
# // 它的镜像一样,那么它是对称的。
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetrical(self, root):
if not root:return True
def core(L, R):
if not L and not R:return True
if not L or not R:return False
if L.val != R.val:return False
return core(L.left, R.right) and core(L.right, R.left)
return core(root.left, root.right)
# 层次遍历
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: int
"""
# 从根开始遍历,每层写入一个新数组
# 在将left ,right写入下次需要巡皇的数组
# 循环完成即可得到每层的数组
queue = [root]
res = []
if not root:
return []
while queue:
templist = []#此层的数组
templen =len(queue)
for i in range(templen):
temp = queue.pop(0)
templist.append(temp.val)
if temp.left:
queue.append(temp.left)
if temp.right:
queue.append(temp.right)
# print(templist)
res.append(templist)
return res
# 测试树
# 6
# 8 8
# 1 4 4 1
# 按层定义
t1 = TreeNode(6)
t2 = TreeNode(8)
t3 = TreeNode(8)
t4 = TreeNode(1)
t5 = TreeNode(4)
t6 = TreeNode(4)
t7 = TreeNode(1)
root = t1
root.left = t2
root.right = t3
t2.left = t4
t2.right = t5
t3.left = t6
t3.right = t7
# t3.right = None #False
obj = Solution()
re = obj.levelOrder(root)
for i in range(len(re)):
print(re[i])
print("\n")
print(obj.isSymmetrical(root))
|
b7fce39adf1ba1fa6029dda276e2fde9eb8277ec | wulinlw/leetcode_cn | /剑指offer/23_链表中环的入口结点.py | 1,404 | 3.796875 | 4 | #!/usr/bin/python
#coding:utf-8
# // 面试题23:链表中环的入口结点
# // 题目:一个链表中包含环,如何找出环的入口结点?例如,在图3.8的链表中,
# // 环的入口结点是结点3。
class ListNode:
def __init__(self, x=None):
self.val = x
self.next = None
class Solution:
def initlinklist(self, nums):
head = ListNode(nums[0])
re = head
for i in nums[1:]:
re.next = ListNode(i)
re = re.next
return head
def printlinklist(self, head):
re = []
while head:
re.append(head.val)
head = head.next
print(re)
def MeetingNode(self, head):
if not head:return False
p1 = slow = fast = head
while 1:
slow = slow.next
if not fast.next.next:
return False
fast = fast.next.next
if slow == fast:
break
while p1 != slow:
p1 = p1.next
slow = slow.next
return slow
n1 = ListNode(1)
n2 = ListNode(2)
n3 = ListNode(3)
n4 = ListNode(4)
n5 = ListNode(5)
n1.next = n2
n2.next = n3
n3.next = n4
n4.next = n5
n5.next = n2#环在这里
# print(n5.val,n5.next.val)
nums = [1,2,3,4,5]
obj = Solution()
# head = obj.initlinklist(nums)
# obj.printlinklist(n1)
print(obj.MeetingNode(n1).val)
|
4154a18778d1e344a20d388bb08ce7d33022adce | wulinlw/leetcode_cn | /leetcode-vscode/78.子集.py | 1,086 | 3.578125 | 4 | #
# @lc app=leetcode.cn id=78 lang=python3
#
# [78] 子集
#
# https://leetcode-cn.com/problems/subsets/description/
#
# algorithms
# Medium (76.55%)
# Likes: 493
# Dislikes: 0
# Total Accepted: 69.2K
# Total Submissions: 90.1K
# Testcase Example: '[1,2,3]'
#
# 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
#
# 说明:解集不能包含重复的子集。
#
# 示例:
#
# 输入: nums = [1,2,3]
# 输出:
# [
# [3],
# [1],
# [2],
# [1,2,3],
# [1,3],
# [2,3],
# [1,2],
# []
# ]
#
#
from typing import List
# @lc code=start
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
re = []
def backtrack(nums, idx, tmp):
if idx >len(nums):return
re.append(tmp[:])
for i in range(idx, len(nums)):
tmp.append(nums[i])
backtrack(nums, i+1, tmp)
tmp.pop()
nums.sort()
backtrack(nums, 0, [])
return re
# @lc code=end
nums = [1,2,3]
o = Solution()
print(o.subsets(nums)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.