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
1f4d2489bcfa31d9c1d3b2e82828c1533fac81d2
MarvvanPal/foundations-sample-website
/covid_full_stack_app/covid_full_stack_app/controllers/database_helpers.py
2,107
4.65625
5
# connect to the database and run some SQL # import the python library for SQLite import sqlite3 # this function will connect you to the database. It will return a tuple # with two elements: # - a "connection" object, which will be necessary to later close the database # - a "cursor" object, which will neccesary t...
88d6c8c24f08d39416cd5d48061058af5a4d6746
Xavitron/Francisco-Xavier-Intro-to-CP-_
/main1.py
4,352
3.984375
4
#My project is going to be something similar to the game lightbikes from tron the movie #My first major milestone, is to set the boundaries of the area were the bikes run in #I do not know how to insert images in python, I know we have learned how to do it, but I forgot about them #I do not think my project is too a...
ff4de9e946d194b65eaf47329ec181c979bac507
arwayzhang/Hadoop_photo
/task1/reduceside_join_reducer.py
1,675
3.5
4
#!/usr/bin/python3 import sys def read_map_output(file): """ Return an iterator for key, value pair extracted from file (sys.stdin). Input format: key \t value Output format: (key, value) """ for line in file: yield line.strip().split("\t", 1) def associate_country(): """ This redu...
7e603d0a3d96c50104630187b700ccab8cf035d7
hemang249/py-cheatsheet
/conditions.py
479
4.15625
4
# Common Conditional Statements used in Python 3 # Basic if-else Condition x = 5 if x == 5: print("x = 5") else: print("x != 5") # Basic Logical operations # and or not a = 0 b = 1 boolean = False if a == 0 and b == 1: print("a = 0 and b = 1") if a == 0 or b == 1: print("Either a = 0 or b = 1")...
3c79d2b1edfad2f6536f17ea087eacdb62b9a5d0
Groot-Space/Bad_Comment_Dtection
/Bidirectional_LSTM/refinecomments.py
612
3.5
4
''' 뉴스 댓글을 크롤링한 데이터 중 90글자가 넘어가는 댓글을 제거처리 하는 기능. ''' def read_data(filename): maxlen = 90 result = open('refinedcomments.txt', 'a', encoding = 'utf-8') datas = [] f = open(filename, 'r', encoding = 'utf-8') while True: line = f.readline() if not line: break ...
8da97d6a35a36f5168e3f128e61c2aca4618f675
javiermontenegro/Python_Design.Patterns
/Creational/FactoryPattern.py
878
3.78125
4
#******************************************************************** # Filename: FactoryPattern.py # Author: Javier Montenegro (https://javiermontenegro.github.io/) # Copyright: # Details: This code is the implementation of the factory pattern. #*******************************************************************...
9e8ec70ffecce773f9cfeab47f4f7ff74cc88b43
javiermontenegro/Python_Design.Patterns
/Structural/ProxyPattern.py
1,481
3.921875
4
#******************************************************************** # Filename: ProxyPattern.py # Author: Javier Montenegro (https://javiermontenegro.github.io/) # Copyright: # Details: This code is the implementation of the proxy pattern. #********************************************************************* ...
4c1f8ab06127e3c46c2bf968f764f2fd4fc90b89
matheusyhwh/Lab4
/lab_mem/page_replacement/python/algorithms/aging.py
1,275
3.6875
4
# This is the file where you must implement the Aging algorithm # This file will be imported from the main code. The PhysicalMemory class # will be instantiated with the algorithm received from the input. You may edit # this file as you whish # NOTE: there may be methods you don't need to modify, you must decid...
99e1949ecf3f1d3119ca5c9586e83a550bb0d864
sajal1302/Coursera-python-courses
/python to acess webdata/week5/assignment/asg.py
348
3.53125
4
import urllib import xml.etree.ElementTree as ET url = input("Enter - ") uh = urllib.request.urlopen(url) data = uh.read() tree = ET.fromstring(data) results = tree.findall('comments/comment') count =0 sum=0 for item in results: x = int(item.find('count').text) count =count+1 sum = sum+x print ("Count : "...
b93af29f5ac53e1f82f5967446b79b4f86cdd933
nacardo/Snake
/snake.py
3,537
3.5625
4
import copy import pygame class Snake(object): def __init__(self, game): self.x = .5 * game.game_width self.y = .5 * game.game_width self.vel_x = 1 self.vel_y = 0 self.position = [] self.position.append([self.x, self.y]) self.snake_length = len(self.position)...
0fa0e75cacaf152fc75e10c493a9ebd2cc4800cc
love525150/leetcode-answer
/test.py
2,194
3.828125
4
''' 给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。 ''' # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def kthSmallest(self, root, k): """ :type root: TreeNode :type k: int...
61db258222a70207052c4d31548a8a14875f00fa
love525150/leetcode-answer
/a3.py
900
3.6875
4
''' 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 ''' ''' 核心: 1. 滑动窗口 问题: slide_window.find(cur)效率比较低,可以换成HashTable,因为这个字符串slide_window是不含重复字符的 ''' class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ if len(s) == 0: return 0 ...
967bba068c37fab983e154c7e39cb2c1126d44e5
love525150/leetcode-answer
/a118.py
895
3.890625
4
''' 给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。 在杨辉三角中,每个数是它左上方和右上方的数的和。 ''' class Solution: def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ if numRows == 0: return [] if numRows == 1: return [[1]] if numRows =...
21b559f251f9dda419d1bbf14f8152b83bfd4771
love525150/leetcode-answer
/ByteDance/str5.py
777
3.875
4
''' 给定一个字符串,逐个翻转字符串中的每个单词。 示例 1: 输入: "the sky is blue" 输出: "blue is sky the" 思路:栈 ''' class Solution: def reverseWords(self, s: str) -> str: stack = [] r = "" for i in range(len(s) - 1, -1, -1): if s[i] == " ": if len(stack) == 0: continue ...
eb72aef51f6ae64bd1ad27b592f0428db843e6bd
love525150/leetcode-answer
/a922.py
1,434
3.59375
4
''' 给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。 对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。 你可以返回任何满足上述条件的数组作为答案。 ''' ''' 解题思路:遍历一遍原数组,找到所有不合适的值,不合适分为两类:奇数不合和偶数不合,然后两类不合交换,这样是额外空间消耗比较少的方案;(第一次做的时候奇数不合跟奇数不合交换导致出错了。。) 如果不考虑额外空间,可以遍历的时候把值放进另一个数组,奇数放奇数索引,偶数放偶数索引 ''' class Solution: def sortArrayByParityII(self, A): ...
13cda4727a9429d818e92e71fedcf10fc5fa7d3b
samturton2/Python_sql_movies_task
/main.py
4,432
3.765625
4
# Import pyodbc to connect with SQL import pyodbc # import csv to help read the csv file import csv #create class that can export data from csv file class MoviesDatabase: # get a connection to the northwind database def __init__(self, username, password): self.username = username self.password ...
b177215bbc7d7ebf8d6b0e22761fa3b2859eb623
arahansa/learn_ml_bottom
/ml/03_신경망/01_신경망함수.py
281
3.65625
4
import numpy as np # def step_function(x): # if x>0: # return 1 # else: # return 0 def step_function(x): y = x > 0 return y.astype(np.int) x = np.array([-1.0, 1.0, 2.0]) print("x", x) y = x > 0 print("y", y) y = y.astype(np.int) print("y", y)
5f6e0fb0ab97ea396162edc4a260aee85d24bcbf
lzc1017/lzc
/py/ex2.py
451
3.859375
4
print "I have some chickens",5+3 print "hens",5 print "roosters",3 print "Do I have more hens than roosters ?",5>3 print "Do I have no less than 2 roosters?",3>=2 print import numpy as np print 3.14*6378*2 print np.pi*6378*2 print 7/4 print 7/4.0 print cars=100 drivers=30 passengers=90 print "There are",cars,"cars av...
6dea2f8d8f2ae2804961d80bc0c224a174d4694b
zihu/job_interview_code
/lcs.py
866
4.1875
4
#!/usr/bin/python def lcs(xs, ys): '''Return a longest common subsequence of xs and ys. Example >>> lcs("HUMAN", "CHIMPANZEE") ['H', 'M', 'A', 'N'] ''' if xs and ys: xb = xs[:-1] yb = ys[:-1] if xs[-1] == ys[-1]: return lcs(xb, yb) + [xs[-1]] else: return max(lcs(xs, yb...
98fda7967aac2792f45d68a36825d1c78e7ebc01
aieml/Week-02
/Codes/2.0 Linear Regression for non linear data.py
690
3.5
4
import numpy as np from matplotlib import pyplot as plt x=np.arange(-10,11,1) x=x[:,np.newaxis] y=2*(x**2)+3*x plt.plot(x,y,'r') ye=[] for i in y: ye.append(i+np.random.randint(-5,5)) ye=np.array(ye) #plt.plot(x,y,'r') plt.scatter(x,ye) from sklearn.linear_model import LinearRegressi...
8ad114e4e5f63a56c8d560f60d05e19dcd77ee42
KimberleyLawrence/python
/for_loop_even_numbers.py
245
4.1875
4
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] for number in a: # % 2 == 0 is dividing the number by 2, and seeing if there is any remainders, any remainders mean that the number is not even. if number % 2 == 0: print number
0e29861cf101d1c51fc42e336cfc15b6b32e40c7
KimberleyLawrence/python
/for.py
435
4.09375
4
start_list = [5, 3, 1, 2, 4] square_list = [] #create a variable for each item in the start_list for number in start_list: #need to create a variable for the variable you wish to put an operator ** on. square = number**2 #then append the square_list to include the square variable results square_lis...
3e9d1139f676f59190ba29b1007ddd8023af962f
KimberleyLawrence/python
/conditionalreview.py
415
3.984375
4
# Make sure that the_flying_circus() returns True def the_flying_circus(): if 2 <= 2: print "if worked" # Start coding here! # Don't forget to indent # the code inside this block! elif not False : print "elif worked" # Keep going here. # You'll want ...
0233ab09eea58933b2911a7f24b558653eadce76
KimberleyLawrence/python
/dotnotation.py
182
3.78125
4
ministry = "The Ministry of Silly Walks" print len(ministry) print ministry.upper() #dot notation ".upper()" only work with strings. The "len() and str() work with other data types.
62f9f087f6c704c0a9a38d9bc8a41630ea1ffcc2
Son-Guhun/Titan-Land-Lands-of-Plenty
/_scripts/objecteditor/model/search.py
1,299
3.609375
4
def get_substrings(string): "Returns all possible substrings of a string." return [string[i: j] for i in range(len(string)) for j in range(i + 1, len(string) + 1)] def map_substrings(deco_names): """ Returns a map of (substrings)->(rawcodes), i.e. a map from each substring to all units w...
7e132de17b4860984232764a5db60faa452f3341
Kthanasis/Python
/CharacterCount/charactercount.py
625
4.03125
4
import pprint message='This is the text we will use as an example. We can use any text, no matter the size!' count={} for character in message.upper(): #we car remove .upper() so it can distinct between #Uppercase and Lowercase count.setdefault(character,0) #this helps to avoid ex...
b17dabd0cb87879b1234e24acced508e1519f287
warda176/TSF-TASK-1
/TSF-TASK1.py
3,140
4
4
#!/usr/bin/env python # coding: utf-8 # # WARDA RAEES # # GRIP TASK 1 # # Prediction using Supervised ML # Task statement - Predict the percentage of an student based on the no. of study hours. # ### Simple Linear Regression With Python scikit learn # Simple linear regression is used to estimate the relationship ...
f22e9421ef5ab41d29ad5e4cc6f6b62484365f49
robertorreis/jogos-python
/jogoaventura.py
6,367
3.921875
4
def jogar(): imprime_abertura() esplic_jogo() um_pergunta = pergunta_um() while um_pergunta <1 or um_pergunta >3: print("ESSA OPÇÃO NÃO EXISTE!!") um_pergunta = pergunta_um() if(um_pergunta == 1): print("Você é um festeiro então e gosta da bagunça!!") dois_um = per...
202d119889eeaeeeaba5ee21ad6368d259c3c4ff
griffs37/CA_116
/highest-number.py
117
3.578125
4
#!/usr/bin/env python total = 0 i = 0 while i < 6: n = input() if n > total: total = n i = i + 1 print total
ac406abf46b1dda63eec810b32380dfd3e682287
Zakaria-ElGhoul/Bewijzenmap
/Python Projecten/main9.py
984
3.75
4
import random i = 0 # def = functie def schudKaarten(): #list van alle strings speelKaart = ["Harten", "Schoppen", "Klaveren", "Ruiten"] waardes = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Boer", "Dishwasher", "Heer", "Aas"] #hier maak ik een random integer aan, lists geven elke keer ...
a738e5e7e06ed38b302ec311a30fb631bad261c1
hariharan13/Sentiment_analysis
/Sentiment_analysis.py
2,294
3.53125
4
#import all libraries needed for performing sentiment analysis import nltk import nltk.sentiment.util import nltk.sentiment.sentiment_analyzer from nltk.sentiment.vader import SentimentIntensityAnalyzer def mySentimentAnalyzer(): #This instruction defines a new subfunction, score_feedback(), which takes a sentence as i...
efd2607c2b56baeb6866395321d6e2c5906c8b9b
lucasarieiv/Livro-Exercicio-Python
/collatz.py
352
4.15625
4
def collatz(number): if number % 2 == 0: v1 = number // 2 print(v1) return v1 elif number % 2 == 1: v2 = 3 * number + 1 print(v2) return v2 print('Enter number. ') num = input() try: collatz(int(num)) except ValueError: pr...
38da766fd7adc410bf9f1646533560e5db66b677
EdwinTriMaulana/Mini-Program-By-Edwin-Tri-Maulana
/edwin tri maulana_2028.py
633
3.734375
4
import random angka_random=random.randrange(1,21) #random angka dari 1-20 while True : print("=== Tebak Angka ===") inputan = int(input("Coba Tebak Angkanya (1-20): ")) #user menginputkan angka 1-20 if inputan == angka_random : #jika inputan==angka_random maka step ini akan dijalankan print("Se...
b77ce8846b989cc21b456b63e4af01e58a92b6e9
PolishDom/COM411
/basics/functions/boulder.py
276
3.765625
4
def boulder(): see = input("Can you see a large boulder or nothing?") if see == "a large boulder": print ("Its time to run!") elif see == ("nothing"): print("We will be fine") else: print("you have misentered the statement") boulder() print ("finish")
b1a7a57ec0c9b45ea64a0d85257b5d9be5f05c45
PolishDom/COM411
/basics/lists/simplelists.py
239
3.890625
4
#this is a list fruits = [] #adding to a list fruits = ["apple", "banana", "cherry"] #adding item to end of list using append fruits.append("dragon fruit") #remove the first showup of this item in the list fruits.remove("dragon fruit")
ca24e36fe9ec0b18c43ba2012e67bf81752bf416
PolishDom/COM411
/basics/plots/task25.3.py
515
3.84375
4
import matplotlib.pyplot as plt def coordinate(): xvalue = input("Please enter a x value") yvalue = input("Please enter a Y value") x_and_y_values = (xvalue , yvalue) return x_and_y_values def path(): print ("Retrieving path...") x_values = [] y_values = [] x = range(4) for i in x: data = coordi...
5b38eecd47ce16ab45f8312debf8f1b7fad26b8d
PolishDom/COM411
/basics/functions/sounds.py
177
3.609375
4
def loudsound(): sound = input("What word would you describe the sound?") print ("What did you just hear?") print (sound) print("That was a loud",sound) loudsound()
ad5a3490d346783cc90737b116af3fedf7a4fb0e
kjh618/problem-solving
/Baekjoon/2504.py
852
3.765625
4
def sum_pop_to(stack, bracket): sum = 0 while True: if len(stack) == 0: return None elem = stack.pop() if isinstance(elem, str): if elem == bracket: return sum else: return None else: sum += elem br...
eb98c1cdf044f3ee1b997fa63e99181c533d1cc7
BrunoFNRodrigues/ProjetoCraps
/Jogo.py
8,221
3.53125
4
# -*- coding: utf-8 -*- """ Created on Sun Mar 29 19:32:38 2020 @author: bru_b """ #Inicio do Jogo print('Bem vindo(a) ao Kassinão!') print('Já que é a sua primeira vez toma aí 1000 fichas') print('Bora jogar Craps') #Variaveis ficha=1000 Pass_Line_Bet=False Field=False Any_Craps=False Twelve=False Point=False a...
9e9c867934f22ce34c5c45b92f480a69dc5f89e7
vivaan1304/rude-words-bleeper
/main.py
1,252
3.609375
4
import string rude_words = open("list_of_words.txt").read().split("\n") def bleeped(s): return "".join(len(s) * '*') def is_rude(s): s = s.strip(string.punctuation).lower() if s in rude_words: return 1 return 0 def count_rude_words(s): count = 0 words = s.split(" ") words[-1] = wo...
21792e8994608b50851edf7c8836b78e7ea60270
jadna/MATE73-IA
/Buscas/dfs.py
1,128
3.6875
4
from collections import defaultdict def __dfs(graph, node, goal, visitados): if node == goal: return [node] if node in graph: for neighbor in graph[node]: if neighbor not in visitados: visitados.append( neighbor ) path = __dfs(gr...
8482bab6c58f3bd830bb05855b0306fb405ffb2d
obgob/Empire
/Debug.py
345
3.578125
4
# File has up to ten debug levels. High debug = low number # SETS THE CURRENT DEBUG LEVEL DEBUG_LEVEL = 10 # DEBUG LEVELS DEBUG_LEVEL_HIGH = 1 DEBUG_LEVEL_MEDIUM = 5 DEBUG_LEVEL_LOW = 10 # Debug Function # Call with printable object and integer level def debug(message, debug_level): if debug_level <= DEBUG_LEVE...
37e9fa37ff5e6cc968b0031e802538c1c902ad9c
Kristy16s/Think-Python-2-Exercises-By-Chapter
/2.1 Exercises.py
1,285
4.4375
4
# 2.10 Exercises # Date 8/4/2021 """ Exercise 1 Repeating my advice from the previous chapter, whenever you learn a new feature, you should try it out in interactive mode and make errors on purpose to see what goes wrong. """ # We’ve seen that n = 42 is legal. What about 42 = n? # 42 = n """ File "<input>", line 1 ...
1a82f0c10a6dcc9dea24b99478f225aba679bfbf
DylanXie123/Data-Structures-and-Algorithm-in-Python
/chapter5/binarySearch.py
363
3.859375
4
def binarySearch(alist, item): found = False subList = alist while len(subList) > 0 and not found: length = len(subList) mid = length // 2 if subList[mid] > item: subList = subList[:mid] elif subList[mid] < item: subList = subList[mid+1:] else:...
61a45ab82e6732eca42759353b4ee2775f275171
karan-jagtap/udemy-python-course
/Section-8/functions.py
241
4.0625
4
def add(x=0, y=0): return x + y print(add(4, 6)) # -- getting user input a = int(input('Enter Num1 : ')) b = int(input('Enter Num2 : ')) print(add(a, b)) # -- uses default values if no arguments are passed print(add()) print(add(5))
41228a26ab53da47dabc59d4d0414c23e806d902
shanksms/python_cookbook
/iterators-generators/generator-examples.py
1,272
4.6875
5
""" Here’s a generator that produces a range of floating-point numbers. Below function returns a generator object. A generator object is also an iterator. an Iterator is an Iterable. That is why you can use it in while loop. """ def frange(start, stop, increment): i = start while i < stop: yield i ...
18409b27c329453b23ce6e306a536c0f539778f2
shanksms/python_cookbook
/iterators-generators/index_value_pair.py
695
3.90625
4
""" You want to iterate over a sequence, but would like to keep track of which element of the sequence is currently being processed """ from collections import defaultdict def enumerate_example(my_list): for index, value in enumerate(my_list): print(index, value) def word_summary(): word_dict = defau...
5870f9e21e64935c82a8919c8079c7a274cfbb3f
emma-rose22/cs-module-project-algorithms
/eating_cookies/eating_cookies.py
2,474
4.0625
4
''' Input: an integer Returns: an integer ''' import time def eating_cookies(n): ''' this method is inefficient because there is repeated work you are repeatedly making the same decision that with one cookie, you can only eat one cookie every time we get to the end of a stack what if we could save...
1bcef5fc6242843ac3f5f8ffe172ec8070909e16
Shivanand212355/CVL757_2021
/Assignment_1/2021CES2355.py
5,916
3.953125
4
Input = [12, 35, 9, 56, 24] def reverse_list(l): return l[::-1] print(f"Reverse List is : {reverse_list(Input)}") l =[1, 2, 3, 4, 5, 6, 7, 8] p1 = 3 p2 = 5 def swapFunc(l,p1,p2): l[p1], l[p2] = l[p2], l[p1] return l print(f"Swapped List is : {swapFunc(l,(p1-1),(p2-1))}") s = "CVL756" def reverse_string...
f39e785e234341b15b08e905489681131a8aa17c
archelaus/GFG-solutions
/Armstrong Numbers/arm.py
260
3.609375
4
class Solution: def armstrongNumber (ob, n): temp = n res = 0 while n > 0: r = n % 10 res += r ** 3 n //= 10 if res == temp: return "Yes" else: return "No"
d5173af56eb88c701126a8d4bd92e27d82969277
ssummun54/wofford_cosc_projects
/350 Projects/DuplicateFileFinder.py
1,519
3.609375
4
import sys import os __author__ = 'Sergio Sum Munoz' def magic(directory): file_dictionary = {} for dir_path, dir_name, file_name in os.walk(directory): for file in file_name: file_path = os.path.join(dir_path, file) file_size = os.path.getsize(file_path) ...
e76d54bbee13c9a8fa05cb97285f229db9715c98
ssummun54/wofford_cosc_projects
/Assignments/sphere.py
390
3.609375
4
# sphere.py # This program contains the sphere class. # A program by Sergio Sum # 5/5/17 from math import * class Sphere: def __init__(self, radius): self.radius = radius def getRadius(self): return self.radius def surfaceArea(self): return 4 * pi * self.radi...
40a0f176eba2fed30a0c5ed96d9ee6fbe654a70a
ssummun54/wofford_cosc_projects
/Assignments/8and10.py
1,719
4.15625
4
# 8and10.py # This progam runs two functions. The first function uss Newton's Method to find the # square root of a number. The second function creates an acronym based on the phrase # given by the user. #importing math for square root from math import * #function for problem 8 def nextGuess(guess, ne...
d92640d7336759a48656c7df4bd333ceecca69aa
ssummun54/wofford_cosc_projects
/Assignments/numerology.py
615
4.4375
4
# numerology.py # This program sums up the Unicode values of the user's full name and displays the corresponding Unicode character # A program by Sergio Sum # 3/24/17 def main(): name = input("Please enter your full name: ") # not counting spaces by turning to list name = name.split() #j...
9e184f3ca75229ac2bcacd258327c97b98010d80
sharababy/icg
/b_circle.py
1,128
3.90625
4
# Assignment 3 , Submission by Vedant Bassi , Ced15i013 # Draw a straight line using Bresenham's Circle Algorithm import sys, pygame pygame.init() pygame.font.init() size = width, height = 530, 500 bgcolor = 255, 255, 255 color = (0,0,0) screen = pygame.display.set_mode(size) surf=pygame.display.get_surface() sc...
2683ba780038948e570a0f19d7fff9517e3c4328
rv404674/Learn-Python3-the-Hard-Way
/ch5.py
524
4
4
my_age = 20 #not a lie my_name = "Rahul Verma" my_height = 80 my_weight = 50 my_eyes = "Brown" my_teeth = "ywllow" my_hair = 'Brown' print(f"Let's talk about {my_name}") print(f"I am {my_age} years old") print(f"My height is {my_height} weight is {my_weight}") print("Actually that's too light") print(f"He's got {my_...
84d83930d17d99491111d7a79baa08e790ddadd3
MateiSirbu/IDS_Sirbu_Tataru
/Laborator2/Ex5.py
825
3.6875
4
import numpy as np def indices(a:np.array, b:np.array) -> tuple: """ Identifică o pereche de indici i, j pentru care a[i][j] > b[i][j]. Parameters ---------- a : np.array, b : np.array Cele două matrici ale căror elemente se vor compara. Returns ------- tuple: O perech...
697d70fece9f54228225c991b37d38dd26a1080f
dexterchan/DailyChallenge
/Practise/tests/test_linked_list.py
1,664
3.96875
4
from linkedlist import (DblLinkedList, Node) def test_insert_linked_list(): dbl_list:DblLinkedList = DblLinkedList() dbl_list.append(1) dbl_list.append(2) dbl_list.append(3) #print(l._head) for i,v in enumerate(dbl_list): assert v.data == i+1, f"v.data: {v.data} != {i+1}" n = dbl_...
1c76d85eebcb7b87d6fdb7b0d4cbe7f7f7b87262
dexterchan/DailyChallenge
/APR2020/SplitaBinarySearchTree.py
3,180
3.984375
4
#Given a binary search tree (BST) and a value s, split the BST into 2 trees, # where one tree has all values less than or equal to s, # and the other tree has all values greater than s while maintaining # the tree structure of the original BST. # You can assume that s will be one of the node's value in the BST. Return...
9cfef1268648f1a5fdbabec4776d900793dd8a77
dexterchan/DailyChallenge
/Jan2020/LongestConsecutiveSequence.py
3,183
3.921875
4
#You are given an array of integers. Return the length of the longest consecutive elements sequence in the array. #For example, the input array [100, 4, 200, 1, 3, 2] has the longest consecutive sequence 1, 2, 3, 4, and thus, you should return its length, 4. #Can you do this in linear time? #Anaysis #Sorting costs O(...
82e411e00fe08ff6d1e4aafd71c8fbb58eb3d34c
dexterchan/DailyChallenge
/NOV2019/RemoveConsecutiveNodesthatSumto0.py
2,169
3.78125
4
#Given a linked list of integers, remove all consecutive nodes that sum up to 0. #Example: #Input: 10 -> 5 -> -3 -> -3 -> 1 -> 4 -> -4 #Output: 10 #The consecutive nodes 5 -> -3 -> -3 -> 1 sums up to 0 so that sequence should be removed. # 4 -> -4 also sums up to 0 too so that sequence should also be removed. class...
36e28ff17f67661ffe1e3807abfad54a110c8ef9
dexterchan/DailyChallenge
/FEB2020/NumberofCousins.py
2,902
3.78125
4
#Given a binary tree and a given node value, # return all of the node's cousins. # Two nodes are considered cousins if they are on the same level of the tree with different parents. # You can assume that all nodes will have their own unique value. #Here's some starter code: #Analysis # a custom data struct of Map # ...
5cb4c21bb4a89a17a4498bb0c5e1274687a69bcc
dexterchan/DailyChallenge
/DEC2019/TrappingRainwater.py
1,514
3.734375
4
#Skills: array iteration #You have a landscape, in which puddles can form. You are given an array of non-negative integers representing the elevation at each location. Return the amount of water that would accumulate if it rains. #For example: [0,1,0,2,1,0,1,3,2,1,2,1] should return 6 because 6 units of water can get...
3ed869277d2d7958bc4d4012434c826f03e88eaf
dexterchan/DailyChallenge
/MAR2020/ScheduleTasks.py
648
4.1875
4
#A task is a some work to be done which can be assumed takes 1 unit of time. # Between the same type of tasks you must take at least n units of time before running the same tasks again. #Given a list of tasks (each task will be represented by a string), # and a positive integer n representing the time it takes to ru...
d6d4cc0dae2f1a1fc7a650798ee6dad83d6b57ed
dexterchan/DailyChallenge
/NOV2019/WordSearch.py
2,069
4.15625
4
#skills: array traversal #You are given a 2D array of characters, and a target string. Return whether or not the word target word exists in the matrix. # Unlike a standard word search, the word must be either going left-to-right, or top-to-bottom in the matrix. #Example: #[['F', 'A', 'C', 'I'], # ['O', 'B', 'Q', 'P']...
5b107d1cde1f64e089082f62a64366c48d94ab31
dexterchan/DailyChallenge
/NOV2019/TwoSum.py
1,075
3.734375
4
#Skill: hash set #Given [4, 7, 1 , -3, 2] and k = 5, #return true since 4 + 1 = 5. def two_sum_HashSet(list, k): memory = set() for i in (list): if(i in memory ): return True wantedNum = k - i memory.add(wantedNum) return False #O(N) def two_sum (list, k): m_siz...
e76e31b3bce987ce0ed9b4a39f29ad6eb1221d92
dexterchan/DailyChallenge
/MAR2020/FilterBinaryTreeLeaves.py
2,112
4.15625
4
#Hi, here's your problem today. This problem was recently asked by Twitter: #Given a binary tree and an integer k, filter the binary tree such that its leaves don't contain the value k. Here are the rules: #- If a leaf node has a value of k, remove it. #- If a parent node has a value of k, and all of its children are...
5dda83f2be9b2a8a87c459d3ba1dfe867633e9a2
dexterchan/DailyChallenge
/MAR2020/PhoneNumbers.py
2,568
3.9375
4
#Skill: Tries #Difficulty : EASY #Given a phone number, return all valid words that can be created using that phone number. #For instance, given the phone number 364 #we can construct the words ['dog', 'fog']. #Here's a starting point: #Analysis #If done by brutal force, time cost is exponent to find all possibiltie...
05709484403ab348a2acc256c6e4d64d7f3d7306
dexterchan/DailyChallenge
/Jan2020/MaxandMinwithLimitedComparisons.py
1,594
4.09375
4
#Given a list of numbers of size n, where n is greater than 3, # find the maximum and minimum of the list using less than 2 * (n - 1) comparisons. #Here's a start: #Analysis #Exploit the property of N>3 #for first 3 element, we can do 3-4 comparison to find the max and min numbers: # A compare to B.... if A is large...
b69780d2a5c6373ec9b6dd42270c45eb2e09c481
dexterchan/DailyChallenge
/DEC2019/LargestBSTinaBinaryTree.py
3,226
4.03125
4
#Skill: Binary Search Tree #You are given the root of a binary tree. Find and return the largest subtree of that tree, which is a valid binary search tree. #Assume a BST is defined as follows: # The left subtree of a node contains only nodes with keys less than the node's key. # The right subtree of a node con...
c9abe5a637e8dbb353af6096239b6bbc9efea72a
dexterchan/DailyChallenge
/OCT2019/findLongestSubStringWithRepeatedCharacters.py
1,843
3.5
4
#Given a string, find the length of the longest substring without repeating characters. from functools import reduce class Solution2: CHAR_MAP_SIZE = 256 def addr(self, chr): return ord(chr)#-97 def lengthOfLongestSubstring(self, s): # Fill this in. r = self.LinearShortestLength(s)...
526c7de44a6b661bf2ebd8545dcf50117f5b34e9
dexterchan/DailyChallenge
/FEB2020/Unicode8Validator.py
2,100
3.828125
4
#SKill : array iteration #A UTF-8 character encoding is a variable width character encoding # that can vary from 1 to 4 bytes depending on the character. The structure of the encoding is as follows: #1 byte: 0xxxxxxx #2 bytes: 110xxxxx 10xxxxxx #3 bytes: 1110xxxx 10xxxxxx 10xxxxxx #4 bytes: 11110xxx 10xxxxxx 10xxxxxx ...
068bcb535e90c9a0d8f6aeb7b4a48160883b6d4f
dexterchan/DailyChallenge
/MAR2020/FindSubtree.py
2,594
3.859375
4
#Given 2 binary trees t and s, find if s has an equal subtree in t, # where the structure and the values are the same. Return True if it exists, otherwise return False. #Here's some starter code and an example: #Analysis: #extract the schema from a tree by BFT #using recursive function coder #each node, we code the s...
133ee747cc2143381788b7c01050e500feca3463
dexterchan/DailyChallenge
/FEB2020/CompareVersionNumbers.py
3,611
4.375
4
#Skill: regex #Version numbers are strings that are used to identify unique states of software products. A version number is in the format a.b.c.d. and so on where a, b, etc. are numeric strings separated by dots. These generally represent a hierarchy from major to minor changes. Given two version numbers version1 and ...
2a7bca268a7ec6b71bad905e5280dabdf963d5da
DorgyFilho/Labyrinth-Enigma
/LabyrinthEnigma.py
4,395
4.09375
4
#Text-Game from time import sleep from random import randint def intro(): print() print('''A traveler is walking down the road to find his hometown. For this, he needs to cross the labyrinth that separates him from his goal. Soon, upon arriving, he finds two people near two entrances.''') sleep(3) ...
5d7b54b9a3d4872a11d3a8af4adaa6de31434594
lyhaha2020/NumericalAnalysis
/Python/PDE/Laplace_equation_2D.py
2,180
3.734375
4
# encoding: utf-8 """ Solving the 2-D Laplace's equation by the Finite Difference Method Numerical scheme used is a second order central difference in space (5-point difference) """ import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # global parameters nx = 60 ...
6b7f233a9e322ac4246a6f73dc6e4126b8910d4f
lyhaha2020/NumericalAnalysis
/Python/PDE/Laplace_2D_Jacobi_Dirichlet_Demo1.py
4,334
3.609375
4
# encoding: utf-8 r""" Solving the 2-D Laplace's equation by the Finite Difference Method Numerical scheme used is a second order central difference in space (5-point difference) PDE: u_xx + u_yy + \mu u = 0 \partial u / \partial \nu = g """ import numpy as np import matplotlib.pyplot as plt from mpl_tool...
bfab83d907abbe3445205f28bb01164aba51d428
saj96/shellexample
/read1.py
236
3.671875
4
file = open('names.txt', 'r') list_names = [] converted_list = [] for content in file.readlines(): list_names.append(content) for element in list_names: converted_list.append(element.strip()) print(converted_list) file.close()
724bc316223bd7c349b031db600f4cd8b0dcf0ee
joshua-ray-hoffman/Simple_Cal
/Simple_Cal.py
1,655
3.9375
4
import os while True: os.system('cls' if os.name == 'nt' else 'clear') print('===============================[Simple_Cal]===============================') InputString = str(input('Run a simple calculation (Yes or No)? : ')) if InputString == str('Yes'): NumberOne = int(input('Enter first num...
df7e09ad9f966cde4b3c8e5f746d5c066de15b93
claraj/national_parks
/get_nat_park_data.py
757
3.625
4
import requests import sqlite3 # Replace with Postgres from keys import keys # Create database, if it does not exist db = sqlite3.connect('db.sqlite3') all_parks_url = 'https://ridb.recreation.gov/api/v1/organizations/128/recareas.json' params = { 'apikey' : keys['RECREATION']} response = requests.get(all_parks_ur...
1825b43c91ba3b66da8b1dfd91c28d9b6ca09e82
Liambass/Python-challenges-exercises-and-tutorials
/Exercises/names#.py
282
4.0625
4
#Write a while loop which asks for the names of 5 people, and for each person prints their name followed by the text "is awesome!" names = [] for i in range(5): name = input("name " + str(i+1) +"? ") names.append(name) for name in names: print(name + " is awesome!")
191263c7a77e5aa8e5cfe1da776ab4f58dc1d849
Liambass/Python-challenges-exercises-and-tutorials
/Exercises/diceroll/diceroll.py
433
3.90625
4
# Create 2 new Python files. In one file, write a function that will generate a number between 1 and 6. Make this a module called dice. # In the second file, use the dice module to simulate throwing 2 dice and print the values you get from the dice. import random def diceroll(x): if x == 10: return random...
54d303d49e8e260e78b3509e332bbe733fb081ff
Liambass/Python-challenges-exercises-and-tutorials
/Exercises/intfloat.py
590
4.1875
4
# Integers and Floats # number1 = input("Enter whole number: ") # number2 = input("Enter decimal number: ") # integer_number = int(number1) # float_number = float(number2) # round_number = int(round(float_number)) # print(number1) # print(number2) # print(round_number) # What will be the output of this code? number...
23d33d1919c7106d14c202c0cacf4eacbc137d5f
oneryalcin/healthheroassignment
/solution1.py
439
4.0625
4
def my_func(lst: list) -> int: """Generator for cumulative sum of even integers Args: lst: (list) List of integers as input Returns: (int): Cumulative sum of even integers """ cum_sum = 0 for elem in lst: cum_sum += 0 if elem % 2 else elem yield cum_sum if __n...
2ea7d16b392e87f58bb97d39e40df65120963c28
JoseCintra/MathAlgorithms
/Algorithms/MatrixDeterminant.py
2,070
4.46875
4
""" Math Algorithms Name: MatrixDeterminant.py Purpose: Calculating the determinant of 3x3 matrices by the Sarrus rule Language: Python Author: José Cintra Year: 2021 Web Site: https://github.com/JoseCintra/MathAlgorithms License: Unlicense, described in http://unlicense.org...
0f0415355fd3bf46915294fdc522a9b957146cd0
jayd2446/NetChat
/users.py
1,260
3.84375
4
import sqlite3 conn = sqlite3.connect("users.db") cursor = conn.cursor() #cursor.execute("CREATE TABLE users (username text, password text, age text, sex text, name text)") def registerNewUser(username,password,age,sex,name): if(not (userExists(username))): cursor.execute("INSERT INTO users VALUES('"+usernam...
13ffd4dda03473021d445f649fbdce9b4df7a0e9
hyperfitz/ClassProjects
/BooksDatabaseProgram/app.py
1,029
3.953125
4
""" This program is a database program for storing books which can be marked as read or not read for the purpose of keeping track of what books I have and which of them I've read. This project was started on October 20, 2020. I completed this project on October 30, 2020. """ from BooksDatabaseProgram.utils import da...
820172896ee62184727ab20333225e6822807fca
pranjaj011/CEMC-CS-circles-exercises
/Chapter13/Palindrome.py
146
3.59375
4
def isPalindrome(S): a = len(S) for i in range(a//2): if S[i] != S[-1-i]: return(False) print(a//2) return(True)
1074e4977323cff8d2940edfa0ea3d7411fb6288
pranjaj011/CEMC-CS-circles-exercises
/Chapter09/Absolute Value.py
75
3.6875
4
x=int(input()) if x >= 0: x = x print(x) else: x = -x print(x)
d02d97fb24d715db26dfc9fdbbd2f9d9a6c34066
pranjaj011/CEMC-CS-circles-exercises
/Chapter07/Pizza Circles.py
69
3.765625
4
import math r = float(input()) pi = (math.pi) a = pi*(r**2) print(a)
c736cb30cbad5e6439e3690447b01a587c3f2d4a
pranjaj011/CEMC-CS-circles-exercises
/Chapter06/Timbits.py
563
3.765625
4
timbitsLeft = int(input()) # step 1: get the input totalCost = 0 # step 2: initialize the total cost if timbitsLeft >= 40: bigBoxes = int(timbitsLeft / 40) totalCost = totalCost + bigBoxes * 6.19 timbitsLeft = timbitsLeft - 40 * bigBoxes if timbitsLeft >= 20: totalCost = to...
d375110109d9762585ec2a9dacb40ea19065732c
YuchenShenUNH/python
/Assignment_3.py
3,053
3.828125
4
#---------------------------------------------------------# # Python Assignment 3 # # # # HOW MUCH OPERATION ON A DICTIONARY IS FASTER # # THAN OPERATION ON A SHELVE? # #-------------------...
e1a1323863efab71496e19de28fc0f1f9dbf9410
julesberhault/Machine-Learning
/TP3/lrCostGradient.py
1,302
3.828125
4
import numpy as np from sigmoid import sigmoid def h(theta, X): h = 0 h = sigmoid(X@theta) return h def lrCostGradient(theta, X, y, Lambda): """computes the gradient of the cost w.r.t. to the parameters theta for regularized logistic regression . """ # préambule m,n = X.shape # m = ...
7e58a06e5ad508b8d888218256f00a309bdbcd40
XuuRee/python-codecademy
/Unit 00/factorial_p3_mysol.py
331
4.15625
4
# factorial program using Python (my own solution) print("Factorial using Python 3 (my own solution)\n") number = eval(input("Enter a non-negative integer for factorial: ")) factorial = 1 for i in range(1,number + 1): # druha pozice = zadane cislo + jedna factorial = factorial * i print("Result: ",f...
c2ffdddf292da3a4fb5e7a66b27b664e52dadd48
pzavisliak/Python
/Circle/Math.py
1,376
4.125
4
import math print("Вычисление длины круга") def bugsa(): if a != "R" or a != "D": print("Нужно было ввести R или D , в следуйщий раз читай внимательнее") exit() a = input("С помощью чего ты хочешь найти длину? Радиус - R, Диаметр - D\n") bugsa() rad = "" diam = "" def bugsradius(): if rad ...
767834b7effd34056085a46b2cc116ab39d740df
meirelop/streaming-anomaly-detector
/geo/distance/base.py
258
3.671875
4
from geo.point import Point from abc import abstractmethod,ABC class Distance(ABC): @abstractmethod def distance(self,p1:Point,p2:Point)->float: pass @abstractmethod def squared_distance(self,p1:Point,p2:Point)->float: pass
dc7e8952ac64e03c719c5575d1bb305d204f0f1d
tanyaweaver/data-structures-2
/src/bst.py
11,772
3.9375
4
#!/usr/bin/env python # -*- coding: utf -8 -*- from __future__ import unicode_literals from collections import deque class Node(object): """Define class for a node of a binary search tree.""" def __init__(self, val, left=None, right=None, parent=None): """Create an instance of Node.""" self....
e72eab3e6e39c19631cf83632aee9090f5c75ef9
greggblenkinsop/football-dispossession-regression-analysis
/analysis.py
1,357
3.5
4
from sklearn import linear_model import pandas as pd import numpy as np import statsmodels.api as sm from analysismenu import analysismenu_print def summary(v, f, d): ''' Prints a summary of the regression analysis Parameters: v (List): Variables that the analysis will be performed over f (Li...
9771cf2ca85b865a4bc3d1fa52e15ba4a688fe16
Dszymczk/Data_analysis_sentdex
/first.py
328
3.9375
4
import pandas as pd df = pd.read_csv("datasets/avocado.csv") # print(df.head(3)) # shows 3 first elements # print(df.tail(2)) # showes 2 last elements # print(df["AveragePrice"].head()) # prints only AberagePrice column(first 5 elements) albany_df = df[df[ df['region'] == "Albany"]] print(albany_df) print(albany_df....
1ed8513cb5477a7195f850a259d51f17bc99d4d5
Jaimeclaure/python
/bucles.py
513
4.0625
4
""" alimentos =['pan','queso','mermelada','leche','mandarinas','dulce de leche', 'carnes frias'] print (alimentos[0]) print (alimentos[1]) print (alimentos[2]) """ """ for alimentos in alimentos: if alimentos=='queso': print('tienes q comprar esto') break print(alimentos) """ ...