blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
3169089c9db7ac4cfa941cdcdf48d717945030d9
surrajjha/Practice
/coding/week_14/day_1/evaluation/sets_intersection.py
370
3.671875
4
# a = {"a", "b", "c", "d", "e"} # b = {"a", "e", "f", "h", "k"} # c = {"a", "b", "c", "z", "m"} a=str(input('enter set 1 ')) b=str(input('enter set 2 ')) c=str(input('enter set 3 ')) commonset='' for i in a : for j in b : for k in c : if i==j==k : commonset+=i ...
8e6b9a50e63333065a16b0b38f51618a7c55f49b
Sulongsl/python
/algorithm/quick_sort.py
1,113
4.15625
4
# -*- coding: utf-8 -*- """ 分治递归 """ def quick_sort(arr, low, high): if low < high: # 获取基准值坐标 key_index = partition(arr, low, high) # 对基准值数组进行拆分 quick_sort(arr, low, key_index - 1) # 对基准值右边进行分组 quick_sort(arr, key_index + 1, high) """ 将数据按基准值分组 之后返回基准值坐标 """ de...
75ec12c8cef5d0cb524419826ee163b5658fa1d8
theishansri/Python_Codes
/Python/remove_friend.py
2,453
3.53125
4
# class Node(object): # def __init__(self, data): # self.data=data # self.next=None # self.prev=None # # self.right=None # class LinkList(object): # def __init__(self): # self.head=None # def append(self,data): # newnode=Node(data) # if(self.head is No...
94354007a3fb1cf74eb1880f9e8002ff79818567
theishansri/Python_Codes
/Python/Merge_Sort.py
575
3.796875
4
def Merge_Sort(a): if(len(a)>1): mid=len(a)//2 L=a[:mid] R=a[mid:] Merge_Sort(L) Merge_Sort(R) i=j=k=0 while(i<len(L) and j<len(R)): if(L[i]<=R[j]): a[k]=L[i] i+=1 elif(L[i]>R[j]): a[k]=R[...
b89f8cfd82046668330ea1e2acd4db9444c02ecc
theishansri/Python_Codes
/Python/Binary_Search_Tree.py
1,152
4.03125
4
class Node(object): def __init__(self,data): self.data=data self.left=None self.right=None def insert(root,data): if(root is None): root=Node(data) else: if(data<=root.data): if(root.left is None): root.left=Node(data) else: ...
6b379da1094fd28998410b29dbb35a6c4397c01c
juanksRuiz/Utilidades
/Estadistica.py
609
3.5
4
def promedio(valores): #Retorna el promedio de los valores ingresados suma = 0 for v in valores: suma = suma + float(v) return suma/(len(valores)) def varianza(valores): #Retorna la varianza de los valores ingresados mean = promedio(valores) sumDist = 0 for v in valores: ...
9bd6c62e5938f66b68ef31dbde4f075b8057d1bd
Junya-0220/python_basic
/basic/seigyokoubun_2.py
1,604
3.921875
4
# count = 0 # while count < 5: # print(count) # count += 1 # count = 0 # while True: # if count >= 5: # break # if count == 2: # count += 1 # continue # print(count) # count += 1 # count = 0 # while count < 5: # if count == 1: # break # print(count) # ...
402fcc2b18a6a69acba00e44e0a936be54f34d96
IndoG117/Binus-Semester-1
/3 Rough Files (do not look)/Python Projects/Project/freecodecamp_pygame_snake_analysis.py
11,114
4.09375
4
#%% #possibly to invoke random module from math module but not necessary in the current version of python import math #imports randomizer module from python library import random #imports pygame python game-making module import pygame #imports tkinter (graphical user interface module for python) and assigns calling na...
cd6eb47cb91482d9373c8dc2f6d789d5464b4a43
funnybunnyofdoom/Homework
/AntognazziA_lines.py
371
3.53125
4
def main(): listOfNumbers = rangeGen(1,10) theSum = sumOfNums(listOfNumbers,0,len(listOfNumbers)+1) print("The sum is ", theSum) def rangeGen(Start,fin): array = list(range(Start,fin+1)) return array def sumOfNums(ARR,start,end): if start > end: return 0 else: return ARR[st...
ecfd0bff8bcd50b71a2df637f14e486a0609cc33
funnybunnyofdoom/Homework
/AntognazziA_nameEmail.py
3,820
4.34375
4
#9-8 Name and E-mail Address #Anthony Antognazzi #2/17/2018 import os.path #This will allow the program to check to see if the file exists. import pickle #Allows us to pickle and unpickle the dictionary def main(): PB = {} #Empty phonebook PB = retrieve() #Fill phonebook from file menu(PB) #Give...
925c7a1bfa4cf35c1d695d8a76848cec915b8b9c
khanhnv100898/ngovankhanh-labs-c4e20
/Lab03/f-math-problem/freakingmath.py
708
3.59375
4
from random import * from eval import calc def generate_quiz(): x = randint(1,10) y = randint(1,10) op = choice(['+','-','*','/']) res = calc(x, y, op) error = choice([-1 , 1]) display_res = res + error return[x,y,op,display_res] # Hint: Return [x, y, op, display_res] def ch...
6c2ecd40d69b8fe597f9dc8fd0d119082b19c338
Nuclearstar/Singular
/src/parser.py
5,196
3.984375
4
from .my_algorithms import my_split, my_strip, my_lower from .calculator import frac_reduc from .Matrix import Matrix import sys # Make everything work with python2. if sys.version_info[0] == 2: input = raw_input def __ask_input(string): """Ask input from user with 'string'.""" try: input_data = ...
d7753de05ada5f8cdff84fa45381d823cfdde5cb
zd123/intro-to-data-viz-soln
/py/soln-chart-1-bar-plot-with-month-names.py
1,924
3.6875
4
# coding: utf-8 # In[194]: import pandas as pd import matplotlib.pylab as plt # In[195]: df = pd.read_csv('data/chitown_crime_arrests_vs_reports.csv') df['Date'] = pd.to_datetime(df['Date']) df.head() # In[196]: # Create a bar chart that shows the amout of arrests made each month. df['Arrests'].plot(kind='bar'...
18d28fa98cd62c47141a6970bead8634edd403f6
NeoZet/pm
/num_meth/sem5/pit/Move_ball(1).py
2,347
3.640625
4
import matplotlib.pylab as plt import matplotlib.animation as animation import array as arr import numpy as np import math n=0 #y = np.loadtxt("yama.txt", delimiter='\n', dtype=np.int)# import data from file to Y_massiv fig=plt.figure() def _read_coords(filename): with open(filename, "r") as coords_file: r...
128cb4902b46abaee17cc894a72bf7ee7c8d4371
swarnanjali/kani
/roman.py
158
3.546875
4
NUM=(input()) KHI=["zero","I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII","XIII","XIV","XV"] for i in range(16): if NUM==KHI[i]: print(i)
d3763659b8b824588d2640a02bc7e627e96a57b3
clarissadesimoni/aoc15
/day8/day8.py
1,422
3.59375
4
data = open('day8/day8.txt').read().split('\n') def countChars1(string): i, code, memory = 0, 0, 0 hexChars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] while i < len(string): if string[i] == '\\': if string[i + 1] == 'x' and string[i + 2] in hexCha...
37efc581d4e072c58fd2be7ffa77c98284bf30c2
russlamb/xl_diff
/compare.py
9,992
3.59375
4
""" This module is the main entry point of the compare excel project. This project compares two excel or CSV files and saves the results in an excel file. Command line parsing has been moved to a separate file to keep code clean. To run the module, you need to pass in three filenames: the two files being compa...
c97456a8cf7154c70ef81c9c9ed16dce2f42dd2e
lcfsluiz/curso-python
/loop.py
188
4.03125
4
#!/usr/bin/python3 while True: variavel = input("Digite 0 para sair: ") if variavel == '0': continue elif variavel == 'sair': break print('teste continue')
cb2f018237782747bd0ec910fa0df47438ddc382
lcfsluiz/curso-python
/dic_for.py
312
4
4
#!/usr/bin/python3 pessoas = [ {'nome': 'daniel', 'idade': 24}, {'nome': 'rafael', 'idade': 6}, {'nome': 'renata', 'idade': 23}, {'nome': 'yasmin', 'idade': 4}, ] for pessoa in pessoas: nome = pessoa['nome'] idade = pessoa['idade'] print("O(A) {} tem {} anos".format(nome, idade))
42e6f4094a596e30dd6c3287dd99df4a9d5ca6ee
beachamc/Quizzer
/Question.py
1,062
3.6875
4
class Question: def __init__(self): self.types = ["multiple_choice", "true/fase", "fill_in_the_blank"] def setType(self, mytype): self.type = self.types[mytype] def setQuestion(self, question): self.question = question def setAnswers(self, answers): self.answers = answers def setCorrect(self, corre...
b51700fd1ef1be36e0c67c2d87246fc14ab350bf
PrathmeshChitnis/Python3
/Examples/curtain_cost.py
506
4.21875
4
""" User wants a curtain for his square window, the height of his window is 24 meters, your shop charges $0.75 / sq_cm, find the total cost of curtain for the window and let the user know. """ print("Cost of the curtain is :- $0.75/sq_cm") print("Required curtain cloth is - 24 sq_meters") cost_per_square_meter = 0.75 ...
dba5ea3118196c71927796b0cccd33a845085101
mbalamat/mbalamat-algo
/mergesort/mergesort.py
656
3.828125
4
def merge(a, b): i = 0 j = 0 merged = [] for k in range(len(a + b)): if i < len(a) and j < len(b): if a[i] < b[j]: merged.append(a[i]) i += 1 else: merged.append(b[j]) j += 1 elif i >= len(a) and j < ...
3600d998567a2153a76ff6fee18d4142b67a48ab
sina-sid/Uber-DBMS
/complex_query_1.py
2,087
3.59375
4
import psycopg2 conn = psycopg2.connect(database="uber", user="postgres", host="127.0.0.1", port="5432") conn.autocommit = True cur = conn.cursor() print('''////////////////////////////////////////////////////////////////////////////// We are deducting tide_credit from a rider for a particular trip (in t...
50bb01614ea53be8186f25184138ed8350f31daf
slientup/simplepython
/gramma/for.py
575
4.0625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- print '*' * 20, "if", '*' * 20 for i in range(10): print i print '*' * 20, "break", '*' * 20 for i in range(10): print i if i > 5: break print '*' * 20, "continue", '*' * 20 for i in range(10): if i < 5: continue print i # 没有break, ...
a01aac3852f5d8f6586af7112589f81f393b35c8
slientup/simplepython
/var/num.py
704
4.0625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # 整数 a = 5 b = 6 print a, b # 5,6 a = a+1 print a # 6 a += 2 print a # 8 print a**2 # 64 print a # 8 a **= 2 print a # 64 # python中很方便的支持长整数 l = a**a print type(l) # <type 'long'> # 394020061963944792122790401001436138050797392704654466679482934042457217714972...
586ecbbf478ada073f086dce1e73be240ba650a6
jasonjiehub/python-study
/QueueTest.py
226
3.75
4
import queue # Queue是线程安全的,可以用于线程间的同步 q = queue.Queue(maxsize=0) # for i in range(100): # q.put(i) # # for i in range(100): # print(q.get()) q.put(0) print(q.get()) print(q.empty())
c388b6c2a54ffc4df5ae3951508190dd90333d87
jasonjiehub/python-study
/CommonXulie.py
272
3.796875
4
first = [1, 2, 3, 4, 5, 6] second = [7, 8] third = [first, second] print(third) print(third[-1]) print(10 * first) print(first[2:5]) print(first[:4]) print(first[0:6:2]) print(first[6:0:-2]) print(first + second) print([None] * 10) print(10 in first) print(len(first))
b237e6c25b6e235b3c662425430b46ac9d223071
duncanodhis/Store-database-
/database.py
955
3.640625
4
# -*- coding: utf-8 -*- """ Created on Mon May 20 18:30:06 2019 @author: duncan odhiambo """ import sqlite3 def create_table(): conn = sqlite3.connect("lite.db") cur = conn.cursor() cur.execute("CREATE TABLE IF NOT EXISTS store(item TEXT,quantity INTEGER,price REAL)") co...
3faa1755d2e00628d1dd9f0b9f8cdd32cd5462a2
nataliaEscobar/Girls_Who_Code
/codingEncryption.py
1,592
4.0625
4
#GLOBAL VARIABLES codeWords = [] realWords = [] #FUNCTIONS def createCodeWords(): codingWords = True while codingWords: print("Would you like to add a word to your code? (y/n)") answer = input().lower() if(answer == "y" or "yes"): print("What is the real word ...
1ae3e97baf42b4984dcbc461a821334cadd9ba3c
louism33/dailyProblems
/day6.py
1,658
4.1875
4
''' Good morning! Here's your coding interview problem for today. This problem was asked by Google. An XOR linked list is a more memory efficient doubly linked list. Instead of each node holding next and prev fields, it holds a field named both, which is an XOR of the next node and the previous node. Implement an X...
17448d144820e4829d0df7a2b62db8871dcc0a0a
huntercasillas/165
/Examples/loops3.py
445
3.953125
4
#! /usr/bin/env python num_seq = raw_input("Number sequences: ") num_seq = int(num_seq) sequences = [] count = 0 while count < num_seq: seq = raw_input("Sequence: ") seq = seq.upper() sequences.append(seq) count += 1 sequences.sort() print "\n".join(sequences) print "" sequences = [] for number in range(num_seq)...
bac643ed0e529bf5c55eab129318f7f4b32f7e67
mervinsun/duoduo
/generator.py
146
3.6875
4
def generatorTest(list): for node in list: yield node list = ["one", "two"] for num in generatorTest(list): print("num:", num)
462f334c376e88d350970601ae07be66ae51aed8
francososuan/1-practice_problems
/3-Variable.py
254
3.796875
4
i = 5 print(i) i = i + 1 print(i) s = '''This is a multiline sentence''' print(s) print("The output is \ {}" .format(i)) length = 4 width = 7 area = 7 * 4 perimeter = 2*(length + width) print("The Area is",area) print("The Perimeter is",perimeter)
2605bb9331dc03c85f243544ef47e029f82adde3
nickmachairas/demo-flask-form-api
/select.py
489
3.671875
4
import sqlite3 conn = sqlite3.connect('app.db') cur = conn.cursor() # --------------------------------------------------------------------------- # cur.execute("SELECT * FROM departments") rows = cur.fetchall() print(" --- DEPARTMENTS --- ") for row in rows: print(row) # -------------------------------------...
a55536fd4ba2ca6276ae85612558b25507bcb9e4
hwc1824/LeetCodeSolution
/leetcode_explore/binary_search/sqrt_x.py
477
3.5
4
# 69. Sqrt(x) # https://leetcode.com/problems/sqrtx/description/ class Solution: def mySqrt(self, x): """ :type x: int :rtype: int """ if x <= 1: return x low, high = 1, x while low < high: mid = low + (high - low)//2 ...
a366063c7f281879a61fb653f37e60f1efcd6831
hwc1824/LeetCodeSolution
/cs_notes/string/palindromic_substrings.py
3,956
3.6875
4
# 647. Palindromic Substrings # https://leetcode.com/problems/palindromic-substrings/description/ # https://leetcode.com/problems/palindromic-substrings/discuss/105687/Python-Straightforward-with-Explanation-(Bonus-O(N)-solution) # https://zh.wikipedia.org/wiki/%E6%9C%80%E9%95%BF%E5%9B%9E%E6%96%87%E5%AD%90%E4%B8%B2 cl...
5584dd3ccb3ade9d4a7fcba81aaef88bdcf053b6
hwc1824/LeetCodeSolution
/cs_notes/tree/recursive/convert_sorted_list_to_binary_search_tree.py
975
3.734375
4
# 109. Convert Sorted List to Binary Search Tree # https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/description/ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # Definition for a binary tree node. # class Tre...
3e05aceb41934b259e28ebf59a795728e823a1cb
hwc1824/LeetCodeSolution
/cs_notes/string/palindrome_number.py
849
3.71875
4
# 9. Palindrome Number # https://leetcode.com/problems/palindrome-number/description/ class Solution: def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x == 0: return True if x < 0 or x%10 == 0: return False invt_x = 0 while x > invt_x:...
77fe4ec4cac4882efc1336c9ef89bb7e75728738
hwc1824/LeetCodeSolution
/cs_notes/tree/recursive/maximum_width_of_binary_tree.py
1,274
3.734375
4
# 662. Maximum Width of Binary Tree # https://leetcode.com/problems/maximum-width-of-binary-tree/description/ # 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 widthO...
1aa1222a72cdb1bafc514232702918ace7510a32
hwc1824/LeetCodeSolution
/cs_notes/arrays/spiral_matrix.py
497
3.53125
4
# 54. Spiral Matrix # https://leetcode.com/problems/spiral-matrix/description/ class Solution: def spiralOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ ret = [] while matrix: # ret+=(matrix[0]) #...
40681e2590580e8461ceb73b6d14ff0260df12fa
hwc1824/LeetCodeSolution
/cs_notes/dynamic_programming/length_of_longest_fibonacci_subsequence.py
2,149
3.703125
4
# 873. Length of Longest Fibonacci Subsequence # https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/description/ class Solution: def lenLongestFibSubseq(self, A): """ :type A: List[int] :rtype: int 本題使用動態規劃,整體算法的流程如下 1) 建立一個字典方便查閱某個數字是否在 A 之中以及如果該元素在 A 中, ...
fff916252db610dc3a7e52be2b70601abb785e47
hwc1824/LeetCodeSolution
/cs_notes/arrays/merge_intervals.py
1,073
3.734375
4
# 56. Merge Intervals # https://leetcode.com/problems/merge-intervals/description/ # Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: def merge(self, intervals): """ :type intervals: List[Interval] ...
dfd0e9ea7829bbaff539855668c83863f979d480
hwc1824/LeetCodeSolution
/top_interview_questions/easy_collection/linked_list/remove_nth_node_from_end_of_list.py
1,253
3.859375
4
""" Remove Nth Node From End of List https://leetcode.com/problems/remove-nth-node-from-end-of-list/ Given a linked list, remove the n-th node from the end of list and return its head. Example: Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes...
da90690d56154e4ba7a5ce6e82a0a76c95d3610c
hwc1824/LeetCodeSolution
/top_interview_questions/easy_collection/math/fizz_buzz.py
552
3.640625
4
# Fizz Buzz # https://leetcode.com/explore/interview/card/top-interview-questions-easy/102/math/743/ class Solution(object): def fizzBuzz(self, n): """ :type n: int :rtype: List[str] """ output = [] for idx, num in enumerate(range(1, n+1)): term = "" ...
1db4afa37ca1f7ce9ea98326ced528fb3c94cba9
hwc1824/LeetCodeSolution
/cs_notes/DFS/pacific_atlantic_water_flow.py
1,441
3.6875
4
# 417. Pacific Atlantic Water Flow # https://leetcode.com/problems/pacific-atlantic-water-flow/description/ ass Solution: def pacificAtlantic(self, matrix): """ :type matrix: List[List[int]] :rtype: List[List[int]] """ row = len(matrix) if row == 0:return []...
333e1f1335ff42605deb2ed60ef54121fa6b63de
hwc1824/LeetCodeSolution
/cs_notes/tree/recursive/count_complete_tree_nodes.py
1,937
3.90625
4
# 222. Count Complete Tree Nodes # https://leetcode.com/problems/count-complete-tree-nodes/description/ # 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): # https://leetco...
9003f0d1612f14836b54c23c8ec3a2e5743ff2c1
hwc1824/LeetCodeSolution
/top_interview_questions/easy_collection/dynamic_programming/best_time_to_buy_and_sell_stock.py
573
3.703125
4
# Best Time to Buy and Sell Stock # https://leetcode.com/explore/interview/card/top-interview-questions-easy/97/dynamic-programming/572/ class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ min_price = sys.maxsize profit = 0 ...
cf63f2873991c64c747f443bb30c27bb12285de8
hwc1824/LeetCodeSolution
/cs_notes/tree/recursive/find_duplicate_subtrees.py
1,393
3.6875
4
# 652. Find Duplicate Subtrees # https://leetcode.com/problems/find-duplicate-subtrees/description/ # 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 findDuplicateSub...
5c75d01c40c4c7059adee9eb077c129e70b58225
jsdelivrbot/ppci-mirror
/ppci/binutils/objectfile.py
12,996
3.703125
4
""" Object files are used to store assembled code. Information contained is code, symbol table and relocation information. The hierarchy is as follows: - an object file contains zero or more sections. - an object file may contains memory definitions, which contain a sequence of contained sections. - a section cont...
8a442f44da545e05c41b9eb5272c789a32be6e48
aidyp/puzzlethon
/classical/level2/tools/helper.py
391
3.59375
4
def print_puzzle_stats(puzzletext): ''' Gives you some observations on the puzzle that you may find useful! ''' print("Length : {}".format(len(puzzletext))) def write_line_to_file(line): ''' Writes out any line to scratchpad.txt ''' with open('scratchpad.txt', 'a') as fd: # Add ...
327ff4a8d0d3e3592d40991ba8f1e2e4623c70bc
BenjaminCall/adventofcode2020
/AdventPuzzles/d2.py
810
3.5625
4
import os inputs = open(os.getcwd() + '/inputs/d2.txt', 'r') lines = inputs.readlines() validPass = 0 failedPass = 0 validPass2 = 0 failedPass2 = 0 def isValidP1(mini,maxi,letter,password): return password.count(letter) >= mini and password.count(letter) <= maxi def isValidP2(mini,maxi,letter,password): retur...
05bc494af0999e3171e13bd70d38efe4e8014425
lopamd/FAQ-semantic-matching
/base_objects.py
3,645
3.5
4
class QAPair: def __init__(self, question, answer): self.question = question self.answer = answer def __str__(self): return "Question: [%s] Answer: [%s]" % (self.question, self.answer) class QAFeatureExtraction( object ): '''qa_pairs is a list of QAPair object...
d833ea6d490404a4640a05be356e890539819574
infomuscle/algorithms-leetcode
/leetcode-python/547. Number of Provinces.py
952
3.5
4
# 제출 코드 - Runtime 96.78 Memory 51.72 class Solution: def explore(self, province, isConnected, visited): size = len(isConnected) for other in range(size): if other not in visited and isConnected[province][other] == 1: visited.add(other) self.explore(other, ...
24bf09f79f273339278000f0c4820ad21aa677c2
infomuscle/algorithms-leetcode
/leetcode-python/709. To Lower Case.py
272
3.640625
4
# 제출 코드 - Runtime 79.09 Memory 98.08 class Solution: def toLowerCase(self, str: str) -> str: return str.lower() s1 = "Hello" s2 = "here" s3 = "LOVELY" sol = Solution() print(sol.toLowerCase(s1)) print(sol.toLowerCase(s2)) print(sol.toLowerCase(s3))
0fa84335c5e134997b192a7671cd324757f7b6e1
infomuscle/algorithms-leetcode
/leetcode-python/206. Reverse Linked List.py
552
3.796875
4
# 제출 코드 - Runtime 53.44 Memory 56.29 class Solution: def reverseList(self, head): if not head: return head next_node = head.next node = head head.next = None while next_node: next_next_node = next_node.next next_node.next = node ...
581fcc0153ef977bd5b46d1536180e3c37c2ec41
RishabhArya/Coursera-Data-Structures-and-Algorithms-by-University-of-California-San-Diego-
/1.Algorithmic Toolbox/week2_algorithmic_warmup/4_least_common_multiple/lcm.py
271
3.71875
4
# Uses python3 import sys def gcd(c, d): if c == 0: return d return gcd(d % c, c) def lcm(q, d): return int((q * d) / gcd(q, d)) if __name__ == '__main__': numbers = sys.stdin.read() a, b = map(int, numbers.split()) print(lcm(a, b))
283be2db0521ba331e8847974f07ab2bdca14a16
RishabhArya/Coursera-Data-Structures-and-Algorithms-by-University-of-California-San-Diego-
/4.Algorithms on Strings/Week 1/Trie.py
658
3.609375
4
import sys def build_tree(patterns): tree = dict() tree[0] = {} index = 1 for pattern in patterns: current = tree[0] for letter in pattern: if letter in current.keys(): current = tree[current[letter]] else: current[letter] = index ...
ef7abc033b053373a2c13dc37233d0d7a016cf5c
kketan227/RL-Maze
/Policy iteration and Value iteration/value_iteration.py
2,635
3.921875
4
''' Has the code for value iteration without any visualization to save the computation time. ''' import maze import maze2mdp import AnimationFile as af import turtle from tabulate import tabulate def value_iteration(grid, gamma): """ Performs value iteration on a given grid of MDPState objects. """ ...
4c2b33eed57391f75b8f14f19685c3b0d49ff564
annasnrhs/introtoDSwithPy
/week 1/advanced_python_objects_map.html
1,093
4.21875
4
#!/usr/bin/env python # coding: utf-8 # # The Python Programming Language : Objects and map() # In[2]: #class diawali dengan huruf capital (camel case) class Person: departmen = 'School of Information' def set_name(self, new_name): self.name = new_name def set_location(self, new_location): ...
949aee01feea61cf8398ae933312155d69ef263e
Koldor-47/AOC2020
/Advent2020/Day5/Day5.py
1,279
3.53125
4
def get_input_data(input_data): with open(input_data, 'r') as F: thedata = F.read().split("\n") return thedata def data_to_number(row_data, letters): # letters needs to a list ie ["F", "B"] answer = "0b" for pos in row_data: if pos.upper() == letters[1]: answer += "1" ...
7b650073aa080644f107c1085d7ecbe84a7afc3c
prem0862/DSA-Problems
/LinkedList/list_cycle.py
823
3.828125
4
# Problem: https://www.interviewbit.com/problems/list-cycle/ # Solution: https://leetcode.com/problems/linked-list-cycle/solution/ # Solution: https://www.geeksforgeeks.org/detect-loop-in-a-linked-list/ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # ...
8061c1c4fb114953669b1c28a86258b2cb99f96f
prem0862/DSA-Problems
/Stack/reverse_string.py
390
3.625
4
# Problem: https://www.interviewbit.com/problems/reverse-string/ class Solution: # @param A : string # @return a strings def reverseString(self, A): rev_str = "" stack = [] str_size = len(A) # add elements in stack for index in range(0, str_size): ...
6ffccf839428f9cb9eafc6d54afb50eea881cf0f
prem0862/DSA-Problems
/Stack/evaluate_expression.py
935
3.75
4
# Problem: https://www.interviewbit.com/problems/evaluate-expression/ class Solution: # @param A : list of strings # @return an integer def evalRPN(self, A): stack = [] operators = set(["+", "-", "*", "/"]) for item in A: # push item to stack until we found any opera...
c1368dd34fb6249f56b671cfe3f9bb380b24d539
prem0862/DSA-Problems
/Binary_Search/sorted_insert_position.py
1,050
4.0625
4
""" Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Here are few examples. [1,3,5,6], 5 → 2 [1,3,5,6], 2 → 1 [1,3,5,6], 7 → 4 [1,3,5,6], 0 ...
68ba0117f5a7077372ded0ea098ccd79df929c7a
prem0862/DSA-Problems
/Maths/trailing_zeros_in_factorial.py
541
4.0625
4
""" Given an integer n, return the number of trailing zeroes in n!. Note: Your solution should be in logarithmic time complexity. Example : n = 5 n! = 120 Number of trailing zeros = 1 So, return 1 """ import math class Solution: # @param A : integer # @return an integer def trailingZeroes(self, A): ...
bd960aa56e2ed82dc7c4722320869555102a9581
ashwinkhushlani/Interview_Questions
/removeDuplicates.py
799
3.71875
4
# // [1,14,13,1,2,25,2,14] # // [1,14,13,2,25] from typing import List class Solution: def removeDuplicates(self,arr: List[int]) -> List[int]: resultArray = [] for i in arr: # print(i) if len(resultArray) < 1: resultArray.append(i) else: ...
5bdf6fe589a17780cb00fc24ebc4631f131723d5
Holysalta/task3
/4-2.py
173
3.515625
4
a=int(input()) alist=[] alist.append(a) cnt=0 for i in alist: while alist[i]!=alist[i+1]: cnt += 1 if cnt == 7 or cnt >7: print('NO') else: print('YES')
4e4d093ace45603b008489ee29aa8f6bcc0933b6
Super-Alpha/LeetCode
/Data-structure/Graph/__init__.py
1,276
3.96875
4
# @Time:2020/7/189:29 graph = {"A":["B","C"], "B":["A","C","D"], "C":["A","B","D","E"], "D":["B","C","E","F"], "E":["C","D"], "F":["D"]} def BFS(graph,s): """ 广度优先搜索 :param graph:定义好的图 :param s: 首先开始搜索的节点 :return: """ res = [] queue = [] ...
ffe7e3a63abf6f411dc7cc6d4f7c1bc30046ceb9
Super-Alpha/LeetCode
/Data-structure/LeetCode/Recursion/__init__.py
2,634
3.6875
4
# Time:2020/6/2411:24 """public class Queue8 { int max = 8; int[] array = new int[max]; // 放置第n个皇后 private void check(int n) { if (n == max) { print(); return; } // 从第一列开始摆放 for (int i = 0; i < max; i++) { array[n] = i; if (judge(n)) { check(n+1); } } } // 判断当前摆放的皇后和之前摆放的皇后是否冲突 private boolean judge(int n) { for (in...
df1756d8b3875fb8cb79a51f8166d6eb958d4d2e
Super-Alpha/LeetCode
/Data-structure/Tree/BinarySearch/BinarySearchTree.py
9,705
3.828125
4
"""二叉搜索树的python实现""" class TreeNode: """ 创建二叉搜索树节点 """ def __init__(self,key,val,left=None,right=None,parent=None): """ :param key:键值 :param val: 数据项 :param left: 左子节点 :param right: 右子节点 :param parent: 父节点 """ self.key=key self.pay...
485876d5eeaf2df921af7ed9a166df12984e2579
Super-Alpha/LeetCode
/Data-structure/LeetCode/Tree/Build_Tree.py
2,942
3.828125
4
# @Time:2020/7/1910:59 """ 将二叉树进行宽度优先遍历,可得到顺序存储二叉树列表 顺序存储二叉树(即将二叉树元素存储到列表)的特点: 1、顺序二叉树通常只考虑完全二叉树 2、第n个元素的左子节点为2*n+1 3、第n个元素的右子节点为2*n+2 4、第n个元素的父节点为(n-1)/2 5、n表示二叉树中的第几个元素(在列表中从0开始) """ # 实现顺序存储二叉树的遍历 class ArrBinaryTree: def __init__(self,arr): self.arr=arr # [1,2,3,4,5,6,7] def __preorder(self,index)...
546d51f54388b368b45dec0188505cd54ad66d5f
Super-Alpha/LeetCode
/Data-structure/Tree/BinaryTree-achieve-in-List.py
1,096
3.953125
4
""" insertLeft/insertRight #将新节点插入树中作为其直接的左/右子节点 getRootVal/setRootVal #取得或设置根节点 getLeftChild/getRightChild #返回左/右子树 """ BinaryTree=["a",["b",["d",[],[]],["e",[],[]]],["c",["f",[],[]],[]]] def BinaryTree(r): return [r,[],[]] def insertLeft(root,newBranch): t = root.pop(1) # pop(1)返回该节点处的元素root[1]给t后,并删除root[1]...
feee5f8b43bed7af0dee8e7aa7a2c2f0eeb75231
Super-Alpha/LeetCode
/Data-structure/Graph/Graph_ADT.py
2,589
3.75
4
class Vertex: """设置Graph的顶点(vertex)类""" def __init__(self,key): """ :param key:该顶点的key """ self.id=key self.connectedTo = {} # 存储与该顶点连接的邻近顶点 def addNeighbor(self,nbr,weight=0): """ 添加该顶点的邻近顶点以及所连接边的权值 :param nbr:所添加邻近顶点的key :param wei...
f80155a07acabc8515fe1d40a333672976b66daf
SharleneL/leetcode-python
/solutions/dp/230609-22-md.py
1,521
3.53125
4
# TODO:过了。但是时间复杂度?空间复杂度? class Solution: def generateParenthesis(self, n: int) -> List[str]: return list(self.helper(n)) def helper(self, n) -> Set[str]: if n == 1: return set(["()"]) totalSet = set() for pCombinationStr in self.helper(n - 1): newResSet ...
d2c5f835e363238d783223b140b46c6018233457
SharleneL/leetcode-python
/solutions/tree/0124-687-md.py
2,256
3.921875
4
# 每层返回什么? # 返回当前节点向下延伸的最长长度 # 每一层做什么? # check左右的返回值并用返回值update class variable(self.cur_longest) class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: cur_longest = 0 def longestUnivaluePath(self, root: ...
2190a8e36647018f7f7db01d03410417b6fa949c
SharleneL/leetcode-python
/solutions/tree/0122-1261-md.py
1,645
3.875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class FindElements: recovered_root = None def __init__(self, root: TreeNode): # recover the tree if not...
bc243b6113e66daea3e6724fe29e3103c40e311e
SharleneL/leetcode-python
/solutions/tree/0121-437-md-tbd.py
1,055
3.78125
4
# 最开始不work是因为如果把totalNum passdown的话,这个变量是局域性的,所以跳出函数之后totalNum不会被改变 class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def pathSum(self, root: TreeNode, sum: int) -> int: totalNum = 0 if n...
849ba4c24eb6461da90002e62a351a003e45bfab
SharleneL/leetcode-python
/solutions/tree/0123-508-md.py
1,332
3.53125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findFrequentTreeSum(self, root: TreeNode) -> List[int]: res_map = dict() if not root: ...
088d9c8107ac26fd9783626186ea535d2198164a
SharleneL/leetcode-python
/solutions/tree/0-input-sample.py
749
3.65625
4
from typing import List class TreeNode: def __init__(self, val=0, left=None, right=None, name=None): self.val = val self.left = left self.right = right self.name = name if __name__ == '__main__': root = TreeNode(1) R = TreeNode(1) R.name = "R" root.right = R R...
0682ac2fb5fe51df7935e47fad72d2bb38dbab7d
SharleneL/leetcode-python
/solutions/tree/0123-538-md.py
1,247
3.75
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # class Solution: # def convertBST(self, root: TreeNode) -> TreeNode: # if not root: # return root # ...
cf9eceb4c11d401f7ea11665a1ecd18b6df1a393
CarlosBrunoFreitasSardinha/Python
/NoçõesBasicas/ManipulandoNumeros.py
932
4.40625
4
print(2 + 3) print(2 - 3) print(2 * 3) print(2 ** 3) print(3 ** 2) print('#####################1#########################') quociente = 7 // 3 # divisão inteira print(quociente) resto = 7 % 3 print(resto) print('######################2########################') print(3.14, int(3.14)) print(3.9999, int(3.9999)) ...
7388c50c15c1e57f9d8ba291ae35e2920f84f6c1
CarlosBrunoFreitasSardinha/Python
/NoçõesBasicas/ManipulandoMatrizes.py
380
4
4
# Manipulado Matrizes. matriz = [] for i in range(0, 5, 1): lista = [] for j in range(0, 5 , 1): lista.append([str(i+1) + "x"+ str(j+1)]) matriz.append(lista) # Impressão Normal print(matriz) # Impressão em outro formato print("Matriz impressa de outra forma:") for lista in matriz: for elemen...
4a5b1835b14e90f236fab6dd72f59bc4339e7774
CarlosBrunoFreitasSardinha/Python
/EstruturasDeDados/Teste2LDSE.py
416
3.53125
4
# TIPO ABSTRATO DE DADOS - TAD #CONJUNTO DE VALORES E CONJUNTO DE OPERAÇÕES SOBRE ESTES VALORES # LDSE - LISTA Dinamica Simplesmente Encadeada import Ldse l = Ldse.Ldse() l.inserirInicio('F') l.inserirInicio('E') l.inserirInicio('D') l.inserirInicio('C') l.inserirInicio('A') l.inserirFim('G') print("\n...
2077720252049d78a9f0dd4f13a1a583a2c5a1b3
ankitrev/Parking-Lot
/Utils/utils.py
228
4
4
import re def is_valid_vehicle_number(vehicle_number): ''' Regex to check the correct format for car registration number ''' if not re.match('^[A-Z]{2}-[0-9]{2}-[A-Z]{2}-[0-9]{4}', vehicle_number): return False return True
b6e4205e82cbfe4c5eade95f0c91b83689e7ec9c
joshuaMarple/CodeDashStuff
/p1.py
368
3.546875
4
import fileinput, sys def main(): #Input stuff (might want to change to array of chars) lines=[] deli = fileinput.input() for line in deli: #char array linelist = [] for char in line: linelist.append(char) lines.append(linelist) #word array #lines.append(line.split(' ')) #actual stuff print(li...
984fcc01d65527c2e9e72942bc416b93e1fb8d1a
alessandrrra/atividade2_algoritmosII
/aluno.py
840
4.125
4
''' Construa um algoritmo para implementar a classe Aluno(código, nome, matrícula). A classe Aluno possui duas subclasses, a classe AluEnsinoMedio(ano) e AlunoGraduacao(semestre). As 3 classes possuem o método construtor e também o método imprimir(), que imprimi na tela os valores de todos os atributos da sua class...
e9f9c188f62d7a15a5b0c2ce909e399a10328054
KevinBrother/pythonwk
/imooc/DataType.py
151
3.9375
4
# coding:utf-8 # 1、1、2、3、5、8、13、21 d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59, 'Paul': 74 } print d.keys() for key in d: print d[key]
5eb2e305588b1af5b0bda29ef532abf0abd60efe
jamestonkin/tuples
/zoo.py
409
4.03125
4
zoo = ('tiger', 'elephant', 'gorilla', 'hyena', 'shark') print(zoo) print(zoo.index('gorilla')) for animal in zoo: if animal is "hyena": print(animal) (tiger, elephant, gorilla, hyena, shark) = zoo print(tiger) print(elephant) print(gorilla) print(hyena) print(shark) zoo2 = list(zoo) zoo2.append('monke...
72d15982be3dad06464c140618372e4d84817372
KR4705/project_euler
/prob045.py
365
3.875
4
def is_triangle(num): n = (0.25+2*num)**0.5 - 0.5 return n == int(n) def is_pentagonal(num): x = (1+(1+24*num)**0.5)/6 return x == int(x) count = 0 i = 1 answer = 0 while count <= 2: #because 1 is also an answer x = i*(2*i-1) #generating a hexagonal number with index i if is_pentagonal(x) and is_triangle(x): c...
2a405190ee956ed8228bcf30c15198dae7dff604
KR4705/project_euler
/prob004.py
1,043
3.953125
4
import time #this is my palindrome works much faster than the other one # which uses the reverse # reverse uses calculations while mine just used the list. def is_palindrome(arg): arg = str(arg) if len(arg) == 1 or len(arg) == 0: return True elif arg[0] == arg[len(arg)-1]: return is_palindrome(arg[1:len(arg)-1...
ef9753d967a04d9e25f077b62b0b5be9044a2ff0
KR4705/project_euler
/prob025.py
296
3.890625
4
def fib(num1,num2): while True: total = num1 + num2 yield num2,total num1,num2 = num2,total def no_digits(num): ans = 0 while num > 0: ans,num = ans + 1,num / 10 return ans a = 1 b = 1 index = 2 while no_digits(b) < 1000: a,b = fib(a,b).next() index += 1 ans = index print ans
ae0cb9671edf0aaf569111c5c2c63fa920294cab
KR4705/project_euler
/prob030.py
420
3.78125
4
powers = [] for i in range(10): powers.append(i**5) def sum_of(num): total = 0 while num > 0: rem = num%10 total += powers[rem] num /= 10 return total answers = [] # found that the converging point of 10**n and (9**5)*n is between 6 and 7 # we get this limit of 6 max_range = 10**6 for i in range(1,max_range...
83a3aaea0e108d67798f2794dfb7604a024452ec
vivianjia123/RoPaSci-360
/Project_final_ver/admin/heuristics.py
40,147
3.765625
4
""" COMP30024 Artificial Intelligence, Semester 1, 2021 Project Part B: Playing the Game Team Name: Admin Team Member: Yifeng Pan (955797) & Ziqi Jia (693241) This module contain functions of our searching strategy to make decisions for player's next action based on evaluation function. """ import math from...
a829a499f131fafa8b76f37ee1c0952496d515aa
AmineNeifer/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/base.py
3,245
3.671875
4
#!/usr/bin/python3 """ Base class is the most super class in this project """ import json import turtle import random class Base: """ conatins methods to all kinds of geometry shapes""" __nb_objects = 0 def __init__(self, id=None): if id is not None: self.id = id else: ...
814c6033633485b93ac4d201fbdd685c083c0997
AmineNeifer/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
515
4.375
4
#!/usr/bin/python3 """ add_integer is a function that takes two arguments a and b that must be integer or float and calculates their sum""" def add_integer(a, b=98): """Args: a: int or float b: int or float Returns: the sum of a and b""" if type(a) is not int and type(a) is not flo...
5fdb928efbd66e20d15f81be3871571a780a59d0
AmineNeifer/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/3-say_my_name.py
540
4.625
5
#!/usr/bin/python3 """ say_my_name is a function that takes two strings, first name and last name and outputs a message of greeting""" def say_my_name(first_name, last_name=""): """Args: first_name: str type. last_name: str type. Returns: Nothing""" if type(first_name) is not str: ...
36f379f4a30c014a9020422889bf30d2fab024a3
AmineNeifer/holbertonschool-higher_level_programming
/0x03-python-data_structures/9-max_integer.py
214
3.703125
4
#!/usr/bin/python3 def max_integer(my_list=[]): if len(my_list) == 0: return None maxi = my_list[0] for element in my_list: if maxi < element: maxi = element return maxi
56b13cb050bed40abe9d9b579c1da59cc8dc2c0d
AmineNeifer/holbertonschool-higher_level_programming
/0x10-python-network_0/6-peak.py
592
4.03125
4
#!/usr/bin/python3 """ funtion find_peak""" def find_peak(list_of_integers): """ find a peak in a list of integers Arguments: list_of_integers: list of int Returns: int or None if list is empty """ if list_of_integers == []: return None length = len(list...
3bc3af80098057642bfc977e3c8aa93e8093ac7e
M0use7/python
/python基础语法/day11-文件操作和异常捕获/01-recode.py
1,617
4.3125
4
"""__author__ = 余婷""" """ 容器类型:字典、列表、元祖和集合 1.列表(list):有序(可以通过下标获取元素)、可变(增删改)、列表中的元素可以是任何类型的数据 2.列表相关操作: 增删改查 3.列表相关的运算:+, *,in/not in , len() 4.列表相关方法:。。。。。 字典(dict):可变(增删改)、key: 唯一的,不可变 value:可以是任何类型的数据 字典相关操作:增删改查 字典相关运算:in/not in, len() 字典相关的方法:。。。。。 元祖(tuple):有序、不可变、元素可以是任何类型的数据 查和列表一样 只要一个元素的元祖:(1,) 获取元祖中的元素:x...
56baaae650852454385b68cbd4e77cf8a29bb5a1
M0use7/python
/day5-循环中关键字/01-循环中的关键字.py
1,660
4.15625
4
#补充:python控制台输入函数 input(提示信息) ''' 1.程序遇到input会停下来,等待输入完成后才会执行后面的代码(阻塞线程) 2.输入结束:遇到return就结束 3.获取到输入的内容的类型是字符串(不管输入什么) ''' # name = input('请输入名字:') # number = input('请输入一个数字:') # print(number,type(number)) # print('==========') # break、continue、else ''' break:程序执行过程中,只要遇到break,就结束/跳出包含break的最近的循环 ''' # 练习:随机生成一个整数,然后去...