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
56cbf0b028c39c25233d8ff3d768717eb0444afb
toancqb/Codes_SaturdayNight
/python3/list_comprehension.py
979
3.984375
4
# pets = ('bird', 'snake', 'dog', 'turtle', 'cat', 'hamster') #old way: old_way_list = [] for pet in pets: old_way_list.append(pet.upper()) print(old_way_list) #List comprehension lst_pets = [pet.upper() for pet in pets] print(lst_pets) #List comprehension with conditions # [expression for item in iterable if...
f9830d01165577b87a3faa5433f7df25dc530a04
jasonmrimer/cse620-simplex
/test_constraint_generator.py
2,770
3.546875
4
from unittest import TestCase from constraint_generator import ConstraintGenerator class TestConstraintGenerator(TestCase): seed = 20 def test_random_in_range(self): # test the consistency of using a seed for randomizer constraint_generator = ConstraintGenerator(self.seed) self.asser...
6d96c19feb12c3143662dbcd01dc6c72ac64a4a5
tberhanu/all_trainings
/HACKERRANK/get_node.py
447
3.703125
4
"""https://www.hackerrank.com/challenges/get-the-value-of-the-node-at-a-specific-position-from-the-tail/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen""" def getNode(head, positionFromTail): ptr1 = head ptr2 = head for _ in range(position...
6995b1e187c1892b73a0cb3380873a8dd4ee6277
tberhanu/all_trainings
/8_training/longest_nonrepeating_substring.py
1,504
4.09375
4
""" https://leetcode.com/problems/longest-substring-without-repeating-characters/ Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: "bbbbb" Output: 1 Explanation: The ...
0ff7bb8444da8ab8a39380751d788fcd058708e4
tberhanu/all_trainings
/more_practice/Day_2/even_square.py
312
4.09375
4
""" QUESTION 5 Use lambda and print the square of all even numbers in the range (1 – 100) """ def square_of_all_evens(): # return [e**2 for e in range(101) if e % 2 == 0] evens = filter(lambda e: e % 2 == 0, [i for i in range(1, 101)]) return [e**2 for e in evens] print(square_of_all_evens())
f9f764c303cca5872cea4f868abcc073a979e9e5
tberhanu/all_trainings
/9_training/transpose*_matrix.py
1,502
4.75
5
""" Given a matrix A, return the transpose of A. The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix. Example 1: Input: [[1,2,3],[4,5,6],[7,8,9]] Output: [[1,4,7],[2,5,8],[3,6,9]] Example 2: Input: [[1,2,3],[4,5,6]] Output: [[1,4],[2,5],[3,6]] ...
494c6a18c71d6da66cab7e15ae435c09daa1b74c
tberhanu/all_trainings
/9_training/220***_contains_duplicate_III.py
1,648
3.671875
4
""" Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k. Example 1: Input: nums = [1,2,3,1], k = 3, t = 0 Output: true Example 2: Input: num...
1ea2f563a5a8338d9627b14e4abc631d749bc41d
tberhanu/all_trainings
/8_training/increasing_order_BST.py
1,269
3.953125
4
""" Given a tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only 1 right child. Example 1: Input: [5,3,6,2,4,null,8,1,null,null,null,7,9] 5 / \ 3 6 / \ \ 2 4 8 / / \ 1 7 9 Out...
e781fa892ab5336a70718954164604896f3b13b2
tberhanu/all_trainings
/HACKERRANK/lowest_common_ancestor.py
345
3.640625
4
"""https://www.hackerrank.com/challenges/binary-search-tree-lowest-common-ancestor/problem""" def lca(root, v1, v2): # Enter your code here if root.info < v1 and root.info < v2: return lca(root.right, v1, v2) elif root.info > v1 and root.info > v2: return lca(root.left, v1, v2) else...
16b4ba7cf26207df3bd36bdb3e08642afec907b1
tberhanu/all_trainings
/HACKERRANK/is_balanced.py
677
3.625
4
class Tree: def __init__(self, val): self.val = val self.left = None self.right = None def is_balanced(root): def helper(root): if root is None: return 0 lefty = is_balanced(root.left) righty = is_balanced(root.right) if lefty == -1 or ri...
d49312d3275d7af730b00dd4eff0844b9f8c9e7a
tberhanu/all_trainings
/revision_1_to_7/15_largest_prime_factor.py
358
4.125
4
""" 15. Given an int, what is the largest prime factor? """ def largest_prime_factor(num): i = 2 while i * i <= num: while num % i == 0: num = num // i i = i + 1 return max(2, num) print(largest_prime_factor(12)) print(largest_prime_factor(15)) print(largest_prime_factor(21)...
0c5854b8869fae22e14ff4e42539831c3fde5b65
tberhanu/all_trainings
/revision_1_to_7/18***_shuffling_advantage.py
1,334
3.53125
4
""" 18. Given 2 arrays A and B of equal size, the advantage of A with respect to B is the number of indices i for which A[i] > B[i]. Return any permutation of A that maximizes its advantage with respect to B """ from collections import deque def shuffled_A(A, B): a = deque(sorted(A)) b = deque(sorted(B)) ...
d1ca4df1ebd74bf0e64444d1ede451425d783520
tberhanu/all_trainings
/9_training/921_add-parenthesis.py
1,607
4.34375
4
""" Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', and in any positions ) so that the resulting parentheses string is valid. Formally, a parentheses string is valid if and only if: It is the empty string, or It can be written as AB (A concatenated with B), where A ...
fcb59269fa6dab90377e6e417d74f78e46874c69
tberhanu/all_trainings
/9_training/870*****_advantage_shuffle.py
1,525
3.953125
4
"""Given two arrays A and B of equal size, the advantage of A with respect to B is the number of indices i for which A[i] > B[i]. Return any permutation of A that maximizes its advantage with respect to B. Example 1: Input: A = [2,7,11,15], B = [1,10,4,11] Output: [2,11,7,15] Example 2: Input: A = [12,24,8,32], B =...
eef2f041e833846a12d892786a2fe57ff176dad0
tberhanu/all_trainings
/revision_1_to_7/27_esp_substrings.py
472
4.03125
4
""" 27. Given a str, find all substrings that contains two or more vowels. Also, these substrings must lie in b/n 2 consonants and should contain vowels only. Ex. "rabcdeefgyYhFjkIoomnpOeorteeeeet" --> Ioo, Oeo, eeeeee """ import re def filter(string): pattern = re.compile(r'(?<=[^aeiou])[aeiou]{2,}(?=[^aeiou])', ...
ccef15befdc8373f187d0be2b6fd3e205057e65b
tberhanu/all_trainings
/8_training/monotonic_array.py
1,193
4.1875
4
""" An array is monotonic if it is either monotone increasing or monotone decreasing. An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j]. Return true if and only if the given array A is monotonic. Example 1: Input: [1,2,2,3] Output...
40682ca5494a465512cda737a7f02c78bec64a05
tberhanu/all_trainings
/3_training/qn4_merging.py
244
4.09375
4
#!/usr/bin/env python3 def merge(arr1, arr2): return sorted(arr1 + arr2) if __name__ == "__main__": my_list = [3, 4, 6, 10, 11, 15] alices_list = [1, 5, 8, 12, 14, 19] merged = my_list + alices_list print(sorted(merged))
98976e9dbd53034092cdad20f46cec9573ed5769
tberhanu/all_trainings
/revision_1_to_7/13_array_flattening.py
352
4.1875
4
""" 13. Given a nested array, return a flattened version of it. Ex. [1, 2, [3, [4, 5], 6]] ---> [1, 2, 3, 4, 5, 6] """ from collections.abc import Iterable def flatten(arr): for a in arr: if isinstance(a, Iterable): yield from flatten(a) else: yield a print(list(f...
54fe0b5fc7a4db4ff0908576a2ac784ee7be6a6b
tberhanu/all_trainings
/revision_1_to_7/32_permutations_combinations.py
364
3.890625
4
""" 32. Given an arr, get the permutations and combinations """ from itertools import permutations, combinations def get_perm_comb(string, n): perms = permutations(string) combs = combinations(string, n) for p in perms: print(p) print("--------") for c in combs: print(c) str...
c1d0acfdc8cbd92a04936427bf06a292addb9b68
tberhanu/all_trainings
/1_training/qn9_overriding.py
429
3.953125
4
#!/usr/bin/env python3.7 class Animal: def catagory(self): print("catagorized as animal") def sounding(self): print("sounds like animal") class Dog(Animal): def sounding(self): print("sounds like dog by overriding sounds of the Animal") if __name__ == "__main__": animal = A...
1531e733cc5859b5be70b6b606c2c75488411c77
tberhanu/all_trainings
/9_training/73_set_matrix_zeroes.py
997
4.28125
4
""" Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place. Example 1: Input: [ [1,1,1], [1,0,1], [1,1,1] ] Output: [ [1,0,1], [0,0,0], [1,0,1] ] Example 2: Input: [ [0,1,2,0], [3,4,5,2], [1,3,1,5] ] Output: [ [0,0,0,0], [0,4,5,0], [0,3,1,0] ] Follow up: ...
4ced710feb067c8c912875511f7af2294b529e03
tberhanu/all_trainings
/revision_1_to_7/8_reverse_array_inplace.py
294
4.15625
4
""" 8. Inplace reverse an array of characters """ def inplace_reverse(arr): i = 0 j = len(arr)-1 while i < j: arr[i], arr[j] = arr[j], arr[i] i = i + 1 j = j - 1 return arr print(inplace_reverse([1, 2, 3, 4])) print(inplace_reverse([1, 2, 3, 4, 5]))
6d179795ac0859f8510572ea530f115133d230aa
tberhanu/all_trainings
/revision_1_to_7/4_remove_duplicates.py
309
4.0625
4
""" 4. Remove duplicates of arr or string """ def remove_duplicates(string): """ Code I""" # dict = {} # arr = [dict.setdefault(s,s) for s in string if s not in dict] # return "".join(arr) """ Code II """ return "".join(list(set(string))) print(remove_duplicates("fabcabbcdeff"))
4a26693e94d754ae4531ef92a89422bf7b2bbd94
tberhanu/all_trainings
/10_training/19_remove_nth_node.py
944
3.90625
4
"""Given a linked list, remove the n-th node from the end of list and return its head. Example: Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Note: Given n will always be valid. Follow up: Could you do this in one pass? """ class Lis...
7c6c0c78a813ec102b63072b31057cd5e909bbc6
tberhanu/all_trainings
/3_training/qn3_shortest_route.py
1,658
4.1875
4
#!/usr/bin/env python3 import networkx as nx import matplotlib.pyplot as plt def shortest_path(network, name1, name2): """shortest_path(network, name1, name2) --> a function taking a NETWORK and output and array of Strings as a shortest path from name1 to name2 --> Need to install networkx, and inbuilt py...
2e8752c1b30b6b0679a342e556923dc6b27794c2
tberhanu/all_trainings
/HACKERRANK/electronic_shop.py
600
3.5625
4
# """ Failed some tests ...""" # def getMoneySpent(keyboards, drives, b): # arr = [] # for i in range(len(keyboards)): # e = keyboards[i] + drives[0] # biggest = e # small = b - e if e <= b else -1 # for j in range(len(drives)): # e2 = keyboards[i] + drives[j] # ...
caa26774740d447eb440fe68c6689660f0ff381e
tberhanu/all_trainings
/5_training/smallest_multiple.py
358
4.0625
4
def smallest_multiple(N): n = N if N % 2 == 0 else N + 1 flag = True while True: for i in range(2, N + 1): if n % i != 0: flag = False break if flag: return n else: flag = True n = n + 2 print(smallest_multi...
f92d79dbdf0d6a8240d264c3065fd72694b2e566
byyasar/python-ders
/datetime1.py
788
3.625
4
from datetime import datetime,date,timedelta # an=datetime.now() bugun=date.today() dun=bugun+timedelta(days=30) print(dun.strftime('%c')) # kacinci_gun=datetime.today().weekday() # ay=datetime.today().month # gun=datetime.today().day # saat=datetime.today().hour # dakika=datetime.today().minute # saniye=datetime...
a42a1b8a508f5dad31c13eac7d6f4d605896155e
Marist-CMPT120-FA19/-Kathryn-McCullough--Project-10-
/censor.py
1,494
4.28125
4
#name: Kathryn McCullough #email: kathryn.mccullough1@marist.edu #description: This program references a file with words and a separate #file with a phrase and censors those words from the first into a third file. #goes through characters and replaces all letters with * #plus censores word with comma will still have ...
c744b36fc3d00588180a6ce81519ce765f5dfbad
lucy74310/PycharmProjects
/python_ch2.2/unpacking.py
748
3.796875
4
# packing : tuple만 가능하다 t = 10, 20, 30, 'python' print(t, type(t)) # Unpacking a, b, c, d = t print(a, b, c, d) # 에러 # a, b, c = t # a, b, c, d, e, = t # unpacking extended t = (1, 2, 3, 4, 5) a, *b = t print(a, b) a, *b, c = t print(a, b, c) # cf. 여러개 파라미터를 받는 함수 def mysum(*num): s = 0 for n in nu...
32a15b8882991c135e95b5e8297eb996cda0561b
Eric-Lingren/sandboxes
/python_sandbox/main.py
247
3.515625
4
# import math # print(math.pi) # import numpy as np # # X=np.array([[1,0],[0,1]]) # # Y=np.array([[2,1],[1,2]]) # # Z=np.dot(X,Y) # a=np.array([1,1,1,1,1]) # c = a+10 # print(c) #* Find the first non repeated character of a given String
c3ba4a7e6e10d87165920262935a40ba90718332
jjmaldonis/Data-Structures-Code
/p02/hashtable.py
3,946
4.1875
4
""" Hashtable class """ class Hashtable: """ re-implements python's hash table functionality """ PERTURB_SHIFT = 5 def __init__(self): """ init function for my hash table. """ self.pos = 0 #The size below is the power of 2 of the hashtable, not the actual size of the table ...
71a4d5d390639160838813bc0ff468853b248ddd
jjmaldonis/Data-Structures-Code
/pythoncrashcourse/intsertion.py
869
4.25
4
#if you import this module you can type help(insertion) and it will give you the help info below """ insertion sort script that demonstrates implementation of insertion sort. """ import random def insertion(l): """ implements insertion sort pass it a list, list will be modified in plase """ pri...
e919b84095f1933ff3a34f6eb3479f26f3525c2f
dfd/CS7641_hw02
/sklearn_code.py
12,066
3.546875
4
### Code in this file are adapted from scikti-learn docs import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_digits from sklearn.model_selection import learning_curve from sklearn.model_selection import ShuffleSplit import seaborn as sns # https://scikit-learn.org/stable/auto_examples...
27763650186c37cf491e56e44345d00c648a0804
Omochao/Project-Euler
/10001st_prime.py
260
3.65625
4
#What is the 10 001st prime number? def sieve(n): return all((n-i)% (2*i+1)>0 for i in range(1,(n+1)//2)) def sundaram(it): return (2*n+1 for n in it if sieve(n)) primes = list(sundaram(range(100000))) print(len(primes)) print(primes[10000])
58b80a18c2a24f6b9ae497474af1eed10fd53404
queenofspade/quote-scrape
/quotes.py
1,727
3.734375
4
#python3! -- quotes.py -- Scrapes a Goodreads quote page for quotes and authors, then stores all quotes to 'quotes.txt' file and stores all authors to 'authors.txt' file. import requests, bs4 from requests_html import HTMLSession from bs4 import BeautifulSoup #opens text files to write to quote_file = open("quotes.txt...
11ac248b5349b30f2830be19f70b79c8ea2aeb2d
chanchanhui/coursera-ml-py
/ex1/ex1.py
1,975
3.9375
4
import numpy as np import matplotlib.pyplot as plt import GradientDescent as GD from mpl_toolkits.mplot3d import axes3d, Axes3D from matplotlib.colors import LogNorm # ===================== Part 1: Plotting ===================== data=np.loadtxt('ex1data1.txt',delimiter=',') #print(data) print(type(data)) print...
87651962b5a12aa5ad09e0183db52df90e89c8f3
jacindaz/algos_practice
/algos/insertion_sort.py
511
4
4
def insertion_sort(list): for current_index, current_item in enumerate(list[1:], start=1): previous_index = current_index - 1 while previous_index >= 0: if current_item < list[previous_index]: previous_item = list[previous_index] list[previous_index] = cur...
49e681c7d3d146839d6d25f4a3e6f19235e53a5f
jacindaz/algos_practice
/algos/stacks_divide_by_2.py
847
4.0625
4
def decimal_number_to_binary(number): """ Convert decimal number (base 10) to binary """ binary_stack = [] while number >= 1: remainder = number % 2 number = int(number/2) binary_stack.append(remainder) binary_number = "" while len(binary_stack) > 0: binary_...
df5d8f7a58fadc4096614b01a37f303132b43d77
tanisha03/Sem5-ISE
/SLL-Python/Data-Science/Iris/iris.py
882
3.5
4
import pandas as pd from pandas import Series, DataFrame import numpy as np import matplotlib.pyplot as plt import seaborn as sns iris_df = pd.read_csv("iris.csv") print("---DataFrame---") print(iris_df) print("---info---") iris_df.info() print("---Functions---") print(iris_df[["variety", "petal.width"]].groupby(["var...
b44963ad2cf12c0891fd345f1b42d812fd4dcfa9
tanisha03/Sem5-ISE
/SLL-finals/SEE/5a.py
1,718
4.03125
4
def farenheittocelcius(): temp = int(input("Please enter the farenheit temperature")) ans = ((temp - 32) * 5) / 9 conv.append((temp, ans)) print(ans) def farenheittokelvin(): temp = int(input("Please enter the farenheit temperature")) ans = ((temp - 32) * 5) / 9 + 273 conv.append((temp, an...
9f2a8ff375e12471f66d2eb4eb4428db0cb67e0d
paradine9/test
/simple_test.py
753
3.859375
4
import time import sys from time import sleep goed = ("goed") or ("Goed") or ("lekker") or ("Lekker") or ("Prima") or ("prima") slecht = ("slecht") or ("Slecht") or ("kut") or ("Kut") or ("Niet zo goed") or ("niet zo goed") or ("ruk") print("Welkom!") naam = input("Wat is je naam? ") time.sleep(0.5) print("Hallo " +...
12bf5dbebf73216195ca8f4ae55712668dca8860
PaulaRodes/Lab2
/resolution_resize.py
367
3.578125
4
from PIL import Image import os path = '/Users/Paula/PycharmProjects/pythonProject/foto' def resize(width, height): for item in os.listdir(path): im = Image.open(item) f, e = os.path.splitext(item) imresize = im.resize((width,height), Image.ANTIALIAS) imresize.save(f + ' resized.j...
af439a60ac650b1a2d00995e24849c7a5132d619
ursu1964/python-algorithms-4
/data-structures/tree/binaryTree.py
2,283
3.953125
4
class TreeNode: def __init__(self, data): self.data = data self.left = None self.right = None def insert(self, data): if self.data: if data < self.data: if self.left is None: self.left = TreeNode(data) else: ...
11380920f71a0ed60f41bf6bebb39a7d45fa612b
ursu1964/python-algorithms-4
/algorithms/sorting/selectionSort.py
476
3.953125
4
def selectionSort(arr): arr_length = len(arr) sorted = [] while len(sorted) != arr_length: min_index = 0 for i in range(len(arr)): if arr[i] < arr[min_index]: min_index = i swap(arr, 0, min_index) sorted.append(arr[0]) arr.pop(0) return...
838b7b4004d507e4e584c171ee7a99b263db2eac
ursu1964/python-algorithms-4
/algorithms/uncategorized/permutations.py
271
3.53125
4
def permutations(arr, visited): if len(arr) <= 1: print visited + [arr[0]] return for i in arr: new_arr = arr[:] new_arr.remove(i) permutations(new_arr, visited[:] + [i]) return permutations(['A', 'B', 'C', 'D'], [])
13517254ee8c63ae8558506806cba1d452a2cd31
ursu1964/python-algorithms-4
/algorithms/sorting/insertionSort.py
398
4.03125
4
def insertionSort(arr): for i in range(len(arr)): if i > 0: current_key = arr[i] j = i - 1 insert_pos = i while arr[j] > current_key and j >= 0: insert_pos = j j = j - 1 arr.pop(i) arr.insert(insert_pos, ...
1e408a7d1ffe5621472cc0cdcaf70c1449759e9c
Aakashdeveloper/SriKanth_Python
/nineFunction.py
828
3.75
4
'''a = 10 if(a%2 == 0): print("number is even") else: print("number is odd")''' '''def isEven(a): if(a%2 == 0): print("number is even") else: print("number is odd") insert = input("please enter number") isEven(insert)''' '''def add(table, column): print('Select '+ column + ' fo...
c775af92156ce81da51a66633be6f6663d62d340
Ahmed-Sh/MatrixClaculator
/mat_calc.py
6,945
3.78125
4
class MatrixCalc: def __init__(self): self.rows = 0 self.column = 0 self.size = 0 self.player_choice = None self.m = None self.m1 = None self.m2 = None self.pick = 0 self.co_factors = [] self.minors = [] self.matrix = [] d...
c14928c6b32a22c60ac5535621e801b955182d24
nick-monto/tensorflow_LD
/image_gen.py
2,742
3.953125
4
""" Author: Henry Wolf Twitter: @chaoticneural Date: 2017.01.12 Notes: This file includes the functions for generating and loading basic images with text on them. """ from PIL import Image, ImageDraw, ImageFont import os import numpy as np import pandas as pd def gen_image(txt, width=128, height=...
c7f09b38290cd555d9d940f93cbf765b2421a32d
DougScalioni/project-euler
/PE054 - Poker Hands.py
3,678
3.5
4
file = open('poker.txt', 'r').read() lines = file.split('\n') suits_value = { 'C': 0, 'D': 1, 'H': 2, 'S': 3 } cards_value = { '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14 } def draw(ln...
b90491cc14e91bab748ff2ced5123b991168f23d
gnanadeepika/MISC
/PROBLEMS/candies.py
547
3.5
4
def candies(n, arr): left = [0]*len(arr) right = [0]*len(arr) left[0]=1 right[-1]=1 for i in range(1,len(arr)): if arr[i-1]<arr[i]: left[i]=left[i-1]+1 else: left[i]=1 for i in reversed(range(0,len(arr)-1)): if arr[i] > arr[i+1]: right[...
a010cea1042a7b859095b3affda4fe3067614608
antonio6643/Terminal-Games
/Games/Surf.py
1,815
3.859375
4
# Basically like subway surfers but in the terminal. import msvcrt import os from random import randrange from time import sleep speed = 0.5 # The time it takes to go to move up. Course = [] # Entries will be simple strings formatted like so: "- O X" (5 characters) Position = 0 Score = -9 Dead = False ...
d8508b1c364c2e9a2da7a50ac32a85bcb4bbc0a1
searfmat/CLRS-Algos
/heapsort.py
930
3.828125
4
import math def left(i): return (i << 1) + 1 def right(i): return (i << 1) + 2 def maxHeapify(arr, i, heapsize): l = left(i) r = right(i) if l <= heapsize and arr[l] > arr[i]: largest = l else: largest = i if r <= heapsize and arr[r] > arr[largest]: largest = r ...
211e365bfbba655ef788bec33d993104050a6d45
chandanmishra-03/Image-Scraper
/InstaScraper.py
4,024
3.578125
4
""" InstaScraper is an images scraping spider class, used to scrape instagram by a given tag. The url we are using is helping us to get a full dictionary of an instagram page. In this case, we don't need to scrape the urls in the html DOM, a simple request retrieves the dictionary as mentioned above. For any further c...
736369155ea9092cb9c2a53be5c6c6d58faa469a
caporta/algorithms-18
/heaps-and-priority-queues/heapsort.py
768
3.984375
4
def heapsort(data): _build_max_heap(data) size = len(data) while size > 1: _swap(data, 0, size - 1) size -= 1 _max_heapify(data, 0, size) def _build_max_heap(data): size = len(data) last = size - 1 start = (last - 1) // 2 while start >= 0: _max_heapify(da...
3e06b88f35b3abf8c093b0cd04c8f5085edc4fd5
maciejbihun9/maciek_python_modules
/different/web_crawler.py
2,342
3.53125
4
from urllib import request from bs4 import BeautifulSoup class WebCrawler: """ Enables web page scrapping. """ def __init__(self, url): f = request.urlopen(url) html = str(f.read()) self.soup = BeautifulSoup(html, "html.parser") def get_values_for_class(self, class_name) ...
24eb77715c80b5f9a991a1bf8625000eef953c98
ali4413/MCL-DSCI-511-programming-in-python
/exercises/exc_01_06b.py
247
3.640625
4
import pandas as pd # Read in the dataset hockey_players = pd.read_csv('data/canucks.csv', index_col=0) # find the the data frame shape of `hockey_players` save it as as `hockey_shape' ____ # Display it by writing the object name. ____
92a1a5e91417d190df48451367bbc172eb10c236
ali4413/MCL-DSCI-511-programming-in-python
/exercises/solution_01_06a.py
285
3.65625
4
import pandas as pd # Read in the dataset hockey_players = pd.read_csv('data/canucks.csv', index_col=0) # Find the column names of `hockey_players` save it as `columns_hockey` columns_hockey = hockey_players.columns # Display it by writing the object name. columns_hockey
6f8fed2d5db996b8143068ac4542b4da37db9df1
blukke/Python
/Dicionario/PesquisaWhile.py
637
3.59375
4
L = [5, 10, 15, 20, 25] # cria uma lista p = int(input("Digite o valor procurado: ")) # entrada de dados achou = False # Defina a variável achour para Falso x = 0 # Define x como 0 while x < len(L): # Enquanto x for menor que o comprimento da Lista if L[x] == p: # Se o numero na posição x for igual ao valor p...
af65a8a74a86d43575484c18e2d8113bdedf8f1b
blukke/Python
/Fatiamento e Analise/Transformacao.py
361
3.578125
4
mensagem = ' tecnicos em informatica ' print(mensagem) print(mensagem.replace('informatica', 'eletroeletronica')) print(mensagem.upper()) print(mensagem.lower()) print(mensagem.capitalize()) print(mensagem.title()) print(mensagem.strip()) print(mensagem.rstrip()) print(mensagem.lstrip()) m = (mensa...
15eb966ccbf88d87a8cf2317c194d182f162240f
blukke/Python
/Listas/Tuplas02.py
373
3.953125
4
pedido = (1, "Hamburguer", "Refrigerante", "Batata Frita") # Cria a tupla pedido print(pedido) # Imprime a tupla inteira print("="*90) print(pedido[1]) # Imprime apenas o item na posição 1 -> Hamburguer print("="*90) print(pedido[1:]) # Imprime desde o item na posiçao 1 até o [último print("="*90) print(pedido[:3])...
177a823c066a671decb3bcf7016c0532b2242e84
blukke/Python
/Funcoes/Exercicios/Coiso 6.py
219
3.796875
4
# Turma B # Exercício número 6 por Juan Lucas Melo de Borba def frase(f): maiu = f.upper() mini = f.lower() caputa = f.title() print("{} \n{} \n{}".format(maiu, mini, caputa)) f = input("digite a frase: ") frase(f)
78d32ae8c71e878934934ebf53a5a401050b80b4
zongxinc/COSSY
/COSSY-setup.py
1,815
3.796875
4
import json import string print("how many rooms are you going to use:") roomNum = input() MAC = {} MAC["OFC-1"] = "ACCC8EB4A2D9" MAC["OFC-2"] = 'ACCC8EB66056' MAC["OFC-3"] = "ACCC8EB65F9D" MAC["TDS-1"] = "ACCC8E655F9D" MAC["TDS-2"] = "ABCC8E655F9D" MAC["TDS-3"] = "B827EB7FC003" MAC["TDS-4"] = "B827EBD01F4E" MAC["TDS-5...
5e23436560ca626364f7bbf58d393f57f5c1f133
Nallo/ud120-projects
/svm/svm_author_id.py
1,987
3.71875
4
#!/usr/bin/python """ This is the code to accompany the Lesson 2 (SVM) mini-project. Use a SVM to identify emails from the Enron corpus by their authors: Sara has label 0 Chris has label 1 """ import sys from time import time sys.path.append("../tools/") from email_preprocess import preprocess ### ...
d2dd17b90160fe9b9b0c0abf95bf39159cbd0d85
Arrisio/6_password_strength
/password_strength.py
3,205
3.59375
4
import re import getpass import string import argparse def validate_password(typed_password): if re.search(r'[^ -~]+', typed_password): raise ValueError( 'password must contain only English characters,' ' numbers and punctuation' ) elif not typed_password: raise...
aee9f703395a891d974d1bce351a6fa00b851761
mofresh27/UM
/Celcius_conversion.py
92
3.890625
4
celsius = input ('What is the tempeture in celsius?\n') f= float(celsius)*9/5+32 print(f)
3cb71a2b56972f44c874c1a856efe8cb69b2166e
tbobm/99problems
/python/lists/P10.py
731
3.734375
4
# encoding: utf-8 # 1.10 (*) Run-length encoding of a list. # Use the result of problem 1.09 to implement the so-called run-length encoding data compression method. Consecutive duplicates of elements are encoded as terms [N,E] where N is the number of duplicates of the element E. # # Example: # ?- encode([...
92c4780a8edac081ff0e7b83f6f9432d7fb12c1c
tbobm/99problems
/python/lists/P06.py
189
3.828125
4
# encoding: utf-8 # 1.06 (*) Find out whether a list is a palindrome. # A palindrome can be read forward or backward; e.g. [x,a,m,a,x]. def func(data): return data == data[::-1]
715066bd00aa896f5816e008d71d2e240bb605d8
Giants533/Risk_Model
/final_points.py
6,832
3.84375
4
# -*- coding: utf-8 -*- """ Created on Thu Feb 18 2021 @author: PINELOPI LOIZOU (BIOS INTERNSHIP) """ from __future__ import division import numpy as np def final_points(year_st, year_en, name='BERMUDA'): """" This function is used for creating files which contain information about the tr...
f8a044503247704e8361defa1967b713b5829bd7
Giants533/Risk_Model
/dam_wind.py
1,275
3.5625
4
# -*- coding: utf-8 -*- """ Created on Thu Feb 18 2021 @author: PINELOPI LOIZOU (BIOS INTERNSHIP) This script is used for getting a relationship between wind speed estimate at Bermuda and damage ratio based on the study by Miller et al., 2013. """ from __future__ import division import numpy as np ...
c6d616cebc923025d4ddbe465f723498c5b95d8f
orlyrevalo/Personal.Project.1
/Project1.19.py
367
3.9375
4
friends = ["Jim", "Karen", "Kevin"] for letter in "Giraffe Aademy": print(letter) for x in friends: print(x) for index in range(10): print(index) for y in range(3, 10): print(y) for z in range(len(friends)): print(friends[z]) for a in range(5): if a == 0: ...
e05da78b08600c8c414b1124abc83e79df23d9c2
orlyrevalo/Personal.Project.1
/Project1.12.py
198
3.71875
4
def cube(num): num*num*num print(cube(3)) def cube1(num): return num*num*num print(cube1(3)) def cube2(num): return num*num*num result = cube2(4) print(result)
f89fbdc4b681b813e357515e378cf07b2aeab38e
bsharabi/Design-Patterns
/Day 02 - 14.03.2019/00_UML/app.1.py
179
3.75
4
text = input('Enter something: ') try: if len(text) < 3: raise Exception() except Exception: print("End of dddapp") finally: print("End of app")
8b3791b73b9552c52659f9f1f80b4e58b02065df
kaisersakhi/python-socket-programing
/server.py
3,514
3.796875
4
import socket import sys from threading import Thread HOST = '127.0.0.1' PORT = 5050 ENCODING_METHOD = "UTF-8" HEADER_SIZE = 10 BUFFER_SIZE = 20 # BYTES def createSock(): """ The arguments passed to socket() specify the address family and socket type. AF_INET is the Internet address family for I...
f2792ae5d4d94df8e2699e9864048857ac7b5d2f
Krysioly/Project-web-app
/seed.py
3,180
3.5
4
"""seed info to make database""" from sqlalchemy import func from model import User, Entry, Todo, connect_to_db, db from server import app from datetime import datetime import hashlib def load_users(): """Load users from users.item into database.""" print("Users") User.query.delete() for row in ope...
102400991be1b1c08930a462d7aa64d62d836806
DawnBee/Problem-Solving-with-Algorithms-and-Data-Structures-using-Python
/Ch03. Basic Data Structures/LinkedLists/SinglyLinkedList/list.py
4,333
3.671875
4
from node import Node class List: def __init__(self): self.head: Node = None self.tail: Node = None def isEmpty(self)->bool: return self.head is None def numberOfElements(self)->int: if self.isEmpty(): return 0 else: current: Node = self.hea...
8a6c6edc2849eebdf33362d7a64d5d1fe12c5fff
DawnBee/Problem-Solving-with-Algorithms-and-Data-Structures-using-Python
/Ch04.Recursion/sum-numbers.py
237
3.921875
4
numbers: list = [1, 2, 3, 4, 5] def sum_nums(nums: list) -> int: if len(nums) == 0: return 0 elif len(nums) == 1: return nums[0] else: return nums[0] + sum_nums(nums[1:]) print(sum_nums(numbers))
e4ad105560a5bffb4cc83a76d4716c5c3311cea4
DawnBee/Problem-Solving-with-Algorithms-and-Data-Structures-using-Python
/Ch02. Analysis/anagramDetectionExtraSpace.py
810
3.59375
4
''' this solution is O(n), but it requires extra space for 2 lists ''' def anagramDetection(string1, string2): l1 = [0] * 26 l2 = [0] * 26 pos1 = 0 while pos1 < len(string1): character = string1[pos1] index = ord(character) - ord("a") l1[index] = l1[index] + 1 pos1 += 1...
862ad65b2725fccef121223f02db814e54211607
danielmulroy/Treatwell
/advanced.py
1,558
3.84375
4
# ┌ is 9484 # └ is 9492 # ┘ is 9496 # ┐ is 9488 # | is 124 def main(): while True: try: w = int(input("What is the width? (minimum 2) ")) if w < 2: print("Input must be an INTEGER greater than 2, please try again.") continue break ...
06f39f59efc477e95f5f5d1030d7f3280d220f39
darmel/python-curso
/04_funciones.py
817
3.546875
4
'''parametros o argumentos son valores que se reciben en una funcion a travez de los parentesis)''' def nombre_funcion(param): valor = 0 return valor def mostrar_usuario(nombre, edad, ciudad): print(f'{nombre} tiene {edad} años y vive en {ciudad}') mostrar_usuario('santiago',37,'villa carlos ...
40eb05df6594fef53e401d65bafc43e61016dd65
darmel/python-curso
/clases.py
599
3.796875
4
#clases #class (palabra reservada) El nombre de la clase comienza en mayuscula class Persona: #pass //pass es para que no tenga nada mas def saludar(self, nombre): #metodo, acciones oo funciones print(nombre, " esta saludando") def comer(self, nombre): print(nombre, " esta comiendo")...
778d4c61b8f8697581305b62f0fe7db57d400faa
darmel/python-curso
/calculaDog.py
198
3.578125
4
#Calcula la edad de tu perro multiplica = 7 edad = int(input('Ingrese la edad de su perro: ')) edadPerro = edad * multiplica print('La edad de tu perro en años perrunos es: ', edadPerro)
19bf407a5e17658ba2e6415c46add2a89ca5f6d5
oguerrerog/fundamentos-python
/Funciones Basicas II.py
3,302
4
4
# Ejercicios #1 - Cuenta regresiva : crea una función que acepte un número como entrada. # Devuelve una nueva lista que cuenta hacia atrás en uno, desde el número # (como el elemento 0) hasta 0 (como el último elemento). # ...
d07c79a0c0088e4c9500f2d6a4588a2bae3e02e0
oguerrerog/fundamentos-python
/Funciones Intermedias II.py
5,179
3.96875
4
# Ejercicio #1 - Cambia el valor 10 en x a 15. Una vez que haya terminado, x ahora debería ser [[5,2,3], [15,8,9]]. #### x = [ [5,2,3], [10,8,9] ] print(f"x Antes :{x}") (x[1])[0] = 15 print(f"x despues :{x}") #### #### # Ejercicio #1.1 "BONUS" - Cambia el valor 10 en x a 15. Una vez que haya terminado, x ahora deb...
e8dae572a8f14ec85a0cdb172f74dc42a1038278
fabianludwig/sim-climate
/functions/print.py
1,447
3.78125
4
def print_watt(menge_in_kw): if menge_in_kw > (1000*1000*1000): return "{} TWh".format( round(menge_in_kw/(1000*1000*1000), 2) ) if menge_in_kw > (1000*1000): return "{} GWh".format( round(menge_in_kw/(1000*1000), 2) ) if menge_in_kw > 1000: return "{} MWh".format( round(menge_in_kw/1000, 2) ...
5a9dff2f0a91e131b60e46a368beace41b98b3dd
oleges1/denoising_project
/BM3D_py/cpp2py_test/close_power_of_2_test.py
508
3.640625
4
import numpy as np def my_closest_power_of_2(M, max): M = np.where(max < M, max, M) while max > 1: M = np.where((max // 2 < M) * (M < max), max // 2, M) max //= 2 return M def closest_power_of_2(n): r = 1 while r * 2 <= n: r *= 2 return r if __name__ == '__main__': ...
aaa3f78681bc327ae6ce4007ac15025982baec1a
Mardud12/Excercism
/triangle/triangle.py
786
4.03125
4
def equilateral(sides): a = sides[0] b = sides[1] c = sides[2] if a+b <c or a+c <b or b+c <a: return False if a <= 0 or b <= 0 or c <= 0: return False if a == b and a == c: return True else: return False def isosceles(sides): a = sides[0] b = sides[1...
bb5cc3ef79e396d1b1db590c523ebbc59f9da353
wbr9727/OnTheApplicationOfDeepLearningInModelingMetasurface
/tmp.py
3,820
3.640625
4
#! /usr/bin/env python # -*- coding: utf-8 -*-  import os import numpy as np import Auxiliary as A import numpy as np import matplotlib.pyplot as plt # def generate_poisson(m): # # print(m) # k = 0 # p = np.exp(-m) # # print('p', p) # sum_poisson = p # y = np.random.random() # # print('y'...
f103a0b57c24c190b83dd9fb8eedee4bf4dbb4f2
jhill57/Module-6-Lab-Activity
/problem 2 randomint.py
260
3.53125
4
# this program was created by Jordan on 2/22/2020 # this program prints a random odd number betweewn 1 and 100 #problem 2 import random #Consider this alternative too: #print(random.randrange(1, 100, 2)) prob = 2*(random.randrange(0,100//2))+1 print(prob)
a046d8947e0d592b1f2a78e44622804208841e89
YaraiLee/Python
/my_practice/case1_100/case_12.py
556
3.765625
4
#!/usr/bin/python #-*-coding: UTF-8 -*- #题目:判断101-200之间有多少个素数,并输出所有素数。 #程序分析:判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除,则表明此数不是素数,反之是素数 h = 0 leap = 1 from math import sqrt from sys import stdout for m in range(101, 201): k = int (sqrt(m+1)) for i in range(2, 2+k+1): if m % i == 0: leap = 0 break if leap == 1: pr...
cacd8842e8fc774c34a3361eebb2731093bfb414
YaraiLee/Python
/my_practice/test.py
1,258
4.09375
4
#!/usr/bin/python # -*- coding: utf-8 -*- import os """ print ("hello, python!") if True: print ("True") else: print ("False") """ ###List """ list=['runoob', 786, 2.23, 'john', 70.2] tinylist = [123, 'john'] print (list) print (list[0]) print (list[1:3]) print (list[:3]) print (list[3:]) print (list[-3:-1]) pri...
5e3597c8259ff5c717285a5e97375c3d89ee781a
YaraiLee/Python
/my_practice/finger_gussing.py
835
3.71875
4
#-*-coding:UTF-8-*- import random while 1: s = int(random.randint(1, 3)) if 1 == s: ind = "石头" elif 2 == s: ind = "剪子" elif 3 == s: ind = "布" m = input("输入 石头、剪子、布,输入'end'结束游戏:") blist = ['石头','剪子','布'] if (m not in blist) and (m != 'end'): print ('输入错误,请重新输入!') elif (m not in blist) and (m == 'end'): ...
19e020f36e6d2f3b5534008c4d379eeb2d2b9c81
nachtmaar/adventofcode2018
/day1/part2/day1.py
633
3.84375
4
#!/usr/bin/env python3 duplicates = set() with open('input', 'r') as f: frequencies = [int(x) for x in f.read().split("\n")] def find_frequency(): sum_frequencies = 0 index = 0 while True: for frequency in frequencies: sum_frequencies += frequency previous_length = len...
2327b6c6896fad705c3cbd530b24c152f4e97905
fagan2888/portfolio
/portfolio/plotting.py
2,956
3.640625
4
""" Functions for plotting """ import numpy as np import matplotlib.pyplot as plt from matplotlib import rc import seaborn as sns def plot_comparison(X, Y, xlabel = None, ylabel = None, filename = None): """ Plots two sets of data against each other :param X: First set of data points :type X: array ...
6edb9ab693e618a5f486a23f33a85afec3ee8458
NickHan-cs/LeetCode
/Algorithms/102 Binary Tree Level Order Traversal/bfs.py
1,901
3.59375
4
from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None ''' class Solution: def __init__(self): self.ans = [] def levelOrder(self, root: TreeNode) -> List[List[int]]: def getNextLevelOrder(lastlevel): ...
767756c9e6e2cf9303c183aa67f625724946baec
NickHan-cs/LeetCode
/Algorithms/94 Binary Tree Inorder Travelsal/BinaryTreeInorderTraversal_Recursive.py
541
3.875
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 inorderTraversal(self, root: TreeNode) -> List[int]: nodeList = self.Recursive(root) valList = [] for i in n...
d1d15ec58255f92b4081f876fdb43ffa38526b6f
NickHan-cs/LeetCode
/Algorithms/107 Binary Tree Level Order Traversal 2/bfs.py
1,079
3.640625
4
from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: ans = [] if not root: return ans level = [root] wh...
03fb6ab407a13a5848341a16e71e05ef9dc74c7a
k-macmillan/advent2020
/1.py
1,211
3.53125
4
def walk_expenses_part_1(expenses) -> int: """ This could be better with some binary searching and logic, but I'm being lazy :return: tuple of data points """ for i in range(len(expenses)): for j in range(len(expenses)): if i != j and expenses[i] + expenses[-j] == 2020: ...
93ca310d0814318cd882a6dc7a030e2949594989
junha6316/Algorithm
/0702_2NTiling.py
245
3.5625
4
def solution(N): #memos=[[1,1]] + [[0,0] for i in range(N-1)] # [tno doble, tno one] if N==1: return 1 memo=[1,2] for i in range(2,N): memo.append(memo[i-2]+memo[i-1]) return memo[-1] print(solution(10))