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
e57bca182bc567be3152a18687e449d6851fd211
felidadae/_general
/algorithms/tree-summing-simple/main.py
1,822
3.53125
4
class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def __repr__(self): left_child = self.left.val if self.left else "X" right_child = self.right.val if self.right else "X" return "Val {}. Child left {}. Child right {}.".form...
10c4f4cab68cbe538e986bb39effc4981c970f0f
suresh-kodiak/python-unit-func-tests
/calc_module/calc.py
144
3.78125
4
def add(x, y): return x + y def divide(x, y): if (y == 0): raise ValueError("Can not divide by Zero") return x / y
8735b4da56d658d4dd54bc749d51f594f0d07dec
oc-cs170/scroller
/scroller.py
1,983
3.5625
4
#!/usr/bin/env python """Main file with game loop for Scroller. """ import pygame from hero import Hero import world from parameters import * WINDOW_TITLE = 'Scroller' FPS = 30 class Scroller(object): """Create a game of Scroller.""" def __init__(self): pygame.init() pygame.key.set_repeat(1...
1f753ef537ed21d6fc2212076fa8152508126240
CSP-NBTHS-idhrolia/iterative-prisoners-dilemma1
/period3/team1.py
2,904
3.5625
4
#### # Each team's file must define four tokens: # team_name: a string # strategy_name: a string # strategy_description: a string # move: A function that returns 'c' or 'b' #### import random team_name = 'Team1' # Only 10 chars displayed. strategy_name = 'Good Boi Points' strategy_description = 'Always...
e7debe4f8bca647018fafd36d7fe7378096e49d1
simran1991/PythonProject
/code/Drawing.py
748
3.734375
4
import numpy as np import cv2 #creating array of 300x300 with each cell having 24 bits to represet 3 channels canvas=np.zeros((300,300,3),dtype="uint8") green=(0,255,0) #line function first argument is image on which we want to draw #second arg start coordinate #third end coordinate #fourth color #fifth there is fifth...
7ea198d09b21f48d6a5db1acf49c108837652c66
paola-md/MLproject1
/src/costs.py
2,355
3.703125
4
import numpy as np def calculate_error(y, tx, w): """ Computes the error vector. :param y: np.array with the labels :param tx: np.array with the features :param w: np.array with the weights :returns: error_vector: np.array of the error vector """ return y - tx.dot(w) def cal...
0e41dcca0c8d52a2885bf6d8ee595690ed3ff527
kadnan/python-fundamentals
/p10-args.py
222
3.921875
4
import sys args = sys.argv if len(args) != 2: print('This is not the correct format') else: number = int(args[1]) if number < 10: print(' It is less than 10') else: print('Something else')
e25319fe7efb431b6b8c1e7b7c89db06c78980bb
AdamFeng/learning_mofan
/numpy/04_numpy_index.py
387
4.03125
4
# numpy 索引 import numpy as np A = np.arange(3,15).reshape(3,4) print(A) print(A[2][1]) # ==A[2,1] print(A[2,:]) # 第2行所有数 print(A[:,1]) # 第1列所有数 # 打印每一行 for row in A: print(row) # 打印每一列 for column in A.T: print(column) print(A.flatten()) # 把矩阵变成单行 #打印矩阵中每个元素 for item in A.flat: print(item)
d3c886bf9a09d15aa325f34e5c948f3bab8f825d
AdamFeng/learning_mofan
/numpy/06_numpy_array_split.py
438
3.875
4
import numpy as np A = np.arange(12).reshape((3,4)) print(A) ''' [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] ''' print(np.split(A, 2, axis=1)) # 对A进行分割,按列 print(np.split(A, 3, axis=0)) # 对A进行分割,按行 # np.split不能进行不等分割,np.array_split可以进行不等分割 print(np.array_split(A,2,axis=0)) print(np.vsplit(A,3)) # 纵向分割,按行 print(n...
779837d905d6bb57cc00894a7583279272e4146b
mihiljose/tip-calculator
/main.py
539
4.0625
4
#If the bill was $150.00, split between 5 people, with 12% tip. bill_amt = float(input("What is the bill amount?")) tip_percentage = float(input("How many percentage do you wish to tip?")) no_of_pple = int(input("How many people are splitting the bill?")) bill_with_tip = ((tip_percentage/100)*bill_amt )+ bill_amt #E...
4f84ec105ffc21122f34790e679d486f35d140c1
holoviz/panel
/panel/_param.py
3,243
3.5625
4
from param import Parameter, _is_number class Align(Parameter): """ A Parameter type to validate alignment options. Supports 'auto', 'start', 'center', 'end' or a two-tuple of these values corresponding to the (vertical, horizontal) alignment. """ def __init__(self, default='start', **params)...
1c5ae131528b6e48953212686c066c5a9736a334
brandonkbuchs/UWisc-Python-Projects
/latlon.py
2,073
4.5
4
# This program collects latitude and longitude inputs from the user and returns # Information on the location of the quadrant of the coordinate provided def latlon(latitude, longitude): # Defines function # Latitude logic tests. if latitude == 0: # Test if on equator print "That location is on the ...
1a969d2a828ec8fa39e3b980e7f5ca0ff9df3fa9
honwenle/pygit
/selection_sort.py
533
4.09375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def selection_sort(arr): size = len(arr) for i in range(size): m = i for j in range(i+1,size): if arr[j]<arr[m]: m = j if m!=i: arr[i],arr[m] = arr[m],arr[i] return arr def input_array(len): arr = [] for i in range(len): num = int(raw_input()) arr...
e95d1f3c88177b0676385d0e810f16577233ec95
honwenle/pygit
/07_slice_iteration.py
432
3.9375
4
#Slice&Iteration #Slice # (list/tuple/string)[start_index=0:end_index:step=1] print range(13)[2:-3:2] #Iteration d = {'a': 1, 'b': 2, 'c': 3} for k in d: print k for v in d.itervalues(): print v for k,v in d.iteritems(): print k,'=',v #from collections import Iterable #isinstance('abc', Iterable) #str是否可迭代 for i, ...
632bfb601e4e444b3f89451ad902e151fa715de8
maumarcastil/ejercicios_py_exercism
/raindrops/raindrops.py
377
4.0625
4
def convert(number): r = "" if number%3== 0: mensaje = "Pling" r= mensaje if number%5==0: mensaje = "Plang" r += mensaje if number%7 == 0: mensaje = "Plong" r += mensaje if number%3!=0 and number%5!=0 and number%7!= 0: re...
5c7aa866893bf32c5844620e9ab0ed54489dc10c
PromytheasN/Data_Stractures_and_Algorithms_in_python
/Chapter_2_Reinforcement.py
17,142
4.46875
4
""" R-2.1 Give three examples of life-critical software applications. """ #1) Critical life support machine software #2) Auto-drive (for self drive vehicles) software #3) Nuclear reactors software """ R-2.2 Give an example of a software application in which adaptability can mean the difference between a prolonged life...
f6abd7a46621848152dcbad14913c6d92b6e08a2
sohnryang/ecdsa-python
/ecdsa/numbertheory.py
1,599
3.703125
4
def inv_mod(n: int, p: int): """ Find a inverse of n mod p. :param n: Value of n where nx === 1 (mod p) :param p: Value of p where nx === 1 (mod p) :returns: Value of x where nx === 1 (mod p) """ return pow(n, -1, p) def legendre(a: int, p: int) -> int: """ Calculate value of Lege...
b17def2955c057eab159b0df71fb7443a6f44957
rsboggs/bradfield_algos
/solutions/graph.py
645
3.515625
4
from collections import deque class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def min_depth(self): # Needed for leetcode edge case if not self: return 0 nodes = deque() nodes.append((self, 1)) while len(nodes) > 0: current_node, ...
743a3b4bb19d7bfd0268da59f146919322a0d6de
rsboggs/bradfield_algos
/solutions/binary_search.py
491
3.75
4
def is_present(alist, item, start_index = 0, end_index = None): if not alist: return False if end_index == None: end_index = len(alist) - 1 midpoint = (end_index + start_index) // 2 if alist[midpoint] == item: return True if item < alist[midpoint]: if start_index == midpoint: return F...
5eea14c56271bb0034e0d80744730fe9bf2ea3ae
vishaldhateria/100daysofcode
/18-August-2020/changedimensions.py
523
4.1875
4
# my__1D_array = numpy.array([1, 2, 3, 4, 5]) # print my_1D_array.shape #(5,) -> 5 rows and 0 columns # my__2D_array = numpy.array([[1, 2],[3, 4],[6,5]]) # print my_2D_array.shape #(3, 2) -> 3 rows and 2 columns # change_array = numpy.array([1,2,3,4,5,6]) # change_array.shape = (3, 2) # print change_array ...
f1543191234c61c998f484d236d00c19f904295c
MrRaisin/pword_project
/fileRead.py
947
3.6875
4
#!/usr/bin/env python3 file_name = 'English_Dictionary_Full.txt' # this function checks to see if the chosen word exists in the file def checkPWD1(pwd, full_filename): try: text_file = open(full_filename, 'r') for line in text_file: if line.lower().strip('\n') == pwd.lower(): ...
e14193caa3a6ea58685a20c4e5edc903cfc6c240
devopsnagarajp/python
/Fibonacci.py
435
3.859375
4
a = 0 b = 1 f = [0,1] def Fibonacci(n): while True: #for i in range(n-2): global a global b c = a + b if c < 100: f.append(c) a = b b = c else: print("Loop is broken.") break return b #n = int(input("Ente...
659e981c2f135e1ae4e3db3d62d90d359c787e71
21eleven/leetcode-solutions
/python/0673_number_of_longest_increasing_subsequence/lsubseq.py
1,203
4.125
4
""" 673. Number of Longest Increasing Subsequence Medium Given an integer array nums, return the number of longest increasing subsequences. Example 1: Input: nums = [1,3,5,4,7] Output: 2 Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7]. Example 2: Input: nums = [2,2,2,2,2] ...
2db77e703645f2f63be84a63610e608e42135557
21eleven/leetcode-solutions
/python/1679_max_number_of_k_sum_pairs/deque.py
1,280
3.765625
4
""" 1679. Max Number of K-Sum Pairs Medium You are given an integer array nums and an integer k. In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array. Return the maximum number of operations you can perform on the array. Example 1: Input: nums = [1,2,3,4], ...
6a52d60f15ef338e27b8c62ce8c034653c0a0f2f
21eleven/leetcode-solutions
/python/0605_can_place_flowers/three_slot.py
1,411
4.15625
4
""" 605. Can Place Flowers Easy You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots. Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be...
11d6e7ccb90f264da3e42963d410f1ddebcf23db
21eleven/leetcode-solutions
/python/0859_buddy_strings/oh_n.py
1,785
3.921875
4
""" 859. Buddy Strings Easy Given two strings A and B of lowercase letters, return true if you can swap two letters in A so the result is equal to B, otherwise, return false. Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at A[i] and A[j]. For exampl...
a3f61908d09cba128724d0d6a533c59075156091
21eleven/leetcode-solutions
/python/1631_path_with_minimum_effort/bfs_w_heap.py
2,594
4.125
4
""" 1631. Path With Minimum Effort Medium You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, ...
f1b97a9131f9ea2cd9d1aa2571b72762996e8b2c
21eleven/leetcode-solutions
/python/1010_pairs_of_songs_with_total_durations_divisible_by_60/mod60_n_choose_k_or_n_times_m.py
1,293
3.609375
4
""" 1010. Pairs of Songs With Total Durations Divisible by 60 Medium You are given a list of songs where the ith song has a duration of time[i] seconds. Return the number of pairs of songs for which their total duration in seconds is divisible by 60. Formally, we want the number of indices i, j such that i < j with (...
289e010acc744601de584f78311482177cb89464
21eleven/leetcode-solutions
/python/1530_number_of_good_leaf_nodes_pairs/breadcrumbs.py
1,326
3.65625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right from itertools import combinations class Solution: def countPairs(self, root: TreeNode, distance: int) -> int: leave...
eb0d69d45fb18fcb9e0a3e0ad19379efb7ec0129
21eleven/leetcode-solutions
/python/0039_combination_sum/btrack.py
1,577
3.828125
4
""" 39. Combination Sum Medium Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. The same number may be chosen from candidates an unlimited number of t...
e0c18fc9473ba8d13347402ee31e37511091297a
21eleven/leetcode-solutions
/python/0987_vertical_order_traversal_of_a_binary_tree/lookup.py
2,097
3.96875
4
""" 987. Vertical Order Traversal of a Binary Tree Hard Given the root of a binary tree, calculate the vertical order traversal of the binary tree. For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at ...
3a9e95b11a28dbdab168e435f66ddf9f3f12cceb
21eleven/leetcode-solutions
/python/0881_boats_to_save_people/two_ptr.py
1,162
3.859375
4
""" 881. Boats to Save People Medium The i-th person has weight people[i], and each boat can carry a maximum weight of limit. Each boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most limit. Return the minimum number of boats to carry every given person. (It is g...
cc45bcaa7a2eab2cd22f4508f4b661bd8c241e0c
21eleven/leetcode-solutions
/python/0083_remove_duplucates_from_sorted_list/clip_while.py
775
3.859375
4
""" 83. Remove Duplicates from Sorted List Easy Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well. Example 1: Input: head = [1,1,2] Output: [1,2] Example 2: Input: head = [1,1,2,3,3] Output: [1,2,3] Constraints: ...
c3955b25e5b20d7a1bbec26a7f5d2d495316189f
21eleven/leetcode-solutions
/python/0449_serialize_and_deserialize_BST/array_of_array.py
2,668
3.8125
4
""" 449. Serialize and Deserialize BST Medium Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm t...
1dc082e4ffa01934841f4fc93dced3bf5f395240
21eleven/leetcode-solutions
/monthly_challenge/202008/07_vertical_order_traversal_of_binary_tree.py
1,806
3.90625
4
""" Given a binary tree, return the vertical order traversal of its nodes values. For each node at position (X, Y), its left and right children respectively will be at positions (X-1, Y-1) and (X+1, Y-1). Running a vertical line from X = -infinity to X = +infinity, whenever the vertical line touches some nodes, we re...
e91c4bf64795f3d48da6ea5289a2fba874e8fcce
21eleven/leetcode-solutions
/python/0421_maximum_xor_of_two_numbers_in_an_array/bitfiddle.py
1,071
3.8125
4
""" 421. Maximum XOR of Two Numbers in an Array Medium Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 ≤ i ≤ j < n. Follow up: Could you do this in O(n) runtime? Example 1: Input: nums = [3,10,5,25,2,8] Output: 28 Explanation: The maximum result is 5 XOR 25 = 28. Example 2...
f94958eda45f460ef60b404201ca037b7cc58f8d
21eleven/leetcode-solutions
/python/0101_symmetric_tree/oh_n.py
912
3.921875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSymmetric(self, root: TreeNode) -> bool: if root == None: return True from...
f5a8bd3373e2d1f891054c4e64a45d6065f6b54b
21eleven/leetcode-solutions
/python/0143_reorder_list/not_optimal.py
1,143
3.703125
4
""" 143. Reorder List Medium Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… You may not modify the values in the list's nodes, only nodes itself may be changed. Example 1: Given 1->2->3->4, reorder it to 1->4->2->3. Example 2: Given 1->2->3->4->5, reorder it to 1->5->2->4->3...
4e74a01383190d6b4ffcd951fae9c0256ae1f18d
yymap/python
/demos/fileio/FileNameOperation/ChangeUSDate2EUDate.py
1,567
3.859375
4
#! python3 ''' If there are many files is named with US date format, and you want to change the file name to EU date format, you can use this function. US Date format: MM-DD-YYYY EU Date format: DD-MM-YYYY ''' import os,shutil,re def renameDirFiles(dirPath): if not os.path.isdir(dirPath): return 'Not di...
a3ce1322dcac48f1ec6795b89894c9f2d195aebe
datianshi/py-leetcode
/twosum/solution_test.py
1,623
3.890625
4
import unittest from twosum.solution import Solution class TestTwoSum(unittest.TestCase): def test_two_sum_1(self): nums = [2] sl = Solution() target = 10 expected = None result = sl.two_sum(nums, target) self.assertIsNone(result, "With nums: {} and target {} it shou...
57bff5b0839f411b5e60ab12254eb167e3e0d840
Bogdanovist/smash2
/Vector.py
2,277
3.828125
4
import numpy as np import math class Vector(object): """ Utility class to make geometry easier. """ def __init__(self,x,y): self.x=x self.y=y def __add__(self,that): return(Vector(self.x+that.x,self.y+that.y)) def __sub__(self,that): return(Vector(self.x-that.x...
f52be823ee9672e15a40176fefd0506550d6b78e
gall1frey/RapidRescuer
/Task1/Task1_A/code/task_1a.py
8,495
3.875
4
# Import necessary modules # Do not import any other modules import cv2 import numpy as np import os # To enhance the maze image import image_enhancer # Maze images in task_1a_images folder have cell size of 20 pixels CELL_SIZE = 20 def readImage(img_file_path): """ Purpose: --- the fun...
0790ccdc036798bf7ce9d542345f784dd6009d39
makhmudislamov/leetcode_problems
/microsoft/arr_and_str/set_matrix_zeroes.py
2,465
4.46875
4
""" Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place. Example 1: Input: [ [1,1,1], [1,0,1], [1,1,1] ] Output: [ [1,0,1], [0,0,0], [1,0,1] ] Example 2: Input: [ [0,1,2,0], [3,4,5,2], [1,3,1,5] ] Output: [ [0,0,0,0], [0,4,5,0], ...
27a566d6f5312cf2b427d42c1e542d53a1384c21
makhmudislamov/leetcode_problems
/microsoft/arr_and_str/trapping_rain_water.py
1,224
4.28125
4
""" Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos f...
0c52d88e60bae867153bbf6b542f2f61bc5dfa69
makhmudislamov/leetcode_problems
/easy/max_profit.py
1,896
4.0625
4
""" Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. Note that you cannot sell a stock before you buy one. Example 1: ...
a83599b59453a57349ae8a7c5ac48bdf4c6374fd
makhmudislamov/leetcode_problems
/easy/first_unique.py
737
3.921875
4
""" Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. Examples: s = "leetcode" return 0. s = "loveleetcode", return 2. Note: You may assume the string contain only lowercase letters. """ class Solution: def firstUniqChar(self, s: str) -> int: ...
14ebac1bd367ed2dba270de377f02485b1dd1483
makhmudislamov/leetcode_problems
/easy/add_strings.py
634
4.09375
4
""" Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. Note: The length of both num1 and num2 is < 5100. Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not contain any leading zero. You must not use any built-in BigInteger library or convert the...
84bf47bae58de89618dd2227a03068ba03b361a2
makhmudislamov/leetcode_problems
/book_epip/arrays/multiply.py
1,569
3.765625
4
""" input: [1,2,3] and [5,5] output: [6,7,6,5] >> 123 x 55 """ def multiply(nums1, nums2): # O(n) time and O(m) space # declare two empty string # iterate over both arrays and create fill each string with # array elements # turn the strings into int # multiply them # iterate over the resul...
2ec137a6a3e4eda1fdd7bcaf74fd41e18f5dafd8
Nisha9698/python_12_10_2019
/NishaThakobhaiPatel_MIT.py
364
3.625
4
no=int(input("Enter Number between 0 to 100 : ")) lst=[] i=1 while i<=no: count=0 if(no%i==0): j=1 while(j<=i): if(i%j==0): count=count+1 j=j+1 if(count==2): lst.append(i) i=i+1 print("Prim...
9d81c0ccc0d5d5a1f1a968084f2fcabc04506ade
cbitosc/python-for-beginners
/repeat.py
267
3.8125
4
#!/usr/bin/python word=input('Enter a string: ')#changed input flag=0 for i in range(0,len(word)): for j in range(i+1,len(word)): if(word[i]==word[j]): print ("the first repeating letter is:",word[i])#added parentheses flag=1 break if(flag==1): break
c7f945c55ed74fbe371256d0e3353bd18d821426
VarshaSLalapura/PythonAndML
/1-BasicsTutorial/worksheet1.py
3,163
3.703125
4
# import numpy as np import itertools def winner(current_game): def all_equal(l,direction): if l.count(l[0]) == len(l) and l[0]!= 0: print('Player {} has won the game {}'.format(l[0],direction)) return True else: return False # Horizontal: for row in ga...
3ef291f45979da590728b53bddb286fd60d6c7f8
VarshaSLalapura/PythonAndML
/1-BasicsTutorial/practise_sheet2.py
1,487
3.875
4
from typing import List game = [[1, 0, 2], [0, 2, 0], [2, 0, 1]] # type: List[List[int]] def dia_winner(current_game, left_to_right=True): check = [] i = len(game[0]) - 1 if left_to_right: for row in game: check.append(row[i]) i+=1 print(check) ...
e674b169353e56cc80076122404d1605197127be
VarshaSLalapura/PythonAndML
/6-MatplotLib/7-LoadDataCSVorNumpy.py
753
3.53125
4
import csv import numpy as np import os import matplotlib.pyplot as plt # this is to load the data called "example.txt" # as cvs file or read it using numpy path = "/home/varshalalapura/Desktop/Inspiration" file_name = "example.txt" # 1: with open(os.path.join(path,file_name)) as csvfile: my_file = csv.reader(...
a386186a2e82f6e5782305b8f8428e0a73ac209f
VarshaSLalapura/PythonAndML
/5-MachineLearningInGeneral/1-LinearRegression-GoogleStockPriceQuandl/9-HowToProrgramTheBestFitLine.py
946
3.625
4
# 9-HowToProgramTheBestFilLine.py import numpy as np import matplotlib.pyplot as plt from statistics import mean from matplotlib import style # check this style style.use('fivethirtyeight') xs = np.array([1, 2, 3, 4, 5], dtype=np.float64) ys = np.array([5, 4, 6, 5, 6], dtype=np.float64) # "weird thing is without th...
a3e3b8be9c4d7f929bfa4fb59a5be05d04e76f8d
VarshaSLalapura/PythonAndML
/2-OpenCVWithPython/4-ImageOperations.py
1,141
3.8125
4
# T4: Image operations using openCV # load the image and read it import numpy as np import cv2 imloc = r"/home/varshalalapura/Desktop/Inspiration/1.jpg" img = cv2.imread(imloc, cv2.IMREAD_COLOR) # cv2.imshow('image',img) # cv2.waitKey(0) # cv2.destroyAllWindows() # access a pixel pxl = img[55,55] # img[x,y] print(p...
db4c7cafb60d3dc44f596ba9109847f2ad28b101
VarshaSLalapura/PythonAndML
/2-OpenCVWithPython/3-worksheet.py
1,039
3.796875
4
# This work sheet is to draw lines, circles, rectangles and polygons on images using openCV import cv2 import numpy as np imloc = r"/home/varshalalapura/Desktop/Inspiration/3.jpg" img = cv2.imread(imloc, cv2.IMREAD_UNCHANGED) # draw a line on the image cv2.line(img, (200,400), (300,80), color=(0,255,255), thicknes...
ccd3642b60a22fcde8e05b562b6f25a2a4788567
BGCX067/ezonas-hg-to-git
/_cryptoys/eulerproj/6.py
103
3.53125
4
#!/usr/bin/env python # ezjonas@gmail.com a, b = 0, 0 for i in range(101): a += i b += i * i a *= a print a- b
fc761574cdec49815018ef19307921cd2917eced
zer0warm/rps
/rps.py
335
3.765625
4
import random beats = {'rock': 'paper', 'paper': 'scissors', 'scissors': 'rock'} user = input('What you play? ') comp = random.choice(['rock', 'paper', 'scissors']) print('You played', user) print('I played', comp) if user == comp: print("It's a draw.") elif user == beats[comp]: print('You win.') else: p...
6842fe3c8db077be3e54baab2058ec882cd7c597
guyimin/python-tutorial-by-Vamei
/3.5包裹传递.py
456
4.1875
4
# coding=utf-8 #!/usr/bin/env python #包裹传递用于用户不知道参数个数的情况 def func(*name): print type(name) print name # 按照位置传入tuple func(1,4,6) func(5,6,7,1,2,3) def func1(**dict): print type(dict) print dict #按照关键词传入dic func1(a=1,b=9) func1(m=2,n=1,c=11) #difference between * and ** def func2(a,b,c): print a,...
1e0225bc030d7c718fe15296109c28a0d9c4134b
zhibosheng/6212algorithms
/chapter1/insertionsert.py
294
4.125
4
#Uses python3 def InsertionSert(arr): length = len(arr) for j in range(1,length): key = arr[j] i = j - 1 while i >= 0 and arr[i] > key: arr[i+1] = arr[i] i -= 1 arr[i+1] = key return arr if __name__ == "__main__": arr = [5,6,8,2,3] result = InsertionSert(arr) print(result)
506694e3a2eecf1a8cd48b931beff1e65447a9f4
coderunner86/SimNDT
/src/SimNDT/core/packing.py
5,626
3.5625
4
import math from math import pi import numpy as np class Ellipse: def __init__(self, x, y, a, b, theta): self.x = x self.y = y self.a = a self.b = b self.theta = theta self.rect = self.getRect() def area(self): return pi * self.a * self.b def ge...
628c9aa1838364bc5e8776d2e3bb924ee2e46f37
kunalbhangare17/Gray-Code-Problem
/2021pcs1012_Lab_2_Gray Code Problem.py
785
3.609375
4
def generateGrayarr(n): # base case if n <= 0: return # 'arr' will store all generated codes arr = list() # start with one-bit pattern arr.append("0") arr.append("1") # Every iteration of this loop generates # 2*i codes from previously generated i codes. i = 2 j = 0 while True: if i >= 1 << n: b...
5aedb4198c43da04294ae72a86d05b78e276c029
sudo-shuhei/AtCoder
/python_atcoder/ABC128B.py
383
3.65625
4
N=int(input()) info=[input().split() for i in range(N)] #mojiretu #print(info) from operator import itemgetter dic1={} for i in range(len(info)): dic1[i+1]=info[i] #print(dic1) info1=sorted(info,key=lambda x:int(x[1]),reverse=True) info2=sorted(info1,key=itemgetter(0)) #print(info2) for i in info2: for key,valu...
90b161065c8bc65413ab93b7cac6299c2b632639
swhan9404/swExpertAcademy
/0405문제/0405order/sol1.py
414
3.75
4
N = int(input()) def tree_num(N) : """ [ 0 [0,0,0], // 왼쪽, 오른쪽, 부모 1 [2,3,0], ] """ tree_arr = [0] * (N+1) for i in range(1, N+1) : next_left = 2*i if 2*i <= N else 0 next_right = 2*i+1 if 2*i+1 <= N else 0 parent = i//2 if i//2 >0 else 0 tree_a...
16714b70eb5192c992a53a02403657eede3bdb9c
swhan9404/swExpertAcademy
/0405문제/중위순회/sol1.py
597
3.703125
4
import sys sys.stdin = open("input.txt") T = 10 def inorder_traverse(x ,inp_arr) : tmp = inp_arr[x] try : inorder_traverse(int(tmp[2]), inp_arr) except : pass print("{}".format(tmp[1]), end="") try: inorder_traverse(int(tmp[3]), inp_arr) except: pass for tc...
b19fa3a4f00116fdeb9ad19c4dc9fcc74c449b08
dblana/AdventOfCode2017
/day18b.py
5,275
3.515625
4
# -*- coding: utf-8 -*- """ Created on Mon Dec 18 14:15:42 2017 @author: Dimitra """ #def foo(): # print("Part 1") # a = 5 # i = yield a # print(a+i) # yield registerA = {} instructions = [] def check_int(s): if s[0] in ('-', '+'): return s[1:].isdigit() retu...
fb9b245370c36c2477f6c8338ef00d1ce1080958
dblana/AdventOfCode2017
/day12.py
1,057
3.53125
4
# -*- coding: utf-8 -*- """ Created on Tue Dec 12 08:49:08 2017 @author: Dimitra """ import re #line = '7 <-> 7, 959' programs = {} with open('day12_input.txt') as f: for line in f: numbers = [int(s) for s in re.findall(r'\d+',line)] programs[numbers[0]] = numbers[1:] def add_c...
0fe24622f30cefa76a0f8fb003bd61cd37d63f35
anmolj7/school_proj
/ques_17.py
496
3.84375
4
''' Write a program for linear search. ''' def search(arr, element): for i in arr: if i == element: return True return False def main(): arr = eval(input('Enter the list: ')) element = eval(input('Enter the element to be found: ')) if search(arr, element): ...
c164cf80984fa4ee5ee2695c7c0cd020dd5a409d
anmolj7/school_proj
/ques_1.py
429
4.0625
4
''' Write a program to check if a given number is prime or not. ''' def is_prime(num): for i in range(2, int(num**0.5)): if num%i == 0: return False return True def main(): num = int(input('Enter the number you wanna test: ')) if is_prime(num): print('The numb...
0be1b4c5d0219880199f0be781a630d6902bf989
anmolj7/school_proj
/ques_2.py
478
4.09375
4
''' Write a program to check a number whether it is palindrome or not ''' def is_palin(num): num = str(num) if num == num[::-1]: #Using List spicing and indexing to reverse the list. return True return False def main(): num = int(input('Enter the number you wanna test: ')) if ...
987ac2da7d6eb5e137637f161e60bf90af818bd1
anmolj7/school_proj
/ques_13.py
332
4.09375
4
''' Write a program to count number of words in a text file. ''' def main(): with open(input('Enter the file\'s name: ')) as f: data = f.read() data = data.split() data = [word for word in data if len(word) > 0] #Filtering empty words. print(len(data)) if __name__ == "__main__":...
a25c7c3bfcd951234da189f0f747d3781eb7b50c
ProgFuncionalReactivaoct19-feb20/clase02-naludena1
/practica/ejer4.py
159
3.9375
4
""" Practica: uso de funcion lambda @naludena1 """ lista = [10, 2, 8, 7, 5, 4, 3, 11, 0, 1] funciones = lambda x: x**3 print(list(map(funciones, lista)))
6c2f2ea582f354e973374fd088b9fa3c26404669
karandevgan/Algorithms
/MatrixMultiplicationNaive.py
795
3.953125
4
def MultiplyMatrix(A, B): n = len(A[0]) # number of cols of A = number of rows of B m = len(A) # number of rows of A r = len(B) p = len(B[0]) # number of cols of B if (n != r): print "Error: Matrices not compatible" return [] C = [] for i in range(m): C.append([])...
5d2eeca1e0693e3cac6ba078737b72fb1b4f205e
karandevgan/Algorithms
/MergeArrays.py
1,183
3.578125
4
class Solution: # @param A : list of integers # @param B : list of integers # @return A modified after the merge def merge(self, A, B): # import pdb # pdb.set_trace() if len(A) < len(B): A, B = B, A i = 0 j = 0 k = -1 C = [] whi...
b5deee2682f9ecd2bd17955fafb1463b6e2b08b8
karandevgan/Algorithms
/SortColors.py
1,060
3.53125
4
class Solution: # @param A : list of integers # @return A after the sort def sortColors(self, A): # Approach 1: Require 3 passes # B = [] # for i in xrange(3): # for color in A: # if color == i: # B.append(color) # return B ...
74bde2f0bea6b49b78315cf4d5366ab27f9fd278
karandevgan/Algorithms
/LinkedList.py
783
3.546875
4
class ListNode: def __init__(self, x): self.val = x self.next = None def getRandomNodes(n, top): import random random.seed(10) nodes = [] for i in xrange(n): node = ListNode(random.randint(0,top)) nodes.append(node) return nodes def joinNodes(nodes): for i i...
1c088f6443bb54609aa3b92396d3c4812a4e1ad4
karandevgan/Algorithms
/GrayCode.py
827
3.53125
4
class Solution: # @param A : integer # @return a list of integers def grayCode(self, A): if A == 0: return [] decimal_list = [] for i in xrange(2**A): decimal_list.append((i>>1)^i) # binary_list = self.auxillary(A) # decimal_list = [int(num, 2...
1bded8a32654231b0db60bd80e3f4824f621a5d9
karandevgan/Algorithms
/CountingSort.py
524
3.84375
4
def CountingSort(numbers, k): aux_list = [0 for _ in range(0,k+1)] final_list = [0 for _ in range(len(numbers))] for index in range(len(numbers)): aux_list[numbers[index]] += 1 for index in range(1,len(aux_list)): aux_list[index] += aux_list[index-1] for index in range(len(final_l...
5b2f5770e980ebeca8a5944726065bb3dee8c0aa
karandevgan/Algorithms
/RadixSort.py
971
4.125
4
def get_nth_digit(num, n): ''' This function returns the nth digit of a number num n = digit which is required num = number ''' divisor = 10 ** n dividend = num new_dividend = dividend % divisor return new_dividend / (divisor / 10) def counting_sort(A, n): count = [0...
102d0c51de5984544ae895768a6747edb89fc1d1
karandevgan/Algorithms
/Subsets.py
667
3.546875
4
from collections import deque class Solution: # @param A : list of integers # @return a list of list of integers def subsets(self, A): if len(A) == 0: return ([[]]) A.sort() subset_dict = deque() subset_dict.appendleft([A[-1]]) for i in xrange(len(A)-2,...
d5536cdfbd9522d93e9e04e1812dd085eee7a4cc
karandevgan/Algorithms
/QuickSort.py
1,014
4.03125
4
import random def Swap(list, index1, index2): list[index1], list[index2] = list[index2], list[index1] def Partition(list, left_index, right_index): pivot = list[right_index] partition_index = left_index for index in range(left_index, right_index): if list[index] <= pivot: if partit...
ff83309a29010223b289355195fad25ac86d36c7
karandevgan/Algorithms
/LargestNumber.py
779
4.28125
4
def compare(number, number_to_insert): str_number_to_insert = str(number_to_insert) str_number = str(number) num1 = str_number + str_number_to_insert num2 = str_number_to_insert + str_number if num1 > num2: return -1 elif num1 == num2: return 0 else: return 1 def la...
bd38ff9fa3e5b0899c15fe8936e27b064d90d940
karandevgan/Algorithms
/Flip.py
818
3.65625
4
def Flip(A): zero_count = 0 max_zero_count = 0 start_index = None last_index = None for index in range(0, len(A)): if A[index] == '0': if start_index is None: start_index = index temp_start_index = index if zero_count < 0: ...
6d99bebeb4886dc7f66f66ba2bfdb66437ce1dc8
karandevgan/Algorithms
/InsertionSortLinkedList.py
1,202
4.0625
4
class Solution: # @param A : head node of linked list # @return the head node in the linked list def insertionSortList(self, A): if A is None or A.next is None: return A head = LinkedList.ListNode("dummy") head.next = A # Stores the starting element ...
50c7b799a722b9439fda90bdc01fb5910784d182
gtsofa/homestudy
/assement/insert_elemnt.py
3,429
4.375
4
# page 3 of 11 # q 3 ''' Imagine you have an empty list (list=[]). If you insert 6 in position 0, 3 in position 1, -[Manager: job=mgr, name=Chris Jones, pay=60000]- and then 9 in position 0 again, what do you get when you print the list? ''' alist = [] print(alist) alist.insert(0, 6) alist.insert(1, 3) print(alist)...
6d70f63216be502725912f1e4b5568711b3d94ca
dambergn/programing-examples
/python/loops.py
135
3.78125
4
test_array=["one","two","three"] for i in test_array: print(i) for i in test_array: print(i) if i == "two": break
9d71eaf6f26c4babb902e2049036049120cfcd8e
xiongfeihtp/python-trick
/trick_for_data.py
3,672
3.71875
4
""" 数学结构与算法 """ import heapq #heapq模块:对堆得利用 class PriorityQueue: def __init__(self): self._queue=[] #index维护优先相同的元素的次序 self._index=0 def push(self,item,priority): heapq.heappush(self._queue,(-priority,self._index,item)) self._index+=1 def pop(self): return ...
9df52819bce43eec035c19d428795d274fb93c8f
VuNghiXuan/AI
/AI/code_HD4.B2_grandient.py
731
3.65625
4
import numpy as np # import matplotlib import matplotlib.pyplot as plt from sklearn import linear_model # Data x = [2,9,7,9,11,16,25,23,22,29,29,35,37,40,46] y = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] x = np.array([x]).T y = np.array([y]).T # Vẽ đồ thị title = plt.figure("Hướng dẫn 4. Bài 2 code công th...
95ec555c409e2c5148a849e68f62303cf1025a9e
EndruK/CodeRecommendations
/Seq2Seq_Pytorch_test/Data/tokenizers/tokenizer.py
350
3.78125
4
import abc class Tokenizer(abc.ABC): @abc.abstractmethod def tokenize(self, text): """ interface for a tokenizer this function should always be called to tokenize a text based on specific schemes :param text: text which should be tokenized :return: array holding the to...
7692e80422173bb7da530cd6de3471e33ac25175
PapenfussLab/Mungo
/snippets/reverse.py
337
3.765625
4
#!/usr/bin/env python """ reverse.py <input> Prints the contents of <input> in reverse order """ import sys if len(sys.argv)==1 or '-h' in sys.argv or '--help' in sys.argv: sys.exit(__doc__) iFile = open(sys.argv[1]) data = [] for line in iFile: data.append(line.strip()) data.reverse() for line in data...
3fffc0216ad36109de1ee961c79f06ebbea9e75c
vsapronova/Harvard-Projects
/dna/dna.py
2,186
3.9375
4
import csv from sys import argv import re def main(): if len(argv) != 3: print("Usage: python dna.py data.csv sequence.txt") return with open(argv[2], "r") as dna: dna = dna.read() list_dna = [] database = open(argv[1], "r") reader = csv.reader(database, delimiter=',') ...
72d7d85c98c80fb8e27aa97504de0a4d46195e2c
deepak27april/Git_Python
/hungry.py
245
3.9375
4
def getTotal(lst): total=0 for item in lst: total=total+item return total l1={1,2,3,4,5} l2={11,22,33,44,55} totalL1=getTotal(l1) totalL2=getTotal(l2) print("Total of List 1:" , totalL1 ) print("Total of List 2:" , totalL2 )
1169b0d3ab15d67b748c924c9756cc58215560e4
ryantcullen/three-doors
/threedoors.py
1,424
3.828125
4
import numpy as np import math # tracks how many times switching was the correct move to make numCorrect = 0 # the number of trials to run the experiment trials = 10000 for i in range(trials): # list of doors doorz = [0, 0, 0] # randomize the user's initial choice choiceIndex = np.random.randin...
4cf9d7967693e62e96ee283e136ef19659874a5a
Cal-NERDS/intro-to-python
/two-day-boot-camp/py-files/Intro-to-Python-Day-2.py
11,084
4.59375
5
# # Intro to Python (Part II) # # ### By: Kseniya Usovich & Karla Palos # # # # --- # ### Table of Contents # # # 1 - [Conditionals] # # 2 - [Loops] # # a - [For Loops] # # b - [While Loops] # # 3 - [Functions] # # a - [Built-in Functions] # # b - [Defining Functions] # # 4 - [Libraries] # --- # # # # **...
bf909b9a04ab2a89d7423e5e4737989fca4ed5d7
Ashe0/CardGames
/card.py
1,069
3.96875
4
class Card: def __init__(self,rank,suit): self.rank = rank self.suit = suit def show_card(self): print(" _________ ") print("| " + self.suit+" |") if self.rank == "T": print("| 10 |") else: print("| "+self.rank+" |") for i in range(3): print("| ...
d137bf1a7458c86845270a5939f581b722633bcd
AJTortola/Networks-Assignment3
/JobCreator.py
2,136
3.75
4
#This is the job creator which tells the job seeker what jobs to perform from socket import * from random import randrange serverName = gethostbyname(gethostname())#gets the host ip serverPort = 12000 clientSocket = socket(AF_INET, SOCK_STREAM) clientSocket.connect((serverName,serverPort)) while True: ...
d3325c80b143b45634dadb59f9ce4fc232c75918
hoon4233/Algo-study
/2021_spring/2021_04_22/5052_Trie_DH.py
1,088
3.640625
4
import sys from collections import defaultdict T = int(sys.stdin.readline().strip()) class Node: def __init__(self, key): self.key = key self.child = {} class Trie: def __init__(self): self.head = Node(None) def insert(self, word): cur = self.head for ch in wor...
201c94fa2ec3fff0b1558a4ea3dfe8a32bd16ce1
hoon4233/Algo-study
/2020_winter/2020_01_06/구명보트_GU.py
537
3.5
4
def solution(people, limit): answer = 0 people.sort(reverse = True) while len(people) > 0: boat = people.pop(0) print("first while",boat) while len(people) > 0: light = people[-1] if light + boat <= limit: boat += light people....
c633305692d8118a59d5d9b74c0ef75b33528511
hoon4233/Algo-study
/2020_winter/2020_01_20/11664_JJ.py
861
3.75
4
import sys # 거리구하기 def getDistance(a, b): tmp = 0 for i in range(3): tmp = tmp + (a[i]-b[i])**2 return tmp**0.5 # 가운데 구하기 def getPoint(a, b): p = [] for i in range(3): p.append((a[i]+b[i])/2) return p val = 10**-6 Ax, Ay, Az, Bx, By, Bz, Cx, Cy, Cz = map(int, sys.stdin.re...
05b08a8d79f89367e37f70ee740f1ec6d205d988
hoon4233/Algo-study
/2020_summer/2020_08_12/1735_GU.py
405
3.5
4
import sys def find(a,b): while b!=0: n = a%b a = b b = n return a a,b = map(int,sys.stdin.readline().split()) c,d = map(int,sys.stdin.readline().split()) gcd = 0 if b > d: gcd = find(b,d) else: gcd = find(d,b) lcm = (b//gcd)*(d//gcd)*gcd a *= lcm // b c *= lcm // d upper = a+c if lcm ...