blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
3fa926780c7733d5db01d1222e1701a011b6d71d
yang4978/LeetCode
/Python3/0529. Minesweeper.py
2,178
3.515625
4
class Solution: def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]: # if board[click[0]][click[1]] == 'M': # board[click[0]][click[1]] = 'X' # return board # directions = [(0,-1),(0,1),(-1,0),(1,0),(-1,-1),(-1,1),(1,-1),(1,1)] ...
71af4e58651e10faf5ff29fdc7cc48b45ed3471c
yang4978/LeetCode
/Python3/1302. Deepest Leaves Sum.py
729
3.703125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def deepestLeavesSum(self, root: TreeNode) -> int: sum_value = 0 temp = 0 stack = [(root,0)] while stack...
19f51a29cb79783ed9a0a9b5e5495fb16350a785
yang4978/LeetCode
/Python3/0214. Shortest Palindrome.py
1,082
3.515625
4
class Solution: # 中心扩散法 # def shortestPalindrome(self, s: str) -> str: if(s==""): return s l = len(s) for i in range(l): temp = s[l-1:l-i-1:-1] + s l_temp = l+i if(temp[:l_temp//2]==temp[l_temp-1:l_temp//2-1:-1] or temp[:l_temp//2]==temp[l...
6f3ecffda7c90d79322ab038fa9f178d3c0707c7
yang4978/LeetCode
/Python3/0865. Smallest Subtree with all the Deepest Nodes.py
714
3.90625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode: def height(node): if not node: return 0 ...
57e06a6decb8ccf90e11ac7bf935ed3b0e37df65
yang4978/LeetCode
/Python3/0234. Palindrome Linked List.py
1,855
3.71875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def isPalindrome(self, head: ListNode) -> bool: # res = [] # while head: # res.append(head.val) # head = head.next # ...
e9c538aa2c6735e5614f12c397bbde389c8b6ecb
yang4978/LeetCode
/Python3/0048. Rotate Image.py
879
3.734375
4
class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ # n = len(matrix) # k = 0 # while(k<n//2): # for times in range(n-2*k-1): # temp = matrix[k][k] # ...
11fba61b0bbdce9ce6b108067892a9b9a96d9499
yang4978/LeetCode
/Python3/0101. Symmetric Tree.py
1,047
3.984375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSymmetric(self, root: TreeNode) -> bool: queue = [root,root] while queue: r1 = queue.pop(0) ...
22327f478c167aa3e06ae39ee2aac76b4303507e
Bbenard/python-snippets
/Data_Search/json_files.py
1,417
3.859375
4
import json from pprint import pprint uid = input("Enter User ID: ") class UserData(object): """ Class to check the JSON file of user data, check if user id is an integer Store the json file in a variable and loop through use with filename as variable to load the json data and store in a vari...
66c033aa71f59194e22a89054896197aa2c42757
GowthamSingamsetti/Python-Practise
/rough10.py
899
4.25
4
# PYTHON program for bubble sort print("PYTHON PROGRAM FOR BUBBLE SORT TECHNIQUE (Ascending Order)") print("-"*70) list = [12,4,45,67,98,34] print("List before sorting" , list) for i in range(0,6): flag = 0 for j in range(0,5): if(list[j]>list[j+1]): temp = list[j] list...
f74a74fccc367e053009c67054da8d290e087767
GowthamSingamsetti/Python-Practise
/rough15.py
662
3.921875
4
graph = {'A': ['B','D','E'], 'B':['A','E','E'], 'C':['B','E','F','G'], 'D':['A','E'], 'E':['A','B','C','D','F'], 'F':['C','E','G'], 'G':['C','F']} # visit all the nodes of the graph using BFS def bfs_connected_component(graph,start): explored = [] ...
aa7ad779bb0d4afdc34a8ed22909172c58518fb0
GowthamSingamsetti/Python-Practise
/rough9.py
1,220
3.96875
4
def mean(numlist): no_of_eles = len(numlist) summ = sum(numlist) avg = summ / no_of_eles print("Mean for given set of numbers is : ", avg) return def median(numlist): numlist.sort() if (len(numlist) % 2 != 0): i = len(numlist) // 2 print("Median for given set of...
cf58f71d2ac959c21a300c91828a09e9227db6e6
GowthamSingamsetti/Python-Practise
/exp-18.py
133
3.75
4
numbers = [100, 20, 5, 15, 5] uniques = [] for i in numbers: if i not in uniques: uniques.append(i) print(uniques)
ea82fcdd3639fb35b94f608b1f27cca26304a4f4
GowthamSingamsetti/Python-Practise
/exp-33.py
364
3.671875
4
class Mammal: def __init__(self, name): self.name = name def walk(self): print(f"{self.name} can walk") class Dog(Mammal): def bark(self): print("It can bark.") class Cat(Mammal): pass dog1 = Dog("Tommy") dog1.walk() dog1.bark() cat1 = Cat("Sophie") ...
b26f795f05c5456c662c07731a3501f80eddf294
brand-clear/pywinscript
/winprint.py
2,285
3.5
4
""" pywinscript.winprint is a high-level win32print wrapper for physical printing. """ import win32api import win32print from config import printer_A, printer_B, printer_D class Printer(object): """Represents a physical printer. Parameters ---------- document : str Absolute path to printable document. papers...
79634513690698ec9a402274f09fef55a006075d
hudaoling/hudaoling_20200907
/Python全栈_老男孩Alex/7 面向对象编程/继承_学校.py
3,012
4.0625
4
# Author:Winnie Hu class Scholl(object): members=0 def __init__(self,name,addr): self.name=name self.addr=addr self.students=[]#初始化空列表,用于接收报名学生 self.staffs=[]#初始化空列表,用于接收教师 def enroll(self,stu_obj):#stu_obj某学生对象 print("为学员%s办理注册手续"%stu_obj.name) self.student...
ec54e2569435a24201e346f5a2eae9b7db8021eb
hudaoling/hudaoling_20200907
/Python全栈_老男孩Alex/5 生成器-迭代器-装饰器-内置方法/裴波那契.py
1,795
3.625
4
#裴波那契数列 # def fib(max):#形参max # n,a,b=0,0,1#变量赋值 # while n<max:#100次循环内 # print(b) # a,b=b,a+b# 初次赋值是a1=1(b0初始值),b1=0(a0初始值)+1(b0初始值)=1,二次赋值a2=1(b1),b2=(a1)+1(b1)=2 # n=n+1 # return 'done' # fib(100) #这是一个函数 #函数式列表生成器,只要有yield就是一个生成器,已经不是函数了 def fib(max):#形参max n,a,b=0,0...
cf8f65d4d28bdc98a8a7cc9cf2ce7d0453bfb980
hudaoling/hudaoling_20200907
/Python全栈_老男孩Alex/3-列表-字典-字符串-购物车/String_UseMethod.py
2,733
4.21875
4
# Author:Winnie Hu name="My Name is {name},She is a worker and She is {year} old" print(name.capitalize())#首字母 print(name.count("i")) print(name.center(50,"-")) #打印50个字符,不够用-补齐,并摆放中间 print(name.endswith("ker")) #判断是否以什么结尾 print(name.expandtabs(tabsize=30))# \ 把这个键转换成多少个空格 print(name.find("is")) #取字符的索引位置,从0开始计算 print...
a261a049f582f22e722ed10d5cffb44a2883e5b5
hudaoling/hudaoling_20200907
/Python全栈_老男孩Alex/2-For-While-Input-数据类型-变量/DataType_数据类型.py
3,608
4.15625
4
# Author:Winnie Hu 一、数字 2是一个整数的例子 3.23是浮点数的例子 type() #查看数据类型 1.int(整型) 在32位机器上,整数的位数为32位,取值范围-2**31~2*31-1 在64位机器上,整数的位数为64位,取值范围-2**63~2*63-1 2.long(长整型,大一些的整数) 长度没有指定宽度,如果整数发生溢出,python会自动将整数数据转换为长整型 3.float浮点数 浮点数用来处理实数,即带有小数的数字。 52.3E-4是浮点数的例子。E标记表示10的幂。在这里,52.3E-4表示52.3 *10**4 二、布尔值 真或假 1或0 三、string字符串 "hello...
29e7e1d222edafc4c2a4c229949848a004ae4285
hudaoling/hudaoling_20200907
/Python全栈_老男孩Alex/7 面向对象编程/静态方法-类方法-属性方法.py
2,048
4.21875
4
# Author:Winnie Hu #动态方法 class Dog(object): def __init__(self,name): self.name=name def eat(self,food): print("动态方法self.:","%s is eating %s"%(self.name,food)) d=Dog("jinmao") d.eat("baozi") #静态方法 class Dog(object): def __init__(self,name): self.name=name # 静态方法,实际上跟类没什么关系了,就可理...
11678f2bb9982e7b7bbb61bf326a3c94c04878dc
einelson/hand-detection
/example code/camera capture.py
5,058
3.53125
4
""" File: teach1.py (week 05) Tasks - Convert video stream to be grayscale - Create a circle mask and apply it to the video stream - Apply a mask file to the video stream usa-mask.jpg byui-logo.png - create a vide stream of differences from the camera - use gray scale - use absdiff() function """ """ Use this c...
5a87994d884876f9e909d0549e8bc7efc5e64b9f
hengrumay/100-women-flask-app
/helpers/makeDFfromJson.py
1,300
3.59375
4
def makeDFfromJson(ibm_out): """ Reformat Json output from IBM API call via Speech Recognition with relevant parameters as a pandaDataFrame --------------------------------------------------------------------------- ## Example use: # from makeDFfromJson import makeDFfromJson # DF0 = mak...
6ccdbdcc90fffe223051131e8b7cc1b2c5bb9341
vlytvynenko/lp
/lp_hw/ex8.py
780
4.28125
4
formatter = "{} {} {} {}" #Defined structure of formatter variable #Creating new string based on formatter structure with a new data print(formatter.format(1, 2, 3, 4)) #Creating new string based on formatter structure with a new data print(formatter.format('one', 'two', 'three', 'four')) #Creating new string based on...
da151fb58a835d22b3409332d68d72a430198604
sheffieldjordan/binarySearchTree
/BST.py
3,378
4.59375
5
#--------------------------------------------------------- # Morgan Jordan # morgan.jordan@berkeley.edu # Homework #3 # September 20, 2016 # BST.py # BST # --------------------------------------------------------- class Node: #Constructor Node() creates node def __init__(self,word): self.word = word #t...
738774b4756d730e942bcb8c88ec3801afe4b54c
legitalpha/Spartan
/Day_9_ques1_Russian_peasant_algo.py
285
4.125
4
a = int(input("Enter first number : ")) b = int(input("Enter second number : ")) count = 0 while a!=0: if a%2==1: count +=b b=b<<1 a=a>>1 if a%2==0: b=b<<1 a=a>>1 print("The product of first and second number is ",count)
1401557e5c71df2c239cf25bf9bcafa814ebd2d1
magik2art/DZ_10_Pavel_Mamaev
/task1.py
700
3.546875
4
from random import randint class Matrix: def __init__(self, my_list): self.my_list = my_list def __str__(self): for row in self.my_list: for i in row: print(f"{i:4}", end="") print("") return '' def __add__(self, other): for i in r...
029694ef897dc8242bfa416216994ade3f99df53
hilariusperdana/praxis-academy
/novice/01-04/soal1.py
267
3.640625
4
#soal no 1 a=2 b=5 print(int(a/b)) print(float(a/b)) #soal no 2 firstname='hilarius' lastname='perdana' print('Hello Praxis, saya',firstname,lastname,'! saya siap belajar enterprise python developer.') #soal no 3 p = 9.99999 q = 'the number: ' print('jawaban',q,p)
5753fc612bf24b08b9224b391385c9534fa4700c
hilariusperdana/praxis-academy
/novice/01-01/latihan/quicksort.py
505
3.640625
4
def QuickSort(A,mulai,akhir): if mulai<akhir: pindex=partition(A,mulai,akhir) QuickSort(A,mulai,pindex-1) QuickSort(A,pindex+1,akhir) def partition(A,mulai,akhir): pivot = A[akhir] pindex = mulai for i in range(mulai,akhir): if (A[i] <= pivot): A[i],A[pindex]...
1612c998d40aa89fa5cccdaf868496a84d139ec5
TangTT-xbb/python1116
/test_SSH/09-多线程.py
556
3.640625
4
import time from threading import Thread # 创建线程 def work(): print("当前线程") def sing(i): for x in range(i): print(f"当前进程号:{t1.name} 正在唱歌") time.sleep(1) def dance(): for x in range(5): print(f"当前进程号:{t2.name} 正在跳舞") time.sleep(1) t1 = Thread(target=sing, args=(4,...
7a45b823413cface7baea747a93611b71bae81eb
Valken32/Card-Games
/21cardgame.py
3,701
4.03125
4
import random ace = 1 jack = 11 queen = 12 king = 13 totalScore = 0 botTotalScore = 0 def cardConditions(): if cardNum or botCardNum == 1: print("ace") elif cardNum or botCardNum == 11: print("jack") elif cardNum or botCardNum == 12: print("queen") elif cardNum or b...
dc9666f2fa8bdd71a080e160d153a0d317c497ab
dgquintero/holbertonschool-machine_learning
/math/0x00-linear_algebra/3-flip_me_over.py
257
3.96875
4
#!/usr/bin/env python3 """function that transpose a matrix""" def matrix_transpose(matrix): """matrix transpose function""" r = [[0, 0, 0], [0, 0, 0]] m = matrix r = [[m[j][i] for j in range(len(m))]for i in range(len(m[0]))] return r
86d2c53c8f8c2444a71a561526384c909ecae90c
dgquintero/holbertonschool-machine_learning
/supervised_learning/0x03-optimization/1-normalize.py
427
3.921875
4
#!/usr/bin/env python3 """normalize function""" def normalize(X, m, s): """ normalizes (standardizes) a matrix Arguments: X: input to normalize shape(d, nx) d: number of data points nx: number of features m: the mean of all features of X shape(nx,) s: standa...
edbbed7b9a0ebeae3e1478b4988008deed3cee2e
dgquintero/holbertonschool-machine_learning
/math/0x03-probability/binomial.py
1,951
4.125
4
#!/usr/bin/env python3 """class Binomial that represents a Binomial distribution""" class Binomial(): """ Class Binomial that calls methos CDF PDF """ def __init__(self, data=None, n=1, p=0.5): """ Class Binomial that calls methos CDF PDF """ self.n = int(n) self.p = float(p) ...
61829caf238855994467336de51105891f86389e
dgquintero/holbertonschool-machine_learning
/supervised_learning/0x03-optimization/10-Adam.py
784
3.625
4
#!/usr/bin/env python3 """create_Adam_op function""" import tensorflow as tf def create_Adam_op(loss, alpha, beta1, beta2, epsilon): """ that training operation for a neural network in tensorflow using the Adam optimization algorithm Arguments: loss: is the loss of the network alpha: ...
5f078110c9b78997fbcaf7fd50dd4452bf6911a5
dgquintero/holbertonschool-machine_learning
/supervised_learning/0x05-regularization/1-l2_reg_gradient_descent.py
1,218
3.953125
4
#!/usr/bin/env python3 """ l2_reg_gradient_descent function""" import numpy as np def l2_reg_gradient_descent(Y, weights, cache, alpha, lambtha, L): """ calculates the cost of a neural network with L2 regularization Arguments: Y: Correct labels for the data shape(classes, m) cache: dictio...
32178b1696d71175cfc45a73e0e0f78c3a62d5b2
dgquintero/holbertonschool-machine_learning
/math/0x04-convolutions_and_pooling/4-convolve_channels.py
1,824
3.65625
4
#!/usr/bin/env python3 """ convolve_grayscale function""" import numpy as np def convolve_channels(images, kernel, padding='same', stride=(1, 1)): """that performs a convolution on images with channels Arguments: images: shape (m, h, w) containing multiple grayscale images m: the number of...
e682a01f28a43fa2e12ea8bede1518dc68de528c
Coder-Liuu/Lesson_design_for_Freshmen
/Python/Python-枚举法/main.py
1,215
3.671875
4
import math def car(): print("罪犯的车牌号为:",end="") for a1 in range(0,10): for a2 in range(0,10): if(a1==a2): for a3 in range(0,10): for a4 in range(0,10): if(a3==a4 and a1!=a3): a = a1*1000+a2*100+a...
7bfc92f730e822a2c639b4605c8d330593184ebd
buzsb/junior_test
/max_sum_sub_list.py
579
3.578125
4
def max_sum_sub_list(array): if array == []: raise ValueError temporary_sum = max_sum = array[0] i = 0 start = finish = 0 for j in range(1, len(array)): if array[j] > (temporary_sum + array[j]): temporary_sum = array[j] i = j else: tempora...
d5491b784640d17450cbf52b9ecd8019f5b630a7
kvanishree/AIML-LetsUpgrade
/Day4.py
1,393
4.25
4
#!/usr/bin/env python # coding: utf-8 # In[8]: #Q1 print("enter the operation to perform") a=input() if(a=='+'): c=(3+2j)+(5+4j) print(c) elif(a=='-'): c=(3+2j)-(5+4j) print(c) elif(a=='*'): c=(3+2j)*(5+4j) print(c) elif(a=='/'): c=(3+2j)/(5+4j) print(c) elif(a=='//'): print("floo...
cafa13ec431741821f02757d8afca267a49c5aa3
sidrap1234/lab3
/cal01.py
88
3.75
4
# calculator in python v01 def add(num1,num2): return num1 + num2 #main print(add(5,3))
1326c22ba6a7b4e403fc6f130b089ec7cdacd472
nk4456542/Password-Checker
/Password Checker.py
4,298
4.03125
4
''' Author : Zaheer Abbas Description : This python script checks if your password has been pwned or not This file contains three main functions. 1. main_file(filename) -> Run this function if you have a lot of passwords stored in a file. You should give the filename as command line argument and also the file must be ...
95704790c99c31725d89bb8f3ad607bc14647c10
liar666/RedDigits
/PyDigits/reddigits/DigitModel.py
2,795
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Class encapsulating Digits """ import matplotlib.pyplot as plt # for displaying images import numpy as np # ªor arrays from PIL import Image # To tag the images from PIL import ImageDraw from Utils import Utils class DigitModel: RIGHT = "RIGHT" ...
c217f28848327a1770a64a26a16d89c685a9f59a
tsubhadarshy/TrainingSDET
/Python/Activity8.py
474
4.0625
4
# Input list of numbers numList = list(input("Enter a sequence of comma separated values: ").split(",")) print("Input list is ", numList) # Get first element in list firstElement = numList[0] # Get last element in list lastElement = numList[-1] # Check if first and last element are equal if (firstElement ==...
2f84d2a9e6ca9f3c850c1b523538d83bb772a5fe
gaurab123/DataQuest
/02_DataAnalysis&Visualization/04_DataCleaning/05_ChallengeCleaningData/05_ConsolidatingDeaths_Cheet.py
1,075
3.890625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Oct 20 11:41:51 2017 @author: kkite """ import pandas as pd import matplotlib.pyplot as plt pd.options.mode.chained_assignment = None # default='warn' def clean_deaths(row): num_deaths = 0 columns = ['Death1', 'Death2', 'Death3', 'Death4', '...
0aa7e42198c23433e721727e0828c14873a812cf
gaurab123/DataQuest
/06_MachineLearning/03_LinearAlgebraForMachineLearning/04_SolutionSets/02_InconsistentSystems.py
338
3.53125
4
# page 29 in the hand written notes for context import numpy as np import matplotlib.pyplot as plt import sympy fig = plt.figure() X,y1,y2 = sympy.symbols('X y1 y2') X = np.linspace(0, 20, 1000) y1= -2*X+(5/4) plt.plot(X,y1,label='y=-2x+5/4') y2= -2*X+(5/2) plt.plot(X,y2,label='y=-2x+5/2') plt.le...
2c87cbf2ca1d5a451ca5cfa7ed8866e1cedcba6f
gaurab123/DataQuest
/04_WorkingWithDataSources/01_APIsAndWebScraping/03_Challenge_WorkingWithTheRedditAPI/05_GettingTheMostUpvotedComment.py
1,846
3.578125
4
import requests import pandas as pd import pprint pp = pprint.PrettyPrinter(indent=4,width=80,depth=20) # make get request to get pythons top comments from the reddit API headers = {"Authorization": "bearer 13426216-4U1ckno9J5AiK72VRbpEeBaMSKk", "User-Agent": "Dataquest/1.0"} params = {"t": "day"} response =...
fa50891b13199682b4f1bc690c28d8a4e567c771
gaurab123/DataQuest
/06_MachineLearning/02_CalculusForML/02_UnderstandingLimits/07_UndefinedLimitToDefinedLimit.py
260
3.53125
4
# See page 3 from math refresher notebook for hand done math steps # There we use direct substitution to arrive at the answer of -3 import sympy as s x2,y = s.symbols('x2 y') y = -x2 limit_four = s.limit(y, x2, 3) print('limit_four:', limit_four)
dcbe69d5095815419df2130635fca147b87a0c74
gaurab123/DataQuest
/02_DataAnalysis&Visualization/01_DataAnalysisWithPandas-Intermediate/05_WorkingWithMissingData/11_UsingColumnIndexes.py
1,692
4.15625
4
import pandas as pd titanic_survival = pd.read_csv('titanic_survival.csv') # Drop all columns in titanic_survival that have missing values and assign the result to drop_na_columns. drop_na_columns = titanic_survival.dropna(axis=1, how='any') # Drop all rows in titanic_survival where the columns "age" or "sex"...
d989a7155779e0da90d703c9958f78fa3c2c19dc
gaurab123/DataQuest
/02_DataAnalysis&Visualization/01_DataAnalysisWithPandas-Intermediate/05_WorkingWithMissingData/15_CalculatingSurvivalPercentageByAgeGroup.py
1,177
3.953125
4
import pandas as pd import numpy as np # Create a function that returns the string "minor" if # someone is under 18, "adult" if they are equal to or # over 18, and "unknown" if their age is null def age_type(row): age = row['age'] if pd.isnull(age): return 'unknown' elif age < 18: return 'minor' el...
e8c2296b901945df30295f140fb33be93f1f37d3
gaurab123/DataQuest
/02_DataAnalysis&Visualization/01_DataAnalysisWithPandas-Intermediate/08_PandasInternalsDataframes/03_UsingCustomIndexes.py
681
3.765625
4
import pandas as pd fandango = pd.read_csv('fandango_score_comparison.csv') # Use the pandas dataframe method set_index to assign the FILM # column as the custom index for the dataframe. Also, specify # that we don't want to drop the FILM column from the dataframe. # We want to keep the original dataframe, so ...
d7955c8a4e0491be0ee67c15c2ab14dd4c423fef
gaurab123/DataQuest
/02_DataAnalysis&Visualization/01_DataAnalysisWithPandas-Intermediate/05_WorkingWithMissingData/12_ReindexingRows.py
1,166
4.09375
4
import pandas as pd titanic_survival = pd.read_csv('titanic_survival.csv') # Drop all columns in titanic_survival that have missing values and assign the result to drop_na_columns. drop_na_columns = titanic_survival.dropna(axis=1, how='any') # Drop all rows in titanic_survival where the columns "age" or "sex"...
5f0efffc670b59f265f4f116296eeacb7357e0ec
gaurab123/DataQuest
/06_MachineLearning/04_LinearRegressionForMachineLearning/02_FeatureSelection/01_MissingValues.py
960
3.625
4
import pandas as pd data = pd.read_csv('AmesHousing.txt', delimiter='\t') train = data.iloc[:1460] test = data.iloc[1460:] target = 'SalePrice' # Selects/excludes columns based upon their dtypes. Super handy, I did this manually in the last chapter :( numerical_train = train.select_dtypes(include=['int64', 'f...
d68f1dc1a7b8f16102579df40bc60c44fe2a0e7c
gaurab123/DataQuest
/02_DataAnalysis&Visualization/01_DataAnalysisWithPandas-Intermediate/08_PandasInternalsDataframes/01_SharedIndexes.py
524
3.640625
4
import pandas as pd fandango = pd.read_csv('fandango_score_comparison.csv') # Use the head method to return the first two rows in the dataframe, then display them with the print function. print('\nPeak at 1st 2 rows using head\n') print(fandango.head(2)) # Use the index attribute to return the index of the d...
f994742fb7c6f439cd6d42563855fc7d0fc14f18
gaurab123/DataQuest
/04_WorkingWithDataSources/01_APIsAndWebScraping/04_WebScraping/05_ElementIDs.py
720
3.578125
4
import requests from bs4 import BeautifulSoup # Get the page content and set up a new parser. response = requests.get("http://dataquestio.github.io/web-scraping-pages/simple_ids.html") content = response.content parser = BeautifulSoup(content, 'html.parser') # Pass in the ID attribute to only get the element ...
47632d2e510e7a9770fc0eb3ec464987425b48b3
gaurab123/DataQuest
/04_WorkingWithDataSources/01_APIsAndWebScraping/03_Challenge_WorkingWithTheRedditAPI/04_GettingPostComments.py
1,091
3.578125
4
import requests import pandas as pd # make get request to get pythons top comments from the reddit API headers = {"Authorization": "bearer 13426216-4U1ckno9J5AiK72VRbpEeBaMSKk", "User-Agent": "Dataquest/1.0"} params = {"t": "day"} response = requests.get("https://oauth.reddit.com/r/python/top", headers=headers, ...
87dd7e960b690e4048727b878a29d140b00e22ce
gaurab123/DataQuest
/04_WorkingWithDataSources/04_SQLAndDatabases_Advanced/01_IntroductionToIndexing/09_AllTogetherNow.py
822
3.546875
4
import sqlite3 conn = sqlite3.connect("factbook.db") q5 = 'EXPLAIN QUERY PLAN SELECT * FROM facts WHERE population > 10000;' query_plan_five = conn.execute(q5).fetchall() print('query plan 5') print(query_plan_five) conn.execute("CREATE INDEX IF NOT EXISTS population_idx ON facts(population);") print("\nCR...
0e770842ddb7c22a02abb4b942a7c8f6e4aac72e
gaurab123/DataQuest
/02_DataAnalysis&Visualization/03_StorytellingThroughDataVisualization/01_ImporvingPlotAesthetics/04_VisualizingTheGenderGap.py
735
3.671875
4
# Generate 2 line charts on the same figure: # 1) Visualizes the percentages of Biology degrees awarded to women over time # 2) Visualizes the percentages of Biology degrees awarded to men over time. import pandas as pd import matplotlib.pyplot as plt women_degrees = pd.read_csv('percent-bachelors-degrees-wome...
5e51c93b37a493cd0b97bcfde597f4e4eee9d313
gaurab123/DataQuest
/06_MachineLearning/04_LinearRegressionForMachineLearning/01_TheLinearRegressionModel/03_SimpleLinearRegression.py
1,577
3.765625
4
# Generate 3 scatter plots in the same column: # The first plot should plot the Garage Area column on the X-axis against the SalePrice column on the y-axis. # The second one should plot the Gr Liv Area column on the X-axis against the SalePrice column on the y-axis. # The third one should plot the Overall Cond colum...
1004cc41fa3aa46f4e9b58acf9f5dee1579dfd7e
gaurab123/DataQuest
/06_MachineLearning/02_CalculusForML/03_FindingExtremePoints/08_PracticingFindingExtremeValues.py
752
3.78125
4
# See page 8 from math refresher notebook for hand done math steps import sympy rel_min = [] rel_max = [] X,y = sympy.symbols('X y') extreme_one = 0 extreme_two = 2/3 print('extreme_one:', extreme_one) X = extreme_one - 0.001 start_slope = 3*X**2 - 2*X print('start_slope:', start_slope) X = extre...
3ceaa37847341f9d3cf7e527dd1d7b98cdd7abeb
approximata/edx_mit_cs
/week_01/findabc.py
597
3.796875
4
s = 'abcdefghijklmnopqrstuvwxyz' longest_abc_words = [] current_word = '' for i in range(len(s)-1): if s[i] <= s[i+1]: current_word += s[i] if i == len(s)-2 and s[-1] >= s[i]: current_word += s[-1] else: current_word += s[i] longest_abc_words.append(current_word) ...
a2d5f9a89b7789c168118e88658a3c6f2b8f73ae
approximata/edx_mit_cs
/final/longest_nunmber.py
2,075
4.0625
4
def longest_run(L): """ Assumes L is a list of integers containing at least 2 elements. Finds the longest run of numbers in L, where the longest run can either be monotonically increasing or monotonically decreasing. In case of a tie for the longest run, choose the longest run that occurs first...
4ffcdeb951858c1f1981ef40812b078d2f58ec6f
approximata/edx_mit_cs
/week_02/problem_set2/problem2.py
662
3.515625
4
#!/usr/bin/python3 def pay_debt_off_pr(balance, annualInterestRate): monthly_intrest = annualInterestRate / 12 fixed_monthly_pay = 0 original_balance = balance while balance > 0: month = 0 fixed_monthly_pay += 10 balance = original_balance print(fixed_monthly_pay, 'fixed...
62074620f90873e8577b48af2422c12b6e87c040
approximata/edx_mit_cs
/midtermexam/problem7.py
484
3.765625
4
#!/usr/bin/python3 def f(a, b): return a + b def dict_interdiff(d1, d2): intersect = {} difference = {} for key1 in d1: if key1 in d2: intersect[key1] = f(d1[key1], d2[key1]) del d2[key1] else: difference[key1] = d1[key1] for key2 in d2: ...
5a29550eb1b08000b460873abfbc9bf3b5b7ed3d
alwinsheejoy/College
/SNIPPETS/Python/strings/strings.py
381
4.1875
4
str_name = 'Python for Beginners' #012356789 print(str_name[0]) # P print(str_name[-1]) # s print(str_name[0:3]) # 0 to 2 Pyt print(str_name[0:]) # 0 to end(full) Python for Beginners print(str_name[:5]) # 0 to 4 Pytho print(str_name[:]) # [0:end] (full) - copy/clone a string. copied_str = str_name[:] #...
1ef5160d59ad6ee3ea50b67b663decafabe66441
gowshalinirajalingam/Churn-Prediction
/Churn prediction classification.py
13,600
3.8125
4
# # We aim to accomplist the following for this study: # # 1.Identify and visualize which factors contribute to customer churn: # # 2.Build a prediction model that will perform the following: # # =>Classify if a customer is going to churn or not # =>Preferably and based o...
934b6d7380894f97cd0c7420c7edf31a1767ce0e
ghawk0/ai-final-proj
/schedule.py
660
3.96875
4
# round robin algorithm for getting pairings of teams def robin(teams, matchups=None): if len(teams) % 2: teams.append(None) count = len(teams) matchups = matchups or (count-1) half = count/2 schedule = [] for round in range(matchups): pairs = [] for i in range(half): ...
45031662df9be1dafbac90323ea6b977949328f5
Jerwinprabu/practice
/reversepolish.py
596
4.34375
4
#!/usr/bin/python """ reverse polish notation evaluator Functions that define the operators and how to evaluate them. This example assumes binary operators, but this is easy to extend. """ ops = { "+" : (lambda a, b: a + b), "-" : (lambda a, b: a - b), "*" : (lambda a, b: a * b) } def eval(tokens): stack = [...
f8c4a3da8fa11ea8dda655f5e1aa03e8484208e5
Jerwinprabu/practice
/reverse.py
439
4
4
#!/usr/bin/python def reverse(arr): if not arr: return i, j = 0, len(arr)-1 while j > i: arr[i], arr[j] = arr[j], arr[i] i+=1 j-=1 return arr def rotate(arr, n): a = arr[:] a = reverse(a) a[n:] = reverse(a[n:]) a[:n] = reverse(a[:n]) return a def test(): ...
c195247fac44336cb05a705d803ed3070839eead
Jerwinprabu/practice
/subsets.py
889
3.796875
4
#!/usr/bin/python """ find all subsets of a set """ import random def subsets(array): if len(array): yield [array[0]] for subset in subsets(array[1:]): yield subset yield subset + [array[0]] def genadj(count): return count * "()" def genrec(count): for p in paren(...
d18d10a6fe1ce761b70b798e27754f497579011f
kengo-0805/pythonPractice
/day3.py
520
3.953125
4
''' # 問題3-1 x = input("1つ目の数字:") y = input("2つ目の数字:") s1 = float(x) s2 = float(y) if s2 == 0: print("0での割り算はできません") else: print("足し算:{} 引き算:{} 掛け算:{} 割り算:{}".format(s1+s2,s1-s2,s1*s2,s1/s2)) ''' # 問題3-2 text = input("文字を入力してください:") count = len(text) if count < 5: print("短い文章") elif 5 < count < 20: prin...
674ad6981f92ca3d53b1cc9a44d602bb28b76e4f
lcar99/URI
/Python 3/1018.py
353
3.65625
4
d = int (input ()) print (d) print (d//100 , "nota(s) de R$ 100,00") d = d % 100 print (d//50 , "nota(s) de R$ 50,00") d = d % 50 print (d//20 , "nota(s) de R$ 20,00") d = d % 20 print (d//10 , "nota(s) de R$ 10,00") d = d % 10 print (d//5 , "nota(s) de R$ 5,00") d = d % 5 print (d//2 , "nota(s) de R$ 2,00") d = d % 2 ...
5e9ebc5cbdad88b893dd0e537f54f67b132868ed
LamLauChiu/Tensorflow_Learning
/TextClassification/textClassification.py
10,464
4.21875
4
""" This notebook classifies movie reviews as positive or negative using the text of the review. This is an example of binary—or two-class—classification, an important and widely applicable kind of machine learning problem. We'll use the IMDB dataset that contains the text of 50,000 movie reviews from the Internet Mov...
dd172806613ef476404aa4771dec704bb411281c
durveshpathak/Udacity_Data_structure_III
/problem_5.py
2,036
3.546875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Oct 27 18:03:18 2019 @author: durvesh """ class TrieNode(): def __init__(self): self.is_word = False self.children = {} def insert(self, char): if char not in self.children: self.children[char] = Tri...
8c7bc323fac2fe5a512c70597af0f99492522323
Rutvik2610/Python-Playground
/Mile to Km Converter using Tkinter/main.py
668
3.921875
4
from tkinter import * def convert(): miles = float(miles_input.get()) km = round(miles * 1.609) km_output.config(text=f"{km}") window = Tk() window.title("Mile to Km Converter") window.config(padx=20, pady=20) miles_input = Entry(width=7) miles_input.grid(row=0, column=1) miles_input.insert(END, string...
768377a03d93071676d31e1f6ee93f9d6b9e8c8c
Krysta1/Offer-Java
/src/leetcode/116. Populating Next Right Pointers in Each Node.py
1,931
3.84375
4
# My solution """ # Definition for a Node. class Node(object): def __init__(self, val=0, left=None, right=None, next=None): self.val = val self.left = left self.right = right self.next = next """ class Solution(object): def connect(self, root): """ :type root: N...
5f76999608f0d7951f8b765ba07114542d975b19
Krysta1/Offer-Java
/src/leetcode/111. Minimum Depth of Binary Tree.py
1,853
3.859375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def minDepth(self, root): """ :type root: TreeNode :rtype: int ...
f6ddb9c5c6a5f76958ac9f732192e80f438d9b41
ataicher/learn_to_code
/careeCup/#q17.py#
1,031
3.875
4
#!/usr/bin/python -tt import sys import numpy as np def set_zero_rows_cols(M,m,n): nonZeroCols = range(n) zeroRows = []; zeroCols = [] newZeroRow = False for i in range(m): j = 0 while j < len(nonZeroCols): cnt += 1 if M[i,nonZeroCols[j]] == 0: zeroRows.append(i); zeroCols.append...
c5363e8be7c3e46cd35561d83880c3162f6ece0f
ataicher/learn_to_code
/careeCup/q14.py~
911
4.3125
4
#!/usr/bin/python -tt import sys def isAnagram(S1,S2): # remove white space S1 = S1.replace(' ',''); S2 = S2.replace(' ','') # check the string lengths are identical if len(S1) != len(S2): return False # set strings to lower case S1 = S1.lower(); S2 = S2.lower() # sort strings S1 = sorted(S1); S2 ...
389269b6491879b987a72d5d907e49f315be8faa
ataicher/learn_to_code
/careeCup/make_change.py
426
3.703125
4
#!/usr/bin/python -tt import sys import time def make_change(n,d): if d == 25: n_d = 10 elif d == 10: n_d = 5 elif d == 5: n_d = 1 else: return 1 ways = 0 for i in range(n/d+1): ways += make_change(n-i*d,n_d) return ways def main(): n = int(sys.argv[1]) print make_change(n,25...
9317aaa0cb94a12b89f6960525791598088003d6
HeavenRicks/dto
/primary.py
2,273
4.46875
4
#author: <author here> # date: <date here> # --------------- Section 1 --------------- # # ---------- Integers and Floats ---------- # # you may use floats or integers for these operations, it is at your discretion # addition # instructions # 1 - create a print statement that prints the sum of two numbers # ...
e964bf6249b52ab72b188dcc18cb4f73b915c6e2
PropeReferio/practice-exercises
/random_exercises/GuessNumberHiLow.py
621
4.03125
4
# From Intro to Python Crash Course, Eric Matthes def guess(): print("I'm thinking of a number between 1 and 99.") import random num = random.randint(1,100) g = int(input("Guess!")) while g != num: if g > num: print("Nope, you're too high! Try again.") else: ...
f1f2b09a5a7d9453ee9ca98f74d12f73e75a182a
PropeReferio/practice-exercises
/important-concepts/get_digit.py
823
3.8125
4
import math class Solution: def get_digit(self, x: int, dig: int) -> int: '''Takes an int an a digit as input, outputs the value of said digit.''' return x // 10 ** dig % 10 # First floor division by 10 for 10's place, # 100 for 100's place, etc (puts 100's place digit in 1's place)...
9c4378edfdb41a942286830610d4bf2c24d2535f
PropeReferio/practice-exercises
/daily-coding-problem/dcp_10.py
266
3.71875
4
#This problem was asked by Apple. #Implement a job scheduler which takes in a function f and an integer n, # and calls f after n milliseconds. import time def scheduler(func, n): time.sleep(n/1000) f() def f(): print('Do stuff') scheduler(f, 5000)
07439e13efd7e16d993733605018fd0624c65820
PropeReferio/practice-exercises
/random_exercises/alien_colors.py
339
3.828125
4
# Ex 5-3 from Python Crash Course alien_color = 'red' points = 0 if alien_color == 'green': points += 5 print(f"Player 1 earned {points} points.") elif alien_color == 'yellow': points += 10 print(f"Player 1 earned {points} points.") elif alien_color == 'red': points += 15 print(f"Player 1 earned...
796c9387dce8f55b1a2a7efd90438bdff7eee5c8
PropeReferio/practice-exercises
/random_exercises/filter_with_lambda_enumerate.py
514
3.59375
4
def multiple_of_index(arr): print(arr) for i, x in enumerate(arr): print(i,x) def divisible_by_index(lst): for i, x in enumerate(lst): if not x % i: return True else: return False #return list(filter(divisible_by_index, arr[1:])) ...
89a8e2146e366ce54617134d314e68d81c6b340a
PropeReferio/practice-exercises
/random_exercises/cars.py
282
3.890625
4
def car_info(manu, model, **car_info): """Creates a dictionary with info about a car that can receive an arbitrary number of k,v pairs""" car = {} car['manufacturer'] = manu car['model'] = model for k, v in car_info.items(): car[k] = v return car
93dedb445a3623c144f6b064941685eea52144d8
PropeReferio/practice-exercises
/random_exercises/opportunity_costs.py
5,771
4.125
4
# A program I made to compare my lifetime earnings in my current career, and #after having taken a bootcamp, or going to college, taking into account #cost of bootcamp/school and the time spent not making money. current_age = float(input("How old are you? ")) retire_age = int(input("At what age do you expect to retire...
2c4c928322977ee0f99b7bfe4a97728e09402656
PropeReferio/practice-exercises
/random_exercises/temp_converter.py
586
4.28125
4
unit = input("Fahrenheit or Celsius?") try_again = True while try_again == True: if unit == "Fahrenheit": f = int(input("How many degrees Fahrenheit?")) c = f / 9 * 5 - 32 / 9 * 5 print (f"{f} degrees Fahrenheit is {c} degrees Celsius.") try_again = False elif unit == "Celsius"...
25cc7ac225f74fd71ba79e365a251a2daf83aeb7
PropeReferio/practice-exercises
/random_exercises/rand_pass.py
730
3.8125
4
# Ex 16 from practicepython.org Write a password generator in Python. Be #creative with how you generate passwords - strong passwords have a mix # of lowercase letters, uppercase letters, numbers, and symbols. The # passwords should be random, generating a new password every time the # user asks for a new password....
7b8aa1806a0084dfd6e189720fc10131d0e0b1b1
PropeReferio/practice-exercises
/random_exercises/fave_fruits.py
438
3.96875
4
# Ex 5-7 from Python Crash Course faves = ["Mangoes", "Papayas", "Maracuya"] if "bananas" not in faves: print("You don't like bananas?") if "mangoes".title() in faves: print("Yeah... mangoes are delish!") if "papayas".title() in faves: print("Papayas have a nice blend of flavors.") if "Maracuya" in faves:...
849c615ac2f77f6356650311deea9da6c32952bf
andrearus-dev/shopping_list
/myattempt.py
1,719
4.1875
4
from tkinter import * from tkinter.font import Font window = Tk() window.title('Shopping List') window.geometry("400x800") window.configure(bg="#2EAD5C") bigFont = Font(size=20, weight="bold") heading1 = Label(window, text=" Food Glorious Food \n Shopping List", bg="#2EAD5C", fg="#fff", font=bigFo...
74f7e45ab5fc619715f5e530b6790c65c51a3767
caiooliveirac/Jogo-da-Forca
/core.py
554
3.53125
4
#Modelo de criação de diferentes arquivos txt com dificuldades diferentes baseados numa lista arquivo = open('palavras2.txt',mode='r',encoding='utf8') arquivo2 = open('palavras3.txt',mode='r',encoding='utf8') todas = [] nivel = [] for linha in arquivo: linha.strip() todas.append(linha) for palavra in arquivo2...
66c823e68f5362768970826ee380e58da07b57d2
jamesspearsv/cs50
/pset6/mario/more/mario.py
648
4.03125
4
from cs50 import get_int def main(): h = 0 while h < 1 or h > 8: h = get_int("Height: ") printPyramid(h) # Function definitions def printPyramid(h): for i in range(h, 0, -1): # Print left half for j in range(h): if j < i-1: print(" ", end="") ...
026dc30173ab7427f744b000f55558ffc19099e8
glaxur/Python.Projects
/guess_game_fun.py
834
4.21875
4
""" guessing game using a function """ import random computers_number = random.randint(1,100) PROMPT = "What is your guess?" def do_guess_round(): """Choose a random number,ask user for a guess check whether the guess is true and repeat whether the user is correct""" computers_number = rand...
19c763e647a12c9b697005354a86de78726e08b7
lukechn99/leetcode
/nDistinct.py
572
3.828125
4
# given a string, find the number of substrings that have n distinct characters # use sliding window def distinct(string, ptr1, ptr2): pass def nDistinct(string, n): ptr1 = 0 ptr2 = n number_distinct = 0 while ptr1 < len(string) - n: while ptr2 < len(string): if distinct(st...
d1a7e7a1efd779623129ce86fa8237e490690b4b
lukechn99/leetcode
/traverse.py
264
3.5625
4
import os def traverse(dir): print(dir) tempcwd = os.getcwd() if os.path.isdir(os.path.join(tempcwd, dir)): for d in os.listdir(os.path.join(tempcwd, dir)): os.chdir(os.path.join(tempcwd, dir)) traverse(d) os.chdir(tempcwd) traverse(".")
4e9a3cb0737ffd797c2231646f57d6f00a14b4e9
lukechn99/leetcode
/pleasePassTheCodedMessages.py
2,429
3.984375
4
# Please Pass the Coded Messages # ============================== # You need to pass a message to the bunny prisoners, but to avoid detection, the code you agreed # to use is... obscure, to say the least. The bunnies are given food on standard-issue prison # plates that are stamped with the numbers 0-9 for easier...
6ff855754a5b040e7b46749ce8a68a90e15a389a
lukechn99/leetcode
/count_clicks.py
3,129
3.703125
4
''' You are in charge of a display advertising program. Your ads are displayed on websites all over the internet. You have some CSV input data that counts how many times that users have clicked on an ad on each individual domain. Every line consists of a click count and a domain name, like this: counts = [ "900,google...
fc3bd6d939a85c3cee0f57229bd9bbdcd4da9be0
lukechn99/leetcode
/removeN.py
822
3.75
4
def removeEven (list): for i in list: if i % 2 == 0: list.remove(i) return list list = [1, 2, 3, 4, 5, 6, 7, 8] print(removeEven(list)) def removeMultTwo (n): list = [] for i in range(2, n+1): list.append(i) for p in list: # p starts as 2 # multiplier = 2 # multiplier = 3 # ... for multiplier in ...
46f70133d8fc36aa8c21c51ba8cd35efd18fcfc7
MenggeGeng/FE595HW4
/hw4.py
1,520
4.1875
4
#part 1: Assume the data in the Boston Housing data set fits a linear model. #When fit, how much impact does each factor have on the value of a house in Boston? #Display these results from greatest to least. from sklearn.datasets import load_boston from sklearn.linear_model import LinearRegression import matpl...
256c69199c1891d4c678824e59db2b80b69e3aa2
sangianpatrick/hacktiv8-python-datascience
/day_01/task5.py
273
3.859375
4
#pesanan orderan = list() order = input("Masukkan pesanan pertama: \n") orderan.append(order) order = input("Masukkan pesanan kedua: \n") orderan.append(order) order = input("Masukkan pesanan ketiga: \n") orderan.append(order) print("Pesanan anda: \n") print(orderan)