blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
405f28e905884cfdd2c11810b27c76f69cc636b9
nueadkie/cs362-inclass-activity-4
/wordcount.py
287
3.875
4
def calc(input_string): # Special case for empty string, or if just whitespace. if len(input_string.strip()) == 0: return 0 words = 1 # Remove any trailing and leading whitespace. for char in input_string.strip(): if char == ' ': words += 1 return words
08a4f34357da5a7063177e4996aa8cadf5c318c6
hendritedjo/python_exercise
/exercise-list.py
1,573
3.75
4
#1 hari = ['senin','selasa','rabu','kamis','jumat','sabtu','minggu'] try: inputhari = input("Masukkan hari : ") inputangka = int(input("Masukkan jumlah : ")) inputhari = inputhari.lower() if (inputhari not in hari): print("Nama hari yang anda masukkan salah") else: sisa = ...
33ab245a6da86e5d0d8c4e51d47762afa12f85a4
hendritedjo/python_exercise
/exam-listspinner.py
434
3.78125
4
#Soal 2 list1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] def counterClockwise(num): num1 = [[a for a in range(num[0][3], num[3][3]+1, 4)], [a for a in range(num[0][2], num[3][2]+1, 4)], [a for a in range(num[0][1], num[3][1]+1, 4...
a7ff689d33dad699ac7e270958cf4d841afb5453
cathyxinxyz/Capstone_project_2
/Top_K_terms.py
3,289
3.515625
4
# function to plot the top k most frequent terms in each class import matplotlib.pyplot as plt import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer import seaborn as sns def Top_K_ngrams(k, ngram, df, text_col, class_col): vect=TfidfVectorizer(ngram_range=(ngram,ngram)) vect.fit(df[...
4557143f73a37747a488bf808e8814b888c2e169
jerome-gingras/Advent-of-code-2015
/day9/day9.py
982
3.53125
4
from itertools import permutations import sys f = open("C:\\Dev\\Advent-of-code-2015\\day9\\input.txt", "r") line = f.readline() cities = set() distances = dict() while line != "": (source, _, destination, _, distance) = line.split() cities.add(source) cities.add(destination) if source in distances: ...
8c75b7197feda25b715d4f2d0641e7e02cffa1e4
Alexionder/TheLifeOfAlex
/Exploration time/items.py
1,183
3.890625
4
class Sword(): def __init__(self, durability, strength, name): self.durability = durability self.strength = strength self.name = name def inspect(self): print "This sword has " + str(self.durability) + " durability and " + str(self.strength) + " strength." class Axe(): def ...
6d52f092b0a8d34724125240a931caf789b0870a
AsleyR/Tic-Tac-Toe-Game---Python
/TTT2.py
11,984
4
4
from tkinter import * #Note: Add choice to be X or O for PvC new_gamemode = False play_as_O = False player = "" computer = "X" x = 0 #General purpose variable for operations board = {0: " ", 2: " ", 3: " ", 4: " ", 5: " ", 6: " ", 7: " ", 8: " ", 9: " "} def turn(): global compu...
fa7ee8f13255f1ceda3e28c58c427c84bf81817f
LionrChen/GraphFeaturesExtraction
/graph/graph.py
7,797
3.546875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ __title__ = '' __author__ = 'ChenSir' __mtime__ = '2019/7/16' # code is far away from bugs with the god animal protecting I love animals. They taste delicious. ┏┓ ┏┓ ┏┛┻━━━┛┻┓ ┃ ┃ ┃ ┳┛ ┗┳ ┃ ┃ ┻ ...
67fe9255295af578c9721b7847299ebe185cf5b8
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Personal_programs/Input_E_rapprString.py
676
4.34375
4
# La funzione input(...) restituisce un tipo stringa, anche se viene passato un numero int o float # Puoi rappresentare una stringa concatenata in diversi modi: # 1- Concatenandola con + e convertendo i numeri con str() ----> 'numero: ' + str(3.6) # 2- Utilizzando la virgola( , ) come separatore tra stringhe e numeri ...
7de1ba91ebbb95ade3f54e652560b2c65369b1e3
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Corso_CISCO_netacad/Strings_in_Python/s8_center_method.py
720
4.25
4
# The one-parameter variant of the center() method makes a copy of the original string, # trying to center it inside a field of a specified width. # The centering is actually done by adding some spaces before and after the string. # Demonstrating the center() method print('[' + 'alpha'.center(10) + ']') print('[' + 'B...
27598f79de97818823527e23f3969c27959f8702
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Corso_CISCO_netacad/Strings_in_Python/s15_split.py
617
4.46875
4
# The # split() # method does what it says - it splits the string and builds a list of all detected substrings. # The method assumes that the substrings are delimited by whitespaces - the spaces don't take part in the operation, # and aren't copied into the resulting list. # If the string is empty, the resulting list i...
0c10af8575d97394bbcb9c2363a82fe424df2bd0
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Corso_CISCO_netacad/integers_octal_exadecimal.py
1,053
4.53125
5
# If an integer number is preceded by an 0O or 0o prefix (zero-o), # it will be treated as an octal value. This means that the number must contain digits taken from the [0..7] range only. # 0o123 is an octal number with a (decimal) value equal to 83. print(0o123) # The second convention allows us to use hexadecimal n...
212a0b661d06ce21a27e70d775accdbddb3a8b1e
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Corso_CISCO_netacad/number_literals.py
907
3.703125
4
# Python 3.6 has introduced underscores in numeric literals, # allowing for placing single underscores between digits and after base specifiers for improved readability. # This feature is not available in older versions of Python. """ If you'd like to quickly comment or uncomment multiple lines of code, select the lin...
fd80e5cecb0c723cf52c16e6b112648476b37388
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Python_Data_Science_Toolbox_Part1/Nested_Functions/NestedFunc1.py
548
4.1875
4
# Define three_shouts def three_shouts(word1, word2, word3): """Returns a tuple of strings concatenated with '!!!'.""" # Define inner def inner(word): """Returns a string concatenated with '!!!'.""" return word + '!!!' # Return a tuple of strings return (inner(word1), inner(wor...
15d42320cb2c5217991e7b6202330c9e5e5fa414
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Corso_CISCO_netacad/Strings_in_Python/s7.py
458
4.4375
4
# Demonstrating the capitalize() method print('aBcD'.capitalize()) print("----------------------") # The endswith() method checks if the given string ends with the specified argument and returns True or False, # depending on the check result. # Demonstrating the endswith() method if "epsilon".endswith("on"): prin...
ada5381cdf4e7ce76bd87b681ea3e233ab83fbc2
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Python_Data_Science_Toolbox_Part1/Part_III/reduce_and_LambdaFunc.py
439
3.9375
4
# Import reduce from functools from functools import reduce # Create a list of strings: stark stark = ['robb', 'sansa', 'arya', 'brandon', 'rickon'] # Use reduce() to apply a lambda function over stark: result result = reduce(lambda item1, item2: item1 + item2, stark) # Print the result print(result) listaNum = [3,...
a959f8c5d7ec65d50fea6f6ca640524a04e13501
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Regular_Expressions_in_Python/Positional_String_formatting/Positional_formatting1.py
812
4.15625
4
# positional formatting ------> .format() wikipedia_article = 'In computer science, artificial intelligence (AI), sometimes called machine intelligence, ' \ 'is intelligence demonstrated by machines, ' \ 'in contrast to the natural intelligence displayed by humans and anima...
968bee9c854610fd5799d875dae04d4227c74cfe
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Functions and packages/PackagesInPython/MathPackageInPython.py
653
4.34375
4
""" As a data scientist, some notions of geometry never hurt. Let's refresh some of the basics. For a fancy clustering algorithm, you want to find the circumference, C, and area, A, of a circle. When the radius of the circle is r, you can calculate C and A as: C=2πr A=πr**2 To use the cons...
22d7fa76f904a0ac5061338e9f90bb3b9afd5d41
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Corso_CISCO_netacad/Lists/list4.py
288
3.734375
4
# A four-column/four-row table - a two dimensional array (4x4) table = [[":(", ":)", ":(", ":)"], [":)", ":(", ":)", ":)"], [":(", ":)", ":)", ":("], [":)", ":)", ":)", ":("]] print(table) print(table[0][0]) # outputs: ':(' print(table[0][3]) # outputs: ':)'
370b98c1d042d5e7f9d98bcac7c72a2eb080385d
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Personal_programs/RandomNum.py
165
3.5625
4
import random print(random.randint(0, 100)) num_int_rand = random.randint(20, 51) print(num_int_rand) for i in range(0, 10): print(random.randint(-2100,1001))
7c92ab969dc4636d99ebe3db1de310dff9dd8727
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Working_with_relational_databases_in_Python/sqliteDB4.py
729
3.625
4
from sqlalchemy import create_engine import pandas as pd engine = create_engine('sqlite:///DB4.sqlite') # Open engine in context manager # Perform query and save results to DataFrame: df with engine.connect() as con: # come con file non hai bisogno di chiudere la connessione in questo modo. rs = c...
100d7f48a899c20b52ee5479eccd7422a87aa667
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Python_Lists/Python_Lists11.py
707
4.125
4
# you can also remove elements from your list. You can do this with the del statement: # Pay attention here: as soon as you remove an element from a list, the indexes of the elements that come after the deleted element all change! x = ["a", "b", "c", "d"] print(x) del(x[1]) # del statement print(x) ...
459188df05fa37b88c1e811b37fae93e096f1ce0
Pasquale-Silv/Improving_Python
/Python Programming language/SoloLearnPractice/ListsInPython/ProofList.py
305
4.03125
4
number = 3 things = ["string", 0, [1, 2, number], 4.56] print(things[1]) print(things[2]) print(things[2][2]) print("----------------------") str = "Hello world!" print(str[6]) print(str[6-1]) print(str[6-2]) print("--------------------------") nums = [1, 2, 3] print(nums + [4, 5, 6]) print(nums * 3)
1ff840fef8bc267fcf37268800d9bd29dd86f521
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Python_Data_Science_Toolbox_Part2/Generators_and_GENfunc_yield/GEN2.py
462
4.34375
4
# [ LIST COMPREHENSION ] # ( GENERATOR ) # Recall that generator expressions basically have the same syntax as list comprehensions, # except that it uses parentheses () instead of brackets [] # Create generator object: result result = (num for num in range(31)) # Print the first 5 values print(next(result)) print(ne...
b3a3caf850d4fffd6f0864bfc293175ab28fd76c
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Python_Data_Science_Toolbox_Part1/Part_I/modulo_builtins.py
820
4.09375
4
import builtins print(builtins) print(dir(builtins)) prova = input('Cerca nel modulo builtins: \n') if prova in dir(builtins): print('La parola', prova, 'è presente nel modulo builtins.') else: print('La parola ' + prova + ' non è stata trovata.') """ Here you're going to check out Python's built-in scope,...
42582cf388cabe7d0ea2e243f171b6608d772443
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Python_Data_Science_Toolbox_Part1/Part_III/Filter_and_LambdaFunc.py
395
4.0625
4
# Create a list of strings: fellowship fellowship = ['frodo', 'samwise', 'merry', 'pippin', 'aragorn', 'boromir', 'legolas', 'gimli', 'gandalf'] # Use filter() to apply a lambda function over fellowship: result result = filter(lambda stringa: len(stringa) > 6, fellowship) # Convert result to a list: result_list print...
25f9ce7108bc60f7825425c67c7bb1366f184c91
SGiuri/hamming
/hamming.py
465
3.59375
4
def distance(strand_a, strand_b): # Check equal Lenght if len(strand_a) != len(strand_b): raise ValueError("Equal length not verified") # set up a counter of differences hamming_difference = 0 # checking each letter for j in range(len(strand_a)): # if there is a difference, i...
ec1a49268a967c2d28c39a06e42f8af02f4d4c26
zomgroflmao/1st_lesson
/vat.py
162
3.578125
4
def get_vat(price, vat_rate): vat = price / 100 * vat_rate price_no_vat = price - vat print(price_no_vat) price1 = 100 vat_rate = 18 get_vat(price1, vat_rate1)
04ce4745d854c9d712ac5089ad94573fe287fae9
anjiboini/anji_python_games
/anji_tkinter_database.py
672
3.5625
4
from tkinter import * from PIL import ImageTk,Image import sqlite3 root = Tk() root.title('Wellcome to India') root.iconbitmap('D:/anji_python software/python/anji tkinter projects/resources/thanu1.ico') root.geometry("400x400") #Databases #Create a Databases or connect one conn = sqlite3.connect('address_book...
21f6b720fa94adb9330322339200a7c8a7e246f6
anjiboini/anji_python_games
/anji_tkinter_databaseusing1.py
1,603
4
4
from tkinter import * from PIL import ImageTk,Image import sqlite3 root = Tk() root.title('Wellcome to India') root.iconbitmap('D:/anji_python software/python/anji tkinter projects/resources/thanu1.ico') root.geometry("400x400") #Databases # Create a Databases or connect one conn = sqlite3.connect('address_boo...
e478ccc2cff10e77e0a85ce42f68bb822ee61d5e
anjiboini/anji_python_games
/anji_tkinte_01.py
2,561
3.765625
4
from tkinter import * #.............................................. #root=Tk() #theLable=Label(root,text="Hi anji how r u") #theLable.pack() #root.mainloop() #............................................ #one=Label(root, text="One", bg="red",fg="white") #one.pack() #two=Label(root, text="Two", bg="ye...
4f7496a27ea1bc08d7252326cea3ee912857e39a
Angelagoodboy/Python_classifyCustomer
/Main.py
430
3.546875
4
#调用Python文件并且实现输入不同参数对应不同分类组合 import sys #实现脚本上输入参数 def main(): try: Type=sys.argv[1] FileInputpath=sys.argv[2] FileOutpupath=sys.argv[3] if Type=='-r': # 调用客户模块: except IndexError as e: print("输入的错误参数") if __name__ == '__main__': print('hellowo...
0e73fa953efc7182444e9bd7148d489b48f92ef6
sksuharsh1611/py18thjune2018
/code21june.py
1,418
3.515625
4
#!/usr/bin/python2 import time,webbrowser,commands menu=''' press 1: To check current date and time: press 2: To scan all your Mac Address in your current cOnnected Network: press 3: To shutdown your machine after 15 minutes: press 4: To search something on Google: press 5: To logout your current machine: press 6: T...
0f62b89ad95ca5e8bee9b211dc1b5bb6f940234b
melodyquintero/python-challenge
/PyPoll/main.py
2,291
3.9375
4
# Import Modules for Reading raw data import os import csv # Set path for file csvpath = os.path.join('raw_data','election_data_1.csv') # Lists to store data ID = [] County = [] Candidate = [] # Open and read the CSV, excluding header with open(csvpath, newline="") as csvfile: next(csvfile) cs...
cf7dbbfe0ffb7790452be0d9b0734d0f1886ce5b
Vishal19914/VishalClock
/test_clock.py
473
3.625
4
import unittest from clock import Clock_Angle class TestClock(unittest.TestCase): def test_check_angle(self): ca= Clock_Angle(3,0) angle= ca.checkValues() self.assertEqual(angle,90, "Angle is 90") def test_check_range(self): ca= Clock_Angle(23213,4324) result= ...
0d77b125701172493da106652ef0aa30551cc60c
tuxnani/open-telugu
/tamil/tscii2utf8.py
626
3.546875
4
#!/usr/bin/python # -*- coding: utf-8 -*- # (C) 2013 Muthiah Annamalai from sys import argv, exit import tamil def usage(): return u"tscii2utf8.py <filename-1> <filename-2> ... " if __name__ == u"__main__": if not argv[1:]: print( usage() ) exit(-1) for fname in argv[1:]: try: ...
7e8298e4733a357b535d473549a4d467b9a7f354
dilithjay/Double-Blank-NPuzzle-AStar
/Python/a_star.py
2,988
3.515625
4
from enum import Enum from queue import PriorityQueue from time import time from utils import get_blanks, get_heuristic_cost_manhattan, get_heuristic_cost_misplaced, get_2d_array_copy, swap BLANK_COUNT = 2 DIRECTION_COUNT = 4 dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)] opposite_dirs = ('down', 'up', 'right', 'left') ...
0b03516098b1e064bad91970b932624408fe53fc
ryanmp/project_euler
/p056.py
875
4.0625
4
''' A googol (10^100) is a massive number: one followed by one-hundred zeros; 100^100 is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1. Considering natural numbers of the form, ab, where a, b < 100, what is the maximum digital sum? ''...
6ab7b8b1135b74d6572efd98bb64f86f85e468ce
ryanmp/project_euler
/p076.py
1,263
4.15625
4
''' counting sums explanation via example: n == 5: 4 + 1 3 + 2 3 + 1 + 1 2 + 2 + 1 2 + 1 + 1 + 1 1 + 1 + 1 + 1 + 1 if sum == 5 -> there are 6 different combos ''' def main(): return 0 # how many different ways can a given number be written as a sum? # note: combinations, not permutations def count_sum_reps(n): '...
905044cf0b3bbe51124477458e02b069ee72eb0f
ryanmp/project_euler
/p034.py
1,037
3.828125
4
''' 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. Find the sum of all numbers which are equal to the sum of the factorial of their digits. Note: as 1! = 1 and 2! = 2 are not sums they are not included. ''' import math f = {} for i in xrange(0,10): f[i] = math.factorial(i) def main(): # hm......
4918127d5c7331402a9aceb8288071c0de80766b
ryanmp/project_euler
/p005.py
628
3.796875
4
''' 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? ''' def main(): divisors = [11, 13, 14, 16, 17, 18, 19, 20] smallest = 2520 while(True): passes = T...
067beb1bcbc592f4a362d68cd4423eee877b094d
ryanmp/project_euler
/p017.py
1,437
3.875
4
''' If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? NOTE: Do not count spaces or hyphens. For example, 342 (...
8b6fbbd63e8a5acb92eb7a2481521cb646abbad6
ryanmp/project_euler
/p024.py
990
3.796875
4
from itertools import permutations from math import factorial as f ''' Q: What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? ''' def main(): p = permutations([0,1,2,3,4,5,6,7,8,9]) # lists them in lexicographic order by default l = list(p) ans = l[1000000-1] #Why the '-1'...
73f0378d6358f6fe1b7ae727facbd236f0134baa
ryanmp/project_euler
/p036.py
611
3.6875
4
''' The decimal number, 585 = 1001001001 (binary), is palindromic in both bases. Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2 ''' def is_palindrome(n): return str(n) == str(n)[::-1] def main(): sum = 0 for i in xrange(1,int(1e6),2): # via logic, no even soluti...
1ddf72a48f1db42476f00c50e39af6f523899ff6
ankitjnyadav/LeetCode
/Strings/Reverse a String.py
258
3.890625
4
def reverseString(s) -> None: """ Do not return anything, modify s in-place instead. """ #Approach 1 s[:] = s[::-1] #Approach 2 i = 0 for c in s[::-1]: s[i] = c i = i + 1 reverseString(["h","e","l","l","o"])
58667121c08c196a1c8141bcdbfce21154849de2
ankitjnyadav/LeetCode
/30 Day Leet Coding Challenge/Day1 - First Bad Version/Day1.py
751
3.53125
4
''' Problem Statement - https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/534/week-1-may-1st-may-7th/3316/ ''' # The isBadVersion API is already defined for you. # @param version, an integer # @return a bool # def isBadVersion(version): class Solution: def isBadVersion(n): if n >= 4: ...
e9916dcf5e90daa9e263831aa893b333bf0b914d
andreea-munteanu/AI-2020
/Lab2-3/Lab2.py
9,042
3.578125
4
import random import sys from queue import Queue n = 12 m = 15 # n = 4 # m = 4 print("n = ", n, "m = ", m) SIZE = (n, m) # n rows, m columns if sys.getrecursionlimit() < SIZE[0] * SIZE[1] : sys.setrecursionlimit(SIZE[0] * SIZE[1]) # if max recursion limit is lower than needed, adjust it sys.setre...
8d6dd0da1e52152ebbec09722fae2d166dbcdd92
urzyasar/Python
/OOPs/Encapsulation.py
797
3.875
4
#Encapsulation class Bike: def __init__(self,n): self.name=n self.__price=50,000 #private variable def setprice(self,p): self.__price=p print(self.__price) self.__display() def __display(self): print("...
240066b054c327e6a05ab214ce54466ba9b39d6f
gonzrubio/HackerRank-
/InterviewPracticeKit/Dictionaries_and_Hashmaps/Sherlock_and_Anagrams.py
992
4.15625
4
"""Given a string s, find the number of pairs of substrings of s that are anagrams of each other. 1<=q<=10 - Number of queries to analyze. 2<=|s|<=100 - Length of string. s in ascii[a-z] """ def sherlockAndAnagrams(s): """Return the number (int) of anagramatic pairs. s (list) - input string """ n...
77dcb824eb6c6197667cb94284a26a69eb445f11
kirtivr/leetcode
/Leetcode/384.py
1,036
3.703125
4
from random import * class Solution: def __init__(self, nums): """ :type nums: List[int] """ self.N = len(nums) self.orig = list(nums) self.nums = nums def reset(self): """ Resets the array to its original configuration and return it. ...
66e4433f8027b693e555e2d80e888e69bb352834
kirtivr/leetcode
/48.py
972
3.828125
4
class Solution: def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ N = len(matrix) for i in range(N): for j in range(N//2): matrix[i][N-j-1],matrix[...
31f66d99d35913915be26b0453125089675a58ca
kirtivr/leetcode
/Leetcode/3.py~
1,070
3.546875
4
from typing import List class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: left = 0 right = len(nums) - 1 def binary_search(start: int, end: int, target: int) -> int: if start > end: return -1 mid = start + (end - start)//2 if nums[mid]...
da16b28f0fdb072a6eacba8883f72c16506ee9b0
kirtivr/leetcode
/Leetcode/151.py
1,165
3.65625
4
class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ s = s.strip() N = len(s) ls = [] j = 0 for i in range(N): if i > 0 and s[i] == ' ' and s[i-1] == ' ': continue ...
99e743c3548ab28186bb6f39b0c2f8ac666fe722
kirtivr/leetcode
/121.py
542
3.625
4
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ minNow = 1 << 30 maxProfit = 0 for i in range(len(prices)): price = prices[i] if price - minNow > maxProfit: maxPr...
c630d50c2ba134e47f202ef7021270cd50198ea5
kirtivr/leetcode
/Leetcode/33.py
1,672
3.8125
4
class Solution: def findPivot(self, start, end, arr): if start > end: return 0 mid = start + (end - start)//2 #print(mid) if mid != 0 and arr[mid-1] >= arr[mid]: return mid elif arr[mid] > arr[end]: return self.findPivot(m...
ccc20ea56a993806ec35c35eea33564c6bb83d1d
kirtivr/leetcode
/Leetcode/skip_lists_code_for_2407.py
6,090
3.625
4
from typing import List, Optional, Tuple, Dict import heapq import pdb import ast import sys from dataclasses import dataclass, field from functools import cmp_to_key import time class ListNode: def __init__(self, val, idx): self.idx = idx self.val = val self.next = None self.prev =...
c66a57a11aa2c998cb24ba707020f1a9f14eeefa
kirtivr/leetcode
/Leetcode/binary_indexed_tree_example.py
1,663
4.03125
4
# Python3 program to count inversions using # Binary Indexed Tree # Returns sum of arr[0..index]. This function # assumes that the array is preprocessed and # partial sums of array elements are stored # in BITree[]. def getSum( BITree, index): sum = 0 # Initialize result # Traverse ancestors of ...
c2e40105692a0a132ae3f2304e99d207d9cceae1
kirtivr/leetcode
/Leetcode/62.py
4,326
3.578125
4
from typing import List, Optional, Tuple, Dict import pdb from functools import cmp_to_key import time def make_comparator(less_than): def compare(x, y): if less_than(x, y): return -1 elif less_than(y, x): return 1 else: return 0 return compare class...
7d6ef70b32516d620199e1002228326e308d7893
kirtivr/leetcode
/Leetcode/python_linked_list_template.py
1,566
3.6875
4
from typing import List, Optional, Tuple, Dict from heapq import heappop, heappush, heapify import pdb import ast import sys from functools import cmp_to_key import time # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next d...
a480c4a2c398cf11d06d5d67301e2ceeff4a7a1e
kirtivr/leetcode
/538.py
754
3.671875
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None ''' 7 5 9 3 6 8 10 ''' class Solution(object): def convert...
a9e85bc4f8f394810469202a03beda752a0c8b4a
kirtivr/leetcode
/Leetcode/19.py
1,008
3.703125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ ...
9fe6f08df783fa4744f9dc2efe179019007d9966
kirtivr/leetcode
/First attempts at/19.py
1,205
3.5625
4
#!/usr/bin/env python import time import pdb import sys import copy from typing import List, TypedDict # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseLinkedList(self, head: Optional[ListNode]) -> bool: ...
e9b85cf35392d9b35970ccab0dab86c258aa1c37
kirtivr/leetcode
/First attempts at/146.py
5,777
3.78125
4
#!/usr/bin/env python import time import pdb import sys import copy from typing import List, TypedDict class Element(object): def __init__(self, key: int, val: int, prev, next): self.key = key self.value = val self.prev = prev self.next = next def __repr__(self): ...
c8c217a9b1cbcc7f7058ac1c5d31c1774edf550c
kirtivr/leetcode
/170.py
1,999
3.859375
4
class TwoSum: def __init__(self): """ Initialize your data structure here. """ self.hashmap = [] self.numbers = set() def add(self, number): """ Add the number to an internal data structure.. :type number: int :rtype: void """ ...
79cd77f09d5b0c796dd4744cd60756c735bf5105
kirtivr/leetcode
/70.py
429
3.640625
4
class Solution(object): def tryClimb(self, n, steps): if n in steps: return steps[n] return steps[n-1]+steps[n-2] def climbStairs(self, n): """ :type n: int :rtype: int """ steps = {} steps[0] = 0 steps[1] = 1 steps[2...
1a7b2f86630f2409b8100d4bc6dc040b657c3d03
kirtivr/leetcode
/56.py
1,173
3.640625
4
class Interval(object): def __init__(self, s=0, e=0): self.start = s self.end = e def __str__(self): return(str(self.start) + ' ' + str(self.end)) class Solution(object): def mergeInt(self, intv1, intv2): return Interval(intv1.start,max(intv1.end, intv2.end)) def m...
b854946978b0c35cb74f63eae02ea1a2aeed0967
zwilhelmsen/regex-tool
/regex-tool.py
4,451
3.75
4
####################################################### # Regular expressions tool ####################################################### """ Regular expressions tool created: zac wilhelmsen 08/31/17 Finds the regular expression used to identify patterns/strings """ def regex_tool(string): split...
a0742f744b2d66be9131ab31988fba386e9178ec
likeke201/qt_code
/DemoUIonly-PythonQt/chap14matplotlib/Demo14_1Basics/Demo14_1Script.py
1,019
3.671875
4
## 程序文件: Demo14_1Script.py ## 使用matplotlib.pyplot 指令式绘图 import numpy as np import matplotlib.pyplot as plt plt.suptitle("Plot by pyplot API script") #总的标题 t = np.linspace(0, 10, 40) #[0,10]之间平均分布的40个数 y1=np.sin(t) y2=np.cos(2*t) plt.subplot(1,2,1) #1行2列,第1个子图 plt.plot(t,y1,'r-o',labe...
905ea1bc35f9777f9afc3d693b90aa5cde8c6c2e
patrickhaoy/RL-Tic-Tac-Toe
/src/state.py
6,654
3.921875
4
import numpy as np board_rows = 3 board_cols = 3 """ Tic Tac Toe board which updates states of either player as they take an action, judges end of game, and rewards players accordingly. """ class State: def __init__(self, p1, p2): self.board = np.zeros((board_rows, board_cols)) self.p1 = p1 ...
0c1b5328bcf938b70a3a96ef1b4ac433ea771e4c
jiangeyre/Graphs
/Day_2_Lecture/graph_with_search.py
2,516
3.921875
4
class Queue: def __init__(self): self.queue = [] def enqueue(self, value): self.queue.append(value) def dequeue(self): if self.size() > 0: return self.queue.pop(0) else: return None def size(self): return len(self.queue) ​ class Graph: ​ d...
d38f462e41e1f2fd0e9f07623bca3fc6a5619272
mikaelgba/PythonDSA
/cap5/Metodos.py
1,411
4.25
4
class Circulo(): # pi é um varialvel global da classe pi = 3.14 # com raio = 'x valor' toda vez que criar um objeto Circulo ele automaticamnete já concidera que o raio será 'x valor' #mas se colocar um outro valor ele vai sobreescrever o 'x valor' def __init__( self, raio = 3 ): ...
c735af789942fa33262fc7f6b6e6970351d3cb1d
mikaelgba/PythonDSA
/cap4/Funcao_Filter.py
687
3.828125
4
#Criando uma função para verificar se um numero é impar def ver_impar(numero): if ((numero % 2) != 0): return True else: return False print(ver_impar(10), "\n") #Criando uma lista adicionando nela valores randomicos import random # a se torna em uma lista com 10 varoles random a = ran...
26690c4000dbfd7bc49817c00aee7d1a406f4475
mikaelgba/PythonDSA
/cap2/Dicionarios.py
1,339
3.875
4
dicio1 = {"Mu":1,"Aiolia":5,"Aiolos":9,"Aldebaran":2,"Shaka":6,"Shura":10,"Saga":3,"Dorko":7,"Kamus":11,"Mascará da Morte":4,"Miro":8,"Afodite":12} print(dicio1) print(dicio1["Mu"]) #Limpar os elementos do Dicionario dicio1.clear() print(dicio1) dicio2 ={"Seiya":13,"Shiryu":15,"Ikki":15,"Yoga":14,"Shun":13} dicio2["...
ea8211501e5fcb7ae3a319cf7c9f2e6878ad759b
mikaelgba/PythonDSA
/cap2/Variaveis.py
362
3.734375
4
a = 1.7 b = 2 print(a , b) print(pow(a,b)) print() a = 1.7777 b = 2 print(round(a,b)) print() b = 2 print(float(b)) print() a = 1.7 print(int(a)) print() var_test = 1 print(var_test) print(type(var_test)) print() pessoa1, pessoa2, pessoa3 = "eu", "você", "E o Zubumafu" print(pessoa1) print(pessoa2) print(pessoa3)...
ea62f060d4d0d4e1b9250e8edd041cc939b109da
mikaelgba/PythonDSA
/cap4/Datetime.py
1,007
3.90625
4
#Importando o pacote DataTime, aplicações de data e hora import datetime # datetime.datetime.now() retorna a data e o horario atual hora_agora = datetime.datetime.now() print(hora_agora) print("\n") # datetime.time() cria um horario hora_agora2 = datetime.time(5,7,8,1562) print("Hora(s): ", hora_agora2.hour) print(...
e1a234adfa92c9621b97e9ea3b9b07b112ff8a23
itsanti/gbu-ch-py-algo
/hw6/hw6_task3.py
1,979
3.609375
4
"""HW6 - Task 3 Подсчитать, сколько было выделено памяти под переменные в ранее разработанных программах в рамках первых трех уроков. Проанализировать результат и определить программы с наиболее эффективным использованием памяти. """ import sys from math import sqrt from memory_profiler import profile print(sys.vers...
c58df5c0848e33e443e455f26433efd010276218
itsanti/gbu-ch-py-algo
/hw8/hw8_task1.py
589
3.6875
4
"""HW8 - Task 1 На улице встретились N друзей. Каждый пожал руку всем остальным друзьям (по одному разу). Сколько рукопожатий было? Примечание. Решите задачу при помощи построения графа. """ n = int(input('Сколько встретилось друзей: ')) graph = [[int(i > j) for i in range(n)] for j in range(n)] count = 0 for r in ra...
dc4153dddd83d25e90daaa526124291729b85405
itsanti/gbu-ch-py-algo
/hw3/hw3_task5.py
1,288
3.9375
4
"""HW3 - Task 5 В массиве найти максимальный отрицательный элемент. Вывести на экран его значение и позицию в массиве. Примечание к задаче: пожалуйста не путайте «минимальный» и «максимальный отрицательный». Это два абсолютно разных значения. """ import random in_arr = [random.randint(-3, 3) for _ in range(5)] print...
f6c3bc55ec38fefd1cf9b8dd646f6bf5135716d4
itsanti/gbu-ch-py-algo
/hw2/hw2_task5.py
489
3.6875
4
"""HW2 - Task 5 Вывести на экран коды и символы таблицы ASCII, начиная с символа под номером 32 и заканчивая 127-м включительно. Вывод выполнить в табличной форме: по десять пар «код-символ» в каждой строке. """ i = 1 for code in range(32, 128): end = '\n' if i % 10 == 0 else '\t' print(f'{code:3}-{chr(code)}...
51ac5cfbf207126f3cf7ea7066c7c942d91dc074
mahanta-tapas/WebScrapers
/verbose.py
467
3.765625
4
import sys question = "Are you Sure ??" default = "no" valid = {"yes": True , "y": True, "ye" : True} invalid = {"no" :False,"n":False} prompt = " [y/N] " while True: choice = raw_input(question + prompt ) if choice in valid: break elif choice in invalid: sys.stdout.write("exiting from program \n") exit() ...
c2d821b83ecc693ba04247ba12a8d7ffcf0919cc
MatthewH1988/Python-Techdegree-Project-1
/guessing_game.py
1,238
4.0625
4
import random def start_game(): print("Welcome to the Number Guessing Game!") import random guess_count = 1 while True: try: random_number = random.randrange(0, 11) player_guess = int(input("Please guess a number between 0 and 10: ")) i...
aaa0660306c6486820cde0f6e75f315cfec3ca3b
NickSKim/csci321
/PygameDemos/0700rpg/tiles.py
4,897
3.625
4
import os, pygame from pygame.locals import * from utilities import loadImage class InvisibleBlock(pygame.sprite.Sprite): def __init__(self, rect): pygame.sprite.Sprite.__init__(self) self.rect = rect def draw(surface): pass class Tile(pygame.sprite.Sprite): def __init__(self, im...
c6248c29ef8daad133c18babcffa42664d602a72
RiverTate/Chern
/hofstadter.py
2,417
3.609375
4
# This program calculate the eigen energies of a qantum Hall # system (square lattice), and plot the energy as a function # of flux (applied magnetic filed). The plot of nergy vs. flux # would generate hofstadter butterfly # Author: Amin Ahmadi # Date: Jan 16, 2018 #####################################################...
ea9d13753a22f346cd86b677fa49ad6ad54846f6
AlexFabra/Sudoku
/Sudoku.py
8,138
4
4
import math class Sudoku: # guardem els números necessaris per que una fila, columna o quadrant estiguin complets: nombresNecessaris = [1, 2, 3, 4, 5, 6, 7, 8, 9] #creem el constructor de Sudoku. Li passarem com a paràmetre un array d'arrays: def __init__(self,arrays): self.arrays=arrays #el...
1825ecd0df5fdfa00eb0e0c5322caef87081e4c5
yijirong/movie-dataset-analysis
/model.py
427
3.609375
4
class StudentModel: def __init__(self, name="", sex="", score=0.0, age=0, sid=0): self.name = name self.sex = sex self.score = score self.age = age self.sid = sid def __str__(self): return f"{self.name} your account is {self.sid},age is {self.age},movie name is...
86afe70c6c5a94161b4a211ca835ffb0e402765a
willbrom/py_prog
/guess_a_number.py
514
4.09375
4
#!/bin/python3 #This is a guess the number game from random import randint rand_num = randint(1,20) print('I am thinking of a number between 1 and 20') for guess_taken in range(0, 7): print('Take a guess') guess = int(input()) if guess < rand_num: print('Your guess is too low') elif guess > rand_num: print...
df8537c34ccabcdf0404e8b0416d6711c59410ca
felipebregalda/gogitcl
/notas.py
278
3.53125
4
#-*- coding utf-8 -*- from funcoes import notaFinal print 'Calculo de notas do Aluno\n' nome = raw_input ('Nome: ') nota1 = float( raw_input('Nota 1: ')) nota2 = float( raw_input('Nota 2: ')) notaFinal = notaFinal(nota1, nota2) print 'Nota final do aluno',nome,'eh',notaFinal
5a9c5719e053d265dd173e766008bc33118b6dae
peterzhou84/datastructure
/samples/python/array.py
1,542
4.4375
4
#coding=utf-8 #!/usr/bin/python3 ''' 展示在Python中,如何操作数组 ''' ################################################# ### 一维数组 http://www.runoob.com/python3/python3-list.html squares = [1, 4, 9, 16, 25, 36] print("打印原数组:") print(squares) ''' Python的编号可以为正负 +---+---+---+---+---+---+ | 1 | 4 | 9 | 16| 25| 36| +---+---+---+--...
2630ddaf65b81180029e68506dce3a45e8c82c08
jamesmold/learning
/aoc2.py
528
3.53125
4
from collections import Counter fhand = open("aoc2.txt") lines = [x.strip() for x in fhand] #removes the new lines from the input file aoc2.txt def part1(): has2 = 0 has3 = 0 for line in lines: c = Counter(line).values() #Counter counts like elements in a string (returns as dict key value pair, ad...
5e0f8b72f7946109f1bb70e8cca938c7a5d0da0e
DarioBernardo/hackerrank_exercises
/dinner_party.py
1,521
3.78125
4
# Find all possible combination of friends using recursion # the total number of combination is given by binomial coefficient formula # n choose k where n is the number of guest and k is the table size # binomial coefficient = n!/(k!*(n-k)!) from itertools import combinations friends = ['A', 'B', 'C', 'D', 'E', 'F',...
7a39583a260a600b2228795bcaa18dd97cb9acde
DarioBernardo/hackerrank_exercises
/recursion/word_break.py
1,959
4.0625
4
""" EASY https://leetcode.com/explore/interview/card/facebook/55/dynamic-programming-3/3036/ Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. Note that the same word in the dictionary may be reused multiple times ...
0a992d783e6c4208da21a3efbdccfd612437d30b
DarioBernardo/hackerrank_exercises
/stacks_and_queues/minimum_lenght_substring.py
4,025
4.125
4
""" Minimum Length Substrings You are given two strings s and t. You can select any substring of string s and rearrange the characters of the selected substring. Determine the minimum length of the substring of s such that string t is a substring of the selected substring. Signature int minLengthSubstring(String s, Str...
2a4554a80c37176663dba8d9e8159fc3676c0e74
DarioBernardo/hackerrank_exercises
/graphs/alien_dictionary.py
2,872
4.03125
4
""" ALIEN DICTIONARY (HARD) https://leetcode.com/explore/interview/card/facebook/52/trees-and-graphs/3025/ Example of topological sort exercise. There is a new alien language that uses the English alphabet. However, the order among letters are unknown to you. You are given a list of strings words from the dictionary,...
486b6adf4f4fc17b23f16aafca1a3fdafe92465d
DarioBernardo/hackerrank_exercises
/new_year_chaos.py
1,301
3.65625
4
""" NEW YEAR CHAOS https://www.hackerrank.com/challenges/new-year-chaos """ def shift(arr, src_index, dest_index): if src_index == dest_index or abs(src_index - dest_index) > 2: return if src_index - dest_index == 1: swap(arr, dest_index, src_index) else: swap(arr, dest_index, s...
3720bb40db37bf3006c90c72bce9419a953aded6
DarioBernardo/hackerrank_exercises
/arrays/merge_intervals.py
1,271
4.0625
4
""" MEDIUM https://leetcode.com/problems/merge-intervals/ Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. Example 1: Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output...
b347b04bc5734a10812e42e9060e8d6323038692
DarioBernardo/hackerrank_exercises
/search/insert_in_sorted_list.py
1,090
3.84375
4
""" Insert a new elem in a sorted list in O(log N) """ import random from typing import List def insert_elem(in_list: List, val: int): if len(in_list) == 0: in_list.append(elem) return start = 0 end = len(in_list) while start < end: middle = start + int((end - start) / 2) ...
bfecec5ea05dd2fd58ee9e5d88cf083126a5bd06
DarioBernardo/hackerrank_exercises
/linked_lists/reorder_list.py
2,478
4.0625
4
""" https://leetcode.com/explore/interview/card/facebook/6/linked-list/3021/ (HARD) You are given the head of a singly linked-list. The list can be represented as: L0 → L1 → … → Ln - 1 → Ln Reorder the list to be on the following form: L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → … You may not modify the values in the lis...
0ef227f6d8f07559a75faa3767d0da5d8fbcbb88
DarioBernardo/hackerrank_exercises
/tree_and_graphs/tree_level_avg_bfs_and_dfsv2.py
2,446
4
4
""" Given a binary tree, get the average value at each level of the tree. Explained here: https://vimeo.com/357608978 pass fbprep """ from typing import List class Node: def __init__(self, val): self.value = val self.right = None self.left = None def get_bfs(nodes: List[Node], result: li...
d4f7b9d7c21da7b017e930daf5fbf1fb729dfe7f
DarioBernardo/hackerrank_exercises
/graphs/journey_to_the_moon.py
2,213
3.703125
4
""" medium https://www.hackerrank.com/challenges/journey-to-the-moon/problem """ class GraphMap: def __init__(self): self.graph_map = dict() def add_link(self, a, b): links = self.children_of(a) links.append(b) self.graph_map[a] = links def add_bidirectional_link(self, a,...
79fe834ad9528d7d1d6bdfcb8c8e37dfe8e90fc9
DarioBernardo/hackerrank_exercises
/graphs/number_of_islands.py
2,474
3.953125
4
""" Given an m x n 2d grid map of '1's (land) and '0's (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: Input: grid = [ ["1","1","1","1",...