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
8f137b5b5888b248ffee6d4906e4fa2ea27ad046
jalexy12/linear_algebra_udacity
/vector.py
1,828
3.625
4
class Vector(object): def __init__(self, coordinates): try: if not coordinates: raise ValueError self.coordinates = tuple(coordinates) self.dimension = len(coordinates) except ValueError: raise ValueError('The coordinates must be nonem...
cb38e3f3fb249f1f033f7b60af92bdfe047d665d
alexresiga/courses
/first semester/fp/assignment10/domain/Board.py
3,660
4.03125
4
from tkinter import * class Board: def __init__(self, n, m): self.__board = [['_' for x in range(m)] for y in range(n)] self.rows = n self.columns = m def print_board(self): """ custom print of game board :return: """ print(' |', end=' ') ...
5dafcca9cc890cfbe8e140a547cd4e53f02edb99
alexresiga/courses
/first semester/fp/assignment1/SetCP12.py
1,355
3.96875
4
# The numbers n1 and n2 have the property P if their writings in basis 10 have the same digits (e.g. 2113 and 323121). Determine whether two given natural numbers have the property P. def pProperty(a,b): """ This function checks if two numbers are formed with the same digits, using a frequency array. ...
1e9e7247ae172d10bbe13f9792e2dbaca49e1e60
alexresiga/courses
/first semester/fp/examen/domain/question.py
1,672
3.703125
4
class Question: def __init__(self, ident, text, choice_a, choice_b, choice_c, correct, dif): self.__id = ident self.__text = text self.__choice_a = choice_a self.__choice_b = choice_b self.__choice_c = choice_c self.__correct = correct self.__dif = dif de...
41be3c636e2d3cda64f2b4db81121a7b47ead5f5
alexresiga/courses
/first semester/fp/assignment1/SetBP10.py
660
4.375
4
# Consider a given natural number n. Determine the product p of all the proper factors of n. def productOfProperFactors(n): """ This function returns the product of all proper factor of a given natural number n. input: n natural number. output: a string with the proper factors and the reuslt...
77ac96a9a0934604a77ae78e48b7db6066795955
alexresiga/courses
/first semester/fp/assignment10/domain/Game.py
2,346
3.8125
4
import time from domain.Board import Board from random import randint class Game: def __init__(self, n, m): self.__board = Board(n, m) self.limit = n+m def move_player(self, i, j): self.__board.move(j, i, 'X') def move_matei(self, i, j): self.__board.move(j, i, 'O') ...
43d71bdfbade8f2e1c4549f7430f8d427a198f57
alexresiga/courses
/first semester/fp/test1/validation.py
255
3.84375
4
def validatePoem(poem): """ validate if input poem is correct :param poem: :return: """ for i in range(len(poem["lyrics"])-1): if poem["lyrics"][i][-3:] != poem["lyrics"][i+1][-3:]: return False return True
e7d2717547a78d685a1d556eafa66387046a0f68
Antonlushnikow/geekbrains_python
/lesson_2/task_5.py
241
3.640625
4
my_list = [7, 5, 3, 3, 2] new_el = int(input('Введите новый элемент: ')) # new_el = 1 index = 0 for i in range(len(my_list)): if new_el <= my_list[i]: index = i + 1 my_list.insert(index, new_el) print(my_list)
19352ef61f5935696f00e7dd89d9023e84b47f92
ecardena19/python-tutorial
/hacker_rank/if_else_hr.py
232
3.765625
4
n = int(input().strip()) result1 = 'Weird' result2 = 'Not Weird' if n % 2 == 0: if 2 <= n <= 5: print(result2) if 6 <= n <= 20: print(result1) if n > 20: print(result2) else: print(result1)
9c6b30333b5598b855034ea7f10e0fc31904d986
ecardena19/python-tutorial
/hacker_rank/arithmetic_operators_hr.py
290
3.984375
4
num1 = int(input()) num2 = int(input()) def addition(int1, int2): return int1 + int2 print(addition(num1, num2)) def subtraction(int1, int2): return int1 - int2 print(subtraction(num1, num2)) def multiply(int1, int2): return int1 * int2 print(multiply(num1, num2))
4583405ebfea5aa2dc06c6ef6411cf56158c83f1
phaesol/Algorithm
/2020.08.21.py
631
3.6875
4
#같은 숫자는 싫어. # def solution(arr): # new_list=[] # for i in range(len(arr)): # print(arr[i+1]) # return new_list # solution([4,4,3,3,2,2]) # def solution(arr): # new_list=[] # for i in range(len(arr)): # if i == 0 and arr[i] == arr[i+1] : # ...
bef9440f05114c93a5618245266f1e5beff13797
phaesol/Algorithm
/2020.08.12.py
592
3.75
4
# def solution(s): # upper_list = [] # lower_list=[] # for i in s: # if i.isupper(): # upper_list += i # else: # lower_list += i # upper_reverse = reversed(upper_list) # lower_reverse = reversed(lower_list) # answer = "".join(lower_reverse) + "".join(...
87013c5589d8fac7ebf712f1384ac6f38388d499
xiaoyangren513/day02
/names.py
457
3.5625
4
names=['yan','yang','guoqian'] names.append() names.insert() names[]="直接给替换值" #delete names.remove("要删除的值") del names[1] names.pop() #默认删除最后的一个元素 可以带参数 names.index("要找的") names[names.index("要找的")] names.count('计数') sort() 排序 names.extend( ) ############### 复制列表 浅拷贝 找内存 直接赋值更没用 import copy #跳着切片 [:...
330c158cd40b77bbfab374d620f6f132943ae150
qiao-zhang/leetcode_problems
/algorithms/_153_find_minimum_in_rotated_sorted_array.py
391
3.53125
4
class Solution(object): def findMin(self, nums): """ :type nums: List[int] :rtype: int """ def solveBS(): lo, hi = 0, len(nums) - 1 while lo < hi: m = (lo + hi) // 2 if nums[m] < nums[hi]: hi = m else: lo...
8077454a55cb6466e2f657e017d6cd9c4973b18b
qiao-zhang/leetcode_problems
/algorithms/_337_house_robber_3.py
624
3.765625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def rob(self, root): """ :type root: TreeNode :rtype: int """ def solveRecursivel...
9769cb53aabdc3427622f4ff545179b4148fa00d
qiao-zhang/leetcode_problems
/algorithms/_101_symmetric_tree.py
1,243
4
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ def traver...
7301f560b8ce2d0196fcc98ecfcea1349f7a0728
qiao-zhang/leetcode_problems
/algorithms/_125_valid_palindrome.py
514
3.625
4
import re class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ def isPalindrome(s): l = len(s) if l <= 1: return True i, j = 0, l - 1 while i < j: if s[i] != s[j]: ...
6199b413403a64c174a4244e16829ee34a5d1289
qiao-zhang/leetcode_problems
/algorithms/_144_binary_tree_preorder_traversal.py
739
3.84375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ ...
7cc4b06ac2e22495cfdc610294a55f385e69d31e
qiao-zhang/leetcode_problems
/algorithms/_235_lowest_common_ancestor_of_a_binary_search.py
717
3.765625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :t...
03c0c73e6909fc68d16903e56c15bb8bc37713ec
shahdadgh/DeepNetSimulator
/ParsingAlgorithm.py
1,960
3.65625
4
def parsing_func(file, keyword, pattern): import re match = False with open(file, 'r') as f: searchlines = f.readlines() for i, line in enumerate(searchlines): result = re.match(keyword, line) if result == None: continue elif result.group(0...
80ae5b72cf646fca3bbff76d08343c1d97607ef7
Mofmof2004/Natural_selection_Simulation
/Agent/Agent_movement/Old_versions/Search_for_food_old_version.py
5,266
3.796875
4
from Simulation.Display_settings import * import numpy from Simulation.Array import world_array def search_for_food_main_old_version(agent_list, num): """ used to to make agent search and find food :param agent_list: agent list :param num: agent identity """ # if food in agent s...
f17aef8a67fdcec5aaf4fd0a26da331e3c0f7d00
Mofmof2004/Natural_selection_Simulation
/Agent/Agent_movement/Go_home.py
3,691
3.640625
4
from Simulation.Display_settings import * from Agent.Agent_movement.Energy_cost import energy_cost def go_home(agent_list, num): """ Used to move agent to the nearest home :param agent_list: agent list :param num: agent identity """ # if nearest home position is not recorded in a...
b75616ab73c91c876455bba48edef001463d179f
sh2an3nu/illustrous-panda
/balanced parantheses.py
327
3.96875
4
import stack """only for one kind of parantheses""" s=input("Enter the parantheses: ") obj = Stack() for i in s: if i=="(": obj.push(i) else: x=obj.pop() if not x: print("Not Balanced") break else: x=obj.pop() print("Balanced") if not x else print("Not Bal...
aeb64ced021f455470024db191312ef3edb083bc
izgebayyurt/asteroids
/collision.py
18,831
3.65625
4
# Bruce A. Maxwell # CS 151S # Fall 2015 # # Project 11 # Collision handler # # Modified by Eric Aaron, Fall 2018 import physics_objects as pho import math # utility math function for calculating Euclidean length of a 2D vector def length(v): return math.sqrt(v[0]*v[0] + v[1]*v[1]) # utility math function for cr...
f6cff810780cdbb8e3c5ae1f490baefd0a11fd3a
MichaelAuditore/prime_code
/bloque_hexa.py
1,303
3.59375
4
#!/usr/bin/python3 """Modulo para identificar una trama hexadecimal""" def convertir_a_binario(bloque, scale=16, num_bits=16): """Convierte un bloque hexadecimal a un binario de 16 bits """ # Convierto a binario y elimino el primer bit perteneciente al encendido # o apagado binario = (bin(int(bloque,...
3e0b6aabf422cb45f6d7620b069505c166532900
hasanalgul/UsakGorselProgramlamaVize
/soru2.py
365
3.625
4
adres="www.alierbey.com" for y in range(len(adres)) : if (adres[y:]==".com"): print("İnternet adresi doğrulandı ") break if (adres[y:]==".net"): print("İnternet adresi doğrulandı") break if (adres[y:]==".org"): print(" İnternet adresi doğrulandı ") break els...
bd14fed2eac157d7aa95b5f0494e4da101471b2a
Jepsonite/linear_regression
/src/linear.py
2,109
3.5625
4
import csv from functools import reduce import matplotlib.pyplot as plt import numpy def sum(listOfPoints): summa = reduce((lambda x, y: x + y), listOfPoints) # print('summa on ' + str(summa)) return summa def gradient(someList): return float(len(someList) * sum(get_xy(someList)) - sum(get_x(someList...
dd7fd259b3c62ccd99a5c7f50c60bc27fbc339a8
kzrl/python-playground
/lists/lists.py
699
3.921875
4
def main(): money = """Money, get away Get a good job with more pay and you're okay Money, it's a gas Grab that cash with both hands and make a stash New car, caviar, four-star daydream Think I'll buy me a football team""" money = money.strip() money = money.replace(",", "") money = money.replace("\n",...
8320454f3091a2a615c2b705e21b7030af04bc5a
tohutohu/Project_Euler
/problem9.py
194
3.546875
4
for c in range(1001): for b in range(c): for a in range(b): if a*a + b*b == c*c and 1000 == a + b + c: print(str(a) + str(b) + str(c)) print("Answer:" + str(a*b*c))
bf379a64f1ccc1cd34240c299787b99782e777c8
oneandzeroteam/python
/rhino/최댓값index.py
132
3.640625
4
list = [17,92,13,22,55,40] # print(max(list)) maxi = 0 for i in list: if maxi < i: maxi = i print(list.index(maxi))
8981b2b3534d9edd5483c752899e2b41cfa97d08
oneandzeroteam/python
/ksk/sigma.py
137
3.953125
4
def sigma(num): if num == 1: return 1 else: return num + sigma(num-1) number = int(input()) print(sigma(number))
a4e6c461cea4d86d34094af65ca4ee743b7be922
oneandzeroteam/python
/dev.garam.seo/factorial.py
227
4.25
4
#factorial.py factorial = 1 number = int (input ("input the number wanted to factorial: ")) print (number) if (number == 1): factorial = 1 else : for i in range (1, number+1): factorial = factorial * i print (factorial)
b3bfdcdb4c4f83f5123fe368afd7bcce97b649f1
oneandzeroteam/python
/ksk/sigmaSquare.py
165
3.984375
4
def sigmaSquare(num): if num == 1: return 1 else: return num * num + sigmaSquare(num - 1) number = int(input()) print(sigmaSquare(number))
e06076d4ed600153ad7606e2157d0a534e5616e8
oneandzeroteam/python
/purificationheo/find_max_index.py
194
3.703125
4
#find_max2.py def find_max(a): n = len(a) max_index = 0 for i in range(1,n): if a[i]>a[max_index]: max_index = i return max_index list=[17,92,18,33,58,7,33,42] print(find_max(list))
c5b0d894bcf1eee9b49fbb1300676c3ce83c8aa4
oneandzeroteam/python
/ksk/findMin.py
198
3.640625
4
def find_small(n_list): minimum = n_list[0] for i in n_list[1:]: if i < minimum: minimum = i print(minimum) li = list(map(int, input().split(' '))) find_small(li)
a18d91f277a5ba1d10e87d2907b1b965ec262e99
judeebene/Dynamic-programming
/countEdges.py
857
3.53125
4
# f (n) = (n - 1) + f (n - 1) # f (0) = 0 def countEdges1(n): table = [[] for i in range(n)] sum = 0 for i in range(n): # add all edge that are linked # to the current vertex sum += i table.append(sum) return sum // 2 #1- It is n(n-1)/2 for undirected. ...
39a7830b0ac7f55e1657e746b1aee777e964f0c3
WhySongtao/Leetcode-Explained
/python/105_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.py
1,686
3.890625
4
# Firstly, when seeing preorder, inorder, I will have a think about their property firstself. # Preorder: we will visit the root node first. # Inorder: we will visit all the left child first and then root node and then right child. # So the idea is to find the value of root node from Preorder, then use this value to fi...
792a69530fb10f0e7197c170f3b9978bf79f4d63
WhySongtao/Leetcode-Explained
/python/33_Search_in_Rotated_Sorted_Array.py
1,185
4
4
# Thought: What makes this question different from a normal binary search is that # in this question, there is an increase followed by an decrease. Depending on # whether the middle point is in the increasing part or the decreasing part, we # will shrink the size differently. So the first solution is simply state all #...
98b8353fedd8c1efa32ef163d62ba63c9cf169c2
WhySongtao/Leetcode-Explained
/python/240_Search_a_2D_Matrix_II.py
1,350
4.125
4
''' Thought: When I saw something like sorted, I will always check if binary search can be used to shrink the range. Here is the same. [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ] Take this as an example. First let's go to the middle of the f...
bde738c30716c5b6cf02846cee9adb41eb76f472
Suresh2304/DS_ML-DL
/1. Python/1.basic-containers.py
194
3.53125
4
#understanding basic types #types are inferred by runtime automatically a = 10.1 print(a) print(type(a)) b = 13.6 print(type(b)) c = 'abc' print(type(c)) e = False print(e) print(type(e))
68b1b5752344d5bfed268444440e8a83c36a39e9
xuhaocuhk/TilinGNN
/tiling/tile_graph.py
16,349
3.59375
4
# Python3 Program to print BFS traversal # from a given source vertex. BFS(int s) # traverses vertices reachable from s. from collections import defaultdict import numpy as np import itertools import math import pickle import util.tiling_util as tiling_util from tiling.tile import Tile EPS = 1e-5 ONE_HOT_EPS = 1e-3 # f...
a19cc14e92f1411c73f52d68c8909071f73c9a4d
Shubhankar-wdsn/Cyberpunkstyle_plotting
/Rought.py
170
3.65625
4
import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({'A': [1,3,4,6,1,3,2], 'B': [3,2,5,7,3,6,1]}) df.plot(marker='o') plt.show()
790f70a17d094c6e2045478d80e0ddf5cf685514
MinahManyama19/DSSG19-Cochrane-PUBLIC
/src/models/probs_to_preds.py
1,928
3.625
4
import pandas as pd import numpy as np def probs_to_preds(probs, threshold): """ Convert probability scores from a model to binary predictions based on a threshold or a series of thresholds for each class. Parameters ========== probs : pd.DataFrame Probabilities of each observation belong...
a21d339c2eca4f647d0a8632988e534dea32c7cd
vasanthnaik/HacktoberFest2020-1
/Calculator.py
4,377
4.1875
4
def addition(): a = float(input("Enter First Number:-")) b = float(input("Enter Second Number:-")) print("Sum of Entered numbers is ", a+b) print("1.)To calculate Again.\n2.)To exit program.\n3.)For main menu.") a = int(input("Enter the Choice:-")) if a == 1: addition() elif ...
86786e15187d45e8fe713b4a1044bfd12d595bc2
NIKKILPRITHVIN/Bell-Curve
/normaldistribution5.py
3,507
3.515625
4
import pandas as pd import statistics import csv df=pd.read_csv("height-weight.csv") height_list=df["Height(Inches)"].to_list() weight_list=df["Weight(Pounds)"].to_list() height_mean=statistics.mean(height_list) weight_mean=statistics.mean(weight_list) height_std_deviation=statistics.stdev(height_list) weigh...
303545ebcd99bd279dfb18b0c2773f8e8e9896e5
renmay/Arithmetic-demo
/demo/py/stringDemo.py
144
3.796875
4
# 先让最大值max等于0,如果i大于max就把这个i复制给max max = 0 for i in range(100): if i > max: max = i print(max)
5f5195771b564ee5a0fe6ab93bc3d066612162a0
iammdalamin/Data-Structure
/Linked List/himu_LL_insert05.py
3,296
4.34375
4
# node structure class Node: def __init__(self, data): self.data = data self.next = None #class Linked List class LinkedList: def __init__(self): self.head = None #Add new element at the end of the list def push_back(self, newElement): newNode = Node(newElement) if(self.head == None): ...
4d464d10e4f8fb674b1c5b2731076c8f953b5a16
iammdalamin/Data-Structure
/Selection Sorting/selection_sort-05.py
485
3.9375
4
def select_sort(data_list): length = len(data_list) for i in range(length - 1): min_index = i for j in range(i + 1, length): if data_list[j] < data_list[min_index]: min_index = j if min_index != i: temp = data_list[i] data_lis...
e735d490e3399fa88412f1aa9450edd63af5770a
Franksas/Study
/Python/Day03/day04.py
307
3.828125
4
name = input('请输入姓名:') age = input('请输入年龄:') job = input('请输入工作:') hobbie = input('你的爱好:') msg = '''-----------info of %s-------------- Name : %s age : %s job : %s Hobbie: %s -----------------------end------------------'''%(name,age,job,hobbie) print(msg)
4dc58b2f72d4602b7bc7c45384b5d0a940660012
MattimusRex/AdventOfCode2018
/Advent of Code 2018/Day 10/10_1_2.py
2,331
3.609375
4
class Node: def __init__(self, id, pos, vel): self.id = id self.pos = pos self.vel = vel def advance(self): x = self.pos[0] + self.vel[0] y = self.pos[1] + self.vel[1] self.pos = (x, y) def get_distance(self, node): x_dist = node.pos[0] -...
25b79b3e8ef70def365cceff0bf2fc0f09485e67
tsharanya18/Python
/basics/printformats.py
155
4.1875
4
name = input("Enter a name: ") age = input("Enter a age: ") print("Hello, " + name + "! You are " + age) print("Hello, {}! You are {}".format(name, age))
b928b09a4b3e417316274d2bd19ddccf31198aff
LeftySolara/Projects
/Classic Algorithms/Collatz_Conjecture/collatz.py
606
4.1875
4
""" Collatz Conjecture: Start with a number n > 1. Find the number of steps it takes to reach one using the following process: If n is even, divide it by 2. If n is odd, multiply it by 3 and add 1 """ try: n = int(input("Enter a number greater than one: ")) if n <= 1: print("Invalid input")...
80f8377d734ff1a9f51ea52956ddbdb172456b78
lachlankerr/AdventOfCode2020
/AdventOfCode2020/day09.py
1,883
4.15625
4
''' Day 09: https://adventofcode.com/2020/day/9 ''' def read_input(): ''' Reads the input file and returns a list of all the lines ''' lines = [] with open('day09input.txt') as f: lines = f.read().splitlines() lines = list(map(int, lines)) # convert list to ints return li...
286eec71c02f54a5287d3f6d0f68d9135cf0e472
lachlankerr/AdventOfCode2020
/AdventOfCode2020/day10.py
2,383
4
4
''' Day 10: https://adventofcode.com/2020/day/10 ''' def read_input(): ''' Reads the input file and returns a list of all the lines ''' lines = [] with open('day10input.txt') as f: lines = f.read().splitlines() lines = list(map(int, lines)) # convert list to ints return l...
90251aa6711f4db8af28ce75d89e4de26552f4a6
danielmaddern/DailyProgrammer
/easy_challenge_1/challange.py
611
4.25
4
""" create a program that will ask the users name, age, and reddit username. have it tell them the information back, in the format: your name is (blank), you are (blank) years old, and your username is (blank) for extra credit, have the program log this information in a file to be accessed later. """ name = raw_input(...
d6aa5790686baec06d4d738288d223fcd1433b2b
JaiminBhagat5021/CyberstormGriffin
/XOR.py
996
3.78125
4
###################################################################################################### # Name: Jaimin Bhagat # Date: 4/23/2020 # Description: XOR crypto method, takes a message(plain text or cipher text) and a key and XOR's them #producing an XOR cipher or decipher (Done in Python 2.7.17)...
95909aedf1cfe36615f0616c55e6d3ed110b39b7
alphabits/yogaunity-app
/backend/stringhelpers.py
401
3.8125
4
import re import unittest first_cap_re = re.compile('(.)([A-Z][a-z]+)') all_cap_re = re.compile('([a-z0-9])([A-Z])') def pascalcase_to_dash(s, dash="-"): s1 = first_cap_re.sub(r'\1{0}\2'.format(dash), s) return all_cap_re.sub(r'\1{0}\2'.format(dash), s1).lower() def dash_to_pascalcase(s, dash="-"): par...
23367bdfdbdddee1d615fb7322218262cecce0ed
yaminmousselli/school
/Georgia Tech/math/Math_3012/project/Dijkstra.py
3,989
4.15625
4
""" I wrote the script to create the Edge Set from the 3.txt file you provided us. I wrote main(), createEdgeSet(), and findoptimalpaths(graph, origin, destination). The Edge Set prints to the command line after executing the script. To give credit, I used the following resources: https://gist.github.com/econchick...
e6188316fecfb8dbe3bddf5df9d444f4d51a6a8b
b12angel/Diplomado-SIC-UAM-2021-G4
/print("Hello world").py
1,238
3.5
4
print("Hello World") print("Ezequiel Rodriguez R") import GPIO.rfi as GPIO pin = 40 print("Hello world") print("Rafael Gonzalez Martinez") print("Merle Yuridia Meza") print("Hello world") print("Rafael Gonzalez Martinez") print("Jorge Miron") print("Marlen Moran Camero_modificar") print("Erick Raul Loza DOminguez")...
a387cf599368615dd0a2692e934c3d0adf5c6f1b
shashacode/Notepad
/notepad.py
2,882
3.984375
4
from datetime import date class User(): def __init__(self, name, email, phone): self.name = name self.email = email self.phone = phone self.is_logged_in = False def user_acct(self): self.name = input('Please enter name: ') self.email = input('Please ent...
79bbe6e5aea90bee254e8f20d9b4e67ccb2124a1
jberezow/fys3012_takehomeexam
/Task2 - FDA.py
4,983
3.578125
4
# -*- coding: utf-8 -*- """ Status: COMPLETE Created on Mon Oct 21 14:47:00 2019 FYS - 3002: Pattern Recognition Take-Home Exam Task 2a, 2b - FDA w/ PCA Comparison ----------------------------------- Implement FDA and use it to classify the data set. Split the data set into training data and test data. S...
5bc53494fea4b54fcde00ef55f03d3be4a93a2a8
WenboWong/Python-Geography-spatial-analysis
/Python Geography spatial analysis/chapter5 Python与地理信息系统/Pythagoras.py
347
4.15625
4
#Pythagoras .py #投影坐标计算距离 import math '''x1=456456.23 y1=1279721.064 x2=576628.34 y2=1071740.33 x_dist=x1-x2 y_dist=y1-y2 dist_sq=x_dist**2+y_dist**2 distance=math.sqrt(dist_sq) print("距离为:{0}".format(distance)) ''' #十进制计算度数进行距离量算 x1=-90.21 y1=32.31 x2=-88.95 y2=30.43 x_dist=math.radians(x1-x2)
245702eb570e8bfe00ca0e3fc85a4860be5ea82b
WenboWong/Python-Geography-spatial-analysis
/Python Geography spatial analysis/chapter5 Python与地理信息系统/方位计算.py
311
3.59375
4
# -*- coding: utf-8 -*- """ Created on Sat Jan 25 17:31:06 2020 @author: 立文 """ from math import atan2,cos,sin,degrees lon1=-90.21 lat1=32.31 lon2=-88.95 lat2=30.43 angle=atan2(cos(lat1)*sin(lat2)-sin(lat1)*cos(lat2)*cos(lon2-lon1),sin(lon2-lon1)*cos(lat2)) bearing=(degrees(angle)+360)%360 print(bearing)
8598ccd11746fd9b25241d72148e8ca4958d6943
San0506/Python-String-Manipulation-Coded
/Remove_Dup_from_String.py
269
3.84375
4
# =================================to remove duplicate from a string and return sorted one =================== def test123(var1): b = set(var1) return ''.join(b) if __name__ == "__main__": a = 'sankalppp' print(test123(a)) print(set(a))
69e98516e7e118d600d104ffcdb05479325efd9d
polinavolos/programming_practice
/week02/hw1/task7.py
144
3.921875
4
def even_or_not(a): even_elem = [] for i in range(0, len(a), 2): print(a[i], end=' ') list = input().split() even_or_not(list)
14e8b6a170a4b5bd535610033c9a276a91f41720
ldarrick/summer2016_research
/clustering/featurecluster.py
9,477
3.71875
4
# # Last modified: 20 June 2016 # Authors: Darrick Lee <y.l.darrick@gmail.com> # Description: The class definition which takes in a set of feature vectors in a csv file and can # perform various methods of clustering and analysis on it # # Note about variable names: # clist refers to the list of features to cluster, ...
21635b5283ff844d69ae13f3ca4208f6ba6a83ea
leah-clark/matchscheduler
/server/data_processing/competitions.py
613
3.5
4
''' for each competition, find the priority in hours and add to a dictionary eg. {'Championship': 12} as Championship is priority 1 = 12 hours ''' def get_competition_priorities_kv_pair(priorities, competitions): priorities = priorities.set_index('Priority Class') pairs = {} for comp in competitions.itert...
3800ded9102221c5c65c29b473d8d693feefc6c9
MichaelDc86/Algorythms
/lesson_08/task_1.py
1,095
3.59375
4
# Определение количества различных подстрок с использованием хеш-функции. # Пусть на вход функции дана строка. Требуется вернуть количество различных подстрок в этой строке. # Примечание: в сумму не включаем пустую строку и строку целиком. # Пример работы функции: # func("papa") # 6 # func("sova") # 9 import hashlib ...
5c4a568dd42ba15a1998988a4147b9002525ccdd
MichaelDc86/Algorythms
/lesson_04/task_1.py
3,310
3.921875
4
# В одномерном массиве целых чисел определить два наименьших элемента. # Они могут быть как равны между собой (оба являться минимальными), так и различаться. # Вариант с использованием рекурсии для поиска минимальных элементов import random # import timeit import cProfile def find_minimals(values): min_val = v...
35cf1ad32b02ae5e60a20e0511e5b0e92e835b76
MichaelDc86/Algorythms
/lesson_02/task_5.py
797
4.3125
4
# Вывести наэкран коды и символы таблицы ASCII, начиная с символа под номером 32 и заканчивая 127 - м включительно. # Вывод выполнить в табличной форме: по десять пар "код-символ" в каждой строке.. def print_symbol(symbol_code): if (symbol_code - 2) % 10 == 0: print() print(f'{symbol_code}-{chr(symbol...
fc65fc48452adbf19a9ef80b4d3382656313f168
MichaelDc86/Algorythms
/lesson_03/task_1.py
466
3.984375
4
# В диапазоне натуральных чисел от 2 до 99 определить, сколько из них кратны любому из чисел в диапазоне от 2 до 9.. final_range = [] for i in range(2, 100): for j in range(2, 10): if i % j == 0: final_range.append(i) break print(f'Всего кратных любому из диапазона от 2 до 9: {len...
72a21a019adcc21cc87036b3fa3429502a785b88
MichaelDc86/Algorythms
/lesson_05/task_1.py
2,487
3.953125
4
# Пользователь вводит данные о количестве предприятий, # их наименования и прибыль за 4 квартал (т.е. 4 числа) для каждого предприятия. # Программа должна определить среднюю прибыль (за год для всех предприятий) # и отдельно вывести наименования предприятий, чья прибыль выше среднего и ниже среднего. from collection...
17140dccdc96de449cac75b4cf97c36a1591e516
michaeltintiuc/python-percentile-rank
/src/percentile_rank/rank_calculator.py
1,176
3.546875
4
from collections import Counter class RankCalculator(): """ Calculate percentile rank based on index """ @staticmethod def flipUniqueList(list): """ Parse passed list Return a dict of unique values """ dict = {} for i, v in list.iteritems(): ...
23a34af5911aa4cb064504f466e05bc6a05cf4aa
suleymanov/higgs-ml
/logreg.py
1,832
3.640625
4
import math, numpy as np import matplotlib.pyplot as plt from scipy.optimize import minimize def logreg(X, y) : ''' Logistic regression minimization using gradient descent. Takes X as matrix of features, y as binary income (0 or 1). Returns Theta - array of trained coefficients. ''' (m, n) = X.shape Theta = ...
d21b8dac69443bb588d3e0244364cd97d41debca
arunvenkatram/python
/multifunction.py
298
3.921875
4
#!/bin/python message = raw_input("Enter the message to be echoed: ") count = raw_input("enter the number if times to echo the message: ").strip() if count: count = int(count) def echo_func(message, count): while count > 0: print(message) count -=1 echo_func(message, count)
8a69899ac973fc94d1b2a41b4543446a137ef808
arunvenkatram/python
/aptry.py
628
3.890625
4
#!/bin/python import argparse parser = argparse.ArgumentParser(description="Read the filename in reverse") parser.add_argument("filename" , help='enter the filename to be read') parser.add_argument('--limit', '-l', type=int, help="number of files to read") parser.add_argument('--version', '-v', action='version', versio...
58d9a04624764a5c3f52da35980ccdbacbcd0e2d
LuisaFranco23/ESTRUCTURA-DE-DATOS.
/JORNADA.py
782
3.703125
4
class DEBER: def __init__(self): pass def CalcularJornada(self): HORAST, HORASEX, HORASET = 0, 0, 0 ph, phe, pt, ph8 = 0, 0, 0, 0 ht = int(input("Ingrese horas trabajadas : ")) ph = float(input("ingrese valor hora : ")) if HORAST > 40: HORAS...
9327550487488551029463ddfc5db24d5ae8880e
LuisaFranco23/ESTRUCTURA-DE-DATOS.
/C aprobado.py
196
3.78125
4
class nota1(): def Calificaciones(self): C=float(input("Ingrese calificación : ")) if C>=8: print("Aprobado") print() nota=nota1() nota.Calificaciones()
db43912f65812dc9d28bd308d9d264fcd73d7364
LuisaFranco23/ESTRUCTURA-DE-DATOS.
/numeros 150.py
239
3.546875
4
class presentar(): def presentarnumeros(self): x = 1 print("Presentar los 150 numeros") while x <= 150: print(x) x = x + 1 presenta = presentar() presenta.presentarnumeros()
d6dd4b93c7acca3febd52ec6368a965a2df7b748
pearlpatel207/LMS-test
/test.py
261
3.875
4
import sqlite3 from queries import * db = sqlite3.connect('LIB') cursor = db.cursor() cursor.execute('SELECT * FROM books') for row in cursor.fetchall(): print(row) cursor.execute('SELECT * FROM books_issued') for row in cursor.fetchall(): print(row)
7f940c718fb28adf66a3c6642517a66ba153fffa
spiderbites/advent-of-code-2019
/d11/main.py
5,899
3.5
4
#!./bin/python import os from PIL import Image POSITION = 0 IMMEDIATE = 1 RELATIVE = 2 class Robot: LEFT = 0 RIGHT = 1 BLACK = 0 WHITE = 1 def __init__(self, squares={}): self.squares = squares self.position = [0, 0] self.direction = 'U' def serialize(self, x): ...
79bf820e90880a8f8b325d9d783f04f65c716143
safwanc/python-sandbox
/sorting/radix.py
638
3.78125
4
''' Radix Sort Runtime: O(kn) Space: O(n) ''' def radix_sort(array): buckets = [list() for _ in range(10)] max_value = max(array) divisor = 1 while max_value > divisor: for num in array: buckets[(num // divisor) % 10].append(num) print('Bucketed by {}s:'.format(divisor), bu...
0707279e8daed7ee79e41d9ad565c809547d92e6
safwanc/python-sandbox
/dynamic-programming/lis.py
605
3.578125
4
''' Longest Increasing Subsequence ''' nums = [10, 22, 9, 33, 21, 50, 41, 60, 80] def brute_force(nums, i=len(nums), upper_bound=float('inf')): if i == 0: return 0 elif nums[i-1] > upper_bound: return brute_force(nums, i-1, upper_bound) else: return max(1 + brute_force(nums, i-1, nums[i-1]), brute_force(n...
2b451462e3b1e69fca7e9488ccf92aba5d1aed87
safwanc/python-sandbox
/strings/palindrome.py
216
3.84375
4
is_palindrome = lambda string: all(string[i] == string[~i] for i in range(len(string) // 2 + 1)) strings = [ 'aba', 'aa', 'b', 'baa' ] for string in strings: print(string, is_palindrome(string))
66a3c00d932f4004c3fc5709c5c3169294f59cac
safwanc/python-sandbox
/sorting/selection.py
532
3.625
4
''' Selection Sort Runtime: O(n^2) & Space: O(1) ''' import operator def selection_sort(array): array_slice_from = lambda start_index: ((i, array[i]) for i in range(start_index, len(array))) for index, value in enumerate(array): min_index, min_value = min(array_slice_from(index), key=operator.itemgette...
30d6b91e9f6b207c10ada126bd415113cc5ed95f
safwanc/python-sandbox
/data-structures/singly-linked-list.py
2,870
3.84375
4
class LinkedListNode(object): def __init__(self, value): self.value = value self.next = None def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ return other == self.value def __str__(self): return se...
19645980e10e562c4654c95210d5a4e0fab2c125
yichenhsiaonz/01_recipes
/component_7_split_inputs.py
699
3.875
4
# Component 11. import re print("please put a comma in between the amount, unit, and name") loop = "" while loop == "": try: user_input = input("Please enter an ingredient listed in the recipe in the order of amount, unit, then name") if len(re.findall(",", user_input)) > 2: raise Val...
c3d5e905492962a237d66b637eced1f83f1f90e1
gubnota/convert_bkrs
/py/u/__init__.py
667
3.71875
4
# -*- coding: utf-8 -*- """converting utf strings to unicode and vice-versa""" __all__ = ('u', 'utf') def u(s): "convert anything to unicode" if isinstance(s, unicode): return s try: s = unicode(s) except UnicodeDecodeError: s = str(s) s = s.decode("utf-8") return ...
86d3a10da395229256de0ccb479486370243bb05
gubnota/convert_bkrs
/py/progress_bar/progress_bar.py
2,394
3.734375
4
#!/usr/bin/env python # -*- coding: UTF-8 -*- import math __all__ = ['ProgressBar'] class ProgressBar(object): """графическое представление продвижения прогресса""" __slots__ = ('_min', '_max', '_value', '_width') def __init__(self, min, max, width, value=None): self.set_min(min) self.s...
cbb462089099d7005231f2511073e20f26d49bb5
bugraaldal/Advent-of-Code-2020
/Day08/Day8.py
2,633
3.53125
4
#import os #os.chdir("/home/buura/Desktop/Python/AdventOfCode2020") """ I turns out I've deleted the second part's answer, so I had to come up with it again. I've actually used a brute force approach at first. Then changed it in an attempt to find a more efficent solution. """ import copy # Setting up some lis...
ed819c046c2f6ca5b27d0ce9fec4d9de3fc3c0d9
PhilipSpechler/csvnome
/csvnome3
6,049
3.84375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import csv from collections import Counter import argparse parser = argparse.ArgumentParser(description= """ This is a python tool used to get a fast look at the contents of a given csv. Run it from the command line! BASIC USAGE: ============ $ csv...
76b089f6b346f17c1586d9209cd53eaf60225248
ruzeena/Hackerrank
/hack11.py
464
3.875
4
input_string=input("Enter String") length=len(input_string) odd_list=[] for i in range(0,length,2): odd_list.append(input_string[i]) odd_result = "".join(str(x) for x in odd_list) even_list=[] for i in range(1,length,2): even_list.append(input_string[i]) even_result = "".join(str(x) for x in even_list) New_...
2bb35a97511d674d6034b488b23d833513188c9b
madecai/learn-python
/learn_python_02/openpyxl_test/02.excel读取.py
1,086
3.5
4
import openpyxl # data_only=True读取数据而不是公式的计算结果 book = openpyxl.load_workbook('test01.xlsx', data_only=True) sheet = book.active # 获取方式一 a1 = sheet['A1'] a2 = sheet['A2'] # 获取方式二 a3 = sheet.cell(row=3, column=1) print(a1.value, a2.value, a3.value) # 获取方式三 print('===========区间获取,返回每行cell的元组') cells = sheet['A1': 'B6'...
d85ccd5f1467f9cf90aa5d491d593741cf201a64
madecai/learn-python
/learn_python_01/14_文档字符串.py
449
3.703125
4
print('======================================================可以使用help(函数查看python中的函数用法') help(print) print('======================================================文档字符串') def test01(a:int, b:bool, c:str='hello') : ''' 文档字符串示例 函数的作用。。。 函数的参数: a,作用,类型,默认值 b,作用,类型,默认值 c,作用,类型,默认值 ''' return 10 help(test01)
1e6644fa9abb1d7f54f5c138895bb00c505c005d
madecai/learn-python
/learn_python_01/15_作用域与命名空间.py
1,041
3.6875
4
print('===============================================================变量作用域') a = 10 # 全局变量 def test01() : a = 20 test01() print('不会改变全局变量的值', a) # 10 def test02() : global a # 使用global声明,后面使用的就是全局的a a = 20 test02() print('会改变全局变量的值', a) # 20 print('===============================================================全局...
7e9aaaa7007db78cbe5b9e7021b1a302e66ff462
TheMagicNacho/resolve
/angle.py
1,415
3.65625
4
""" This script will resolve the angle of attack for a direct fire mission of a rocket to an ENY location. All units are in metric, except for the degree translation REF: https://www.mathsisfun.com/algebra/trig-finding-angle-right-triangle.html https://betterexplained.com/articles/intuitive-trigonometry/ """ # Import...
57d424e5c044c56dfb7aacf10f0ec45dd2ba34a3
yathie/machine-learning
/aprendizado_supervisionado.py
569
3.765625
4
#Algoritmo para aprender todos os atributos e os nomes dos animais, e o conhecimento obtido com esses dados é usado para testar novos animais. from sklearn import tree features = [[7, 0.6, 40], [7, 0.6, 41], [37, 600, 37], [37, 600, 38]] labels = ["chicken", "chicken", "horse", "horse"] #labels = [0, 0, 1, 1] classi...
cc68d3d33daad46d3395e152c04d2ca0786fdb99
yathie/machine-learning
/ex8-basico-python.py
520
4.1875
4
'''faça um programa que leia um valor e apresente o número de Fibinacci correspondente a este valor lido. Lembre que os primeiros elementos sa série de Fibonacci são 0 e 1 e cada próximo termo é a soma dos 2 anteriores a ele. 0 1 1 2 3 5... ''' posicao = int(input("Digite uma posição: ")) def fib(x): seq = [0, 1, 1] ...
935c02819ca25d2b0a5922084e734991188b462a
tjbyars/FizzBuzz
/FB1-Simple.py
334
3.671875
4
# FizzBuzz 1 - Simple # Run file and outputs to shell # Runs through 1 to 100 # Using if...else for i in range(1, 101): out = "" if (i % 3 == 0): out = "Fizz" if (i % 5 == 0): out = "Buzz" if (i % 3 == 0) and (i % 5 == 0): out = "FizzBuzz" if len(out) == 0: out = i ...
e702b9b05531acd8759b9700da40fac1f1b3d403
LorgioPython/PythonRiva
/MCD.py
559
3.796875
4
# programa q halla el MCD def MCD(x,y): if x>y: r=x%y while r>0: b=r r=y%r y=b if r==0: pass return y else: r=y%x while r>0: b=r r=x%r x=b if r==0: pass return x print "ingresa dos numeros a los cuales quieras hal...