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
91b86b652a65751aa29ec30da40c0524983dd4e0
vaibbhav-kalra/Financial-Engineering
/Dijkstra's Shortest Path.py
2,195
4.09375
4
import sys class Graph(): def __init__(self, vertices): self.V = vertices # initialising a graph with 0 values self.graph = [[0 for column in range(vertices)] for row in range(vertices)] def printPath(self, parent, j): if parent[j] == -1 : ...
5dd490e5ed1570add557d3232d598c74b3dde55e
winstonsummers/algorithms-
/brackets.py
3,251
3.640625
4
# # if a given closure is greater than its opener then this is False # # if in the end the total closures and total openers are not equal this is false. # # if next closure is not equal to the previous opener this is false # def test_brackets(s): # brackets = { # "{":0, # "}":0, # "[":0, # "]":0, # ...
e72f31942b3077b838ec289bffcf5a22526eea40
priyakrisv/priya-m
/set17.py
400
4.1875
4
print("Enter 'x' for exit."); string1=input("enter first string to swap:"); if(string1=='x'): exit() string2=input("enter second string to swap:"); print("\nBoth string before swap:"); print("first string=",string1); print("second string=",string2); temp=string1; string1=string2; string2=temp; print("\nBoth string afte...
1dc88d9acffc251909f6c30e731c47389c80a503
hoanghai2001/k-thu-t-l-p-tr-nh
/thi giua ki.py
293
3.546875
4
while True: try: a=int(input('nhap a: ')) except: print(' loi, nhap lai: a') b=int(input('nhap b: ')) except: print(' loi, nhap lai: b') c= a/b; break print('ketquala: ',c)
2da02aef5a674f537333002ed25409d4e79b1a3f
hoanghai2001/k-thu-t-l-p-tr-nh
/bài tập 3 chương 8.py
546
3.8125
4
from tkinter import * from tkinter.ttk import * window = Tk() window.title("Welcome") selected = IntVar() rad1 = Radiobutton(window, text='First',value=1,variable=selected) rad2 = Radiobutton(window, text='Second',value=2,variable=selected) rad3 = Radiobutton(window, text='Third',value=3,variable=selected) def ...
39959d08343f4ca027e3150e4a29186675a8ab2d
ramshaarshad/Algorithms
/number_swap.py
305
4.21875
4
''' Swap the value of two int variables without using a third variable ''' def number_swap(x,y): print x,y x = x+y y = x-y x = x-y print x,y number_swap(5.1,6.3) def number_swap_bit(x,y): print x,y x = x^y y = x^y x = x^y print x,y print '\n' number_swap_bit(5,6)
4e8b6a217f7368d69d4ed789d03fb4bbfc25107a
ramshaarshad/Algorithms
/palinedrome.py
894
3.984375
4
''' Return all of the palindromes in a given string ''' def palindrome(s): if len(s) == 1 or len(s) == 0: return [] if palindrome_helper(s): return [s] + palindrome(s[:-1]) + palindrome(s[1:]) return palindrome(s[:-1]) + palindrome(s[1:]) def palindrome_fast(s, memo): if len(s) == 1 or ...
91d4be631a14a62bea2a2de3bb1bb2ec33850921
Buzzkata/AIplaysConnect4
/sourceCode/human_play.py
1,974
3.59375
4
from mcts import MonteCarloTreeSearch, TreeNode from configuration import CFG class HumanPlay(object): #Class that allows human vs AI play def __init__(self, game, net): self.game = game self.net = net def play(self): #Function which allows human play vs AI. prin...
78da24fc54a2f7f9cb4401b08fa0978e6492a4aa
diegozencode/AirBnB_clone
/tests/test_models/test_place.py
924
3.78125
4
#!/usr/bin/python3 """ Unit test place model """ import unittest from models.place import Place class TestPlace(unittest.TestCase): """test place""" def test_instance(self): """test instance of the class and attributes instance of data type""" obj1 = Place() self.assertIsInstance(...
428cccb1bb619ea043a0328f125e5e69a6d322ce
caiopg/turist-catalog
/populatedb.py
22,892
3.5625
4
from model import DBSession from model.attraction import Attraction from model.country import Country from model.user import User ''' populatedb is used to populate the db with some information related to countries and their attraction points. ''' # Create the admin user. All countries and attractions created here wi...
791d7c4cd15524dc0a85ef1cceabe5a30aea4eb6
sunshineDrizzle/learn-python-the-hard-way
/ex15.py
904
3.96875
4
from sys import argv # 从sys模块中导入属性argv script, filename = argv # 将从命令行传入的两个实参赋值给两个变量 txt = open(filename) # 打开名为filename的文件,将文件对象赋值给变量txt print("Here's your file %r:" % filename) # 打印一条说明信息 print(txt.read()) # 调用文件对象的read方法,打印文件内容 txt.close() print("Type the filename again:") # 打印一条提示信息 file_again = input("> ...
8712efb746ee37f10d0e3d235b47a0f16c4f2c9f
sunshineDrizzle/learn-python-the-hard-way
/ex11.py
928
4.25
4
print("How old are you?", end=' ') age = input() # 在python3.0之后就没有raw_input()这个函数了 print("How tall are you?", end=' ') height = input() print("How much do you weigh?", end=' ') weight = input() print("So, you're %r old, %r tall and %r heavy." % (age, height, weight)) # study drill 1 # raw_input()(存在于python3.0之前的版本)的...
6c2fe4c2157ccb716e0bd4c642cbfdb73bb78f00
davidqian91/startfromhere
/practice_in_python/#104maxDepth_def.py
274
3.5
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def maxDepth(self, root): if root == None: return 0 depth1 = self.maxDepth(root.left) depth2 = self.maxDepth(root.right) return max(depth1,depth2) + 1
17c9c6591f042c1cb926d2f808c3a292564fcd95
davidqian91/startfromhere
/practice_in_python/rotatelist2.py
1,063
3.953125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @param k, an integer # @return a ListNode def rotateRight(self, head, k): if k == 0 or head is None: ret...
d5fee7610ee20a3ef6236ede88b17b1188c10279
davidqian91/startfromhere
/practice_in_python/maxprofit1.py
1,442
3.5
4
class Solution: # divide and conquer # find the maximum profit should require us to find the max price difference # create a difference price list # find the max subarrays in the list # use divid and conquer # there's three situation of the original problem # 1. the max subarrays are all in ...
f6634934ef8f10f4957ef39601d2e2e2ab81d97f
davidqian91/startfromhere
/practice_in_python/zigzag.py
1,557
4.03125
4
#Given a binary tree, return the zigzag level order traversal of its nodes' values. #(ie, from left to right, then right to left for the next level and alternate between). # #use two stacks, one stack contain the node that is outputing, #and add its child elements to the other, #so in the layer that we output from lef...
e18847a169b7646f7139b437096b0eb0114406f3
davidqian91/startfromhere
/practice_in_python/#169majorityElement.py
692
3.703125
4
#Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. #You may assume that the array is non-empty and the majority element always exist in the array. class Solution: # @param num, a list of integers # @return an integer def majorityE...
95f7ee8cce4d7306f98a1f61c5b012d2d41fe041
echrisinger/leetcode-problems
/solutions/movingAverage.py
543
3.734375
4
from queue import SimpleQueue class MovingAverage: def __init__(self, size: int): """ Initialize your data structure here. """ self.size = size self.queue = SimpleQueue() self.total = 0 def next(self, val: int) -> float: if self.size == 0: s...
c372deb8cea59347dd3315a53b5fa0f0ba5a49b5
echrisinger/leetcode-problems
/solutions/wordLadder.py
1,207
3.640625
4
from queue import Queue class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: sz = len(endWord) queue = Queue() queue.put((len(wordList), 1)) wordList.append(beginWord) word_groups = { i: defaultdict(l...
16512486e691c0c3e020b1673bcc1ff16bd9857a
echrisinger/leetcode-problems
/solutions/highFive.py
657
3.625
4
from collections import defaultdict from queue import PriorityQueue class Solution: def highFive(self, items: List[List[int]]) -> List[List[int]]: student_top_five_scores = defaultdict(PriorityQueue) for student, score in items: pq = student_top_five_scores[student] ...
0e88e8ff8f7c9e1167687f4a5a3133341d05ed9a
jpwigdor/Sprint-Challenge--Data-Structures-Python
/ring_buffer/ring_buffer.py
1,190
3.875
4
class RingBuffer: def __init__(self, capacity): self.capacity = capacity # set the storage self.storage = [] # create variable of the oldest created item. This will update as we iterate over a list at max storage. self.oldest = 0 def append(self, item): # Check t...
50ea487c9c3dd452fc4ed94cd86b223554b7afc2
rajivpaulsingh/python-codingbat
/List-2.py
2,799
4.5
4
# count_evens """ Return the number of even ints in the given array. Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1. count_evens([2, 1, 2, 3, 4]) → 3 count_evens([2, 2, 0]) → 3 count_evens([1, 3, 5]) → 0 """ def count_evens(nums): count = 0 for element in nums: if element % 2 == 0: ...
98a8744b7bbf730169aa30bf609a202ac53dd56c
guilhermeLMiranda325/cursoPython
/dev/aulas/tomada_decisao/exercicio2_15.py
125
3.890625
4
caractere = 'z' if(caractere in ('a', 'e', 'i', 'o', 'u')): print("É uma vogal!") else: print("Não é uma vogal!")
fe8ea4f4b76f48c7803c60bcfad5f1e9411461de
guilhermeLMiranda325/cursoPython
/dev/aulas/conceitos_python/exercicio1_13.py
415
3.859375
4
dias = int(input("Insira a quantidade em dias:")) horas = int(input("Insira a quantidade em horas:")) minutos = int(input("Insira a quantidade em minutos:")) segundos = int(input("Insira a quantidade em segundos:")) dias_segundos = dias * 86400 horas_segundos = horas * 3600 minutos_segundos = minutos * 60 soma = dias_...
b1f0d9a25023158b6abc215b3458541a222285c9
guilhermeLMiranda325/cursoPython
/dev/aulas/strings/iterando_strings.py
284
3.890625
4
# coding: utf-8 # Exemplo 1 # s = "Iterando Strings" # # for c in s: # print(c) # Exemplo 2 # s = "Iterando Strings" # indice = 0 # # while indice < len(s): # print(indice, s[indice]) # indice+=1 # Exemplo 3 for k, v in enumerate("Iterando Strings"): print(k, v)
0033e2426ab50b890909e8e257407e2c500d15d7
guilhermeLMiranda325/cursoPython
/dev/aulas/tomada_decisao/exercicio2_12.py
134
3.984375
4
valor = float(input("Insira um valor: ")) if(valor % 1): print("O valor é decimal!") else: print("O valor não é decimal!")
9c2045368076525d459ee9bab9109b2b685ecbab
ishiharaTatsuki/Library
/heuristics.py
737
4
4
# 二次元配列斜め操作 N = 8 def is_safe(board, row, col): for i in range(N): if board[row][i] == "Q": return False # 始点から左斜め上 for i, j in zip(range(row, - 1, -1), range(col, - 1, -1)): if board[i][j] == "Q": return False # 始点から右斜め上 for i, j in zip(range(row, - 1, -1), r...
81ac722ac1fd78620fd0d7497cd8abb87b5af15d
lpyeates/MSCI332
/MSCI333instance.py
7,018
3.546875
4
#Basis for the simulated annealing was taught to me by Hannah Gautreau #Some logic was used in her CS 686(Artifical Intelligence) course Assignment 2 #here is a link to the github repo: https://github.com/gauhannah/CS686A2-TSP #The code here is different as it solves another problem but some logic comes from there impo...
2b516c268a7e0437a6f54c2a673988cec421bc88
toyjrah/Movie_Trailer
/media.py
732
3.640625
4
import webbrowser class Movie(): ''' This class provides a way to store movie related documentation ''' valid_ratings = ["G", "PG", "PG-13", "R"] def __init__( self, movie_title, movie_storyline, poster_image, trailer_youtube): ''' Attri...
92a0027a7cfa94e4be2cec974d3f66ed4bd6bdd9
Ibnuadha28/19104020_IbnuAdhaNurRohman_PemrogramanGUI
/Modul 3/Counter.py
914
3.53125
4
class persegiPanjang: # Atribut Statis counter = 0 def __init__(self, p, l): self.panjang = p self.lebar = l # Encapsulation # Setter def ubahPanjang(self, p): self.panjang = p def ubahLebar(self, l): self.lebar = l # End Encapsulation def...
986c1a47d427ba06fc0be2b2f17adbe8127acaf1
parttee/tira2020
/week6/subtrees.py
1,233
3.8125
4
from collections import namedtuple def diff(node): if not node: return 0 l = nodeSum(node.left) r = nodeSum(node.right) return max(abs(l - r), diff(node.left), diff(node.right)) def nodeSum(node): if not node: return 0 return 1 + nodeSum(node.left) + nodeSum(node.right) ...
c2d0c07f19c2bc5e5b3c190a0ca66fc14b96194c
parttee/tira2020
/week7/tasks.py
484
3.609375
4
from heapq import heappush, heappop class Tasks: def __init__(self): self.list = [] def add(self, name, priority): heappush(self.list, (-1 * priority, name)) def next(self): return heappop(self.list)[1] if __name__ == "__main__": t = Tasks() t.add("siivous", 10) t.a...
9a027a3d930ec04977b5b2340b02bf59894a7c79
parttee/tira2020
/week3/fixlist.py
452
3.546875
4
def changes(t): n = len(t) changes = 0 for i in range(1, n): prev = t[i - 1] v = t[i] d = max(prev - v, 0) if v < prev: changes += d prev = v + d t[i] = prev return changes if __name__ == "__main__": print(changes([3, 2, 5, 1, 7])) # ...
08dddcc6eb9d0d565d4cc9fe40f24a1cbac6b78b
wilsonbow/CP1404
/Prac05/dates_of_birth.py
244
3.921875
4
num_names = 5 names_dict = {} for i in range(1, num_names + 1): this_name = input("Name {}: ".format(i)) this_dob = input("DOB (dd/mm/yyyy): ") this_dob = this_dob.split('/') names_dict[this_name] = this_dob print(names_dict)
4404e39852e74e7ca1ad170550b02fd3b09f76dd
wilsonbow/CP1404
/Prac03/gopher_population_simulator.py
1,190
4.5
4
""" This program will simulate the population of gophers over a ten year period. """ import random BIRTH_RATE_MIN = 10 # 10% BIRTH_RATE_MAX = 20 # 20% DEATH_RATE_MIN = 5 # 5% DEATH_RATE_MAX = 25 # 25% YEARS = 10 print("Welcome to the Gopher Population Simulator!") # Calculate births and deaths def gopher_births(po...
bf7f37daf9416a72a47f872bed882e87afc57a25
vikash2109/python
/Python/cinema.py
768
3.953125
4
films={"Findings Dory":[3,5], "Bourne":[18,5], "Tarzan":[15,5], "Ghost Busters":[12,5] } while True: choice = raw_input("What films would you like to watch?:").strip().title() if choice in films: age=int(raw_input("How old are you?:").strip()) if age >f...
f53eb57e9cfe18c4672d2b4f2fbadfede6c73493
SamArtGS/Python-Intermedio
/Excepcion.py
959
3.765625
4
#try: # f=open("archivo.txt","r") # datos=f.readlines() #except: # print("Error al abrir el fichero") #finally: # f.close() # with open("archivo.txt","r") as f: contenido = f.read() #PAra que se ejecuten automáticamente sentencias, al terminar esa sentencia pasará automáticamente algo class closing(object): def __ini...
117b11fc9877f256a1530ae600cf4974709f6f9c
pud1m/puc-isi-candidatos-2021
/modules/computing.py
870
3.640625
4
def get_base_payload(year): """ Returns a base payload for the year """ return { 'year': year, 'gender': { 'universe': 0, 'women': 0, 'totalElected': 0, 'womenElected': 0, }, 'age': { 'candidates': [], 'elected': [] } } def compute_data(payload): """ R...
622270fe79360de410d277f6cacac7cf1c968bb7
AlfredPianist/holbertonschool-higher_level_programming
/0x03-python-data_structures/2-main.py
662
4.09375
4
#!/usr/bin/python3 replace_in_list = __import__('2-replace_in_list').replace_in_list my_list = [1, 2, 3, 4, 5] print("Original list") print(my_list) idx = 3 new_element = 9 new_list = replace_in_list(my_list, idx, new_element) print("New list with idx 3 replaced by 9") print(new_list) print(my_list) new_list = rep...
0f7ce5070086230718720870a6a3c20e7e52471e
AlfredPianist/holbertonschool-higher_level_programming
/0x0B-python-input_output/9-student.py
850
4.0625
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- """9-student This module creates class `Student` with public attributes first_name, last_name and age, and a public method ``to_json`` that retrieves a dictionary representation of a Student instance. """ class Student(): """A simple Student class. Attributes: ...
48962a04b339bd45b604eaf525747de3ebc295a9
AlfredPianist/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/rectangle.py
4,981
4.125
4
#!/usr/bin/python3 # -*- coding:utf-8 -*- """rectangle module. This is the Rectangle class inherited from the Base class, with private attributes width, height and x and y as offsets for printing the rectangle, each with its getters and setters, and public methods area, display, update, and to_dictionary. """ from mod...
32d8bf289cc25007e1359fc8c9a8b84e2deb0425
AlfredPianist/holbertonschool-higher_level_programming
/0x10-python-network_0/6-peak.py
892
4.09375
4
#!/usr/bin/python3 """ Function that finds a peak in a list of unsorted integers """ def find_peak(list_of_integers): """Main find_peak function""" if (type(list_of_integers) != list or len(list_of_integers) == 0): return 0 list_len = len(list_of_integers) return find_peak_helper(list_of_integ...
c1c268aa78f389abc625b582e37ba9316f36a849
AlfredPianist/holbertonschool-higher_level_programming
/0x06-python-classes/100-singly_linked_list.py
2,885
4.3125
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- """100-singly_linked_list A Node class storing integers, and a Singly Linked List class implementing a sorted insertion. """ class Node: """A Node class. Stores a number and a type Node. Attributes: __data (int): The size of the square. __next_node (...
f6bbf632124358d644b37819b66ea52f2010d960
AlfredPianist/holbertonschool-higher_level_programming
/0x0A-python-inheritance/7-base_geometry.py
954
3.78125
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- """7-base_geometry This module creates a class `BaseGeometry` with access to methods ``area`` and ``integer_validator. """ class BaseGeometry(): """BaseGeometry class with methods ``area`` and ``integer_validator``.""" def area(self): """A method with a sol...
e62c99e0a88f67778b9573559d2de096255a3e2d
AlfredPianist/holbertonschool-higher_level_programming
/0x0B-python-input_output/2-append_write.py
479
4.28125
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- """2-append_write This module has the function write_file which writes a text to a file. """ def append_write(filename="", text=""): """Writes some text to a file. Args: filename (str): The file name to be opened and read. text (str): The text to be ...
b995f4a7d2167c37c9e9dab4d07ad6c1074d5870
AlfredPianist/holbertonschool-higher_level_programming
/0x0B-python-input_output/5-save_to_json_file.py
502
3.921875
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- """5-save_to_json_file This module has the function save_to_json_file which writes a file with the JSON representation of an object. """ import json def save_to_json_file(my_obj, filename): """Writes a file with the JSON representation of an object. Args: my...
4dc5436727deeb74f913e2cc676568fde891aee7
anantgupta04/Coding-Challenges
/space_time_complexity.py
944
3.953125
4
''' Asked by: Stripe Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. For example, the input [3, 4, -1, 1] should give ...
9acd03a2950b2bcd0bbbc6b0cdc5c44c71997b08
fud200/p1_201611067
/W9/w9main.py
587
3.578125
4
import math kyungbokgung=tuple() kyungbokgung=(37.575797, 126.973468) gwang=tuple() gwang=(37.571599, 126.976584) anguk=tuple() anguk=(37.576481, 126.985449) dokrib=tuple() dokrib=(37.574559, 126.957765) jonggak=tuple() jonggak=(37.570149, 126.983076) cityhall=tuple() cityhall=(37.565696, 126.977114) stations=list() s...
ab2e4ab754d571fcb0c206324b480f84f5604c01
lsfischer/Taxify
/spark_rdd_client.py
4,248
3.578125
4
import pyspark from pyspark.sql import SparkSession import traceback import calendar spark = SparkSession.builder.master('local[*]').appName('taxify').getOrCreate() sc = spark.sparkContext def get_user_options(): """ Function that gets all the users input for creating the inverted index. This func...
bbb4a67092b02f132bb0decd76bf80c7e219c761
orlychaparro/python_cardio_platzi
/code/reto2_piedra_papel_tijera.py
2,937
4.15625
4
""" Reto 2 - Piedra, papel o tijera Ejercicios realizados por Orlando Chaparro. https://platzi.com/p/orlandochr Escribe un programa que reciba como parámetro “piedra”, “papel”, o “tijera” y determine si ganó el jugador 1 o el jugador 2. Bonus: determina que el ganador sea el jugador que gane 2 de 3 encuentros. Ejemp...
e1158aa7ec734bf029dc2a6e3c3d781a65a409bb
MarcPalomo/NorthwesternBootCamp
/python-challenge/PyBank/main.py
2,305
3.859375
4
#import os import os # read the csv import csv csvpath = os.path.join("budget_data.csv") with open(csvpath, newline='') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') csv_header = next(csvreader) # start start all the variables at 0 since the header will get skipped row_total...
2c6d1dc11a27dbf06f909d9fb5054916a3298202
paulcdejean/project-euler
/1.py
121
3.890625
4
#!/usr/bin/python answer = 0 for x in range(1000): if (x % 3 == 0) or (x % 5 == 0): answer += x print answer
227fce25bf6584d1fcfcf3f3857fbfb1fcb84c71
BRutan/PythonScripts
/FileFunctions.py
4,578
3.765625
4
################################################################################################ ## FileFunctions.py ################################################################################################ # * Description: Define functions useful in working with files. import csv import os import win32f...
a9e1f9ced95aff674f68abce6ed89c4009766872
alvaro-ai/IA_I
/TP_4/main.py
4,305
3.546875
4
# https://docs.google.com/document/d/1Ocz9ZmOkIiVV7kgDguH99cpOWDKuxoKF6hwgtIv_NNQ/edit from random import randrange, seed import colorPrint #seed(121) def crear_mapa(size): map = [None] * size for i in range(size): map[i] = [None] * size for i in range(0, size): for j in range(0, size): ...
0ead716252440ff54d7f520ff9574c2e09ea631b
ties/algorithm-challenges
/hackerrank/python/interview_prep/string_manipulation/special_substring.py
1,033
3.75
4
#!/bin/python3 import math import os import random import re import sys def drop_middle(s: str) -> str: len_s = len(s) if len_s % 2 == 0: return s if len_s < 3: return s half_len = len_s // 2 return s[0:half_len] + s[half_len+1:] def all_the_same(s: str) -> bool: len_s = len(...
1efe7705c0d23449f9d102cf6173296b5e832e0f
ties/algorithm-challenges
/hackerrank/python/interview_prep/string_manipulation/sherlock_and_the_valid_string.py
858
3.84375
4
#!/bin/python3 import math import os import random import re import sys from collections import Counter # Complete the isValid function below. def isValid(s): char_counts = Counter(s) occurence_counts = Counter(char_counts.values()) if len(occurence_counts) <= 1: return "YES" elif len(occur...
6659910ba28b675bba71b78a3600a9baeb1e6626
another-maverick/design-patterns
/singleton/python/singleton.py
943
3.984375
4
#!/Users/vadlakun/.pyenv/shims/python class Singleton: class __inner: """ An inner class that implements singleton. """ def __init__(self, arg): self.val = arg def __str__(self): return repr(self) + self.val single_instance = None def __i...
e027dd5a8d329e991594ee6f1eb693581367c61f
tyler-patton44/CodingDojo-Sept-Dec-2018
/Python/python_OOP/SList2.py
1,455
3.796875
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): ...
4517bb35bd493297825e93b603cd454db1d1f7a7
tyler-patton44/CodingDojo-Sept-Dec-2018
/Python/python_OOP/bike.py
968
4
4
class bike: def __init__(self, price, max_speed, miles): self.price = price self.max_speed = max_speed self.miles = miles def ride(self): self.miles = self.miles + 5 def reverse(self): self.miles = self.miles - 5 def displayInfo(self): print("price:", s...
c51da4549dc5effcf1187071aaa8a55fbdd2be74
Herrj3026/CTI110
/P3HW2_DistanceTraveled_HerrJordan.py
888
4.34375
4
# # A program to do a basic calcuation of how far you travled # 6/22/2021 # CTI-110 P3HW2 - DistanceTraveled # Jordan Herr # #section for the inputs car_speed = float(input("Please enter car speed: ")) time_travled = float(input("Please enter distance travled: ")) #math section for the calculations dis_...
bafccac8c8c35d2411cebc53c12964b38da00fff
dero24/task_manager
/TaskManager/create_task.py
477
3.625
4
import re def append_task(cur_user, user_tasks): while True: task = input("Enter task name: ") date = input("Enter date to run task (XX-XX-XXXX): ") if match := re.search('\d\d-\d\d-\d\d\d\d', date): break print() user_tasks[cur_user].append([task,date]) ...
69ef0a8c684bd46b9b79c8ab3460c5b829d83b85
pramilagm/Data_structure_and_algorithm
/sortingALgos/bubblesort.py
350
4.09375
4
def bubbleSOrt(arr): n = len(arr) for j in range(n): swapped = False for i in range(0, n-j-1): if(arr[i] > arr[i+1]): arr[i], arr[i+1] = arr[i+1], arr[i] swapped = True if(swapped == False): break return arr arr = [13, 8, 3,...
82060a79bfe89515e5f05ab0ec4dd6a824767bdf
pramilagm/Data_structure_and_algorithm
/BST/isBinarySearchTree.py
687
3.71875
4
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def check_binary_search_tree(root): return isBinaryUtl(root, None, None) def isBinaryUtl(root, left, right): if root is None: return True if left != None and root.data <= left.da...
a169a1c768eb52bc7da47fb365d260e2cd6934ea
pramilagm/Data_structure_and_algorithm
/LinkedList/doublyLinkedList/isPalindrome.py
1,117
3.796875
4
class Node: def __init__(self, data): self.data = data self.next = None self.prev = None class DDL: def __init__(self): self.head = None def isPalindrome(self): pass def push(self, data): newNode = Node(data) if self.head is None: ...
163336962e6ba9174bda258e3d7c84a22ff79a22
shuaib88/algorithms_review
/data_structures/remove_max_from_stack.py
1,978
4.03125
4
class Stack: # initialize an empty list def __init__(self): self.items = [] # push a new item to the last index def push(self, item): self.items.append(item) # remove the last item def pop(self): # if the stack is empty, return None # (it would also be reasonab...
2c9fa5061cf0ebde85e256a5f83c79982b851810
haydenptornabene/mgive
/PhoneMassage/phonemassage.20161214.py
6,188
3.921875
4
# This script will take .xlsx (Excel) files and peform the following operation: # 1. It will take a phone number written in some strange way, (303)-990-1002, and return # a string of that phone number, 3039901002. # 2. This script is smart enough that it will take any column in the excel file titled # 'Phone Num...
b37ecfe77417b55d00d7a433f4b47093fd729852
jgpeco/harvard_cs50
/pset6/mario/more/mario.py
231
3.671875
4
from cs50 import get_int h = 0; while(True): h = get_int('Height: \n') if(h > 0 and h <= 8): break for i in range(h): spaces = ' ' * (h-i-1) blocks = '#' * (i+1) print(f'{spaces}{blocks} {blocks}')
c59a4dff73b60bc3b56b1fca00b43d9d80a99231
xwmyth8023/python-date-structure
/sort_and_search/shell_sort.py
665
3.984375
4
"""希尔排序""" def shell_sort(num_list): n = len(num_list) step = n // 2 """ 比较第index项和与第index项相隔step的项,如果第index项小于相隔step项,则交换位置 """ while step >= 1: for i in range(step, n): index = i while index - step >= 0: if num_list[index] < num_list[index - ste...
3f1988976a3a7a852db16b768af7bf8279736b53
xwmyth8023/python-date-structure
/sort_and_search/order_search.py
356
3.828125
4
"""顺序查找""" def order_search(num_list,target): index = 0 found = False """从索引0开始查找,依次加1,直到找到目标""" while index < len(num_list) and not found: if num_list[index] != target: index += 1 else: found = True return found print(order_search([1,2,3,4,5,6],7))
bcaa46b3e1cc5dbff52abb328b7eb3a11184df87
xwmyth8023/python-date-structure
/queue/deque.py
1,528
4.25
4
""" deque(也称为双端队列)是与队列类似的项的有序集合。 它有两个端部,首部和尾部,并且项在集合中保持不变。 deque 不同的地方是添加和删除项是非限制性的。 可以在前面或后面添加新项。同样,可以从任一端移除现有项。 在某种意义上,这种混合线性结构提供了单个数据结构中的栈和队列的所有能力。 deque 操作如下: 1. Deque() 创建一个空的新 deque。它不需要参数,并返回空的 deque。 2. addFront(item) 将一个新项添加到 deque 的首部。它需要 item 参数 并不返回任何内容。 3. addRear(item) 将一个新项添加到 deque 的尾部。它需要 item 参数并不返回任...
1b49166a5a51dfe2867443fed86d0e236b26aaa5
nibill/BME-CAS
/assignments/toolcalibration/calibration.py
864
3.5
4
import numpy as np def pivot_calibration(transforms): """ Pivot calibration Keyword arguments: transforms -- A list with 4x4 transformation matrices returns -- A vector p_t, which is the offset from any T to the pivot point """ p_t = np.zeros((3, 1)) T = np.eye(4) A = []...
d4a3339ea000210d5d5a10abbfbf99baec02928b
condad/mcgill
/206/assign_5/cgi-bin/formgen.py
2,488
3.984375
4
#!/usr/bin/env python def top(): print "Content-type: text/html\n\n" print """ <!DOCTYPE html> <html> <head> <title>Create Survey</title> <link rel="stylesheet" href="http://www.cs.mcgill.ca/~csulli7/style.css"> </head> <body> <div class="header"> <h1>Create Survey</h1> </div> <div class="menu...
565f35fe1655159ab0dd5c6ecd2f844708f0e37a
furgerf/advent-of-code-2019
/day_02/day_02.py
781
3.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from day import Day from intcode import Intcode class Day02(Day): def __init__(self): super(Day02, self).__init__(2) def parse_data(self): return self.parse_intcode_data() @staticmethod def intcode(data, noun, verb): data[1] = noun data[2] = ve...
0eba10a052a69675d1bf71230652014d58d18e76
nijo34/Cats_Bats_Spiders
/scripts/Cats_Bats_Spiders_ProfessorRenderer.py
305
3.65625
4
# Author: Professor Renderer # Language: Python # Github: https://github.com/Renderer-RCT2 x = 0 for x in range(1, 100): if x % 3 is 0 and x % 5 is 0: print("spiders") elif x % 3 is 0: print("cats") elif x % 5 is 0: print("bats") else: print(str(x))
de58ce2b88fe8672528880af3d30942d09602b9b
jamjs98764/OMI-Internship-Test
/binary_tree/tree.py
4,822
3.984375
4
from collections import deque from random import randint import math ###### # Part 1: Tree Class ##### class binaryTree(): # Simple implementation of binary search tree, with insertion and search def __init__(self,value): self.left = None self.right = None self.value = value def getLeftChild(self): ret...
188986f6076392455e7b8b685622b82cd1547105
alvin-c/messenger-visual-analytics
/select.py
1,520
3.65625
4
from pathlib import Path from tkinter import filedialog from tkinter import * from os import walk def select_convo(): """ Selects the conversation folder to analyze TODO: make this a nice scrollable list for the user to select via GUI :return: convo_folder_filepath """ # Create local tmp dir...
7837e83f37f3250752a719a018dc37c742096c2f
Quaifep/change.py
/change.py
367
3.875
4
# Author: Paul Quaife # Date: 1/12/2020 # Description: Gives change for less than a dollar in highest amount. print("Please enter an amount in cents less than a dollar.") coins = int(input()) print("Your change will be:") print("Q:", coins // 25) coins = coins % 25 print("D:", coins // 10) coins = coins % 10 print("N:...
22f15679fb6ba73890d58612d28a507cc6c62aa7
stulsani/Additional-WorkSpace
/Data_Structure/Python/MultiProcessing/mp.py
426
3.515625
4
from multiprocessing import Pool import multiprocessing def myfunction(num): print("Process No. {}".format(num)) def job(num): return num*2 if __name__ == '__main__': for i in range(100): p = multiprocessing.Process(target=myfunction(i),args=(i,)) p.start() p.join() p1 = Pool...
163b9addcdb7263e314ffe3851886222654d57e7
stulsani/Additional-WorkSpace
/Data_Structure/Python/dictionaryoperations/dictoperation.py
347
3.5625
4
shopping = { 'soap' : 3.45, 'shampoo' : 7.50, 'crackers' : 10.23, 'protein bars' : 20.00, 'protein powder' : 60.59 } print(min(zip(shopping.values(),shopping.keys()))) print(max(zip(shopping.values(),shopping.keys()))) print(sorted(zip(shopping.values(),shopping.keys()))) print(sorted(zip(shopping....
858230eecdd1015a9f42001e9804e0693072c41f
SBrman/Project-Eular
/6.py
618
3.9375
4
#! python3 """ Sum square difference Problem 6 The sum of the squares of the first ten natural numbers is, 1**2+2**2+...+10**2=385 The square of the sum of the first ten natural numbers is, (1+2+...+10)**2 = 55**2 = 3025 Hence the difference between the sum of the sq...
3cec4c83350a40b81dc8e58910b57ce3e5c5428d
SBrman/Project-Eular
/4.py
792
4.1875
4
#! python3 """ Largest palindrome product Problem 4 A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. """ def isPalindrome(num): num = str(...
e64851f537f4bbc6ab07a90a80f4faf8eb348f1d
craighawki/python_bootcamp
/love_calculator.py
2,106
4.0625
4
#! /usr/bin/env python # 🚨 Don't change the code below 👇 print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is their name? \n") # 🚨 Don't change the code above 👆 #Write your code below this line 👇 t1_count = name1.lower().count("t") t2_count = name2.lower().count...
88f6ba0e4dd029aae005d9a72e8b9505324de894
craighawki/python_bootcamp
/passwordgen.py
2,380
3.859375
4
#!/usr/bin/env python import random from random import shuffle #Password Generator Project letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', ...
9280b1fe46cebc42e3576335fc367af6d42139b7
konantian/Data-Structure
/Codes/BinarySearchTree.py
9,466
3.984375
4
class TreeNode: def __init__(self,initdata,initleft,initright): self.value=initdata self.left=initleft self.right=initright class BST: #Initialize the root node def __init__(self): self.root=None self.size=0 #Get the left child value of given key def getLeft(self,key): return self.find(key).left.val...
6b8af418e394aae618b409bfd0e397580cff36a3
konantian/Data-Structure
/Codes/BinaryTree.py
2,257
3.984375
4
from BinarySearchTree import BST,TreeNode class BinaryTree(BST): #Add a key to the tree in level order def insert(self,key): temp=TreeNode(key,None,None) if self.root is None: self.root=temp else: stack=[self.root] while True: node=stack.pop(0) if node.left is None: node.left=temp ...
ffa6cc751a1a6844621185ac94a1f015677f11f1
jonathanjdavis/euler
/problem.0004/problem4.py
256
3.65625
4
#!python3 num1 = 999 num2 = 999 palindrome = set() while num1 > 100 : while num2 > 100 : x = num1 * num2 if str(x) == str(x)[::-1] : palindrome.add(x) num2 -= 1 num1 -= 1 num2 = 999 print(max(palindrome))
9af7f0f7a29798891798048deea3137e95eca3f4
Jimmyopot/JimmyLeetcodeDev
/Easy/reverse_int.py
2,193
4.15625
4
''' - Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). ''' # soln 1 class Solution(object): ...
03771000919750582f4e9899e9c509c15fcbf40b
Jimmyopot/JimmyLeetcodeDev
/Easy/prefix.py
3,336
4
4
''' Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: strs = ["flower","flow","flight"] Output: "fl" ''' # soln 1 class Solution(object): def longestCommonPrefix(self, strs): if len(strs) ...
718ea718ecdb01fa9b61c52187e55b98bd041a49
Jimmyopot/JimmyLeetcodeDev
/algorithms/recursion.py
1,767
3.65625
4
''' - Recursion is a way of programming or coding a problem, in which a function calls itself one or more times in its body. - Recursion in computer science is a method where the solution to a problem is based on solving smaller instances of the same problem. ''' # soln 1 def factorial(n): if n == 1: ...
940c9290705eb80d2ad7292b4075eb98f0c791e4
Jimmyopot/JimmyLeetcodeDev
/Easy/climbing_stairs.py
1,773
4
4
''' 70. Climbing Stairs You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? ''' ''' DYNAMIC PROGRAMMING - All about RECURSION => REPETITION! - Pattern based, eg, Fibonacci sequence. - Find a recursive so...
56888aa535ee5c33f476d621e6f3fcde0d24b9ee
SelinaBlijleven/MachineLearning
/10574689_Blijleven_Prog5/split_data.py
2,064
3.84375
4
""" Selina Blijleven 10574689 Programming Assignment 5 December 2015 """ import csv import numpy as np def main(file_name="digist123-1.csv", train_p = 0.6, validation_p = 0.2, test_p = 0.2): """ Splits the data from a given file into smaller sets given three proportions. """ data...
c202cc468ad1fe9fb9ff53bb8f105de980aeaa8f
aashir789/PythonPractice
/91_decode_ways.py
1,719
3.875
4
''' A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given a non-empty string containing only digits, determine the total number of ways to decode it. Example 1: Input: "12" Output: 2 Explanation: It could be decoded as "AB" (1 2) or "L" (...
cd81229ef2a96ae1996b7a0b8c179263dc8e4f60
anuragmallick/Assignment-10
/assignment 11/a11.py
457
4.09375
4
#Question 1 import re j=0 email=input("enter email") a=re.finditer("^[a-z A-Z 0-9][_a-zA-Z0-9.]*(@)(gmail.com|yahoo.com)$",email) for m in a: j=m.group() if email==j: print("valid email") else: print("invalid email") #Question 2 import re i=0 n=input("enter number") a=re.finditer("^[6-9]\d{...
7c963189ff182c8e89334f59280af99602198a13
kevinawood/pythonprograms
/Pvault.py
559
3.515625
4
#! python3 #pvault.py - Dungeon of passwords import sys import pyperclip PASSWORDS = {'email' : 'erger', 'facebook' : 'sdfrferg', 'MEW' : 'sds#' } if len(sys.argv) < 2: print('Usage: python pvault.py [account] - copy account password') sys.exit() account = sys.argv[1] ...
b58ae8395c1283f60765b7dab5e0d80bb3b97751
kevinawood/pythonprograms
/LeagueDraw.py
1,539
4.125
4
import random import time teams = ['Sevilla', 'Bayern', 'Roma', 'Barcelona', 'Manchester City', 'Liverpool', 'Juventus', 'Real Madrid'] draw = [] def draw(): #for i in range(len(teams)): for i in range(len(teams), 1, ...
7be82d335f8ce68dc0d5b12c91d8e3b66c4dcb20
kevinawood/pythonprograms
/NBALottery.py
1,149
3.5625
4
# NBA lottery # # import os import pprint import random import time teams = [] draft_order = {} bye_lottery = "Thank you for participating in this years NBA lottery\nHave an amazing evening." def nbateams(): with open('nbateams.txt') as f: lines = list(f) for i in range(15): teams.append(rando...
b0af8d9a9bf7534ee368b3eddf2bcc9edc32a60c
souravk1113/course-projects
/nqueens.py
860
3.5625
4
def check(i,j,n): global board for x in range(n): if board[i][x]==1: return False if board[x][j]==1: return False for x in range(n): for y in range(n): if x+y==i+j and board[x][y]==1: return False if x-y==i-j and board[x][y]==1: return False return True def display(board,...
df57d9496d5318f74f7b0a4cb68dc4e259a8bf75
pzhao1799/WilliamstownPoliceModeling
/fuzzy_search.py
825
3.796875
4
# How to search fuzzy from fuzzywuzzy import fuzz from fuzzywuzzy import process import pandas import argparse import sys import math # Create the parser parser = argparse.ArgumentParser(description='OCR') # Add the arguments parser.add_argument('csv', metavar='csv', ...
399cb2a542e995969b17089d75fb73b1018dc706
dspec12/real_python
/part1/chp05/invest.py
923
4.375
4
#!/usr/bin/env python3 ''' Write a script invest.py that will track the growing amount of an investment over time. This script includes an invest() function that takes three inputs: the initial investment amount, the annual compounding rate, and the total number of years to invest. So, the first line of the functio...
97b77d34419916777ca28b3fd81a02f718603431
dspec12/real_python
/part1/chp07/7-1.py
447
4.0625
4
#!/usr/bin/env python3 ''' Figure out what the result will be (True or False) when evaluating the following expressions, then type them into the interactive window to check your answers: 1 <= 1 1 != 1 1 != 2 "good" != "bad" "good" != "Good" 123 == "123” ''' print(1 <= 1, "A: True") print(1 != 1, "A: False ") ...