blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
84f3ddd7342143271b182ee05cbb4efebc3238ca
jing1988a/python_fb
/好咧,最后还是要搞google/medium/KnightProbabilityinChessboard688.py
2,045
3.875
4
# On an NxN chessboard, a knight starts at the r-th row and c-th column and attempts to make exactly K moves. The rows and columns are 0 indexed, so the top-left square is (0, 0), and the bottom-right square is (N-1, N-1). # # A chess knight has 8 possible moves it can make, as illustrated below. Each move is two squar...
8b2b75dee2673888cbd68c771d6e9341ace83822
jing1988a/python_fb
/fb/LowestCommonAncestorIII578.py
1,214
3.828125
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): this.val = val this.left, this.right = None, None """ class Solution: """ @param: root: The root of the binary tree. @param: A: A TreeNode @param: B: A TreeNode @return: Return the LCA of the two nodes. ""...
247dbaca0f1a51ef074090f65357870a673aa2c9
jing1988a/python_fb
/lintcode_recent/LeftmostOne898.py
1,366
4.0625
4
# Given a 2D array, and each line has only 0 and 1, the front part is 0, and the latter part is 1. Find the number of columns in the leftmost 1 of all the rows in the array. # # Example # Given arr = [[0,0,0,1],[1,1,1,1]], return 0. # # Explanation: # Arr[1][0] is the leftmost 1 in all rows and its column is 0. # Given...
2cfe7c91405ec313dfed83e864bf6e18f5d8e276
jing1988a/python_fb
/900plus/FractionAdditionandSubtraction592.py
2,718
4.1875
4
# Given a string representing an expression of fraction addition and subtraction, you need to return the calculation result in string format. The final result should be irreducible fraction. If your final result is an integer, say 2, you need to change it to the format of fraction that has denominator 1. So in this cas...
0ab4d00ee5ea5f4fba43186a6904a5f4b2b69400
jing1988a/python_fb
/900plus/OnlineElection911.py
2,725
3.90625
4
# In an election, the i-th vote was cast for persons[i] at time times[i]. # # Now, we would like to implement the following query function: TopVotedCandidate.q(int t) will return the number of the person that was leading the election at time t. # # Votes cast at time t will count towards our query. In the case of a ti...
3eb77067ef5abfc83a618e8ec8ad1899c9f1a5c2
jing1988a/python_fb
/好咧,最后还是要搞google/medium/GroupShiftedStrings249.py
1,288
3.984375
4
# Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence: # # "abc" -> "bcd" -> ... -> "xyz" # Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence. #...
40aaf7fe83032a9f0eeff2fce24c03d8247650c9
jing1988a/python_fb
/amazon/MinimumDifference1566.py
1,178
3.9375
4
# Given a 2D array size of n * m and the elements of each row of the array are sorted. Select 1 number from each row and select n numbers in total. And the diff of n numbers is maximum-minimum, find the minimum diff. # # Example # Input: [[1,2,3,4,5],[6,7,8,9,10]] # Output: 1 import sys import heapq class Solution: ...
fe4c283e5949db75a7355f5ae079056504f8a432
jing1988a/python_fb
/dropbox/taskDelay_mianjing.py
745
3.84375
4
# 2: Coding. 多线程题目。 具体忘记了, 实现一个方法, def(Task task, long dealy) task 是个interface, 有个action()方法。 用户端用调用def方法, 然后task将会在延迟后执行。里面涉及到lock, condition, notify,wait之类,小伙伴要是去面Dropbox就多看看多线程相关吧。 import threading import time def task(): print('task at: '+time.strftime("%b %d %Y %H:%M:%S")) class delayDo: def do(self ,...
ab51b2c2db68485fe2c71f856dbf00559eb8be92
jing1988a/python_fb
/amazon/UniqueSubstring1481.py
1,237
3.765625
4
# Description # Given a string s, find all the unique substring with the length of k and sort the results in lexicographic order. # # Have you met this question in a real interview? # Example # Input: s = "caaab" # k = 2 # Output:["aa","ab","ca"] class Solution: """ @param s: a string @param k: an integer ...
41fcfb392f87df48f830138322fdcf8b38ed183c
jing1988a/python_fb
/test.py
1,425
3.71875
4
# import heapq # class Solution: # """ # @param lists: a list of ListNode # @return: The head of one sorted list. # """ # def mergeKLists(self, lists): # # write your code here # hq=[] # for l in lists: # if l: # heapq.heappush(hq , [l.val , l ]) #...
1d6687262b17a34a75fc642547e7811146fd08a5
jing1988a/python_fb
/dropbox/conditionTest.py
2,493
3.6875
4
# threading.Condition # 可以把Condition理解为一把高级的琐,它提供了比Lock, RLock更高级的功能,允许我们能够控制复杂的线程同步问题。threadiong.Condition在内部维护一个琐对象(默认是RLock),可以在创建Condigtion对象的时候把琐对象作为参数传入。Condition也提供了acquire, release方法,其含义与琐的acquire, release方法一致,其实它只是简单的调用内部琐对象的对应的方法而已。Condition还提供了如下方法(特别要注意:这些方法只有在占用琐(acquire)之后才能调用,否则将会报RuntimeError异常。): # # C...
6c34ac7a3d3602f6d8491e50c3510b469e5af57d
jing1988a/python_fb
/fb/MaximumGap400.py
317
3.5625
4
class Solution: """ @param nums: an array of integers @return: the maximun difference """ def maximumGap(self, nums): # write your code here nums.sort() ans=0 l=len(nums) for i in range(1 , l): ans=max(ans , nums[i]-nums[i-1]) return ans
eac954524d7faedfb518f256fccf45047f611805
jing1988a/python_fb
/amazon/amazon_oa/zeroToNine.py
1,804
3.578125
4
# 第二题 二维图从[0,0] 出发,0表示点不能去,1 表示能去,找去目标点的最短路径,常规bfs class Problem: def solve(self, matrix, end): n = len(matrix) if n == 0: return [] m = len(matrix[0]) if m == 0: return [] candidate = [] visited = [[False for _ in range(m)] for _ in range(n)...
9e401932e193268fa5fbf02d35a88fafd70a00c6
jing1988a/python_fb
/fb/LargestPlusSign1044.py
843
3.578125
4
class Solution: """ @param N: size of 2D grid @param mines: in the given list @return: the order of the plus sign """ def orderOfLargestPlusSign(self, N, mines): # Write your code here graph = self.getGraph(N, mines) leftMost = self.getLeft(N, graph) topMost = se...
df123d3897a57a1a7230cc34499cb9391a419e8b
jing1988a/python_fb
/amazon_leetcode/PartitionLabels763.py
1,310
4.09375
4
# A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts. # # Example 1: # Input: S = "ababcbacadefegdehijhklij" # Output: [9,7,8] # Explanation: # The p...
f85017e6f9373210b1861c03ea0c2c742b4944bc
jing1988a/python_fb
/amazon_leetcode/BinaryTreeLongestConsecutiveSequence298.py
1,688
4.0625
4
# Given a binary tree, find the length of the longest consecutive sequence path. # # The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse). # # Example 1: # # Input...
4d7006c60a8c19fa21308516953152edc3ef1e72
jing1988a/python_fb
/fb/RecoverBinarySearchTree691.py
799
4.03125
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: the given tree @return: the tree after swapping """ a=None b=None pre=None def bstSwappedNode(self, root): ...
2f2d8b64092b52b3450206b30db72815785a0d3d
jing1988a/python_fb
/好咧,最后还是要搞google/medium/SwapAdjacentinLRString777_TLE.py
1,657
3.953125
4
# In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given the starting string start and the ending string end, return True if and only if there exists a sequence of moves to transfo...
3a0515818904adf2b688c28013bc3937abb70ccd
jing1988a/python_fb
/lintcode_lyft/ReadNCharactersGivenRead4IICallmultipletimes660.py
1,709
3.796875
4
# The API: int read4(char *buf) reads 4 characters at a time from a file. # # The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file. # # By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the...
15180647e2d3432555fc88f4780e87c176aee704
jing1988a/python_fb
/fb/CombinationSumIV564.py
563
3.5625
4
class Solution: """ @param nums: an integer array and all positive numbers, no duplicates @param target: An integer @return: An integer """ def backPackVI(self, nums, target): # write your code here # is [1 , 2 , 1] and [1 , 1, 2] count as different? # assume diffrernt ...
293ee950a17a5a4999145ce76e05b2b4c42e6521
jing1988a/python_fb
/amazon/maxFreqStr1484.py
1,392
3.90625
4
# 给你一个String (I am Jack and my father is Jimmy. I like wearing Jack and Jone's. ), 一个exclude list, 让你给出出现频率最高或者并列高的词(不Case sensitive, Jack和jack算一个词,都出现的话等于算jack出现两次). (而不是大家之前说的给一个k,然后求出出现频率最高的k个), 比如Jack和Jone都是频率最高且出现三次,那么return [Jack, Jone]。 # 24/25 case # 给你一个字符串, 一个排除的清单, 让你给出出现频率最高或者并列高的词,这里要注意大小写。很多人的是不区分,但是我这里...
277cda1e6a6fa735dcfa304ae30cb4008a00afee
jing1988a/python_fb
/好咧,最后还是要搞google/medium/SentenceSimilarityII737.py
2,294
3.96875
4
# Given two sentences words1, words2 (each represented as an array of strings), and a list of similar word pairs pairs, determine if two sentences are similar. # # For example, words1 = ["great", "acting", "skills"] and words2 = ["fine", "drama", "talent"] are similar, if the similar word pairs are pairs = [["great", "...
1e4e214385a54a8e225977e90172fe154dd2300a
jing1988a/python_fb
/lintcode_lyft/ReverseInteger413.py
558
4.125
4
# Reverse digits of an integer. Returns 0 when the reversed integer overflows (signed 32-bit integer). # # Example # Given x = 123, return 321 # # Given x = -123, return -321 class Solution: """ @param n: the integer to be reversed @return: the reversed integer """ def reverseInteger(self, n): ...
444f622e84d7d9f948afbfef911e18b56c5c73cc
jing1988a/python_fb
/lintcode_lyft/SwapNodesinPairs451.py
1,033
4
4
# Given a linked list, swap every two adjacent nodes and return its head. # # Example # Given 1->2->3->4, you should return the list as 2->1->4->3. # # Challenge # Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. # """ Definition of ListNode cl...
8167e0b56f5d564e5fa2cc854690dc230018a8f6
jing1988a/python_fb
/amazon/MinimumSumPath1482.py
833
3.921875
4
# Given a BST, find the path with the minimum sum from root to leaves. # # Example # Input:{5,2,6,#,3,#,8} # Output:10 # # """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ import sys class Solution: """ @param root:...
97fa1da88930ba48ae1aa8c6def68a64d84a1412
jing1988a/python_fb
/dropbox/gameofLife289.py
3,250
4.09375
4
# According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." # # Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizont...
7693a4aed94fcb15ba63630472426f093ef5fd24
jing1988a/python_fb
/fb/Powxn428.py
464
3.625
4
class Solution: """ @param x: the base number @param n: the power number @return: the result """ def myPow(self, x, n): # write your code here if x==0: return 0 if n<0: return 1.0/self.myPow(x , -n) if n==0: return 1 tem...
37cfc2c29c28c0739d3855e7576f3983751ccfd5
jing1988a/python_fb
/fb/RearrangeaStringWithIntegers720.py
520
3.65625
4
class Solution: """ @param str: a string containing uppercase alphabets and integer digits @return: the alphabets in the order followed by the sum of digits """ def rearrange(self, s): # Write your code here s=list(s) s.sort() i=0 l=len(s) if l==0: ...
f8aef6ac6c5f8838b8fed96f3f36437c6560a423
Almr1209/idk
/ex32.py
1,001
4.59375
5
the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # this first kind of for-loop goes through a loop for number in the_count: print(f"This is count {number}") # same as above, basically it's using the same format but different var...
d77a26b6e8dc614c8d2a64a49cb7890648dfae74
alexsincai/sayer-of-things-discord-bot
/file_handler.py
705
3.5
4
HEADERS = ["author", "quote"] def read_from_file(): from csv import DictReader with open("quotes.csv", "r") as file: return [r for r in DictReader(f=file, fieldnames=HEADERS)] def write_to_file(name, text): from csv import DictWriter current = ensure_uniq([*read_from_file(), {"author": nam...
ddca4e021440a36032874123a1c858db579cf7f8
ml4713/final_project
/ml4713/data_visual/analysis_visual.py
6,263
3.59375
4
# -*- coding: utf-8 -*- """Visual Data functions defines feature_category class to functions to perform necessary analysis Author: Mengfei Li (ml4713) """ __all__ = ['feature_category', 'input_validation', 'plot_function', 'prompt_for_subcategory', 'subcategory_validation', 'add_subcategory_for_plot'] import re im...
b41fbb60e07f5cb2b409e04fb2fe54e997f4003f
Anthonymcqueen21/Daily-Python-Practice
/Python Toolbox/mean.py
261
3.921875
4
def mean(*x): """Returns the mean of all the numbers""" total_sum = 0 # Initial sum n = len(x) # Number of arguments for i in x: total_sum = total_sum + i return total_sum/n print((mean(4,5), mean(30,35,40))) output: (4.5, 35.00)
f47197d1d5cff82bcaad878af87c7e4c9d8bf9e8
Anthonymcqueen21/Daily-Python-Practice
/Python Toolbox/count_digits.py
125
3.96875
4
def count_digits(z): """Prints the number of digits in an integer""" print(len(str(z))) count_digits(697) output: 3
cd5f5394f66ccab0fa5f78b9474367c845c033b0
Mauriciofrias22/PYTHON_CODE_CHALLENGES_CONTROL_FLOW
/large_power.py
358
4.03125
4
#function that takes two parameters named base and exponent. #If base raised to the exponent is greater than 5000, return True, #otherwise it returns False def large_power(base, exponent): if base ** exponent > 5000: return True else: return False print(large_power (2, 13)) # should print True print(larg...
31e75b3f512d1a8d65c54fb6608f6fa6d3db720c
Xiaoctw/leetCode_python
/quadratic.py
982
3.703125
4
import math import cmath import sys def get_float(msg,allow_zero): while True: x=input(msg) if x: try: x=int(x) if not allow_zero and abs(x)<sys.float_info.epsilon: print("Zero is not allowed") x=None ...
9d9363c197d2035b4e23bc70551b3444271f6f76
Xiaoctw/leetCode_python
/命名的元组.py
456
3.796875
4
import collections Sales=collections.namedtuple("Sales","productid customerid date quantity price") sales=[] sales.append(Sales("001", 1, "2017-4-2", "good", 500)) sales.append(Sales("002",2,"2017-4-5","well",400)) total=0 for sale in sales: total+=sale.price**2 #print("{0.productid} and {1.productid} total prices ...
a6ec7fbff14b620d8f2f7d227ac5818d82032892
Gustana/py-challenges
/learn/triangle.py
355
4.3125
4
height = int(input("Insert height :")) #5 # * # * * # * * * # * * * * # * * * * * # * * * * * * limit = 1 while (limit<=height) : star = limit space = height while (space >= limit) : print(" ", end="") space-=1 while (star >= 1) : print("* ", end="") s...
1aea79ec2f8f3198109ebadb6a20ad5e222c0aea
Gustana/py-challenges
/reverse_string.py
101
4.5
4
#This program will inverse a string word = input("Insert a word : ") print ("".join(reversed(word)))
7fe9e90664b0c333fa689783ba02c403ce6eecb1
SuperOzi01/GeneralSamples
/Python101.py
2,275
4.0625
4
Names = ['Amal','Mohammed','Khadijah','Abullah','Rawan','Faisal','Layla'] Numbers = ['1111111111','2222222222','3333333333','4444444444','5555555555','6666666666','7777777777'] PhoneBook = [] def main(): InitialData() MainProgram() return True def InitialData(): for i in range(len(Names)): ...
f7d8aeb63190f98f4e2b268a900fdd0dda81a2d6
Tobijoe/LPTHW
/ex15.py
645
3.984375
4
#from sys import argv argument from sys import argv #add arguments to argv, in this case script name (ex15.py)and the text sample (ex15sample.txt) script, filename = argv #set var txt to open filename given in argument txt = open(filename) #print formatted string, with filename print(f"Here is your file {filename}") #...
9cb5b8724dd26c2576326e513a26628010a279c6
sivolko/codeforce
/Twilio Software Engineer - New Grad-Part-2/missingWords.py
591
3.890625
4
# # Complete the 'missingWords' function below. # # The function is expected to return a STRING_ARRAY. # The function accepts following parameters: # 1. STRING s # 2. STRING t # def missingWords(s, t): # Write your code here s_list = s.split() t_list = t.split() missing = [] i = j = 0 while ...
10755c22729240201a8b9bc5e5d92687e6e3aa0a
sivolko/codeforce
/Workday Senior Java Platform Developer/degreeOfArray.py
735
3.546875
4
# # Complete the 'degreeOfArray' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER_ARRAY arr as parameter. # from collections import Counter, defaultdict def degreeOfArray(arr): # Write your code here maxDeg = 0 num2count = defaultdict(int) firstSeen = {...
f6e0956317b8176858135152d4e1b95886101fbb
sivolko/codeforce
/VISA Senior Software Engineer 2019/Round - 3 - Onsite/Design Elevator/elevator.py
1,284
3.71875
4
from collections import deque class Elevator(object): def __init__(self): self.cf = 0 # current floor self.dirc = "NULL" self.req = deque([]) self.reqSet = set([]) def in_cmg_req(self, floor): self.req.append(floor) self.reqSet.add(floor) def process(self)...
6ca93d9a5fd4ab3654186883a427d7aa0bc02515
Valery-Bolshakov/learning
/theory/lesson_6.py
1,159
4.15625
4
print('Переменные\n') a = 1 # создали переменную х и присвоили ей значение 1 y = 3 # int u = 3.5 # float my_var1 = 15 # определить тип переменной: print('задали перменную класса - ', type(y)) print('задали перменную класса - ', type(u)) # Переменные являются регистрозависимыми: x = 13 X = 14 print(x, X) ''' Псе...
ff65e7e17ffdbd9fedc19810c8e1e5be922e09f8
Valery-Bolshakov/learning
/theory/lesson_13.py
3,564
4.21875
4
print('Циклы For и While\n') ''' Инструкция, позволяющая повторять цикл пока выполняется определённое условие. do = True while do: print('делаем') do = False print('делаем') else: print('закончили') # делаем # делаем # закончили На каждом витке цикла условие, заданное при помощи выражения идущего...
23893617a48dd1ba50dc04ee173656d3536fe8de
Valery-Bolshakov/learning
/theory/lesson_21.py
2,675
4.03125
4
""" HomeWork: Task 1 Дан список words. Составьте из него список слов-палиндромов. Попробуйте это сделать двумя способами: произвольное решение и решение в одну строчку кода. """ words = ['мадам', 'топот', 'test', 'madam', 'word'] new_word = [] for i in words: if i == i[::-1]: new_word.append(i) print(f'За...
25b74f5d0e91b4427586bbb6b3ad584977e71cbf
Valery-Bolshakov/learning
/theory/lesson_29.py
3,837
4.1875
4
print('Homework\n') """ 1. Дан массив, в котором среди прочих элементов есть слово "odd" (нечетный). Определите, есть ли в списке число, которое равно индексу элемента "odd". Напишите функцию, которая будет возвращать True или False, соответсвенно. """ my_list_1 = ["even", 4, "even", 7, "even", 55, "even", 6, "even"...
deefdf022e8fe03e6d4c9c8f21f1a0a8a12ecb4a
LMlmptm/python
/我要自学网/python初学者1.py
807
3.640625
4
#-*- coding:utf-8 -*- # def f1(a): # print(a,"你好啊") # # f1("a") # def f(a,b,c): # e=a+b+c # # print(e) # return e # add=f(2,4,5) # print(add) # def a(cm,cl,ck): # print("你来吧") # print("我不来") # print(cm,"不来",cl,"来",ck,"可能吧") # c=cm+cl+ck # return c # l=a("li","man","shuaige") # print(l...
f0586916bdba18bba358a93f0b7185764910d585
LMlmptm/python
/我要自学网/爬虫10.py
2,128
3.765625
4
#-*- coding:utf-8 -*- # import threading # import time # def run(name): # print(name,"执行了") # # t1=threading.Thread(target=run,args=("t1",)) # t2=threading.Thread(target=run,args=("t2",)) # t1.start() # t2.start() # t1.join() # t2.join() # time.sleep(3) # print("执行完毕") # lock=threading.Lock() # class mythread(threa...
d7c5d178fefb1feaffce85a4b6c30d01b8bdfa2c
LMlmptm/python
/我要自学网/python初学者6.py
1,598
3.625
4
#-*- coding:utf-8 -*- # import threading # import time # def run(name): # print("线程呗至新浪:",name) # time.sleep(5) # #创建线程 # a=threading.Thread(target=run,args=("a",)) # b=threading.Thread(target=run,args=("b",)) # time.sleep(3) # a.start()#线程开始 # b.start() # a.join()#子线程结束后才执行主线程 # b.join() # import threading # ...
b64d64f1495f59bff756a84611a82f68c4400318
agrawalayan/Artificial-Intelligence
/BFS & DFS/bfs_dfs.py
3,927
3.9375
4
import sys # BFS - Breadth First Algorithm # DFS - Depth First Algorithm print "Inplementing Breadth First Algorithm & Depth First Algorithm - Puzzle 8" #incr_list =[] goal_state = [0,1,2,3,4,5,6,7,8] def puzzle_8_step(state): for i in range(0,9,3): print "-------------" print "|", state[i], "|", s...
fad0cc88b1da6e8c6a96e843319c33b29cc98ea5
johnnysaldana/python_practice_exercises
/interesttable.py
340
3.75
4
# interesttable.py principle = float(input("Enter starting amount: ")) rate = float(input("Enter interest rate: ")) time = float(input("Enter time: ")) def compound(p, r, t): p * (1.0 + r) ** t def main(): for i in range(int(time)): print(compound(principle, rate, i)) i += 1 print(compound(princ...
2f288e1aaacdf76bbb9589d225650e76412a070c
johnnysaldana/python_practice_exercises
/mysqrt.py
378
3.828125
4
# mysqrt.py def mysqrt(n): guess = n // 2 i = 1 while i < 30: guess = (guess + (n / guess)) / 2 i += 1 return guess print(guess) def main(): print("Welcome to the Square Root Approximator!") number = float(input("Enter a number: ")) print("The square root of", number, " is", mysqrt(number...
b5c303d6c01d4c2ba0502f9b1de61e95f6e5e0b4
johnnysaldana/python_practice_exercises
/isEven.py
160
3.796875
4
# isEven def isEven(x): if x % 2 == 0: return True else: return False def main(): k = int(input("Enter Int")) print(isEven(k)) main()
ef91bbc597ececbf17f15adc86449659304e7999
TewariUtkarsh/Library-Management-Using-Python
/Library Management.py
2,267
3.765625
4
from os import system class lib: def __init__(self, name): self.name = name self.books = {} def DisplayBooks(self): print("\nBooks Available:\n") if(len(self.books) == 0): print("NONE") else: x = 1 for i...
42ce539048e71bd9245ac1188d3408dd18d5afbc
elminson/python_developer_hiring_test
/q3.py
1,879
3.6875
4
#!/usr/bin/env python def findPreLength(subStr, prefix): maximum = 0 i = 1 while i < (len(subStr) + 1): length = 0 j = len(prefix) - 1 string = subStr[0:i] k = len(string) - 1 while j >= 0 and k >= 0: if string[k] == prefix[j]: length +=...
1dcc811dee1a6d279bc8c6ba3133dceb11372e5b
elminson/python_developer_hiring_test
/q10.py
301
3.828125
4
#!/usr/bin/env python def maxMoney(n, k): sum = 0 i = 0 while i <= n: sum += i if (sum == k): sum = sum - 1 i += 1 return sum def main(): n = int(input()) k = int(input()) print maxMoney(n, k) if __name__ == '__main__': main()
25530afeebc8665a575549e2355dbd8a461974c1
UTMUniverStuff/university_labs
/MMC_Python_Labs/lab4/code/ex1_2.py
470
3.875
4
from my_interpolate import my_interpolate from math import pi import matplotlib.pyplot as plt from numpy import linspace x_range = linspace(-pi/2, pi, 200) # Ex1 x = (0, pi/2, pi) y = (0, 1, 0) f = my_interpolate(x, y) plt.plot(x_range, f(x_range), label = "quadratic") plt.plot(x, y, 'ro') # Ex2 x = (-pi/2, 0, pi/2...
76cecbbc9b4e5e5f07e809f5143b1f542bbb9473
UTMUniverStuff/university_labs
/APA_Catruc/lab4/code/tree_generator.py
315
3.609375
4
import random def tree_generator(size, nodeConnections): nodes = [x for x in range(size)] tree = [] for node in nodes: for i in range(nodeConnections): start = node end = random.choice([x for x in nodes if x != node]) length = random.randint(0, 100) tree.append([start, end, length]) return tree
4aea226321663ee6a5031aaccb9bbe133514347e
UTMUniverStuff/university_labs
/MMC_Python_Labs/lab1/ex01/main.py
1,706
3.671875
4
import fractions as fr import numpy as np import sys # We can't use np.sinh or np.cosh or np.e ** n, for huge numbers, because # the result becomes bigger than the float limit. That's why, we're using # a continued fraction to determine the result, even though it's not perfectly # precisive # Sometimes we don't need s...
749f8d30edb64fefd9e6824fa86a82911625accf
McRishka/BelovMD_11-008_project
/game/fire.py
1,501
3.703125
4
def fire(pc_element): if pc_element < 9 and pc_element > 4: print('\n\n', "Вы выиграли!") if pc_element == 5: print("Компьютер выбрал бумагу") print("Бумага сгорела") elif pc_element == 6: print("Компьютер выбрал губку") print("Губка сгорела") ...
ff25f0eb2691585e62696e3d979000a91f3ea9e4
PankeshGupta/pynotes
/multithreaded.py
479
3.734375
4
from threading import Thread import time def timer(name,delay,repeat): print("the timer : ", name," started") while repeat>0: time.sleep(delay) print(name," : ",str(time.ctime(time.time()))) repeat-=1 print("timer : ",name,"completed") def Main(): t1 = Thread(target=timer,args=("...
37c6c1f49f2584d000551fd7c58dc60974151439
PankeshGupta/pynotes
/storing_adress.py
317
3.546875
4
class adress(): def __init__(self,country): self.country = country def route(self): print("directing to ur location.......") class friend(): def __init__(self,name,adress): self.name = name self.adress = adress if __name__=="main": main()
1db04fd146c0b2f1e59f1deda53a59c68beca376
baldingwizard/python-pygame-asteroids
/asteroids/testpygame.py
817
3.59375
4
import pygame pygame.init() screenwidth = 800 screenheight = 600 screen = pygame.display.set_mode((screenwidth,screenheight)) clock = pygame.time.Clock() # Initialize stuff (replace with your own code) frame = 0 circleheight = 400 # Main game loop while True: pygame.event.pump() keys = pygame.key.get_pre...
d44773e6c6874f64d5bebe5f8dc859d2ac3d2e04
aladagemre/misc
/academic/DataMining/clustering.py
14,675
3.859375
4
from math import sqrt class Data: def __init__(self, value): self.value = value def __sub__(self, other): if isinstance(other, Cluster): return other - self elif isinstance(other, Data): # Make sure they are the same type. assert type(self.va...
5386cb0ac1eb21838d98eba96ff8c61db3f78572
mkukar/EE554_Group_Project
/Algorithm.py
9,833
3.59375
4
# Algorithm.py import time, threading from Road import * import Constants class Algorithm(): # # # Constructor # # def __init__(self, timeConstraintIn): print("Created algorithm") self.timeConstraintFloat = timeConstraintIn # # # Variables # # timeConstraintFloat = 0.33 timerFinished = False # chan...
11cf5de4e5a8ee0e232496aae2d8bbac4ff9e800
rcpierce/Minesweeper
/src/UI.py
8,435
3.84375
4
""" Class UI handles the ins and outs of the User Interface including but not limited to the start of the program window, user input, and game loop. pydoc -w UI """ #This is the UI, it will handle the initial screen in which the User chooses the size of the board and number of mines import pygame from src.Gameboa...
ea7ecb36eb3b41d0195248d103d6311b158d47f4
shenwfeng/python-learning
/data_structures/stack/next.py
345
3.75
4
''' 找出序列中后面比当前数大的数,没有返回-1 ''' def printNGE(arr): for i in range(0,len(arr),1): next = -1 for j in range(i+1,len(arr),1): if arr[i]<arr[j]: next = arr[j] break print(str(arr[i]),'--',str(next)) arr = [11,8,9,13,21,3,5] printNGE(arr)
4d982a576a499f3f3886b2e7686850e5522ad039
WilfredoRTG/Automata
/Rege.py
1,435
3.78125
4
import re NUMEROS = [] def printSavedValues(): global NUMEROS if len(NUMEROS) == 0: return numbers = ''.join(NUMEROS) print(f'TOKEN TEXT: {numbers}') print(f'TOKEN LEXICAL CATEGORY: OPERAND') NUMEROS = [] def checkOperator(lexical_string): # Confirma si es un operado...
e5db03cd5cde605a6fda0837ae334bfb247d231f
sarahoeri/Giraffe
/window.py
1,229
4.15625
4
# Tuples...don't change like in lists even_numbers = (2, 4, 6, 8, 10, 12) print(even_numbers[5]) # Functions def sayhi(name, age) : print("Hello " + name + " you are " + age) sayhi("Nancy", "25") sayhi("Christine", "27") # Return Statement def square(num) : return num*num print(square(8)) def cube(num) : ...
2f93d955e9d885f554c1b919eff3d6a68c567a56
Ridwanullahi-code/Tkinter_Age_Calculator
/Tkinter_age_calculator.py
2,379
3.59375
4
from tkinter import* from PIL import ImageTk,Image import datetime date_now = datetime.date.today() year_now = int(date_now.year) root = Tk() root.geometry("400x550") root.resizable(width=NO, height=NO) root.title("Age Calculation") y_value = IntVar(value="") m_value = IntVar(value="") d_value = IntVar(value="") text...
9391c201f98ce42de5efc3c74cf6a32887901013
hyperskill/hs-test
/src/test/java/projects/python/coffee_machine/stage3/machine/coffee_machine.py
1,127
4.25
4
# Write your code here water_amount = int(input('Write how many ml of water the coffee machine has:')) milk_amount = int(input('Write how many ml of milk the coffee machine has:')) coffee_amount = int(input('Write how many grams of coffee beans the coffee machine has:')) N = int(water_amount / 200) if N > milk_amount /...
4902b9fcccb2b72820406a4a57f9fb0c275945a8
Jayden358/Python
/Cash Register.py
674
4.0625
4
#Jayden Williams #9/19 #Cash Register num_items = 100 cost_per_item = 3.75 tax_rate = .09 #calculate and store the sub total sub_total = num_items * cost_per_item #calculate the amount of tax and store result tax_amount = sub_total * tax_rate #calculate the total price and store amount total_price ...
cd3169ae553d5d12ef2554c50d5671e20fb6b302
Jayden358/Python
/alarm_clock.py
2,026
3.75
4
#Jayden Williams #9/19 #Alarm clock import time import calendar from tkinter import * from tkinter import ttk from tkinter import font import winsound h = 0 m = 0 s = 0 t = "am" def current_time(h,m,s,t): total_seconds = calendar.timegm(time.gmtime()) current_second = total_seconds%60 ...
1fef20a275363c124313b4f4f557c77aff9023f4
Jayden358/Python
/coin_flip.py
273
3.984375
4
#Jayden Williams #9/19 #coin flip import random def coin_flip(): coin = random.randint(1,2) if coin is 1: coin = coin.replace("1","heads") print(coin) else: coin = coin.replace("2","tails") print(coin) coin_flip()
666d9eefcf8b5b6a51707cb3ebb5eec84e6ca726
oguh43/bilicka
/Hugo Bohácsek/znamky.py
980
3.765625
4
class Student: def __init__(self, name: str, grades: list[int]) -> None: self.name = name self.grades = grades self.avg = sum(grades) / len(grades) self.prospech = self.getProspech() def getProspech(self) -> str: if self.avg < 1.5 and len(self.grades) != le...
d222af66745f6c00f413b701c8b545a34986c074
oguh43/bilicka
/Hugo Bohácsek/postupnost_cisel.py
213
3.859375
4
while True: if (inp:=int(input("Číslo? > "))) < 5: if inp == 0: print("Postupnosť bola dodržaná!") else: print("Postupnosť nebola dodržaná!") break
4b87956dd341d25cad6e768de188bf058e50ff03
oguh43/bilicka
/fml/frig_off.py
1,006
3.6875
4
from __future__ import annotations from random import randint def insert(source_str: str, insert_str: str, pos: int) -> str: return source_str[:pos] + insert_str + source_str[pos:] if input("(A)gressive || (S)ilent bypass?").lower() == "a": with open("manipulate.txt", "r", encoding="utf-8") as f: con...
3bc955fc1acf179ed150374497fdc11801517206
oguh43/bilicka
/straight.py
1,579
3.625
4
from random import randint, shuffle def winner(player_hand,ai_hand): player_hand = straight(player_hand) ai_hand = straight(ai_hand) if len(player_hand) == 0 and len(ai_hand) != 0: return "ai" elif len(player_hand) != 0 and len(ai_hand) == 0: return "you" elif len(player_hand) == 0 and len(ai_hand) == 0: re...
9e466c4b8e1d0a22ec10fead6102e2305e82ba5c
oguh43/bilicka
/Hugo Bohácsek/tabulenka.py
164
3.65625
4
a = [] b = [] for i in range(1,11): for j in range (1,11): b.append(i*j) a.append(b) b = [] print(a) a = [list(map(str,x)) for x in a]
8dad8d01baaea9b8872aedb7cef557d4ea28bc58
oguh43/bilicka
/Hugo Bohácsek/vylet.py
289
3.671875
4
nosnost = int(input("Nosnosť? > ")) veci = [] while True: item = int(input("Vec? > ")) if sum(veci) + item > nosnost: break veci.append(item) print(f"Dosiahnutá hmotnosť: {sum(veci)}/{nosnost}\nPočet vecí: {len(veci)}\nVeci: {', '.join(map(str,veci))}")
affb8d0b97889d983d5f7952bf4757270a8df56c
oguh43/bilicka
/Hugo Bohácsek/modelka.py
266
3.640625
4
vyska = int(input("Výška (cm)> ")) prsia = int(input("Prsia> ")) pas = int(input("Pás> ")) boky = int(input("Boky> ")) if vyska >= 175 and prsia == 90 and pas == 60 and boky == 90: print("Mňaminy") else: print(":(")
db97d4e8523274f872d81960f314b7017e5ddcc1
firefeifei/CodePool
/LeetCode/697 Degree of an Array.py
1,538
4.03125
4
#!/usr/bin/python3 """ Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums. Example 1: Input: [1, 2, 2, 3, ...
7c088efb8762dbc86d25015b5b7f402fed09f6f7
firefeifei/CodePool
/LeetCode/751 IP to CIDR.py
3,665
4.28125
4
#!/usr/bin/python3 """ Given a start IP address ip and a number of ips we need to cover n, return a representation of the range as a list (of smallest possible length) of CIDR blocks. A CIDR block is a string consisting of an IP, followed by a slash, and then the prefix length. For example: "123.45.67.89/20". That pre...
5b611212611e6694d74d243c6f7ebb777bc69c33
firefeifei/CodePool
/LeetCode/773 Sliding Puzzle.py
3,458
4.09375
4
#!/usr/bin/python3 """ On a 2x3 board, there are 5 tiles represented by the integers 1 through 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it. The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]]. Given a puzzle b...
b5d31895f2a434cc8d751f4cf6d4d7def1544248
firefeifei/CodePool
/fzutils/fzutils/algorithm_utils.py
5,715
3.921875
4
# coding:utf-8 """ 算法utils """ from random import shuffle __all__ = [ 'bubble_sort', # 冒泡排序法 'insertion_sort', # 插入排序法 'selection_sort', # 选择排序法 'quick_sort', # 快速排序法 'bogo_sort', ...
be7f66d6d135d44c714a5e006cb5bd109cc896e7
RSavitskiy/Git_project
/Python/Coin/Number.py
401
3.75
4
# -*- coding: utf-8 -*- import random number = random.randint(1, 10) a = 0 while a < 10: player = raw_input("you namber ") if int(number) == int(player): print "bingo you win" break elif player != number: a += 1 print "you not win, Try again, you have " + str(10 - a) + " cha...
16d66063361d97559559c3cf69e47fe5952e87c5
shellyw19-meet/yl1201718
/OOP.py
917
4.03125
4
import turtle class Animal(object): def __init__(self,sound,name,age,favorite_color): self.sound = sound self.name = name self.age = age self.favorite_color = favorite_color def Eat(self,food): print("Yummy! " + self.name + " is eating " + food) def Description(self): print(self.name + " is " + str(sel...
ace8686c01b421b22ea5cbac45c525a7a0c13cba
dvillaunal/Dia_30_15abril
/main.py
3,462
4.25
4
# Expresiones regulares (regular expressions): ''' El código anterior importa el paquete <re> y compila un patrón de expresión regular que puede coincidir con al menos uno o más caracteres de espacio. ''' # 1 y 2. # importamos las "regular expressions": import re regex = re.compile('\s+') # 3. # Importamos el .t...
1b8b476ce92d556fb35a541fb39308c40d60bb42
Poonammahunta/New_world
/dat.py
669
3.84375
4
import datetime import calendar from datetime import timedelta target = raw_input("Enter the format %Y,%W: " ) p = datetime.datetime.strptime(target,"%Y,%W") print p def dat(p): st = calendar.day_name[p.weekday()] print st if st == "Thursday": pd = p- timedelta(days=3) if st == "Tuesday": ...
536edc86f868cb5920c667cab68096032b25b55f
Gcoral90/tareas
/lanzar_dados.py
440
3.921875
4
''' PROGRAMA QUE SIMULA EL LANZAMIENTO DE UN DADO Y TE ENTREGA EL RESULTADO EN UN STRING''' import random def lanzar_dados(): resultado=random.randint(1,6) return resultado print(lanzar_dados()) print(type(lanzar_dados())) def mostrar_menu(): print('\t 1-.lanzar datos') print('\t 2-.Salir) opcion...
574cbf654d212b151254a4321485b1406188cac3
Gcoral90/tareas
/3ejercicio.py
483
3.65625
4
lista_usuarios = [] usuario_uno = { 'nombre': 'Galileo', 'descuento': '5%', 'curso': 'Python 3' } usuario_dos = { 'nombre': 'Mike', 'descuento': '15%', 'curso': 'Analisis de datos con python' } lista_usuarios.append(usuario_uno) lista_usuarios.append(usuario_dos) for usuario in lista_usuarios:...
eefcdf6ce353aad5ae5f5c6deebc33b1a67569f8
teclivre/Python
/Desafios- Python/Desafio-38.py
535
3.96875
4
print('\33[1;30;45m Desafio 38 \33[m') print('\n\n') '''Escreva um programa que leia dois números inteiros e compare-os mostrando na tela uma mensagem: - O primeiro número é maior - O Segundo número é maior - Os números São iguais''' n1 = int(input('Digite o primeiro número: ')) n2 = int(input('Digite o segundo número...
063db711e7233c9c6015b6f873bf0bd8812c9f51
teclivre/Python
/Desafios- Python/Desafio-18.py
386
4.03125
4
from math import sin, cos, tan,radians a = float(input('\n\n Informe um ângulo: ')) sen = sin(radians(a)) cos = cos(radians(a)) tan = tan(radians(a)) print('\n\n O ângulo escolhido é: {:.3f}'.format(a) ) print('\n\n\n O seno de {:.3f} é: {:.3f}'.format(a, sen)) print('O cosseno de {:.3f} é: {:.3f}'.format(a, cos)) p...
d57b8844bceef78fced815b35272ac4cf5ba8921
teclivre/Python
/Desafios- Python/Desafio-34.py
444
3.765625
4
print('\n\n Cálculo de aumento de salário. \n\n') salary = float (input('Diga o seu salário para calculamos o valor do aumento: R$')) s10 = salary + (salary*0.10) s15 = salary + (salary*0.15) if salary > 1250.00: print('Seu salário hoje é R${:.2f} e parrara a ser R${:.2f}, após o aumento.'.format(salary, s10)) el...
ed52765477ed86e8935adab50389b4e99b44267a
teclivre/Python
/Aulas/Aula-12.py
709
3.84375
4
print('\33[1;34m --=--\33[m'*9) print('\33[1;30;43m Conteúdo da Aula 12\33[m \33[1;4;31m Condições Aninhadas.\33[m ') print('\33[1;34m --=--\33[m'*9) print('\n') color = {'White': '\33[1;30m', 'Red': '\33[1;31m'} n = str( input(' \33[1;36m Qual é seu nome? \33[m ')) n1 = n.strip() name = n1.capitalize() if ...
5eec2c2664854d07b2d64b018cfe574207550ebc
teclivre/Python
/Desafios- Python/Desafio-36.py
649
3.953125
4
print ('\33[1;31m Desafio 36 \33[m') print('\n') print('\33[1;36;40m Vamos tentar simular o seu emprestimo.\33[m') name = str(input('Informe seu nome completo: ')) salary = float(input('Informe Seu salário: R$')) value = float(input('Informe o Valor do Imível: R$')) months = int(input('Informe o período em meses: ')) ...
4aee1f712f834c7788c09fbbc5267e85674b9af4
teclivre/Python
/Desafios- Python/Desafio-07.py
346
3.90625
4
print ('Cálculo de médias de notas: \n \n \n') student = input ('Digite o nome do aluno: ') n1 = float (input('Digite a primeira nota: ')) n2 = float (input('Digite a segunda nota: ')) print ('Primeira nota: {} \n Segunda nota: {}'.format(n1,n2)) average = (n1+n2)/2 print ('A média das nota de {} é {:0.2f}.'.fo...
3399f8dbc8fddc7c7002fb84d2c47871d9d03ff9
GNLRaviTeja/Python
/12_bisectionSqrt.py
1,072
4.09375
4
# -*- coding: utf-8 -*- """ Studying approximate solutions using bisection search Program to find cube root Author: Kriyative Edge """ #previous cube root also serves the same idea but, this program gives iterative output x = int(input("Enter an Integer: ")) epsilon = 0.01 #change epsilon and try differen...
b7c335f76abddbfc693c5d8a48757569fd3ebafe
GNLRaviTeja/Python
/10_a_approxCube.py
1,415
4.09375
4
# -*- coding: utf-8 -*- """ Studying approximate solutions in exhaustive enumeration Program to find cube root Author: Kriyative Edge """ # good enough solution # start with a guess and increment by some small value #|guess^3|-cube <= epsilon - for some small epsilon # decreasing increment size --> slowe...