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
2081835326d1b1d0697ccedf501fe8ad5a47d21d
gatlinbredeson/US-Medical-Insurance-Costs
/Insurance Analysis.py
9,830
3.71875
4
from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split import pandas as pd from matplotlib import pyplot as plt def get_stats(dataframe, column): """ Prints the average and standard deviation for the data in column :param dataframe: DataFrame containing the ...
21cf23a41920667e122a1110d48c2de95643e92a
Net-Admin/TitanPay
/src/Accounting/allemployees.py
496
3.734375
4
import csv import sys import pprint #function to convert a csv file to a list of dictionaries. #Takes in variable - "all_employees" def csv_dict_list(all_employees): reader = csv.DictReader(open('D://Users/medic/PycharmProjects/TitanPay/src/Accounting/Data/all_employees.csv'), delimiter = ',') result = {} ...
f431acc25953c26fa8f95116049ad3a4bd3b6593
yonghyeokrhee/algorithm-local
/ridi/ridi1.py
344
3.65625
4
def solution(arr): answer = [] newarr = list(range(1, len(arr) + 1)) for i in newarr: prefix = newarr[i - 1:] suffix = newarr[:i - 1][::-1] answer.append(arr == (prefix + suffix)) #print(prefix + suffix) print(bool(sum(answer))) if __name__ == "__main__": arr = [3,2...
8090250a484841cbae1fe3c19d3c1ce38e96138c
hodquang/Chess-Moves-Validation-Program
/Helpers.py
2,081
3.609375
4
def numToChar(num): # Num to Rank map = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8} for i in map: if map[i] == num: return i def charToNum(char): # Rank to Num map = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8} for i in map: if i == char: return map[i] def numTo...
f3da163c3c66d0b6efd3ec172839d3594f5b500f
hughian/OJ
/LeetCode/Python/M863. All Nodes Distance K in Binary Tree.py
1,901
3.78125
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 distanceK(self, root, target, K): """ :type root: TreeNode :type target: TreeNode :type K: int ...
684cde2571ef0a7607182a03dff122fb06cd69d7
hughian/OJ
/LeetCode/Python/M865_ Smallest Subtree with all the Deepest Nodes.py
1,980
3.8125
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: parents = {} m = 0 mleaf = set() def pre(root,...
b5d6291433c08f34a6dfe1fbd67c08fc34dea755
hughian/OJ
/LeetCode/Python/E572_SubtreeOfAnotherTree.py
533
3.53125
4
class Solution: def isSubtree(self, s, t): """ :type s: TreeNode :type t: TreeNode :rtype: bool """ def isSame(s, t): if s==None and t==None: return True elif (not s and t) or (s and not t): return False else: return s.val==t.val an...
54bbc6cb757598ce0729bea9000512324d83dbdf
hughian/OJ
/LeetCode/Python/M114. Flatten Binary Tree to Linked List.py
2,177
3.734375
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def flatten(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ def pre(root): if not root:...
7d0985e8d2ff50acbc002f08c439f6139c80ec33
hughian/OJ
/LeetCode/LeetCode/Tree.py
18,896
3.78125
4
import collections from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def __repr__(self): return f'{{ {self.val}, left:{{{self.left}}}, right{{{self.right}}}}}' class ListNode: def __init__(self, val): se...
8491fcf0d5de498c43906a5434c8ea7bc5c1d6c9
amanabhishk/project-euler
/greatestprime.py
535
3.53125
4
def prime_check(n): total = True for i in range(2,n/2): total = total and n%i != 0 if total == False: return False return True prime = [] for i in range(2,100000): if prime_check(i) == True: prime.append(i) def greatest_prime_factor(n,prime): k = 1 for i in range(0,len(prime)): print 'prime is:' ,pr...
c68ad1c994e775c5ec6084cf50c58044e83beea7
Ahmetnarin/PythonCrashCourse_Code
/cubes.py
84
3.578125
4
cubes = [value ** 3 for value in range(0,11)] for cube in cubes: print(cube)
e46a2594256f47196d860e8be455da5dbe900c70
Ahmetnarin/PythonCrashCourse_Code
/helloadmin.py
401
3.578125
4
userlist= ['admin'] for i in range(1,1000+1): userlist.append('user_'+str(i)) #print("userlist= ",userlist) if userlist: for user in userlist: if user == 'admin': print("Hello "+ user + " would you like to see a status report?") else : print("Hello " + user + ", tha...
17414bbb1a1bed1a5214fd5499fa66137e2bbd87
Ahmetnarin/PythonCrashCourse_Code
/amusement_park.py
782
3.8125
4
import datetime print("Welcome to Amusement Park. ", datetime.datetime.now()) year = datetime.date.today().year # Persons birthdate who want to entry in the park dad = 1960 mom = 1965 child1 = 2000 child2 = 2001 child3 = 2002 child4 = 2003 child5 = 2015 child6 = 2018 birthdates = [dad, mom , child1 , ch...
3d2b806928e50a251478925e8e3b02ead73397f3
Ahmetnarin/PythonCrashCourse_Code
/checking_username1.py
799
3.578125
4
current_user = [] for i in range(0,100): current_user.append('current_user_' + str(i)) # Add end of the list two new users which have to same name with new_user. current_user.append('John') current_user.append('Georg') new_user =[] for i in range(0,100): new_user.append('new_user_' + str(i)) # Add end of th...
a0ffe00c2134319bcd85d4a66aead7f5ad0c9f47
Ahmetnarin/PythonCrashCourse_Code
/matrixmultiplication.py
826
3.859375
4
def matrix_mult(A,B): rows_A = len(A) cols_A = len(A[0]) rows_B = len(B) cols_B = len(B[0]) if cols_A != rows_B: print("It is not possible!!") return C = [[0 for row in range(cols_B)] for col in range(rows_A)] for i in range(rows_A): for j in range(...
512715c26d5c911ed80ca54e15d6c5c02b819a78
lufonius/ml-hello-world
/package/linear_algebra/line.py
1,780
3.75
4
from .point import Point from .vector import Vector import typing class Line: # Ax + By = k # where the normal vector is [A, B] # and the constant_term is k # [x, y] can be any direction vector def __init__(self, normal_vector: Vector, constant_term: float): self.__normal_vector = normal_ve...
6093e47d62152f55277e49a0752de968cfb16860
felixdittrich92/Python3_book
/00_Original/32_Parallele_Programmierung/multiprocessing/primzahltest_multiprocessing_locking.py
1,202
3.640625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import multiprocessing class PrimzahlProzess(multiprocessing.Process): def __init__(self, zahl, einauslock): super().__init__() self.Zahl = zahl self.EinAusLock = einauslock def run(self): i = 2 while i*i <= self.Zahl: ...
a720c8f632e937225f192cd7f83a612132b4b9b6
felixdittrich92/Python3_book
/00_Original/05_Kontrollstrukturen/break.py
408
3.65625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- geheimnis = 1337 versuch = -1 zaehler = 0 while versuch != geheimnis: versuch = int(input("Raten Sie: ")) if versuch == 0: print("Das Spiel wird beendet") break if versuch < geheimnis: print("Zu klein") if versuch > geheimnis:...
17834f02169a161dcfc13bcc452771c8061946ff
felixdittrich92/Python3_book
/00_Original/19_Funktionen/fakultaet2.py
342
3.671875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def betrag(zahl): if zahl < 0: return -zahl else: return zahl def fak(zahl): ergebnis = 1 for i in range(2, zahl+1): ergebnis *= i return ergebnis while True: eingabe = int(input("Geben Sie eine Zahl ein: ")) print(...
cdc76df6aeb9b8eaac0ec2f086cbaa939db99798
felixdittrich92/Python3_book
/00_Original/39_Grafische_Benutzeroberflaechen/TkInter/widgets/radiobutton.py
767
3.546875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import tkinter class MyApp(tkinter.Frame): def __init__(self, master=None): super().__init__(master) self.pack() self.auswahl = ["Berlin", "London", "Moskau", "Ottawa", "Paris", "Rom", "Tokio", "Washington DC"]...
5fe351283b2427f7f6f5a6bf737f117d28012d4a
felixdittrich92/Python3_book
/00_Original/39_Grafische_Benutzeroberflaechen/TkInter/beispiel2_events.py
1,567
3.515625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import tkinter class MyApp(tkinter.Frame): def __init__(self, master=None): super().__init__(master) self.pack() self.createWidgets() self.createBindings() def createWidgets(self): self.label = tkinter.Label(self) ...
4baf49f12262b9d79f3fb3fe2a0df50c52e21acc
fudigit/Basic_Algorithm
/7.Permutation-based&Graph-based_DFS/16.Permutations_II.py
1,796
3.84375
4
''' purmutations with duplicate numbers use dfs with dup tweak How to avoid dups? i.e, [1,2,2'] [1,2,2'] and [1,2',2] will be dups, what are their paths? 1. [1] -> [1,2] -> [1,2,2'] 2. [1] -> [1,2'] -> [1,2',2] # - we only pick path 1, so in the for loop, if previous # is the same and has not been visited, skip # - no...
b21de42d3e9975c9ad8c79c5219293bb4940f4e7
fudigit/Basic_Algorithm
/6.Combination-based_DFS&Memoization_Search/152.Combinations.py
2,042
3.5
4
''' 1. use range(1, n + 1) as the list of candidates 2. find the subset (without reapeating) using dfs 3. constraint: return when there are k elements O(c(n,k)*k) ''' class Solution: """ @param n: Given the range of numbers @param k: Given the numbers of combinations @return: All the combinations of ...
d7aa3500e9aa5b798523779fca2030286b2b71c0
fudigit/Basic_Algorithm
/7.Permutation-based&Graph-based_DFS/33.N-Queens.py
2,013
3.734375
4
''' permutation trick: a permutation of the numbers can represent the queen on the drawChessboard i.e., [1,3,0,2] -> (0,1), (2,3), (3,0), (4,2) has a queen # 1. The question become finding a permutation such that no queen can attack other queens # 2. Use a drawChessboard function to draw the chessBoard # 3. Use a isVa...
31cdc826950e586a890b6681a9104dc6dd265707
fudigit/Basic_Algorithm
/8.Data_Structure__Stack_Queue_Hash_Heap/545.Top_k_Largest_Numbers_II.py
624
3.671875
4
''' use a minimum heap, similar to LC 544 ''' import heapq class Solution: """ @param: k: An integer """ def __init__(self, k): self.heap_min = [] self.size = k """ @param: num: Number to be added @return: nothing """ def add(self, num): heapq.heappush(self....
5ed9ee259e97790a127a533994f8d3e59216e4c4
fudigit/Basic_Algorithm
/3.Two_Pointers/464.Sort_Integers_2.py
4,141
3.96875
4
'''bubble sort''' ''' 1. raising the largest number from left to right of array take n-1 comparisions 2. n - 1 raising is needed to sort all elements - O(n-1)*O(n-1) = O(n^2) ''' class Solution: """ @param A: an integer array @return: nothing """ def sortIntegers(self, A): if A == []: ...
25541f8cd1e39509c7f53d918905253e279a9503
fudigit/Basic_Algorithm
/6.Combination-based_DFS&Memoization_Search/17.Subsets.py
5,884
3.78125
4
''' start from [], turn the combination into a binary tree problem 1. for each num in the list, decide weather add it(or not) into the subset: 2. the last level (leafs) is all the subsets for [1,2] [] [1], [0] [1,2],[1],[2],[0] ''' class Solution: def subsets(self, nums): results = [] if nums == No...
35923782948559764850ddbc3132e049a25a1104
fudigit/Basic_Algorithm
/5.Binary_Tree&Tree-based_DFS/902.Kth_Smallest_Element_in_a_BST.py
1,240
3.734375
4
''' use pre order iterator ''' """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: the given BST @param k: the given k @return: the kth smallest element in BST """ def kt...
b785ba0090ee5e4d1d1b60cc752dd39599d7d3e5
fudigit/Basic_Algorithm
/2.Binary_Search&LogN_Algorithm/1219.Heaters.py
1,204
3.5625
4
class Solution: """ @param houses: positions of houses @param heaters: positions of heaters @return: the minimum radius standard of heaters """ def findRadius(self, houses, heaters): if heaters == []: return -1 hourses = sorted(houses) heaters = sorte...
da808fd3d72cf667ee897619bce8ceeb273d9cf0
fudigit/Basic_Algorithm
/11.Recursion&Non_recursion/22.Flatten_List.py
1,615
4.03125
4
''' recursion 1. traverse the nestedList, if a list, traverse items in the list, if integer, append to result ''' class Solution(object): # @param nestedList a list, each element in the list # can be a list or integer, for example [1,2,[1,2]] # @return {int[]} a list of integer res = [] def flatt...
90417d57bf4540cbfbfba026aa9862fe964d9716
Sleeither1234/t06_huatay.chunga.py
/chunga/condicional_simple_15.py
1,074
3.546875
4
# BOLETA DE VENTA DE UN CONCIERTO import os tipo_de_entrada_1 = (os.sys.argv[1]) ripo_De_entrada_2 = (os.sys.argv[2]) precio_vip = float(os.sys.argv[3]) precio_general = float(os.sys.argv[4]) unidades_vip = int(os.sys.argv[5]) unidades_general = int(os.sys.argv[6]) TOTAL = precio_vip * precio_vip + precio_general...
d551a83f39a4e7acbb96c523db6e9a255a1d6312
cjhuo/Lab_projects-EcoBT-HOST-N-SERVER
/webEngine/ecg/Histogram.py
1,348
3.65625
4
__author__ = 'leetop' # Making histogram # originaldata : data to make histogram # totalbin : the number of bins for making histogram # histodata : the result of histogram class histo() : def __init__(self, originaldata, totalbin) : # self.minimumVal : minimum data of given dataset. Starting va...
91ac1b1ae35102175e68d75e296e1ef0f64687ef
porosya80/codesignal
/electionsWinners.py
365
3.796875
4
def electionsWinners(votes, k): winners = 0 current_winner = max(votes) for item in votes: if k > 0 and item + k > current_winner: winners += 1 if k == 0 and item == current_winner and votes.count(item) == 1: winners += 1 return winners votes = [2, 3, 5, 2] k =...
fc1d237b17cea8c5dc6378225f5ffdfa14f84276
porosya80/codesignal
/is_lucky.py
171
3.546875
4
def isLucky(n): n_str = str(n) return sum([int(x) for x in n_str[:len(n_str)//2]]) == sum([int(x) for x in n_str[len(n_str)//2:]]) n =239017 print(isLucky(n))
621a84c9303d9f4a09f12497d6677b9438e1f3b7
porosya80/codesignal
/reverseParentheses.py
388
3.65625
4
def reverseParentheses(s): print(s[s.rfind("("):s.find(")", s.rfind("("))+1]) print(s[s.rfind("(")+1:s.find(")", s.rfind("("))][::-1]) while "(" in s: s = s.replace(s[s.rfind("("):s.find(")", s.rfind("("))+1], s[s.rfind("(")+1:s.find(")", s.rfind("("))][::-1]) return s ...
d33f24bf9074e07b2ed4b6c978159c4cdaff00e5
porosya80/codesignal
/findEmailDomain.py
260
3.65625
4
import re def findEmailDomain(address): result = re.search(r'(\w+(-|\.)?\w+\.\w+|\w+)$', address) return result.group(0) address = "example-indeed@strange-example.com" # address = "<>[]:,;@"! \# $%&*+-/=?^_{}| ~.a"@example.org" print(findEmailDomain(address)) # = "example.org"
c38c2435b771e32e367989015776a438ba8346d7
porosya80/codesignal
/sudoku.py
941
3.671875
4
def sudoku(grid): moves = [(x, y) for x in [1, 0, -1] for y in [1, 0, -1]] etal = set(range(1, 10)) # check = [] for row in grid: if set(row) != etal: return False for row in zip(*list(grid)): if set(row) != etal: return False for row in range(1, 9, 3): ...
dbea4298438e7e0ba2e766bbf294586c79de4538
nickbuoncristiani/170
/project-code/reader_utils.py
3,918
3.5625
4
import networkx as nx import matplotlib.pyplot as plt import STSP """ Given a naive .in file with properties as defined in the spec, read input into 0-indexed networkx graph. Calculates approximate 'cycle', then outputs to file. Assumes the matrix given is symmetric and obeys the triangle inequality for now. Assumes ...
4119f6b414150c718e8611b430c52a89412ed5b4
projects-ls/Lambda-School-Day-131-132-Hash-Tables
/resizing_hashtable/r_hashtables.py
4,042
3.921875
4
# ''' # Linked List hash table key/value pair # ''' class LinkedPair: def __init__(self, key, value): self.key = key self.value = value self.next = None # ''' # Fill this in # Resizing hash table # ''' class HashTable: def __init__(self, capacity): self.storage = [None]*capa...
bf693dc046204fb369e8449705cd986a405f588c
winnochan/algorithmic_design_and_techniques
/week4_divide_and_conquer/majority_element.py
696
3.5
4
# Uses python3 import sys def get_majority_element(a, left, right): if left == right: return -1 if left + 1 == right: return a[left] #write your code here return -1 def get_majority_element_o_n(a): c = {} n = len(a) h = n // 2 + 1 for i in a: c.setdefault(i, 0...
ac30300a5957928883c6c04958f1f0de3f237303
winnochan/algorithmic_design_and_techniques
/week2_algorithmic_warmup/fibonacci_huge.py
879
3.5625
4
# Uses python3 import sys def get_fibonacci_huge_naive(n, m): if n <= 1: return n previous = 0 current = 1 for _ in range(n - 1): previous, current = current, previous + current return current % m def get_fibonacci_huge(n, m): if n <= 1: return n dp = {} d...
1bfb5b71a6d3d08ea006d8a8b6bffaae937e78c0
Sheersha-jain/Graph
/dfs.py
590
3.65625
4
# depth first search in graph from collections import defaultdict class Graph: def __init__(self): self.graph = defaultdict(list) def add_edges(self, u, v): self.graph[u].append(v) def dfs(self): visited = [False]*len(self.graph) for i in range(len(self.graph)): ...
a45f0b3f7c7de5ea96ed708463a6d42fada2fbdb
sumon3255/pythonadvanced
/AdvancePython/argsandkwargs.py
539
3.5
4
#*args And **kwargs # def func1(a,b,c,d,e): # print(a,b,c,d,e) # # func1("sumon","galib","nerob","kamrul","junaed") def myfunargs(a,*args,**kwargs): for item in args: print(item) print("Now lets talk about their positions") for key,value in kwargs.items(): print(f"{key} pos...
a3b988261743a290910d8c3110733d393ef01512
wolverinez/T_Mud
/dice.py
1,099
4.15625
4
"""this module contains functions for rolling dice from a cointoss to a one hundred sided dice the funtions are named with the letter 'd' and then a number forinstance the function to simulate a d20 is simply named d20(pluss=0) where the pluss argument makes it possible to modify the roll """ import random as R de...
dd608412e5d11aca757e0ad78b76e676b2f79712
kajalth999/Linear_Regression_fromScratch
/linear_regression_scratch.py
1,924
3.640625
4
import numpy as np import pandas as pd class linear_Regression(): def y_hat(theta0,theta1,x): return theta0 + np.dot(x,theta1) def cost_function(theta0,theta1,x,y): return np.sum(np.square(y_hat(theta0,theta1,x)-y))/(2*len(y)) def gradient_descent(theta0,theta1,x,y): gr...
35a8ac27c8ef029c096c109afdf467a99e39b526
johnnybecerra/school
/CS362/randomTesting/tests.py
5,619
3.734375
4
# Jhonatan Becerra # Random Testing import random from credit_card_validator import credit_card_validator # holds the different card brands brandName = ["VISA", "MASTERCARD", "AMEX", "RANDOM1", "RANDOM2"] # holds the length of the number for a brand brandLen = [16, 16, 15, 15, 16] # createCreditNumber generates an...
714be16e84d8a3739b43e6a791de0dd1092304ca
HarshMathur86/Face-Recognition-using-KNN
/Face recognition/face_data_collection.py
2,099
3.5625
4
# Write a Python Script that captures images from your webcam video stream # Extracts all Faces from the image frame (using haarcascades) # Stores the Face information into numpy arrays # 1. Read and show video stream, capture images # 2. Detect Faces and show bounding box (haarcascade) # 3. Flatten the largest face i...
16359ae944acf0413727a4393ec15457d65ac83d
hliriano03/CSI33
/Python/Homework/Homework 5/SimpleSolitarySimulation.py
1,368
3.8125
4
# SimpleSolitary.py from SimpleSolitary import SimpleSolitary class SimpleSolitarySimulation(object): #------------------------------------------------------------ def __init__(self, games, dealtcards): self.games = games self.dealtcards = dealtcards self.wins = 0 self.loses...
be25a4e36f4f3a490b27947753740663a9b976f8
hliriano03/CSI33
/Python/Class Assigment/StackTest.py
1,147
3.703125
4
# 725+*367-*- # 3 - 2 * (5 + (7 - 3)) import sys import unittest from Stack import * # Stack.py class StackTest(unittest.TestCase): #------------------------------------------------------------ def testPush(self): '''post: places x on top of the stack''' stack = Stack() s...
231ac8c62a9e3721c3d4e532d6d78750be4b3bcc
hliriano03/CSI33
/Python/Homework/Homework 13/Homework 14 - Problem 2.py
527
3.5
4
def find_rec(self, root, item): """ Search for item in BST post: Returns item from BST if found, None otherwise""" if root is not None and not(root.item == item): if item < root.item: return self.find(root.left, item) else: return self.find(root.rig...
46bfe9a96f1fc4755a5607fd9ac044da919eeaa8
Ankush-Kumar421/Python---Become-A-Pokemon-Master
/pokemon_my_version_final.py
10,252
4.15625
4
class Pokemon: """ To create a pokemon, give it a name, type, and level. Its max health is equal to its level. Its starting health is equal to the max health. Also, the pokemon is not knocked out.""" def __init__(self, name, type, level=5): self.name = name self.level = level self.type = ty...
e1e08ea0bb60117546a9222f87175fe9a9e8e1b4
huiwenzhang/spinup-practise
/first_round/algos/trpo/nav.py
340
3.796875
4
def rotate(matrix): if not matrix: return n = len(matrix) for i in range(n): for j in range(i, n): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] for i in range(n): for j in range(int(n / 2)): matrix[i][n - 1 - j], matrix[i][j] = matrix[i][j], m...
57f9fcc7146860a2793e1ad20a05d153aaa62b74
SKikkawa-alt/hangman
/hangman.py
2,305
3.65625
4
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> home = "アメリカ" >>> if home == "アメリカ": print("Hello, America!") Hello, America! >>> else: SyntaxError: invalid syntax >>> home = "アメリカ" >>> i...
a5280318b0d3348e14a8f5a38e12dc4e51b12f41
divir94/Python-Projects
/Algorithms Practice/Monty Problem.py
1,209
3.734375
4
from random import randint def test(numDoors): # doors[i] = 1 if car behind door, = 0 if goat behind door doors = [0]*numDoors # Initially all doors have a goat carIndex = randint(0, len(doors)-1) # get random number doors[carIndex] = 1 # add a car behind a random door choice = doors.pop(randi...
89ddaf85fc8a8bb69f4181805d18d2c143e9f9a3
divir94/Python-Projects
/Project Euler/Problem 3.py
510
3.53125
4
# The prime factors of 13195 are 5, 7, 13 and 29. # What is the largest prime factor of the number 600851475143 ? from math import sqrt t = [] def factors(n): if (n==1): return i=2 root = int(sqrt(n)+2) # Check only till sqrt(n) while (i<=root and n%i): # increment if not divisible by i i+=1 ...
b3de1de10bb74a7b2ef23f5671de0ca2feff2f2e
divir94/Python-Projects
/Games/Roulette.py
1,615
3.9375
4
from random import choice class roulette: # money balance = 10000 last_bet = 10 # outcome last_outcome = 1 loss_streak = 0 # variables max_loss_streak = 4 bet_amount = 10 multiplier = 2 def __init__(self, iterations): ...
4125db8aaa60416d0ccd30d7c23fea23b20c4246
divir94/Python-Projects
/Algorithms Practice/Reducible Word.py
1,572
4.15625
4
# http://www.greenteapress.com/thinkpython/thinkpython.pdf # Exercise 12.6 def make_word_dict(): d = dict() fin = open('../Data/English Wordlist.txt') for line in fin: word = line.strip().lower() d[word] = word return d """memo is a dictionary that maps from each word that is known to ...
02aafa3780e4d22999da47ab78ad9554ac85ca38
divir94/Python-Projects
/Algorithms Practice/Scramble Words.py
729
4
4
# Reads a file and scrambles each word, leaving the first and last letters # unchanged, and writes back to another file. from random import shuffle readFile = open("../Data/Piedpiper.txt", "r") writeFile = open("../Data/Scrambled Piedpiper.txt", "w") def scrambleWord(word): if(len(word)<3): return word newWor...
05178a218c95a41919115870949fc6e1d1c8c57c
TimPaquaij/MOD-9-Biorobotics-group-23
/state_object.py
521
3.515625
4
from states import States class StateObject(object): def __init__(self): self.last_state = None self.state = States.STANDSTILL return def set_state(self, state): # Also updates the last_state self.last_state = self.state self.state = state return...
2b953aeab24e60b0a44915565b05b7cb3f1a4dd6
kosskiev/University-of-Michigan
/turtle_and_color_figure.py
873
4.46875
4
#Write a program that asks the user for the number of sides, the length of the side, the color, and the fill color of a regular polygon. #The program should draw the polygon and then fill it in. import turtle number_side = int(input('How many sides would you like?(Сколько сторон у вашей фигуры?) ')) angle = 360 / nu...
429a1d0562b5385edfa9a443c0732272e82bef4d
hutor04/UiO
/in1000/oblig_3/ordbok.py
1,197
4.34375
4
# The program initiates a dictionary with product names as keys and their prices as values. It then prints out the list # Then the program asks the user to input a new product and its price two times. # It ads new products to the dictionary and then prints a new dictionary. # We create a dictionary that holds product ...
215b78a3a4ae410b55ea532938f4d337b338ee1f
hutor04/UiO
/in1000/oblig_1/hei_student.py
361
4.21875
4
# The following program prints salutation, asks the user to input its name. # Then it prints out salutation and the name that was provided by the # user. # Prints to screen the first salutation print('Hei Student!') # Asks to input the name of the user navn = input('Scriv navnet ditt nå: ') # Prints to screen new salu...
244d75ba014b5114fc7e6801b910f98150f861da
hutor04/UiO
/in3110/assignment6/classifier/visualize.py
1,954
3.671875
4
import io from classifier.data import prepare_data from classifier.fitting import Predictor import numpy as np import matplotlib.pyplot as plt def visualize(features, mode=0, standalone=True): """ Visualizes the decision boundaries for a chosen classifier. Supported modes: 0 - kNN, 1 - SVC, 2 - NB. NB is ...
dc156aa6a85670e28c0f111265bae84a0f71e469
hutor04/UiO
/in1000/oblig_6/hund.py
765
3.828125
4
# The class Hund class Hund(): # Initiate the instance with 2 positional variables, one variable has a default value def __init__(self, alder, vekt, metthet=10): self._age = alder self._vekt = vekt self._hunger = metthet # Returns age of the dog @property def alder(self): ...
8b43e4a0fe3acdc19fd373acc7027594e6d95340
hutor04/UiO
/in4110/assignment5/fetch_player_statistics.py
6,516
3.640625
4
from requesting_urls import get_html from bs4 import BeautifulSoup from players_data import data import matplotlib.pyplot as plt def extract_name(url): """ Extracts name of the team from semifinals column. :param url: Path to the wikipage with data about the season. :type url: str :return: List wi...
8066bce0f2d4fdbf82bfc9f99a8683128d6dbe81
hutor04/UiO
/in1000/oblig_3/sirkel.py
506
3.890625
4
# The program draws a red circle. # We import the ezgraphics module import ezgraphics # We create a new parent window with the dimensions 202 by 202 window = ezgraphics.GraphicsWindow(202, 202) # We create a graphic canvas in the window canvas = window.canvas() # We set the outline of the objects to red color canva...
05930454d02a2116c43e9edbd86aab87be4c08f4
hutor04/UiO
/in4110/assignment3/Array.py
10,036
3.953125
4
from functools import reduce class Array: # Assignment 3.3 def __init__(self, shape, *values): """ Make sure that you check that your array actually is an array, which means it is homogeneous (one data type). Args: shape (tuple): shape of the array as a tuple. A 1D array w...
106f2bd5bb9456d90cc8a9b8db7aa96e031b76bc
jafedor/OrderDataAnalysis
/OrderDataAnalysis.py
3,068
3.8125
4
import requests import pandas import pprint # Use an HTTP get request with GitHub's API to download a spreadsheet from my GitHub repo r = requests.get('https://raw.githubusercontent.com/jafedor/OrderDataAnalysis/main/ItemOrderData.xlsx') print(r.status_code) # print(f'{r.headers}\n{r.content}') order_file_name = "Ite...
a47e6390eba3e1f9c2be77fd69f32cc78b0548ec
csg71/helloworld
/numero_primo.py
561
3.796875
4
def funcion_cuenta(a): b=0 while(b<=a): if(int(b/2)*2==b): print(b) else: print(b,"No es par") b=b+1 print("he acabado!") def funcion_primo(a): b=2 if(a==2): print(a) return(1) while(a>b): if(a%b==0): return(0) """se puede...
1fe2beb8f0547f3f4fef3180f75726b5df3aed74
matthewharrilal/Matthew-Corey-Solutions
/Chapter_One.py
683
3.90625
4
'''Given two strings write a method to decide if one is a permutation of the other''' def compare_two_words(word1, word2): word1_dictionary = {} word2_dictionary = {} for letter in word1: word1_dictionary[letter] = word1.count(letter) for letter in word2: word2_dictionary[letter] = wo...
858e20f7e0436fae2ad34460698f7d3b286df580
Paul-Ngigi/Contact-application
/main.py
3,109
4.46875
4
#!/usr/bin/env python3.6 from contact import Contact def create_contact(fname, lname, phone, email): """ function to create a new name """ new_contact = Contact(fname, lname, phone, email) return new_contact def save_contact(contact): """ function to save contacts """ contact.sa...
b7c3f5b54e9533d9093b2aa57822e8256f0b4152
wp6530/studypython
/01python基础/列表生成器_生成器_迭代器/推导式.py
1,701
3.90625
4
# -*- coding:utf-8 -*- # 列表推导式 # 格式: [ 表达式 for 变量 in 旧列表 ] 或者[表达式 for 变量 in 旧列表 if 条件] names = ['tom', 'jack', 'jerry', 'bob'] # 过滤掉长度小于或等于3的人名 result = [name for name in names if len(name) > 3] print(result) ''' def func(names): newlist=[] for name in names: if len(name)>3: newlist.append(...
44f194b83eb83c5603c90a01b4564234e7ca75fa
wp6530/studypython
/01python基础/面向对象/02面向对象init.py
562
3.796875
4
# -*- coding:utf-8 -*- # class Phone: # def __init__(self): # print("---------init----------") # # def call(self): # print('price: ', self.price) # # # p = Phone() # p.price = 1000 # p.call() class Person: name = '张三' def __init__(self): self.name = 'zhangsan' self.age ...
1dc9c27af13a5506b763842a637a7abb2cb43435
wp6530/studypython
/01python基础/错误和异常/exception01.py
1,418
3.953125
4
# -*- coding:utf-8 -*- # 异常处理 ''' try: 可能出现异常的代码 except: 如果有异常执行的代码 [finally: 无论是否存在异常都会执行的代码] 情况1: try: 有可能产生多种异常 except 异常的类型1: print("xxxxxxxx") except 异常的类型2: print("xxxxxxxx") except Exception as err: print("error: ", err) try: pass except : pass finally: pass ''' def f...
d72e0f35db7ed2cb7326a09484f47c0fa74b2899
FuqingWang/Movie_Analyzer
/data_importer.py
2,063
3.8125
4
import csv import sqlite3 conn = sqlite3.connect('movie.db') cur = conn.cursor() print("connected to sqlite3") def db_drop_table(): cur.execute("DROP TABLE IF EXISTS movie_table;") print("Table cleared") def db_create_table(): cur.execute("CREATE TABLE IF NOT EXISTS movie_table (" "color...
236b01e6b73f818dff72ce39e4e02fba43621fe4
spettigrew/cs-module-graphs-ii-hash-tables
/hash_function.py
376
3.5625
4
""" Modify the function below to use a different procedure for generating a hash. Research some other basic methods ("mid-squares", "division hashing", "multiplicative hashing", etc.) for ideas. """ def my_hashing_func(str, table_size): bytes_representation = str.encode() sum = 0 for byte in bytes_represen...
bc52e774eda00e71c26eae2dbfb207c4da286b8d
panchicore/Try-Catch-Chess-Challenge
/chess_board_config.py
2,800
4
4
# -*- coding: cp1252 -*- """Try Catch's Chess Challenge The problem is to find all unique configurations of a set of normal chess pieces on a chess board with dimensions MN where none of the pieces is in a position to take any of the others. The colour of the piece does not matter, and there are no pawns among the piec...
1ccea8098ed9e3c8489fcc2580f93ffb5fee577f
nokoro3345/Python
/Food Stand.py
2,664
3.890625
4
#Everything should work. import math print("Enter 'Y' or 'y' for Yes and 'N' or 'n' for No.") Wel = input("Welcome to Good Burger Home of the Good Burger may I take your order: ") print("") while Wel == "Y" or Wel == "y": CN = 0.45 GB = 2.50 MMS = 5.00 D = 2.00 if Wel == "Y" or Wel == "y":...
d745c8be1d5ee8f5601c5b79c7f072111872dcd0
CharlieHuang95/Algorithms
/Leetcode/combination_sum.py
1,516
3.8125
4
# Combination Sum # Given an array of positive integers, and a target, find all # combinations of these integers that sum up to the target. # This problem can be solved using recursion. At each node, we keep # track of the current total, and we evaluate whether the current # selection sum up to the target. If the cur...
e4279841462864909d41865df0c27e91b156831d
CharlieHuang95/Algorithms
/Sorting/quick_sort.py
1,188
4.25
4
# Quicksort works by randomly selecting an element to be its pivot, and shifting # smaller elements to its left side, and larger elements to its right side. # At the end of all the shifting, the pivot should ultimately be in the correct # location. import random def quick_sort_helper(array, left, right): if left ...
e03617b0ef1b29d596f386d5559faea9dcd86d95
CharlieHuang95/Algorithms
/Leetcode/move_zeroes.py
576
3.6875
4
# Move Zeroes # Given an array of 0s and 1s, move the ones to the beginning. # This problem can be solved by manipulating pointers, or by # counting the number of ones, and re-writing the entire array. # We will use two pointers in our solution. class Solution(object): def moveZeroes(self, nums): p1 = 0 ...
405e4aa685dba652b86f30f9d93709559ead54e3
CharlieHuang95/Algorithms
/Sorting/radix_sort.py
1,068
4.09375
4
# Radix sort works by sorting elements lexicographically import random def num_digits(num): length = 0 while num > 0: num /= 10 length += 1 return length def get_digit(num, index): return (num / 10 ** index) % 10 def radix_sort_int(array): buckets = [[] for _ in xrange(10)] #...
f7eaaefb1ae0de36a6a9f35c3c3497a388834a73
MeenaRepo/augustH2K
/SetTest.py
760
3.984375
4
''' Unordered No Duplicates ''' sampleSet = {'one','two','three','four','five'} print(sampleSet) # Add sampleSet.add('six') print(sampleSet) #Remove sampleSet.remove("six") print(sampleSet) sampleSet.add("eleven") print(sampleSet) #Iterate for eachitem in sampleSet: print(eachitem) # ...
fd2a94cec38175d7ff35a93814bc5815df69dcd0
MeenaRepo/augustH2K
/DictionaryTest.py
1,285
4.1875
4
sampleDictionary = { "Warm":"Red", "Cold":"Baige", "Nuetral":"Grey", "Common":"Black", } print(sampleDictionary) print(sampleDictionary["Cold"]) print(sampleDictionary.get("Warm")) # Add - replaces the old value sampleDictionary["Warm"] = "Blue" print(sampleDictionary) # Membership if...
8731076e2f65942f439fdc680871a37978f4cf1e
mwyszogrodzki/Programowanie
/Menu.py
847
3.8125
4
#Funkcja menu def gamemenu(): scores = {} while True: print("==================") print("Co chcesz zrobić?") print("[1] Nowa gra") print("[2] Dodaj wynik") print("[3] Wyświetl najlepsze wyniki") print("[4] Zakończ") choice = input("Wybierz:") if c...
002b4e503c7275094827d946c8717137817ec4b4
mwyszogrodzki/Programowanie
/Mastermind.py
1,528
3.515625
4
# funkcja realizująca grę mastermind import random n1 = random.randint(1, 9) n2 = random.randint(1, 9) n3 = random.randint(1, 9) n4 = random.randint(1, 9) numberswrong = 0 print(n1, n2, n3, n4) guess1 = input("Podaj pierwszą liczbę: ") guess2 = input("Podaj pierwszą liczbę: ") guess3 = input("Podaj pierwszą liczbę: "...
d0b53fbab5372a888ec40f57d70917a8801bd1dd
mwyszogrodzki/Programowanie
/BohaterIPrzeciwnik.py
1,896
3.546875
4
import random class bohater(object): def __init__(self, name): self.health = 100 self.name = name def obrona(self, attack_value): self.health -= attack_value print(self.name, "ma", self.health,"/100 punktów życia") def attack(self, enemy): attack_random = random.ra...
5f74fd68398d4371f09e696db0908255e97cf362
mwon3919/Learn_Python
/lesson1.py
921
4
4
#computation in Python print(2 ** 3) # variables, storing values in names age = 23 # integer value print(age) name = 'Matthew' # exact text is a string object print(name) # boolean variable, is either True or False isPythonFun = True # boolean value print(isPythonFun) # naming variable is_python_programming_fun...
6fac4ae13b9d8983b4b3d9117d277aec6696b049
C109156142/Midterm
/5.階層判斷.py
142
3.796875
4
m=int(input("請輸入階乘值M:")) n = i = 1 while (i<=m): i*=n n+=1 print("超過M為"+str(m)+"的最小階層N值為:"+str(n-1))
10cd5c0f8f3bf6fae6e03e1e740a115f505a1aba
duthaho/python-design-patterns
/creational/builder.py
2,288
4.15625
4
from abc import abstractmethod from typing import Optional class Car: def __init__(self): self.seat = 0 self.engine = "" self.trip_computer = False self.gps = False def info(self): print(f"Car: {self.seat} - {self.engine} - {self.trip_computer} - {self.gps}") class B...
045f7a898e4901ead647863c3b62e72d0a62223c
sweetysweets/Algorithm-Python
/jobtest/bank.py
607
3.75
4
def getMax(n): n = n - 5 return getMaxForN(n) tmp = [] def getMaxForN(n): if n == 0: return 0 if n == 1: return 1 result = 1 for i in range(n-1,0,-1): result += getMaxForN(i) return result tmp = [] def getMaxTmp(n): global tmp tmp = [0 for i in range(n+1)...
1fba894026c968d0da668020acd16884b3d7788b
sweetysweets/Algorithm-Python
/myclass/homework1/problem3.py
2,105
3.875
4
""" 数组和窗口 Description 给定一个整型数组arr和一个大小为w的窗口,窗口从数组最左边滑动到最右边,每次向右滑动一个位置,求出每一次滑动时窗口内最大元素的和。 Input 输入的第一行为数组,每一个元素使用空格隔开;第二行为窗口大小。 Output 输出一个值。 Sample Input 1 4 3 5 4 3 3 6 7 3 Sample Output 1 27 """ from sys import stdin class Solution: def maxSlidingWindow(self, nums, k): """ :type nums...
ee95a358420d200f9de488343e0b705e7be310f2
sweetysweets/Algorithm-Python
/myclass/homework3/problem1_xin.py
3,295
3.6875
4
def print1(): for i in range(len(result)): for j in range(len(result[0])): if i == len(result)-1 and j == len(result[0])-1: print(result[i][j]) elif i != len(result)-1 and j == len(result[0])-1: print(result[i][j],end=',') else: ...
e22c3713d741efb8cb73198204c9af545bc1e80a
sweetysweets/Algorithm-Python
/myclass/contest4/problem3.py
3,421
3.828125
4
""" 按照要求保留数组元素使得和最大 Description Given an array of N numbers, we need to maximize the sum of selected numbers. At each step, you need to select a number Ai, delete one occurrence of Ai-1 (if exists) and Ai each from the array. Repeat these steps until the array gets empty. The problem is to maximize the sum of selecte...
75f18230b92176cba1824edef24337ba10238c0e
sweetysweets/Algorithm-Python
/jobtest/huawei/test1.py
1,885
3.6875
4
""" 老师想知道从某某同学当中,分数最高的是多少,现在请你编程模拟老师的询问。当然,老师有时候需要更新某位同学的成绩. 输入描述: 输入包括多组测试数据。 每组输入第一行是两个正整数N和M(0 < N <= 30000,0 < M < 5000),分别代表学生的数目和操作的数目。 学生ID编号从1编到N。 第二行包含N个整数,代表这N个学生的初始成绩,其中第i个数代表ID为i的学生的成绩 接下来又M行,每一行有一个字符C(只取‘Q’或‘U’),和两个正整数A,B,当C为'Q'的时候, 表示这是一条询问操作,他询问ID从A到B(包括A,B)的学生当中,成绩最高的是多少 当C为‘U’的时候,表示这是一条更新操作,要求把ID为A的学生...
36c3ce76efc802ff475ace659338107a283bda71
sweetysweets/Algorithm-Python
/myclass/homework2/problem1_v3_动态规划.py
4,510
4
4
""" 最长公共子序列 Description 给定两个字符串,返回两个字符串的最长公共子序列(不是最长公共子字符串),可能是多个。 Input 输入为两行,一行一个字符串 Output 输出如果有多个则分为多行,先后顺序不影响判断。 Sample Input 1 1A2BD3G4H56JK 23EFG4I5J6K7 Sample Output 1 23G456K 23G45JK """ import sys class Solution(object): """ 最长公共子序列: 通过动态规划,得到矩阵D, 并从矩阵D中读出一个最长公共子序列 ""...
27ee889ee5ee7065c11f401ae0f3f21920227239
sweetysweets/Algorithm-Python
/microsoft/4.py
587
3.8125
4
class Node: def __init__(self,v): self.val = v self.next = None def set_next(self,next): self.next = next def get_length(node): if node is None: return 0 p = node q = node while p.next is not None and q.next is not None and q.next.next is not None: p ...
1abe70156692cdc14b51b1453e38beef745de85c
kevinkuan4/cse337_1
/py3_Kevin_Kuan_109645104/q6_p4.py
1,292
3.859375
4
# CSE337 # Kevin Kuan # 109645104 def count_pattern(str, pattern, replace_str): assert len(str) >= len(pattern) ord_pattern = 0 result="" for i in pattern: ord_pattern+=(ord(pattern[0])-ord(i)) # print(ord_pattern) # for i in range(len(str)-(len(pattern)-1)): i= 0 while i < len(str)-(len(pattern)-1): temp...
0e8862bcc4d11e28d399fcaf3902259bb6b2ea49
Row35/Homework.SSAcademy
/CW/CW_180220.py
2,698
4
4
# 1. Напишіть скрипт-гру, яка генерує випадковим чином число з діапазону # чисел від 1 до 100 і пропонує користувачу вгадати це число. # Програма зчитує числа, які вводить користувач і видає користувачу підказки # про те чи загадане число більше чи менше за введене користувачем. # Гра має тривати до моменту поки ...
02cc83b1ffa3e101d4a738e2e216f5ce5ab9ecdf
Row35/Homework.SSAcademy
/CW/CW_280220.py
3,485
4.0625
4
# 1. Напишіть програму, яка пропонує користувачу ввести ціле число # і визначає чи це число парне чи непарне, чи введені дані коректні. # try: # x=int(input("enter the natural number: ")) # if x<0: # raise ValueError("Error!, Please write the NATURAL number") # if x%2==0: # print("number ...