blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
c8880a75da03808b6dff3ecca3f077dcc7303b83
Parisang/pyclass
/S5h2.py
336
3.921875
4
#parisa najari ghahremani thursday 14-18 class #barnameiy ke 3 ta list ra dar ham mirizad va az akhar be #aval yeki dar mion chap mikonad list1=[1,2,3] list2=[4,5,6] list3=[7,8,9] list1.extend(list2+list3) print(list1[-1: :-2]) #ravesh dovom list1=[1,2,3] list2=[4,5,6] list3=[7,8,9] list1.extend(list2+list3) lis...
cc2486d9e84c762be5fa1ba528f49c10bd317dcb
ramiBoss/Elementary-Programs
/python/fibV2.py
304
4
4
#!/usr/bin/python def fib(num): if(num == 0): return 0 if(num == 1): return 1 return fib(num-1)+fib(num-2) def main(): num = raw_input('Fibonacci up to: ') print 'The fibonacci sequence : ', print fib(int(num)) return if __name__ == '__main__': main()
66e7003c0a34b5e2a8bbf77bc0617db3159da7fa
Niranjana4/xfcghuji
/Color randomizer2.py
1,152
3.65625
4
from tkinter import* root=Tk() root.title("Encapsulation") root.geometry("600x600") label_score=Label(root,font=("Papyrus",12,"bold")) label_score.place(relx=0.1,rely=0.1,anchor=W) label_color=Label(root,font=("Papyrus",20)) label_color.place(relx=0.5,rely=0.3) text_input=Entry() text_input.place(relx=0.5...
c6fd7070fa0c4de01c8e69431b9e02fd9f33e8f8
manudeepsinha/daily_commit
/2021/02/python/20 - HCF.py
468
3.796875
4
#HCF code #pending: error and exception handling def hcf(small,big): ans = [] for i in range (1, small + 1): if (small % i == 0) and (big % i == 0): ans.append(i) return max(ans) num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) if num1 < nu...
b8ff8071713abef72ef9c58735bb55357ff1f60e
manudeepsinha/daily_commit
/2021/01/python/09_linked_list_insertion.py
1,338
4.625
5
#after making the linked list, insert operation code is below (some changes are pending) ''' below is the earlier code for making a linked list. using this code, the following is built. #this code makes a linked list and traverses the list then prints it. #this class will be used to made new nodes class LLNod...
0b34b1b1cc34f95b2238d3e3f9b4c4a195206d10
manudeepsinha/daily_commit
/2021/01/python/26 - Summation of primes.py
465
3.640625
4
''' https://projecteuler.net/problem=10 The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. ''' def isPrime(num): if num < 2: return "Neither Prime nor Composite" for i in range(2, int(num*0.5)+1): #this is the logic that reduces the time excessively ...
79d3b03b22baed0cf3a3031b7fe8fcab297449ac
manudeepsinha/daily_commit
/2020/12/Python/21_numpy_arrays.py
409
4.125
4
#Importing numpy module import numpy as np #making a 3D array arr3d = np.array([[[1, 2, 3],[4,5,6]],[[7,8,9],[10,11,12]]]) #making a 5D array arr5d = np.array([1,2,3, 4], ndmin=5) print('3D array is as follows: ') print(arr3d) print('\n5D array is as follows: ') print(arr5d) print('\nnumber of dimension...
f72db0afefd42ddd9fda0e73ed0b7ca77127c750
manudeepsinha/daily_commit
/2020/12/Python/26_seaborn_distribution_plots.py
1,079
3.78125
4
#exploring plots in the seaborn library import seaborn as sns #for plotting the graphs in the notebook iteself %matplotlib inline #tips is a dataset in seaborn tips = sns.load_dataset('tips') #printing the top 5 enteries to know the columns and rows structure print(tips.head()) #NOTE, all the plots were...
269328a957b143c7207b18c5da030f56df0c28a2
manudeepsinha/daily_commit
/2021/01/python/11_linked_list_multiple_insertion_deletion_finding.py
6,447
4
4
''' the following code is built on the wip linked list code and adding some methods to the class i'll post the entire code everytime i make new addition of code with this line at top and a what's new section. what's new: finding an element deletion method inserting multiple...
dfd653e7a26dec023b274e6cc1cbe4d902a4a148
manudeepsinha/daily_commit
/2020/12/Python/19_pandas_missing_data.py
1,171
3.734375
4
import numpy as np # dictionary of lists dict = {'First Sem Marks':[80,60,np.nan,91], 'Second Sem Marks': [30, 45, 56, np.nan], 'Third Sem Marks':[np.nan, 40, 80, 98]} # creating a dataframe from list df = pd.DataFrame(dict) # using isnull() function to get boolean output, True for null ...
ec2a32a6652339c669162fa66a95422e9f3fcaf3
manudeepsinha/daily_commit
/2020/12/Python/16_matrix_input.py
559
4.0625
4
x = input('Enter the numbers of the matrix: ') c = int(input('Enter the number of columns: ')) x = x.split() matrix = [] r = [] i = 0 #converting user input data in integer to do operations later on for i in x: r.append(int(i)) length = int(len(r)/c) #loop condition c-1 as last element may end up with...
0c34e9e007b04bb80abb7882e365e3978fbb608c
yueyingli308/samples-of-python
/algorithms and data tools/dynamic programingๅŠจๆ€่ง„ๅˆ’.py
1,643
3.59375
4
# -*- coding: utf-8 -*- """ Created on Sat Feb 8 16:09:42 2020 @author: admin """ ##Dynamic Programming #1.1 Package Problem #่ƒŒๅŒ…้—ฎ้ข˜ #Description #้ฆ–ๅ…ˆๆˆ‘ไปฌๅ…ˆๆž„ๅปบไธ€ไธช่กจๆ ผdp[i][j]๏ผŒๆจช่ฝดไธบ่ƒŒๅŒ…็š„ๅฎน็บณ้‡้‡๏ผˆไปŽ1ๅˆฐ่ƒŒๅŒ…็š„ๅฎž้™…ๆœ€ๅคงๅฎน็บณ๏ผ‰๏ผŒ็บต่ฝดไธบๅ„ไธชๅฏ้€‰ๆ‹ฉ็š„็‰ฉๅ“ใ€‚ #่€Œ่กจๆ ผไธญ็š„ๆฏไธชๅ•ๅ…ƒๆ ผ่กจ็คบ็š„ๆ˜ฏไฝฟ็”จiไธŽๅ‰็š„็‰ฉๅ“ใ€ไธ”ไฟ่ฏๆ€ป้‡้‡ไธๅคงไบŽjๆƒ…ๅ†ตไธ‹่ƒŒๅŒ…่ƒฝๅฎน็บณ็‰ฉๅ“็š„ๆœ€ๅคงไปทๅ€ผใ€‚ #Line of thinking #ๅœจi่กŒjๅˆ—็š„ๆœ€ๅคงๅ€ผๅฏไปฅ่ฏดๆ˜ฏ๏ผˆi-1่กŒ[ๅณไธๅ–i็‰ฉ...
3dd46f18824eef1e9b8678b192bf1aebbb59622a
yueyingli308/samples-of-python
/daily coding/#18
744
4.09375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Feb 7 14:02:48 2020 @author: yueyingli """ ###Given an array of integers and a number k, #where 1 <= k <= length of the array, #compute the maximum values of each subarray of length k. #For example, given array = [10, 5, 2, 7, 8, 7] and k = 3, we s...
ec841a8ea75f3f51ce688bae4999a83a59199a07
yueyingli308/samples-of-python
/daily coding/#2.py
1,484
3.71875
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 23 15:20:54 2020 @author: admin """ #Given an array of integers, return a new array such that each element at index i of the new array is the #product of all the numbers in the original array except the one at i. #For example, if our input was [1, 2, 3, 4, 5]...
1da1de674fd5f2ec5a82d27e95c7beb76352a32c
lsteiner9/python-chapters-7-to-9
/chapter8/degreedays.py
1,140
4.03125
4
# degreedays.py def get_from_file(): filename = input("Enter the file name: ") file = open(filename, "r") heat = 0 cool = 0 for line in file.readlines(): temp = int(line) if temp > 80: heat += temp - 80 elif temp < 60: cool += 60 - temp return coo...
af81c32c95b310c7c282104dfed0a04655129872
lsteiner9/python-chapters-7-to-9
/chapter7/bmi.py
1,169
4.15625
4
# bmi.py class WeightError(object): pass class HeightError(object): pass def main(): print("This program calculates your body mass index, and evaluates " "whether it is in a healthy range.") try: pounds = float(input("Enter your weight in pounds: ")) if pounds < 0: ...
c761dce33132d83390df1e8843b940945af28b51
lsteiner9/python-chapters-7-to-9
/chapter8/syracuse.py
520
4.0625
4
# syracuse.py def main(): print( "This program prints the Syracuse sequence based on a starting value.") start = int(input("Enter a starting value (must be a natural number): ")) sequence = [start] while start != 1: if (start % 2) == 0: start = int(start / 2) else: ...
613fabed575adc985ccc676b3e3fc65508d02987
HyunJungChoe/multicampus-1.pyclass
/1--python_basic/day2_3.py
6,982
3.984375
4
# ์ž๋ฃŒํ˜•์˜ ์ข…๋ฅ˜ # ๊ธฐ๋ณธ ์ž๋ฃŒํ˜• - ๋ฌธ์ž์—ด, ์ •์ˆ˜, ์‹ค์ˆ˜, ๋ถˆ๋ฆฐํ˜• # ์ง‘ํ•ฉํ˜• ์ž๋ฃŒํ˜•=์ฝœ๋ ‰์…˜ : ์—ฌ๋Ÿฌ๊ฐœ์˜ ๊ตฌ์„ฑ์š”์†Œ๋กœ ์กฐ์งํ™” # : ๋ฆฌ์ŠคํŠธ [], ํŠœํ”Œ (), ๋”•์…”๋„ˆ๋ฆฌ { }, ์ง‘ํ•ฉ{ } # CRUD : Create Read Update Delete # ๋ฆฌ์ŠคํŠธ [] # ๋‹ค๋ฅธ ๋ฐ์ดํ„ฐํ˜• ๊ฐ€๋Šฅ # ์ˆœ์ฐจ์ ์œผ๋กœ ์ƒ์„ฑ # ๋นˆ ๋ฆฌ์ŠคํŠธ, ์ดˆ๊ธฐ๊ฐ’ ์„ค์ • ๋ฐฉ์‹ mylist=[] # mylist[0]=100 # print(mylist[0]) #IndexError: list assignment index out of range mylist.append(100) mylist.ap...
66390c6581437830219b1899c35a05d7296b5dff
mattblefeld/challenge_1
/challenge2_solution.py
749
4
4
import json def remove_element_from_json(element_name): """ Purpose: To accept an element name and remove it from the json file :param element_name: this is the text of the element you want to delete :type str """ with open('test_payload.json', 'r') as json_file: data = json.load(json_...
cce12af0f127a92498bf461e9d19d8124cbfe3fc
girishpillai17/Data-Structures-and-algorithms
/Recursion/word_split.py
1,046
4.46875
4
"""Create a function called word_split() which takes in a string phrase and a set list_of_words. The function will then determine if it is possible to split the string in a way in which words can be made from the list of words. You can assume the phrase will only contain words found in the dictionary if it is compl...
4fe9182c8125e0e9a4f6e064d6096b2fb87c3e6c
girishpillai17/Data-Structures-and-algorithms
/Linked_list/Delete_linked_list.py
1,535
4.1875
4
# -*- coding: utf-8 -*- """ Created on Fri Jul 24 19:07:28 2020 @author: girish """ class Node: def __init__(self, data): self.data = data self.next = None class Linkedlist: def __init__(self): self.head = None def insertEnd(self,newNode): if self.head i...
9ffe73e8faddc9cb42c5a5d7f6ab45923ef62751
girishpillai17/Data-Structures-and-algorithms
/LeetCode/hashMap.py
1,642
4.40625
4
# Program to implement HashTable in python class HashTable: def __init__(self): self.size = 100 #Size of the HashMap/Hashtable self.arr = [None for i in range(self.size)] #initializing the array with Null values first and then values will be added accordingly def ge...
395c240a7371ac08c5ac6bfb7eb8ac3f700a16dc
girishpillai17/Data-Structures-and-algorithms
/LeetCode/Easy/Arrays/pallindrome.py
1,167
4.21875
4
""" Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. For example, 121 is palindrome while 123 is not. Example 1: Input: x = 121 Output: true Example 2: Input: x = -121 Output: false Explanation: From left to right, it reads - 121. From r...
d1401207fedf3f98db63974e86f80b6fe1d50de0
girishpillai17/Data-Structures-and-algorithms
/LeetCode/Easy/Arrays/twoSum.py
1,093
4.15625
4
from typing import List """ Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. Example 1: Input: nu...
9ae79ad45dc22625f0ba52e99dfef4cc3936a7c2
LeoLuna98/Aprende-a-programar-en-15-dias
/suma.py
124
3.71875
4
num1 = int(input('Ingresa valor 1: ')) num2 = int(input('Ingresa valor 2: ')) suma = num1 + num2 print('La suma es:',suma)
de9875d43736ed5aa5fa09610eb964ef0445ea23
derickdev6/pymedium
/hangmaan.py
2,849
3.5
4
import random import os def main(): words = readData() play(words) def readData(): try: words = [] with open('assets\data.txt', 'r') as f: words = [i.replace('\n', '') for i in f] return words except FileNotFoundError as e: print('Error File not found', e)...
4a453b64d065229a95f57262cf4d7d1485dde9f6
ravirana9050/new-learner
/main.py
2,102
3.90625
4
import random_word_generator def change_word_state(selected_word, current_word_state, character): modified_word_state="" for i in range(len(selected_word)): if current_word_state[i]=='_' and character == selected_word[i]: modified_word_state += character else: modified_wo...
3989d083e2cf93827b359645fe54f41df1f38538
villejacob/interview-prep
/InterviewBit/EvaluateExpression.py
1,921
4.0625
4
''' Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Examples: ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 ''' A = ["4", "13", "5", "/", "+"] cl...
09faad70b5370965befc84b40986d88d7faf9e23
villejacob/interview-prep
/leetcode/reverse-nodes-in-k-group.py
2,123
4.03125
4
''' Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. You may not alter the values in...
22a58c0fcfec4796010ece9a04437a6df6ff2c08
villejacob/interview-prep
/InterviewBit/AllUniquePermutations.py
1,596
4.09375
4
''' Given a collection of numbers that might contain duplicates, return all possible unique permutations. Example : [1,1,2] have the following unique permutations: [1,1,2] [1,2,1] [2,1,1] NOTE : No 2 entries in the permutation sequence should be the same. ''' class Solution: # @param A : list of integers # ...
b3d75fa0e5a412d77ccc73283c83111834fc5c83
villejacob/interview-prep
/leetcode/simplify-path.py
1,515
4.1875
4
''' Given an absolute path for a file (Unix-style), simplify it. For example, path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c" click to show corner cases. Corner Cases: Did you consider the case where path = "/../"? In this case, you should return "/". Another corner case is the path might co...
fb7cd356c3e3900fb8bb2871b9d6d1a048bb55a6
villejacob/interview-prep
/leetcode/regular-expression-matching.py
1,041
4.1875
4
''' Implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). Some examples: isMatch("aa","a") -> false isMatch("aa","aa") -> true isMatch("a...
30555f43a1a1140612e60e27e8026df65dc8f4c5
villejacob/interview-prep
/firecode.io/iterative_inorder_traversal.py
1,046
3.84375
4
class BinaryTree: def __init__(self, root_data): self.data = root_data self.left_child = None self.right_child = None def inorder_iterative(self): inorder_list = [] root = self stack = [] # Go as far left as you can, adding nodes to the stack (Create L o...
8e4081b9f5e0468505ea4d8eaf1f8064a9d9004d
villejacob/interview-prep
/mock_interviews/sergio/sort-colors.py
791
4.28125
4
''' Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. ''' def sortColors(n): """ :type n: Lis...
4118cab25b8360a414e7dab21ad6d62745e69d04
villejacob/interview-prep
/InterviewBit/NQueens.py
2,672
3.953125
4
''' The n-queens puzzle is the problem of placing n queens on an nxn chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a quee...
1ff7e08048f9c0ed848d65d13c4a32966038e8a2
villejacob/interview-prep
/InterviewBit/PrettyPrint.py
1,077
4.40625
4
''' Print concentric rectangular pattern in a 2d matrix. Let us show you some examples to clarify what we mean. Example 1: Input: A = 4. Output: 4 4 4 4 4 4 4 4 3 3 3 3 3 4 4 3 2 2 2 3 4 4 3 2 1 2 3 4 4 3 2 2 2 3 4 4 3 3 3 3 3 4 4 4 4 4 4 4 4 Example 2: Input: A = 3. Output: 3 3 3 3 3 3 2 2 2 3 3 2 1 2 3 3 2 2 2 3...
81c84212da735f91a6927266dd0cb6159aaf4153
samarthjj/BFS-2
/cousinsInTree.py
1,450
3.921875
4
# Time Complexity : O(n), where n is the number of nodes in the tree. # Space Complexity: O(h), where h is the height of the tree. # Did this code successfully run on Leetcode : yes # Any problem you faced while coding this : no # Your code here along with comments explaining your approach class Solution(object): ...
207e54acbda9e2bd9a4ec4d6a9ce66c8d2822031
Johannes0Horn/endslate.ai
/slateAI_Backend/LogManager.py
1,826
3.734375
4
"""A class that can log events in a permanent JSON file. """ import os import json import datetime from typing import Any from PathManager import PathManager class LogManager: """Log reading, management and writing in/from a JSON file (log.json). Attributes: path: Path of the logfile to read/write. ...
832a6303b02a44ffe7423317a9cb3c55a68de648
EricHanLiu/sparkview
/client_area/utils.py
638
4.28125
4
import datetime def days_in_month_in_daterange(start, end, month, year): """ Calculates how many days are in a certain month within a daterange. Example: Oct 28th to Nov 5th has 4 days in October, this would return 4 for (2018-10-28, 2018-11-05, 10) """ one_day = datetime.timedelta(1) date_co...
94cd2e2ddf635cc901e3b3f2c9fe8f79488304e0
GeoWag/pdsnd_github
/bikeshare_2_gw_new.py
7,992
4.5
4
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name o...
02a1b35fe1ddde237c4c6c1cb433ebda48c4d3d7
yibei8811/algorithm
/public/listnode.py
512
3.5625
4
class ListNode: def __init__(self, data=None, next_node=None): self.data = data self.next_node = next_node def __str__(self): result = [self.data] p = self while p.next_node is not None: p = p.next_node result.append(p.data) return result....
edd9ad4a064bfe108e1dc9d6c2fce2080d036a5d
yibei8811/algorithm
/codingInterview/024/solution.py
1,007
3.609375
4
class ListNode: def __init__(self, data=None, next=None): self.data = data self.next = next def __str__(self): result = [] return self.dfs(result) def dfs(self, result): if self.next is None: result.append(self.data) return result.__str__() ...
76cddd3c5ea394c4b460f2ba96206ac635e6249a
yibei8811/algorithm
/codingInterview/018/solution.py
842
3.703125
4
class ListNode: def __init__(self, data=None, next=None): self.data = data self.next = next def __str__(self): result = [] return self.dfs(result) def dfs(self, result): if self.next is None: result.append(self.data) return result.__str__() ...
b75a18201ad80972e68a2b11cbfd5d40f7c11540
yibei8811/algorithm
/codingInterview/025/solution.py
634
3.765625
4
class Solution: @staticmethod def solve(list1, list2): result = [] while True: val1 = -1 val2 = -1 if len(list1) > 0: val1 = list1[0] if len(list2) > 0: val2 = list2[0] if len(list1) == 0 and len(list2) =...
2d0a45c368a8c80ad27737cab895c0974a9e1632
julife12/laboratorio_funciones_remoto
/primo.py
472
3.890625
4
def is_prime(a): divisores=0 mitadE=a//2 for i in range(1, mitadE+1): if a%i==0: divisores=divisores+1 if divisores==3: break if divisores<2: return 1 else: return 0 while True: try: x=int(input("El numero a probar...
cc5e63db3c05d606c8ef1798b1f84bb8b30c226b
callumwishart/mapdatabase
/L2-project.py
4,970
4.03125
4
import random import math def sum_nums(n): sum = 0 i = 1 while (i<=n): sum = sum + 1 i += 1 print(sum) '''n = int(input("Enter a number \n")) def factorial(n): fact = 1 i = 1 while (i<=n): fact = fact * i i += 1 print(fact) ''' def check_prime(n): f=1 i=2 while(i <= m...
cd6f9603a6a7311c1e10b45aaa4e87bec403331c
USAMAWIZARD/ProgrammingProblemsSolving
/capitalize_firlst_letter_word.py
261
3.828125
4
string="usama is a computer wizard" string=string[0].upper() def capitalize(sent,loc): return sent[:loc]+sent[loc].upper()+sent[loc+1:] i=0 while i < len(string): if string[i]==' ': string=capitalize(string,i+1) i+=1 print(string)
a8549a55bc52c41fea99e2e7c8a5d6023407b75f
USAMAWIZARD/ProgrammingProblemsSolving
/169. Majority Element.py
416
3.875
4
'''Given an array nums of size n, return the majority element. The majority element is the element that appears more than โŒŠn / 2โŒ‹ times. You may assume that the majority element always exists in the array. Input: nums = [3,2,3] Output: 3 ''' nums=[3,2,3] numcounts={} for i in nums: if i in numcounts: num...
7f036504422327599bc61eb9219f9d5863f408c7
gaganng/Automating-Real-World-Tasks-with-Python-Week4
/report_email.py
1,341
3.84375
4
#By Gagan Gundala #Meant for Learning Purpose.I do not recommend using it for Coursera Submission. #This code is in-efficient and not written with correct programming practices #But it works!!!! #!/usr/bin/env python3 from datetime import date import os import reports import emails today=date.today() #Gets today's da...
5c6ee08f6998dc3f84e014136d58dce6810716dd
jannikw/aoc-2019
/day01/part1.py
222
3.84375
4
def calculate_fuel(mass): return mass // 3 - 2 file = open("input.txt", "r") lines = file.readlines() sum = 0 for line in lines: mass = int(line) fuel = calculate_fuel(mass) sum = sum + fuel print(sum)
361a22548a23d218e66baaa1147850722d47ed41
amchigello/hacker_rank
/company_logo.py
356
3.671875
4
#!/bin/python3 from collections import Counter if __name__ == '__main__': s = input() lits_s = list(s) s_counter = dict(Counter(list(s))) l1=[(y,x) for x,y in zip(s_counter.values(),s_counter.keys())] sorted_l1=sorted(l1,key=lambda x:(x[1]*-1,x[0]),reverse=False) for x in sorted_l1[:3]: ...
ddce3dd61aaa6d21285dd271cc49302280577d88
vrushali-jadhav/DataStructures-and-Algorithms
/MergeSort.py
1,860
4.40625
4
#Merge sort implementation # Complexity: nlog(n) # Space complexity: O(n) # YOu are using the same variable 'sortTheList'. So when smaller list is sorted, the next call made to bigger list # that has the smaller list, it's left and right sides are already sorted def MergeSort(sortTheList): if len(sortTheList)>1:...
c1af07d11dac4a303a9841b3f0388aa21b1751f7
AnneWZonneveld/amstelhaege
/code/classes/house.py
4,930
3.578125
4
############################################################################### # house.py # # Programmeertheorie # Anne Zonneveld, Fleur Tervoort, Seike Appold # # - A class to create House instances. ############################################################################### from code.algorithms import randomiz...
01be3e628979d9747d18801b977902fa1ed0eb0f
SymmetricChaos/MyOtherMathStuff
/Curves/RegressionCurves.py
3,036
3.5625
4
import numpy as np import matplotlib.pyplot as plt from Conversions import xy_to_points, points_to_xy from Drawing import make_blank_canvas, draw_curve_xy, draw_dots_xy # Difference between prediction f(x) and observed value y at x def residual(x,y,f): return y - f(x) # Polynomial function def poly(x,coefs): ...
332303d8a1a1c0af9bcdc7f363f2eaadd68db6ed
SymmetricChaos/MyOtherMathStuff
/Utils/StringManip.py
8,452
3.828125
4
def bracket_matching(S,left="(",right=")",overlap=True,inner=False,warn=True): """ Args: S (str): a string to work on left (str): string with all characters to be counted as left brackets right (str): string with all characters to be counted as right brackets overlap (bool):...
c0c50af9cdf5344618db062dc5ee856063fc5999
SymmetricChaos/MyOtherMathStuff
/GEB/Chapter13FlooP.py
4,402
4
4
# Valid FlooP programs: # A function with a finite number of inputs # They can contain the following symbols and terms # if, return, break, =, ==, +, < # They can also contain any other valid FlooP or BlooP program # There must always be a value returned and it must always be an integer # Parentheses and colons are ...
c3abeaff08ae472e066ed58c2cb86e3a50cf9bfd
SymmetricChaos/MyOtherMathStuff
/CycleDetection/FloydsAlgorithm.py
1,320
3.890625
4
# Find cycles produced by an interated fuction def floyds_algorithm(func,x): slow = func(x) fast = func(func(x)) # Run until both slow and fast are inside the # cycle while fast != slow: slow = func(slow) fast = func(func(fast)) # Find the position where the cycle begins ...
59ffadcda080fc469087900b4d2776e4c38906cf
SymmetricChaos/MyOtherMathStuff
/Calculator/ReversePolishCalcInteractive.py
1,018
3.828125
4
from math import sqrt def reverse_polish_interactive(): operation = {"+" : lambda x,y: x+y, "*" : lambda x,y: x*y, "sqrt" : lambda x: sqrt(x), "-" : lambda x,y: y-x, "/" : lambda x,y: y/x } arity = {"+" : 2, ...
c004c43b3ff050cb16d316a8e500249caa4d55aa
SymmetricChaos/MyOtherMathStuff
/Curves/GCD.py
1,268
3.796875
4
def egcd(a, b): """Extended Euclidean Algorithm""" if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def gcd(*args): """Greatest Common Denominator""" # Handle the case that a list is provided if len(args) == 1 and type(args[0])...
ecd5856b6311e40aa7fc99f4bcaa222601fe5604
SymmetricChaos/MyOtherMathStuff
/WordSearch/MakeCorpus.py
553
3.8125
4
import pickle import re import csv C = [] with open('Corpus.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: # Remove words too short to use # Really even three letters is too short # but they are good for kids word search if len(row[0])...
2af54d05b70da46a2303a1ade7fe9dc8b00c693a
SymmetricChaos/MyOtherMathStuff
/LanguageStuff/LevenshteinDistance.py
303
3.640625
4
def levenshtein(s1,s2): i, j = len(s1), len(s2) if min(i,j) == 0: return max(i,j) A = levenshtein(s1[:-1],s2) + 1 B = levenshtein(s1,s2[:-1]) + 1 C = levenshtein(s1[:-1],s2[:-1]) + (1 if s1[-1] != s2[-1] else 0) return min(A,B,C) print(levenshtein("kitten","sitting"))
2e33d997879b781ffd3993bb04f96756bb476c49
SymmetricChaos/MyOtherMathStuff
/Utils/DictManip.py
669
3.921875
4
def sort_by_values(D): L = sorted(D.items(), key=lambda kv: kv[1]) return L def show_dict(D,superdict=""): """ Recursively show the contents of a dictionary or iterable that may contain other dictionaries or iterables """ if type(D) == dict: if len(D) == 0: print(f"{sup...
031d55a5e2f12352d6b75b9d7db1869268aa8247
G-Cristian/T.Leng-TP
/expressions.py
4,238
3.515625
4
class Expression(object): def evaluate(self, indexLevel, line): # Aca se implementa cada tipo de expresion. raise NotImplementedError class Number(Expression): def __init__(self, value, nType, line): self.value = value self.type = nType self.line = line self.operation = "Number" def evaluate(self, i...
158302702fdf497711642ecc6c2e67961ded1fff
jakevoytko/emell
/emell/testutil/make_random_function.py
740
3.640625
4
"""Contains a utility for making a random() substitute.""" from typing import Callable, List def make_random_function(returns: List[float]) -> Callable[[], float]: """ Return a function that returns the input values in sequence. Used to simulate a random function for tests. Parameters ---------...
41abc44fb06b76a7066bd3c9af9e42e7f0a900cf
jakevoytko/emell
/emell/neuralnetwork/test_neuron.py
1,795
3.71875
4
"""Tests for neuron.py.""" import unittest import numpy as np import emell.neuralnetwork.neuron as neuron from emell.testutil import make_random_function DELTA = 0.00001 def relu(x: float) -> float: """A testing implementation of relu.""" if x < 0: return 0 return x class TestNeuron(unittest....
fc272cdc9ce8ae59c8f09f03f6bf6a96d1187136
jakevoytko/emell
/emell/neuralnetwork/network.py
1,855
3.90625
4
"""Contains the definition of a feedforward neural network.""" from typing import List, NamedTuple import numpy as np from emell.neuralnetwork.input_layer import InputLayer from emell.neuralnetwork.layer import Layer class Network: """ Represents a feedforward neural network. More information can be f...
4a5d49c548981e32f2a237fea2c76b811cf0a955
jakevoytko/emell
/emell/neuralnetwork/dense_layer.py
3,355
3.96875
4
"""Contains the implementation of a densely-connected neural network layer.""" from random import random from typing import Callable, Optional import numpy as np from emell.neuralnetwork.layer import Layer class DenseLayer(Layer): """ A dense layer for a feedforward neural network. More information ca...
8011d60c940b5f2d9f351c653fd7cfc5d9298d29
Farukh-Basle/Python_Training
/power_consumption.py
961
4.28125
4
#Function to calculate Power Consumption #units = 0 def calculateBill(units): if (units >=1 and units<=50): #units 1 to 50 rate 3 return units * 3 elif (units >=51 and units<=100): #units 51 to 100 rate 6 return((50 * 3)+(units - 50)*6) #first 50 uni...
29eacdfec002d6f225154e7fa6847baa3fcd996c
kkanthm/eclipse_projects
/Python_Coding/default_package_modules/SLinkList.py
3,411
3.65625
4
''' Created on Nov 19, 2018 @author: Krishnakanth M ''' import math import os import random import re import sys class SinglyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None class SinglyLinkedList: def __init__(self): self.head = None self...
c758bd5bca767d4237f7f2b937b0569f3ec8421b
kkanthm/eclipse_projects
/Python_Coding/default_package_modules/Recursion.py
4,981
3.53125
4
''' Created on Jan 14, 2019 @author: Krishnakanth M def fun(n,m,count,tp): if count!=1 and n==m: print(m) return count=count+1; if tp and m>0: print(m, end=' ') m=m-5 if m<=0: tp=False if tp==False: print(m,end=' ') m=m+5 ...
61892802ad667042d4726382e1fa9c739ce31411
kkanthm/eclipse_projects
/Python_Coding/default_package_modules/Derangements_Problem.py
551
3.90625
4
''' Created on Sep 6 2019 @author: Manohar Goud Balagonu Analysis of Algorithms Program #1 Derangement Probability Computation Recursive Algorithm The program is producing the expected correct outputs ''' import math def computeDn(n): if n==0: return 1; elif n==1: return 0; else: re...
b786b9388afa10deeb6d6b5a7de9a48efa334c82
jaydeepdeka/DataStructures-Algo
/Queue.py
766
3.984375
4
class Node: def __init__(self, value): self.value = value self.next = None class Queue: def __init__(self): self.first = None self.last = None self.length = 0 def enque(self, value): node = Node(value) if self.length == 0: self.first = nod...
aafdb8d5ff33fd152658f9fddea15154bdb945a2
NewMike89/Python_Stuff
/Ch.1 & 2/fav_num.py
181
3.921875
4
# Michael Schorr # 2/19/19 # Program takes my favorite number and adds it to a string. fav_num = 666 print("My favorite number is " + str(fav_num) + "! May you be blessed by the damned.")
35a3717535ae3112a0ab34a57a559d019ff0480c
NewMike89/Python_Stuff
/Ch.3/sort_lists2.py
272
4.1875
4
# Michael Schorr # 3/4/19 # sorting a list but retaining the orignal order. cars = ['bmw', 'audi', 'toyota', 'subaru'] print("Here is the original list:") print(cars) print('\nHere is the sorted list:') print(sorted(cars)) print("\nHere is the original list again:") print(cars)
be5a90c0a5ab8c924ce6fdf90183cb5398b1e4ea
NewMike89/Python_Stuff
/Ch.4/4-8cubes_&_4-9cube_comp.py
300
4.5
4
# Michael Schorr # 3/21/19 # List of cubes for 1 - 10 with and without list comprehension. # without list comprehension cubes = [] for num in range(1, 11): cube = num**3 cubes.append(cube) print(cubes) print("\n") # with list comprehension cubes2 = [nums**3 for nums in range(1, 11)] print(cubes2)
a827cb35e6c7839a5b57ba72358bdf98024c1a43
NewMike89/Python_Stuff
/Ch.3/3-8seeing_the_world.py
375
4.1875
4
# Michael Schorr # 3/13/19 # printing a list and sorting it in several different ways. places = ['italy', 'germany', 'canada', 'philippines', 'mexico'] print(places) print(sorted(places)) print(places) print(sorted(places, reverse=True)) print(places) places.reverse() print(places) places.reverse() print(places) place...
14991adf43a472d8897b6a01994586b16dace659
NewMike89/Python_Stuff
/Ch.4/numbers.py
239
4.375
4
# Michael Schorr # 3/20/19 # FOR loop with the RANGE() function and making a list with it. for value in range(1, 5): print(value) print("\n") for values in range(1, 6): print(values) print("\n") numbers = list(range(1, 6)) print(numbers)
0f749f5329ac9624185ac7fdedc3c71391413396
NewMike89/Python_Stuff
/Ch.3/mod_list2.py
343
4.03125
4
# Michael Schorr # 2/26/19 # Adding new items to the end of a list. # Part 1 motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) motorcycles.append('ducati') print(motorcycles) # Part 2 motorcycles = [] motorcycles.append('honda') motorcycles.append('yamaha') motorcycles.append('suzuki') motorcycles.appen...
37e250438aad9b031c6e4ea44aba4d309d6768fd
merryChris/leetcode
/solution_240.py
3,451
3.609375
4
class Solution: ### 240. Search a 2D Matrix II ### # @param {integer[][]} matrix # @param {integer} target # @return {boolean} def searchMatrix(self, matrix, target): if not matrix: return False m, n = len(matrix), len(matrix[0]) i, j = m-1, 0 while 0<=i<m and 0<=j<n...
3acc0afbdef27589861a4e9e8fe1b32221b22524
merryChris/leetcode
/solution_20.py
4,260
3.609375
4
class Solution: ### 20. Valid Parentheses ### # @param {string} s # @return {boolean} def isValid(self, s): if not s: return True left = '' for _ in s: if left and left[-1]+_ in ('()', '[]', '{}'): left=left[:-1] elif _ in '([{': left += _ el...
2a4a5875f5c0c7abd63f22e4ffa148ffb48c9042
jungilhan/Algorithm
/Python/quicksort.py
695
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def sort(array): quicksort(array, 0, len(array) - 1) def quicksort(array, left, right): if left < right: pivotIndex = partition(array, left, right) quicksort(array, left, pivotIndex - 1) quicksort(array, pivotIndex + 1, right) def partition(array, left, right): ...
42777b3923375e74e134168a27886281c64d9e45
zhouchen0603/PythonProject
/PyExamples/test.py
716
3.90625
4
""" Find how many "BALLOON" can be created from a string Example: BALLOON -> return 1 BALLOONBALLOON -> return 2 BBAALLLLOOOONN -> return 2 AAAAABBBALLOONXXX -> return 1 XXXX -> return 0 """ import collections class Solution: @classmethod def solution(self,S): table = collections.de...
b50e3d6cefdf7315fdd96bc7fab08bd17d38a3f4
zhouchen0603/PythonProject
/PyHello/test2.py
908
3.640625
4
# input num # ouput chinese class Solution: def covert(self, num): chinese_arr = ['้›ถ','ๅฃน','่ดฐ','','','',''] num_str = str(num) left, right = int(num_str.split('.')[0]), int(num_str.split('.')[1][:2]) res = '' # ๆ•ดๆ•ฐ้ƒจๅˆ† while(left>9): # wan if(len...
896cc6837184b9c809c80fcb9b43ab2f46c29cc0
snkishanthnelson/PythonDev
/exception.py
526
3.734375
4
i = 3 while i >= 1: try: print("Resource loaded! Update begins") a = int(input("Enter the value of a: ")) b = int(input("Enter the value of b: ")) c = a/b d = b/a i = 0 print("Update success!") except Exception as a: i-= 1 print("Update fai...
90ad211def4689928abd7434c6ef4c4249a752b5
zhanzi123/zz
/pythonwj/web/mypro/test_dir/get_file_data.py
1,005
3.625
4
'''่ฏปๅ–ๆ•ฐๆฎๆ–‡ไปถ''' '''่ฏปๅ–txtๆ–‡ไปถ''' '''read():่ฏปๅ–ๆ•ดไธชๆ–‡ไปถ''' '''readline():่ฏปๅ–ไธ€่กŒๆ•ฐๆฎ''' '''readlines():่ฏปๅ–ๆ‰€ๆœ‰่กŒ็š„ๆ•ฐๆฎ''' # ่ฏปๅ–ๆ–‡ไปถ with(open("D:\\testdata\\test1.txt","r")) as txt_file: data = txt_file.readlines() #ๆ ผๅผๅŒ–ๅค„็† users = [] for line in data: user = line[:-1].split(":") users.append(user) #ๆ‰“ๅฐusersไบŒไบŒ็ปดๆ•ฐ็ป„ print(users) '''่ฏปๅ–cs...
942bcf9c93850c07a761f1d7c5fd39ed9cecc87d
MADMAXITY/sqlite3
/contacts.py
852
3.515625
4
import sqlite3 class contac(object): def connect(self): try: self.connection = sqlite3.connect('database.db') self.c = self.connection.cursor() self.c.execute('''Create Table Contacts (Name text,Phone_Number integer,Email text,Linkdin text)''') ...
91d95707719d29e96ddb7d7b9b8fa344253b4dee
stonecoldgames/mammal-class
/main.py
411
3.90625
4
# parent class class Mammal(object): # initialize here def __init__(self, mammalName): self.mammalName = mammalName print(mammalName, 'is a warm-blooded animal.') #i wrote this!!! look at me go def bark(self): print(self.mammalName + " barks") # child class class Dog(Mammal): def __init__(self): ...
c83288fc950199864dc02f6c63806315ec27db57
gunjany/hangman
/hangman.py
1,106
3.796875
4
import secrets def hangman(word): wrong = 0 stages = ["", "_____________ ", "| ", "| | ", "| O ", "| /|\\ ", "| / \\ ", "| " ] rletters = list(word) board = ["__"] * len(word) chance = l...
36e7c77d04557b8ea61aa131224dcb338c46c44c
megumigachi/UdpTest
/UdpTest/main.py
532
3.6875
4
from functools import reduce def udp_add(num1,num2): numRes=num1+num2 if numRes >=2**16: numRes-=(2**16-1) numRes=2**16-1-numRes return numRes def udp_rdc(listnum): res=reduce(udp_add,listnum) return res def main(): numA=0B0110011001100000 numB=0B0101010101010101 num...
1a1dd5c2c7df392e3d116d23e28a14a514dbe8fe
krohitdev/interview_questions
/interview_questions/Python/LC_58_length_of_last_word.py
498
3.890625
4
# Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. # If the last word does not exist, return 0. # Note: A word is defined as a character sequence consists of non-space characters only. # Example: # Input: "Hello World" # Output: 5 ...
9e33df45239770c7a9c39f800f177b21163af0e1
tiancy/leetcode
/python/guessnumber.py
1,108
3.921875
4
# Source https://leetcode.com/problems/guess-number-higher-or-lower/ # Author cytian # Updated 2016-07-25 # We are playing the Guess Game. The game is as follows: # I pick a number from 1 to n. You have to guess which number I picked. # Every time you guess wrong, I'll tell you whether the number is higher or lower. ...
59669f11a6b0c81cbbdcc92b65b4965df1015a47
Atulu12/The-Algorithms-Python-
/To find selected range of numbers.py
259
4.34375
4
# Python program to # print natural number # using range # printing a natural # number upto 20 for i in range(1, 20): print(i, end =" ") print() # printing a natural # number from 5 t0 20 for i in range(5, 20): print(i, end =" ")
90aa9c1c38bdb8c408b0f9473050055d1e7c1aea
marcelohjw/webcam
/main.py
217
3.53125
4
import cv2 # This is how i can capture video from the webcam. cap = cv2.VideoCapture(0) print("Starting webcam capture...") while True: success, img = cap.read() cv2.imshow('Webcam', img) cv2.waitKey(1)
29dc084e44b5d9c09832cc398ab9f08b32c0abf7
dhill94/hello-world
/Week10hexagon.py
150
3.78125
4
def hexagon(t, length): """Draws a hexagon with the given length.""" for count in range(6): t.forward(length) t.left(60)
1a21fa7905e3c86a4c7bf08d35c7e4d98b492d31
esonger/learning
/algorithm/find_max_subarray.py
2,417
3.625
4
# -*- coding: utf-8 -*- # ๆŸฅๆ‰พไธ€ไธชๆœ€ๅคงๅญๆ•ฐ็ป„ # ็ฉทไธพๆŸฅๆ‰พ def find_max_subarray1(lists): max = 0 start = 0 end = 0 length = len(lists) for i in range(0, length): for j in range(i + 1, length): sub_sum = sum(lists[i:j]) if sub_sum > max: max = sub_sum ...
d11083be899307cb1452e7de13b14d8dd6b9152d
DennisPing/image-processor-mvc
/model/util.py
2,105
3.625
4
import os import numpy as np import logging from PIL import Image def readImage(filename): """ Read an image file into a 3d numpy array. It can read both RGB and RGBA images. """ if filename is None: raise TypeError("Filename is None") try: img = Image.open(filename) matrix...
566752c62cda3c25838207bfdf1e3c591016fbfa
tobereborn/byte-of-python2
/src/examples/cat.py
942
3.859375
4
#!/usr/bin/python # -*- coding:utf-8 -*- ''' Created on Jan 1, 2017 @author: weizhen ''' import sys def readfile(filename): '''Print a file to the stdout.''' f = file(filename) while True: line = f.readline() if len(line) == 0: break print line, f.close() ### Mai...
a1f729380378ff671c275d3b51023535dfc90da8
tobereborn/byte-of-python2
/src/examples/return.py
186
4.03125
4
#!/usr/bin/python # -*- coding:utf-8 -*- ''' Created on Dec 31, 2016 @author: weizhen ''' def max(x, y): if x > y: return x else: return y print max(2, 3)
6ba400375c367d4778ee0ac1feca19893a9959a3
borkmaster/500_Algorithms
/Python/C1_two_sum.py
660
3.984375
4
# Challenge: 1 # Source: leetcode # Difficulty: Easy # Given an array of integers, return indices of the two numbers such that they add up to a specific target. # You may assume that each input would have exactly one solution. # Example: # Given nums = [2, 7, 11, 15], target = 9, # Because nums[0] + nums[1] = 2 + 7...
6ea5dcaf89307736fea7cc63296864f979033385
taratemima/AssignmentsTreehouse
/dungeon.py
3,337
3.96875
4
import random '''Written by Tara Edwards for Treehouse''' '''Uses random.choice for two lists of a range between 0 and 2''' CELLS = [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)] #a list of tuples def draw_map(): '''Draw map for game''' print("__") tile = '|{}' for idx, c...