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
e6d1ce3e8d16adfa28f60af86e809f5d792c4875
YusraMasoodUIT/Quiz_Question
/Quiz Question.py
3,297
4.03125
4
print("Yusra Masood ") print("18B-093-CS (A)") print("Quiz Question") print("\n") def cost(): cups = int(input("How many cups of tea do you want to purchase ")) cost = 25 * cups print("Your total bill is " +str(cost)+"Rs") print("\n") amount = int(input("Please Enter your amount ")) ...
4522354305d451a192f2047c78872d9df280443a
zyonshepherd/standard_algorithms
/example/standard_algorithms_dr_g_start.py
582
4
4
def loadArray(thisArray): print("loadArray was called") def printArray(thisArray): outString = "" for n in thisArray: outString = outString + str(n) + " " print(outString) numElements = len(thisArray) print("there are {} elements in the array".format(numElements)) def sumArray(): p...
c3aeacb86fae64c4db1824fb001618456d9315cd
MaestroAshmin/Cryptography
/vignere.py
616
3.875
4
plain_text=input('Enter plain Text: ') plain_text=plain_text.lower() cipher_text='' enc_key=input('Enter Key: ') enc_key=enc_key.lower() keys='abcdefghijklmnopqrstuvwxyz' plain_text2='' while len(enc_key)<len(plain_text): enc_key+=enc_key if len(enc_key)>len(plain_text): enc_key=enc_key[:len(plain_text)...
9a699b2104e9ad8ffc98f79c3744a7bfa14f0e02
IamAfrica/My-Python-Code
/Exam3.py
1,349
3.828125
4
#Jordan Darling made this 3/19/17 #Using randomization, lists, and loops to make a game import Rad import random def cards(choices): attempts = 1 keepGoing = True while keepGoing: first = Rad.userInt("Pick the first card to turn over (0-9):") second = Rad.userInt("Pick the second card to t...
c708d8c2b19319bd58f6cabb4b5783cbd43e3b4f
IamAfrica/My-Python-Code
/Sorting.py
208
3.84375
4
list = [98, 77, 87, 93, 66] newlist = sorted(list, reverse = True) #print newlist d = {'Math' : 98, 'English' : 77, 'Python' : 87, 'Yoga' : 93, 'Circuits' : 66 } newD = sorted(d, reverse = True) print newD
d95e5ca57799c5d0a423614459dab1174e4bf04a
IamAfrica/My-Python-Code
/HW7.py
793
3.875
4
# Jordan Darling made this on 4/9/17, uses basic json principles # Professor names: Kebra Ward, Christopher Thomas, Jeff Parkman, Emily Maher, Louis Stelling, Mark Cohen import json import Rad # Reads the json file def read(): jsonTxt = "" f = open('Prof.json') for line in f: line = line.strip() ...
d6c22588bb455310e1560bebf0987015a88fc38f
IamAfrica/My-Python-Code
/Malcorps.py
418
3.5
4
print 'How many malcorps did you find on planet Exflon?' , Exflon = raw_input() print 'How many malcorps did you find on planet Mobiles?' , Mobiles = raw_input() print 'How many malcorps did you find on planet Monsantoes?' , Monsantoes = raw_input() Total = int(Exflon) + int(Mobiles) + int(Monsantoes) print 'You found ...
1a1539ab53eb4e1874901c1a2b11f4eaf590afa5
IamAfrica/My-Python-Code
/HotDog.py
1,307
4.03125
4
# Jordan Darling made this 3/5/17 # Uses While loops, time, and random to make a hot-dog eating contest import Rad import random import time def countDogs(): name = Rad.userString("Pick a winner (Tom, Sally, or Fred):") print "Ready, Set, Eat! \n" TomDogs = 0 SallyDogs = 0 FredDogs = 0 keepGo...
f90ffb94499c817424427c3a657d4268ed30995c
lw75251/leetcode
/Python_Solutions/283_Move_Zeroes.py
654
3.78125
4
class Solution: """ My Solution: One Pass O(n) Solution IDEA: Let | be a divider such that everything to the left are non-zero elements. As we iterate through the array, when we reach an element that is nonzero we swap then increment the divider. # Time Complexity: O(n) # Space Complexity...
4b4c8aabc4943b5cf79a7022a77fc8e0bb430b56
lw75251/leetcode
/Python_Solutions/441_Arranging_Coins.py
1,255
3.53125
4
class Solution: """ My Solution 1: O(n) Brute Force Solution IDEA: Subtract the ith row starting at 1. We keep incrementing i until n-i is negative (which means we went over). Thus, we have to return the i-1th row. # Time Complexity: O(n) # Space Complexity: 1 """ def arrangeCoins...
9393924b810d7591af562a8e1e6fa58d7ff7eeea
lw75251/leetcode
/Python_Solutions/1189_Maximum_Number_of_Balloons.py
2,526
3.921875
4
import collections class Solution: """ My Solution: Unoptimized O(N) Solution IDEA: Get the character counts of all the letters in the string. Then, have a dict that stores the required letter counts to create BALLOON. Continue to count until one of those letters turns negative, which means w...
850dc532ddb126b8d36519a9d84ec63395522884
aybarskerem/WebScraper
/Amazon/Advanced Product Detail Extractor/Process/process_helpers/polarity_sentiment_analysis.py
2,773
3.578125
4
from nltk.sentiment import SentimentIntensityAnalyzer import nltk tokenizer = nltk.data.load('tokenizers/punkt/english.pickle') def polarityBased_sentiment_analysis(review): ''' Returns a dict containing the polarity information of each sentence along with the sentences themselves given the 'review'. Param...
2bded783eb4c281619f8b47bbba800c6e15a409b
sajalagrawal/BugFreeCodes
/HackerRank/DS_Quiz1/Olive and indexing.py
244
3.765625
4
#https://www.hackerrank.com/contests/dsquiz1/challenges/olive-and-indexing #Author- Sajal Agrawal #sajal.agrawal1997@gmail.com line=input() x = line.split(' ') m=int(x[0]) n=int(x[1]) i=int(x[2]) j=int(x[3]) result=i*n+j+1 #n=number of columns print(result)
ae0241b2f68eaa55a213b2dfca9cec3fe167c83d
ShanmugaSaiKiranKarnamReddy/Python_programming
/Exercise1_Cardgame1.py
19,447
3.65625
4
import enum import random # card class holds the characterstic of cards class Card: def __init__(self, id, name, health, agility, damage, attack_range, intelligence): self.id = id self.name = name self.health = health self.agility = agility self.damage = damage self...
865233b3d9157d34853a56e977e90d5915c0cee9
karacanil/Practice-python
/#09.py
720
4.03125
4
#09 from random import randint print('Welcome to the Guessing game!') counter=1 flag=1 number=randint(1,9) inp='' print('I picked a number between 1 and 9 (including 1 and 9)') while flag!=0: inp=input('You can enter "close" to exit or you can enter your guess:\n') if inp!='close': guess=int(inp) ...
ea2638797b8f339b3a16f09b52a918690b1df4e6
karacanil/Practice-python
/#13.py
243
4.15625
4
#13 inp=int(input('How many fibonnaci numbers you want me to generate:\n')) def fibonnaci(num): counter=0 x=1 y=0 while counter<num: print(x) temp=x x+=y y=temp counter+=1 fibonnaci(inp)
b3561a5180fc2c219f1b7fa97a663de9ea0be793
Whitatt/Python-Projects
/Database1.py
1,057
4.25
4
import sqlite3 conn = sqlite3.connect('database1.db') with conn: cur = conn.cursor() #Below I have created a table of file list cur.execute("CREATE TABLE IF NOT EXISTS tbl_filelist(ID INTEGER PRIMARY KEY AUTOINCREMENT, \ col_items TEXT)") # in the file list, i have created a column of items. ...
bdf52e77638377a7a1c164ad1ef281673863dc87
ricepaddyhat/coincidenceIndex
/app.py
1,142
3.75
4
#!/usr/bin/python #uses pytesseract to convert image to text #this will not always be 100% accurate import pytesseract from PIL import Image import string print('This program calculates the co-incidence index of a piece of text') print('Press 1 to enter a file path to an image\nPress 2 to enter text directly') #ca...
da22a282a263658f5c7226c1f9b17ed4ba5b2e83
zarkle/code_challenges
/misc/ci.py
601
3.9375
4
def compound_interest(): principal = int(input('Please enter your inital deposit: $')) rate = int(input('Please enter the expected interest rate: ')) rate = rate / 100 time = int(input('Please enter the number of years it will be saved: ')) time += 1 compound = input('How many times is the inter...
7d32b260a8251dfe0bd111e615f8c84975d7102c
zarkle/code_challenges
/codility/interviewing_io/prechallenge2.py
2,097
4.1875
4
""" Mary has N candies. The i-th candy is of a type represented by an interger T[i]. Mary's parents told her to share the candies with her brother. She must give him exactly half the candies. Fortunately, the number of candies N is even. After giving away half the candies, Mary will eat the remaining ones. She loves...
d6356c7baf7fb81b3b836adc7624d443c254dff7
zarkle/code_challenges
/leetcode/two_sum_iii.py
996
4.09375
4
# https://leetcode.com/problems/two-sum-iii-data-structure-design/ (Premium) """ Two Sum III - Data structure design Design and implement a TwoSum class. It should support the following operations: add and find. add - Add the number to an internal data structure. find - Find if there exists any pair of numbers which...
3c449290e32bf50fc92174d6c144a1e0398a40c2
zarkle/code_challenges
/leetcode/search_insert.py
1,309
3.546875
4
# https://leetcode.com/problems/search-insert-position/description/ class Solution: def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if target not in nums: nums.append(target) nums.sort() ...
ba81db6eb0340d66bc8151f3616069d4d6a994a0
zarkle/code_challenges
/dsa/recursion/homework_solution.py
2,026
4.3125
4
def fact(n): """ Returns factorial of n (n!). Note use of recursion """ # BASE CASE! if n == 0: return 1 # Recursion! else: return n * fact(n-1) def rec_sum(n): """ Problem 1 Write a recursive function which takes an integer and computes the cumulative ...
95ceaa512a7cf774c5ca911f131109f93dc55c50
zarkle/code_challenges
/hackerrank/25_python_if_else.py
269
4.125
4
# https://www.hackerrank.com/challenges/py-if-else/problem #!/bin/python3 N = int(input()) if N % 2 == 1: print('Weird') if N % 2 == 0: if 1 < N < 6: print('Not Weird') elif 5 < N < 21: print('Weird') else: print('Not Weird')
bdcffce22053c3dba23d76fa62788ba4f34f2a4b
zarkle/code_challenges
/dsa/trees/trim_bst.py
447
3.96875
4
"""Given the root of a binary search tree and 2 numbers min and max, trim the tree such that all the numbers in the new tree are between min and max (inclusive). The resulting tree should still be a valid binary search tree.""" def trimBST(tree, minVal, maxVal): print tree.left # LeftChild print tree.right ...
93d0d5d70c2f306b2ac3813a950fae3ce6451dca
zarkle/code_challenges
/leetcode/valid_palindrome.py
2,130
3.609375
4
# https://leetcode.com/problems/valid-palindrome/description/ class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ s = re.sub('[^A-Za-z0-9]+', '', s).lower() return s == s[::-1] # iteratively, better solution class Solution(object):...
1118f50623a9238bf2fc8222c3ce894912f8457f
zarkle/code_challenges
/codility/interviewing_io/demo_challenge.py
2,102
3.796875
4
""" Missing Integer (Medium difficulty) Find the smallest positive integer that does not occur in a given sequence. Write a function: def solution(A) 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], t...
b43fec3c2ad1fca40c1baed24882e3c4482be505
zarkle/code_challenges
/hackerrank/29_capitalize.py
312
3.796875
4
# https://www.hackerrank.com/challenges/capitalize/problem # Complete the solve function below. def solve(s): s = s.split(' ') for i in range(len(s)): s[i] = s[i].capitalize() return ' '.join(s) # make sure to specify to split on ' ' because will fail if there are multiple spaces in a row
84ba5a4f2a1b9761148d8ec7c803bb7732f3e75a
zarkle/code_challenges
/fcc_pyalgo/07_minesweeper.py
1,491
4.5
4
""" Write a function that wil take 3 arguments: - bombs = list of bomb locations - rows - columns mine_sweeper([[0,0], [1,2]], 3, 4) translates to: - bomb at row index 0, column index 0 - bomb at row index 1, column index 2 - 3 rows (0, 1, 2) - 4 columns (0, 1, 2, 3) [2 bomb location coordinates in a 3x4 matrix] we s...
ebd7b3de8daec2659f0f639a3d464c37683b5e63
zarkle/code_challenges
/leetcode/find_duplicate_number.py
397
3.625
4
# https://leetcode.com/problems/find-the-duplicate-number/ # https://leetcode.com/articles/find-the-duplicate-number/ # does not meet constant space restraint # runtime 60 ms, 27%; memory 15.2 MB, 7% class Solution: def findDuplicate(self, nums: List[int]) -> int: seen = set() for num in nums: ...
eea82f6231e45fc5670d5116374f22917bb6a200
zarkle/code_challenges
/leetcode/merge_sorted_array.py
5,345
3.84375
4
# https://leetcode.com/problems/merge-sorted-array/ # https://leetcode.com/articles/merge-sorted-arrays (Premium) # runtime 24 ms, 80%; memory 11.8 MB, 32% class Solution(object): def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] ...
188bc9fae6380e2c1a675084f9191a310657d23f
zarkle/code_challenges
/cracking/1.1_is_unique.py
736
3.84375
4
""" Is Unique Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? Hints: #44, #117, #132 https://leetcode.com/problems/contains-duplicate/ """ # 64 ms, 13.22%; 18.9 MB, 25% def unique(s): seen = set() for char in s: if char in ...
c2a5429480d3c26fefd305b728e27c8fe7824ebf
zarkle/code_challenges
/hackerrank/16_tree_postorder_trav.py
783
4.21875
4
# https://www.hackerrank.com/challenges/tree-postorder-traversal/problem """ Node is defined as self.left (the left child of the node) self.right (the right child of the node) self.info (the value of the node) """ def postOrder(root): #Write your code here traverse = '' def _walk(node=None): ...
0554dffeceb42bdac0de097c88cd415a61f0bd7a
zarkle/code_challenges
/cracking/1.4_palindrome_permutation.py
874
4.0625
4
""" Palindrome Permutation Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words. EXAMPLE Input: Tact Co...
5d4d935ab49745cec6581b2e4765b8b43060ade7
zarkle/code_challenges
/leetcode/intersect_arr.py
1,527
3.828125
4
# https://leetcode.com/problems/intersection-of-two-arrays/description/ # https://leetcode.com/articles/intersection-of-two-arrays # runtime 40 ms, 74%; memory 13.2 MB, 5% # without lines 13-14, runtime 44 ms, 52%; 13.2 MB, 5%; but ran a second time and got same results of including those lines (runtime 40 ms, 74%; m...
d38d221e4c91ddd862cf15086c6ac9cedbe94281
zarkle/code_challenges
/leetcode/buy_sell_stock_iii.py
1,024
3.515625
4
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/description/ # passes 189/200 test cases class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if not prices: return 0 profit = [] low...
16048b046a0e35d21c46096fbcd18b3d02d1569c
zarkle/code_challenges
/codility/interviewcake/Find_Duplicate_Space.py
9,722
3.984375
4
""" Find a duplicate, Space Edition™. [see PDF] We have a list of integers, where: 1. The integers are in the range 1..n 2. The list has a length of n+1 It follows that our list has at least one integer which appears at least twice. But it may have several duplicates, and each duplicate may appear more than twice. W...
567c1dbce429a5a1793b79f5ff479faef31a98cb
zarkle/code_challenges
/leetcode/remove_dup_array_ii.py
3,703
3.546875
4
# https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/ class Solution: def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 i = count = 0 for j in range(1,len(nums...
6d42a0d8ae201b273dec12a66249f33f0f214717
AmadeyKuspakov/DiffEqComputationalAssignment
/main.py
1,386
3.71875
4
import diffeqssolver import graph while(True): print("Please provide initial value of the program:") print("x0:") x0 = input() print("y0:") y0 = input() print("xf:") xf = input() print("n:") n = input() diffeqssolver.setInitData(float(x0), float(y0), float(xf), in...
cf84c3b017ac0075f7095d2729c2f65d48420d1f
ciscokang/100-Days-of-Code-with-Python
/Pong: The Famous Arcade Game (OOP)/pong.py
1,045
3.75
4
from turtle import Turtle from random import randint, choice class Pong(Turtle): def __init__(self): super().__init__() self.penup() self.shape("circle") self.color("white") self.x_move = 10 self.y_move = 10 self.move_speed = 0.1 # def s...
0798425ff44a2a514bb72b38a219a0be45a757a3
eshimelis/cpp_practice
/src/license_key_formatting.py
706
3.5
4
class Solution(object): def licenseKeyformatting(self, s, k): """ :type s: str :type k: int :rtype: str """ # remove all dashes and convert to upper s = s.replace('-', '') s = s.upper() # reverse for easier parsing result = "" ...
cdde4c4c0a7a2d61c4bba3cc705f4f9b4d266512
LaxminarayanaV7416/MostlyPython
/Python_Collections.py
3,680
4.03125
4
# lets talk about Python's Most widely used inbuilt module collections # Collections is nothing but the container datatypes, whcih are very handy and faster # we will talk about five main aspects in collections counter, ordereddict, namedtuple, defaultdict, deque #please refer documenattion for object oriened benfits ...
f5897594c9fc477985bb6d94383910541e27e259
minddrummer/weightreservoir
/weightreservoir/reservoir.py
4,007
3.65625
4
''' This module brings the effective reservoir sampling method, with or without weight. The reservoir sampling is used when you have a very large and unknown dataset of size N, and you want to sampling a subset of k of these N samples, with one stream or one file reading. If the weight is not present, each sample wil...
836f36772652e68e5d15e7fb6857c84bef7b0d80
penandlim/InterviewPrep
/solutions/CH1/IsUnique.py
316
3.6875
4
def isUnique(s): countMap = {} for c in s: if (c in countMap): return False else: countMap[c] = 1 return True def test(arr): for a in arr: print("Input: " + a) print("Output: " + str(isUnique(a)) + "\n") test(["asda sd", "a bc", "awwww2"])
5544d86fda298d8f43496bac9a7a8f518a0887f3
Alexlilihxq/-PythonProjects
/NameCardManagementSystem/cards_tools.py
3,675
3.6875
4
card_list = [] def show_menu(): """显示主菜单选项""" print("1.新增名片\n" "2.显示所有名片\n" "3.搜索名片\n\n" "0.退出系统\n") print("^"* 50) action_str = input("请选择希望执行的操作:") return action_str def return_menu(): while True: action_str=input("\n输入0返回主界面") if action_str=="0": ...
1b2bc824bf1eacbf2c97ad0b5848d71bb31bab1e
solive93/python_katas
/StringCalculator/StringConverterTest.py
1,020
3.734375
4
import unittest from StringConverter import StringConverter class MyTestCase(unittest.TestCase): def test_returns_0_when_empty_string_given(self): converter = StringConverter() output = converter.add("") self.assertEqual(0, output) def test_returns_same_number_as_int(self): con...
091e66ef55938bdc8585a4064c4d1e7a4437afd5
amaankahmad/MIT6.0001Python
/PS3 - Words game/problem2.py
1,325
4.09375
4
def update_hand(hand, word): """ Does NOT assume that hand contains every letter in word at least as many times as the letter appears in word. Letters in word that don't appear in hand should be ignored. Letters that appear in word more times than in hand should never result in a negative count; ins...
26545a184b900de994eab6430b26b9da3beb6125
rickey-dong/introcs
/intro1/merge_lab.py
6,869
4.25
4
import random #This is here for later use def rand_list(n, limit): g = [] while (n > 0): g.append(random.randrange(limit)) n-= 1 return g #================================================== # Problem 0 # Base your answers on the following lists: a = [1, 3, 4, 8, 9] b = [2...
523b5b4ed3718c2438acad37b59b201df433cd59
rickey-dong/introcs
/intro1/data_project/airline_data.py
13,297
3.828125
4
# Leonard Ma and Rickey Dong # Period 9 Annual Intro CS with Mr. DW # Project 00: Big Data, BIGGER Fun # ------------------------------------------------------------------------------------ # The data that we will be processing and analyzing in this Python # program is about airplane travel. Our data shows informa...
cfad65137a2987daf22e36d343a8d749bf9b0d22
rickey-dong/introcs
/intro1/test2_review.py
1,155
3.609375
4
def taxifare(miles, customers): if customers < 5: return miles * 1.50 if customers > 5: return miles * 2.50 print(taxifare(8, 3)) print(taxifare(8, 6)) def onLine(slope, yint, xcor, ycor): if ycor == (slope * xcor) + yint: return True else: return False...
4dcc7326f5ed05301554790e931a35ba22060e52
Jangsem/NotenTracker
/Note.py
1,594
3.578125
4
import datetime from FileHandler import FileHandler filehandler = FileHandler() class Note(): pass def __init__(self, wert, fach, year, month, day): self.wert = wert self.date = datetime.datetime(year, month, day) self.fach = fach def setWert(self, w): self.wert = w ...
d22681acb6c9e1d4cc2d927f351d703dc59852dc
Sukumu/sukumu.github.io
/src/waves.py
642
3.609375
4
# src/waves.py from typing import Callable import numpy as np def wave(frequency: int, amplitude: int = 1, phase: int = 0) -> Callable: """ Returns a closure based on the wave_ function. Parameters: frequency: int amplitude: int phase: int Returns: Callable """ ...
7624dfe6435e1575121da552c169df512f974c24
rxu17/physics_simulations
/monte_carlo/toy_monte_carlo/GluonAngle.py
1,025
4.1875
4
# Rixing Xu # # This program displays the accept and reject method - generate a value x with a pdf(x) as the gaussian distribution. # Then generate a y value where if it is greater than the pdf(x), we reject that x, otherwise we accept it # Physically, the gluon is emitted from the quark at an angle # Assumptions:...
052ca596b497a8cb49118c7c49b187ff7bfb7a1f
Sfaurat/py_lesson2
/farm/livestock.py
1,538
4.09375
4
from datetime import datetime, timedelta def fib(n): """Вычисления числа Фибоначчи.""" a = 2 b = 3 for __ in range(n): a, b = b, a + b return a def bunnies(day): """ Подсчёт выводка кроликов. Кролики размножаются раз в 10 дней в соответствии с числами Фибоначчи. """ ho...
5fdddd5219475f2bcb7278b5e2c1b82fd3fefbc8
snrtherock/CoolPool
/Python/一些功能模块的测试/ThreadPool_test.py
2,972
3.5625
4
# coding:utf-8 # Project :Python 的线程池实现 # Author: Anka9080 import Queue import threading import sys import time import urllib class MyThread(threading.Thread): def __init__(self,workQueue,resultQueue,timeout = 30, **kwargs): threading.Thread.__init__(self,kwargs = kwargs) self.timeout = timeout self.setDaemon...
bad6cb0bb957fbe017c93ae637d873b6d4f30123
snrtherock/CoolPool
/Python/deduplicate.py
541
3.8125
4
# coding: utf-8 # author: anka9080 # date : 20160408 # 去重小脚本 def deduplication(): list1 = [] # 总文件列表 list2 = [] # 去重参数列表 list3 = [] # 去重后的文件列表 with open('1.txt') as f1: for i in f1.readlines(): list1.append(i.rstrip()) with open('2.txt') as f2: for i in f2.readlines(): list2.append(i.rstrip()) ...
75de7e953c2d75348bcaedae1dd653b40d159079
berkcangumusisik/HackerrankPractice
/Python/03.Strings/014. Merge The Tools!.py
428
3.703125
4
# PROBLEM: https://www.hackerrank.com/challenges/merge-the-tools/problem def merge_the_tools(string, k): x = [string[i:i+k] for i in range(0, len(string), k)] for i in x: j = 0 short = "" for _ in i: if i.index(_) == j: short += _ j += 1 p...
44808f12938e259c49ea9725e0b30718da3ef217
stanjacob/python
/quicksort.py
554
3.953125
4
def quicksort(arr, lo, hi): if lo < hi: p = partition(arr, lo, hi) quicksort(arr, lo, p) quicksort(arr, p + 1, hi) def partition(arr, lo, hi): pivot = arr[lo] i = lo - 1 j = hi + 1 while True: i += 1 while arr[i] < pivot: i += 1 j -= 1 while arr[j] > pivot: j -= 1 if i >= j: return j; ...
c99e9cc38655ca118c032c00ac1dd3c2ea84da66
hgbarrow/PythonSnippets
/base_converter.py
796
4.03125
4
from math import pi def converter(n, decimals=0, base=pi): """takes n in base 10 and returns it in any base (default is pi) with optional x decimals""" # digit can be alphanumermic (max base = 36) numeration = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' out_str = "" # check if number is neg...
197ec3193cfe000d6d033a2eb0b1c7e4efc0d116
Stefs-2142/learn-homework-2
/for_dict_challenges.py
6,134
3.78125
4
from collections import Counter # Задание 1 # Дан список учеников, нужно посчитать количество повторений каждого имени ученика. def count_1(): students = [ {'first_name': 'Вася'}, {'first_name': 'Петя'}, {'first_name': 'Маша'}, {'first_name': 'Маша'}, {'first_name': 'Петя'}, ] a = dict(Counter([st...
2601235816634abad9f33c14fe0b22d543a0f4c3
fsload/algorithm
/프로그래머스/다리를 지나는 트럭.py
618
3.640625
4
def solution(bridge_length, weight, truck_weights): # bridge_length 다리 길이 int # weight 다리가 견딜수 있는 무게 int # truck_weights 트럭들의 길이 list # bridge_length = 5 # weight = 5 # truck_weights = [2, 2, 2, 2, 2, 1, 1, 1, 1, 1] time = 0 bridge = [0] * bridge_length while len(bridge) != 0: ...
1c93ecf314f0fd0a5b7ccc235d39a6b869cf6454
fsload/algorithm
/SWEA/파스칼의 삼각형.py
610
3.515625
4
TC = int(input()) for t in range(TC): n = int(input()) arr = [] for i in range(n): if i == 0: arr.append([1]) else: li = [] for j in range(i+1): if j == 0 or j == i: li.append(1) else: ...
47a511d2685c19942745314af90ea651b1fe4681
kilianFatras/Draughts-game-AI
/IN104_simulateur/move.py
1,150
4.0625
4
class Move(): ''' A move is simply a list of cells which a piece passes by. It can be either a CaptureMove or a SimpleMove. These classes do not check whether the list of cells define a valid move''' def __init__(self, l): self.cells = l def __eq__(self,other): ...
c6be4757dcfe28f09cee4360444ede6068058a8b
omarMahmood05/python_giraffe_yt
/Python Basics/13 Dictionaries.py
786
4.40625
4
# Dict. in python is just like dicts in real life. You give a word and then assign a meaning to it. Like key -> An instrument used to open someting speciftc. # In python we do almost the same give a key and then a value to it. For eg Jan -> January monthConversions = { "Jan": "January", "Feb": "February",...
ed90c53d8cb6e98d6f9a7162d2af074042193b60
ritomar/ifpi-386-2017-1
/Lista03b_Q05.py
261
3.953125
4
# 5. Faça um programa que peça um inteiro positivo e o mostre invertido. # Ex.: 1234 gera 4321 n = int(input("Digite um número inteiro: ")) inv = 0 while n > 0: dig = n % 10 n = n // 10 inv = (inv * 10) + dig print("Número invertido:", inv)
14e8864277a8574509c40c08ac66b32cc4bc9b43
ritomar/ifpi-386-2017-1
/Lista03_Q05.py
312
3.625
4
# 5. Dados dois números inteiros positivos, determinar o máximo divisor # comum entre eles usando o algoritmo de Euclides. def MDC(a, b): while (b != 0): q = a / b r = a % b a = b b = r return a a, b = 348, 156 print("MDC de %d e %d é: %d" % (a, b, MDC(a, b)))
e03f5102f11516c3c3fd7afb465799879f79c6a0
ritomar/ifpi-386-2017-1
/Lista03_Q04.py
815
4.125
4
# 4. A seqüência de Fibonacci é a seguinte: # 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ... # Sua regra de formação é simples: os dois primeiros elementos são 1; # a partir de então, cada elemento é a soma dos dois anteriores. # Faça um algoritmo que leia um número inteiro calcule o seu número # de F...
69a5d7683815eca8a650b405137449360ca3684b
Stensby/2018-advent-of-code
/day1/day1-1.py
139
3.734375
4
input_file = open("input", "r") frequency_list = input_file.readlines() frequency = sum(int(n) for n in frequency_list) print(frequency)
9c6ab864e19f9af8d1b3d3cb3b2b0f8678e4cdbe
TaT0n/zadanie3
/4.py
449
3.59375
4
# Реализовать функцию вывода списка с учетом вложенных списков sp = [1, 'ttt', [1, 2, 3, 'qqq'], [4, 5, 6]] def func(A): print(A) for i in range(len(A)): if type(A[i]) is int: print(A[i], end=' ') elif type(A[i]) is str: print(A[i], end=' ') else: fo...
b4dc752b17bd9a3fcf459f50cd2b02867e497ef7
Itnug/Minesweeper
/main/difficulty.py
1,746
3.5625
4
''' Created on 26-Jan-2020 @author: Srinivas Gunti ''' import tkinter as tk from collections import namedtuple Difficulty = namedtuple('Difficulty', ['width', 'height', 'bombs']) Beginner = Difficulty(9, 9, 10) Intermediate = Difficulty(15, 15, 40) Expert = Difficulty(30, 16, 99) class Custom(tk.Toplevel): def...
20e7665ed31c306e4f93c47dfc638b4f927ddc75
Nfreewind/iarc007_hitcsc
/iarc/src/pilot/scripts/tst.py
402
3.640625
4
import numpy as np import string num = input("Enter the number") l_s = raw_input("enter the location") l_o = l_s.split(",") location = [string.atof(l_o[0]),string.atof(l_o[1])] store = [] for i in range(num): temp = raw_input("enter the data") data = temp.split(",") ttemp = [] for j in range(len(data)...
aa42a10a065262ab81a2b1431c28e654b614908a
aiko11/MoonPython
/02.Grammar/19.comprehension.py
1,524
3.90625
4
# -------------------------------------------------------------------------- # Comprehension 이란 iterable한 오브젝트를 생성하기 위한 방법중 하나로 # 파이썬에서 사용할 수 있는 유용한 기능중 하나입니다. # 파이썬에는 다음과 같은 크게 네 가지 종류의 Comprehension 이 있다. # - List Comprehension (LC) # - Set Comprehension (SC) # - Dict Comprehension (DC) # - Generator Expression (GE) ...
ef8787379cceba7d90ed547bc7570d9abf0e0ef8
aiko11/MoonPython
/02.Grammar/21.lazy_evaluation.py
470
3.765625
4
import time def wait_return(num): print("sleep") time.sleep(0.5) return num def print_items(items): for i in items: print(i) def main(): print("=========== list comprehension") iterator_list = [wait_return(i) for i in range(10)] print_items(iterator_list) print("=========== ...
29593bcf16f60abcc83878d68ea4389d1ab30080
mdeng1110/Computing_Talent_Initiative
/6_A1_Pancake_Sort.py
835
3.953125
4
# reverses the first k elements of an array def flip(arr, k): for i in range(k//2): arr[i], arr[k-i-1] = arr[k-i-1], arr[i] def pancake_sort(nums): k_values = [] k = len(nums) max_index = 0 while k > 1: max_index = nums.index(max(nums[0:k])) print('MAX: ', max_index) if max_index != k: ...
32d4d61e14062979d8d23b72e77cb2d9c7459e32
mdeng1110/Computing_Talent_Initiative
/6_S1_Color_Sort.py
483
3.859375
4
def color_sort(nums): # nums = [0, 0, 1, 1, 1, 2] i = 0 j = len(nums) - 1 k = len(nums) index = 0 mid = nums[int(len(nums) / 2) + 1] while index < k and i <= index and j >= index: if nums[index] == 0: nums[index], nums[i] = nums[i], nums[index] i = i + 1 elif nums[index] == 2: nu...
f4b7f4583a75e74625d418c13e588f0f9b5a082f
mdeng1110/Computing_Talent_Initiative
/5_A1_Square_Root.py
130
3.53125
4
def squareRoot(num): result = num ** (.5) result = int(result) return result sampleInput = 9 print(squareRoot(sampleInput))
9cef13849dc1e45a43e9ec30b315efbb73c506cb
mdeng1110/Computing_Talent_Initiative
/10_S1_Divide.py
616
4.03125
4
def divide(dividend, divisor): if divisor == 0: return 0 else: result = 0 sign = True if dividend < 0 or divisor < 0: sign = False if dividend < 0 and divisor < 0: sign = True dividend = abs(dividend) divisor = abs(divisor) while((dividend - divisor) >=...
5adad2dad37ccfd3788478cbc15d6c7fa8a77f52
mdeng1110/Computing_Talent_Initiative
/3_P1_First_Missing_Integer.py
904
3.765625
4
def first_missing_positive_integer(integers): found_integers = [] for integer in integers: if integer < 0: continue if integer + 1 > len(found_integers): extend_size = integer - len(found_integers) + 1 found_integers.extend([False] * extend_size) found_integers[integer] = True f...
2781aceb1adfff0d5da87946d824572779f73c8e
mdeng1110/Computing_Talent_Initiative
/9_P3_Min_Stack.py
1,041
4.125
4
class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.stack = [] self.min = 999 def push(self, x): """ :type x: int :rtype: None """ if x <= self.min: self.stack.append(self.min) ...
582db4566ff28ac42c88d9c380418717d2450c69
mdeng1110/Computing_Talent_Initiative
/5_E1_Rotated_Array.py
784
3.625
4
input_list = [4,5,6,7,0,1,2] def find_pivot_index(input_list): # List is sorted, but then rotated. # Find the minimum element in less than linear time # return it's index # for current_element_index in range(len(input_list)): # if input_list[current_element_index] < input_list[current_element_index - 1]: ...
a1a726746b3b41b70fedef537c27a5da6c313d28
mdeng1110/Computing_Talent_Initiative
/7_P3_Evaluate_Expression.py
893
4.125
4
def evaluate_expression(expression): # create empty stack - > stack = [] stack = [] # loop over the expression for element in expression: if element.isnumeric(): stack.append(int(element)) else: #print('STACK: ', stack) if element == "*": a = stack.pop() b = stack.pop()...
49695d0e93140f28bda12007c022011a0307e1e4
sbrinkmeyer/terraform_policy_module
/modules/cross-acct-role/tools/add_list.py
482
3.8125
4
import argparse import json parser = argparse.ArgumentParser(description='take a list of numbers, return the result') parser.add_argument('numbers', metavar='N', nargs='+', help='series of numbers to add') args = parser.parse_args() #The numbers arrive as strings, so parse to ints def add(num_st...
7f7fbf325ce027bb6d57bdaf4a2eeebe2bb91a82
jtcanfield/python-intro
/classes.py
1,438
4.0625
4
# Classes class Greeter: # ALL CLASSES HAVE TO HAVE "SELF" SET # This line is required: def __init__(self, greeting="Hello", excited=True): # "greeting" does not have to be set, but if it is, it will # use what it is set as by default if nothing is specified self.greeting = greeting ...
57aabe4645b70754a64fac0aacd93878768ceec8
abhinavk454/DataStructure_py3
/Sorting/selection.py
1,269
3.703125
4
#import section import matplotlib.pyplot as plt import time import random import matplotlib.animation as animation #selection sort def selectionsort(arr): for i in range(len(arr)): min_index=i for j in range(i+1,len(arr)): if arr[min_index]>arr[j]: min_index=j ...
853cea58931a361d3f281daa2111fb906e1a6cd3
tanvirarafin/intro-power-analysis
/src/rsa-code/custom_pow.py
1,069
3.765625
4
# ANCHOR: function_def # Custom implementation of pow(x, y) def custom_pow(x, y): res = 1 # Until we have reached the highest power while (y > 0): # If the last byte is a one if (y & 0x01): res *= x # Move on to the next byte y >>= 1 x *= x return r...
e8546a3cfb150b6355e001f13d2c522b7301cc87
malbiruk/PythonCourse
/hw_B3.py
251
3.65625
4
#!/usr/bin/python3 with open('rosalind_hamm.txt', 'r') as file: dna=file.read() distance=0 dna_list=dna.split('\n') dna0=dna_list[0] dna1=dna_list[1] for i in range(len(dna0)): if dna0[i] != dna1[i]: distance += 1 print(distance)
ff63e64de8abf1b067a242559527bb3722d4ccd9
dorakarkut1/Rosalind_exercises-Bioinformatics-Stronghold
/Mendelian Inheritance.py
1,089
3.734375
4
""" Given: Three positive integers k, m, and n, representing a population containing k+m+n organisms: k individuals are homozygous dominant for a factor, m are heterozygous, and n are homozygous recessive. Return: The probability that two randomly selected mating organisms will produce an individual possessing a domin...
f00b8e62bd3a566ecb70f5bded4f6dced073cca7
AllenTango/Python001-class01
/week07/zoo.py
2,382
3.890625
4
# 定义“动物”、“猫”、“动物园”三个类,动物类不允许被实例化。 # 动物类要求定义“类型”、“体型”、“性格”、“是否属于凶猛动物”四个属性,是否属于凶猛动物的判断标准是:“体型 >= 中等”并且是“食肉类型”同时“性格凶猛”。 # 猫类要求有“叫声”、“是否适合作为宠物”以及“名字”三个属性,其中“叫声”作为类属性,猫类继承自动物类。 # 动物园类要求有“名字”属性和“添加动物”的方法,“添加动物”方法要实现同一只动物(同一个动物实例)不能被重复添加的功能。 from abc import ABCMeta, abstractmethod class Animal(metaclass=ABCMeta): Animal...
e34e0f50e9866ffcc5a753215667178269618495
julianascimentosantos/exerciciosPython
/Recursão_e_Iteração.py
710
3.765625
4
import time def fib_rec(n): if n < 2: return n else: return fib_rec(n - 1) + fib_rec(n - 2) def fib_it(n): res = n a, b = 0, 1 for k in range(2, n + 1): res = a + b a, b = b, res return res m = dict() def fib_mem(n): if n < 2: return n elif m....
e55ad2fe62b15b9dec4131dbc18758cb2439e55c
mnzhang2012/ahcg_pipeline
/python_scripts/del_chr_character.py
281
3.515625
4
import sys #argv[1] is the BED file with the following format "chr chrom_start chrom_end strand name". The file has header. with open (sys.argv[1]) as fin: for line in fin: if line.startswith("chr"): print(line.replace("chr",""), end="") else: print(line, end="")
7e01e4b4814e2e8ae5c48a9a0a5ae55108621b29
sabinem/treehouse-python-techdegree
/project08_django_mineralcatalog2/analyze.py
2,668
3.75
4
""" Helper programm to analyze the data in minerals.json. """ import json import os from collections import defaultdict from mineral_catalog.settings import DATA_DIR def analyze_minerals(): """ Analyzes the minerals.json file and outputs two text files. A summary contains the aggregations and answers whi...
44d2d2bc1cc85bf6dfbd8f3b383560f4fefc049b
giorgiolbt/WSEassignment
/SemanticWeb2/WSEassignement.py
7,483
3.609375
4
import nltk import requests as requests nltk.download('punkt') # Section 1 # utf-8-sig to have unicode without the BOM (Byte Order Mark) bookFile = open('The Adventures of Tom Sawyer by Mark Twain', mode='r', encoding='utf-8-sig') # Read the text of the book and remove the new line characters book = bookFile.read() ...
48ebdac4cccfedf7c46b3569fe191dfce825ec7b
huangqiank/Algorithm
/laiclass/recursion2/find_parentheses.py
543
3.78125
4
''' Created on Sep 26, 2017 @author: qiankunhuang ''' def permutation(input): n = len(input)/2 l = 0 r = 0 res = [] find_permutation(l,r,n,res) def find_permutation(l,r,n, res): if l == n and r == n: print(res) return if l < n: res.append("(") find_permu...
2c0d938c985080cb3e3c3023831bcedd1e4e8a04
huangqiank/Algorithm
/laiclass/recursion/palindrom.py
713
3.890625
4
''' Created on Sep 24, 2017 @author: qiankunhuang ''' class listnode: def __init__(self,value): self.next = None self.val = value nodep0 = listnode(0) nodep1 = listnode(1) nodep2 = listnode(2) nodep3 = listnode(3) nodep4 = listnode(0) start = nodep0 nodep0.next = nodep1 nodep1.next = nodep2...
7ffa4128876b70ca455d7896f2d638ea03c11e4a
huangqiank/Algorithm
/leetcode/sorting/merge_interval.py
1,196
3.5625
4
# _*_coding:utf-8_*_ ##多维度排序,先按照第一维度排序,再按照第二维度排序 ###输入: [[1,3],[2,6],[8,10],[15,18]] ###输出: [[1,6],[8,10],[15,18]] ##新建res ##找中间集合 ##有交集和左边合并,再找中间,循环 ##没有交集则写入res def intersect(a, b): ## 不相交, if a[1] < b[0]: return 0 ## 包含 if a[1] >= b[1]: return -1 ## 相交 return 1 def merge(a,...
2935d9e5617f497d5eb145bc473650ab021d996a
huangqiank/Algorithm
/leetcode/sorting/sort_color.py
1,112
4.21875
4
# Given an array with n objects colored red, # white or blue, sort them in-place  # so that objects of the same color are adjacent, # with the colors in the order red, white and blue. # Here, we will use the integers # 0, 1, and 2 to represent the color red, white, and blue respectively. # Note: You are not suppose to ...
aa47fdd48a4a7c357eab7ef07a35531a77d1b672
huangqiank/Algorithm
/laiclass/dynamic_programing/climb_stair.py
241
3.75
4
''' Created on Dec 20, 2017 @author: qiankunhuang ''' def climb(n): dp = [1 for i in range(n + 1)] dp[1] = 1 dp[2] = 2 for i in range(3, n + 1, 1): dp[i] = dp[i - 1] + dp[i - 2] return dp[n] print(climb(10))
f6b5f341effd803517cde4c5a19ab18095baa155
huangqiank/Algorithm
/laiclass/hashmap/length_of_last_word.py
309
3.796875
4
''' Created on Oct 8, 2017 @author: qiankunhuang ''' def length_of_last_word(str): n = len(str) last = 0 while n > 0 and str[n - 1] == " ": n -= 1 while n > 0 and str[n - 1] != " ": n -= 1 last += 1 return last A = "abc des fs " print(length_of_last_word(A))
9f8d29499b8f818c38a96b73188aa80a9b2e3db1
huangqiank/Algorithm
/laiclass/heap/max_min_heap.py
1,312
3.59375
4
''' Created on Jan 21, 2018 @author: qiankunhuang ''' import heapq class max_heap_int(object): def __init__(self,val): self.val =val def __it__(self,other): return self.val >other.val def __eq__(self,other): return self.val == other.val def __str__(self): return self(sel...
2f8e8fa9338d7fae70136cbe59262cf86bb6065b
huangqiank/Algorithm
/laiclass/string2/p1.py
502
3.671875
4
''' Created on Feb 15, 2018 @author: qiankunhuang ''' def reverse(input): res=[] i = 0 new=[] n = len(input) while i < n: new=[] while i<n and (len(new)== 0 or input[i]!=" "): new.append(input[i]) i+=1 new = new[::-1] res.extend(new) r...