blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
1f42a110d9f2363d931d5b174276df7f48b7cd09
armgit5/algorithms
/python/graph_theory/tushar/minimumHeap.py
4,435
3.65625
4
class Node(): def __init__(self, weight=0, key=None): self.weight = weight self.key = key class BinaryMinHeap(): def __init__(self): self.allNodes = [] self.nodePosition = {} def swap(self, node1, node2): key = node1.key weight = node1.weight nod...
81791f493ed32353650d6514003c0140da675950
armgit5/algorithms
/python/csDojo/shortestDist.py
723
3.703125
4
# https://www.youtube.com/watch?v=eaYX0Ee0Kcg&index=3&list=PLBZBJbE_rGRVnpitdvpdY9952IsKMDuev import math from csDojo.maxHeapTuple import MaxHeapTuple points = [(-2,4), (0,-2), (-1,0), (3,5), (-2,-3), (3,2)] def shortestDist(points, n): pointWithD = {} mHeap = MaxHeapTuple() for i in points: d = m...
d60427e8fb7de630a115d5bb05162ff338e04369
armgit5/algorithms
/python/interviewCake/kth_to_last_node.py
1,387
4.1875
4
# https://www.interviewcake.com/question/python/kth-to-last-node-in-singly-linked-list?utm_source=weekly_email&utm_campaign=weekly_email&utm_medium=email class LinkedListNode: def __init__(self, value): self.value = value self.next = None a = LinkedListNode("Angel Food") b = LinkedListNode("Bund...
c220a444c429a98bc49ddb74b7674049ed0595e8
armgit5/algorithms
/python/myCodeSchool/tree/getHeight.py
570
3.921875
4
# https://www.youtube.com/watch?v=hmWhJyz5kqc&index=3&list=PLamzFoFxwoNgvI2T5vagi6-wk0Vo8j5OF from tree import Tree import sys def getHeight(root): if root == None: return -1 leftHeight = getHeight(root.left) rightHeight = getHeight(root.right) return 1 + max(leftHeight, rightHeight) root =...
363da872320a2a053a19a8b94b63625e8115950c
armgit5/algorithms
/python/interviewCake/brackets.py
688
3.578125
4
a = "{[]()}" b = "{[(])}" def is_valid(brackets): openers_to_closers = { '(': ')', '{': '}', '[': ']' } openers = frozenset(openers_to_closers.keys()) closers = frozenset(openers_to_closers.values()) openers_stack = [] for char in brackets: if char in openers:...
fe63824d054f0216c55ea6e303e08d4c24adb382
armgit5/algorithms
/python/hackerrank/quickestWayUp/quickestWayUp.py
1,906
3.671875
4
# https://www.geeksforgeeks.org/snake-ladder-problem-2/ # https://www.youtube.com/watch?v=1pMNYQmtVVg # https://www.hackerrank.com/challenges/the-quickest-way-up/problem # ladders = [[32, 62], [42, 68], [12, 98]] # snakes = [[95, 13], [97, 25], [93, 37], [79, 27], [75, 19], [49, 47], [67, 17]] # ladders2 = [[8, 52], [...
1e5fdeac527c4c16e9ffe8fa997fab0d7da9addc
armgit5/algorithms
/python/test/smallestPosNotInA.py
827
3.765625
4
# https://codility.com/c/run/demo58PUSG-R6A # that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. # # For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. # # Given A = [1, 2, 3], the function should return 4. # # Given A = [−1, −3],...
1edef02df7be73ddc779598ba7fad54ee317f9dc
armgit5/algorithms
/python/geek/battle_ship.py
4,179
3.984375
4
# Ship class class Ship: def __init__(self): self.start_row = 0 self.end_row = 0 self.start_col = 0 self.end_col = 0 self.ship_number = "" self.ship_area = 0 # Make ships from string def make_ships(S): ship_one_string = S.split(",")[0] ship_one_string_1 = sh...
07e248588361855f9ed1e9de34585d77ea02848e
armgit5/algorithms
/python/byteByByte/nthToLastLinkedList.py
816
3.8125
4
# https://www.youtube.com/watch?v=i7v1UWlaYrI&index=2&list=PLNmW52ef0uwsjnM06LweaYEZr-wjPKBnj class Node(): def __init__(self, value): self.value = value self.next = None def nthToLast(node, n): curr = node follower = node # Move curr n steps further for i in range(n): if ...
296fcc5a3060d1cc516b3f2500876d52e8bda008
armgit5/algorithms
/python/csDojo/dynamic/fib.py
502
3.8125
4
n = 6 memo = [None] * (n+1) def fib(n, memo): if memo[n] != None: return memo[n] if n == 1 or n == 2: memo[n] = 1 return 1 result = fib(n-1, memo) + fib(n-2, memo) memo[n] = result print(memo) return result def fib_bottom_up(n): bottom_up = [0] * (n+1) bottom_...
649746d271e31558e2164cedb5d071c79eb75262
armgit5/algorithms
/python/amazonPractice2020/contact.py
993
3.703125
4
# https://www.hackerrank.com/challenges/contacts/problem queries = [['add', 'hack'], ['add', 'hackerrank'], ['find', 'hac'], ['find', 'hak']] def contacts(queries): contacts_dict = {} output_list = [] # Make dict iterating through all char in word def add(word): for i in range(1, len(word) +...
21347714d47babceee1e130a895b2d5ff9104e21
armgit5/algorithms
/python/csDojo/subsets.py
602
3.890625
4
# https://www.youtube.com/watch?v=bGC2fNALbNU&list=PLBZBJbE_rGRVnpitdvpdY9952IsKMDuev&index=6 arr = [1,2] def helper(arr, subset, i): if i == len(arr): print(subset) else: subset[i] = 0 helper(arr, subset, i+1) subset[i] = arr[i] helper(arr, subset, i+1) def subsets...
83e69478c72d4d3fa43741b192efa4a4e0d179ea
armgit5/algorithms
/python/LeetCode/jumpGame.py
1,403
3.65625
4
input = [2,3,1,1,4] # 2 # input = [1] # 0 input4 = [8,2,4,4,4,9,5,2,5,8,8,0,8,6,9,1,1,6,3,5,1,2,6,6,0,4,8,6,0,3,2,8,7,6,5,1,7,0,3,4,8,3,5,9,0,4,0,1,0,5,9,2,0,7,0,2,1,0,8,2,5,1,2,3,9,7,4,7,0,0,1,8,5,6,7,5,1,9,9,3,5,0,7,5] input2 = [1,2,1,1,1] input3 = [1,4,3,7,1,2,6,7,6,10] def jumpDFS(nums): if len(nums) <= 1: ...
65966c76f53c2c82946742b82b6fc947a9c6224d
armgit5/algorithms
/python/LeetCode/islandPerimeter.py
836
3.78125
4
# https://leetcode.com/problems/island-perimeter/ # https://leetcode.com/problems/island-perimeter/discuss/1333293/Python-solution-using-2-approaches-with-explanation from typing import List class Solution: def islandPerimeter(self, grid: List[List[int]]) -> int: count = 0 for i in range(len(grid...
9b78b1adb75653678460baee602a42cb6f1db702
VitoriaCarvalho/BinaryTrees
/Implementação/rbt.py
7,222
3.65625
4
import sys class Node: RED = True BLACK = False def __init__(self, key, color = RED): if not type(color) == bool: raise TypeError("Bad value for color parameter, expected True/False but given %s" % color) self.color = color self.key = key self.left = self.right = self.parent = NilNode.inst...
7ac1806260925c2f881407bd683073c66bec3b1a
Adefreit/cs110z-f19-t4
/Lesson 3/lesson3-ipo.py
334
4.03125
4
# Example Input-Process-Output Problem # Problem: Write an algorithm that gets two numbers from the # user, calculates the average, and outputs the result. # Step 1: Get the values value1 = int(input()) value2 = int(input()) # Step 2: Process the values average = (value1 + value2) / 2 # Step 3: Print the Result ...
bb827f77bd7a41990f6d03f370659b71f7db3389
Adefreit/cs110z-f19-t4
/Lesson 4/hogwarts.py
1,862
4.09375
4
# Storing Points gryffindor = 0 ravenclaw = 0 hufflepuff = 0 slytherin = 0 # QUESTION #1 q1_answer = input("How would you describe yourself?\n a) brave,\n b) studious,\n c) loyal,\n d) ambitious?\n") if q1_answer == 'a': gryffindor = gryffindor + 1 elif q1_answer == "b": ravenclaw = ravenclaw + 1 elif q1_answ...
17ee84361f73d22d35974ac286b8b344e7b3a7b2
Adefreit/cs110z-f19-t4
/Lesson 3/lesson3-challenges.py
762
3.8125
4
# Pre Class Challenge #1 #print('Good Morning', "Class") # Pre Class Challenge #2 #print( 'Good Morning') # Pre Class Challenge #3 #x = 5 #y = 4 #print("x + y") # Pre Class Challenge #4 #name1 = input() #print("Good Morning", name1) # Pre Class Challenge #5 #print('ready') print('to') print("learn") # Math Ex...
308d49c561b125ab02f20507f1e78c38aef09c34
Adefreit/cs110z-f19-t4
/Lesson 12/bouncing_balls_template.py
1,098
4.21875
4
import pythonGraph, math # Ball Radius BALL_RADIUS = 10 # Global Variables ball_1_x = 300 ball_1_y = 300 ball_1_x_velocity = 3 ball_1_y_velocity = 5 # Functions Go Here def erase_everything(): pythonGraph.clear_window(pythonGraph.colors.WHITE) def draw_ball(): pythonGraph.draw_circle(ball_1_x, ball_1_y, BAL...
e8141895e3549a57a2a8fe92c9246695863cd10d
Adefreit/cs110z-f19-t4
/Lesson 10/distance_formula.py
141
3.609375
4
import math def distance_formula(x1, y1, x2, y2): distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) return distance print(distance)
56028fe97b0c3b66a1a6054d5dd062bebe194220
gokulvanan/Learning
/datastructrues/python/sort.py
2,255
3.921875
4
def insertion(data): for i in range(0,len(data)-1): while j >= 0: if greater(data,j,j+1) > 0: data[j],data[j+1] = data[j+1],data[j] else: break j -= 1 def shell(data): h = 1 while h < ( len(data)/2 ): h = 3 * h + 1 #incr...
1d49738c5a38b9e7241b7989d845e0f5dd2a383f
lalitcse/python
/#001/first.py
188
4.09375
4
num1 = input('Enter 1st number : ') num2 = input('Enter 2nd number : ') num3 = input('Enter 3rd number : ') print(f"Average of three number : {(int(num1) + (int(num2) + (int(num3)) / 3}")
ba90c0ed66a04ce8feddf1403d95c706e275ca79
caver24/nanodegree
/phython-testing/test.py
1,716
4.4375
4
#this is some phython testing #print("hello world") a = [1, 2, 3, 4, 5, 15] def say(msg): print(msg) ''' Programming background in Python. The first exercise allows you to assess your ability to program in Python. As a data analyst, you will spend much of your time writing code and programs to work with data or to...
a96464f7f12670c6a6dcb53fa3bacaaee7fa47ad
spnear/Python-Advanced-Concepts
/decoradores.py
507
4.1875
4
#Un decorador es un closure especial: """ Un decorador es una función que recibe como parámetro otra función, le añade cosas, la ejecuta y retorna esta función modificada (diferente) """ def decorator(func): def wrapper(): print('Added this to original func') func() return wrapper def hello():...
e88e71f24d78a2108881c43c5f698891ea58e308
Abhiroop97204/Python_
/Abhiroop's Calculator.py
412
3.796875
4
import main print("Welcome To Abhiroop's Calculator") x=int(input("Enter First Number: ")) y=int(input("Enter Second Number: ")) print("1. multiply, 2. divide, 3. add, 4. subtract") f=int(input("Enter Your choise: ")) if f == 1: print("value is: ",a*b) if f == 2: print("value is: ", a / b) if f == 3: ...
a4987425509fc8c41fa9cec92acab70bab0ae68d
ZeroPoint095/PROG
/les06/werkboek/Final_Assignment/Final_Assignment6.py
685
3.578125
4
### DEEL 1 ### def code(str): str.split() encripted=[] for letter in str: letterCode=ord(letter) encripted.append(chr((letterCode)+3)) ''.join(encripted) print(''.join(encripted)) code('abAW ') ### DEEL 2 ### def tabel(): t=[['Tuple', 'JA', 'NEE', 'JA', 'JA'], ['Dictionar...
c9f2b96fadcb430784fed4fbd3f5ba8980a0a6af
Kolbynko/Kalkulacka
/#python kalkulacka.py
491
3.546875
4
#python kalkulacka a=str(input('Zadaj priklad: ')) znamienka=[ a.find('+'), a.find('-'), a.find('*'), a.find('/'), ] def poloha(s, num): return int(s[:num]), int(s[num+1:]) if znamienka[0]>0: x,y=poloha(a, znamienka[0]) print(x+y) if znamienka[1]>0: x,y=poloha(a, ...
6dfd681e7961838ebe41f635eb53196788aaf2b9
MariusKlassen/Euler_Verfahren
/NiMoNa_Aufg3/Aufg3b.py
507
3.515625
4
import numpy as np import matplotlib.pyplot as plt h=0.1 alpha=1 x0=0.5 y=int(7/h) def f(x): return -alpha*x x=np.zeros(y+1) t=np.linspace(0, 7, y+1) x[0]=x0 for i in range(y): x[i+1]=x[i]+h*f(x[i]) a = np.linspace(0, 7, 256) b=np.exp(-alpha*a)*x0 plt.plot(t, x...
bd984215d9545eca93c9c1bc20e062ddc81c94e7
AlirezaPNouri/DataMining
/Codes/TextCleaning.py
1,663
4.03125
4
# Functions for preprocessing the text before feature extraction # Author: Alireza import string import re from nltk.corpus import stopwords from nltk.tokenize import word_tokenize # This function removes stopwords from a text. def remove_stopwords(str_): stop_words = set(stopwords.words('english')) word_tokens = ...
64700af93bc97b381a482172c53e01483a32b51a
richzw/CodeHome
/Python/readLast10LinesOfFile.py
848
3.703125
4
import os def reversed_lines(file): "Generate the lines of file in reverse order." part = '' for block in reversed_blocks(file): for c in reversed(block): if c == '\n' and part: yield part[::-1] part = '' part += c if part: yield part[::-1...
8da65d5312ba6fb4c126269076eb5d01dc6645d0
richzw/CodeHome
/Algorithm/NumberOccuring/nk+b.py
3,124
3.5
4
#Ref: http://stackoverflow.com/questions/9442958/find-the-element-occurring-b-times-in-an-an-array-of-size-nkb?rq=1 """ Given an Array of size (n*k+b) where n elements occur k times and one element occurs b times, in other words there are n+1 distinct Elements. Given that 0 < b < k find the element occurring b times....
f3638bc6fd1fe1aaec9aee96ccfd0e723016dba0
richzw/CodeHome
/Python/Questions/StringShuffle.py
1,442
4.3125
4
''' We are given 3 strings: str1, str2, and str3. Str3 is said to be a shuffle of str1 and str2 if it can be formed by interleaving the characters of str1 and str2 in a way that maintains the left to right ordering of the characters from each string. For example, given str1=”abc” and str2=”def”, str3=”dabecf” is a vali...
fb94d40d7ec9097dd4116945db93f61d99319bd3
richzw/CodeHome
/DataStructure/SubMatrixSearch.py
2,365
4
4
""" I give quotation mark because what I mean is for example: B = [[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20]] suppose we select row 2,4 and col 1,3, the intersections will give us A = [[6,8], [16,18]] My question is suppose I have A and B, is there a way that I can find out whi...
bc521026cfa90f21e36ff48edd4ec1f1b71ba89c
richzw/CodeHome
/DataStructure/AStar/GreedyBFS.py
553
3.640625
4
def heuristic(a, b): # Manhattan distance on a square grid return abs(a.x - b.x) + abs(a.y - b.y) def greedy_bfs(graph, start, goal): frontier = PriorityQueue() frontier.put(start, 0) came_from = {} came_from[start] = None while not frontier.empty(): current = frontier.get() if cu...
0b8cfa3f4380356402fde028273e8f8aec1b6773
richzw/CodeHome
/Algorithm/Permution/Permutation.py
509
3.859375
4
def permutation(string): '''(str) -> list Get all permutation of element >>> permutation('abc') ['abc', 'bac', 'bca', 'acb', 'cab', 'cba'] ''' if len(string) == 0 or len(string) == 1: return string result = [] cur_char = string[0] ret_list = permutation(string[1:]) ...
2d82ddb254604639ab413bd99df784a85ab7bfff
yinjinghao211/PythonTest
/learn9/Bomb.py
467
3.65625
4
# 冒泡排序 import random list_data = [] for i in range(10): list_data.append(random.randint(0, 20)) print(list_data) list_len = len(list_data) - 1 for i in range(10): sort_over = True for j in range(list_len - i): if list_data[j] > list_data[j + 1]: tmp = list_data[j] list_da...
4e905706201e5f9e07f8650ab69faa0941d4d240
yinjinghao211/PythonTest
/learn6/tuple.py
844
4.3125
4
# 要元组只包含一个元素,必须要有一个逗号,用于和普通分组操作区分 tuple1 = ("sad",) tuple2 = ("what", "is", "python") print(type(tuple2)) tuple3 = "what is python" print(tuple3) tuple4 = ([1, 3, 5, 8]) print(tuple4, type(tuple4)) child = [("age", "height"), [10, 20]] child1 = list(child) child2 = list(child1) # 可以看到id都是不一样的 print(id(child), ...
975e30f89639259781701ce1c9e0e6b25f0a03bd
diacarcor/day-5-3-exercise
/main.py
203
3.921875
4
#Write your code below this row 👇 total = 0 for number in range (1,101): if number % 2 == 0: total += number print(total) total = 0 for number in range (2,101,2): total += number print(total)
4a765e5ca0d994bbd38c77d3ad8834261863b167
IIeming/python
/num.py
3,573
3.96875
4
# coding: utf-8 ''' 把一个浮点数分解成整数部分和小数部分字符串 num 需要被分解的浮点数 返回分解出来的整数部分和小数部 第一个数组元素是整数部分,第二个数组元素是小数部分 ''' def divide(num): # 将一个浮点数强制类型转换为int型,即得到它的整数部分 integer = int(num) # 浮点数减去整数部分,得到小数部分,小数部分乘以100后再取整得到2位小数 fraction = round((num - integer) * 100) # 下面把整数转换为字符串 return (str(in...
ad2ad18e0980ce1224c56634f90eb4497c5aa59b
goldsborough/euler
/23.py
1,680
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum...
4467d70d51bcdb2ebdccaf274ded70bd56b61ab8
goldsborough/euler
/5.py
757
3.765625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? """ def brute(n): x = 1 while True: for m in range(1, n + ...
0299a181d9855b23862afcfa7e3a70b2998b7a42
goldsborough/euler
/28.py
666
4.25
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13 It can be verified that the sum of the numbers on the diagonals is 101. What ...
da96ed3c489839cd3a5b8886b36cd8276d1e3f89
AP-MI-2021/lab-4-MeltisDragos
/main.py
2,783
4
4
def citire_lista(): l = [] givenString = input("Dati numerele, separate prin virgula: ") numbersAsString = givenString.split(",") for x in numbersAsString: l.append(int(x)) return l def printMeniu(): print("1.Cititi lista") print("2.Afisare lista") print("3.Elimina numerele pri...
8257e25d0b4c196c4a530d059484a28402d6ba11
rahulj1601/Python
/Excel, Word, and PDF Documents/Word Text to String.py
366
3.578125
4
import docx #get all text from word document in string def getText(filename): doc = docx.Document(filename) fullText = [] for para in doc.paragraphs: fullText.append(para.text) return '\n'.join(fullText) print(getText('/Users/rahul/Documents/Programming/Automating the Boring Stuff with Python...
6aa9afdf450f2d8271d444834c06b3eb7f6d0ffa
rahulj1601/Python
/Project Euler/P23.py
830
3.625
4
import time from math import sqrt def is_abundant(num): divSum = 1 for i in range(2,int(0.5*num)+1): if num % i == 0: divSum += i return divSum > num def main(): start = time.time() upp_limit = 28123 total = 0 abundantNums = set(x for x in range(1,upp_...
835a32f760d46e36f7fcf3cc10f2990e27b473d8
rahulj1601/Python
/Other/Reference Numbers.py
454
4.25
4
spam = [0,1,2,3,4,5] cheese = spam cheese[1] = "hello!" print(cheese) print(spam) # This also changes spam[1] to "hello!" # Because the variable name cheese will obtain the reference to the list spam # So changing the list stored at that reference will also alter spam # Because spam and cheese are connected to the same...
4cfd5680f78b355e6cb49a1e4d9dfb822f9a9d54
rahulj1601/Python
/Other/Guess the Number.py
658
4.0625
4
# Writing a Guess the Number Program import random num = random.randint(1,20) gotIt = False name = input("Enter your name: ") print("Hey " + name + " I am thinking of a number between 1 and 20, can you guess it?") for i in range(1,7): guess = int(input("Guess the number: ")) if guess > num: print("To...
e6253cfda96aa979af31a3d5d959c6a4a8de8943
PrathikT24/Python_Basics
/lovescore.py
445
3.6875
4
boy=input(" Enter boy's name ") girl=input("Enter girl's name ") together=boy+girl relation=together.lower() t=relation.count("t") r=relation.count("r") u=relation.count("u") e=relation.count("e") true=t+r+u+e l=relation.count("l") o=relation.count("o") v=relation.count("v") e=relation.count("e") l...
5a8d2c2c6649761b4c2a63dd219c8d71adc8ce6e
Jameswafy/VirtualMart
/Shopping_List-master/apptest/ivo.py
3,905
3.828125
4
class Item(object): def __init__(self, name, price): self.name = name self.price = price class Cart(dict): def __init__(self): self.cartlist={} self.last_itemid=0 def add_item(self, item, amount): try: if item in self.cartlist.keys(): ...
e09bafff6a2b083348f00ebeb013bd6d64b9ff7b
CS207Project/cs207project
/other/old_TimeSeries.py
1,445
3.859375
4
import reprlib import itertools class TimeSeries: """ A class for representing a time series, initiated with data stored as a list. Formats data in shortened notation when printing. Attributes ---------- data : list values in the timeseries Methods ------- Tests ...
db35e181085b2278d3253108f18bea79069dd6fb
DSandman/csc521
/python-quirk/interpreter.py
15,259
3.859375
4
import sys import pprint import json pp = pprint.PrettyPrinter(indent=1, depth=100) """ This program executes the quirk program of the input parse tree ***parse tree is in json form*** print will write to the quirk.out file. Bonus: checks for if return length matches assignment length and if index is with in return ...
80678162ae2d816e260dd514fc0451281ee9ffaa
dsreekant211/python
/Desktop/python/sree.py
540
4.03125
4
#print("how many meteres you have travelled") #kms = input() #meters = int(kms)*1000 #print(f"i have travlleld {meters} meters today ") #print("give length and breadth of rectangle") #length = input("give length in meters") #breadth = input("give breadth in meters" ) #area = 2*(int(length)*int(breadth)) #print(f"area...
b2a1683846ee194ffe5a277a119259e7d701b896
atlj/same-server
/run_server.py
373
3.8125
4
from main import main ip = input("IP >> ") while 1: port = input("PORT >> ") try: port = port.replace(" ", "") port = int(port) if port == "": print("portu yanlış girdiniz") continue except ValueError: print("portu yanlış girdiniz") continue ...
c9b52381fe11a70e3da2a8bdef3646f48f5e4af9
vsaivignesh/AlgosTask3
/task 3 q 3.py
354
3.734375
4
integer=int(input("Enter n \n"))+1 out=0 increment=1 var=0 for i in range(2,integer): if(i>2): for j in range(2,i): if(i%j==0): var=1 break if(var==0): out=out+increment increment=increment+1 else: var=0 pri...
13a80c902ca88152f73c33cfb5233fb9a4f50cf2
tarbitrary/pythonlearning
/advanced_features/generator.py
215
3.796875
4
#!/usr/bin/env python #-- coding: utf-8 -- g = (x * x for x in list(range(10))) for x in g: print(x) print("*********************************") g = (x * x for x in list(range(10))) while True: print(next(g))
c33f52f7b59bf216b8b31d324b2fe0b8f9b96976
tarbitrary/pythonlearning
/advanced_features/iteratoranditerable.py
1,906
4.3125
4
#!/usr/bin/env python #-- coding: utf-8 -- from collections import Iterable from collections import Iterator #迭代器Iterator与可迭代对象Iterable,tuple, list,dict, str都是可迭代对象但是都不是迭代器生成器既是可迭代对象也是迭代器, 简单来说可用next()方法迭代的对象就是迭代器 t = {1, 2, 3} l = [1, 2, 3] s = ([1, 2, 3]) d = {1:1, 2:2, 3:3} g = (x * x for x in range(10)) r = range...
3fff1a80eeb2ebf1955cc80e46ca132610c6c880
harshuop/GeeksforgeeksEXE
/factorial_of_a_number.py
106
3.75
4
def fac(a): return 1 if (a==0 or a==1) else a * fac(a-1); a = int(input('Your num: ')) print(fac(a))
9553db5dff6b0bd0c76f3adc3e65f2d2478fa995
srivastavas08/IndianStateGame
/main.py
3,613
3.5
4
import turtle import pandas # libraries to be imported import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders screen = turtle.Screen() screen.title("Indian States/UT Game") image = "blank.gif" screen.addshape(i...
b1043bc3432b2759e5072abadd1ac0eb674ba4f4
lanttern/Algorithic_thinking-Rice-
/Module2/project2.py
2,496
4.0625
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 13 21:55:41 2014 For the Project component of Module 2, you will first write Python code that implements breadth-first search. Then, you will use this function to compute the set of connected components (CCs) of an undirected graph as well as determine the size of its l...
d1f7e0ef4e43aab7ee755e551ceabcd2a3add89f
tsingh94/Data-Structures
/Stack.py
865
4.125
4
class Stack(object): #constructor for the stack #takes no arguements def __init__(self): self.container = [] #returns true if empty and false otherwise def isEmpty(self): if len(self.container) == 0: return True else: return False #this method adds an element to the front of the stack def push(s...
bcb24af655e7e6212f8bb612e02cebe598e80cc7
j4eliu/Python
/Number Reduction Game.py
2,715
4.0625
4
from random import * print("Welcome to the Number Reduction Game!") print("You will be playing against a computer.") print("") order = input("Would you like to go first? (Y/N): ") print("") if order in ["Y", "y"]: num = int(input("Enter a starting number: ")) else: print("The computer will ...
7e803639de7c81b9e790b66c2c333d9772911067
n27jain/PID_GeneticAlgorithm
/logistics.py
472
3.515625
4
from os import wait3 import random def printCleanMatrix(array): for list in array: print(list) print("DONE \n") def popMatrixCol(matrix, col): for i in range(len(matrix)): try: if(len(matrix[i]) >= col+1): matrix[i].pop(col) except: print("f...
4467ed309aa6c235bc35f1bbadb94babc93c24a8
gtang31/algorithms
/llist/merge_sort.py
1,447
4.0625
4
""" Given a linkedlist, sort it into ascending order. We can use the merge sort to accomplish this in O(nlogn) time. """ from llist.linkedlist import Node def merge_sort(ll_head): """ @param ll_head. Head node of a linked list @return ll_head. Head of the the sorted linked list use divide and conquer ...
002f0200ea58f21f62a31ff20282a7f77912dda1
gtang31/algorithms
/tree/trie.py
2,787
4.15625
4
""" Implement the Trie data structure. A Trie is essentially a special-case of the tree data structure, where each node in the trie contains up to 26 children, one for each letter in the alphabet. A word is complete if it is followed by an asterisk(*). """ from tree.btree import BTree, Node __author__ = 'Gary Tang' c...
3e9717aee9a35af279da11a060068901c1a46501
gtang31/algorithms
/dynamic_programming/smallest_path_sum.py
2,187
3.71875
4
""" Given a m x n self.grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Assume 0 <= self.grid[i][j] < 10 To measure performance, use: python -mtimeit -s'from dynamic_programming.smallest_path_sum import MinPathSum' 'MinPathSum(70, ...
bc0133ef5badc6a6fcdf12ea049e5abdfdb558b0
gtang31/algorithms
/llist/find_cycle.py
2,257
3.875
4
""" Detect cycle in a linked list and return the head of the cycle. We use a slow and fast pointer traversing the linked list, if the fast pointer reaches a null then no cycle exists. Otherwise the slow and fast pointer will eventually meet. """ from llist.linkedlist import Node __author__ = "Gary Tang" def has_cycle...
dcbbc6954037b86ea948cd917e7be503c270619c
gtang31/algorithms
/dynamic_programming/valid_parentheses.py
2,604
4.1875
4
""" Create an algorithm to print all valid combinations of N pairs of parentheses To test the run time between a recursive vs. memoization approach: python -mtimeit -s'from dynamic_programming.valid_parentheses import ParenthesesSolution' 'ParenthesesSolution().recursive(13)' python -mtimeit -s'from dynamic_programmin...
3ef354d8d77221b11c71b404a193819a5f49d9e9
gtang31/algorithms
/sort/MergeSort.py
1,862
4.5
4
""" Performs a Merge Sort. _do_merge() function takes two lists and combines them into one sorted list. merge_sort() function takes any list and sorts it using merge sort paradigm """ __author__ = "Gary Tang" def _do_merge(_a, _b): """ merges two lists into one ordered list @param _a: list[int] @para...
b30cd616706b6adf7601e23e8856677691a72619
gtang31/algorithms
/search/find_words.py
2,883
4.03125
4
""" Given a 2D board and a list of words from the dictionary, find all words in the board. Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word. """ import pdb c...
8d90837f3d73cfeba7053b04981a2e7ea5d1849f
gtang31/algorithms
/array_string/longest_consec_subarray.py
1,045
4.09375
4
""" Given an unsorted array of integers, find the length of the longest consecutive elements sequence. Your algorithm should run in O(n) complexity. Example: Input: [100, 4, 200, 1, 3, 2] Output: 4 Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. """ def longest_co...
a5a7ffb037ae4bc10a89ba4d42830dd9e182aed8
TakeMeHigher/mssf
/连续最大和.py
725
3.5
4
# -*- coding: utf-8 -*- """ 摘 要: 连续最大和.py 创 建 者: Chentaizhang 创建日期: 2019/2/13 16:27 """ def maxList(a): maxpre = realmax = a[0] length = len(a) for i in range(1, length): if realmax <= 0: realmax = a[i] else: realmax += a[i] if maxpre < re...
fcafbeea62774adb05c85d9b48adaa8d38a576f5
TakeMeHigher/mssf
/排序算法/二叉堆.py
1,775
3.953125
4
class Heap(object): def __init__(self): self.size = 0 self.heap_list = [0] def build_heap(self, data): i = len(data) // 2 self.size = len(data) self.heap_list = [0] + data while i > 0: self.pre_down(i) i -= 1 def pre_down...
fa1d3f15db3f9a1414adcd3c333d180fbe7139e7
TakeMeHigher/mssf
/二叉树/二叉堆.py
1,896
4.03125
4
""" 摘 要: 堆排序.py 创 建 者: Chentaizhang 创建日期: 2020-07-10 18:10 """ class Heap(object): def __init__(self): self.size = 0 self.heap_list = [0] def build_heap(self, data): i = len(data) // 2 self.size = len(data) self.heap_list = [0] + data while...
50adbf616d1c66a1cca1f71b7dc2104d01f91c29
TakeMeHigher/mssf
/排序算法/选择排序.py
512
3.609375
4
# -*- coding: utf-8 -*- """ 摘 要: 选择排序.py 创 建 者: Chentaizhang 创建日期: 2019/2/13 14:14 """ def func(li): """ :param li: :return: """ for i in range(len(li)-1): mic = i for j in range(i+1, len(li)): if li[j] < li[mic]: mic = j if ...
ec546c01a4d5fb997bfbebfb34bd637180d59f76
TakeMeHigher/mssf
/排序算法/冒泡.py
549
3.515625
4
# -*- coding: utf-8 -*- """ 摘 要: 冒泡.py 创 建 者: Chentaizhang 创建日期: 2019/2/13 13:54 """ def mp(li): """ :param li: :return: """ for i in range(len(li)-1): change = False for j in range(len(li)-i-1): if li[j] > li[j+1]: li[j], li[j+1] =...
6a86e665c2df861b7918d1719dd142d98ec267d3
albertobetan/Python
/Navigate.py
561
4.15625
4
#This code helps the user to navigate a file fileName = input("Enter the input file name: ") filehandle = open(fileName, 'r') fileList = [] count = 0 with open(fileName, 'r') as f: for i in filehandle: count += 1 fileList.append(i) print("Total number of lines is:", count) userLine = int(input("Ent...
dba91891043ba6c1d5cb82d9757c7da818b5bf7b
HarambeLover99/Python
/chase_scully134.py
2,233
3.71875
4
from __future__ import print_function # must be first in file import random def food_id(food): ''' Returns categorization of food food is a string returns a string of categories ''' # The data fruits = ['apple', 'banana', 'orange'] citrus = ['orange'] starchy = ['banana', 'potato']...
0c9115619b685523872e68fc685085476492fb2a
staceylii/csci127-assignments
/final_2/dict.py
906
3.765625
4
def addline(d, line): lower = line.lower() for i in lower.split(): if i[0] in d: d[i[0]].append(i) else: d[i[0]] = [i] return d def spellcheck (d,word): lower = word.lower() if word in d[lower[0]]: return True else: return Fa...
a6451722bec9d5258df8f32d3da45538a22192e7
staceylii/csci127-assignments
/final_2/scrabble.py
719
3.6875
4
def canMakeWord(letters,word): wordlist = list(letters) for i in word: if i in wordlist: wordlist.remove(i) else: return False return True print(canMakeWord("ladilmy", "daily")) print(canMakeWord("eerriin", "eerie")) print(canMakeWord("orrpgma", "program")) print(can...
279b611e38c9d1df02212cf85ac1cf8a3d43e896
kylessmith/SASE-mapper
/SASE_mapper/rand.py
1,409
3.609375
4
from random import random import numpy as np def multi_random(range_max, size): """ requires range_max: upper bound of range (0 to range_max) size: tuple of dimensions returns: array of random integers without replacement """ sample_arr = np.zeros(size, dtype=int) sample_ran...
1689d7dada6ef53ee1a40db279f068c18059c466
webtester1999/hello-world
/no_3.py
168
3.84375
4
list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] list_2 = [] for x in list: if x < 5: list_2.append(x) else: pass print(list_2)
f478ae51defe24215746066a0465208ea70f7405
icorrs/python_learning
/stack_queue.py
875
4.1875
4
#先确认是stack还是queue,然后实现堆栈/队列,python核心编程6.15节 stack=[] def push(): new_string=input('enter new string:') stack.append(new_string) def pop(): if len(stack)==0: print('stack is empty,can\'t pop') else: stack.pop() def remove(): if len(stack)==0: pring('stack is empty,can\'t remov...
3966cf5f96eddb16830dd9a72a9a9c1c6be4cc2b
icorrs/python_learning
/diamond_class.py
1,420
3.828125
4
#the use of super in diamond class inherite question;in sup=True condition, # base_class's call_me run one time, # in sup=False condition,base_class's call_me run two times. class BaseClass(): num_base_calls = [0] def call_me(self): print('calling base class') self.num_base_calls[0] += 1 class...
3a8f9532204dec718b63ab9f69b3263a7e772a86
hkourilova/pyNMR
/t1BPP.py
3,343
3.5625
4
# -*- coding: utf-8 -*- """ This module provides - molarity() calculate the molarity of a solution given the substance or molar Mass of the solute and the volume - t1() calculate the T1 for a given nucleus based on the BPP formula referenced therein. """ import sys import numpy as np import scipy.constants as const ...
270265b9510cd3cf30670cbf2c6f4174038f358c
cltl/python-for-text-analysis
/Chapters/the_program_v2.py
268
3.671875
4
from utils import count_words from utils import x from utils import python words = ['how', 'often', 'does', 'each', 'string', 'occur', 'in', 'this', 'list', '?'] word2freq = count_words(words) print('word2freq', word2freq) print('x', x) print('python', python)
ab2bdadab25c339040d15e10021b0bd085691f40
harshitb8/learning
/binary_tree/traversal.py
2,489
4.6875
5
""" To print the tree in level traversal """ from tree_utils import * from intro import * # ================================== using recursion (tough) def printLevelOrder(root): """ This is using recursion """ print("---- printing below the level traversal of the tree -----") print("=============...
079e30764522ff43017c8697f544103339d45b5a
dacardonaj/pullrequest
/misaludo.py
98
3.640625
4
nombre = "nombre" edad = 28 print("mi nombre es {} y tengo una edad de {}" .format(nombre, edad))
dd6dd09e2b6cbc792d836309da48b278730315e3
micycle1/Project-Euler
/euler 33.py
260
3.546875
4
for y in range(1, 99): # bottom for x in range(1, y): # top if len(str(x)) == 2 and len(str(y)) == 2: if x / y == int(str(x)[-2]) / int(str(y)[-2]) and not str(y)[1] is "0" and not str(y)[1] == str(y)[0]: print(x, y)
fcc6ae80847800d5362db95bb27645fb61735e1a
marrecs/py_dragon
/dragon.py
1,675
3.921875
4
import random import time def mostrarIntroducción(): print ('Estás en una tierra llena de dragones. Frente a tí') print ('hay dos cuevas. En una de ellas, el dragón es generoso y') print ('amigable y compartirá su tesoro contigo. El otro dragón') print ('es codicioso y está hambriento, y te devo...
b25d724f2b024fe82d1a5d001a2e22ce309bf0cc
lanchaoxiang/python
/2048.py
5,076
3.78125
4
#!/usr/bin/python #-*-coding:utf-8-*- import random import copy def display(mtrx): #output function a = ("┌", "├", "├", "├", "└") b = ("┬", "┼", "┼", "┼", "┴") c = ("┐", "┤", "┤", "┤", "┘") for i in range(4): print a[i] + ("─" * 5 + b[i]) * 3 + ("─" * 5 + c[i]) for j in range(4): print "│%4s" % (...
3096a1cbd430d29c538217930308460587888394
ynonp/basic-python-non-devs
/session1/04_loops_while.py
382
4
4
# Two important loops: # while # for ##### While Loop x = 10 while x > 0: print(f"{x} bottles of beer on the wall") # x -= 1 x = x - 1 # while True: # try: # number = int(input()) # print(f"Wow that WAS a number {number}") # if number > 99: # break # # except...
0b69753ace3035b765637cee78952c5285978512
ynonp/basic-python-non-devs
/session3/01_reading_text_files.py
219
3.71875
4
# File Handle with open('demo.txt', encoding='utf8') as file: max_line_length = 0 for line in file: if len(line) > max_line_length: max_line_length = len(line) print(max_line_length)
15c52e6a28c82b11b79a8d9caca0e6d7b2fb636c
micxmusic/Tour-Itinerary-Planner
/reference.py
892
3.96875
4
""" function takes in a place name and finds k number of locations closest to that place from the list of locations """ def kclosest(place, k, locations): sorted_locations =[] output = [] #calculates distance of each location and adds to new list a tuple #containing location name and correspo...
4cbe8a585094ae2cd0cb5739a1cf20d27e409312
BlackDevil738/Area-and-perimeter-of-rectangle-Square
/Area and perimeter of rectangle & Square.py
1,850
4.28125
4
class Area_and_Perimeter: #Function To Define Wheather it is a Square Or Rectangle def Square_rectangle(length,breadth): if length == breadth: return "It's A Square" else : return "It's A Rectangle" #Function to Find Area def Area(length,breadth): ...
77b7f26285f07583fe3b9424a9123db335ab275a
jameskirkpatrick/DarkHalo
/geometriclib.py
1,065
3.59375
4
"""geometriclib.py functions used to work out geometric stuff """ from math import sqrt, cos, sin,pi from numpy import arctan2 """ modulus returns the modulus of a 2D vector""" def modulus(coord): return sqrt(coord[0]**2 + coord[1]**2) """angle gets the angle of a 2D vector wrt to the origin """ def angle(coor...
71cae83d2bfbbccb61708e276aeaab6cafa08d31
heatheness/algorithmic-toolbox
/week_3/dot_product.py
476
3.671875
4
#Uses python2 import sys def min_dot_product(a, b): #write your code here res = 0 new_a = sorted(a) new_b = sorted(b, reverse=True) res = sum(map(lambda x: x[0]*x[1], zip(new_a, new_b))) return res if __name__ == '__main__': input = sys.stdin.readlines() data = [] for line in inpu...
775520b58e5e7e4796bc56471acbd20772ebb7b0
apbfor/python
/pz5/pz5reader.py
1,803
4
4
"""Read files""" from abc import ABC, abstractmethod import json import xml import xml.etree.ElementTree as elemTree class Reader(ABC): """Abstract class""" @abstractmethod def read(self, filename): pass class ReaderJson(Reader): """Read JSON files""" def read(self, filename): "...
915c93e79e7791e5b715ae2b37cc91f974a3d7be
WangYihang/CrackMe
/templates/keygen.py
724
3.5625
4
#!/usr/bin/env python # encoding:utf-8 import sys def check_password(username, password): v2 = 0 v7 = 0 for k in password: v7 = v2 v3 = 0 if (k > ord("0")) and (k < ord("9")): v3 = 1 v5 = v7 if v3 == 1: break v5 = ord(...
bc10c77edbfc9db9efc8393fbe25d0c2abf82528
vanlintbram/DEVASC
/python/myLocation.py
358
3.84375
4
class Location: def __init__(self,name, country): self.name = name self.country = country def myLocation(self): print(f"{self.name} lives in {self.country}") loc1 = Location("Bram", "Grimbergen") loc2 = Location("Ine", "Humbeek") loc3 = Location("Jonas", "Mechelen") loc1.myLocation() ...
17628b1b0cd074aa0ead887799558c31f20c0e61
guilhermepirani/cs50x
/pset6/cash/cash.py
440
3.921875
4
from cs50 import get_float # Get change owed value while True: owed = get_float("Change owed: ") if owed > 0: break # Trasforming dollars to cents, making sure it's an integer cents = int(owed * 100) coins = 0 # For each value in the list it divides cents by the value # Adding the result to coins and...