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
155a6195c974de35a6de43dffe7f1d2065d40787
IsaacMarovitz/ComputerSciencePython
/Conversation2.py
1,358
4.15625
4
# Python Homework 09/09/2020 # Inital grade 2/2 # Inital file Conversation.py # Modified version after inital submisions, with error handeling and datetime year # Importing the datetime module so that the value for the year later in the program isn't hardcoded import datetime def userAge(): global user_age us...
bf00b432183b7c83bed5de8f1f78ce59322e1889
IsaacMarovitz/ComputerSciencePython
/Minesweeper.py
10,535
3.59375
4
# Isaac Marovitz - Python Homework 02/10/20 # Sources: N/A # Blah blah blah # On my honour, I have neither given nor received unauthorised aid import sys, random, os, time # Declaring needed arrays mineGrid = [] gameGrid = [] # Clear the terminal def clear(): if os.name == "nt": os.system('cls') else...
6cad478212cb9a345107e33659dd716f49e674a0
daniromero97/Python
/e025-StringMethods/StringMethods.py
1,049
3.75
4
print("##################### 1 #####################") sequence = ("This is a ", "") s = "test" sentence = s.join(sequence) print(sentence) sequence = ("This is a ", " (", ")") sentence = s.join(sequence) print(sentence) """ output: This is a test This is a test (test) """ print("##################### 2 ###...
00e97c511c9114dd8cb32f68a3ce3323cfd7ebf4
daniromero97/Python
/e004-Tuples/Tuples.py
1,380
3.875
4
print("########################### 1 ############################") my_tuple = ("value 1", "value 2", "value 3", ["value 4.1", "value 4.2"], 5, ("value 6.1", "value 6.2")) print(my_tuple) print(my_tuple[0]) print(my_tuple[-1]) print(my_tuple[2:5]) """ Output: ('value 1', 'value 2', 'value 3', ['value 4.1', 'value...
ddbeef1a26cb8b570434e5e595dd1421a81a5625
daniromero97/Python
/e013-Encapsulation/OOP.py
728
4.03125
4
class Person(object): def __init__(self, name, height, weight, age): self.__name = name self.__height = height self.__weight = weight self.__age = age def properties(self): print("Name: %s, height: %.2f m, weight: %.1f kg, age: %d years old" % (self.__name, self.__height...
a5eaef2210158228b7681822194cb4ae04dfd677
daniromero97/Python
/e006-ControlFlowStatements/ControlFlowStatements.py
1,780
3.9375
4
print("########################### 1 ############################") a = 0 while a<5: print(a) a+=1 """ Output: 0 1 2 3 4 """ print("########################### 2 ############################") a = 0 while True: a += 1 print(a) if a == 3: break """ Output: 1 2 ...
7dcde1f414b5214079c7516810a9d96094538107
daniromero97/Python
/e033-Datetime/Main.py
3,097
3.734375
4
import datetime print("###################### 1 ######################") print(datetime.MINYEAR) """ output: 1 """ print("###################### 2 ######################") print(datetime.MAXYEAR) """ output: 9999 """ print("###################### 3 ######################") print(datetime.date.today()) pr...
b574c115fc9c68ca068880dfb5b2a247f985d8c2
xiong-zh/Arithmetic
/sort/radix.py
685
3.84375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020/6/15 # @Author: zhangxiong.net # @Desc : def radix(arr): digit = 0 max_digit = 1 max_value = max(arr) # 找出列表中最大的位数 while 10 ** max_digit < max_value: max_digit = max_digit + 1 while digit < max_digit: temp = [[] for...
774ce49dd157eca63ab05d74c0d542dd33b4f14a
Nyame-Wolf/snippets_solution
/codewars/Write a program that finds the summation of every number between 1 and num if no is 3 1 + 2.py
629
4.5
4
Summation Write a program that finds the summation of every number between 1 and num. The number will always be a positive integer greater than 0. For example: summation(2) -> 3 1 + 2 summation(8) -> 36 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 tests test.describe('Summation') test.it('Should return the correct t...
389b09b0bcc2596b3847791765a47127b4f97f13
McBonB/text01_lf
/t.py
1,958
3.65625
4
""" 最远足迹 莫探险队对地下洞穴探索 会不定期记录自身坐标,在记录的间隙中也会记录其他数据,探索工作结束后,探险队需要获取到某成员在探险过程中,对于探险队总部的最远位置 1.仪器记录坐标时,坐标的数据格式为 x,y x和y——》0-1000 (01,2)(1,01) 设定总部位置为0,0 计算公式为x*(x+y)*y """ import re,math s = "abcccc(3,10)c5,13d(1$f(6,11)sdf(510,200)adas2d()(011,6)" #原始字符串 #print(re.findall(r'[^()a-z]+', s)) pattern = re.compile(r'\(([0-9]{1...
a1e2cbfe73c8889bca05dd05a02ef1789bb61a68
Bellroute/python_class
/day0911/example2_6.py
304
4.09375
4
def sumDigits(n): result = 0 while(n != 0): result += n % 10 n //= 10 return result def main(): n = int(input('Enter a number between 0 and 1000 : ')) result = sumDigits(n) print('The sum of the digits is', result) if __name__ == "__main__": main()
483a180d35ed99b23cd82163b47fe2f78e18148c
Bellroute/python_class
/day1002/example5_19.py
253
3.703125
4
inputValue = int(input("Enter the number of lines: ")) for i in range(1, inputValue + 1): line = " " for j in range(i, 0, -1): line += str(j) + " " for j in range(2, i + 1): line += str(j) + " " print(line.center(60))
282434fc39e19a79f8ce6b7ca4b142a9a61aed9d
Bellroute/python_class
/someday/factorize.py
457
3.765625
4
import prime def factorize(n): factor = [] while True: m = prime.isPrime(n) if m == n: break n //= m return factor def main(): n = int(input('type any number : ')) result = prime.isPrime(n) if result: print(n, '은 소수야!') else: print(n...
d920f009c5aa6209e9daf681197d9de7ca73a1f5
acttx/Python
/Comp Fund 2/Lab4/personList.py
1,811
3.59375
4
import csv from person import Person from sortable import Sortable from searchable import Searchable """ This class has no instance variables. The list data is held in the parent list class object. The constructor must call the list constructor: See how this was done in the Tower class. Code ...
e96466aa5575c4b719780a0c2585c270e6f2fb16
acttx/Python
/Comp Fund 2/Lab9/road.py
8,547
3.859375
4
import math from edge import Edge from comparable import Comparable """ Background to Find Direction of Travel: If you are traveling: Due East: you are moving in the positive x direction Due North: you are moving in the positive y direction Due West: you are moving in the negative x direction Due South: you are mo...
5fbadcc16da279332b3cf317155a683f3744e93d
acttx/Python
/Comp Fund 2/Lab4/person_main.py
3,160
4.1875
4
from comparable import Comparable from personList import PersonList from person import Person from sort_search_funcs import * def main(): """ This main function creates a PersonList object and populates it with the contents of a data file containing 30 records each containing the first name and birthda...
6b789ec1822bfeef3b0518c2114a51dee2425424
acttx/Python
/Comp Fund 2/Lab8/charCount.py
530
3.75
4
from comparable import Comparable class CharCount(Comparable): def __init__(self, char, count): self.char = char self.count = count def get_char(self): return self.char def get_count(self): return self.count def compare(self, other_charCount): if self.char <...
62ef143a7d1a7dd420ad2f2f4b8a4ec9dda89f4f
DanielOram/simple-python-functions
/blueberry.py
2,627
4.625
5
#Author: Daniel Oram #Code club Manurewa intermediate #This line stores all the words typed from keyboard when you press enter myString = raw_input() #Lets print out myString so that we can see proof of our awesome typing skills! #Try typing myString between the brackets of print() below print() #With our stri...
15cc2f889516a57be1129b8cad373084222f2c30
viniciuschiele/solvedit
/strings/is_permutation.py
719
4.125
4
""" Explanation: Permutation is all possible arrangements of a set of things, where the order is important. Question: Given two strings, write a method to decide if one is a permutation of the other. """ from unittest import TestCase def is_permutation(s1, s2): if not s1 or not s2: return False if ...
9332ac35cb63d27f65404bb86dfc6370c919c2be
viniciuschiele/solvedit
/strings/is_permutation_of_palindrome.py
1,117
4.125
4
""" Explanation: Permutation is all possible arrangements of a set of things, where the order is important. Palindrome is a word or phrase that is the same forwards and backwards. A string to be a permutation of palindrome, each char must have an even count and at most one char can have an odd count. Question: Given ...
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() ...