blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
ba0603bd695e6bbb5cd2c391bb309473836bec4b
monkeylyf/interviewjam
/medium/leetcode_determine_if_two_strings_are_close.py
616
3.53125
4
# https://leetcode.com/problems/determine-if-two-strings-are-close/ from collections import Counter class Solution: def closeStrings(self, word1: str, word2: str) -> bool: if len(word1) != len(word2): return False c1 = Counter(word1) c2 = Counter(word2) if len(c1) != le...
15f5331ce57343012d944fb0dc6c13f349838b94
monkeylyf/interviewjam
/str/leetcode_Read_N_Characters_Given_Read4_II_Call_Multiple_Times.py
2,367
3.609375
4
"""Read n characters given read4 II call multiple times The API: int read4(char *buf) reads 4 characters at a time from a file. The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file. By using the read4 API, implement the function int read(c...
8c871fefeb37e594b961c63ba5345cc38dbd6f98
monkeylyf/interviewjam
/arr/leetcode_make_two_arrays_equal_by_reversing_sub_arrays.py
476
3.703125
4
# https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays from collections import Counter class Solution: def canBeEqual(self, target: List[int], arr: List[int]) -> bool: # As long as two list are content-wise equal, they can already be converted # to each other by reversing th...
f635d765f3de1c4e7cb41ff9c9faa2105b8ca5c6
monkeylyf/interviewjam
/medium/leetcode_sort_characters_by_frequency.py
378
3.578125
4
# https://leetcode.com/problems/sort-characters-by-frequency/submissions/ from collections import Counter class Solution: def frequencySort(self, s: str) -> str: if not s: return '' c = Counter(s) by_freq = [(freq, i) for i, freq in c.items()] by_freq.sort(reverse=True...
e18dcfb2f0075c1fe8616b29c6b18059076a2146
monkeylyf/interviewjam
/sort/leetcode_Wiggle_Sort_II.py
1,811
3.90625
4
"""Wiggle sort II leetcode Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... Example: (1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, 4, 1, 5, 1, 6]. (2) Given nums = [1, 3, 2, 2, 3, 1], one possible answer is [2, 3, 1, 3, 1, 2]. Note: You may assume all inp...
578e73518be86b17c4457128021284389d19f016
monkeylyf/interviewjam
/bit/leetcode_Reverse_Bits.py
777
3.90625
4
"""Reverse bits leetcode Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). """ class Solution(object): def reverseBits(self, n): ""...
f5c523609cdd156c32331ca3a468a78a25818c5f
monkeylyf/interviewjam
/medium/leetcode_number_of_sub_arrays_of_size_k_and_average_greater_than_or_equal_to_threshold.py
833
3.546875
4
# https://leetcode.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/ from typing import List class Solution: def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int: threshold_sum = threshold * k window = sum(arr[:k]) count = 0 if w...
bd4354c1444a3029a3c6c3267b62ff0c7f9daf9e
monkeylyf/interviewjam
/str/hackerrank_Anagram.py
584
3.5
4
"""hackerrank_Anagram https://www.hackerrank.com/challenges/anagram """ from collections import Counter def solve(s): length = len(s) if length % 2 == 1: return -1 a = Counter(s[: length / 2]) b = Counter(s[length / 2 :]) for key, value in a.iteritems(): try: a[key]...
0ed24c44e99cf40670af4f5ac2b64db0e5a18f0d
monkeylyf/interviewjam
/graph/A_Star_Search.py
4,181
3.9375
4
"""A* search. http://en.wikipedia.org/wiki/A*_search_algorithm """ from Queue import PriorityQueue class Matrix(object): """Matrix calss that represents a graph.""" Obstacle = 0 def __init__(self, mtx): """""" self._mtx = mtx self.n = len(mtx) self.m = len(mtx[0]) ...
8a1fd8524d01372e1f9333a93866cda2af3dd34c
monkeylyf/interviewjam
/misc/hackerrank_Upstairs.py
832
3.515625
4
"""hackerrank_Upstairs https://www.hackerrank.com/contests/addepar/challenges/upstairs """ def solve(arr, N): """N >= 2""" local_max = 0 floor = -1 for i in xrange(1, N): before = up(arr[i - 1], arr[i]) after = up(arr[i], arr[i - 1]) if i - 2 >= 0: before += up(arr[...
fd49e4b1592fd61aa0e984f5ba3238678b7b0d20
monkeylyf/interviewjam
/tree/leetcode_Closest_Binary_Search_Tree_Value.py
1,060
4.03125
4
"""Closet binary search tree value leetcode Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target. Note: Given target value is a floating point. You are guaranteed to have only one unique value in the BST that is closest to the target. """ # Definition for ...
ddc5045dd9230e4a43e6c46425dccc2aa7fd3e20
monkeylyf/interviewjam
/sort/leetcode_Largest_Number.py
1,840
4.15625
4
"""leetcode_Largest_Number. leetcode Given a list of non negative integers, arrange them such that they form the largest number. For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. Note: The result may be very large, so you need to return a string instead of an integer. """ class Solution(o...
8bfd4660a8a3210e925907b823c2050713ad52b0
monkeylyf/interviewjam
/arr/leetcode_richest_customer_wealth.py
1,306
3.9375
4
# https://leetcode.com/problems/richest-customer-wealth/ # You are given an m x n integer grid accounts where accounts[i][j] is the amount # of money the ith customer has in the jth bank. Return the wealth that the richest customer has. # # A customer's wealth is the amount of money they have in all their bank account...
25175fa1ae6869e44fe17c8ff8559cd395fc48c1
monkeylyf/interviewjam
/graph/leetcode_Longest_Increasing_Path_In_A_Matrix.py
3,724
4
4
"""Longest increasing path in a matrix leetcode Given an integer matrix, find the length of the longest increasing path. From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed). Example 1: nums = [...
199b9eccde088ca58f142e193f0ae6fedb94c218
monkeylyf/interviewjam
/search/leetcode_Number_Of_Island_II.py
3,065
3.9375
4
"""Number of island II leetcode A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand operation which turns the water at position (row, col) into a land. Given a list of positions to operate, count the number of islands after each addLand operation. An island is surrounded by ...
e45202ef67047d64c17b517927c21d65bbcbf6ee
monkeylyf/interviewjam
/medium/leetcode_maximum_difference_between_node_and_ancestor.py
1,093
3.921875
4
# https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/ # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def maxAncestorDiff(self, root: TreeN...
477f8c39ece10bcd6462bab9e879f9e03c0c6346
monkeylyf/interviewjam
/arr/leetcode_number_of_students_unable_to_eat_lunch.py
820
3.640625
4
#https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/ from typing import List class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: one = students.count(1) n = len(students) zero = n - one i = 0 while i < n: ...
6f2c69da4ea5112c839c2ae2f767fb8ac5f2c570
monkeylyf/interviewjam
/bit/google_Find_Duplicate.py
764
4.15625
4
# Given an integer array with length n + 1, all elements are from [1, n] # and there is only one duplicate element. Find it. #google def find_duplicate(arr): # Solution xor all elements in array and xor all number from [1, n] # Then all elements are xor'ed two times and duplicates are xor'ed # three time...
e3be18aad3facdf21c5ed4c55fc78bf2f4eec850
monkeylyf/interviewjam
/easy/leetcode_number_of_days_between_two_dates.py
517
4.03125
4
# https://leetcode.com/problems/number-of-days-between-two-dates/ from datetime import datetime class Solution: def daysBetweenDates(self, date1: str, date2: str) -> int: a = datetime.strptime(date1, '%Y-%m-%d').date() b = datetime.strptime(date2, '%Y-%m-%d').date() return abs((a - b).days...
6dce7932a6763bf9d11cc09cc7c3563d05592135
monkeylyf/interviewjam
/misc/hackerrank_Manasa_And_Stones.py
544
3.65625
4
"""hackerrank_Manasa_And_Stones https://www.hackerrank.com/contests/w2/challenges/manasa-and-stones """ def solve(n, a, b): s = set([0]) for _ in xrange(n - 1): ss = set() for e in s: ss.add(e + a) ss.add(e + b) s = ss print ' '.join(map(str, sorted(lis...
be769dde56db5b262c645afbf05114215de0578b
monkeylyf/interviewjam
/graph/leetcode_find_largest_value_in_each_tree_row.py
999
3.8125
4
"""https://leetcode.com/problems/find-largest-value-in-each-tree-row/submissions/""" # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import deque class Solution: def largestValues(se...
0bafbcfb9f8870088ad3464f917c66f7b2006213
monkeylyf/interviewjam
/dynamic_programming/leetcode_Paint_House_II.py
3,393
3.59375
4
"""Paint House II leetcode There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. The cost of painting each house with a certain color is ...
fc53331bdb889a3d153c5a3ca179a47618d93842
monkeylyf/interviewjam
/easy/leetcode_shift_2d_grid.py
738
3.625
4
# https://leetcode.com/problems/shift-2d-grid/ from typing import List class Solution: def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: if not grid: return grid n = len(grid) m = len(grid[0]) k = k % (n * m) flattened = [] for row ...
8bc1219bdabdbfbd689cbad8aa782ef459025a9f
monkeylyf/interviewjam
/tree/leetcode_Count_Univalue_Subtrees.py
1,709
4.03125
4
"""Count univalue subtrees leetcode Given a binary tree, count the number of uni-value subtrees. A Uni-value subtree means all nodes of the subtree have the same value. For example: Given binary tree, 5 / \ 1 5 / \ \ 5 5 5 return 4. """ # Definiti...
3128c8ca3d2b16b81244548f73ee51f483b295e6
monkeylyf/interviewjam
/dynamic_programming/leetcode_Maximal_Square.py
1,664
3.8125
4
"""Maximal square leetcode Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area. For example, given the following matrix: 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 Return 4. """ class Solution(object): def maximalSquare(self, matrix): """DP sol...
dc1306ec0ffa745f77caa038f88117b4fbc53703
monkeylyf/interviewjam
/math/codeforces_Inna_And_Nine.py
1,337
3.9375
4
"""codeforces_Inna_And_Nine. http://codeforces.com/contest/374/problem/B """ def solve(n): """The idea is to find the pattern like: a, 9 - a, a, 9 - a... If the pattner has even length, say 4. In order to get as many as nines there is only one way to sum them to 9, which does not matter. If the length...
dc0397787b25b9b714d56ef819a1433eca8d0ef7
monkeylyf/interviewjam
/math/leetcode_Perfect_Squares.py
1,761
3.578125
4
"""Perfect squares leetcode Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9. """ class Solution(object): def numSquares(self, n): ...
5e391ce054a776689740f9cb5b6934184d7813c8
monkeylyf/interviewjam
/easy/leetcode_repeated_substring_pattern.py
741
3.578125
4
# https://leetcode.com/problems/repeated-substring-pattern class Solution: def repeatedSubstringPattern(self, s: str) -> bool: # Assume pattern p' exists then s is consisted of at least two p's # for s consistant of n p's, where n >= 2 # - remove the first char of n p's leaves (n - 1) p's ...
2829a5965709897cf4dffa5360b96f1eeca43c1f
monkeylyf/interviewjam
/arr/leetcode_Zigzag_Iterator.py
4,020
4.25
4
"""Zigzag iterator leetcode Given two 1d vectors, implement an iterator to return their elements alternately. For example, given two 1d vectors: v1 = [1, 2] v2 = [3, 4, 5, 6] By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1, 3, 2, 4, 5, 6]. Follow up: What ...
44d349e4faf0de3b29efa2748bd121856ebaeef4
miguelpz/Pruebas_Python
/anexos/ejercicio.py
244
3.546875
4
# Inicializar lista lista=[] # Recorrer números del 1 al 100 for n in range(1,101): # Condición if ((n%3)==0 and (n%4)==0 ): lista.append(n) print (lista) # Añadir elemento a la lista
d355d82dd0831d2b14581dc47f92bb12439f21d3
HAREESH341/WONDER-WORLD
/loops2.py
452
3.9375
4
# num = int(input("enter a number:")) # for i in range(1,12): # if(i%3==0 or i%5==0): # continue # print("%d * %d = %d" % (num,i,num*i)) # # output: # 21 * 1 = 21 # 21 * 2 = 42 # 21 * 4 = 84 # 21 * 7 = 147 # 21 * 8 = 168 # 21 * 11 = 231 # for i in range(1,11): # if(i%3==0): # print("hello # %d" %i) # con...
233c3d4e19b302e936ebf66378a0ea061adb9d92
HAREESH341/WONDER-WORLD
/cool.py
562
3.765625
4
# list1=[10,20,30,44,59,24,10,30,44,24,55,77,77,55] # uni=[] # rep=[] # for i in list1: # if i not in uni: # uni.append(i) # else: # rep.append(i) # print("unique elements", uni) # print("repeated elements", rep) # l1=[1,2,3,44,5,6,7,8,9] # squ=[] # l1.sort() # for i in l1: # squ.append(i**2) # print(squ) #...
57c261413a26f7cca2e0546fa23f4ea0bc18fd37
ShreyKumar/Course-Management-system
/old/student.py
6,367
4.0625
4
# Assignment 1 - Managing Students! # # CSC148 Fall 2014, University of Toronto # Instructor: David Liu # --------------------------------------------- # STUDENT INFORMATION # # List your group members below, one per line, in format # <full name>, <utorid> # Shreyansh Kumar, kumarsh6 # Yun-Yee Megan Yow, yowm...
ba617a0349eb71e7bb3866efed39058a14b880b3
jaynewey/bubbles
/bubbles/particle.py
4,238
3.53125
4
import math from pathlib import Path class Particle: """Class for representing an individual Particle.""" # Some default particle textures for you sample_texture_map = {str(i.name): str(i) for i in (Path(__file__).parent / "textures").glob('**/*') if i.is_file()} def __init__(self): # Interp...
8e44f4b663b2b9e5545d3d528d4b55ca1e55b2db
Shadat-tonmoy/DeepLearningNanoDegreeUdacity
/NeuralNetworks/projects/02.HandWrittenDigitRecognition/tensorflowBasics/hello_tf.py
561
3.765625
4
import tensorflow as tf x1 = tf.constant([5]) #designing the computation graph x2 = tf.constant([6]) #designing the computation graph print(x1*x2) #abstract tensor with no value computed with tf.Session() as sess: #starting a session to perform computation and close that session when computation is finished outp...
aedae231dbdf71e25efeeaec3e7821ee8b021efe
Shadat-tonmoy/DeepLearningNanoDegreeUdacity
/NeuralNetworks/projects/02.HandWrittenDigitRecognition/neural_network_for_digit_recognition.py
4,693
4.21875
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data ''' steps activation function = (relu/sigmoid) Feed Forward Network : input -> weight -> hidden layer 1 -> activation function -> hidden layer 2 -> activation function -> hidden layer 3 -> activation function -> weight -> output l...
e5f08359f360f2f65ec9f0489f50ae327f9cf476
Shadat-tonmoy/DeepLearningNanoDegreeUdacity
/NeuralNetworks/projects/01.FirstNeuralNetwork/actual_answer.py
8,139
3.875
4
import numpy as np class NeuralNetworkAnswer(object): def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate): # Set number of nodes in input, hidden and output layers. self.input_nodes = input_nodes self.hidden_nodes = hidden_nodes self.output_nodes = output_nod...
e60bfc5daea4d1d36fde3028f9b876d342219c08
MartinSolansky/MySoloProjects
/Text_analyzer.py
6,337
3.984375
4
#!/usr/bin/python3 import sys accounts_database = {"bob": "123", "ann": "pass123", "mike": "password123", "liz": "pass123"} print("*" * 60, """ Hello and welcome to: TEXT ANALYZER Version 1.0.0 """, "*" * 60) print("""PRESS ENTER IF YOU ARE REGISTERED USER. If you wish to register type any key. If yo...
bd00f27fe9cb731aa7eca8428ee56e8ec87da31f
tejas342/Password-Generator
/password_generator.py
2,138
3.90625
4
def password(length): import random ch = "abcdefghijklmnopqrstuvwxyz" CH = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" num = "0123456789" sym = "@#$&!*+" cmn = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@#$&!*+abcdefghijklmnopqrstuvwxyz" if(length == 1): pw = random.choice(cmn) retu...
0f8801373db76ef9be3a6d425f03fb8b0ba24e7f
tryingtobuilddreams/betting-data
/In Game Play.py
3,747
3.515625
4
from bs4 import BeautifulSoup ### CODE FOR SCRAPING DATA FROM BOVADA from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.expected_conditions import presence_of_e...
e028c0c6ac8d3f0a5b476b3a841313172f5a2ee6
stephenwest10/candycrushproject
/discretephase.py
1,054
3.546875
4
import numpy.matlib import numpy as np import matplotlib.pyplot as plt import scipy.stats as stat valuesToPlot = [] t1 = np.arange(1, 100, 1) #t1 defines a range of values to plot over initialDist = np.array([0, 0, 1, 0]) #Change this initial distribution depending on where you start Tmatrix = np.array([[0, 3/4, 0,...
d0af121c73e28e6e234b57e999eea1d94fe681b3
BaiduOSS/dlpb
/program/lesson1/matplotlib_gray_demo.py
1,611
3.796875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Description : This is for demo of using matplotlib in python Authors : tanzhongyi(tanzhongyi@baidu.com) Date : 2017-12-18 """ import matplotlib.pyplot as plt import numpy as np import scipy import scipy.ndimage def rgb2gray(rgb): """ 图...
a58969a58ab66bac2d08a61ea1b9272d98ef55ac
dfe325/journey
/journey.py
2,428
3.609375
4
#! python3 #journey.py is a text-based adventure game import random import time from pprint import pprint class Player(object): def __init__(self, Pname, Phealth, Pattack, Pdefense, Pranged, Pmagic): self.name = Pname self.health = Phealth self.attack = Pattack self.defense = Pdefen...
3fc44a6136401b8ec2d1b44d7d39bbf9c2cce0ab
JuMiSanAr/TodoList_SQL
/Delete_all/delete_all_todos.py
384
3.96875
4
import sqlite3 def delete_all_todos(): conn = sqlite3.connect('todos_database.db') c = conn.cursor() print('') condition = input('Are you sure you want to delete all todos from all lists? [y/n] ') print('') if condition == 'y': c.execute('DELETE FROM todos') print('All todos ...
ae4fc983b36c7ac9924e921638010659acd66708
JuMiSanAr/TodoList_SQL
/Print_helpers/print_todo_lists_details.py
530
3.6875
4
import sqlite3 conn = sqlite3.connect('todos_database.db') c = conn.cursor() def print_all_todo_lists(): todo_lists = c.execute(''' SELECT * FROM todo_lists ORDER BY todo_list_id ''') print('List of all current todo lists: ') print('') for ll in todo_li...
554950a8a4e47a32bb93dc3da105411ffaf31c0e
ChrisUrrea/machine-learning-basics
/01-simple-data-preprocessing/data_preprocessing_notes.py
2,509
3.609375
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv('data.csv') #take all rows and take all columns EXCEPT last (-1) X = dataset.iloc[:,:-1].values #y is last value y = dataset.iloc[:,-1].values #taking care of missing data #import imputer class from scki library from sklea...
880b28aa15d2c81c3f939fa7c35e74a198d32050
JeeHyesoo/algorithm
/07_두수의합.py
451
3.515625
4
def twoSum (nums, target): nums_map = {} for i, num in enumerate(nums): nums_map[num] = i for i, num in enumerate(nums): if target - num in nums_map and i != nums_map[target - num]: return [i, nums_map[target - num]] def twoSum2 (nums, target): nums_map = {} for i, num...
118ca678c4626f0c1953090fcf291eee5a0eaeac
josephrubin/Elijah
/recv/gui_custom.py
960
3.796875
4
import tkinter as tk # In order to make our background color consistent we must ensure that every widget uses the same color. BG_COLOR = 'white' class CustomLabel(tk.Label): """Custom label to make our look and feel consistent.""" def __init__(self, ctx, *args, **kwargs): super(CustomLabel, self).__...
3bf8a62738e7f705dcd3e60a30a5beb0a82533df
hyhplus/LeetCodeByPython
/timeDecorator.py
857
3.78125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import time import timeit """ 装饰器实现程序函数的⏲计时器功能 """ def clock(func): """ 计时装饰器 """ def clocked(*args): t0 = timeit.default_timer() result = func(*args) elapsed = (timeit.default_timer() - t0) * 1000 # 函数或程序运行的时间 name = func.__nam...
714c974989541a04324c8cffe28cc2f72ebee3fe
hyhplus/LeetCodeByPython
/001~100/014LongestCommonPerfix.py
2,039
3.78125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 14、最长公共前缀 """ # class Solution: # def longestCommonPrefix(self, sl): # """ # :type sl: List[str] # :rtype: str # """ # if '' in sl: # return '' # n = len(sl) # if n > 1: # pr = '' # ...
e97daf49539b9a29a48b9224de2913adca278dfc
hyhplus/LeetCodeByPython
/interviews/005dictTest.py
640
3.5625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Python字典里面不能有列表 TypeError: unhashable type: 'list' """ # d1 = {} # d2 = {3: 5} # d3 = {[1, 2, 3]: 'user'} # d4 = {(1, 2, 3): 'user'} # # print(type(d4)) # a = 10 # 局部变量,仅在本模块或类中使用,不能在函数内部以及外部使用 # def set_a(): # a = 100 # 函数变量,内部变量,仅在函数内有效 # set_a() # print...
48c6a3d45bd0df90af51809945f1718e85cc135b
hyhplus/LeetCodeByPython
/interviews/001abcstring.py
1,102
3.953125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 给你一个字符串,比如“abc”,请打印出该字符串的所有排列组合, 如abc: abc,acb,bac,bca,cab,cba, 实际的字符长度超过100个字符串。 """ class Solution: def all_string_play(self, s): """ :param s: str :return str_list: list """ if len(s) <= 1: return [s] ...
8252d6137c104f22d92e421abb876f7d4a37476b
MonadWizard/pandas_Demo
/dates_and_Times/working_with_date_and_time.py
10,580
3.828125
4
import datetime as dt someday =dt.date(2010, 1, 12) someday.year someday.month someday.day somedaytime = dt.datetime(2010,1,10,21,13,57) str(someday) str(somedaytime) somedaytime.hour somedaytime.second print("--------------------------Timetamp-------------------------------") # it's pand...
210ae45b73627ac143f047b2d96dcd9a815bc86a
MonadWizard/pandas_Demo
/dataFrames/dataFrame3.py
7,054
3.546875
4
import pandas as pd bond = pd.read_csv("jamesbond.csv") print(bond.head(3)) print("----------------------------.set_index() and .reset_index() methods-------------") bond.set_index("Film", inplace = True) # create index but other column are empty print(bond.head(3)) bond.reset_index(drop = False) print...
66cbe56dc5f91dd234610350a0c9732c8082ae16
reinaldogoes/neuroevolutionary_snake
/neural_network/neural_network.py
5,859
4.125
4
""" Implements a multi-layer perceptron. @author Gabriel Nogueira (Talendar) """ import numpy as np class NeuralNetwork: """ Basic implementation of a multi-layer perceptron, the standard feedforward neural network. """ def __init__(self, layers_size=None, layers_activation="sigmoid", weights_multiplier=1)...
5150285b6e5255e263e8ff58a3e8f8f5f0a931e8
med95/Introduce_to_algorithms-python-
/mergeSort.py
1,086
4.125
4
def mergeSort(lists): if len(lists) <= 1: return lists middle = int(len(lists)/2) left = mergeSort(lists[:middle]) right = mergeSort(lists[middle:]) return merge(left,right) def merge(a,b): #p<=q<r #merge alist[p,q] and alist[q+1,r] in a sorted order alist1 = a.copy() alist2 = b.copy() #print('alist1:',al...
7f1847daebe48b9935e290907f25bd2e50649609
garthk1/GarthsJunk
/BooksExamples/HardWay/Ex3.py
382
3.8125
4
__author__ = 'gkline' # print('The area is ', 3.14159*float(input("What is your radius?"))**2) total_secs = int(input("How many seconds, in total?")) hours = total_secs // 3600 secs_still_remaining = total_secs % 3600 minutes = secs_still_remaining // 60 secs_finally_remaining = secs_still_remaining % 60 print("Hrs= ...
95d5e4c0e05ca833479616eaad8d0549c75fb0de
garthk1/GarthsJunk
/Projects/Kens/Assignment 2/fibonacci.py
1,688
4.40625
4
# Assignment 2: Write a Python script that generates the nth sequence # of the Fibonacci numbers. The script will take exactly one command # line argument for n. # filename : fibonacci.py # Author: Garth import sys # Things to do: # First: dummy guard. Cant allow input that is not a non-negative digit.as # Next: As...
dd016a0c036cbaad1aacfefb9ef2e68a67a6801c
Austin-Chandler/CST-305-Project-1
/AChandlerProject1.py
1,573
3.546875
4
#Austin Chandler #CST-305 #This is my own work #The equation I am working with is throughput = inventory / time #To simplify this I am calling inventory some constant k and time t. dx/dt is throughput #The equation in numerical terms is dx/dt = k / t #Importing the necessary libraires to solve the ODE import numpy as...
1f6b53e8d104eaab6d176ebc38ef685b6ecd629a
dnmcginn57/4883-SWTools-McGinn
/Assignments/A05/ascii_image.py
2,114
3.625
4
""" David McGinn 6 March 2019 4883 SWTools This program converts an image to ASCII art, but in a creative manner """ import os import sys from PIL import Image, ImageDraw, ImageFont, ImageFilter """ returns the best character to use depending on the value of the color passed in, lower value = a more full character h...
f0868ddb9729f9cab8c047343558ac06dbcd3cab
jbbaillet85/SOSMacGyver
/labyrinth.py
2,684
3.59375
4
# ! /usr/bin/env python3 # # -*- coding: utf8 -*- import pygame from wall import Wall from constants import SPRITE_SIZE, screen, win, lost class Labyrinth (pygame.sprite.Sprite): def __init__(self, path_structure): pygame.sprite.Sprite.__init__(self) self.structure = path_structure self....
8b6a806e12c203aad366771306c3474aa651215d
stuharley8/CS3400-Labs
/Lab3/knn.py
1,542
3.5
4
import random import numpy as np from scipy import spatial from scipy import stats class KNN: """ Implementation of the k-nearest neighbors algorithm for classification and regression problems. """ def __init__(self, k, aggregation_function): """ Takes two parameters. k is the num...
c23ca0fe50913b9c40b4bdee4c65d55c65167dac
Emmanuelraj/python-crash-course
/variables.py
387
4.15625
4
hello = 'Emmanue' print(hello) world = 'world' print(world) print(hello, world) # constrains naming convention # not allowed to start with special character and also numbers #hello_world #corrct hello32 ='de' print(hello32) # possible hello_32 ="a" print(hello_32) #possible # concate the string concat_...
bc20baa43832d7f75e5827807fcae0d04ab9e755
hongwongyung/web1
/2884.py
392
3.5625
4
def add(a,b): if (b>=45): a = a b = b-45 print(a,b) elif(a<=0 and b>=45): a = a+23 b = b-45 print(a,b) elif(a<=0 and b<45): a = a+23 b = b+15 print(a,b) else: a = a-1 b = b+15 print(a,b)...
aafe3cbd9f7989227dc90115f5294182158d5259
joe-molitoris/Scientific-Computing-With-Python
/Budget app/budget.py
7,939
3.921875
4
from typing import Union, List class Category: def __init__(self, name:str): # String name of category self.name = name # Ledger of deposits, withdrawals and transfers self.ledger = [] def deposit(self, amt:Union[int,float], description:str=""): """Deposits funds in led...
49c9069f5dc7bb40da432f9107b991ecea0feed0
nasir-001/Week_ll_Exercise_l
/format.py
352
3.65625
4
# Authur: Nasir Lawal # Date: 29-Nov-2019 """ Description: Exercise on format builtin function """ def main(): firstName = "Nasir" middleName = "Lawal" lastName = "Aliyu" # first method print("{}, {}, {}".format(firstName, middleName, lastName)) # second method print(f"{firstName}, {middleName}, {lastName}")...
4f161cb40180282d143f8d527761e422d7f3dde7
dba-base/python-homework
/Day03/func_test5.py
1,062
3.640625
4
#组合参数,实参个数不固定 def test(*args): print(args) test(1,2,3,4,5) test(*[1,2,3,4,5]) # *args = *[1,2,3,4,5] args = tuple([1,2,3,4,5]) # *args:接受N个位置参数,转换成元组形式 def test2(x,*args): print(x) print(args) test2(1,2,3,4,5) #可以传递字典,**kwargs接受的是关键字参数,转换成的是字典 def test3(**kwargs): print('name:',kwargs['name'...
e6ddee86dc6bb2b82854b002a774998554b9c80a
dba-base/python-homework
/Day03/eval函数.py
425
4.09375
4
#字符串转还成列表 a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]" b = eval(a) print(b) print(b[0][1]) #字符串转换成字典 a1 = "{1: 'a', 2: 'b'}" b = eval(a1) print(b) #字符串转换成元组 a3 = "([1,2], [3,4], [5,6], [7,8], (9,0))" b = eval(a3) print(b) #arg = "{'bakend': 'www.oldboy.org','record':{'server': '100.1.7.9','weight': 20,'maxconn': 30}}...
b760fb99a6b30e2f96efc225573cb322cb6f6685
VS89/testTaskRep
/webService/testDB/func_db.py
2,548
3.515625
4
import sqlite3 import json from flask import jsonify PATH_DB = 'testDB/user_db' def insert_new_user(name: str, surname: str) -> str: """ Функция, которая добавляет нового пользователя в таблицу user_db :param name: имя пользователя :param surname: фамилия пользователя :return: id добавленного пол...
363b01879ad1cd86a42118fd23601d334276a731
NitRina/rina_proga
/hw2/hw2.py
158
3.9375
4
s=input("Введите слово кириллицей:") for i in range(len(s)-1,-1,-1): if s[i]=="з" or s[i]=="я": continue print(s[i])
a763a6e75427fad53e6376b25a4d74052f28b227
NitRina/rina_proga
/hw14/hw14.py
480
3.53125
4
import re import collections def my_words(): with open('textic.txt', encoding='utf-8') as f: text = f.read() symbols = ''',.:;()?!*'"\|/[]}—{«»@#$%~`^&1234567890''' words = [i.strip(symbols) for i in text.split()] return words def main(words): d = {word: len(word) for word in words} fo...
9e58e4a34b8ac1826e70be6f0ca03e41a0c67e27
myers404/algorithms-and-data-structures
/Graphs/topological_sort.py
1,281
3.703125
4
#!/usr/bin/python """ See: https://github.com/harishvc/challenges/blob/master/graph-detect-cycle-topological-sort.py for DFS with cycle detection """ def topological_sort(graph): ''' Topological Sort ''' def dfs(graph, vertex, visited, resp): visited.add(vertex) for edge in graph[vertex]: if edge not ...
fb0d027bae748fae61f29d5f87e30b6ea58d4885
myers404/algorithms-and-data-structures
/Dynamic_Programming/zero_one_knapsack.py
754
3.765625
4
#!/usr/bin/python def print_matrix(matrix): for i, row in enumerate(matrix): print row print '' def zero_one_knapsack(total, weights, values): cols = total + 1 rows = len(values) + 1 memo = [[0 for _ in range(cols)] for _ in range(rows)] for i in range(1, rows): for j in range(1, cols): if j >= weights...
a2d3fde67c485485fdf259ca92aef4ca9f443674
myers404/algorithms-and-data-structures
/Dynamic_Programming/minimum_cost_path.py
793
3.9375
4
#!/usr/bin/python def print_matrix(matrix): for i, row in enumerate(matrix): print row print '' def minimum_cost_path(grid): cols = len(grid[0]) rows = len(grid) memo = [[0 for _ in range(cols)] for _ in range(rows)] memo[0][0] = grid[0][0] for i in range(1, rows): memo[i][0] = memo[i-1][0] + grid[i]...
fb30a6345a87d0e05539df3d8f2777de06bec18b
CarsonStevens/Mines-Courses
/Mines Courses/CSCI_252/Lab 5 - Magnetism/MagneticLab5.py
1,369
4.03125
4
#Author: Carson Stevens #Date: March 8, 2018 #Description: Use a reed switch to detect a magnetic field. #import the GPIO and time libraries import RPi.GPIO as GPIO import time #setup two variables to hold the values for the pin numbers #(one for LED and one for reed switch) reedPin = 27 LEDPin = 26 #setup the pin...
5da81a67de414f2ef249a776cf0a6f1249123335
Mynssem/webscraping
/Capítulo_2/programa2_v3.py
396
3.65625
4
#exemplo de scraping que utiliza a função next_sibling -> facilita a coleta de dados em tabelas, principalmente as que tem linhas de títulos from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen("http://pythonscraping.com/pages/page3.html") bsObj = BeautifulSoup(html,"lxml") for sibling in b...
af504f84a950d9e310ba34a4c2040a56c91c27ef
Mynssem/webscraping
/Capítulo_2/programa2_v0.py
616
3.96875
4
#Este programa seleciona todo o conteúdo de uma página e depois mostra na tela somente o texto que estiver entre as tags: #<span class="green"></span> #No exemplo da página utilizada, os textos entre estas tags são nomes from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen("http://pythonscra...
027e76441a134ef56e8a3dcd5c6f40eb4c0a0157
mayukh45/Modules
/golden/DynamicGenerator.py
3,125
4.03125
4
#============================================================================================= # Class Dynamic Generator - The chief functionality of this class to be able to take a piece # of code as string and able to run it as any other python code and return the output string # We achieve this today by writing into...
20c1326757eecccbf9eb868ea6695ee76cbf541f
FallG0D/M2Py
/m2-lesson2.py
474
3.578125
4
class cars: position = '0' move = 0 def __init__(self,name='Unknown',beep='silence...', power='0'): self.name = name self.beep = beep self.power = power def beep(self): print(self.beep) def position_(self): print(self.position) def move_...
62b0c2754b208af4372192ff6c83cf855dfd1165
samsmusa/python_basic
/python class/1_class.py
441
3.90625
4
class Rectangle: def __init__(self, length, width): self.length = length self.width = width def area(self): return self.length * self.width def perimeter(self): return 2 * self.length + 2 * self.width class Square: def __init__(self, length): self.length = leng...
294b3cf5019f8bbd709cfeb4c2e954ece3d5e99b
fashioncrazy9/HackBulgaria_0
/Week_1/1_to_n_by_2.py
143
3.703125
4
# 1_to_n_by_2.py n = input("Give me a number: ") n = int(n) counter = 1 while counter <= n: print(counter) counter = counter + 2
9cac5f1ef857941bfa432f02083426f48a7b39cc
fashioncrazy9/HackBulgaria_0
/Week_2/sum_numbers.py
296
4.0625
4
# sum_numbers.py n = input("Enter a number: ") n = int (n) count = 1 numbers = [] while count <= n: number = input("Enter number: ") number = int(number) numbers = numbers + [number] count += 1 total_sum = 0 for number in numbers: total_sum += number print(total_sum)
0ea67650cb7bbe3b641323ddcdb2f064206ac912
fashioncrazy9/HackBulgaria_0
/Week_4/pairs.py
1,107
3.875
4
def count_zero_neighbors(numbers): count = 0 index = 0 for number in numbers: if index < len(numbers)- 1: neightbor = numbers[index+1] if number + neightbor == 0: count +=1 index += 1 return count numbers = [1, 2, -2, 0, 0, 5, -5] print(count_...
df2ed1e9e21c69133ad60d83398ce24765aecb80
fashioncrazy9/HackBulgaria_0
/Week_1/legal.py
172
3.890625
4
# age.py age = input("What is your age?") age = int(age) if age < 21: print("Area not allowed for underaged.") else: print ("You are welcome! Come in :-)" )
683e029d189fba45f0f4a5e087cbddda5616902a
fashioncrazy9/HackBulgaria_0
/Week_3/random_numbers.py
395
4.0625
4
# random_numbers.py def generate_random_list(n, start, end): list = [] counter = 1 while counter <= n: list += [randint(start, end)] counter += 1 return list from random import randint n = input("Enter n: ") n = int(n) start = input("Enter start: ") start = int(start) end = inp...
4fc0f7827433af55a7251596c0dadf1624cf146f
fashioncrazy9/HackBulgaria_0
/Week_1/even_odd_interval.py
743
4.125
4
# even_odd_interval.py while True: a = input("Enter first number: ") b = input("Enter second number: ") a = int(a) b = int(b) if a < b : start = a while start <= b: if start%2 == 0: print(start, "- even") else: print (star...
dd40873261c4170f5e9d5e9205b85d847a818283
fashioncrazy9/HackBulgaria_0
/Week_1/calculator.py
365
4.0625
4
# calculator.py print ( "Hi") a = input("Enter number for a: ") a = int(a) b = input("Enter number for b: ") b = int (b) oper = input("Enter operator. Choose from +, -, *, и /: ") if oper == "+": print (a + b) elif oper == "-": print (a - b) elif oper == "*": print (a * b) elif oper == "/": print (a ...
a7dccb8c87594aedb9b9e2439d7ee700ec9ed427
fashioncrazy9/HackBulgaria_0
/Week_1/sum_digits_intervals.py
560
3.984375
4
# sum_digits_intervals.py n = input("Give me a number: ") n = int(n) m = input("Give me another number: ") m = int(m) if n == 0 and m == 0: print("Both", n," and ",m, "are 0. Their sum is 0") start = 0 end = 0 if n < m: start = n end = m elif n > m: start = m end = n while start <= end...
973b1df9ed047cdd1210c82e7ac7cc99131ccc28
fashioncrazy9/HackBulgaria_0
/Week_2/only_evens.py
542
4.25
4
# only_evens.py n = input("Enter total number: ") n = int(n) count = 1 numbers = [] while count <= n: number = input("Enter number: ") number = int(number) numbers = numbers + [number] count += 1 even_numbers_count = 0 even_numbers = [] for number in numbers: if number % 2 == 0: even_...
fb156f6b3024d937c54a26f1b7084b1279db6dbe
yevhenii-ldv/flask_birthday_coincidence_project
/birthday_range_coincidence.py
924
3.625
4
import sys import argparse def create_parser(): parser = argparse.ArgumentParser() parser.add_argument('--drange', default=7, type=int) parser.add_argument('--pcnt', default=8, type=int) parser.add_argument('--ydays', default=365, type=int) return parser def funct_birthday(drange, pcnt, ydays):...
fd3283a6091897513d66bfb3a268a2b9c19a2355
mariuspodean/NATIONAL-PYTHON-01
/lesson_7/dobricsongor/decorator.py
1,761
3.765625
4
# Create a decorator called uppercase that will uppercase the result def uppercase(fnc): def inner_func(given_text): return fnc(given_text).upper() return inner_func @uppercase def greet(name): return "Greetings {}!".format(name) print(greet("World")) #---------------------------...
e059da8be758a3c4e446aba615812fdff6dd1c33
razikhshaik/MIT-6.0002-Introduction-to-Computational-Thinking-and-Data-Science
/Assignments/ps1/ps1a.py
7,235
3.9375
4
########################### # 6.0002 Problem Set 1a: Space Cows # Name: # Collaborators: # Time: from ps1_partition import get_partitions import time #================================ # Part A: Transporting Space Cows #================================ # Problem 1 def load_cows(filename): """ Read the conten...
6a2bf4a90181878bc4eca1425eff616943f6bd62
FKomendah/PYTHON_TIZI
/first_assignment/guessing_game.py
681
4
4
#!/usr/bin/python import random answer=random.randint(1,20) name=raw_input("Please enter your name:") print ("Hi %s, I want us to play a little guessing game."%name) print ("I am going to give you three chances to guess a number between 1 and 20") i=0 while i<3: guess=raw_input("Please enter a number between 1 and...
a21e93d83464bdde31a4767d8f6de9ea2d4aadb7
mohankumarp/Training
/Python_RF_Training/Python/LAB/class_method1.py
831
3.5625
4
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: MohanKumarP # # Created: 22/12/2015 # Copyright: (c) MohanKumarP 2015 # Licence: <your licence> #------------------------------------------------------------------------------- ...
9701a5abadb05731b84e83e24d694741fdf71658
atphinn/cracking_codes_with_python
/reversechiper.py
557
3.890625
4
#reversechiper.py #https://nostarch.com/crackingcodes (BSD Licensed) # varible with the message to be encoded #message = 'Three can keep a secret, if two of them are dead.' #takes in an user inputed message message = input('Enter message: ') #Varible to store the reversed message translated = '' #find the length of t...
afba53ea2c5dde02d10b58c7e2392d87a92800ee
muzammiltariq/Probability-and-Statistics-Project
/task2_simulation.py
1,073
3.765625
4
import turtle import random prob1 = [0.5, 0.5, 0] prob2 = [0.5, 0.5, 0] wn = turtle.Screen() wn.bgcolor("light blue") wn.title("Task 2 Simulation") bob1 = turtle.Turtle() bob2 = turtle.Turtle() apart = 200 bob1.penup() bob1.goto(apart/2,0) bob1.pendown() bob2.penup() bob2.goto(-apart/2,0) bob2.pendown(...
ccc0c939ae93968eef2262a738bd57f89ab14dbf
danielfilhocoelho/hello-world
/helloworld.py
98
3.5
4
a = 0 b = 1 print('bla bla') if(a + b > 12): print('ok') print('bla bla') print('bla bla bla')
c2f766814664ac7972bcecf8c1c3bc2dc9f9e98b
Williscool13/AD-Project
/quiz.py
17,532
3.875
4
import tkinter as tk from tkinter import font as tkfont import pymysql from datetime import date import numpy as np """ class Quiz: def __init__(self, cursor, module_name, username): #Initializes quiz attributes self.correct_answers = 0 #questions contains ALL questions in a list. This list...
c376bdd4b35ed4f8541129932ac100fe245f5dcf
Captain1986/utils
/U#0014-打印OpenCV版本和编译信息/getOpenCVInfo.py
778
3.515625
4
#!/usr/bin/python3.6 #-*- coding: utf-8 -*- import cv2 # 参考资料:https://www.learnopencv.com/how-to-find-opencv-version-python-cpp/ # https://www.learnopencv.com/get-opencv-build-information-getbuildinformation/ # Print version string print "OpenCV version : {0}".format(cv2.__version__) # Extract major, min...
f33c8ea8bca76b2af5205b8124ef362fd279a3c8
ayushkumarshah/Dynamic-Programming-MCM-and-LCS
/matmul.py
2,090
4.1875
4
# Dynamic Programming Python implementation of Matrix Chain Multiplication. import sys from time import time # Matrix Ai has dimension p[i-1] x p[i] for i = 1..n def MatrixChainOrder(p, n): # For simplicity of the program, one extra row and one # extra column are allocated in m[][]. 0th row and 0th # column of m[]...