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
4f46f746f21e445f71ea8fc61155dff62e3ce033
ToBeTree/cookbookDemo
/1-数据结构和算法/1-19转换计算.py
610
4.15625
4
# 需要灵活使用生成器,避免内存消耗 s = {'name', 12, 11.11} print(','.join(str(a) for a in s)) nums = [1, 2, 3, 6, 7] # 生成器 s = sum(s * s for s in nums) print(s) # 下面的方式会生成一个临时的列表 s = sum([s * s for s in nums]) print(s) # 命名元组不能修改但是_replace可以创建一个新的对象替代 from collections import namedtuple Student = namedtuple('Student', ['name', 'age', ...
aa30ccd7c7131ead7652cbade240b1cfae3c6161
BerlinA-B/AI-Project-1
/boardGame.py
5,474
3.90625
4
# Longitude from 0-3 # Latitude from 0-3 import copy class Board: def __init__(self): self.startTable = [] self.curTable = [] self.goalTable = [] self.lat = 0 self.lon = 0 '''Initializes board''' def makeBoard(self, filename): count = 1 ...
12f4625a421f85e40f4ab2700795fceb8e53acad
TLTerry23/CS30practice
/CS_Solutions/Thonnysolutions/3.3.2Area_of_figures.py
791
4.4375
4
# Area Calculator # Put Your Name Here # Put the Date Here choice=input("What do you want to find the area of? Choose 1 for rectangle, 2 for circle, or 3 for triangle.") if choice=='1': rectangle_width=float(input("What is the width of your rectangle?")) rectangle_height=float(input("What is the length of your...
b17951ae94b0815f45c47a9f88d8488124b24d20
TLTerry23/CS30practice
/reeborgSolutions/Pon_Step13.py
981
3.625
4
#Pon Step 13 #November 14, 2019 #Robot detect and jump_hurdles() until goal. def turn_right(): repeat 3: turn_left() def turn_around(): repeat 2: turn_left() def jump_hurdles(): turn_left() move() turn_right() move() turn_right() move() turn_left() think (100) while...
8b0a1b36dc58cdd2aac4ef2005bf7304c8d66a6f
wutz-it/Assignment
/parseQuote.py
1,443
3.640625
4
""" " This program is used for parsing history quote close prices and volumes of " each symbol on each day from source 'http://www.nasdaq.com/symbol/[quote]/historical' """ import requests import lxml import csv from bs4 import BeautifulSoup import sys # Receive input quote_symbol = str(sys.argv[1].lowe...
58519976fbce13372c26cfecce31e6a139d3d702
Germanoh/IC_Lapisco
/Python/Topic11/topic11.py
1,296
3.78125
4
''' Reads an image with a black square on the center and a white background, converts to grayscale and draws a circle on the centroid of the black square. ''' import cv2 as cv import numpy as np # reads an image image = cv.imread('C:/Users/germa/Documents/Lapisco/IC_Lapisco/Python/Topic11/image.jpg') # converts to g...
c1073996332c08bb41dc141aa356da3f6375a15d
Germanoh/IC_Lapisco
/Python/Topic6/topic6.py
556
3.8125
4
''' Reads an image, converts to grayscale, applies canny filter and show the results ''' import cv2 as cv # Reads an image image = cv.imread('image.jpg') # Converts to grayscale grayscale_img = cv.cvtColor(image, cv.COLOR_BGR2GRAY) # displays input image cv.imshow('Input Image', grayscale_img) cv.waitKey(0) ...
a2781049e4ac8d2f94355326498919ad5501cd25
brettmadrid/Algorithms
/recipe_batches/recipe_batches.py
1,409
4.25
4
#!/usr/bin/python import math def recipe_batches(recipe, ingredients): batches = math.inf ''' First check to see if there are enough ingredients to satisfy the recipe requirements ''' if len(recipe) > len(ingredients): return 0 ''' Now check to see if there are enough of each i...
f8fa6b77b71bd50acf2cbddeff370e0b2709d3bf
barvaliyavishal/DataStructure
/Cracking the Coding Interview Exercises/Linked Lists/SinglyLinkedList/RemoveDups.py
741
4.3125
4
from LinkedList import LinkedList class RemoveDuplicates: # Remove duplicates Using O(n) def removeDuplicates(self, h): if h is None: return current = h seen = set([current.data]) while current.next: if current.next.data in seen: curren...
387473b7fd2bb0e48ae98786fe85610e26014b05
barvaliyavishal/DataStructure
/Bit Manipulation/uniqueNumber.py
164
3.640625
4
''' unique number in array ''' def uniqueNumber(arr): res = 0 for i in arr: res = res ^ i return res print(uniqueNumber([2,3,6,4,2,3,6,6,3,2]))
9955a7163d7acbf68d002ee7afd744e1d8f6032d
barvaliyavishal/DataStructure
/Leetcode Problems/SortElemetsOfArrayInGivenRange.py
680
3.921875
4
def mergeSort(arr, n): if len(arr) > 1: mid = n//2 l = arr[:mid] r = arr[mid:n] mergeSort(l, len(l)) mergeSort(r, len(r)) i = j = k = 0; while i < len(l) and j < len(r): if l[i] < r[j]: arr[k] = l[i] i += 1 ...
5cb6bf71c9595b6136e85a85503d405eea92c941
barvaliyavishal/DataStructure
/Practice Questions./add Digits.py
87
3.625
4
def add(n): if n == 0: return 0 return n%10+add(n//10) print(add(1234))
983b106ab6e4e093ee330866707bd6e35b7df3da
barvaliyavishal/DataStructure
/Cracking the Coding Interview Exercises/Linked Lists/SinglyLinkedList/removeDuplicates.py
766
4.25
4
from LinkedList import LinkedList class RemoveDuplicates: # Remove duplicates Using O(n^2) def removeDuplicates(self, head): if head.data is None: return temp = head while temp.next: start = temp while start.next: if start.next.data ...
7370e481c39b0c0d3d4fa9a17f790aeaef32ca10
barvaliyavishal/DataStructure
/Cracking the Coding Interview Exercises/Linked Lists/SinglyLinkedList/isPalindromeApproach2.py
631
4.0625
4
from LinkedList import LinkedList, Node def reverse(head): temp = None while head: newnode = Node(head.data) if temp: newnode.next = temp temp = newnode else: temp = newnode head = head.next return temp def is_palindrome(head): rev ...
e088d2881b5687fa08d37866f2a7489c31e8eeaf
barvaliyavishal/DataStructure
/Cracking the Coding Interview Exercises/Linked Lists/SinglyLinkedList/KthToLastElementInLinkedListRecursive.py
370
3.78125
4
from LinkedList import LinkedList class KthToLastElement: def kthlast(self, k, h): if h is None: return 0 index = self.kthlast(k, h.next)+1 if index == k: print(h.data) return index o = LinkedList() o.add(1) o.add(2) o.add(3) o.add(4) o.add(5) o.add(6) o.a...
8a0a0ec4ab443cfc7dc03b9ed2e50ea93895ef3a
barvaliyavishal/DataStructure
/Practice Questions./PowerOfN.py
113
3.78125
4
def powerOfN(n,p): if p == 1: return n return n * (powerOfN(n, p-1)) a = powerOfN(10,3) print(a)
c9dc172791ca2825767c260a86d4ee6b4ea79fa5
barvaliyavishal/DataStructure
/GeeksForGeeks/subArrayWith0Sum.py
580
3.59375
4
''' This is a problem called "subarray with 0 sum" and link for this problem is given below... https://www.geeksforgeeks.org/find-if-there-is-a-subarray-with-0-sum/ Given an array of positive and negative numbers. Find if there is a subarray (of size at-least one) with 0 sum. Example 1: Input: 5 4 2 -3 1 6 Output: Y...
4c88e0185234a9e0fc799877126f61c859b342f0
pedrohenmuniz/Pedro_IC
/eureka/testeddarray.py
280
3.59375
4
import ddarray a = ddarray.double_ddarray(2, 3) for i in range(2): for j in range(3): ddarray.setitem(a, i, j, i + 1) print (ddarray.calculate(a, 2, 3)) for i in range(2): for j in range(3): print("{} ".format(ddarray.getitem(a,i,j))) ddarray.deleteddarray(a,2,3)
acf06218e8bcd70ccfb4aa6627f1ee6522a7f92b
10vernothin/Tic-tac-Toe
/Tic-Tac-Toe.py
4,206
4.375
4
from math import * """ This program makes a tic-tac-toe game. It consists of four helper functions: -constructPlayspace() makes the graphics -checkStatus() checks if the game ends, and if it's a win or a tie -clearSpace() clears the space to default -inputIntCheck() checks if the input is i...
923aafcb9147d70e62d8512fabb477b5a8365a5e
garciaha/DE_daily_challenges
/2020-08-13/eadibitan.py
1,788
4.15625
4
"""Eadibitan You're creating a conlang called Eadibitan. But you're too lazy to come up with your own phonology, grammar and orthography. So you've decided to automatize the proccess. Write a function that translates an English word into Eadibitan. English syllables should be analysed according to the following rule...
ba929253c23f2a8140b891231b5551438becd533
garciaha/DE_daily_challenges
/2020-08-28/iso_group.py
764
4
4
"""Isolated or Grouped? Write a function that extracts the max value of a number in a list. If there are two or more max values, return it as a list, otherwise, return the number. This process could be relatively easy with some of the built-in list functions but the required approach is RECURSIVE. """ def iso_group(l...
85051a8cef826a0fb73dfc66172c8f588dc3433f
garciaha/DE_daily_challenges
/2020-07-09/maximize.py
1,015
4.1875
4
""" Maximize Write a function that makes the first number as large as possible by swapping out its digits for digits in the second number. To illustrate: max_possible(9328, 456) -> 9658 # 9658 is the largest possible number built from swaps from 456. # 3 replaced with 6 and 2 replaced with 5. Each digit in the secon...
081fa71ed4ff5ac6c1e5402c48cbb46429f5e46f
garciaha/DE_daily_challenges
/2020-08-20/summer_olympics.py
1,058
4.21875
4
"""Summer Olympics Analyse statistics of Olympic Games in the summer CSV file. Create a function that returns 1. Find out the (male and female) athlete who won most medals in all the Summer Olympic Games (1896-2014). 2. Return the first 10 countries that won most medals: Bonus: Use pandas to create a datafr...
736a16c6c9f13efd689a4449c5bdaef22d1d96fc
garciaha/DE_daily_challenges
/2020-08-03/unravel.py
641
4.4375
4
"""Unravel all the Possibilities Write a function that takes in a string and returns all possible combinations. Return the final result in alphabetical order. Examples unravel("a[b|c]") -> ["ab", "ac"] Notes Think of each element in every block (e.g. [a|b|c]) as a fork in the road. """ def unravel(string): pas...
900c2272f61d7cf2f0386f6c66588706ba44b7f3
garciaha/DE_daily_challenges
/2020-09-07/odd_square_patch.py
693
4.0625
4
"""Odd Square Patch Create a function that takes an array of numbers, and returns the size of the biggest square patch of odd numbers. See examples for a clearer picture. """ def odd_square_patch(board): pass if __name__ == "__main__": assert odd_square_patch([ [1, 2, 4, 9], [4, 5, 5, 7], ...
8cd9783dc602893f32c52a2c4c2e21952662def3
garciaha/DE_daily_challenges
/2020-07-22/connect.py
1,742
4.28125
4
"""Connecting Words Write a function that connects each previous word to the next word by the shared letters. Return the resulting string (removing duplicate characters in the overlap) and the minimum number of shared letters across all pairs of strings. Examples connect(["oven", "envier", "erase", "serious"]) -> ["...
79b243b7c8dc4a887e111dac8b620adb5db55420
garciaha/DE_daily_challenges
/2020-09-09/all_explode.py
1,679
4.21875
4
"""Chain Reaction (Part 1) In this challenge you will be given a rectangular list representing a "map" with three types of spaces: - "+" bombs: When activated, their explosion activates any bombs directly above, below, left, or right of the "+" bomb. - "x" bombs: When activated, their explosion activates any bombs p...
80554dc7195ea4994ca21111eb681d4538597d8f
garciaha/DE_daily_challenges
/2020-08-26/check_pattern.py
911
3.953125
4
"""Fit the Pattern Create a function that checks if the sub-arrays in an array adhere to the specified pattern. Notes - The length of the pattern will always be the same as the length of the (main) array. - The pattern does not necessarily have to be alphabetically ordered. """ def check_pattern(arrays, pattern)...
057749ce3d1477aeba641cc0be95361ae1ce48fe
aschnirel/UCB_Python
/AddieSchnirelX442.3_assignment10.py
3,366
4.125
4
#Question 1 # Write a simple Rectangle class. It should do the following: ##Accepts length and width as parameters when creating a new instance ##Has a perimeter method that returns the perimeter of the rectangle ##Has an area method that returns the area of the rectangle ##Don't worry about coordinates or negative v...
ef49e72d1bd3ab380f0363b5683a24cb8c7a094f
PWbio/Bioinformatics-Algorithms
/Grokking_Algorithms_An_Illustrated_Guide_for_Programmers_and_Other_Curious_People/recursion.py
1,236
3.75
4
def sum_(object): if object == []: return 0 return object[0] + sum(object[1:]) def len_(object): if object == []: return 0 return 1 + len_(object[1:]) def max_(object): if len(object) == 2: # base case return object[0] if object[0] > object[1] else object[1] sub_max = m...
cfd0d6c5a051bdd715fc2ca1013d06a4c8e5462c
PWbio/Bioinformatics-Algorithms
/Grokking_Algorithms_An_Illustrated_Guide_for_Programmers_and_Other_Curious_People/selection sort.py
464
3.96875
4
def find_smallest(list): smallest_num = list [0] smallest_index = 0 for i in range (1, len(list)): if list[i] < smallest_num: smallest_num = list[i] smallest_index = i return smallest_index def selection_sort(list): sorted_list = [] for i in range (len(list)): ...
d4ccdd86d43eb8f7606e7d19ee963665079ba832
Jrsnow8921/NameMatch
/name_match.py
840
3.578125
4
class Check(object): def __init__(self, word): self.word = word def abbr(self): e = self.word w = self.word[:1] lens = len(self.word) last = self.word[-1:] all = '%s%s%s' %(w, lens, last) self.check_fn(e, all) def check_fn(self, my_name, intials): a ...
b7583643a10a752540bd40e758b081589dabf561
AndreasArne/treeviz
/treevizer/builders/balanced_binary_tree.py
1,972
3.78125
4
""" Uses invisible nodes to balances trees in graph. Based on https://stackoverflow.com/a/48198645 to balance tree. """ from treevizer.builders.edge import Edge from treevizer.builders.base_graph import Graph class BalancedBinaryTree(Graph): """ Builder for Balanced Binary Trees with igraph """ def _...
596bab83975944db9730372ef793948f8cc52496
TenederoGerard/X_normalized
/X_normalized.py
190
3.515625
4
import numpy as np X= np.random.random ((5,5)) print ("Original Array: ") print (X) x= np.mean(X) sdev=np.std(X) Z= ((X-x)/sdev) print ("Normalized Array: ") print (Z)
d307df49a5513fca6adcdebaff0163ca5c52ef65
Yossarian0916/AlogrithmsSpecialization
/quicksort.py
1,515
3.953125
4
import random def random_partition(array, l, r): i = random.randint(l, r) array[l], array[i] = array[i], array[l] return partition(array, l, r) def median_of_three(array, l, r): """use median of the left, middle, right elements to be the pivot""" mid = (l + r) // 2 x = array[l] - array[mid] ...
fcbcadad5c0e4d0e049ea77164fe3f9366b490d9
Yossarian0916/AlogrithmsSpecialization
/karatsuba_mul_int.py
1,008
3.921875
4
def karatsuba(x, y, base=10): """ Karatsuba Mulitiplication, complexity O(n**log3) Args: x, y(int): default base is 10 base: default=10 """ if len(str(x)) or len(str(y)) == 1: try: return x * y except ValueError: print('inputs are not valid!') ...
ac78a45b5b38dd896ea5740a6ec00ef1835371ed
Yossarian0916/AlogrithmsSpecialization
/deterministic_select.py
1,052
3.921875
4
"""median of medians, select algorithm whose worst-case running time is O(n)""" def Dselect(array, n): pivot = choose_pivot(array, len(array)) p = partition(array, array.index(pivot)) if p == n-1: return array[p] elif p < n-1: return Dselect(array[p:], n-p) else: return Dse...
56ae86a640e1ffef13d7f04792943bfd696a6b9d
Yossarian0916/AlogrithmsSpecialization
/insertion_sort.py
380
4.15625
4
# insertion sort def insertion_sort(array): for i in range(1, len(array)): # insert key into sorted subarray card = array[i] j = i-1 while j >= 0 and array[j] > card: array[j+1] = array[j] j = j-1 array[j+1] = card if __name__ == '__main__': lst ...
c3415350f1ced537794b63828b3981010daa1684
Yossarian0916/AlogrithmsSpecialization
/queue_array.py
1,408
4.03125
4
class Queue: def __init__(self, length): """a queue of at most n elements using an array of n+1 element size""" self.length = length self.queue = [None]*(length+1) self.head = 0 self.tail = 0 def enqueue(self, x): if self.is_full(): return 'Overflow' ...
44feb9d2a1b33a07641f57ae21b5ca8748bdf086
tahe-ba/Programmation-Python
/serie/serie 3 liste/code/ex10.py
343
4.03125
4
#program that check if there is at least one common element in two lists def commun(l1, l2): result = False for x in l1: for y in l2: if x == y: return True li=[1,2,3,4] lo=[5,6,7] if commun(li,lo) : print("same element exists in both lists") else : print("no common ...
f842ae932a008fe849380f8d7b3b245da6017724
tahe-ba/Programmation-Python
/serie/serie 3 liste/code/ex15.py
197
4.03125
4
#program to generate and print a list # except for the first 5 elements, # where the values are square of numbers between 1 and 20 l = [] for i in range(1,20): l.append(i**2) l=l[5:] print (l)
a0042c5e43f8b7608b580d7e0fa70876a50a9da4
tahe-ba/Programmation-Python
/serie/serie 3 liste/code/exemple.py
225
4.21875
4
# creating an empty list lst = [] # number of elemetns as input n = int(input("Enter number of elements : ")) for i in range(n): ele = int(input("element n° "+str(i+1)+": ")) lst.append(ele) print (lst)
891b21382cc0cd84bb66d14ef296e4f70a230ccc
tahe-ba/Programmation-Python
/serie/serie 3 liste/code/ex9.py
369
4.21875
4
''' program to find the list of words that are longer than n from a givenlist of words. ''' li = [] li = [item for item in input("Enter the words seperated by space: ").split()] msg=input("text= ") txt=msg.split(" ") print (txt) print (li) n=int(input("longueur de mot ")) lw = [] for i in range(len(li)): if len...
1dde29703e719ff0b1021626a9d004b32f9d7798
tahe-ba/Programmation-Python
/serie/serie 2 input/code/ex2_tabmult.py
392
3.8125
4
quitter='F' while quitter!='T': while True : x=input("Introduisez un entier ") if x.isdigit() is True : print("La table de multiplication de ", x) for i in range(11): print(x, '*' , i, ' = ', int(x)*i ) break else : print("erreu...
31de87045288069ce8dc80acd46cda2ff4d86dd8
tahe-ba/Programmation-Python
/serie/serie 1 I-O/code/second.py
629
4.15625
4
# Find how many numbers are even and how many are odd in a sequenece of inputs without arrays while True : try : n=int(input("combien d'entier vous aller entrer: ")) break except ValueError: print("Wrong input") j=z=0 for i in range(n): while True : try : ...
0a0ad5bf22df8d73dedd1ea1a3cabe99e590d9d4
Lingfeng-Z/Leetcode-Practice
/92. Reverse Linked List II.py
1,327
3.8125
4
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: virtual_head = ListNode(None) virtual_head.next = head new_head = virtual_head i = 0 while new_head...
4374b34a13e3de78600d001938fc689f4b542981
Lingfeng-Z/Leetcode-Practice
/62. Unique Paths.py
486
3.515625
4
class Solution: def uniquePaths(self, m: int, n: int) -> int: postion = m + n - 2 need_to_fill = n - 1 P_numerator = 1 P_denominator = 1 for i in range(1, need_to_fill+1): P_numerator = P_numerator * postion postion -= 1 P_denominator = P_d...
df957aa89ae264ee87ae3bcb975754614988e879
Lingfeng-Z/Leetcode-Practice
/79. Word Search.py
1,936
3.5625
4
import copy class Solution: def exist(self, board: list, word: str) -> bool: position = [] self.connect = {} for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == word[0]: position.append(tuple([i,j])) se...
3d4e90754323c0dd6f6d616505446a53adf74cad
Lingfeng-Z/Leetcode-Practice
/70. Climbing Stairs.py
420
3.671875
4
class Solution: def climbStairs(self, n: int) -> int: dp = [] i = 0 while i < n: if i == 0: dp.append(1) elif i == 1: dp.append(2) else: dp.append(dp[i-1] + dp[i-2]) i += 1 return dp[-1] ...
7c35310e46b1cfd757ecb5b4b51d3935eaaef3a5
Lingfeng-Z/Leetcode-Practice
/23. Merge k Sorted Lists.py
1,187
3.640625
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None import numpy as np class Solution(object): def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ head ...
3cd6e28449819b8c6e71d77be7fa5354f5741eb2
Lingfeng-Z/Leetcode-Practice
/33. Search in Rotated Sorted Array.py
1,247
3.578125
4
''' @Descripttion: @version: @Author: Lingfeng Zhang @Date: 2020-01-24 @LastEditors : Lingfeng Zhang @LastEditTime : 2020-01-25 ''' class Solution: def search(self, nums: list, target: int) -> int: if target not in nums: return -1 stan = sorted(nums) mv = len(nums)-self.stepSe...
8fca128fd272366999665de92a9e70198195eecb
rhamybachour/Porta-Automatica
/porta.py
8,245
3.5625
4
import random import time class Cores: """ Classe responsável pela coloração do texto """ RED = '\033[91m' YELLOW = '\033[93m' GREEN = '\033[92m' BLUE = '\033[94m' class Calendario: """ Classe responsável pela definição do objeto calendario """ def...
ee322e21b16e1b08a7976bfa0b49e8262b4d9669
leolunac-Holbertons/holbertonschool-low_level_programming
/0x1C-makefiles/5-island_perimeter.py
742
4
4
#!/usr/bin/python3 """Module that calculates the perimeter of an island in a grid.""" def num_water_neighbors(grid, i, j): """Returns the number of water neighbors a cell has in a grid.""" num = 0 if i <= 0 or not grid[i - 1][j]: num += 1 if j <= 0 or not grid[i][j - 1]: num += 1 ...
e6969d64b8764f82681270a38bacc3333a00ba4d
KHyoseon/Software_Design
/register_test.py
503
3.90625
4
import sqlite3 conn = sqlite3.connect('db/student.db') cur = conn.cursor() print('받아야 할 것 : id, password, student_id, name, major, is_abeek') user_id = input('id: ') user_pw = input('password: ') student_id = input('student_id: ') name = input('name: ') major = input('major: ') is_abeek = input('is_abeek: ') # inser...
b27b400a04bd931f170e7b2d01ff85abdc7e975e
MadisMaisalu/prog_alused_vs20
/yl6/yl2.py
627
3.5
4
def eelarve(kylalised): sook = 10 * kylalised rent = 55 kokku = sook + rent return kokku kylaliste_koguarv = int(input("Mitu inimest on kutsutud ")) kylaliste_kindel_arv = int(input("Mitu inimest tuleb ")) print("Maksimaalne eelarve on " + str(eelarve(kylaliste_koguarv)) + " eurot") print("Minimaalne...
8373be56d5e81480e41314a2bac2d26072636ea0
MadisMaisalu/prog_alused_vs20
/otsast peale/yl1/yl5.py
234
3.65625
4
ainepunktid = int(input("Sisestage ainepunktide arv: ")) nadalad = int(input("Sisestage nädalate arv: ")) tunde_nadalas = round(int(ainepunktid) / int(nadalad)) print("Teil on nädalas ümmarguselt " + str(tunde_nadalas) + " tundi.")
e1396ac7cd9262d2d121c12558cc41ce4eca6a18
YuJIhyeon/Prj.HomePT
/Humble_Learning/test.py
422
3.65625
4
import numpy as np def sigmoid (o): return 1./(1+np.exp(-1*o)) def formal(RMS, ANG): X1 = -9.89347521 * RMS +16.33257357 * ANG + 2.96626043 X2 = 4.66725605 * RMS -54.0110004 * ANG -25.43624075; H1 = sigmoid(X1); H2 = sigmoid(X2); A = -7.71454823 * H1 +17.75385267 * H2 -0.00684656; p...
cde4eaa08a1d0f136f3616fbabeb1970ea1be8be
michaelsmclayton/DeepLearningNotes
/TensorFlow/Chapter2-TensorFlowEssentials/Chapter2-Jupyter.py
1,581
3.734375
4
''' Before loading a Jupyter notebook, it is important that you cd into the directory containing .ipynb files.''' # cd ~/directoryOfInteret ''' You can launch Jupyter notebooks by entering the following command into the terminal''' # jupyter notebook '''Running the previous command should launch a new browser window ...
abeb315a223a15514715607be1fb4667629681c6
michaelsmclayton/DeepLearningNotes
/TensorFlow/Chapter2-TensorFlowEssentials/Chapter2-Variables.py
2,739
3.75
4
# Import dependencies import os import tensorflow as tf os.environ['TF_CPP_MIN_LOG_LEVEL']='2' sess = tf.InteractiveSession() # Start an interactive session ######################################################################### print(' Defining, updating, and saving variables') ############################...
6b11394d66d21c7785d1fef7a58f8f1d2708e160
glibrelon/GasCalculator
/App_Gasolina.py
2,127
3.71875
4
import tkinter as tk from tkinter.constants import BOTTOM, LEFT, RIGHT from tkinter import messagebox def calculate(): single_travel_distance = float(Dist.get()) n_ride = float(n_viagens.get()) total_distance_traveled = single_travel_distance * n_ride car_efficiency = float(km_L.get()) gas...
f3957ba2e1b06834d1dc96675f63d98ee161d5b1
ChasonZhang/Python-100-Days
/Day-01/day-01-import-this.py
2,026
3.96875
4
# Day-01 # 作业链接:https://github.com/jackfrued/Python-100-Days/blob/master/Day01-15/01.%E5%88%9D%E8%AF%86Python.md#%E7%BB%83%E4%B9%A0 # 在Python交互式环境中输入下面的代码并查看结果,请尝试将看到的内容翻译成中文。 # 说明:输入上面的代码,在Python的交互式环境中可以看到Tim Peter撰写的“Python之禅”,里面讲述的道理不仅仅适用于Python,也适用于其他编程语言。 import this # Output """ The Zen of Python, by Tim Pete...
381007913bcd073e5a1aa745b00ea030fe371b84
sandeepvura/Mathematical-Operators
/main.py
538
4.25
4
print(int(3 * 3 + 3 / 3 - 3)) # b = print(int(a)) **Mathematical Operators** ``` ###Adding two numbers 2 + 2 ### Multiplication 3 * 2 ### Subtraction 4 - 2 ### Division 6 / 3 ### Exponential When you want to raise a number 2 ** 2 = 4 2 ** 3 = 8 ``` ***Note:*** Order of Mathematical operators to execute...
ec7104ba93be1df50a1437969e29f0b4c0bdde68
MMMM758/workshop2
/forif/ifelse3.py
139
3.90625
4
a = 200 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and are equal") else: print("a is greater tahn b")
9ca4d466fdcc29e36375798862e0fe2c1de2334e
MMMM758/workshop2
/operatore/comparisonop.py
288
4.03125
4
x = 10 y = 12 print("x > y is", x > y) print("x < y is", x < y) print("x == y is", x == y) print("x != y is", x != y) print("x >= y is", x >= y) print("x <= y is", x <= y) # Output : # x > y is False # x < y is True # x == y is False # x != y is True # x >= y is False # x <= y is True
d4b9d3c2040727765465b9d916b9f50fc6a1551e
lvqj2/dm_alchemy
/dm_alchemy/types/helpers.py
4,418
3.875
4
# Lint as: python3 # Copyright 2020 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # U...
a158b8e3b960a58a2f662718bace00a09f92dd80
BigBowly/CFour
/CFour.py
17,026
3.515625
4
# importing OS for screen clear; importing random for randomizing starting player import os import random # class to hold the gameboard values; some last entire game, others per turn class GameBoard: def __init__(self, players = 2): # [rows,columns] self.rows = 0 self.columns =...
113156f213987d3dbfef0ee2e511b6ae354901c3
mukulbichkar19/DataStructures_And_Algorithms_Python
/Collections/reverseKInQueue.py
478
3.8125
4
from collections import deque def reverseKElements(queue, k): size = len(queue) if(k > size): print("Cannot perform action.") else: stack = [] cnt = 0 while(cnt != k): stack.append(queue.popleft()) cnt += 1 while(stack): queue.append(stack.pop()) cnt = 0 while(cnt != (s...
706d51abadb93345518f299414b3d7a549f24eae
mukulbichkar19/DataStructures_And_Algorithms_Python
/Collections/pqclass.py
405
3.59375
4
import heapq class Skill(object): def __init__(self, name, priority): self.name = name self.priority = priority def __lt__(self, other): return self.priority < other.priority skills = [] heapq.heappush(skills, Skill("Java", 9)) heapq.heappush(skills, Skill("C", 8)) heapq.heappush(skills, Ski...
ff8a3f5fd98f68f353eb3d48e35ea3c520be5332
mukulbichkar19/DataStructures_And_Algorithms_Python
/Collections/Employee.py
357
3.578125
4
class Employee: def __init__(self, name, age): self.name = name self.age = age self.__salary = 90000 def printEmpInfo(self): print(self.name, self.age, self.__salary) def setSalary(self, salary): self.__salary = salary e = Employee('Aby', 22) e.setSalary(78000) e.__salary = 8000 e.print...
94f06086a83312f891d5b598c4b3a54b34c79dac
mlanderos/UdacityWork
/Python/different_approach.py
4,512
4.28125
4
def get_answerfor(mode): """function to return answer key for selected mode. easy, medium, hard are the only acceptable values. Returns list""" if mode == 'easy': answer_key = ['python', 'guido', '.py', 'print'] elif mode == 'medium': answer_key = ['variable', 'assign', 'operand', 'operator...
a8dc0e09004d54294d1825a8597398cfab4c08cc
johanloones/ga-learner-dsmp-repo
/Project-Decision-Trees-Loan-Defaulters/code.py
6,566
3.859375
4
# -------------- ##Data loading #Importing header files import pandas as pd from sklearn.model_selection import train_test_split # Code Starts here #Load the dataset from 'path'(given) and store it in a variable called 'data'. data=pd.read_csv(path) #Create a subset of dataframe 'data' by dropping the columns ['custo...
7492cdf5ec1c7666d8db4c29a2be9f2294b7057f
JOEL-K-S/bci-emotiv-pygame-fruitrally
/src/gameState.py
2,135
3.5
4
import pygame import logging import random from src.objectType import GameObjectType from src.input import Input class GameState: """ Class that contains all info about current game state """ matched_sequence = [] time_game_started = 0 penalties = 0 expected_sequence = [] min_signal_w...
804e95e997ec17053cbd6c6e9d134db7a8527568
johannesfleisch/Informatik
/vererbung_fuer_test.py
3,274
3.953125
4
##!/usr/bin/env python """ Aufgabe 3: Klassen """ # random, numpy und die zwei erstellten Module importieren import random import numpy as np from math import pi class Shape: """Klasse Shape""" def __init__(self): """keine Instantiierung""" pass def area(self): """keine Rückgabe...
b5903119e910edd74578d4c2626617c9e75a7784
Aman-zishan/python-programming-series
/dictionary_party.py
550
3.9375
4
def combine_guests(guests1, guests2): # Combine both dictionaries into one, with each key listed combine_dic = guests1 for key in guests2: if key in guests1: pass else: combine_dic[key] = guests2[key] return combine_dic # only once, and the value from guests1 taking precedence Rorys_gue...
d1c055c65699678d7a7089d7e4ad22114c9a1332
sutejaacts11/python_fundamentals
/Python_Function_B21.py
861
3.5
4
#!/usr/bin/env python # coding: utf-8 # In[1]: #How to define function. def greet_user(): """Display a simple greeting""" #Used for giving comments in functions print("Hello I am going to start Python") # In[8]: greet_user() # In[11]: #Passing Information to function def greet_user(username): ...
56f181d9a0e586f0b60b8933fb96eba806072721
MartyMcFlyHasNoFarmHiaHiaHo/asractivelearning
/parser/brackets.py
1,225
3.65625
4
__author__ = 'martin' import math import pyparsing class BracketParser(object): @staticmethod def check_for_trailing_brackets(string, opening_bracket, closing_bracket): if string[0] != opening_bracket: raise ValueError("String does not begin with '{0}'".format(opening_bracket)) if...
8461fab58a43644bfb2db1cc341d369810bb5204
iasmimsilveira/Estudos-em-Python
/Lista2/Ex10 copy.py
573
3.765625
4
import datetime def verifica_data(data): ok = False try: datetime.datetime.strptime(data, "%d/%m/%Y") ok = True except: print("Erro: formato inválido. Entre com dd/mm/aaaa") return ok def dividir_data(data): data = data.split("/") dia = int(data[0])...
4d0b60b097ffcd6241202fe450524343fcba3269
iasmimsilveira/Estudos-em-Python
/CalculaMedia2.py
285
3.875
4
soma = 0 cont = 0 FIM = -1 nota = int(input("Entre com a nota: ")) while (nota != FIM): soma += nota cont += 1 nota = int(input("Entre com a nota: ")) if (cont > 0): media = soma / cont print(f"Média = {media: .2f}") else: print("Não há notas")
13a9a5852b1c59430faaebe5644c5b693e131874
joe753/hello
/Python/2018.11.26/2018.11.26.py
1,052
3.859375
4
import re line = "Beautiful is better than ugly." matches = re.findall("Beautiful", line) # print(matches) matches2 = re.findall("beautiful", line, re.IGNORECASE) # print(matches2) zen2 = """Although never is often better than * right * now. If the implementation is hard to explain, it's a bad idea. If the implemen...
f802e10e5f7eaec4a908b2b51690885d225c8cf8
joe753/hello
/Python/2018.11.22/2018.11.22/2018.11.22(도혜).py
5,112
3.515625
4
import random class Deck: ##instance 없이 쓰는 static method로 Deck.make_deck() deck = [] received_card = [] ##### received카드를 아래===line 34가 아닌 Deck의 변수로 잡을경우 def __init__(self): #####player.pop_card의 received카드와 dealer.popcard의 received카드가 p...
034370467cdda9349ec8f651479d185019747609
rec/bbcprc
/bbcprc/old/prime_factorize.py
820
3.953125
4
import math def prime_factorize(n): factors = [] number = abs(n) factor = 2 while number > 1: factor = get_next_prime_factor(number, factor) factors.append(factor) number //= factor if n < -1: # If we'd check for < 0, -1 would give us trouble factors[0] = -factor...
e486195fadb3fa14fcb783b6409acabafcc99667
nemasobhani/Nutrition-from-Web-Scraped-Recipes
/get_nutrition.py
20,718
3.6875
4
# Nema Sobhani # Nutrition from Web Scraped Recipes # https://github.com/nemasobhani/Nutrition-from-Web-Scraped-Recipes ''' This script will return the following from a .csv file containing web scraped recipe information as collected by Naomi Goodnight (partner on this project): From raw scraped data: Recipe titl...
df7316aa5170c85444841236a154503167972c38
chikin1993/Cryptography
/Hello world test.py
133
3.671875
4
#Hello World test print('Hello World!') print('What is your name?') myName = input() print('Hello ' + myName + ' how are you?')
c95c1458d15aefa912438ca35775946b881f99f7
VenterMEI/MachineLearninginAction
/2_kNN/plot.py
2,081
3.75
4
from kNN import * import matplotlib#将training目录下的所有文件转化为label和mat import matplotlib.pyplot as plt fig=plt.figure() #创建figure类,一个figure对象可以包含一个或多个Axes对象,每个Axes都拥有一个拥有坐标系的绘图系统 ax=fig.add_subplot(1,1,1) #add_subplot()在figure中插入子图。add_subplot(1,1,1)创建了一个只有一个子图的figure mat,labels=file2matrix('D:\ADA\save\python\MachineLe...
5c8fda35bbbdd18358bd90d4ffd57b1ce0b17adf
bharatrajput2409/coding_practice-DSA-
/Sorting Algorithms/quick-sort.py
461
3.53125
4
def partition(arr,l,r): i = l-1 for j in range(l,r-1): if arr[j] < arr[r]: i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[r] = arr[r], arr[i + 1] return i + 1 def quick_sort(arr, l, r): if l < r: pi = partition(arr,l,r) quick_sor...
b47510588d87a15c53399dede66ad2d75f769ad8
bharatrajput2409/coding_practice-DSA-
/Applications/single-occuring-element.py
1,348
3.640625
4
def single_m2(arr): if len(arr) == 1: return arr[0] if len(arr) == 3: if arr[0] != arr[1]: return arr[0] return arr[2] mid = len(arr) // 2 if arr[mid] != arr[mid - 1] and arr[mid] != arr[mid + 1]: return arr[mid] if arr[mid] == arr[mid - 1]: ...
910cb23eec47721552946292fe8e197ffb0f8d1e
bharatrajput2409/coding_practice-DSA-
/Linked List/merge-sorted-lists.py
1,441
3.796875
4
class ListNode: def __init__(self, val): self.val = val self.next = None def insert(root, item): temp = ListNode(item) if root == None: root = temp else: ptr = root while ptr.next: ptr = ptr.next ptr.next = temp return ...
14f5dc9c7a905176965f74157719a47e7454e4ee
bharatrajput2409/coding_practice-DSA-
/Applications/median-of-two-sorted-arrays.py
617
3.875
4
def med(arr1,arr2): arr3=[] i=j=k=0 while i<len(arr1) and j<len(arr2): if arr1[i] < arr2[j]: arr3.append(arr1[i]) i+=1 else: arr3.append(arr2[j]) j+=1 k+=1 while i<len(arr1): arr3.append(arr1[i]) i+=1 ...
4192412b3960e9d3f3e1fbdfb30284a9af9f16aa
Quackers71/opencourseware
/python/concatenation.py
312
3.796875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 28 12:19:02 2020 @author: robq """ x = 1 print(x) x_str = str(x) print("My favourite num is", x, ".", "x =", x) print("My favourite num is", x_str + "." + "." + "x=" + x_str) print("My favourite num is " + x_str + " . " + "x = " + x_str)
72d5e45733bd57e15bf146449f590aefb274d356
Quackers71/opencourseware
/python/conditionals.py
1,052
3.953125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 28 12:46:10 2020 @author: robq """ # x = float(input("Enter a num for x: ")) # y = float(input("Enter a num for y: ")) # if x == y: # print("x and y are equal!") # if y != 0: # print("Therefore, x / y is", x/y) # elif x < y: # p...
a6876cdf02ae210786485985f51a501b29f3e49f
Xusan77/Python-darslari
/uchburchakning ikki tomoni bor, ular orasidagi burchak berilgan, uchuinchi tomonini topish.py
267
3.5625
4
#uchburchakning ikki tomoni bor, ular orasidagi burchak berilgan, uchuinchi tomonini topish, c=?a=int(input("a=")) import math a = int(input("a=")) b = int(input("b=")) x = int(input("x=")) x_rad = x/180*math.pi c = math.sqrt(a**2+b**2-2*a*b*math.cos(x_rad)) print(c)
94612d2b82530b4cd5972f136fa8353ce7b3e0b3
nmsafiri/ml
/mlPractice/getData.py
844
3.5
4
import pandas as pd import matplotlib.pyplot as plt import numpy as np df = pd.read_csv('/home/nmbwamb/Documents/ml/mlPractice/iris.data', header = None)#load data to dataframe y = df.iloc[0:100, 4].values #get the values on column 4 row 0 to 100 of the data frame y = np.where(y == 'Iris-setosa', -1,1) #rename t...
44c3662bac6085bd63fcb52a666c2e81e5a683ff
farhadkpx/Python_Codes_Short
/list.py
1,689
4.15625
4
#list # mutable, multiple data type, un-ordered lis = [1,2,3,4,5,6,7,8,9] #nos lis2 = ['atul','manju','rochan'] #strings lis3 = [1,'This',2,'me','there'] #both #create empty list lis4 = [] #empty lis5 = list() #empty #traversl for item in lis: print (item), #slicing print (lis[:],lis[2:3],lis[3:]) #Mutable l...
41eec8a9507f11496543ce4cd9816cea4bb6f875
farhadkpx/Python_Codes_Short
/ifelse.py
111
3.84375
4
if 1==1: print (" is this correct") elif True: print ("what the hell I know") else: print ("I dont know")
b7c9b92cee6cc429f56ac685326fa26b029b5a16
Residencia-Fiep-Turma-2/distribuicao_marcia
/pkg_marcia/ex05.py
468
4
4
#!/usr/bin/env python3 #5 - Leia um número e imprima a raiz quadrada do número caso ele seja positivo ou igual a zero e o quadrado do número caso ele seja negativo. import math number = int(input("Insert a number: ")) #Verifica se number é positivo def positivo(n): return(n >= 0) def operacoes(number): if (pos...
d9f900f8be0244be5c984b5b92c40f880ab6dc7f
nirmaldeveloper/AIML
/PrepCourses/Programming refresher/Code/Account.py
1,157
3.78125
4
''' Created on Apr. 29, 2020 @author: nirmal ''' from Bank import Bank class Account(Bank): branchname = "Jubilee Hills Corporate Office" branchlocation = "Jubilee Hills" def __init__(self, accountID, customer, balance, SMinBalance): self.AccountID = accountID ...
28ec5060a74ff5c0e0f62742317d22266a5f41a2
sadieBoBadie/feb-python-2021
/Week1/Day2/OOP/intro_OOP.py
2,111
4.46875
4
#1. # OOP: # Object Oriented Programming # Style of programming uses a blueprint for modeling data # Blueprint defined by the programmer -- DIY datatypes # -- customize it for your situation # Modularizing # 2: # What is CLASS: # User/Programmer defined data-type # Like a function is a reci...
36c9bac791ef0ee4aba78e32851a4fcb6756fafb
Lawlietgit/Python_reviews
/review.py
2,202
4.15625
4
# 4 basic python data types: # string, boolean, int, float # str(), bool(), int(), float() # bool("False") --> True # bool("") --> False # bool(10.2351236) --> True # bool(0.0) --> False # bool(object/[1,2,3]) --> True # bool([]) --> False # bool(None) --> False # FIFO --> queue dat...
a71f4e61d09f283698ea7b23a3ff618e4183fd7c
sarahelizgray/towers-of-hanoi
/hanoi.py
15,770
4.28125
4
# -*- coding: utf-8 -*- # Sarah Gray # Towers of Hanoi # python version 2.7 import random import copy def int_to_base_two(number): '''Returns a binary array. The number argument is a positive integer. This method converts number to base two as a list of integers in reverse order. For example, int_to_base_two(6) ...
25b23efeed2442fe43c6615a312838e26a54cca1
2648226350/Python_learn
/pych-ten/10_3to10_5.py
616
3.9375
4
#10-3 filename = 'pych-ten/guest.txt' with open(filename,'w') as file_object: file_object.write("dante\nnaruto") #10-4 name = input("Please input your name: ") while name != 'quit': print("Hello, "+name.title()) filename_2 = 'pych-ten/guest_book.txt' with open(filename_2,'a') as file: file.write...