blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
b198a8afa7ed97c801d12eac78a22e596d35f439 | emreustaa/PythonProgramming | /Week 2/secondproject/ikinciders_2.py | 1,748 | 4.125 | 4 | # CHAPTER 4
# Working more with Lists
names = ["ali", "ahmed", "bob"]
for name in names:
print(name)
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title() + ', that was a agreat trick')
print("I can't wait to see your next trick, " + magician.title() + ".\n")
print... |
0abfac960f8faffc7ff276f37173e5cb26c3b920 | xwang322/Coding-Interview | /Linkedin/FindOneValidTriangle.py | 819 | 3.90625 | 4 | '''
寻找数组里有没有三个数字可以组成一个三角形。楼主当时看到就以为是原题要找出所有可以组成三角形的三个数组,哗啦啦讲了一大堆,
小哥说你这个复杂度太高了,纠结了一下还能怎么简化,结果发现人家只是让找有没有一组数字满足要求即可。。- -
时间不太够了就赶紧写了写完事。惨痛的教训:不要看到原题就激动的去做,一定要好好听完题。。
'''
def findOneTriangle(nums):
if not nums:
return 0
nums.sort()
for i in range(len(nums)-1, 1, -1):
left = 0
... |
a021b8c976d287952719d207a4f2f51f22d4831f | xwang322/Coding-Interview | /python/P436.py | 621 | 3.5625 | 4 | # Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def findRightInterval(self, intervals):
if len(intervals) == 0 or len(intervals) == 1:
return [-1]
answer = []
... |
05e82ef2a7b4233806a2c9205be976975b5058f4 | xwang322/Coding-Interview | /uber/uber_algo/LC36ValidSudoku3.py | 1,325 | 3.671875 | 4 | class Solution(object):
def isValidSudoku(self, board):
if not board or not board[0]:
return False
return self.rowcheck(board) and self.colcheck(board) and self.digcheck(board)
def rowcheck(self, board):
for i in range(9):
temp = set()
for j ... |
a4ebe202c8655e906e57412fe85546eba7ca9afb | xwang322/Coding-Interview | /uber/uber_algo/IntervalAnd_UB.py | 1,811 | 3.875 | 4 | '''
题目:Given 2 sets of intervals.
Interval is defined with left and right border and discrete points, like [2, 3], [0, 0], etc.
Set of intervals is non intersected set of sorted intervals,
for example: [0, 0], [2, 2], [5, 10] is a valid set of intervals, but [0, 0], [1, 2] is not valid, because you can write it as ... |
3ae95a8744eb2ee64e74367438d9477d07a8ad11 | xwang322/Coding-Interview | /uber/uber_ood/ThreadSafeSet.py | 1,473 | 3.796875 | 4 | '''
怎么实现一个系统,如果key不在里面就新加一个entry并返回true,如果key在里面就直接返回false,类似unix系统里的touch这个命令。
先讲了单机版的,主要focus在write lock怎么整
'''
import threading
class Touch(object):
def __init__(self):
self.array = set()
self.lock = threading.Lock()
def _add(self, key):
if key in self.array:
... |
9046833af34ac19ac0bbff34070917eb8d309d2b | xwang322/Coding-Interview | /python/P362.py | 1,185 | 3.546875 | 4 | class HitCounter(object):
''' using double side queue
def __init__(self):
from collections import deque
self.total = 0
self.record = deque()
def hit(self, timestamp):
if not self.record or self.record[-1][0] != timestamp:
self.record.append([ti... |
f869ecb9a707d48db2977eef4834a92325d49f00 | xwang322/Coding-Interview | /uber/uber_algo/LC326PowerOfThree.py | 259 | 3.734375 | 4 | class Solution(object):
def isPowerOfThree(self, n):
if n < 1:
return False
if n == 1:
return True
while n>1:
if n%3:
return False
n/=3
return True
|
f1b7024b0f175431af4a509728572b683ad6665b | xwang322/Coding-Interview | /Linkedin/NearestMeetPoint.py | 926 | 4 | 4 | '''
第二题给定一个m*n的grid,上面有一些点代表一群人的位置,找最近的meet point
'''
def meetNearestPoint(grid, start):
if not grid:
return [-1, -1]
m = len(grid)
n = len(grid[0])
if not 0 <= start[0] < m or not 0 <= start[1] < n:
return [-1, -1]
queue = [start]
visited = set()
while queue:
... |
e352cecdd54cbd22604a4a3e08bbe7fbabeae1b0 | xwang322/Coding-Interview | /uber/uber_ood/LC146LRUCacheDLL.py | 1,616 | 3.828125 | 4 | class Node(object):
# for double linked list, simply deleting is not O(1), but with the dict help, it is O(1)
def __init__(self, k, v):
self.key = k
self.value = v
self.prev = None
self.next = None
class LRUCache(object):
def __init__(self, capacity):
s... |
c867fc3186d4d8ffbf40f631e114a466cab708de | xwang322/Coding-Interview | /uber/uber_algo/longestwordindicttrie2_UB.py | 1,043 | 3.515625 | 4 | /*
* 另一题是给一个字典和一个字符串S,在字典的所有单词中找出一个最长的单词并且其所有字母都在S中出现过。面试官希望看到的是trie+dfs。
**/
import collections
def findLongestWordInDict(dictionary, string):
if not string or not dictionary:
return ''
counter = collections.Counter(string)
trie = {}
for word in dictionary:
t = trie
f... |
e09038dc2afb5601179e529c6de4e46570a260f8 | xwang322/Coding-Interview | /python/P513.py | 401 | 3.703125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findBottomLeftValue(self, root):
curr_list = [root]
for each in curr_list:
cur... |
7511e220ba15ecb6ac896d42a57a99f9b592bd98 | xwang322/Coding-Interview | /EA/LC186ReverseWordsInAStringII.py | 664 | 3.59375 | 4 | class Solution(object):
# input is a char array, not a strict string
# in-place replacement
def reverseWords(self, string):
if not string:
return
string.append(' ')
start = 0
i = 0
while i < len(string):
if string[i] == ' ':
... |
82d9a86e7b35440c82eb35d2280a5cdf38a46229 | xwang322/Coding-Interview | /uber/uber_algo/LC212WordSearchII.py | 1,440 | 3.625 | 4 | class Solution(object):
def findWords(self, board, words):
if not board or not words:
return []
answer = []
trie = {}
for word in words:
t = trie
for char in word:
if char not in t:
t[char] = {}
... |
af13da7bbf40c35c413d48dc4e2a49a8b02f9f93 | xwang322/Coding-Interview | /asml/LC766ToeplitzMatrix.py | 335 | 3.53125 | 4 | class Solution(object):
def isToeplitzMatrix(self, matrix):
if not matrix or not matrix[0]:
return False
temp = matrix[0]
for i in range(1, len(matrix)):
if temp[:-1] != matrix[i][1:]:
return False
temp = matrix[i]
return T... |
8d956e20b10085744f68e898976f3cd4f9a182e6 | xwang322/Coding-Interview | /sumologic/prefix_calculator_SL.py | 1,075 | 3.984375 | 4 | /*
* prefix calculator
**/
def prefixCalculator(string):
tokens = string.split(' ')
stack = []
total = None
for token in tokens:
if token.isdigit():
temp = int(token)
if not total:
total = temp
else:
total = evaluat... |
19c3f4be348edbcf874d1a946c8e810cd1295d8e | xwang322/Coding-Interview | /uber/uber_algo/LC23MergeKSortedLists.py | 2,004 | 3.90625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
from Queue import PriorityQueue
class Solution(object):
# Python Heap
'''
def mergeKLists(self, lists):
if not lists:
return None
... |
0e56291e9739102bf907d06507b68d7958a50644 | xwang322/Coding-Interview | /uber/uber_algo/LC98ValidateBinarySearchTree.py | 775 | 3.875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isValidBST(self, root):
return self.isValidBSTrange(root, -float('inf'), float('inf'))
def is... |
7c0b1f7e9c395b1629b9db7cab33e6e30bb591bb | xwang322/Coding-Interview | /python/P145.py | 518 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def postorderTraversal(self, root):
answer = []
stack = [root]
while stack:
... |
eb86cb5dc16fcbdaa9bddd3374ffc887a4d2f644 | xwang322/Coding-Interview | /uber/uber_algo/BankTransaction_UB.py | 1,370 | 3.703125 | 4 | /*
* 第二轮,很搞笑了,紧张的等了好久没接到电话然后HR说interviewer有urgent matter,约了下周..
* 可能interviewer感到愧疚所以给了一道很简单的题:给了一些bank间transaction的数据,把两个一样的bank数据merge起来输出。
* 比如BOA->CHASE 20, CHASE->BOA 10, result就是 BOA->CHASE 10.
**/
def BankTransaction(records):
if not records:
return records
dictionary = {}
for r... |
7607a9de322ca5f95d59496aade734aa9e464981 | xwang322/Coding-Interview | /uber/uber_ood/Battleship.py | 5,429 | 3.875 | 4 | '''
设计一个战棋游戏,主要是保存状态还有决定谁赢了, 类似battleship
'''
import sys
import collections
import random
class Player(object):
def __init__(self, id):
self.id = id
self.side = 5
def PlaceShip(self, length):
horizontal = random.randint(0, self.side-1)
vertical = random.randint(0, s... |
57b3ebe56c3ab219f4d1423e4868d81b12e3adeb | xwang322/Coding-Interview | /EA/pylist.py | 149 | 3.625 | 4 | a = []
d = []
b = [1 ,2, 4]
c = [2, 3, 4]
a.append(b)
a.append(c)
d.append(b[:])
d.append(c[:])
print a
print d
b.pop()
print a
print d
|
6cae11659e1753a257e6c4fe4e73744becf7442f | xwang322/Coding-Interview | /EA/FindFirstBad.py | 548 | 3.609375 | 4 | '''
第一题:一个boolean array,里面是good bad的flag,如果bad发生,他之后就都是bad. 比如good, good, bad, bad,....., bad。求第一个bad。很简单,binary search.
'''
import bisect
def findFirstBad(flags):
if not flags or -1 not in flags:
return -1
new_flag = []
for flag in flags:
if flag == 1:
new_flag.append(... |
205057950b4183926d8c6f6be41ee963e12ecd2d | xwang322/Coding-Interview | /python/P404.py | 711 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def sumOfLeftLeaves(self, root):
if not root:
return 0
answer = []
self.d... |
2e31029eb3c2530437fd07cc8d7f820c0ae227bf | xwang322/Coding-Interview | /uber/uber_algo/IntervalIntersectionLinkedList_UB.py | 1,470 | 3.671875 | 4 | '''
intervals_intersection in linked list format
'''
class ListNode(object):
def __init__(self, start, end):
self.start = start
self.end = end
self.next = None
class solution(object):
def intervals_intersection(self, list1, list2):
if not list1 or not list2:
... |
1b43890941e87a3947e0d84b3caa2d9072453eb5 | xwang322/Coding-Interview | /Linkedin/LC10RegularExpression2.py | 881 | 3.515625 | 4 | class Solution(object):
# This version is actually more easily understanding
def isMatch(self, s, p):
m = len(s)
n = len(p)
dp = [[False for i in range(m+1)] for j in range(n+1)]
dp[0][0] = True
for i in range(1, n+1):
if p[i-1] == '*':
... |
3e9aa45720a9db708f04fdb29750b7e32e53d9e1 | xwang322/Coding-Interview | /python/P515.py | 788 | 3.859375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
# bfs
def largestValues(self, root):
if not root:
return []
curr_list = [root... |
dfba4a1e652d89115f306040699f85999e3763b9 | xwang322/Coding-Interview | /uber/uber_ood/Parking.py | 6,008 | 3.796875 | 4 | '''
Elevator design:
# system design
# OOD
# algorithm
useful link:
https://www.youtube.com/watch?v=DSGsa0pu8-k
https://www.geeksforgeeks.org/design-parking-lot-using-object-oriented-principles/
System design:
1. clarify questions: is this a sd or ood or coding?
2. How is this parking designed? Open space or ... |
7c7220234e6e3b75be7ac6c4880e283f457c8dad | xwang322/Coding-Interview | /uber/uber_ood/LC381InsertDeleteGetRandomO(1)DuplicatesAllowed.py | 1,124 | 3.71875 | 4 | class RandomizedCollection(object):
def __init__(self):
self.array = []
self.dictionary = collections.defaultdict(set)
def insert(self, val):
self.array.append(val)
self.dictionary[val].add(len(self.array)-1)
return len(self.dictionary[val]) == 1
def rem... |
21d7c01c8eeed7f23e632d4faff564117a246df8 | xwang322/Coding-Interview | /Linkedin/LC170TwoSumIII-DataStructureDesign2.py | 780 | 3.65625 | 4 | class TwoSum(object):
def __init__(self):
self.list = []
def add(self, number):
if not self.list:
self.list.append(number)
else:
index = bisect.bisect_left(self.list, number)
self.list.insert(index, number)
def find(self, value):
... |
5e8be7710636626d14a7c48bb03a982526121da5 | xwang322/Coding-Interview | /uber/uber_algo/BreakingBad_UB.py | 1,460 | 4 | 4 | /*
* 电面45分钟, 题目是 breaking bad + 分析时间空间复杂度。有点赶,但总算是有写完。
* Given an array of strings `words` and a string `name`, find one substring of `name` that matches any word in `words`.
* Put brackets around the matching substring in `name` and capitalize the first letter.
* Sample input: words = ['B', 'Ar', 'O']
* name = 'a... |
3528e6ed7932838b542db077b8a225e5ecddd552 | xwang322/Coding-Interview | /python/P435.py | 657 | 3.59375 | 4 | # Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def eraseOverlapIntervals(self, intervals):
# sort by first element
if not intervals:
return 0
intervals... |
9834fdabc1206358d8317b6ba0462910b4468530 | xwang322/Coding-Interview | /EA/LookUpInBST.py | 855 | 3.625 | 4 | '''
问了BST lookup (int val)的实现
'''
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def lookUpinBST(root, target):
if not root:
return False
if root.val == target:
return True
elif root.val > target:
... |
46a56ed7f4f865044bd2da5ad10ed723cf1c1ef6 | xwang322/Coding-Interview | /uber/uber_algo/SortedArraySquareSorted_UB.py | 687 | 3.5625 | 4 | /*
* 第一题是将一个有序数组乘方后返回import bisect
**/
def SortedSquareArray(array):
left = right = bisect.bisect_left(array, 0)
print left, right
answer = []
while right-left < len(array):
if right == len(array):
while left > 0:
answer.append(array[left-1]**2)
... |
039e37afafbe7a2487ba2590e6a90cff32e67c11 | xwang322/Coding-Interview | /groupon/FindKthSmallestElement_GP.py | 525 | 3.546875 | 4 | /*
* find kth smallest number in an array
**/
import heapq
def findKthSmallest(nums, k):
heap = []
for i in range(len(nums)):
if len(heap) < k:
heapq.heappush(heap, -nums[i])
else:
temp = heapq.heappop(heap)
if temp < -nums[i]:
heap... |
91fb9f85a32b3412ca071830ff17cc35a6fd0bcb | xwang322/Coding-Interview | /Linkedin/LC146LRUCacheCoderpad.py | 1,851 | 3.671875 | 4 | class Node(object):
def __init__(self, k, v):
# the role of key here is to remove the node by the node count, when updating the dictionary, based on node.key
self.key = k
self.value = v
self.next = None
self.prev = None
class LRUCache(object):
def __init__(sel... |
0c4fb75e1e2ff8653ba2d56a2662ea8ad88e76d3 | xwang322/Coding-Interview | /EA/IsBalancedTree_mutation.py | 1,877 | 3.75 | 4 | '''
isBalancedTree 这个题和leetcode的不大一样,要求是看整个tree最短的和整个tree最长的path 差是否小于2.我的复杂度高了点,没被满意。
'''
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class IsBalancedTree(object):
def __init__(self):
self.node1 = TreeNode(7)
... |
06fe0edf2980db052769478bd1ecf6d83f72cefc | xwang322/Coding-Interview | /python/P20.py | 811 | 3.90625 | 4 | class Solution(object):
def isValid(self, s):
if not s or len(s) == 0:
return True
if len(s)%2:
return False
stack = []
for each in s:
if each == '(' or each == '[' or each == '{':
stack.append(each)
else:
... |
40a02fb83eccaf0d6050ee056f0e6bbcdfc149d7 | xwang322/Coding-Interview | /drawbridge/number_of_combination_DB.py | 450 | 3.765625 | 4 | /*
* Given a positive integer target, count all the combinations of contiguous positive
* integers that sum up to the target.
* For Example,
* target = 15
* return 3
* since
* 15 = 4 + 5 + 6
* 15 = 1 + 2 + 3 + 4 + 5
* 15 = 7 + 8
* */
def numofComb(num):
if num <= 0:
return 0
count = 0
... |
22e3faea8978d18516cddd91bbb5e5c47e88b612 | xwang322/Coding-Interview | /Linkedin/CartesianProducts.py | 1,853 | 3.8125 | 4 | '''
一个说话声音很轻没精打采的烙印,一副我欠他钱的样子,给一个list的set,{{a,b,c},{d},{e,f}},
输出它们的Cartesian product {a,d,e},{a,d,f},{b,d,e},{b,d,f},{c,d,e},{c,d,f},
recursive做好后要用iterative的for循环来写
'''
def cartesianProduct(lists):
if not lists:
return []
for list in lists:
if len(list) == 0:
return []
... |
fb5344182d69d1ada4848ab53d4ef5b81f3887eb | xwang322/Coding-Interview | /uber/uber_algo/SerializeAndDeserilizeBinaryTreeMutation_UB.py | 4,463 | 3.546875 | 4 | '''
Serialize and deserialize a k-ary tree
意大利小哥,问的问题是encode and decode tree,也就是tree2string, string2tree。leetcode上貌似有原题,
但是不同的地方在于,leetcode上是binary tree,面试的时候我问了能不能假设tree是binary tree,他说不可以。。。
于是开始码,然后写test case,然后跑代码。。感觉思路是对的,但是跑出来结果总是不对,然后debug,
中间发现一个粗心大意的bug,解决后发现还有其他bug,也是各种试,最后在小哥的提醒下发现了有地方递归了两边。。
所以打印出来的东... |
9b0def67860648d736da53799160b5106aa648c4 | xwang322/Coding-Interview | /python/P36.py | 825 | 3.5 | 4 | class Solution(object):
def isValidSudoku(self, board):
m = len(board)
n = len(board[0])
for i in range(m):
for j in range(n):
if board[i][j] != '.' and not self.isvalid(i, j, board):
return False
return True
def isvalid(... |
d84b26161af860be80c7087e94715602fb29d4de | xwang322/Coding-Interview | /uber/uber_algo/LC133CloneGraph.py | 1,559 | 3.59375 | 4 | # Definition for a undirected graph node
# class UndirectedGraphNode:
# def __init__(self, x):
# self.label = x
# self.neighbors = []
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGraph(self, node):
# BFS
'''... |
14048f3d23876dbfbcfe469e3af4227c643eda00 | bbreslauer/Pygraphene | /artist.py | 7,469 | 3.71875 | 4 |
from base import *
from color import Color
class Artist(PObject, Parent):
"""
Base class for any object that draws onto a Figure.
To draw an Artist on a Figure, it must know where to draw.
This is done by setting an origin and a position in relation
to that origin. The origin is defined in the Fi... |
845bf7fb3b8b848b47cacf2da9c85b6905ae251b | bbreslauer/Pygraphene | /text.py | 4,739 | 3.9375 | 4 |
from artist import Artist
from font import Font
class Text(Artist):
"""
Represent a label on a canvas.
The font used can be either a string with the font family name in it,
or a PyGraphene Font object.
The Text object contains a color property from Artist, and if font is
a Font object, the... |
26791189fdc2502fec76a410f8f5622d1ce025a9 | ytpedro11/perez_116482_project01_dontgetcaught | /funciones_juego.py | 1,545 | 3.5 | 4 | from graphics import *
from random import randint
width = 900
height = 700
player_size = 50
enemy_size = 50
enemy_pos = [randint(0, width - enemy_size), 0]
enemy_list = [10]
win = GraphWin('Game', width, height)
Game_over = False
def player_rojo(win):
player = Rectangle(Point(50, 50), Point(0, 0))
player.set... |
3d211b0687d35c56bf9998a44ce5d10cbc0c146b | louipr/design_patterns_practice | /factory_pattern_py/ShapeFactory.py | 679 | 3.625 | 4 | from Circle import Circle
from Rectangle import Rectange
from Square import Square
class ShapeFactory(object):
#use getShape method to get object of type shape
def getShape(self,shapeType):
""" get the expected object type
Args:
shapeType ([type]): [description]
Returns:... |
74edb8a3d9892e3e092eaa774862dca9d2eb58bb | arnav900/Dcoder-Challenges | /Easy/Python/The_Running_Race.py | 122 | 3.515625 | 4 | d, x, y = [int(i) for i in input().split()]
if x == y:
print("Draw")
elif x > y:
print("Alex")
else:
print("Ryan")
|
18a0b2587a4d1d70bd6b1797cb1f17cb701a595a | arnav900/Dcoder-Challenges | /Easy/Python/Fare.py | 154 | 3.515625 | 4 | f_km, for_f_km, per_km, distance = [int(i) for i in input().split()]
if distance > f_km:
print((distance - f_km) * per_km + for_f_km)
else:
print(4)
|
770da1ed109f8c25636132ea4aafb56bb92d30b9 | arnav900/Dcoder-Challenges | /Easy/Python/Threes_Company.py | 74 | 3.9375 | 4 | n = int(input())
string = input()
for i in string:
print(i * 3, end="")
|
fa3565c6a562904f8439dd2de7e838e8088a9548 | arnav900/Dcoder-Challenges | /Easy/Python/Exponentia.py | 303 | 3.828125 | 4 | n = int(input())
if n > 0:
for i in range(n + 1):
if i == (n):
print(2 ** i)
continue
print(2 ** i, end=",")
elif n < 0:
print(1.0, end=",")
i = -1
while i >= n:
if i == n:
print(2 ** i, end="")
break
print(2 ** i, end=",")
i -= 1
else:
print(1)
|
dc6a36503d3ad4920a14f31193a40cf8894b1485 | brentcaulf/COP2002 | /Project6/contacts_Caulfield.py | 3,343 | 4.375 | 4 | #!/usr/bin/env python3
import csv
# a file in the current directory
FILENAME = "contacts.csv"
# displays the program title
def display_title():
print("Contact Manager")
print()
# displays the menu and command choices
def display_menu():
print("COMMAND MENU")
print("list - Display all contacts")
... |
820cc062a9f31fc7a6dda7e2af8684d39906bfa7 | IsaacSegovia/1748957-MC | /prueba.py | 306 | 3.625 | 4 | Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> print("prueba")
prueba
>>> 1+1
2
>>> 1<2
True
>>> 1<1
False
>>> for i in range(1,10) :
print(i)
1
2
3
4
5
6
7
8
9
>>>
|
d8d84ecc44e1fbb4e419df4b01aa25603d9dad47 | limkeunhyeok/algorithm-study | /keunhak/est/prob1.py | 567 | 3.578125 | 4 | def solution(s):
slideSize = 1
startIndex = 0
while True:
if startIndex + slideSize == len(s):
break;
if isSemiAlternating(s[startIndex:startIndex + slideSize]):
slideSize += 1
else:
startIndex += 1
if isSemiAlternating(s[startIndex:startInd... |
b7218db366d8adac25f8b017d2996866a10eedec | limkeunhyeok/algorithm-study | /keunhak/chap6/tsp.py | 728 | 3.5 | 4 | import copy
INF = 1000000000
def solution(n, dist):
visited = [True]
for i in range(n - 1):
visited.append(False)
# 0 부터 시작
return shortestPath([0], visited, 0, n, dist)
def shortestPath(path, visited, currentLength, n, dist):
if len(path) == n:
return currentLength + dist[path[0... |
69608c26013daa2dcefab2e4f77e418658b51e29 | scottlow/projecteuler | /45.py | 370 | 3.71875 | 4 | import math
import time
t = time.clock()
def isPentagonal(num):
root = (1 + math.sqrt(1 + 24*num)) / 6
return root == int(root)
def isHexagonal(num):
root = (0.5 + math.sqrt(0.25 + 2*num)) / 2
return root == int(root)
n = 286
Tn = n * (n + 1) / 2
while not isPentagonal(Tn) or not isHexagonal(Tn):
n += 1
Tn =... |
8f69b22eb7f718d85d77186b967d8d5760ecca6f | scottlow/projecteuler | /24.py | 512 | 3.5 | 4 | # Never run this code.
base = "0123456789"
count = 0
def toString(intBase):
stringBase = str(intBase)
if len(stringBase) != 10:
return "0" + stringBase
def containsAllDigits(base):
booleanArray = [False] * 10
for c in base:
if booleanArray[int(c) - 1] == False:
booleanArray[int(c) - 1] = True
else:
... |
52f7fb8e1a42d20062a095d6f3d5323fbcc3a32b | PRMITR-GEEKS/ATM | /withdraw.py | 770 | 3.9375 | 4 | def sub(a,b):
return a-b
def add(a,b):
return a+b
def mul(a,b):
return a*b
def div(a,b):
return a/b
def mod(a,b):
return a%b
def cube(a):
return a**3
def square(a):
return a*a
def sqrt(a):
return a**(0.5)
def cbrt(a):
return a**(1/3)
a = int(input("Enter The First Number"))
b = int(input("E... |
73e2b6135eb41418b5d45e40827c5956d2e648f9 | AlexSchumi/Algorithms | /BFS/199.Binary_tree_rightside_view.py | 1,353 | 4.40625 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# This is my implementation of binary tree right side view
# I will use BFS to implement it
def rightSideView(self, root):
"""
:type root: TreeNode
:rty... |
8faddf22794ea6ccadfbf02843bdc8f33acbd296 | AlexSchumi/Algorithms | /DFS/257.binary_tree_paths.py | 1,738 | 4.125 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
paths = []
... |
9776a7f9eac5fe57f5b15e0f89e9659743149d57 | AlexSchumi/Algorithms | /Array/Roman_to_inter.py | 469 | 3.53125 | 4 | def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
dict = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000} # dictionary for roman integers
if not s:
return
if len(s) == 1:
return dict[s]
res = dict[s[0]] # the first elements
for r in range(1, len(s))... |
198478381c8d9e09512b873f57d4aaf826595d24 | AlexSchumi/Algorithms | /sort/merge_sort.py | 925 | 4.34375 | 4 |
# This file is to practice merge_sort algorithm in python
# merge_sort is a recursive algorithm to sort arrays
def sort(a, lo, hi):
"""
nums: a unsorted list
rtype: sorted array
"""
if hi <= lo:
return
mid = lo + (hi - lo) // 2 # check out for mid calculation
sort(a, lo, mid) #... |
a7a9209657d2049201a8ba9e8ef108bd86758057 | AlexSchumi/Algorithms | /two_pointer/16.3sum_closet.py | 2,095 | 3.640625 | 4 | import sys
class Solution(object):
"""
This is my implementation of 3sum closet using two pointer, loop over i, use j, k two pointers;
j is designed to move right and k is designed to more left.
Time complexity: O(nlogn + n^2)
Space complexity: O(1)
"""
def threeSumClosest(self, nums, targe... |
3c7c74e832f7493518b33ded08d155334be3803d | AlexSchumi/Algorithms | /DFS/47.permutation II.py | 1,073 | 3.640625 | 4 | """
:type nums: List[int]
:rtype: List[List[int]]
"""
class Solution():
def permuteUnique(self, num):
results = []
cur = []
used = [False for i in range(len(num))]
self.dfs(results, used, cur, num)
return results
# this is helper function to get the permutation
def d... |
28b715a1874e51fa1985eaab4411782a24199765 | AlexSchumi/Algorithms | /binary_search/35.search_insert_position2.py | 912 | 3.765625 | 4 | class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target < nums[0] or not nums:
return 0
if target > nums[-1]: # if target is greater than the last element of nums
... |
77ee94000e4bfe9d197d5b037deddc8cf226acbb | AlexSchumi/Algorithms | /hash_table/36.Valid Sudoku.py | 3,518 | 3.890625 | 4 | class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
"""
First implementation of solving sudoku using brutal force, check every row and column and every small cube;
Time complexity: O(n^2)
Space complexity:... |
4ce77744b1921ee682c4be4bf7309cf3a481857d | AlexSchumi/Algorithms | /hash_table/76.minimum_window_substring.py | 2,301 | 3.59375 | 4 | import sys
class Solution:
def minWindow(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
if not s or not t: #if we do not have any of those two strings
return ""
if len(t) > len(s):
return ""
res = {}
min_len... |
57f34a15932db8efe921d7595cae9b787964a26f | hao1Lh/menuInPandas | /mainmenu.py | 5,383 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pandas as pd
#Import an Excel file and convert it to a pandas dataframe
xl = pd.ExcelFile("OSSalesData.xlsx")
lines = "="*25 + "\n"
#select a specific sheet
SalesData= xl.parse("Orders")
#function that show profit column
def SubCatProfit():#
#accessing data f... |
4878f9cf9893cb1804a851fd7fc0d1b3369d5e13 | ardeshirsaadat/adventure_game | /adventure_game.py | 3,424 | 3.921875 | 4 | import time
import random
def print_pause(msg, sec):
time.sleep(sec)
print(msg)
def fight(items):
print_pause("1.fight 2.run-away", 1)
choice = input()
if choice == "1" and "2" in items:
print_pause("you won", 1)
play_again(items)
elif choice == "2":
print_pause("you ... |
532b956b057b4824f66d7d27112d08e8d3a74176 | holmes1313/Cracking_the_Coding_Interview | /1_Array_and_Strings.py | 4,796 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 10 10:11:58 2019
@author: z.chen7
"""
# 1. Array and Strings
# Hash Tables
"""
A hash table is a data structure that maps keys to valus for highly efficient lookup.
Implementation (an array of linked lists and a hash code function)
1. compute the key's hash code
2. map ... |
3032c0458bf9d8c9d0f73d2bd3b7f47cd5c6e0b4 | GerardProsper/Intermediate-Python-Programming-Course | /Random Numbers.py | 1,634 | 3.609375 | 4 | import random
a = random.random() # generates a random float number between 0 and 1
print(a)
b = random.uniform(1, 10) # generates a float number between the 2 given inputs
print(b)
c = random.uniform(1, 20) # generates a float number between the 2 given inputs. Include upper bound
print(c)
d = random... |
8b4293e7bd7c490645188da8ccd676d0da4a97e4 | GerardProsper/Intermediate-Python-Programming-Course | /Function Arguments.py | 3,045 | 3.765625 | 4 |
# difference between arguements and parameters
def print_name(name): # name here is parameter
print(name)
print_name('Gerard') # Gerard here is arguments
def fool(a,b,c):
print(a,b,c)
fool(1,2,3)
fool(a=1,c=3,b=2) # this is keyword arguments. order doesnt matter
fool(2, b=3, c=5) # this would ... |
76189b3c5a77bb13f40751f143527c495032f6e9 | GerardProsper/Intermediate-Python-Programming-Course | /Sets.py | 2,414 | 4.15625 | 4 | # #Sets:unordered, mutable, no duplicates
#
# myset = {1,2,3,1,2}
# print(myset)
#
# myset2 = set("Hello")
# print(myset2)
#
# myset3 = {} #this is a dictionary and not a set
# print(myset3)
# print(type(myset3))
#
# myset4 = set() #this is a set
# print(myset4)
# print(type(myset4))
# myset4.add(3)
# m... |
4e3f7d9b80b91af9ee030d52fa81470d3aee3ddf | yveso/ProjectEuler | /0001-0100/0001-0020/0002/0002.py | 234 | 3.625 | 4 | def fibonacci_numbers():
x, y = 1, 2
while True:
yield x
x, y = y, x + y
answer = 0
for fib in fibonacci_numbers():
if fib % 2 == 0:
answer += fib
if fib > 4000000:
break
print(answer) |
b711b198c80ffcb01d7950c2d9511d0250bc89e2 | feoh/WeeklyPythonExercises | /01/wpe01_solution.py | 788 | 3.765625 | 4 | from collections import Counter, defaultdict
visits = defaultdict(Counter)
def collect_places():
visits.clear()
while True:
city_country = input("Tell me where you went: ")
if not city_country:
break
try:
(city, country) = city_country.split(', ')
vi... |
d1f8ec281e192d59bd2837a14383da844d5c2a62 | furkanozturk98/AI-PROJECT | /backtrack.py | 1,204 | 3.625 | 4 | from heuristics import select_unassigned_variable, order_domain_values
from utils import is_consistent, assign, unassign
"""
Backtracking Algorithm
pseudo code found @ https://sandipanweb.files.wordpress.com/2017/03/im31.png
"""
def recursive_backtrack_algorithm(assignment, sudoku):
# if assignment is complete th... |
5969c938fd76af7a4375bf8c42274c4325313cb6 | burkt4/PRProject2020 | /task3/features.py | 2,876 | 3.609375 | 4 | '''
Make sure to have a "words" folder in your working directory
This Program output a collection of picture of words: xxx-xx-xx.jpg where the xxx-xx-xx is the id of the word represented the image.
Each of this picture is a portion of an original handwritten scanned page.
The the program transform those words images... |
f9f8ec0213aecf8697156f249321cda3b1125436 | burkt4/PRProject2020 | /2c/utils.py | 5,357 | 4.1875 | 4 |
"""
In this file, we build two classes : the MLP and the OurDataset class.
There is also a function train_model which we use to train our model
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset
import numpy as np
class MLP(nn.Module):
"""
This class ... |
16dae6b32780f2ba32c9fa19efcc7efc06fbefed | liza-panineyeva/Mathematical-models-simulation-and-Computer-Control-System-with-python | /simulations/uklad_lorentza.py | 2,041 | 3.5 | 4 | import matplotlib.pyplot as plt
import numpy as np
import mpl_toolkits.mplot3d.axes3d as ax3d
import random
import matplotlib.animation as animation
from matplotlib import cm
#układ lorentza 2d i 3d
def euler(x0,y0,z0,T,h):
t=0
time = []
x=[]
y=[]
z = []
while t<=T:
time.append(t)
... |
a7bd68f593c7015d2231c31a28a2facd43e1703d | MrLW/algorithm | /05_doublepoint/middle_75_sortColors.py | 1,674 | 3.53125 | 4 | from typing import List
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
75. 颜色分类:
给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
"""
# 双指针
i, p0, p2 = 0, 0, len(nums)-1
... |
36fe94a832483e1208f13ab1a5f8063ecf05a14a | MrLW/algorithm | /07_tree/middle_105_buildTree.py | 995 | 3.859375 | 4 | # Definition for a binary tree node.
from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
index =... |
d75adc0c8b795594af133de1e49e9f88466b60dc | MrLW/algorithm | /leetcode/everyday/middle_82_deleteDuplicates.py | 2,077 | 3.71875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
'''
思路1:
1. 先用一个for循环记录每个元素出现的个数
2. 再遍历链表, 删除出现个数大于1的元素
... |
c51da86443c0a52fd3f54f69dfe84b0c83e70b04 | MrLW/algorithm | /leetcode/everyday/easy_88_merge.py | 1,544 | 3.734375 | 4 | from typing import List
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
'''
88. 合并两个有序数组
'''
# 2. 原地排序
k = m + n - 1
while m > 0 and... |
17d8382c47bd1a30ed4c624bf28f7ea52b23d1ce | MrLW/algorithm | /leetcode/everyday/easy_83_deleteDuplicates.py | 833 | 3.671875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
res = ListNode(1, head)
cur = res.next
pre = res
while cur is not Non... |
ae5e9f375ca8f39e97f0470614f8a2599b01105c | jgreen44/ASU-IFT101-Lab_03 | /Lab 3.py | 1,366 | 4.40625 | 4 | # Filename: Lab 3
# Created by: jasongreen
# Date: Monday, January 21, 2019
# Time of Creation: 11:48
# ---
# find the average of three numbers
number1 = int(input("Please enter a number: "))
number2 = int(input("Please enter another number: "))
number3 = int(input("Please ... |
b2d286f1713db480a56fc90a5d958f0a49be2752 | georgehargreaves95/AutomateTheBoringStuff | /chap_2_flowcontrol/vampires.py | 1,921 | 4 | 4 | # This program demonstrates flow control, aka vampire
name = "Carol"
age = 3000
names = ["Alice", "Mary", "Frank", "James", "Mark", "Carol"]
ages = [10, 58, 42, 101, 50, 3000]
def vampire1(): # Working if/else tree
if name == "Alice":
print("Hi, Alice")
elif age < 12:
print("You're not Alice,... |
2ea2f45776f19837d33af43462ab4b3fd4c53ccb | georgehargreaves95/AutomateTheBoringStuff | /chap_2_flowcontrol/swordfish.py | 648 | 3.8125 | 4 | # While statement demo
import sys
def demo1():
while True:
print("Who are you?")
name = input()
if name != "Joe":
continue
print("Hello, Joe. What's the password?")
password = input()
if password == "swordfish":
break
print("Access grante... |
9b4260e98a8882923548b31039d137038750e6ca | koksyncho/qa-automation-with-python-selenium-101-follow-along | /module03/solution.py | 2,484 | 3.765625 | 4 | import math
def sum_of_digits(n):
digitSum = 0;
if n < 0:
n = n * (-1)
while n:
digitSum += n % 10
n = n // 10
return digitSum
def to_digits(n):
digitList = []
while n:
digitList.append(n % 10)
n = n // 10
return list(reversed(digitLi... |
1d35c912bfdf573347785fbb7332f67d800deac0 | mohammadabdlkarim/checkers-pygame | /checkers/Game.py | 3,367 | 3.5 | 4 | import pygame
from .constants import WHITE, BLACK, winner_font, WIDTH, HEIGHT
class Game:
def __init__(self, board):
self._init(board)
def _init(self, board):
self.board = board
self.selected = None
self.turn = WHITE
self.last_played = BLACK
self.last_piece_move... |
1bed5e4e9dd069b53e61e44eeffe45bbab2a0a6e | Alondra-Mishel-Otero-Mendoza/Alondra-Mishel-Otero-Mendoza-poo-1720110351 | /Semana3/Ejercicio 1.py | 924 | 3.984375 | 4 | class Estudiante():
def __init__(self):
pass
def clase(self):
while True:
materia = input("Materia: ")
numeroAlumnos = int(input("Número de alumnos: "))
nombreAlumno=input("nombre Alumno:")
numeroClases=int(input("numero de Clases:"))
numeroRetardos=int(input("numero de Retrasos"))
... |
60226e7ab81f581a339e85bb61b18a0cb8913c86 | AkilaMihiranga123/IdentifyHeartAttack | /ActualHeartAttackIdentificationModel.py | 2,855 | 3.53125 | 4 | # Import required libraries
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Load and save the data into variable
df = pd.read_csv('heart.csv')
# Print the data
df.head()
# Get data types
df.dtypes
# Get the shape of the data
df.shape
# Removing columns
list_drop = ['c... |
2a4c1363ec0c02e99e14260d56877a197e6ad4b4 | git-chinmay/myML | /UdemyPractice/18-DeepLearning/CNN/cnn.py | 3,637 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Convolutinal Neuralnetworks
Dataset Details:-
We have 10000 photos of dogs and cats
out of 10k , we split 8k for train and 2k for test sets
Out of 8k , we have 4k each for DOg and Cat similarly in test out of 2k we have
1k each for Dog and Cat.
So above split is our data preprocessing.We d... |
ec8ee2de8eb2ca6e8a034b1bbf561932f9db529a | git-chinmay/myML | /DeepLearning/NeuralNet/Practice/P4.py | 1,519 | 3.703125 | 4 | """
Making NN more generic with Class objects
Making batches we can run in parallel many batches using GPUs.
Input will be list of lists
We will create Multilayer Neural Network
"""
import numpy as np
# First Layer Neuron
X_input = [[1.0, 2.0, 3.0, 2.5], [2.0, 5.0, -1.0, 2.0], [-1.5, 2.7, 3.3, -0.8]]
weights1 = [[0.2... |
c2e2c8fe4075b981c720cb5fa549878fc4148401 | AleeWeb/python3-training | /variables.py | 153 | 3.65625 | 4 |
# Variables and Strings in PY 3
michael = "61 years old, 5'11 and is retired"
print (michael)
age = 31
print (age)
p3 = "This is Python 3"
print(p3) |
3ab21556ae1608f14d675a27141aea104887c1dc | WanYuLiao/Codewars-Python | /7kyu-Vowel Count.py | 650 | 3.984375 | 4 | """
Vowel Count
7kyu
Return the number (count) of vowels in the given string.
We will consider a, e, i, o, u as vowels for this Kata (but not y).
The input string will only consist of lower case letters and/or spaces.
"""
# Version 1
def get_count(input_str):
num_vowels = 0
string = list(input_str)
for ... |
07fdc0833584c253ea3b2b3105e05fc766efa129 | calstatelaacm/lets_learn_python_with_pygame | /pygame/8 Image Follows Mouse & Collision Detection/image_follows_mouse_and_collision_detection.py | 3,885 | 3.59375 | 4 | import pygame
from pygame.locals import *
import random
import sys
def main():
pygame.init()
RED = pygame.Color(255, 0, 0)
screen_size = (0, 0)
screen = pygame.display.set_mode(screen_size)
clock = pygame.time.Clock()
FPS = 60
# create the sprite lists
block_list = pygame.sprite.Gro... |
71fcd616d5947344064b31c0909b6c8f11c925d9 | 1127378627/IKBT | /b3/core/blackboard.py | 1,692 | 3.65625 | 4 | __all__ = ['Blackboard']
class Blackboard(object):
def __init__(self):
self._base_memory = {}
self._tree_memory = {}
self.set('TotalCost', 0)
def _get_tree_memory(self, tree_scope):
if (tree_scope not in self._tree_memory):
self._tree_memory[tree_scope] = {
... |
dd66b2f6e430640a4372e7ad5a79adda48ce75ec | josemgoujat/adventofcode2019 | /day-1/day-1.py | 652 | 3.71875 | 4 | """
https://adventofcode.com/2019/day/1
"""
with open('day-1.input', 'r') as input_f:
modules_mass = [int(line) for line in input_f.read().splitlines()]
# Star 1
def simple_fuel_calculator(mass):
return mass // 3 - 2
answer_1 = sum(map(simple_fuel_calculator, modules_mass))
print(f'Answer 1: {answer_1}')
... |
68c325b35bfbc9f26ea35dbf25bc3f50f4ae85f0 | Hvs911/CODE2RACE | /SOLUTIONS/Armstrong.py | 185 | 4.09375 | 4 | Num = int(input("Enter a number = "))
temp = Num
arm = 0
while(temp):
arm += (temp%10)**3
temp//=10
if(arm == Num): print(Num, "is Armstrong")
else: print(Num, "is NOT Armstrong")
|
673d949a1fdda264862e1abfea9e15432057beb5 | Hvs911/CODE2RACE | /SOLUTIONS/fibonacci3.py | 97 | 3.71875 | 4 | a=0
b=1
print a
print b
i=3
while i<=n:
c=a+b
print c
a=b
b=c
i=i+1
fibonacii(10)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.