blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
8ae4373f77c54df1b77d3f21aa80620463d40762
alannesta/algo4
/src/python/data_structure/graph/37_sudoku.py
3,119
3.9375
4
""" https://leetcode.com/problems/sudoku-solver/ leetcode经典系列, 解数独 """ from typing import List class Solution: def solveSudoku(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ self.solve(board, 0, 0) def solve(self, board, r...
55dc75da97fa062e361fc3af0466b7d263330f82
alannesta/algo4
/src/python/data_structure/linked_list/linked_list.py
2,588
3.734375
4
""" Linked list impl """ class LinkedList: def __init__(self): self.head = None self.tail = None def add_last(self, val): a_node = Node(val=val) if not self._is_empty(): self.tail.next = a_node self.tail = a_node else: self.head = sel...
06f4cf1b7ae25c55e8b0228f3322c28a8129302e
alannesta/algo4
/src/python/data_structure/heap/priority_queue.py
1,729
3.9375
4
""" Implmentation using heapq module examples from python official documentation """ import heapq from collections import namedtuple from dataclasses import dataclass, field import itertools PrioritizedItem = namedtuple("task", ['priority', 'item']) pq = [] # list of entries arranged in a hea...
65e6989de135ad9d4cbef0f64c52594dbe66376d
alannesta/algo4
/src/python/lc_submission/77_combination.py
1,750
3.765625
4
""" https://leetcode.com/problems/combinations/ Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For example, If n = 4 and k = 2, a solution is: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ] """ from copy import copy """ Solution 1: backtrack暴力穷举, leetcode超时 combin...
b58450f1afed2ff8e3dea4579afd246c26294113
alannesta/algo4
/src/python/design/355_design_twitter.py
3,344
3.796875
4
""" https://leetcode.com/problems/design-twitter/ 典中典 """ from typing import List, Dict, Optional import heapq from datetime import datetime class Twitter: def __init__(self): self.user_tracker: Dict[int, User] = {} def postTweet(self, userId: int, tweetId: int) -> None: if userId in self.use...
f485451cf3e79e80505450ce3d274461d92c0f34
alannesta/algo4
/src/python/data_structure/stack/232_implement_queue.py
2,018
4
4
""" https://leetcode.com/problems/implement-queue-using-stacks/ Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty). """ class MyQueue: def __init__(self): self.queue = [] self.in...
1ffffe10347278a15c78ff3549ed2ea13d14393f
alannesta/algo4
/src/python/lc_submission/114_flatten_tree_node.py
1,298
4.21875
4
""" https://leetcode.com/problems/flatten-binary-tree-to-linked-list/ Given the root of a binary tree, flatten the tree into a "linked list": The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null. The "linked l...
3c5e726bedf5ff2bde5c4aef6250b2b797274d28
StAResComp/sifids_web
/db/trips.py
4,548
3.890625
4
#!/usr/bin/python # -*- coding: UTF-8 -*- import psycopg2 import csv import math # maximum distance between 2 consecutive points in same track # 1000m, roughly 1 minute at 30 knots maxDist = 1000 # more than 5 minutes between time stamps means a new trip maxTime = 5 * 60 # minimum length of trip minTracks = 10 # dis...
1fe098bab468fd61d04ca397c3dbcb03faf9af29
josephriad/bikes
/bikeshare.py
9,680
4.34375
4
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } months = ['january', 'february', 'march', 'april', 'may', 'june','all'] days = ["monday","muesday","wednesday","thursday"...
9913025c82e86c6ebf7686554c5138d5e8efdcda
danmachinez/curso_em_videoPython
/ex011_continue.py
521
3.921875
4
print("-" * 55) print("SAIBA QUANTO DE TINTA PRECISARIA PARA PINTAR SUA PAREDE") print("-" * 55) lar = float(input("Digite a largura de sua parede: ")) alt = float(input("Digite a altura de sua parede: ")) area = lar * alt litros = area / 2 print("A dimensão de sua parede é de {} x {} e sua área é de {}m²".forma...
a5719fa243883f0eb46c10795e31743667e0587c
danmachinez/curso_em_videoPython
/ex014.py
328
4.28125
4
print('-' * 36) print('CONVERTA A TEMPERATURA DE °C PARA °F') print('-' * 36) print('') c = float(input('Digite a temperatura em °C: ')) f = (9 * c)/5 + 32 print('') print('A temperatura de {}°C corresponde a {}°F !' .format(c, f)) print('') print('-' * 40) print('Muito obrigado por usar nosso conversor!') print('-' * ...
932f98b87e9534d2d9332b4f4c0f671154ca81d2
ulitol97/ja-pychess
/pieces/pawn.py
2,258
3.828125
4
from typing import List from board import board from movement import Coordinate from pieces.piece import Piece class Pawn(Piece): """The Pawn represents a chess piece capable of forward movement and attacking other pieces diagonally.""" REPRESENTATION: str = "P" VALUE: int = 1 def __init__(self, col...
f57267ffafad37d97e26720bd648f6f78b60a06a
mabagheri/PythonPractice
/DailyCodingProblems/49.py
880
3.984375
4
""" Problem 49 This problem was asked by Amazon. Given an array of numbers, find the maximum sum of any contiguous subarray of the array. For example, given the array [34, -50, 42, 14, -5, 86], the maximum sum would be 137, since we would take elements 42, 14, -5, and 86. Given the array [-5, -1, -8, -9], the maximu...
e214f8860788cc6c3f0931c54226e9b496942c13
mabagheri/PythonPractice
/Assorted/Greatest_Common_Denominator.py
145
3.640625
4
def gcd(a, b): r = a % b if r == 0: return b else: a = b b = r return gcd(a, b) print(gcd(205, 11))
f2cdb4598da3aa7c88a4aa8243cc19b96de2d199
madhumithaasaravanan/madhumitha5
/b104.py
98
3.8125
4
n=int(input("enter the number:")) k=int(input("enter the number:")) res=int(pow(n,k)); print(res)
1c81577585d969ef431f17e1ff489b13a59bbf96
madhumithaasaravanan/madhumitha5
/b53.py
122
4.03125
4
n1=int(input("enter num1:")) n2=int(input("enter num2:")) n3=int(input("enter num3:")) n=n1+n2+n3 print("total value=",n)
bcdc5ed38cc18a393126acd93b3c44f2d20194a0
JuniorDugue/data-structure-and-algos-in-python
/python-crashcourse/strings.py
312
3.71875
4
# strings print('Hello') print("helloooo") print("""What's up How's it going? I'm doing great, thank you! """) # include the \ to prevent errors when using '' within '' or "" within "" print('Hello, "i\'m leaving"') # print('Hello, "i'm leaving"') # escape print("Hello \"using quotes here\" double quotes")
81ed26ef274df089b84ca850915ba81bcd1abb8f
dantin/python-by-example
/crash_course/ch09/exec/privileges.py
1,212
4.3125
4
class User(): """A simple user class.""" def __init__(self, first, last): """Initialize with attributes.""" self.first_name = first self.last_name = last def describe_user(self): """Print user description.""" full_name = self.first_name + ' ' + self.last_name ...
db1fb77c41c0cb03fc3df26f348a12222d82f822
dantin/python-by-example
/crash_course/ch09/exec/number_served.py
1,309
4.1875
4
class Restaurant(): """A simple Restaurant class.""" def __init__(self, name, cuisine_type): """Initialize restaurant name and cuisine type attributes.""" self.restaurant_name = name self.cuisine_type = cuisine_type self.number_served = 0 def describe_restaurant(self): ...
95bbd2aaea454fe6087ca9a34ce181fbd3fab0d6
dantin/python-by-example
/crash_course/ch09/exec/ice_cream_stand.py
1,200
4.28125
4
class Restaurant(): """A simple Restaurant class.""" def __init__(self, name, cuisine_type): """Initialize restaurant name and cuisine type attributes.""" self.restaurant_name = name self.cuisine_type = cuisine_type def describe_restaurant(self): """Print restaurant descri...
9005037aa997de65090617f6b61b4839df356236
dantin/python-by-example
/crash_course/ch08/exec/great_magicians.py
377
4.03125
4
def show_magicians(names): """Print the name of each magician in the list.""" for name in names: print(name.title()) def make_great(names): """Modify magicans list by add the phrase 'the Great'.""" for idx, name in enumerate(names): names[idx] = 'the Great ' + name names = ['alice',...
31ff2f422515867d042c2551d50b5c702b92a75f
dantin/python-by-example
/learning_python/ch21/timer.py
952
3.703125
4
# -*- coding: utf-8 -*- import sys import time timer = time.clock if sys.platform[:3] == 'win' else time.time def total(reps, func, *args, **kwargs): """Total time to run func() reps times. Returns (total time, last result) """ repslist = list(range(reps)) start = timer() for i in repslist:...
5ea4bd90ec285e268f60cf986f66400ca8c2a17c
dantin/python-by-example
/numpy/quick-start/basics/idx_slice_iter.py
2,062
4.4375
4
# -*- coding: utf-8 -*- import numpy as np from example import print_shape def one_dimension_demo(): """One-dimensional arrays can be indexed, sliced and iterated over, much like `lists` and other Python sequence.""" a = np.arange(10)**3 print('a =') print(a) print('indexing') print('a[2] =...
c63e67bb2c28f4e5ed990a85d053b8b7820906ef
dantin/python-by-example
/crash_course/ch08/exec/city_names.py
288
4.0625
4
def city_country(city, country): """Return a formatted string of country and city.""" return city.title() + ', ' + country.title() print(city_country('shanghai', 'china')) print(city_country(country='china', city='beijing')) print(city_country(city='paris', country='france'))
e190d88b4fe6517670252f97b6f7e3240c7f8d5e
dantin/python-by-example
/numpy/quick-start/shape-manipulate/split.py
584
4
4
# -*- coding: utf-8 -*- import numpy as np if __name__ == '__main__': a = np.floor(10*np.random.random( (2,12) )) print('a =') print(a) # specifying the number of equally shaped arrays to return s = np.hsplit(a, 3) # Split 'a' into 3 print('# specifying the number of equally shaped arrays to...
1cf7c195ceed12fd59ea2deb193ecfbfb2813eec
dantin/python-by-example
/crash_course/ch08/exec/album.py
433
4.125
4
def make_album(artist, title, tracks=''): """Build a dictionary describing a music album.""" album = {'artist_name': artist, 'album_title': title} if tracks: album['tracks'] = tracks return album albums = [ make_album('Adele', 'Hello'), make_album(title='Poker Face', artist='Lady Gag...
81478d5da78250b8a595f9f7da25cb39b6466e81
dantin/python-by-example
/crash_course/ch06/exec/polling.py
331
3.75
4
favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } users = ['david', 'jen'] for user in users: if user in favorite_languages.keys(): print('Thanks ' + user.title() + ' for taking the poll.') else: print(user.title() + ', please to take t...
2bd6635456b347e814ae97fedf7ab4160ae305d8
dixonnn/dataset-python
/delete_col.py
420
3.71875
4
import csv # Function Declaration def del_col (old, new): # Open source file with open(old, 'rb') as src: reader = csv.reader(src) # Open destination file with open(new, 'wb') as res: writer = csv.writer(res) # Delete row specified by index, write to new file for row in reader: del row[0] w...
9e12d8bdd093d83ffe31e4a9cd7168b8fbfd4920
mariahisse/Desafio-Python
/Questão 1/exercicio1.py
412
3.703125
4
# vamos inicializar a variável contador com zero cont = 0 # estrutura de repetição para testar o intervalo # não testa o 5000000 (não é necessário) for i in range(1, 5000000): # condição para um número, deve ser par e múltiplo de 49 e 37 # caso aconteça soma um ao contador if ((i % 2 == 0) and (i % 49 == 0) and (i ...
b5261d81687dc17a1e0d67d2881b6046c9cfdce0
Aayushi-Mittal/WinterOfMentorship-PaintApp
/PRACTICE/3-SimpleInterest.py
178
3.6875
4
p = int(input("Enter Principal: ") ) r = int(input("Enter Rate of Interest: ") ) t = int(input("Enter Time Period (in years): ") ) i = (p*r*t)/100 print(f"Simple Interest = {i}")
8bab44fa4b5acb67640df5d08235bb7d8e17c77c
Aayushi-Mittal/WinterOfMentorship-PaintApp
/PRACTICE/StringSlicing.py
243
4
4
string="I am Aayushi" print(string) # string slicing print(len(string)) print(string[0:5]) print(string[0:100]) print(string[:9]) print(string[:]) print(string[0:12:2]) # print(string[-7:-1]) print(string[::-1]) #reverse print(string[-12:-1])
5ea21484ab4ad21107e1ef3d68cf47e49a542b0c
awatekiran/codedkulptor
/mousecontroller.py
741
3.59375
4
# watch implementation at http://www.codeskulptor.org/#user13_nS0InDUstk_0.py import simplegui import math width = 500 height = 400 ball_pos = [width/2, height/2] ball_radius = 20 ball_colour = "Red" def distance(p, q): return math.sqrt( (p[0]-q[0])**2 + (p[1]-p[1])**2) def click(pos): global ball_pos, ball...
8dbf15bfab3940e5ac2db802d296972cc581c18c
jacquerie/leetcode
/leetcode/0665_non_decreasing_array.py
792
3.640625
4
# -*- coding: utf-8 -*- class Solution: def checkPossibility(self, nums): peak = None for i in range(len(nums) - 1): if nums[i] > nums[i + 1]: if peak is not None: return False peak = i return ( peak is None ...
8566339d31b1fa6cede1985cf86b4ed18e703f5f
jacquerie/leetcode
/leetcode/1859_sorting_the_sentence.py
519
3.890625
4
# -*- coding: utf-8 -*- class Solution: def sortSentence(self, s: str) -> str: tokens = s.split() result = [None] * len(tokens) for token in tokens: word, index = token[:-1], int(token[-1]) result[index - 1] = word return " ".join(result) if __name__ == ...
b3a36f66ba261ebcc994a03d6bbfc602e4300ae9
jacquerie/leetcode
/leetcode/1008_construct_binary_search_tree_from_preorder_traversal.py
1,405
3.59375
4
# -*- coding: utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def __eq__(self, other): return ( other is not None and self.val == other.val and self.left == other.left and self.rig...
c44608e6eb67c41faf0bc5aadadd86bae320f760
jacquerie/leetcode
/leetcode/0125_valid_palindrome.py
349
3.71875
4
# -*- coding: utf-8 -*- import re class Solution: def isPalindrome(self, s): s = s.lower() s = re.sub("[^a-z0-9]+", "", s) return s == s[::-1] if __name__ == "__main__": solution = Solution() assert solution.isPalindrome("A man, a plan, a canal: Panama") assert not solutio...
88bea6ea4ea5c7269f00fde3e365eaa51c09eb18
jacquerie/leetcode
/leetcode/1184_distance_between_bus_stops.py
600
3.953125
4
# -*- coding: utf-8 -*- class Solution: def distanceBetweenBusStops(self, distance, start, destination): if destination < start: start, destination = destination, start return min( sum(distance[start:destination]), sum(distance[:start]) + sum(distance[destinati...
af3fedef669e10d5fd4d9b1880684b56823dbcb4
jacquerie/leetcode
/leetcode/2057_smallest_index_with_equal_value.py
519
3.6875
4
# -*- coding: utf-8 -*- from typing import List class Solution: def smallestEqual(self, nums: List[int]) -> int: for i, num in enumerate(nums): if i % 10 == num: return i return -1 if __name__ == "__main__": solution = Solution() assert 0 == solution.smalles...
795667c6ad326ac620f24e1c4f643867506a3aad
jacquerie/leetcode
/leetcode/0504_base_7.py
529
3.984375
4
# -*- coding: utf-8 -*- class Solution: def convertToBase7(self, num): if num == 0: return "0" sign = -1 if num < 0 else 1 num *= sign digits = [] while num: digits.append(str(num % 7)) num //= 7 if sign < 0: digit...
c6f23cc8ad6b5bc8ba580da8b887b4b89ad1c76a
jacquerie/leetcode
/leetcode/0001_two_sum.py
407
3.546875
4
# -*- coding: utf-8 -*- class Solution: def twoSum(self, nums, target): numsMap = {num: i for i, num in enumerate(nums)} for i, num in enumerate(nums): if target - num in numsMap and numsMap[target - num] != i: return [i, numsMap[target - num]] if __name__ == "__main_...
26789846c48ac5f38baebfc05b3c134208738ade
jacquerie/leetcode
/leetcode/1185_day_of_the_week.py
399
3.59375
4
# -*- coding: utf-8 -*- import datetime class Solution: def dayOfTheWeek(self, day, month, year): return datetime.date(year, month, day).strftime("%A") if __name__ == "__main__": solution = Solution() assert "Saturday" == solution.dayOfTheWeek(31, 8, 2019) assert "Sunday" == solution.dayOf...
d84e5d927c88829191cd705d166e48c8b1088773
jacquerie/leetcode
/leetcode/0976_largest_perimeter_triangle.py
527
3.578125
4
# -*- coding: utf-8 -*- class Solution: def largestPerimeter(self, A): A.sort(reverse=True) for i in range(len(A) - 2): if A[i + 2] + A[i + 1] > A[i]: return A[i + 2] + A[i + 1] + A[i] return 0 if __name__ == "__main__": solution = Solution() assert 5...
d5bede798705c54e1db1bf80d4172de984fdbae1
jacquerie/leetcode
/leetcode/0002_add_two_numbers.py
1,331
3.71875
4
# -*- coding: utf-8 -*- class ListNode: def __init__(self, x): self.val = x self.next = None def __eq__(self, other): return other is not None and self.val == other.val and self.next == other.next class Solution: def addTwoNumbers(self, l1, l2): carry, val = divmod(l1.va...
f3fe526214b982bac6b3f48e3f9f0a4573820a7b
jacquerie/leetcode
/leetcode/2133_check_if_every_row_and_column_contains_all_numbers.py
542
3.515625
4
# -*- coding: utf-8 -*- from typing import List class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: for row in matrix: if len(row) != len(set(row)): return False for col in zip(*matrix): if len(col) != len(set(col)): retu...
a5adb3298fea07ca56371f0cde0cfc05b1f6f05e
jacquerie/leetcode
/leetcode/1446_consecutive_characters.py
550
3.75
4
# -*- coding: utf-8 -*- import itertools class Solution: def maxPower(self, s: str) -> int: result = 0 for _, group in itertools.groupby(s): result = max(result, len(list(group))) return result if __name__ == "__main__": solution = Solution() assert 2 == solution.ma...
37f8cb58ec85f718655b00132d6123e09d67aa70
jacquerie/leetcode
/leetcode/2078_two_furthest_houses_with_different_colors.py
602
3.5625
4
# -*- coding: utf-8 -*- from typing import List class Solution: def maxDistance(self, colors: List[int]) -> int: result = float("-inf") for i, color in enumerate(colors): if color != colors[0]: result = max(result, i) if color != colors[-1]: ...
5489e4faf7b7b8d5d6b0963985c06bff0739e105
jacquerie/leetcode
/leetcode/1360_number_of_days_between_two_dates.py
504
3.71875
4
# -*- coding: utf-8 -*- from datetime import datetime class Solution: def daysBetweenDates(self, date1: str, date2: str) -> int: return abs( ( datetime.strptime(date1, "%Y-%m-%d") - datetime.strptime(date2, "%Y-%m-%d") ).days ) if __name__...
405a83ef4fb7a656bd01f9012d3f5345aa4f0fc4
jacquerie/leetcode
/leetcode/0023_merge_k_sorted_lists.py
1,827
3.78125
4
# -*- coding: utf-8 -*- from heapq import heappop, heappush class ListNode: def __init__(self, x): self.val = x self.next = None def __eq__(self, other): return other is not None and self.val == other.val and self.next == other.next def __lt__(self, other): return other ...
e0aacd74f57abac5dadbca8e194a473a0d42cfdc
jacquerie/leetcode
/leetcode/0357_count_numbers_with_unique_digits.py
572
3.828125
4
# -*- coding: utf-8 -*- class Solution: def countNumbersWithUniqueDigits(self, n): if n > 10: return 0 elif 1 <= n <= 10: return 9 * self.factorialPrefix( 9, n - 1 ) + self.countNumbersWithUniqueDigits(n - 1) return 1 def factorialPr...
9941014374b7dbf624867342a09588dc1566c481
jacquerie/leetcode
/leetcode/0707_design_linked_list.py
2,461
3.609375
4
# -*- coding: utf-8 -*- class ListNode: def __init__(self, val): self.val = val self.next = None self.prev = None class MyLinkedList: def __init__(self): self.count = 0 self.head = ListNode(None) self.tail = ListNode(None) self.head.next = self.tail ...
c35e74288bb6f1c9752d0bc5b132a898af960417
jacquerie/leetcode
/leetcode/1290_convert_binary_number_in_a_linked_list_to_integer.py
1,540
3.625
4
# -*- coding: utf-8 -*- class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def getDecimalValue(self, head: ListNode) -> int: current, result = head, 0 while current is not None: result = 2 * result + current.val curren...
96972ec63f62808ecc3df665f986106440db6500
jacquerie/leetcode
/leetcode/0739_daily_temperatures.py
595
3.65625
4
# -*- coding: utf-8 -*- from collections import deque class Solution: def dailyTemperatures(self, temperatures): result = [0] * len(temperatures) stack = deque() for i, temperature in enumerate(temperatures): while stack and temperatures[stack[-1]] < temperature: ...
a081abee6d4854f6e2c89437d5f8222452ac84a5
jacquerie/leetcode
/leetcode/0459_repeated_substring_pattern.py
491
3.59375
4
# -*- coding: utf-8 -*- class Solution: def repeatedSubstringPattern(self, s): length = len(s) for i in range(1, length // 2 + 1): if length % i == 0 and s[:i] * (length // i) == s: return True return False if __name__ == "__main__": solution = Solution() ...
2c7109b0ae15648ce72885eda26790d849ec59ea
jacquerie/leetcode
/leetcode/0189_rotate_array.py
312
3.71875
4
# -*- coding: utf-8 -*- class Solution: def rotate(self, nums, k): nums[:] = nums[len(nums) - k :] + nums[: len(nums) - k] if __name__ == "__main__": solution = Solution() nums = [1, 2, 3, 4, 5, 6, 7] assert solution.rotate(nums, 3) is None assert [5, 6, 7, 1, 2, 3, 4] == nums
318b1399766bf7abe29c6cba05f45d51cf10dd28
jacquerie/leetcode
/leetcode/0856_score_of_parentheses.py
636
3.625
4
# -*- coding: utf-8 -*- class Solution: def scoreOfParentheses(self, S): current_depth, result = 0, 0 for i, c in enumerate(S): if c == "(": current_depth += 1 else: current_depth -= 1 if S[i - 1] == "(": ...
9e6945ece37e20063d5e431c024d338b0047856d
jacquerie/leetcode
/leetcode/0989_add_to_array_form_of_integer.py
846
3.65625
4
# -*- coding: utf-8 -*- from typing import List class Solution: def addToArrayForm(self, num: List[int], k: int) -> List[int]: return self.toArrayForm(self.fromArrayForm(num) + k) def toArrayForm(self, num: int) -> List[int]: return [int(digit) for digit in str(num)] def fromArrayForm(s...
8b8c89cbe7eb92d7bcff511977aa42f2f826e7d7
jacquerie/leetcode
/leetcode/0442_find_all_duplicates_in_an_array.py
486
3.75
4
# -*- coding: utf-8 -*- class Solution: def findDuplicates(self, nums): result = [] for num in nums: i = abs(num) - 1 if nums[i] > 0: nums[i] = -nums[i] else: result.append(abs(num)) return result if __name__ == "__mai...
0ced123ad0e2a5a9728b8dee64d1e7a9a019377c
jacquerie/leetcode
/leetcode/2160_minimum_sum_of_four_digit_number_after_splitting_digits.py
390
3.671875
4
# -*- coding: utf-8 -*- class Solution: def minimumSum(self, num: int) -> int: digits = sorted(str(num), reverse=True) return ( int(digits[0]) + int(digits[1]) + 10 * int(digits[2]) + 10 * int(digits[3]) ) if __name__ == "__main__": solution = Solution() assert 52 ==...
fb78e64acacdb16c69de81ea4cc92c37aa001ecb
jacquerie/leetcode
/leetcode/1175_prime_arrangements.py
719
3.53125
4
# -*- coding: utf-8 -*- from math import factorial class Solution: PRIMES = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,...
4571f4ab02e2d9bbdd32867b05e6f88290a059a8
jacquerie/leetcode
/leetcode/0202_happy_number.py
390
3.53125
4
# -*- coding: utf-8 -*- class Solution: def isHappy(self, n): seen = set() while n != 1: n = sum(int(char) ** 2 for char in str(n)) if n in seen: return False seen.add(n) return True if __name__ == "__main__": solution = Solution(...
7ec5715d2ac86ff52fa4de0c128bc50924271b2b
jacquerie/leetcode
/leetcode/1417_reformat_the_string.py
977
3.859375
4
# -*- coding: utf-8 -*- class Solution: def reformat(self, s: str) -> str: digits, letters = [], [] for char in s: if char.isdigit(): digits.append(char) else: letters.append(char) if abs(len(digits) - len(letters)) > 1: ...
9a8f5b718f6d2d08fb0e5cc13e1ac5c12f1fab7f
jacquerie/leetcode
/leetcode/0812_largest_triangle_area.py
589
3.734375
4
# -*- coding: utf-8 -*- import itertools class Solution: def largestTriangleArea(self, points): result = 0 for (x_a, y_a), (x_b, y_b), (x_c, y_c) in itertools.combinations(points, 3): area = abs((x_a - x_c) * (y_b - y_a) - (x_a - x_b) * (y_c - y_a)) / 2 if area > result: ...
feb22aa5c69cdec060bf618b79be03046b4eedc9
jacquerie/leetcode
/leetcode/0056_merge_intervals.py
1,392
3.671875
4
# -*- coding: utf-8 -*- class Interval: def __init__(self, s=0, e=0): self.start = s self.end = e def __eq__(self, other): return self.start == other.start and self.end == other.end class Solution: def merge(self, intervals): intervals.sort(key=lambda interval: interval....
8af974cf30f71656110ff8ea3510219cad025632
jacquerie/leetcode
/leetcode/1374_generate_a_string_with_characters_that_have_odd_counts.py
380
3.671875
4
# -*- coding: utf-8 -*- class Solution: def generateTheString(self, n: int) -> str: if n % 2: return "a" * n return "a" * (n - 1) + "b" if __name__ == "__main__": solution = Solution() assert "aaab" == solution.generateTheString(4) assert "ab" == solution.generateTheStri...
d6775606b284fe583098ad9226703dea535724c0
jacquerie/leetcode
/leetcode/0079_word_search.py
1,724
3.734375
4
# -*- coding: utf-8 -*- class Solution: def exist(self, board, word): visited = set() for i in range(len(board)): for j in range(len(board[0])): if self.startsHere(board, word, visited, 0, i, j): return True return False def startsHere(s...
09e00c841d3e15e5dbc36435de3646ac1eb2a14f
jacquerie/leetcode
/leetcode/0101_symmetric_tree.py
1,239
3.90625
4
# -*- coding: utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSymmetric(self, root): if root is None: return True return self._isSymmetric(root.left, root.right) def _isSymmetric(s...
83030afbf88e3d5bae192c5e1ec3a470dd41b7a8
jacquerie/leetcode
/leetcode/0141_linked_list_cycle.py
816
3.734375
4
# -*- coding: utf-8 -*- class ListNode: def __init__(self, x): self.val = x self.next = None def __eq__(self, other): return other is not None and self.val == other.val and self.next == other.next class Solution: def hasCycle(self, head): slow, fast = head, head ...
a3b84a300e74838926894dee80cd573c2a6f5469
jacquerie/leetcode
/leetcode/0946_validate_stack_sequences.py
744
3.828125
4
# -*- coding: utf-8 -*- from collections import deque class Solution: def validateStackSequences(self, pushed, popped): i, j, stack = 0, 0, deque() while i < len(pushed) or j < len(popped): if j < len(popped) and stack and stack[-1] == popped[j]: stack.pop() ...
83f155bca052fb0718ed3d1812b23aedac7a60fc
jacquerie/leetcode
/leetcode/0785_is_graph_bipartite.py
1,395
3.671875
4
# -*- coding: utf-8 -*- from collections import deque class Color: BLACK = 0 WHITE = 1 class Solution: def isBipartite(self, graph): color = {} for node in range(len(graph)): if node in color: continue stack = deque([node]) color[node]...
71642b1d6f4ee81d60035a39f039099eb9582a20
jacquerie/leetcode
/leetcode/1822_sign_of_the_product_of_an_array.py
629
3.59375
4
# -*- coding: utf-8 -*- from typing import List class Solution: def arraySign(self, nums: List[int]) -> int: negative_count, zero_seen = 0, False for num in nums: if num == 0: zero_seen = True elif num < 0: negative_count += 1 if ze...
f1ab104326656551a508c9f977c67b56c6e50be1
jacquerie/leetcode
/leetcode/0876_middle_of_the_linked_list.py
846
3.921875
4
# -*- coding: utf-8 -*- class ListNode: def __init__(self, x): self.val = x self.next = None def __eq__(self, other): return other is not None and self.val == other.val and self.next == other.next class Solution: def middleNode(self, head): slow, fast = head, head ...
1b788777bd76203caa7a7d9a1ee683b6221363d1
jacquerie/leetcode
/leetcode/0594_longest_harmonious_subsequence.py
474
3.578125
4
# -*- coding: utf-8 -*- from collections import Counter class Solution: def findLHS(self, nums): result = 0 counter = Counter(nums) for num in counter: if num + 1 in counter: result = max(result, counter[num] + counter[num + 1]) return result if __n...
ee3e819de392fc00132df6aedcb93602dc88365c
jacquerie/leetcode
/leetcode/1252_cells_with_odd_values_in_a_matrix.py
562
3.5625
4
# -*- coding: utf-8 -*- from collections import Counter class Solution: def oddCells(self, n, m, indices): row_counts = Counter() col_counts = Counter() for row, col in indices: row_counts[row] += 1 col_counts[col] += 1 return sum( (row_counts[...
f8567b991f92f9e20fd8bf25e2bd47d9957f5491
jacquerie/leetcode
/leetcode/1496_path_crossing.py
632
3.890625
4
# -*- coding: utf-8 -*- class Solution: def isPathCrossing(self, path: str) -> bool: x, y, visited = 0, 0, set([(0, 0)]) for char in path: if char == "N": x += 1 elif char == "E": y += 1 elif char == "S": x -= 1 ...
384cf639af460ccb442ae94a73aef8a05e92b211
jacquerie/leetcode
/leetcode/2206_divide_array_into_equal_pairs.py
374
3.515625
4
# -*- coding: utf-8 -*- from collections import Counter from typing import List class Solution: def divideArray(self, nums: List[int]) -> bool: return all(el % 2 == 0 for el in Counter(nums).values()) if __name__ == "__main__": solution = Solution() assert solution.divideArray([3, 2, 3, 2, 2, ...
706413dd18849263340b0e21e6a8e6b9f87a8a98
jacquerie/leetcode
/leetcode/0532_k_diff_pairs_in_an_array.py
635
3.53125
4
# -*- coding: utf-8 -*- from collections import Counter class Solution: def findPairs(self, nums, k): if k < 0: return 0 elif k == 0: return len([_ for _, count in Counter(nums).items() if count > 1]) result = 0 nums_set = set(nums) for num in num...
953e53dec8d2301145c160297f2fff21e32e3a04
jacquerie/leetcode
/leetcode/2138_divide_a_string_into_groups_of_size_k.py
480
3.890625
4
# -*- coding: utf-8 -*- from typing import List class Solution: def divideString(self, s: str, k: int, fill: str) -> List[str]: if len(s) % k: s += fill * (k - len(s) % k) return [s[i : i + k] for i in range(0, len(s), k)] if __name__ == "__main__": solution = Solution() as...
74fd298f325a6fdeb5e557bbbed25b6998a40a93
jacquerie/leetcode
/leetcode/0788_rotated_digits.py
872
3.640625
4
# -*- coding: utf-8 -*- class Solution: def rotateDigit(self, d): if d == "0": return "0" elif d == "1": return "1" elif d == "2": return "5" elif d == "5": return "2" elif d == "6": return "9" elif d == "8...
416eb0057e052d049c1688da9f686a1a241f563d
jacquerie/leetcode
/leetcode/0349_intersection_of_two_arrays.py
247
3.734375
4
# -*- coding: utf-8 -*- class Solution: def intersection(self, nums1, nums2): return list(set(nums1) & set(nums2)) if __name__ == "__main__": solution = Solution() assert [2] == solution.intersection([1, 2, 2, 1], [2, 2])
ea558c42e614c002603d30064f84139a43210015
jacquerie/leetcode
/leetcode/0831_masking_personal_information.py
938
3.515625
4
# -*- coding: utf-8 -*- import re class Solution: def maskPII(self, S): if self.isEmail(S): return self.maskEmail(S) return self.maskPhoneNumber(S) def isEmail(self, S): return "@" in S def maskEmail(self, S): name1, rest = S.lower().split("@") return...
ac921b0ecb0669b4e37c9e17266d85bd425de836
jacquerie/leetcode
/leetcode/0118_pascals_triangle.py
785
3.609375
4
# -*- coding: utf-8 -*- class Solution: def generate(self, numRows): result = [] if not numRows: return result current = [1] for row in range(numRows): next = [] for col in range(row + 1): if col == 0: next.ap...
a53868adba2ac24b6ad4b2749e8994bc5751d6ce
jacquerie/leetcode
/leetcode/1437_check_if_all_1s_are_at_least_length_k_places_away.py
688
3.5625
4
# -*- coding: utf-8 -*- from typing import List class Solution: def kLengthApart(self, nums: List[int], k: int) -> bool: last_index = None for index, num in enumerate(nums): if num == 1: if last_index is not None and index - last_index <= k: return ...
b3732c55bf3cc794fda7811b88558f7e6672b6f8
anthonyndunguwanja/Anthony-Ndungu-bootcamp-17
/Day 2/Data_Types_Lab .py
396
3.984375
4
def data_type(x): if type(x) is int: if x < 100: print('less than 100') elif x == 100: print('equal to 100') else: print('more than 100') elif type(x) is None: print('no value') elif type(x) is bool: print(bool(x)) elif type(x) is str: print(len(x)) elif type(x)...
2d0d7b720e33a2017c9e0dbf7e2ef1c2e7741910
AdityaMV1215/fractal_hackerrank_hiring_challenge_2
/q01_get_minimum_unique_square/build.py
236
3.75
4
# Default imports from math import sqrt # Write your solution here: def q01_get_minimum_unique_square(x,y): count = 0 for i in range(1,x+1): if i**2 >= x and i**2 <= y: count = count + 1 return count
63e020b7c54591d8692741c004a54bc94b623a86
davidpenuel/Test_Python
/Animal.py
92
3.640625
4
answer=input("What is your favortie animal?") print("Your favortie animal is") print(answer)
056814f23fc7cade96550231ca4bdb009f00627d
ngupta23/more
/build/lib/more/viz_helper/pca_helper.py
3,577
3.734375
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA def perform_pca(data, n_components=3, y=None): """ data = Data on which to perform PCA n_components = 3. This is the number o...
c2dd03a67ae64acd2a5f1a5573cd1459448eaf65
baturkey/eulerpy
/022.py
843
3.671875
4
""" Project Euler Problem 22 ======================== Using names.txt, a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For...
f72e7a27b97824abe6a860fff4d2f2024d20a97a
baturkey/eulerpy
/010.py
689
3.8125
4
""" Project Euler Problem 10 ======================== The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. """ from math import sqrt prime_list = [3] def is_prime(x): output = False root = sqrt(x) global prime_list for prime in prime_list: ...
c99b25563b86f4fe43706ec94c935278a98bad48
thiagodnog/projects-and-training
/Curso Python Coursera/Semana 2/Lista de Exercícios Adicionais 1/Adicional1Exercicio2 - segundos.py
435
3.75
4
segundos_str = input("Por favor, entre com um número de segundos que deseja converter: ") total_segundos = int(segundos_str) dias = total_segundos // 86400 seg_restantes = total_segundos % 86400 horas = seg_restantes // 3600 seg_restantes_2 = seg_restantes % 3600 minutos = seg_restantes_2 // 60 seg_restantes_final = s...
3b71a97cb832c9953155e117ed22fad463c33a25
thiagodnog/projects-and-training
/Curso Python Coursera/Semana 3/Livro Texto/livroTexto-cap06Selecao-ex9.py
490
4.125
4
"""" Curso de Introdução à Ciência da Computação com Python Parte 1 Livro Texto Exercício 9 Modifique é_ímpar de forma que ela use uma chamada para é_par para determinar se o argumento é um inteiro par ou ímpar. """ numero = int(input("Digite o número a ser avaliado: ")) def é_par(n): par = n % 2 == 0 ret...
894470e0bdd582775a410b9bfbf321909599b102
thiagodnog/projects-and-training
/Curso Python Coursera/Semana 5/Lista de Exercícios 4/lista4Exercicio1-maximo2.py
423
4.3125
4
''' Curso de Introdução à Ciência da Computação com Python Parte 1 Semana 5 - Lista de Exercício 4 Exercício 1 - Máximo Escreva a função maximo que recebe 2 números inteiros como parâmetro e devolve o maior deles. Exemplos de execução no shell do Python: >> maximo(3, 4) 4 >> maximo(0, -1) 0 ''' def maximo(num1,nu...
a96677f7fedce137bbbd43458d761be853b910ae
thiagodnog/projects-and-training
/Curso Python Coursera/Semana 3/Livro Texto/livroTexto-cap06Selecao-ex12.py
833
4.34375
4
"""" Curso de Introdução à Ciência da Computação com Python Parte 1 Livro Texto Exercício 12 Um ano é bissexto se ele é divisível por 4 a menos que seja um século que não é divisível por 400 ou é divisível por 100. Escreva uma função que receba um ano como argumento e retorna True se o ano é bissexto e False caso ...
1d5bd2b1847aee83932b5235b5a2ff24106a4090
thiagodnog/projects-and-training
/Curso Python Coursera/Semana 3/Lista de Exercícios 2/Lista2Exercicio2-fizz.py
404
4.125
4
""" Curso - Introdução à Ciência da Computação com Python Parte 1 Exercícios 2 - FizzBuzz parcial, parte 1 Receba um número inteiro na entrada e imprima Fizz se o número for divisível por 3. Caso contrário, imprima o mesmo número que foi dado na entrada. autor: Thiago Nogueira """ numInt = int(input("Digite um núme...
d5b3f9e00ad09d921aa87e12d5e6d943531ad552
DaveLoaiza/UCBX433
/homeworks and class exercises/dloaiza_HW2.py
1,866
4.0625
4
# -*- coding: utf-8 -*- """ Created on Fri Apr 28 13:05:55 2017 Homework Assignment #2: 1. Include a section with your name @author: Dave Loaiza -- dave.loaiza@gmail.com Python For Data Analysis And Scientific Computing UC Berkeley Extensoin 16. Organize your code: use each line from this assignment as a comment l...
35cc31adbadae0cef06d23c86d2e7ee14b30372a
zdzc/penyisihan-idefuse-2019
/src/b.py
1,172
3.5
4
import math from collections import deque N = 2000000 def can_traverse(towers, radius): visited = [False] * len(towers) queue = deque([(0, towers[0])]) while queue: num, (x1, y1) = queue.popleft() if visited[num]: continue visited[num] = True for i, (x2, y2...
8b1b41a43dfd7d324ac24111733fa17a4de99f57
Chewbaccademy/toad-project
/Dataset.py
2,207
3.5625
4
class Dataset: def __init__(self, fields, data): """ Constructor for Dataset @param {list[string]} fields name @param {list[Datum]} data """ self._fields = fields self._data = data self._nbfields = len(fields) self._index = 0 self._n...
ebe166884175888fedfcd6cb135d5da3f5f03b42
virenukey/LinkedList
/singleLinkedList.py
4,321
4
4
class Node: def __init__(self, data=None): self.data = data self.next = None def getData(self): return self.data def getNext(self): return self.next def setData(self, newData): self.data = newData def setNext(self, newNext): self.next = newNext c...
0db3bdf84b62779b2a189cd5d4e0df737fc526da
JeffreyDCummings/Travel_Cost_Analysis
/city_set.py
657
4.1875
4
""" Set of functions for reading and formatting lists of cities. """ import pandas as pd def extract_count(citieslist): """ Reads in large population city list and returns this as list and its length. """ cities = pd.read_csv(citieslist, delimiter=",") return cities, len(cities) def city_set(cities, start...
36dcd86c27744be03c9515704703f997f49cb77b
HETHAT/LinkedList
/DNode.py
498
3.5625
4
class Node: def __init__(self, data, next_=None, prev=None): self.data = data self.next = next_ self.prev = prev def __repr__(self): return f"{self.data!r}" def __lt__(self, other): if isinstance(other, Node): return self.data < other.data ...
55667aa019be8138a0a17c018d6c9e3d54f99733
nkuhero/pytest
/enum_test.py
170
3.546875
4
from enum import Enum, unique @unique class Weekday(Enum): Sun = 0 Mon = 1 Tue = 2 if __name__ == "__main__": day = Weekday.Mon print(day.value)