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
05d3835f466737814bb792147e8d7b34a28d912f
qiqi06/python_test
/python/static_factory_method.py
1,038
4.1875
4
#-*- coding: utf-8 -*- """ 练习简单工厂模式 """ #建立一工厂类,要用是,再实例化它的生产水果方法, class Factory(object): def creatFruit(self, fruit): if fruit == "apple": return Apple(fruit, "red") elif fruit == "banana": return Banana(fruit, "yellow") class Fruit(object): def __init__(self, name, ...
bf1579ed5e6abab53aa502637d8be30591fef51a
sdurgut/ToyProjects
/NetflixMovieRecommendationSystem/testProject2Phase1a.py
2,066
3.59375
4
''' >>> userList = createUserList() >>> len(userList) 943 >>> userList[10]["occupation"] 'other' >>> sorted(userList[55].values()) [25, '46260', 'M', 'librarian'] >>> len([x for x in userList if x["gender"]=="F"]) 273 >>> movieList = createMovieList() >>> len(movieList) 1682 >>> movieList[27]["title"] 'Apollo 13 (1995)...
c056c7e6e90f54a6a42b7a7d5c408c749debffed
michaszo18/python-
/serdnio_zaawansowany/sekcja_1/funkcja_id_operator_is.py
1,399
4
4
a = "hello world" b = a print(a is b) print(a == b) print(id(a), id(b)) b += "!" print(a is b) print(a == b) print(id(a), id(b)) b = b[:-1] print(a is b) print(a == b) print(id(a), id(b)) a = 1 b = a print(a is b) print(a == b) print(id(a), id(b)) b += 1 print(a is b) print(a == b) print(id(a), id(b)) b -= 1 print(a i...
f98a82205815d1acef54f565f03bfafe1df4f0aa
mertcankurt/temizlik_robotu_simulasyonu
/evarobotmove_gazebo/scripts/Interface/Database.py
583
4.0625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import sqlite3 def createTable(): connection = sqlite3.connect('login.db') connection.execute("CREATE TABLE USERS(USERNAME TEXT NOT NULL,EMAIL TEXT,PASSWORD TEXT)") connection.execute("INSERT INTO USERS VALUES(?,?,?)",('motar','motar@gmail.com','motar')) ...
478ea10daafffde5120ff8962eba92c173cd1ade
nosy0411/Object_Oriented_Programming
/homework2/example.py
285
3.546875
4
# import turtle # # t=turtle.Turtle() # # for i in range(5): # # t.forward(150) # # t.right(144) # # turtle.done() # spiral = turtle.Turtle() # for i in range(20): # spiral.forward(i*20) # spiral.right(144) # turtle.done() # import turtle # pen = turtle.Turtle()
e3c32038f58505113c4477596d1708390c510d98
dgriffis/autocomplete
/MyAutoComplete.py
3,298
4.15625
4
#!/usr/bin/env python import sys class Node: def __init__(self): #establish node properties: #are we at a word? self.isaWord = False #Hash that contains all of our keys self.keyStore = {} def add_item(self, string): #Method to build out Trie #This is do...
deae850e32102c9f22d108c817cfd69eebd4344f
szzhe/Python
/ActualCombat/TablePrint.py
854
4.28125
4
tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] # 要求输出如下: # apples Alice dogs # oranges Bob cats # cherries Carol moose # banana David goose def printTable(data): str_data = '' ...
54033a39aaf84badb53bb8266b6f882ca5d5a96c
christophemcguinness/The-Art-of-Doing-Code-40-Challenging-Python-Programs-Today
/Grocery_List/main.py
697
3.8125
4
def remove_smallest(numbers): y = numbers if len(numbers) == 0: return y , NotImplementedError("Wrong result for {0}".format(numbers)) y = numbers y.remove(min(numbers)) return y, NotImplementedError("Wrong result for {0}".format(numbers)) print(remove_smallest([1, 2, 3, 4, 5])) # , [2,...
91308a237cd5b5ac06c0c26d67f8dd1795819687
christophemcguinness/The-Art-of-Doing-Code-40-Challenging-Python-Programs-Today
/BinaryHexadecimalConversion/main.py
1,164
4.03125
4
print("\n:: Welcome to the Binary/Hexadecimal Converter App ::") computeCounter = int(input("\nCompute binary and hexadecimal value up to the following decimal number: ")) dataLists = [] for nums in range(computeCounter+1): dataLists.append([nums, bin(nums), hex(nums)]) print(":: Generating Lists....complete! ...
30ad077dc68f5b4f369d146dd278be4d69c89fa9
christophemcguinness/The-Art-of-Doing-Code-40-Challenging-Python-Programs-Today
/GuessMyNumberApp/main.py
879
4.09375
4
from random import randint print(":: Welcome to the Guess My Number App ::\n") name = input("Please input your name:\n") number = randint(1, 20) print("We the computer are thinking of a number between 1 - 20") print("You have 5 tries to guess the number before we blow you up. Choose wisely\n") for x in range(1,6):...
52a4a2e5afcf1f190f75dc69e38ef404e392be79
rudyardrichter/globus-automate-client
/globus_automate_client/cli/callbacks.py
6,310
3.5625
4
import json import os import pathlib from typing import AbstractSet, List from urllib.parse import urlparse from uuid import UUID import typer import yaml def url_validator_callback(url: str) -> str: """ Validates that a user provided string "looks" like a URL aka contains at least a valid scheme and net...
8c9bf8a07c5057a5b2bdd73f2b8a84d20b4b6b7d
CichonN/BikeRental
/BikeRental.py
3,607
3.984375
4
# ---------------------------------------------------------------------------------------------------------------------------------- # Assignment Name: Bicycle Shop # Name: Neina Cichon # Date: 2020-07-26 # ----------------------------------------------------------------------------...
63fbe3a8ecd0fd1716226f819458bc604a8faefe
dxfl/pywisdom
/try_one.py
1,182
3.53125
4
#!/usr/bin/env python3 ''' example adapted from stackoverflow: https://stackoverflow.com/questions/26494211/extracting-text-from-a-pdf-file-using-pdfminer-in-python ''' from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import TextConverter from pdfminer.layout import LAPara...
c6d84e1f238ac03e872eea8c8cb3566ac0913646
Cpeters1982/DojoPython
/hello_world.py
2,621
4.21875
4
'''Test Document, leave me alone PyLint''' # def add(a,b): # x = a + b # return x # result = add(3, 5) # print result # def multiply(arr, num): # for x in range(len(arr)): # arr[x] *= num # return arr # a = [2,4,10,16] # b = multiply(a,5) # print b ''' The function multiply takes two parameter...
12769258a066d58da3c740c75205211755481d0f
Cpeters1982/DojoPython
/OOP_practice.py
5,376
4.40625
4
# # pylint: disable=invalid-name # class User(object): # '''Make a class of User that contains the following attributes and methods''' # def __init__(self, name, email): # '''Sets the User-class attributes; name, email and whether the user is logged in or not (defaults to true)''' # self.name = ...
787b69242140019629701eaf9e35c4eb97eaec44
Doctus5/FYS-STK4155
/project2/nn.py
11,991
3.625
4
import matplotlib.pyplot as plt import numpy as np import pandas as pd import math as m #Fully Connected Neural Network class for its initialization and further methods like the training and test. Time computation is quite surprisingly due to the matrix operations with relative smallamount of datasets compared to life...
c02f664998073d00a27a016e5edfe0f289b785b9
aditdamodaran/incan-gold
/deck.py
898
3.875
4
import random class Deck: # The game starts off with: # 15 treasure cards # represented by their point values, # 15 hazards (3 for each type) # represented by negative numbers # 1 artifact (worth 5 points) in the deck def __init__(self): self.cards = [1,2,3,4,5,5,7,7,9,11,11,13,14,15,17] \ ...
c8633e4755e9dfd08535a9806245154b042526b2
gersongroth/maratonadatascience
/Semana 01/01 - Estruturas Sequenciais/07.py
135
3.84375
4
lado = float(input("Informe o lado do quadrado: ")) area = lado ** 2 dobroArea = area * 2 print("dobro do área é %.1f" % dobroArea)
cbbe2be00332fe79c2b2f47a9ee1abf4e3606d1c
gersongroth/maratonadatascience
/Semana 01/03 - Estruturas de Repetição/02.py
444
3.859375
4
""" Faça um programa que leia um nome de usuário e a sua senha e não aceite a senha igual ao nome do usuário, mostrando uma mensagem de erro e voltando a pedir as informações. """ def getUser(): user=input("Informe o nome de usuário: ") password= input("Informe a senha: ") return user,password user,passw...
44b81e47c1cd95f7e08a8331b966cf195e8c514d
gersongroth/maratonadatascience
/Semana 01/02 - Estruturas de Decisão/11.py
1,156
4.1875
4
""" As Organizações Tabajara resolveram dar um aumento de salário aos seus colaboradores e lhe contraram para desenvolver o programa que calculará os reajustes. Faça um programa que recebe o salário de um colaborador e o reajuste segundo o seguinte critério, baseado no salário atual: salários até R$ 280,00 (incluindo) ...
e1ebae30cf58ae268c07ffa4f088c1b5dc3fe644
gersongroth/maratonadatascience
/Semana 01/01 - Estruturas Sequenciais/10.py
121
3.921875
4
celsius = float(input("Informe a temperatura em celsius: ")) f = celsius * 9 / 5 + 32 print("%.1f graus Farenheit" % f)
b2612751a0971f2191f1d65bd3e987ce611e9fb9
DabicD/Studies
/The_basics_of_scripting_(Python)/Exercise2.py
853
3.8125
4
# Exercise description: # # "Napisz program drukujący na ekranie kalendarz na zadany miesiąc dowolnego roku # (użytkownik wprowadza informację postaci: czerwiec 1997–nazwa miesiąca w języku polskim)." # ############################################################################################## import loc...
b5a42001ab9ec5ec13c1c0538824fdcc1d9e4b83
MarinaSergeeva/Algorithms
/day02_dijkstra.py
1,301
3.78125
4
import heapq from math import inf def dijkstra(graph, source): visited = set([source]) distances = {v: inf for v in graph} # parents = {v: None for v in graph} distances[source] = 0 for (v, w) in graph[source]: distances[v] = w # parents[v] = source vertices_heap = [(w, v) for (...
578a7c30e7e0df3e7e086223575e1a682f4c200e
MarinaSergeeva/Algorithms
/day12_median_maintenance.py
1,415
3.765625
4
import heapq class MedianMaintainer: def __init__(self): self._minheap = [] # for smallest half of fthe array, uses negated numbers self._maxheap = [] # for largest half of the array self.median = None # if similar number of elements - use value form maxheap def insert_element(self, el...
023911c5beb0dc2cdb8b29f5f4447b6198a85b33
MarinaSergeeva/Algorithms
/day07_quicksort.py
757
3.921875
4
def partition(array, low, high): # uses array[low] element for the partition pivot = array[low] repl_index = low for i in range(low + 1, high): if array[i] < pivot: repl_index += 1 array[i], array[repl_index] = array[repl_index], array[i] array[low], array[repl_index]...
5d185a1960ee3b49934bf30e2e03a48c5ac09db7
HSabbir/Python-Challange
/day 1.py
155
4.15625
4
## Print Multiplication table number = int(input("Enter Your Number: ")) for i in range(10): print(str(i+1)+' * '+str(number)+' = '+str(number*(i+1)))
348084b89a6dda4fd185da2863c05cb4cb3b4a3f
Vrittik/LINEAR_REGRESSION_FROM_SCRATCH
/SLR_By_calc.py
772
3.6875
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd from statistics import mean from ML_library import mlSkies dataset=pd.read_csv("Salary_Data.csv") X=dataset.iloc[:,0].values y=dataset.iloc[:,1].values X_train,X_test,y_train,y_test = mlSkies.train_test_split(X,y,split_index=0.2) X_train=np.array...
89c3903452e5ee6c194159e3a3311fbe2d6ba04d
davidlowryduda/pynt
/pynt/base.py
4,086
4.03125
4
""" base.py ======= Fundamental components for a simple python number theory library. License Info ============ (c) David Lowry-Duda 2018 <davidlowryduda@davidlowryduda.com> This is available under the MIT License. See <https://opensource.org/licenses/MIT> for a copy of the license, or see the home github repo <htt...
0685f7856c0b7032a146198548e1db5dc3a0bbad
numblr/glaciertools
/test/treehash/algorithm_test.py
2,242
3.53125
4
#!/usr/bin/python from pprint import pprint def next_itr(last): for i in range(1, last + 1): yield str(i) def calculate_root(level, itr): # Base case level if level == 0: return next(itr, None) left = calculate_root(level - 1, itr) right = calculate_root(level - 1, itr) retu...
5f4b7dc66789528b881bc081632e8b54fc6192f3
bubblegumsoldier/kiwi
/kiwi-user-manager/app/lib/username_validator.py
333
3.546875
4
import re username_min_string_length = 5 username_max_string_length = 30 username_regex = "^[a-zA-Z0-9_.-]+$" def validate(username): if not username_min_string_length <= len(username) <= username_max_string_length: return False if not re.match(username_regex, username): return False ...
2280d3663399e1dcd1dc76de2ee713c3416c484d
ash-fu/coursera-algo
/Assign2.py
1,711
3.703125
4
count = 0 def mergeSort(alist): # print("Splitting ",alist) global count # count = 0 if len(alist)>1: mid = len(alist)//2 lefthalf = alist[:mid] righthalf = alist[mid:] mergeSort(lefthalf) mergeSort(righthalf) # splitSort(lefthalf, righthalf,count) ...
f3ae407a822f0cd36fdfb490b705e35cd2a275d6
SaraZ3964/Python
/pybank.py
420
3.625
4
import pandas as pd file = "budget_data.csv" data_df = pd.read_csv(file) data_df.head() Months = data_df["Date"].count() Sum = data_df["Profit/Losses"].sum() Ave = data_df["Profit/Losses"].mean() Max = data_df["Profit/Losses"].max() Min = data_df["Profit/Losses"].min() print("Months:" + str(Months)) print("Total: " ...
37238eb1a843fb3a7d5e1d36364bf3f0b1bbd7ee
kylehovey/kylehovey.github.io
/spel3o/files/geohash.py
2,354
3.8125
4
import webbrowser import math ImTheMap = input("would you like a map site to look up your coordinates? ") if ImTheMap == "yes": print('look up your current location on this website') webbrowser.open("https://csel.cs.colorado.edu/~nishimot/point.html") else: print('''okay then, let's continue''') Lat = input...
06abfdc014c7ef45be7f8c1ac53007c49983062c
TheAutomationWizard/learnPython
/pythonUdemyCourse/Concepts/General Concepts/slicing.py
543
4.09375
4
list = [1, 2, 34, 4, 56, 7, 8, 99, 2] def various_slicing_in_python(list_object): """ slicing operations in python :param list_object: :return: slice (Start, end , step) """ # Using slice method print(list_object[slice(0, 4, 1)]) # Using index slicing +==> [start : stop+1 : step...
4bf52a9a6adb7f222b981d2c48c51cd912324faa
TheAutomationWizard/learnPython
/pythonUdemyCourse/Concepts/OOPS/Inheritance/FiguresExample.py
1,227
3.953125
4
class Quadrilateral: def __init__(self, length, height): self.length = length self.height = height def quad_area(self): area_ = self.length * self.height print(f'Area of Quadrilateral with length {self.length} and height : {self.height} is = {area_}') return area_ clas...
18d811c538e2db5846bdf7caf92fbca0eaac8f44
TheAutomationWizard/learnPython
/pythonUdemyCourse/Concepts/OOPS/Inheritance/PythonicInheritance.py
1,119
4.03125
4
class A(object): def __init__(self, a, *args, **kwargs): print('I (A) am called from B super()') print("A", a) class B(A): def __init__(self, b, *args, **kwargs): print('As per inverted flow, i am called from class A1 super()') super(B, self).__init__(*args, **kwargs) p...
cc1812713296f1e020d7a5d426397c2f54622232
fanying2015/algebra
/algebra/quadratic.py
407
3.78125
4
def poly(*args): """ f(x) = a * x + b * x**2 + c * x**3 + ... *args = (x, a, b) """ if len(args) == 1: raise Exception("You have only entered a value for x, and no cofficients.") x = args[0] # x value coef = args[1:] results = 0 for power, c in enum...
38d2e2e55b3ac7a05246a18367a4c82c4bd95cc8
BOUYAHIA-AB/DeepSetFraudDetection
/split_data.py
4,321
3.5
4
"""Build vocabularies of words and tags from datasets""" from collections import Counter import json import os import csv import sys import pandas as pd def load_dataset(path_csv): """Loads dataset into memory from csv file""" # Open the csv file, need to specify the encoding for python3 use_python3 = sys...
c742ba20728912aac3293cf456bc83fe88a588cf
Danisaura/phrasalVerbs
/main.py
6,114
3.703125
4
from random import shuffle # printing the welcome message print("\n" + "---------------------------------------------------" + "\n" + "Welcome! this is a script to practice phrasal verbs." + "\n" + "\n" + "You will be shown sentences with blank spaces inside," + "\n" + "try to fill them with the corr...
e6536e8399f1ceccd7eb7d41eddcc302e3dda66b
guv-slime/python-course-examples
/section08_ex04.py
1,015
4.4375
4
# Exercise 4: Expanding on exercise 3, add code to figure out who # has the most emails in the file. After all the data has been read # and the dictionary has been created, look through the dictionary using # a maximum loop (see chapter 5: Maximum and Minimum loops) to find out # who has the most messages and print how...
f93dd7a14ff34dae2747f7fa2db22325e9d00972
guv-slime/python-course-examples
/section08_ex03.py
690
4.125
4
# Exercise 3: Write a program to read through a mail log, build a histogram # using a dictionary to count how many messages have come from each email # address, and print the dictionary. # Enter file name: mbox-short.txt # {'gopal.ramasammycook@gmail.com': 1, 'louis@media.berkeley.edu': 3, # 'cwen@iupui.edu': 5, 'antr...
995c34fb8474004731ba29407120537d9612529f
tacyi/tornado_overview
/chapter01/coroutine_test.py
787
3.953125
4
# 1.什么是协程 # 1.回调过深造成代码很难维护 # 2.栈撕裂造成异常无法向上抛出 # 协程,可被暂停并且切换到其他的协程运行的函数 from tornado.gen import coroutine # 两种协程的写法,一种装饰器,一种3.6之后的原生的写法,推荐async # @coroutine # def yield_test(): # yield 1 # yield 2 # yield 3 # # yield from yield_test() # # return "hello" async def yield_test(): yield 1 yield...
cc7a0230928450b5bb71fa5fa6e57429a6e25882
lmtjalves/CPD
/scripts/gen_random_big_parse_tests.py
1,160
3.609375
4
#!/bin/python import sys, argparse, random def test_rand(t): if t == "both": return random.randint(0,1) elif t == "positive": return 0 else: return 1 parser = argparse.ArgumentParser(description="problem gen. clauses might be duplicate and have repeated variables") parser.add_arg...
6214901ec8317a2ead9409991548282f5ce33c57
bobgautier/rjgtoys-config
/examples/translate.py
590
3.890625
4
""" examples/translate.py: translate words using a dictionary """ import argparse import os from typing import Dict from rjgtoys.config import Config, getConfig class TranslateConfig(Config): words: Dict[str, str] cfg = getConfig(TranslateConfig) def main(argv=None): p = argparse.ArgumentParser() cf...
2d7724e5786f00b9f2c1e2f8640ebde7138f7c85
maryamkh/MyPractices
/Find_Nearest_Smaller_Element.py
1,930
3.90625
4
''' Given an array, find the nearest smaller element G[i] for every element A[i] in the array such that the element has an index smaller than i. Elements for which no smaller element exist, consider next smaller element as -1. Output: An array of prev .smaller value of each item or -1(if no smaller value ex...
ff2ac738c1718fa12bd84e447ddc9b0e1080420a
maryamkh/MyPractices
/Min_Sum_Path_Bottom_Up.py
4,255
4.375
4
#!usr/bin/python ''' The approach is to calculate the minimum cost for each cell to figure out the min cost path to the target cell. Assumpthion: The movementns can be done only to the right and down. In the recursive approach there is a lot of redundent implementation of the sub-problems. With Dynamic prog...
bd745cc83163bd91f36ab2f2d034f7f0a02093c0
maryamkh/MyPractices
/Pow_function_recursive.py
697
3.921875
4
''' Implement pow(x, n), which calculates x raised to the power n (i.e., xn). Example: Input: x = 2.00000, n = -2 Output: 0.25000 Explanation: 2-2 = 1/22 = 1/4 = 0.25 Time Complexity: O(log(n))===> In this solution n is reduce to half and therefore this is the time cimplexity Spcae Complexity: We need to do the computa...
d1917f2bd44d327224cfb121c1d18f68c5de2383
maryamkh/MyPractices
/Stairs.py
2,092
4.09375
4
#!usr/bin/python ''' Find the numbers of ways we can reach the top of the stairs if we can only clime 1 or 2 steps each time? Input: Integer: The stair number in which we should reach to Output: Integer: The numebr of ways we can clime up to reach target stair Reaching any stair with only 1 step climing...
f9a66f5b0e776d063d812e7a7185ff6ff3c5615f
maryamkh/MyPractices
/ReverseLinkedList.py
2,666
4.3125
4
''' Reverse back a linked list Input: A linked list Output: Reversed linked list In fact each node pointing to its fron node should point to it back node ===> Since we only have one direction accessibility to a link list members to reverse it I have to travers the whole list, keep the data of the nodes and then rearra...
145413092625adbe30b158c21e5d27e2ffcfab50
maryamkh/MyPractices
/Squere_Root.py
1,838
4.1875
4
#!/usr/bin/python ''' Find the squere root of a number. Return floor(sqr(number)) if the numebr does not have a compelete squere root Example: input = 11 ===========> output = 3 Function sqrtBinarySearch(self, A): has time complexity O(n), n: given input: When the number is too big it becomes combursome ...
55ab2d3473fb7ff9485f1ff835dd599d427e0a5d
hokiespider/win_probability
/win_probability.py
4,054
3.734375
4
#!/usr/bin/env python # coding: utf-8 import pandas as pd import requests import json # What school are you analyzing? school = "Virginia Tech" # Get data from the API df = pd.DataFrame() for x in range(2013, 2020, 1): # Line data is only available 2013+ parameters = { "team": school, "year": ...
65256d3f3d66a41bd69be4dc55bb89b2c643036e
DaniRyland-Lawson/CP1404-cp1404practicals-
/prac_06/demo_program.py
1,784
3.75
4
"""CP1404 Programming II demo program week 6 prac 0. Pattern based programming 1. Names based on problem domain 2. Functions at the same leve of abstraction( main should "look" the same Menu- driven program load products - L_ist products - S_wap sale status (get product number with error checking) - Q_uit (save file)...
e47f166763aad48f70da971a79953db8875531b7
DaniRyland-Lawson/CP1404-cp1404practicals-
/prac_07/miles_to_kms.py
1,154
3.53125
4
"""CP1404 Programming II Week 7 Kivy - Gui Program to convert Miles to Kilometres.""" from kivy.app import App from kivy.lang import Builder from kivy.app import StringProperty MILES_TO_KM = 1.60934 class MilesToKilometres(App): output_km = StringProperty() def build(self): self.title = "Convert Mi...
4a20f0a4d156b03c5e658e0073f8086ab5ca0b95
DaniRyland-Lawson/CP1404-cp1404practicals-
/prac_08/unreliable_car_test.py
676
3.640625
4
"""CP1404 Programming II Test to see of UnreliableCar class works.""" from prac_08.unreliable_car import UnreliableCar def main(): """Test for UnreliableCars.""" # Create some cars for reliability good_car = UnreliableCar("Good Car", 100, 90) bad_car = UnreliableCar("Bad Car", 100, 10) # Attemp...
de7b30a4f51727085b556dc01763180a3fdedffd
Monkin6/yarygin
/hm4.py
132
3.5
4
n = int(input()) maximum = -1 while n != 0: if n % 10 > maximum: maximum = n % 10 n = n // 10 print(maximum)
c0c510cbebedb03947bb2b9ed16c16efa23a4956
Sahil-k1509/Python_and_the_Web
/Scripts/Miscellaneous/Email_extractor/extract_emails.py
407
3.78125
4
#!/usr/bin/env python3 import re print("Enter the name of the input file: ") file=str(input()) try: f = open(file,"r") except FileNotFoundError: print("File does not exists") email={} for i in f: em = re.findall('\S+@\S+\.\S+',i) for j in em: email[j]=email.get(j,0)+1 f.close() for...
d99e28fea0f6d213659694f220451d12930dcd84
Mertvbli/JustTry
/CW_filter_list_7kyu.py
363
3.640625
4
def filter_list(l): new_list = [] for number in l: if str(number).isdigit() and str(number) != number: new_list.append(number) return new_list # or [number for number in l if isinstance(number, int) print(filter_list([1,2,'a','b'])) print(filter_list([1,'a','b',0,15])) print...
ddbfeec96361f4c3576874c2ff007d88717f1566
CodingDojoDallas/python_sep_2018
/austin_parham/product.py
948
3.671875
4
class Product: def __init__(self,price,item_name,weight,brand): self.price = price self.item_name = item_name self.weight = weight self.brand = brand self.status = "for sale" self.display_info() def sell(self): self.status = "sold" return self def add_tax(self,x): self.price = (self.price * x) + ...
13dac1bd992f843d432a94f266a283671e39c2fa
CodingDojoDallas/python_sep_2018
/Solon_Burleson/Basics.py
370
3.796875
4
# def allOdds(): # for x in range(3001): # if x % 2 != 0: # print (x) # allOdds() # def Iterate(arr): # for x in arr: # print (x) # Iterate([1,2,3,4,5]) # def Sumlist(arr): # sum = 0 # for x in arr: # sum += x # return sum # print(Sumlist([1,2,3,4,5])) list =...
bb488183c87ed750f3cd459bda9d758416b5613e
CodingDojoDallas/python_sep_2018
/austin_parham/func_intermediate_1.py
819
3.828125
4
def randInt(): import random hold = (random.random()*100) hold = int(hold) print(hold) randInt() def randInt(): import random hold = (random.random()*50) hold = int(hold) print(hold) randInt() def randInt(): import random hold = (random.uniform(50,100)) hold = int(hold) print(hold) randInt() def randInt(...
8b9f850c53a2a020b1deea52e301de0d2b6c47c3
CodingDojoDallas/python_sep_2018
/austin_parham/user.py
932
4.15625
4
class Bike: def __init__(self, price, max_speed, miles): self.price = price self.max_speed = max_speed self.miles = miles def displayInfo(self): print(self.price) print(self.max_speed) print(self.miles) print('*' * 80) def ride(self): print("Riding...") print("......") print("......") self.mi...
60abefff5fa43ad4a30bee1e102f3a31a08c15b6
CodingDojoDallas/python_sep_2018
/albert_garcia/python_oop/slist.py
1,276
3.78125
4
class Node: def __init__(self, value): self.value = value self.next = None class SList: def __init__(self, value): node = Node(value) self.head = node def Addnode(self, value): node = Node(value) runner = self.head while (runner.next != None): ...
189bd9eb0029b856f348e9ff86f32ceb6f99d84b
CodingDojoDallas/python_sep_2018
/Solon_Burleson/RunCode.py
380
3.703125
4
class MathDojo: def __init__(self): self.value = 0 def add(self, *nums): for i in nums: self.value += i return self def subtract(self, *nums): for i in nums: self.value -= i return self def result(self): print(self.value) x = M...
ab847b8b4d3b115f88b96b560b41f076a7bd6bdc
CodingDojoDallas/python_sep_2018
/Solon_Burleson/FunctionsIntermediateI.py
195
3.65625
4
import random def randInt(max=0, min=0): if max == 0 and min == 0: print(int(random.random()*100)) else: print(int(random.random()*(max-min)+min)) randInt(max=500,min=50)
36a4f28b97be8be2e7f6e20965bd21f554270704
krismosk/python-debugging
/area_of_rectangle.py
1,304
4.6875
5
#! /usr/bin/env python3 "A script for calculating the area of a rectangle." import sys def area_of_rectangle(height, width = None): """ Returns the area of a rectangle. Parameters ---------- height : int or float The height of the rectangle. width : int or float The width o...
dda3e4ff366d47cea012f9bfede9819fac448af9
BlueAlien99/minimax-reversi
/app/gui/utils.py
8,441
3.515625
4
import enum import pygame from typing import List import pygame.freetype from pygame_gui.elements.ui_drop_down_menu import UIDropDownMenu from pygame_gui.elements.ui_text_entry_line import UITextEntryLine import time class Color(enum.Enum): NO_COLOR = -1 BLACK = "#212121" WHITE = "#f5f5f5" GREEN = "#3...
dacaf7998b9ca3a71b6b90690ba952fb56349ab9
Kanthus123/Python
/Design Patterns/Creational/Abstract Factory/doorfactoryAbs.py
2,091
4.1875
4
#A factory of factories; a factory that groups the individual but related/dependent factories together without specifying their concrete classes. #Extending our door example from Simple Factory. #Based on your needs you might get a wooden door from a wooden door shop, #iron door from an iron shop or a PVC door from th...
ab049070f8348f4af8caeb601aee062cc7a76af2
Kanthus123/Python
/Design Patterns/Structural/Decorator/VendaDeCafe.py
1,922
4.46875
4
#Decorator pattern lets you dynamically change the behavior of an object at run time by wrapping them in an object of a decorator class. #Imagine you run a car service shop offering multiple services. #Now how do you calculate the bill to be charged? #You pick one service and dynamically keep adding to it the prices f...
4bcdaa732a2a499c3e52a902911b1a6cbc6636bf
Kanthus123/Python
/Design Patterns/Behavioral/Strategy/main.py
817
3.671875
4
#Strategy pattern allows you to switch the algorithm or strategy based upon the situation. #Consider the example of sorting, we implemented bubble sort but the data started to grow and bubble sort started getting very slow. #In order to tackle this we implemented Quick sort. But now although the quick sort algorithm w...
478e6714f68fb421aff714cf178486c60d46980b
russellgao/algorithm
/dailyQuestion/2020/2020-05/05-14/python/solution.py
376
3.78125
4
from functools import reduce # 位运算 写法1 def singleNumber1(nums: [int]) -> int: return reduce(lambda x, y: x ^ y, nums) # 位运算 写法2 def singleNumber2(nums: [int]) -> int : result = nums[0] for i in range(1,len(nums)) : result ^= nums[i] return result if __name__ == "__main__" : nums = [2,3,4...
ba0c5f0469a2b8ef74c669af85355c81c4a40eb6
russellgao/algorithm
/dailyQuestion/2020/2020-10/10-10/python/solution.py
891
4
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def partition(head: ListNode, x: int) -> ListNode: first = first_head = ListNode(0) second = second_head = ListNode(0) while head: if head.val < x: first.next ...
a6f65dc2d6ac9f5f160229c2dc76b2d74c150550
russellgao/algorithm
/dailyQuestion/2020/2020-07/07-29/python/solution_n.py
263
3.890625
4
# 一次遍历 def missingNumber(nums: [int]) -> int: for i,v in enumerate(nums) : if i != v : return i return nums[-1] + 1 if __name__ == "__main__" : nums = [0,1,2,3,4,5,6,7,9] result = missingNumber(nums) print(result)
1587894d5e65ee725de94d02e15cd0ec84f1987b
russellgao/algorithm
/dailyQuestion/2020/2020-06/06-02/python/solution.py
445
3.515625
4
def lengthOfLongestSubstring(s: str) -> int: tmp = set() result = 0 j = 0 n = len(s) for i in range(n) : if i != 0 : tmp.remove(s[i-1]) while j < n and s[j] not in tmp : tmp.add(s[j]) j += 1 result = max(result, j - i) return result i...
47ddbc6c436d80ff4ba68199da5e803edabf3402
russellgao/algorithm
/dailyQuestion/2020/2020-05/05-22/python/solution_dlinknode.py
2,137
3.84375
4
# 双向链表求解 class DlinkedNode(): def __init__(self): self.key = 0 self.value = 0 self.next = None self.prev = None class LRUCache(): def __init__(self, capacity: int): self.capacity = capacity self.size = 0 self.cache = {} self.head = DlinkedNode()...
98786826bd97d037c30c7f2b4244b7101ccd963e
russellgao/algorithm
/data_structure/heap/python/002.py
1,317
4.03125
4
# 堆排序 def buildMaxHeap(lists): """ 构造最大堆 :param lists: :return: """ llen = len(lists) for i in range(llen >> 1, -1, -1): heapify(lists, i, llen) def heapify(lists, i, llen): """ 堆化 :param lists: :param i: :return: """ largest = i left = 2 * i + 1 ...
77ec5582550e18cce771f24058e78bc18686ec9a
russellgao/algorithm
/dailyQuestion/2020/2020-04/04-29/python/solution.py
1,683
3.84375
4
class ListNode: def __init__(self, x): self.val = x self.next = None # 方法一 # 递归,原问题可以拆分成自问题,并且自问题和原问题的问题域完全一样 # 本题以前k个listnode 为原子进行递归 def reverseKGroup1(head: ListNode, k: int) -> ListNode: cur = head count = 0 while cur and count!= k: cur = cur.next count += 1 if c...
30cea365bbb1ea986b435692edfb5eb4118249cc
russellgao/algorithm
/dailyQuestion/2020/2020-08/08-06/python/solution_dict.py
1,341
3.71875
4
def palindromePairs(words: [str]) -> [[int]]: indices = {} result = [] n = len(words) def reverse(word): _w = list(word) n = len(word) for i in range(n >> 1): _w[i], _w[n - 1 - i] = _w[n - i - 1], _w[i] return "".join(_w) def isPalindromes(word: str, lef...
32c5ca8e7beb18feafd101e6e63da060c3c47647
russellgao/algorithm
/data_structure/binaryTree/preorder/preoder_traversal_items.py
695
4.15625
4
# 二叉树的中序遍历 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # 迭代 def preorderTraversal(root: TreeNode) ->[int]: result = [] if not root: return result queue = [root] while queue: root = queue.pop() if root: ...
5723367d25964f32d4f5bc67a99e3f824309f639
russellgao/algorithm
/dailyQuestion/2020/2020-10/10-01/python/solution.py
927
4.03125
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def increasingBST(root: TreeNode) -> TreeNode: result = node = TreeNode(0) queue = [] while root or len(queue) > 0 : while root : queue...
b8189f9da4e8491b8871a75225d4376c9ea2cc0c
russellgao/algorithm
/dailyQuestion/2020/2020-06/06-06/python/solution.py
476
3.796875
4
def longestConsecutive(nums: [int]) -> int: nums = set(nums) longest = 0 for num in nums: if num - 1 not in nums: current = num current_len = 1 while current + 1 in nums: current += 1 current_len += 1 longest = max(long...
cb8bdd7d8b00d9b6214787b82fe5766228741eee
russellgao/algorithm
/data_structure/sort/tim_sort.py
2,031
3.734375
4
import time def binary_search(the_array, item, start, end): # 二分法插入排序 if start == end: if the_array[start] > item: return start else: return start + 1 if start > end: return start mid = round((start + end) / 2) if the_array[mid] < item: return...
a4d555397fb194beb604dd993a6b08c746409046
russellgao/algorithm
/dailyQuestion/2020/2020-07/07-11/python/solution.py
546
3.828125
4
def subSort(array: [int]) -> [int]: n = len(array) first,last = -1,-1 if n == 0 : return [first,last] min_a = float("inf") max_a = float("-inf") for i in range(n) : if array[i] >= max_a : max_a = array[i] else : last = i if array[n-1-i] <= ...
c836d3a26bb6d7432f734c7a771df38e8aaec095
russellgao/algorithm
/dailyQuestion/2020/2020-07/07-18/python/solution_recurse.py
708
3.875
4
def isInterleave(s1, s2, s3): """ :type s1: str :type s2: str :type s3: str :rtype: bool """ m = len(s1) n = len(s2) t = len(s3) if m + n != t: return False dp = [[False] * (n + 1) for _ in range(m + 1)] dp[0][0] = True for i in range(m + 1): for j in ...
bd9249d9d6593d652adca04e69220e3326615cd4
russellgao/algorithm
/dailyQuestion/2020/2020-06/06-14/python/solution_vertical.py
432
3.96875
4
def longestCommonPrefix(strs: [str]) -> str: if not strs: return "" length, count = len(strs[0]), len(strs) for i in range(length): c = strs[0][i] if any(i == len(strs[j]) or strs[j][i] != c for j in range(1, count)): return strs[0][:i] return strs[0] if __name__ ...
ff3ce63ef2e076344a7e1226b9fadf5a37a5653b
russellgao/algorithm
/dailyQuestion/2021/2021-03/03-20/python/solution.py
961
3.515625
4
class Solution: def evalRPN(self, tokens: [str]) -> int: stack = [] for i in range(len(tokens)) : tmp = tokens[i] if tmp == "+" : num1 = stack.pop() num2 = stack.pop() stack.append(num2 + num1) elif tmp == "-" : ...
9d4fa8524fe6b0b3172debd49bf081e98f5a0282
russellgao/algorithm
/dailyQuestion/2020/2020-06/06-09/python/solution_mod.py
335
3.6875
4
# 动态求余法 def translateNum(num: int) -> int: f_1 = f_2 = 1 while num: pre = num % 100 f = f_1 + f_2 if pre >= 10 and pre <= 25 else f_1 f_2 = f_1 f_1 = f num = num // 10 return f_1 if __name__ == '__main__' : num = 12258 result = translateNum(num) print(res...
861fab844f5dcbf86c67738354803e27a0a303e9
russellgao/algorithm
/dailyQuestion/2020/2020-05/05-31/python/solution_recursion.py
950
4.21875
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # 递归 def isSymmetric(root: TreeNode) -> bool: def check(left, right): if not left and not right: return True if not left or not right: ...
21f1cf35cd7b3abe9d67607712b62bfa4732e4ce
russellgao/algorithm
/dailyQuestion/2020/2020-05/05-01/python/solution.py
944
4.125
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None def reverseList(head): """ 递归 反转 链表 :type head: ListNode :rtype: ListNode """ if not head : return None if not head.next : return head l...
86bee5da92c7b029a182b67d9e3aa4bb2eb1b949
franztrierweiler/maths_python
/exercices_02mars.py
2,000
3.8125
4
from fractions import * def somme(): S = 1 for i in range (1,21): S = S + pow(Fraction(1,3),i) # Converts fraction to float # and returns the result return float(S); def compte_espaces(phrase): nbre = 0 for caractere in phrase: if caractere==" ": nbre=n...
407273956e8e87a116912ee44dc192e8233f5fac
swainsubrat/Haw
/Dependencies/DataFrameBuilder.py
5,313
3.9375
4
""" Structures dataframes for plotting """ import re import pandas as pd from io import StringIO from pandas.core.frame import DataFrame def basicDataFrameBuilder(FILE: StringIO) -> DataFrame: """ Function to pre-process the raw text file and format it to get a dataframe out of it 1. Datetime extr...
fc94459d32944d0e67d1870d0b2e864263dc8319
Narusi/Python-Kurss
/Uzdevums Lists.py
3,209
4.1875
4
#!/usr/bin/env python # coding: utf-8 # # Klases Uzdevumi - Lists # ## 1.a Vidējā vērtība # Uzrakstīt programmu, kas liek lietotājam ievadīt skaitļus(float). # Programma pēc katra ievada rāda visu ievadīto skaitļu vidējo vērtību. # PS. 1a var iztikt bez lists # # 1.b Programma rāda gan skaitļu vidējo vērtību, gan V...
d278d8c5efedbd61317118887461b052690dd605
wulinlw/leetcode_cn
/常用排序算法/quicksort.py
828
3.8125
4
#!/usr/bin/python #coding:utf-8 # 快速排序 def partition(arr,low,high): i = ( low-1 ) # 最小元素索引 pivot = arr[high] for j in range(low , high): # 当前元素小于或等于 pivot if arr[j] <= pivot: i = i+1 arr[i],arr[j] = arr[j],arr[i] # print(i,arr) arr[i+1],arr[...
8beaa095846c553f6c970e062494b068733a5d6a
wulinlw/leetcode_cn
/leetcode-vscode/671.二叉树中第二小的节点.py
2,205
3.734375
4
# # @lc app=leetcode.cn id=671 lang=python3 # # [671] 二叉树中第二小的节点 # # https://leetcode-cn.com/problems/second-minimum-node-in-a-binary-tree/description/ # # algorithms # Easy (45.43%) # Likes: 61 # Dislikes: 0 # Total Accepted: 8.5K # Total Submissions: 18.6K # Testcase Example: '[2,2,5,null,null,5,7]' # # 给定一个非空...
8504344ee52ab7c26d4e0a926e97ad8a8874308f
wulinlw/leetcode_cn
/程序员面试金典/面试题01.05.一次编辑.py
1,707
3.75
4
#!/usr/bin/python #coding:utf-8 # 面试题 01.05. 一次编辑 # 字符串有三种编辑操作:插入一个字符、删除一个字符或者替换一个字符。 给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑。 # 示例 1: # 输入: # first = "pale" # second = "ple" # 输出: True # 示例 2: # 输入: # first = "pales" # second = "pal" # 输出: False # https://leetcode-cn.com/problems/one-away-lcci/ from typing import Lis...
539c0e8e5f78fb080ec39bf80e69aa14161cbc3c
wulinlw/leetcode_cn
/剑指offer/55_2_平衡二叉树.py
1,298
3.609375
4
#!/usr/bin/python #coding:utf-8 # // 面试题55(二):平衡二叉树 # // 题目:输入一棵二叉树的根结点,判断该树是不是平衡二叉树。如果某二叉树中 # // 任意结点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 归并的套路,先拿到子结果的集,在处理资结果的集 def IsBalanced(self, r...
28cb62abf374b9a10b964d944b5b858474c2422c
wulinlw/leetcode_cn
/leetcode-vscode/872.叶子相似的树.py
1,729
3.921875
4
# # @lc app=leetcode.cn id=872 lang=python3 # # [872] 叶子相似的树 # # https://leetcode-cn.com/problems/leaf-similar-trees/description/ # # algorithms # Easy (62.23%) # Likes: 49 # Dislikes: 0 # Total Accepted: 9.7K # Total Submissions: 15.5K # Testcase Example: '[3,5,1,6,2,9,8,null,null,7,4]\n' + # '[3,5,1,6,7,4,2,n...
efcf849ffdf2209df24b021a2dff59c5138618aa
wulinlw/leetcode_cn
/程序员面试金典/面试题05.04.下一个数.py
5,329
3.515625
4
# #!/usr/bin/python # #coding:utf-8 # # 面试题05.04.下一个数 # # https://leetcode-cn.com/problems/closed-number-lcci/ # # 下一个数。给定一个正整数,找出与其二进制表达式中1的个数相同且大小最接近的那两个数(一个略大,一个略小)。 # 示例1: # # # 输入:num = 2(或者0b10) # 输出:[4, 1] 或者([0b100, 0b1]) # # # 示例2: # # # 输入:num = 1 # 输出:[2, -1] # # # 提示: # # # num的范围在[1, 21...
c8eab7467ee25294d227d9d16ef6cea5f97d7ab2
wulinlw/leetcode_cn
/程序员面试金典/面试题02.07.链表相交.py
3,147
3.6875
4
#!/usr/bin/python #coding:utf-8 # 面试题 02.07. 链表相交 # 给定两个(单向)链表,判定它们是否相交并返回交点。请注意相交的定义基于节点的引用,而不是基于节点的值。换句话说,如果一个链表的第k个节点与另一个链表的第j个节点是同一节点(引用完全相同),则这两个链表相交。 # 示例 1: # 输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3 # 输出:Reference of the node with value = 8 # 输入解释:相交节点的值为 8 (注意,如果...
b282517a21d331b04566b1697602e99244800f48
wulinlw/leetcode_cn
/leetcode-vscode/15.三数之和.py
2,939
3.546875
4
# # @lc app=leetcode.cn id=15 lang=python3 # # [15] 三数之和 # # https://leetcode-cn.com/problems/3sum/description/ # # algorithms # Medium (25.70%) # Likes: 2228 # Dislikes: 0 # Total Accepted: 241.9K # Total Submissions: 874.9K # Testcase Example: '[-1,0,1,2,-1,-4]' # # 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c...
c1de2f72e8609e27c4c06ec7c843559d6ae6e447
wulinlw/leetcode_cn
/程序员面试金典/面试题08.03.魔术索引.py
1,651
3.84375
4
# #!/usr/bin/python # #coding:utf-8 # # 面试题08.03.魔术索引 # # https://leetcode-cn.com/problems/magic-index-lcci/ # # 魔术索引。 在数组A[0...n-1]中,有所谓的魔术索引,满足条件A[i] = i。给定一个有序整数数组,编写一种方法找出魔术索引,若有的话,在数组A中找出一个魔术索引,如果没有,则返回-1。若有多个魔术索引,返回索引值最小的一个。 # 示例1: # # 输入:nums = [0, 2, 3, 4, 5] # 输出:0 # 说明: 0下标的元素为0 # # # 示例2: # # 输入:n...