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
4bcc68a95b9a3cc050923030076aab25a37c835e
ausaki/data_structures_and_algorithms
/leetcode/largest-time-for-given-digits/403090331.py
446
3.5
4
# title: largest-time-for-given-digits # detail: https://leetcode.com/submissions/detail/403090331/ # datetime: Thu Oct 1 20:28:46 2020 # runtime: 32 ms # memory: 14.1 MB class Solution: def largestTimeFromDigits(self, arr: List[int]) -> str: a = sorted(itertools.permutations(arr)) b = (2, 3, 5, 9...
26172b410b0e1f0d03a13f4c76f9656387b496d4
ausaki/data_structures_and_algorithms
/leetcode/check-if-there-is-a-valid-path-in-a-grid/375738683.py
978
3.546875
4
# title: check-if-there-is-a-valid-path-in-a-grid # detail: https://leetcode.com/submissions/detail/375738683/ # datetime: Tue Aug 4 12:29:55 2020 # runtime: 4972 ms # memory: 566.1 MB class Solution: def hasValidPath(self, A: List[List[int]]) -> bool: m, n = len(A), len(A[0]) uf = {(i, j): (i, j)...
2e85d320ce4d64a2be79c60d4e8799479a6034f6
ausaki/data_structures_and_algorithms
/three_sum.py
712
3.703125
4
def three_sum(sequence, sum): sequence = sorted(sequence) n = len(sequence) for i in range(n - 2): l, r = i + 1, n - 1 sub_sum = sum - sequence[i] if sub_sum < sequence[l] + sequence[l + 1] or sub_sum > sequence[r] + sequence[r - 1]: continue while l < r: ...
f816d88626f40ca8c653183cf0927ec5605f0e15
ausaki/data_structures_and_algorithms
/leetcode/transpose-matrix/406865171.py
421
3.546875
4
# title: transpose-matrix # detail: https://leetcode.com/submissions/detail/406865171/ # datetime: Sat Oct 10 17:11:04 2020 # runtime: 72 ms # memory: 14.7 MB class Solution: def transpose(self, A: List[List[int]]) -> List[List[int]]: m, n = len(A), len(A[0]) B = [[0] * m for i in range(n)] ...
fee37ef5fe31684200d94c9ae3cb7b769d4fd8b0
ausaki/data_structures_and_algorithms
/leetcode/how-many-numbers-are-smaller-than-the-current-number/386174767.py
557
3.65625
4
# title: how-many-numbers-are-smaller-than-the-current-number # detail: https://leetcode.com/submissions/detail/386174767/ # datetime: Tue Aug 25 22:17:50 2020 # runtime: 48 ms # memory: 13.7 MB class Solution: def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: n = len(nums) result ...
47f889aed8e1fda9db8c0ea16de529beadfdc29b
ausaki/data_structures_and_algorithms
/suffix_array.py
1,467
3.65625
4
''' https://cp-algorithms.com/string/suffix-array.html https://en.wikipedia.org/wiki/Suffix_array ''' def suffix_array_count_sort(s): s += '$' b = ord('$') K = ord(max(s)) - b + 1 n = len(s) p = [0] * n c = [0] * n cnt = [0] * max(K, n) for i in range(n): cnt[ord(s[i]) - b] ...
af0326a9fc3b943ed8095292152acdcc33d76e72
ausaki/data_structures_and_algorithms
/leetcode/cells-with-odd-values-in-a-matrix/394274324.py
491
3.515625
4
# title: cells-with-odd-values-in-a-matrix # detail: https://leetcode.com/submissions/detail/394274324/ # datetime: Sat Sep 12 01:28:46 2020 # runtime: 44 ms # memory: 13.9 MB class Solution: def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int: rows = [0] * n cols = [0] * m ...
d5e8f226210a3977940877874b2b632c1302b1c0
ausaki/data_structures_and_algorithms
/leetcode/break-a-palindrome/390963712.py
484
3.5
4
# title: break-a-palindrome # detail: https://leetcode.com/submissions/detail/390963712/ # datetime: Fri Sep 4 23:45:35 2020 # runtime: 28 ms # memory: 13.7 MB class Solution: def breakPalindrome(self, palindrome: str) -> str: n = len(palindrome) m = n // 2 for i in range(m): i...
22bc93214a0a36fef35ca53d6de8eb52762d2ce4
ausaki/data_structures_and_algorithms
/leetcode/check-if-number-is-a-sum-of-powers-of-three/464248909.py
663
3.859375
4
# title: check-if-number-is-a-sum-of-powers-of-three # detail: https://leetcode.com/submissions/detail/464248909/ # datetime: Sat Mar 6 22:44:42 2021 # runtime: 2164 ms # memory: 630.7 MB class Solution: powers = [1] * 16 for i in range(1, 16): powers[i] = powers[i - 1] * 3 def checkPower...
1296af11e593c162f635aed485bcc72cf4b7378b
ausaki/data_structures_and_algorithms
/leetcode/pancake-sorting/402301056.py
593
3.578125
4
# title: pancake-sorting # detail: https://leetcode.com/submissions/detail/402301056/ # datetime: Wed Sep 30 00:08:58 2020 # runtime: 44 ms # memory: 14.1 MB class Solution: def pancakeSort(self, arr: List[int]) -> List[int]: n = len(arr) result = [] for v in range(n, 0, -1): i ...
eb6f98e21d1ce0766eaa4c5e7722693e31e7ff28
saito1/lab1
/servidor
4,275
3.53125
4
#!/usr/bin/env python3 # seu código aqui import socket import re import sys import queue import select """ def readline(socket): ret = '' while True: c = socket.recv(1) if c == b'\\': d = socket.recv(1) if d == b'n' or d == b'': break else: ret += str(d.decode("utf-8")) break elif c == b'...
9582c3c5c904081392e126156faf1b15da98a1c3
buitrungtbc4/hetrogiup
/schoolsql.py
1,370
3.53125
4
import sqlite3 from school import School # chon 1 truong voi username def select_school(username): conn = sqlite3.connect('school.db') c = conn.cursor() c.execute("SELECT * FROM school WHERE user_name = '%s'" % username) row = c.fetchone() if row is None: return None else: schoo...
a71578bc8fd968e3c5a51bb13432bac898b401b0
Renqianbei/python_study
/pythonBase/text_13.py
958
3.78125
4
#! /usr/bin/env python # -*- coding: utf-8 -*- import sys def fuckyou(x): print(x*3) #每个模块都有一个__name__属性,当其值是'__main__'时,表明该模块自身在运行,否则是被引入。 if __name__ == '__main__': print(sys.path) print('程序自身在执行') else: print('我来自另一模块') def sayHello(): print('helloword') #内置的函数 dir() 可以找到模块内定义的所有名称。以一个字符串列...
84a2892438324565885224e9327732e7cfb78450
BahadirGLCK/TrainingPython
/Koşullu_Durumlar_Problemler.py
3,331
3.640625
4
#Problem 1 kilo = int(input ("Kilonuzu Giriniz : ")) boy = float (input("Metre Cinsinden Boyunuzu Giriniz: ")) bke= kilo / (boy **2) if (bke <= 18.5): print("Zayıf") elif (bke <= 25 and bke >= 18.5 ): print ("Normal") elif (bke <= 30 and bke >= 25 ): print ("Fazla Kilolu") elif ( bke >= 30 ): print ("Obez") #Pro...
966b58194fe1c884be231c8583a7a900549fa1bb
BahadirGLCK/TrainingPython
/Sqlite Veritabanı/veritabanı.py
743
3.59375
4
import sqlite3 con = sqlite3.connect("kütüphane.db") cursor = con.cursor() def tablo_olusturma(): cursor.execute("CREATE TABLE IF NOT EXISTS kitaplık (İsim TEXT, Yazar TEXT,Yayınevi TEXT,Sayfa INT)") con.commit() def veri_ekleme(): cursor.execute("Insert into kitaplık VALUES('Yalın Yeni Girişim','Eric Ri...
38b7970dc756904998585d3e0374dac539fdfe17
tomsitter/bioinfo-algorithm-experiments
/utility.py
2,264
3.796875
4
from collections import defaultdict from string import maketrans def reverse_complement(seq): '''Given a DNA sequence, prints the reverse complement''' forward = 'ATGC' reverse = 'TACG' revseq = seq[-1::-1] comp = revseq.translate(maketrans(forward, reverse)) return comp def list_occurences(...
b1adbf5abb72a6d4887304a8f641c82bcd24015a
stefanonu/Python
/Laborator 7/Problema 3.py
1,763
3.578125
4
# 3. Gasiti toate fisierele duplicate dintr-un director dat ca argument si afisati timpul de rulare. # Calea grupurilor de fisiere duplicate vor fi scrise intr-un fisier output.txt. import os import hashlib def compute_hash_of_file(file): m = hashlib.sha1() f = open(file, "rb") while True: data =...
c26c1dba7c20103836aec0fb9b0e717334dcc040
stefanonu/Python
/Lab2Python/Problema 6.py
429
3.8125
4
def lista(y,*listOfLists): x=dict() for iterator in listOfLists: for iterator2 in iterator: if iterator2 in x.keys(): x[iterator2]=x[iterator2]+1 else: x[iterator2]=1 items=list() for iterator in x.keys(): if x[iterator] == y: ...
924b871f334495a6ea10a1d6cb7bd17b695b255f
stefanonu/Python
/Test 1/Problema 2.py
389
3.765625
4
def gaseste_asemanari(list_one,list_two): set_one=set() for iterator in list_one: for iterator2 in list_two: if str(iterator)==str(iterator2): set_one.add(iterator) return set_one print(gaseste_asemanari([1,2,3,4,5,6,5,4,3,2,1], [1,1,2,2,3,3,4,5])) print(gaseste_asem...
738570a5b886431f2b2eeb734146375e1cef285b
Kmenguete/OpenClassroom_projet2
/get_books_for_category.py
1,646
3.875
4
import csv import os import requests from bs4 import BeautifulSoup from Book_detailed_scraper import book_extract_information, store_book_information, fieldnames """ the goal of the get_books_for_category function is to get every book information for one category. Here, we took #the category travel as an example. Ins...
cf53a1b7300099ea8ecbe596ac2cb6574642e05f
sainath-murugan/small-python-projects-and-exercise
/stone, paper, scissor game.py
1,231
4.21875
4
from random import randint choice = ["stone","paper","scissor"] computer_selection = choice[randint(0,2)] c = True while c == True: player = input("what is your choice stone,paper or scissor:") if player == computer_selection: print("tie") elif player == ("stone"): if computer_selection =...
20a6ca776f7f3fc4786e43d4deed00280e3020eb
animeshpatcha/automation
/leetcode/self_dividing_numbers.py
1,225
4.0625
4
''' A self-dividing number is a number that is divisible by every digit it contains. For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. Also, a self-dividing number is not allowed to contain the digit zero. Given a lower and upper number bound, output a list of every pos...
4750979b737ba02e701c686f9f50a7a4b7c05661
Sachey-25/PythonTutorials
/pythonModule.py
3,332
3.5
4
# # '#' --> Regex #passord --> re.fullmacth('[a-k][0369][a-zA-Z0-9]*','\s') '''Modules in python --> A file containng a set of functions/python code which you want to include in your application''' '''def test_module(name): print("I am printing from another python file") person_info = { "name":...
a3ec1b25bbe6d13b167a218556e67a2ad4989815
tstuessi/advent-code-2016
/day6/sol2.py
635
3.703125
4
# Part 1 of day 6 # # Frequency counter # Tyler Stuessi from collections import defaultdict from operator import itemgetter def frequency_counter(): input_list = [] message = "" with open("input.txt", "r") as f: input_list = f.read().split("\n") del input_list[-1] dicts = [] f...
fb0a422f12dd7a159a0cb25e808ca58576bbf889
Tjasa1/advent_of_code_2020
/day6-1.py
846
3.8125
4
#Advent of Code 2020: Puzzle 6, Part 1 #1 import the data with open("day6-1.txt", "r") as inputfile: data = inputfile.read() #2 Separates answers into the list of lines answ_group = data.split("\n\n") #3 counts the answers counter = 0 for i in answ_group: #3.1 Splits answers per group (separated by \n\n): ...
ce415d0436469e376e6909eaa32ca9196568bbfe
Tjasa1/advent_of_code_2020
/day6-2.py
1,019
3.828125
4
#Advent of Code 2020: Puzzle 6, Part 2 #1 import the data with open("day6-1.txt", "r") as inputfile: data = inputfile.read() #2 Separates answers into the list of lines answ_group = data.split("\n\n") #print(answ_group) #3 counts the answers answ_counter = 0 for i in answ_group: #3.1 splitting answers per gr...
4de111c2213b8f5f462f6ddf99266c8d8523e42a
mbilal85/Working-with-Dates-and-Time-in-Python
/Working with dates and time in python.py
92,386
4.28125
4
#!/usr/bin/env python # coding: utf-8 # # Working with Dates and Times in Python # # You'll probably never have a time machine, but how about a machine for analyzing time? As soon as time enters any analysis, things can get weird. It's easy to get tripped up on day and month boundaries, time zones, daylight saving ti...
a7e85d096d9f717c8de1745914f1df3f70611818
Sapi98/Small_Projects
/MAC_Changer.py
7,736
3.640625
4
import os import subprocess import time class MACChanger: """This is the class designed to contain all the methods and data that are required for basic operation of the code. All the basic functionalities are encapsulated within this class. It is possible to easily extract all the components of this file...
1e80c9f0e536a0a7074cbfca87da20302ba299fe
OliverNichols/python-exercises
/day-2/exercise-1b.py
157
3.78125
4
# Exercise 1 + stretch goal a my_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] result = [] for x in my_list: if x < 5: result.append(x) print(result)
c28824299a13da65f89187e2c6394eb58dfa9cfc
OliverNichols/python-exercises
/day-2/exercise-3.py
119
3.578125
4
# Exercise 3 my_list = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] result = [x for x in my_list if not x%2] print(result)
590e2a14a92c54ada537038a0963f0409e7be01f
etmasi/CS-101
/06 prove/chapter 8/loops.py
237
4.03125
4
user = int(input(f'How many colums and row do you want in your multiplication table?')) number = user + 1 for val_1 in range(1,number): for val_2 in range(1,number): print('{:3}'.format(val_1 * val_2),end='') print()
4e8799d7ea432ad432a77bb646bfc8746f617b0b
mperdikeas/py-abstract-algebra
/gcd-euclidean-algorithm/gcd.py
9,674
3.734375
4
# # Abstract Algebra: Theory and Applications # Chapter 2, Programming Exercise #3 # # Write a computer program that will implement the Euclidean algo- # rithm. The program should accept two positive integers a and b as input # and should output gcd(a, b) as well as integers r and s such that # gc...
1d6393ad2e81d38d54d2273844e40f2022cfcfab
Vikrant7981/Lab6-Lab7
/q1/test.py
904
3.96875
4
import numpy as np def avada_kedavra(my_list): # Create an array 'a0' from this list 'my_list' # print a0 a0=np.array(my_list) print("a0 at beginning:\n{}".format(a0)) # reshape a0 to create a 5X5 matrix a1 a1=np.reshape(a0,(5,5)) # print a1 print("a1 at the beginning:\n{}".format(a1)) # now, change the cen...
c533d92da737a692b02e2f2b74b8080fa6800863
ankitk2109/LeetCode
/13. LengthOfLastWord.py
437
3.625
4
#Problem Statement available at: https://leetcode.com/problems/length-of-last-word class Solution: def lengthOfLastWord(self, s: str) -> int: if(s is not ""): s_lst = s.split(' ') n = len(s_lst) while(n>0): if(s_lst[n-1] is not ''): re...
7e10f9f91560ebcc5ab920e9f0eb4f84dc3cf9cb
ankitk2109/LeetCode
/12. AddTwoNumbers(linkedlist).py
1,804
3.65625
4
#Problem Statement available at: https://leetcode.com/problems/add-two-numbers # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def createNode(self, val, current, carry): if(val>9): r = val % 10...
490ac1bdd78965ca1c1f5313b53e66b8515b8ef8
ankitk2109/LeetCode
/23. RemoveLinkedListElement.py
1,150
3.71875
4
#PS: https://leetcode.com/problems/remove-linked-list-elements # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: if not head: ret...
17b831979fdd476141c0d8edd59b02c10693431e
asperaa/programming_problems
/tree/lca_in_bt_linear_space.py
1,216
3.671875
4
"""lca in binary tree. Time-O(n) and Space-O(n)""" class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None class LCA: def __init__(self): self.lca = None def bt_search(self, root, p, q): if not root: return False ...
0bea4a359a651daeb78f174fe3fb539e118c39ad
asperaa/programming_problems
/linked_list/cll_create.py
1,345
4.34375
4
# class for Circular linked list node class Node: # function to initiate a new_node def __init__(self, data): self.data = data self.next = None # class for circular linked list class CircularLinkedList: # function to initialise the new_node def __init__(self): self.head = None...
5f78d8aa113bfe63ec884f9fb4e66e60bdf0764e
asperaa/programming_problems
/tree/symmetric_tree.py
1,099
3.96875
4
"""Symmetric tree""" class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None class SymmetricTree: def is_symmetric_util(self, root1, root2): if root1 == None and root2 == None: return True if root1 == None or root2 == None: ...
f8c8020295a24bc73e4e3b2d7fec81dec513b5b7
asperaa/programming_problems
/linked_list/dell_dup_2.py
2,396
3.8125
4
"""Delete the duplicates in ll and only keep distinct elments at the end""" # A Node class class Node: # initialse the node with data and next def __init__(self, data): self.data = data self.next = None # A linked list class class LinkedList: # initialise the head of the linked list def ...
0323f6c218134e004dad1354bddde832dafa72a0
asperaa/programming_problems
/stack/astroid_collision.py
932
3.53125
4
"""Astroid collision question""" def astroid_collision(arr): stack = [] for element in arr: if len(stack) == 0 or element > 0: stack.append(element) else: while stack and stack[-1] > 0: if stack[-1] == -element: ...
8e0ebcafccd66a0c306987258ff873d105620e93
asperaa/programming_problems
/linked_list/plus_one_linked_list_recursive.py
1,348
3.8125
4
"""Add a number to the linked list where each node denotes the digit recursively""" class ListNode: def __init__(self, val): self.val = val self.next = None class LinkedList: def __init__(self): self.head = None def append(self, val): new_node = ListNode(val) if...
df452d8d8b7b8e33bcd9288e1e21816b6781cd0c
asperaa/programming_problems
/linked_list/ll_length.py
1,368
4.09375
4
# Node class class Node: # function to start a node and fill data def __init__(self, data): self.data = data # fill the data self.next = None # point the next of linked list to null # LinkedList class class LinkedList: # function to initialise a linked_List def __init__(self): ...
bfb20bf8264e5c06b59c7afe0cafd470b731c881
asperaa/programming_problems
/array/sum_of_two_num.py
273
3.546875
4
def twoSum(nums, target): hash_dict = dict() for i, num in enumerate(nums): hash_dict[target-num] = i for i in range(len(nums)): if nums[i] in hash_dict: if i != hash_dict[nums[i]]: return [i, hash_dict[nums[i]]]
ebc792a1c6dc8bfc7e7c7e62406fb35cf0db3037
asperaa/programming_problems
/tree/validate_BST.py
816
4
4
"""Validate BST""" class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def is_bst_util(root, lower_limit, upper_limit): if not root: return True val = root.val if val <= lower_limit or val >= upper_limit: return False r_...
80c5a656ada54ee032d00da1798c65f398cba8ec
asperaa/programming_problems
/tree/num_of_path_sums_O(n)_time.py
1,309
3.6875
4
"""Find the number of path sums in whole tree""" class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None class PathSumNum: def path_sum_util(self, root, sum, curr_sum, cache): if not root: return None curr_sum += root.v...
9df8060a2eff1b0b5915f41c6a1040246e96880a
asperaa/programming_problems
/tree/root_to_leaf_path_sum_all_paths.py
1,372
3.6875
4
"""Path sum routes equal to root to leaves""" class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None class PathSumAll: def __init__(self): self.path_sum = [] def path_sum_all_util(self, root, sum, r_sum, route): if not ro...
316c16a74400b553599f007f61997e65a5ed0069
asperaa/programming_problems
/linked_list/rev_group_ll.py
1,889
4.25
4
""" Reverse a group of linked list """ class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: # initialise the head of the linked list def __init__(self): self.head = None # add a new node to the end of linked list def add_node(self, ...
dd379898627e998abe65dcb2a028949b007f72f9
asperaa/programming_problems
/linked_list/ll_selection_sort.py
2,663
3.796875
4
"""Selection sort in a linked list (TODO: Rectify this one)""" class ListNode: def __init__(self, val): self.val = val self.next = None class LinkedList: def __init__(self): self.head = None def append(self, val): new_node = ListNode(val) if not self.head: ...
a5a71f6a82073258d5f000b52fc4d7e34d1be79d
asperaa/programming_problems
/tree/connect_nodes_at_same_level_O(n)_space.py
976
3.859375
4
"""Connect nodes at Same level .O(n) space""" from collections import deque class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None self.next = None def connect_nodes(root): if not root: return None queue = deque() ...
f7fa6a108c3a05c476fa48b679ec81b9dab0edd7
asperaa/programming_problems
/linked_list/rev_ll.py
1,383
4.25
4
# Node class class Node: def __init__(self, data): self.data = data self.next = None # LinkedList class class LinkedList: def __init__(self): self.head = None def push(self, data): new_node = Node(data) new_node.next = self.head self.head = new_no...
e05982cee993abbc9163123021f57d352d644225
asperaa/programming_problems
/stack/queue_using_stack.py
834
4.34375
4
"""Implement queue using stack i.e only use stack operations""" class Queue: def __init__(self): self.s1 = [] self.s2 = [] def empty(self): return len(self.s1) == 0 def push(self, val): self.s1.append(val) def pop(self): while len(self.s1) != 0: ...
acfd28963d6ba7c5a9dd912f726e6352d76f6104
asperaa/programming_problems
/linked_list/detet_loop.py
1,606
4.03125
4
# Node class class Node: def __init__(self, data): self.data = data self.next = None # LinkedList class class LinkedList: def __init__(self): self.head = None def push(self, data): new_node = Node(data) new_node.next = self.head self.head = new_node ...
c7050569b47d1066643cadf86d46b25237cf1179
asperaa/programming_problems
/dp/min_cost_climbing_stairs.py
448
3.6875
4
"""Min cost climbing stairs. DP. Time - O(n). Space - O(n)""" def min_cost(costs): length = len(costs) dp = [None] * (length + 1) dp[0] = costs[0] dp[1] = costs[1] for i in range(2, length): dp[i] = min(dp[i-1] + costs[i], dp[i-2] + costs[i]) dp[length] = min(dp[length-1], dp[length-2]...
956495f4026844ed336b34512c87aceec11c0ef8
asperaa/programming_problems
/linked_list/reverse_first_k.py
2,093
4.375
4
"""Reverse the first k elements of the linked list""" # Node class for each node of the linked list class Node: # initialise the node with the data and next pointer def __init__(self, data): self.data = data self.next = None # Linked list class class LinkedList: # initialise the head of the...
b1507117769677b028c86f588a88e91e67ef410f
asperaa/programming_problems
/binary_search/sqrt(x).py
385
4.1875
4
"""sqrt of a number using binary search""" def sqrtt(x): if x < 2: return x l = 2 r = x//2 while l <= r: pivot = l + (r-l)//2 num = pivot*pivot if num > x: r = pivot - 1 elif num < x: l = pivot + 1 else: return pivot ...
1711936a3ce541c4f8a06f5650b55255fe9d38d6
asperaa/programming_problems
/linked_list/add_two_numbers_I_recur.py
1,839
3.890625
4
"""Add two numbers as linked list I """ class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def append(self, data): new_node = Node(data) if not self.head: self.head = new_nod...
41fdbaf03a4002bd81fddac70b87d6014b7a3102
asperaa/programming_problems
/stack/prefix_to_postfix.py
534
3.953125
4
"""Prefix to postfix""" def prefix_to_postfix(exp): stack = [] operator = {"+": True, "-": True, "*": True, "/": True} for element in exp[::-1]: if element in operator: operand_1 = stack.pop() operand_2 = stack.pop() stack.append(operand_1+operand_2+element) ...
86b7267dba7692f6063fce705a6a8558ddfb6263
asperaa/programming_problems
/binary_search/pow(x, n).py
368
4.03125
4
"""Power of x. Binary Search Recursive""" def power_util(x, n): if n == 0: return 1 half = power_util(x, n//2) if n%2 == 0: return half*half else: return half*half*x def power(x, n): N = n if N < 0: x = 1/x N = -N return power_util(x, N) if __n...
fc6999c13ccf5b13fe731744b0535391435878eb
asperaa/programming_problems
/linked_list/last_occurence.py
1,439
3.78125
4
"""delete the last occurence of an item from the linked list""" import gc class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def append(self, data): # create a new node new_...
d07d3123904cd9ab00abf35017e5ff6cdf62fa38
asperaa/programming_problems
/binary_search/binary_search_recur.py
422
3.890625
4
"""Binary Search Recursion""" def bs(arr, l, r, item): if r >= l: mid = l + (r-l)//2 if arr[mid] == item: return mid elif item < arr[mid]: return bs(arr, l, mid-1, item) else: return bs(arr, mid+1, r, item) else: return False ...
18ac3d32ed748cc574f915b5b56d54474cd574af
asperaa/programming_problems
/tree/maximum_binary_tree.py
1,244
3.75
4
"""654. Make a maximum binary tree. T - O(n2), S - O(n2)""" class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def max_tree(arr): if not arr: return None length = len(arr) # get the index of the max element in the array (pyth...
47ae0d290252c3ead8171e047df364e3dc0dcac4
jhillorg/myPython
/sqlight1.py
388
3.53125
4
# # import sqlite3 conn = sqlite3.connect('tutorial.db') c = conn.cursor() def create_table(): c.execute('CREATE TABLE IF NOT EXISTS stuffToPlot(unix REAL,datestamp TEXT,keyword TEXT,value REAL)') def data_entry(): c.execute("INSERT INTO stuffToPlot VALUES(1234512345, '2016-10-28', 'Python', 5)") conn.co...
403a429c9574c03b09e6edefb0a40db17bf4c427
Vichu7190/Python
/checkDBConn.py
3,470
4.0625
4
""" Created on Sun Oct 31 15:01:50 2020 @author: Viswanathan A @Descirpion : Database Manager Class with Class Methods. This Code lets you connect to the Game Database. """ import sqlite3 class DatabaseManager: ''' This is the Database Manager class''' def __init__(self, db_name): self.db_name = db...
9bd1ec0e8941bae713a60098d73bc0d7f996bf9c
eldimko/coffee-machine
/stage3.py
1,047
4.34375
4
water_per_cup = 200 milk_per_cup = 50 beans_per_cup = 15 water_stock = int(input("Write how many ml of water the coffee machine has:")) milk_stock = int(input("Write how many ml of milk the coffee machine has:")) beans_stock = int(input("Write how many grams of coffee beans the coffee machine has:")) cups = int(inpu...
dd7519e7a1f1778f23cc336a341ba654ad05a0c4
alejeau/cocoma_mini_projet
/protocols/yankee_swap.py
2,956
3.71875
4
#!/usr/bin/python3 # -*-coding: utf-8 -* import copy def yankee_swap(participants: [int], gifts: [int], utilities: {str: [int]}) -> {str: int}: """ Implements the yankee swap protocol for n agents and m wrapped gifts. The gifts are chosen based on the maximum utility. Each gift can only b...
284220e1df9d5eab312d614498e48612e6d72b21
Eglopez/Python-GUI
/LinkedList.py
1,484
3.921875
4
from Node import * from Compare import * class LinkedList(): def __init__(self): self.first = None def add(self,value): if(not self.first): self.first = Node(value) else: compare = Compare() if(compare.compare(self.first,value) > 0): ...
f08db8d2ac2df4b7c871aa4f4103d8b5913e8c24
IlyaGagarin/gloacademypython
/урок8/zadanie6.py
276
3.734375
4
# -- coding: utf-8 total=0 counter=0 number=int(input()) number1=number while number != 0: number=int(input()) total+=number counter+=1 print(int((total+number1)/counter))
c6c43585b4424e2495c6d0902b1688b11f5d451d
IlyaGagarin/gloacademypython
/урок7/zadanie3.py
218
3.859375
4
# -- coding: utf-8 number1, number2 = int(input()), int(input()) if number2>number1: for i in range (number1, number2+1): print (i) else: for i in range (number2, number1+1): print (i)
8e8099196e84431837afd9c32cc280596e7f7604
IlyaGagarin/gloacademypython
/урок6/zadanie3.py
312
3.96875
4
# -- coding: utf-8 nametekst1 = input() nametekst2=input() nametekst3=input() if len(nametekst1)>len(nametekst2) and len(nametekst1)>len(nametekst3): print (nametekst1) elif len (nametekst2)>len(nametekst1) and len (nametekst2)> len (nametekst3): print (nametekst2) else: print (nametekst3)
d1d825c5a42a0fe1c818590b1d4c4df442e33d83
jdar/HacDC-Intro-to-Programming
/class_2/code/pong_paddle_new.py
1,951
3.828125
4
#!/usr/bin/python # there are some magic numbers around, but that's the point # right? """ A simple ball that hits a pong paddle """ import pygame from pygame.locals import * # some globals SCREEN_WIDTH = 640 SCREEN_HEIGHT = 480 FRAMERATE = 60 # initialize pygame pygame.init() # make a clock so things don't move un...
d47d976ac39dfa47b4383a50abea5d90556c3d45
payalkutana/datavisualization
/scatter_plot.py
227
3.578125
4
import matplotlib.pyplot as plt x=[1,2,3,4,5,6,7,8] y=[5,2,4,2,1,4,5,2] plt.scatter(x,y,label="skitscat",color="k",marker="o",s=25) plt.xlabel("X") plt.ylabel("Y") plt.title("Scatter Plot") plt.legend() plt.show()
9fa294f19b05addc2e4619c8969f8110cc8b40e0
RichardHHill/olympusElo
/league_simulation.py
6,664
3.953125
4
import random import numpy as np import matplotlib.pyplot as plt from player import Player # Simulation of how our elo system would play out # Players at launch def summarize_season(players): """After playing games, summarize the elo scores of players and their significance versus their strengths as pla...
a70f4863d89c02c276efdbd2df1ee02d55bb73d1
yufanq/Python
/matplotlib_base/lines_bars_markers/eventplot_demo.py
1,719
3.625
4
''' An eventplot showing sequences of events with various line properties. The plot is shown in both horizontal and vertical prientations ''' import matplotlib.pyplot as plt import numpy as np import matplotlib matplotlib.rcParams['font.size'] = 8.0 #Fixing random state for reproducibility np.random.seed(19680801)...
5e1c76466b5a4e309b8e53ced65d3f651168969e
anujns/Predictive-Analytics
/Assignment 2/Submission/mapper2.py
1,104
3.703125
4
#!/usr/bin/python3 import sys import re import string for line in sys.stdin: words = line.split() words = re.findall(r'\w+', line.strip()) length = len(words) i = 0 while (i+2 < length): first = words[i] first = first.strip(string.punctuation).lower() second = words[i+1] second = second.strip(string.p...
54fc68c2ba08b5a6d7af7110ba5ae66d7c9169c7
ashishsj9/myCode
/PDF/pdf2jpeg.py
590
3.609375
4
import os import sys from pdf2image import convert_from_path def convertPDF(pdf_file): try: if pdf_file.endswith(".pdf"): pages = convert_from_path(pdf_file, 300) pdf_file = pdf_file[:-4] for page in pages: page.save("%s-page%d.jpeg" % (pdf_file,pages.i...
69a1845303537328dfd0db3c2379b2d094643633
satya497/Python
/Python/storytelling.py
1,340
4.15625
4
storyFormat = """ Once upon a time, deep in an ancient jungle, there lived a {animal}. This {animal} liked to eat {food}, but the jungle had very little {food} to offer. One day, an explorer found the {animal} and discovered it liked {food}. The explorer took the {animal...
0f4005420c98c407a9d02e6f601c2fccbf536114
satya497/Python
/Python/classes and objects.py
775
4.46875
4
# this program about objects and classes # a class is like a object constructor #The __init__() function is called automatically every time the class is being used to create a new object. class classroom: def __init__(self, name, age): # methods self.name=name self.age=age def myfunc1(s...
27de6ce63fc85b15c6b5ae34d1fd60f1207348c1
Rickfdalton/numerical_python
/numerical python/newtons.py
650
3.515625
4
import sympy import math input_function =input("enter function ") err=float(input("enter error")) p=float(input("initial guess")) x= sympy.Symbol('x') diff_fun=sympy.diff(input_function,x) def f(x): return eval(input_function) def f1(x): return eval(str(diff_fun)) def g(k): return k-(f(k)/...
e34048b0fef3dec9c722ba371ae9ad73a856b9fe
Rickfdalton/numerical_python
/numerical python/fixed-point.py
537
3.609375
4
import math #fixed-point def g1(x): return 2*x-3*x**2 """def g2(x): return x-((x**3-21)/(3*x**2)) def g3(x): return x-((x**4-21*x)/(x**2-21)) def g4(x): return (21/x)**0.5""" print('====G1========') p=0.3 for i in range(10): print(p) p=g1(p) """print('====G2========') p...
9e37e9344ef0ab2ef7f8030c8f76152958ae14f0
JustinPrivitera/DayOfWeek
/main.py
189
4.21875
4
#!/usr/bin/python3 from dayOfWeek import * print("Enter future date in the following format: MM/DD/YYYY or MM/DD/YY: ") enteredDate = input() print(dayConverter(dayOfWeek(enteredDate)))
bfe56ede1e8b6307218295de126d9a334ab070d5
johnbuttigieg/Code
/Assignment ItemsForHire/JohnButtigiegA1.py
4,807
3.96875
4
#This allows the program to be exited when the user chooses to import sys def load_items(): returnarray = [] #Open, read and transfer the lines in data to the memory variable data_file = open("items.csv") for line in data_file: values = line.split(",") returnarray.append([values[0], va...
8ab192b9020532c84a0376facd8c8b6350db9693
anmoltanubhrt/Python_GeeksForGeeks
/lettersdigits.py
553
4
4
""" '''Write a program that accepts a sentence and calculate the number of letters and digits. ''' sentence = raw_input("Enter a sentence") # This statement records the input the user has given d={"DIGITS":0,"LETTERS":0} # Here, we are intializing a dictionary. The dictionary has two variables, digits and letters to ...
37b4d06bae9efe1e395517aa09e8fa7af3d033d7
YQRY/Practice
/wordgame4.py
735
3.890625
4
# users/朔/PycharmProjects # -*- coding:utf-8 -*- # author:YQRY time:2018/9/29 import random secret = random.randint(1,10) times = 3 print('猜数小游戏') guess = 0 print('猜我想的是哪个数字:', end='') while (guess != secret) and (times > 0): temp = input() while not temp.isdigit(): temp = input('抱歉,输入格式不对!请重输:') gu...
cb364e1508921977776712c109fea961d24e1ba4
YQRY/Practice
/递归法判断回文联.py
451
3.96875
4
# users/朔/PycharmProjects # -*- coding:utf-8 -*- # author:YQRY time:2018/12/1 def is_palindrome(n, start, end): if start > end: return 1 else: return is_palindrome(n, start+1, end-1) if n[start] == n[end] else 0 string = input('请输入一个字符:') length = len(string)-1 if is_palindrome(string, 0, leng...
bf0d5524c6dfabbfb9595850d7cab7bbb433b019
YQRY/Practice
/比较大小2.py
628
3.984375
4
# users/朔/PycharmProjects # -*- coding:utf-8 -*- # author:YQRY time:2018/10/11 x = int(input('输入第一个数:')) y = int(input('输入第二个数:')) z = int(input('输入第三个数:')) if x < y: # x < y small = x #接着比较x和z if z < small: # z < x 如果small<z,small=small,所以不写small<z small = z #所以z最小 elif y <...
c3ba88058f0459e9373ed14906118625921d0ff6
RebeccaWPerry/python_seam_carving
/seamcarving.py
4,254
3.515625
4
""" Seam carving functions Written for seam carving workshop -- functions to find and remove vertical seams. author: Rebecca Perry """ import random import numpy as np def findseam(image): """Find a seam running from top to bottom of image image: color or grayscale image to remove seam from """ ...
b6514e18096633b3f6c214d6ba4b3c12f897d423
yaswanthsaivendra/automation-scripts
/Youtube_downloader/youtube_downloader.py
591
3.671875
4
from pytube import YouTube url = input("Enter the url of the video: ") print("Fetching video info....") try: yt = YouTube(url) print("Video Title: ", yt.title) you = yt.streams.filter(progressive=True) for i in range(len(you)): print(str(i)+". " + str(you[i])) except : print(f"Error while...
322756d17f96d9e9c530023d3286ea0686937f0f
RafaD0507/hw9
/RafaelSanabria_GenerarTiempos.py
463
3.78125
4
import time def fibonacci(N): #Retorna el N esimo numero de Fibonacci if(N== 0 or N==1): return N else: return fibonacci(N-2)+fibonacci(N-1) def get_time(N): #Retorna el tiempo que se demora en calcular el N esimo numero de fibonacci t0 = time.time() fibonacci(N) t1 = time....
5b7f40cc69402346f9a029c07246da2286022c7f
Vk686/week4
/hello.py
212
4.28125
4
tempName = "Hello <<UserName>>, How are you?" username = input("Enter User Name: ") if len(username) < 5: print("User Name must have 5 characters.") else: print(tempName.replace("<<UserName>>",username))
3d0f9ecc15abdcabd8867979cdb34dc08232ee7e
astropy/specutils
/specutils/spectra/spectral_region.py
11,072
3.578125
4
import itertools import sys import astropy.units as u class SpectralRegion: """ A `SpectralRegion` is a container class for regions (intervals) along a spectral coordinate. This class can either represent a single contiguous region or a set of regions related to each other in some way (For examp...
5e55aa98b35fdc538ceac837616920e8e0c7d0ee
creator-krixus/Api-python
/database/tasks.py
2,701
3.5625
4
import sqlite3 from sqlite3 import Error from sqlite3.dbapi2 import Cursor from .connection import create_connection def insert_task(data): conn = create_connection() sql = """ INSERT INTO tasks(title, created_date) VALUES(?, ?) """ try: cur = conn.cursor() cur.execute(sql...
1596d1d1e7ef22f858dad005741768c7887a5a0e
wardragon2096/Week-2
/Ch.3 Project1.1.py
296
4.28125
4
side1=input("Enter the first side of the triangle: ") side2=input("Enter the second side of the triangle: ") side3=input("Enter the thrid side of the triangle: ") if side1==side2==side3: print("This is an equilateral triangle.") else: print("This is not an equilateral triangle.")
8161b0066578055b529048d15154b5f9809ecb6f
rl-opt/rlopt
/src/functions/core.py
603
3.84375
4
"""Classes base para todas funções.""" import abc import typing class Domain(typing.NamedTuple): min: float max: float class Function: """Classe base para todas funções.""" def __init__(self, domain: Domain): assert domain is not None self._domain = domain @abc.abstractmethod def __call__(self...
0a434671903297138a049ab85719937bba7e50e3
LucianoPAlmeida/python-lessons
/turtle-mini-project.py
614
3.890625
4
import turtle import math def draw_shape(angle): brad = turtle.Turtle() brad.shape("circle") brad.color("white") brad.right(angle) brad.speed(200) for i in range(2): brad.right(120) brad.forward(60) brad.right(60) brad.forward(60) def draw_flower(): for i in ...
a3c023f6b405bb6c65fd061c4cafbda6fc6f65a9
AlexBikbaeva/emojic-bot
/SQLite_database.py
1,724
3.53125
4
import sqlite3 def sqlite_database(): try: conn = sqlite3.connect("emojic_database.db") cur = conn.cursor() print("Connected to SQLite") cur.executescript("\ PRAGMA foreign_keys=on;\ CREATE TABLE IF NOT EXISTS messages(\ ...
49d0e1cc17cc3e0e12468b590bf8cd48b2732cf9
maples1993/LeetCode
/q3.py
891
3.640625
4
""" Date: 2018/9/8 """ class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ if len(s) < 2: return len(s) head = 0 tail = 1 char_dict = {s[head]: 1} max_len = 1 cur_len = 1 ...
bf68a9b1d6a53bde7ff1f916e9b350e5a1a29421
maples1993/LeetCode
/q20.py
760
3.84375
4
""" Date: 2018/8/16 """ class Solution: def isValid(self, s): """ :type s: str :rtype: bool """ left_par = [] for c in s: if c in ['(', '{', '[']: left_par.append(c) if c == ')' and len(left_par) > 0 and left_par[-1] == '(': ...
287a7a11e520eca59414025148512fb48d0e5332
maples1993/LeetCode
/q9.py
571
3.984375
4
""" Date: 2018/8/15 如果直接翻转可能会遇到数值溢出的问题 因此可以只翻转一半 """ class Solution: def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x < 0 or x != 0 and x % 1 == 0: return False x_old = x x_new = 0 while x_old > x_new: x_new =...
88f6eb723ce37681e26229f67d488230b606be26
maples1993/LeetCode
/q100.py
899
3.859375
4
""" Date: 2018/8/19 判断左右子树是否一样,转化为递归 """ class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ if p an...