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
4a771e44aeddddc7ef07197affcb765f7f20866d
August-us/exam
/exchangeString.py
565
3.625
4
def fun(strList): set1=set() for a in strList: ja=a[::2] oa=a[1::2] set1.add(''.join(sorted(ja))+''.join(sorted(ja))) return len(set1) def fun1(strList): set1=set([''.join(sorted(a[::2])) + ''.join(sorted(a[1::2])) for a in strList ]) return len(set1) a='abcd' b='adcb' pri...
fc03ed75d9e33669901d21ee49d6e271521fa6b9
kimp10/explorepackage
/explorepackage/recursion.py
786
4.09375
4
def sum_array(array): '''Return sum of all items in array''' return sum(array) #if len(array) == 1: #return array[0] #else: #return array[0] + sum_array(array[1:]) #print(sum_array([1,3,5,7,9])) #print(sum_array([])) def fibonacci(n): '''Return nth term in fibonacci sequence''...
9a06dd1b4a054f8202f226251f3038002c011d11
skyaiolos/myshiyanlou
/designPattern/behavioralPattern/templateMethod.py
1,864
4.15625
4
__author__ = "Jianguo Jin (jinjianguosky@hotmail.com)" # !/usr/bin/python3 # -*- coding:utf-8 -*- # Created by Jianguo on 2017/6/5 """ Description: """ import abc class Fishing(object): """ 钓鱼模板基类 """ __metaclass__ = abc.ABCMeta def finishing(self): """ 钓鱼方法中,确定了要...
75f49095bad47438bf8a0fca7490ef9feb6b9445
daveboat/interview_prep
/coding_practice/general/valid_square.py
2,284
3.75
4
""" LC593 - Valid Square Given the coordinates of four points in 2D space, return whether the four points could construct a square. The coordinate (x,y) of a point is represented by an integer array with two integers. Example: Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1] Output: True Note: All the input ...
47690010dab9f2c87b81cec9db53972fc8242a01
daveboat/interview_prep
/coding_practice/bit_manipulation/add_binary.py
1,483
3.734375
4
""" LC67 - Add Binary Given two binary strings, return their sum (also a binary string). The input strings are both non-empty and contains only characters 1 or 0. Example 1: Input: a = "11", b = "1" Output: "100" Example 2: Input: a = "1010", b = "1011" Output: "10101" Constraints: Each string consists only...
65c2f4b7494113493819a2f9ec7651e436340d67
daveboat/interview_prep
/coding_practice/general/missing_number.py
652
3.859375
4
""" LC268 - Missing Number Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. Example 1: Input: [3,0,1] Output: 2 Example 2: Input: [9,6,4,2,3,5,7,0,1] Output: 8 """ class Solution(object): def missingNumber(self, nums): """ :...
1226a6de159e071159a9aca6f00a4dd2483265ab
daveboat/interview_prep
/coding_practice/binary_tree/populating_next_right_pointers_in_each_node.py
2,486
4.125
4
""" LC116 - Populating Next Right Pointers in Each Node You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: struct Node { int val; Node *left; Node *right; Node *next; } Populate each next pointer to point...
4540776d60c6aa384ea467e4fe7565c936ce3da0
daveboat/interview_prep
/coding_practice/general/largest_time_for_given_digits.py
2,948
3.84375
4
""" LC949 - Largest time for given digits Given an array of 4 digits, return the largest 24 hour time that can be made. The smallest 24 hour time is 00:00, and the largest is 23:59. Starting from 00:00, a time is larger if more time has elapsed since midnight. Return the answer as a string of length 5. If no valid ...
3d6012d3f58e7f7dac19fad28badcb150b632723
daveboat/interview_prep
/coding_practice/bit_manipulation/iterator_for_combination.py
2,598
3.65625
4
""" LC1286 - Iterator for combination Design an Iterator class, which has: A constructor that takes a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments. A function next() that returns the next combination of length combinationLength in lexicographic...
49dfa92d60ff280719607b50f9e5a6aa40f76e1e
daveboat/interview_prep
/coding_practice/general/robot_bounded_in_circle.py
2,663
4.15625
4
""" LC1041 - Robot bounded in circle On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions: "G": go straight 1 unit; "L": turn 90 degrees to the left; "R": turn 90 degress to the right. The robot performs the instructions given in order...
1560636d9af42712bbdf039263d6e816e2db182f
daveboat/interview_prep
/coding_practice/queues/sliding_window_maximum.py
4,783
4
4
""" LC239 - Sliding Window Maximum You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window. Exa...
a827098e3d8eb8f2416aa060434e56360704d26a
daveboat/interview_prep
/coding_practice/bit_manipulation/power_of_four.py
1,020
3.703125
4
""" LC342 - Power of four Given an integer (signed 32 bits), write a function to check whether it is a power of 4. Example 1: Input: 16 Output: true Example 2: Input: 5 Output: false Follow up: Could you solve it without loops/recursion? """ class Solution(object): def isPowerOfFour(self, num): """ ...
6a8b410311a90bdfad9b3e45be75e49ba5e79515
daveboat/interview_prep
/coding_practice/general/permutation_sequence.py
3,015
3.515625
4
""" LC60 - Permutation Sequence The set [1,2,3,...,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for n = 3: "123" "132" "213" "231" "312" "321" Given n and k, return the kth permutation sequence. Note: ...
cb804b1d0354d230cdebf34a1aed218f953c2494
daveboat/interview_prep
/coding_practice/general/point_clusters.py
3,596
3.671875
4
import math # given a list of N (x, y) points, find clusters of points, where a cluster is a set of points where all points are at # least a distance k apart from another point in the set # let's assume the points, and k, are normalized so that they are between 0 and 1 (this is always possible by dividing # both x, y...
3b735a77ae3d6886db56db8d8319ad2bb6eb25c2
daveboat/interview_prep
/coding_practice/bit_manipulation/single_number.py
2,276
3.859375
4
""" LC136 - single number Given a non-empty array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Example 1: Input: [2,2,1] Output: 1 Example 2: Input: [4,1,2,1,2] Outpu...
cffa1b37372ec33c1db33c83c2916daefb1cbd2b
daveboat/interview_prep
/coding_practice/graphs/graph_bipartition.py
3,126
4
4
""" Seeing if a graph defined as a series of edges is bipartite, using a graph coloring algorithm """ class Solution(object): def possibleBipartition(self, N, dislikes): """ :type N: int :type dislikes: List[List[int]] :rtype: bool """ # Create an undirected graph,...
54539e6eabc9a07f94f5c872841d5cdc8e660851
daveboat/interview_prep
/coding_practice/tries/add_and_search_word.py
3,251
3.546875
4
""" LC211 - Add and search word - data structure design Design a data structure that supports the following two operations: void addWord(word) bool search(word) search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter. Example:...
18a3403e797be03ec553e0fadebe090c6a507537
daveboat/interview_prep
/coding_practice/binary_tree/vertical_order_traversal_of_a_binary_tree.py
3,201
3.953125
4
""" LC987 - Vertical Order Traversal of a Binary Tree Given a binary tree, return the vertical order traversal of its nodes values. For each node at position (X, Y), its left and right children respectively will be at positions (X-1, Y-1) and (X+1, Y-1). Running a vertical line from X = -infinity to X = +infinity, w...
43e0a4b3b11ee57414e5840a20f43016e88c58d3
daveboat/interview_prep
/coding_practice/binary_search/arranging_coins.py
1,747
3.6875
4
""" LC441 - Arranging Coins You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins. Given n, find the total number of full staircase rows that can be formed. n is a non-negative integer and fits within the range of a 32-bit signed integer. Example 1: ...
12e63f8ef96abef628478a1b3edbfa2cfbbe5d48
daveboat/interview_prep
/coding_practice/binary_tree/maximum_depth_of_binary_tree.py
1,413
3.875
4
""" LC104 - Maximum depth of binary tree Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Example 1: Input: root = [3,9,20,null,null,15,7] Output: 3 Example 2: Input: root = [1,n...
cf73126584a3d977fe47b634c261d5bc193f1052
daveboat/interview_prep
/coding_practice/linked_list/rotate_list.py
2,452
3.859375
4
""" LC61 - Rotate list Given a linked list, rotate the list to the right by k places, where k is non-negative. Example 1: Input: 1->2->3->4->5->NULL, k = 2 Output: 4->5->1->2->3->NULL Explanation: rotate 1 steps to the right: 5->1->2->3->4->NULL rotate 2 steps to the right: 4->5->1->2->3->NULL Example 2: Input: 0-...
42b9ed4246e8554681c9ef9eb5f4b6f29b5909d6
daveboat/interview_prep
/coding_practice/graphs/course_schedule.py
4,541
4.125
4
""" LC207 - Course Schedule There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses and a list of prerequisite pai...
b256246369b10439e7271bad434bce74f2ae75bb
daveboat/interview_prep
/coding_practice/general/merge_intervals.py
2,256
3.78125
4
""" LC56 - Merge Intervals Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. Example 1: Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explan...
c38cc560308edabac42c87bec8252bc9f446e39c
momentum-cohort-2019-05/w2d2-palindrome-bhagh
/palindrome.py
577
4.25
4
import re #grab user input submission = input("Enter a word or sentence(s): ") #function to clean up text by user def cleantext (submission): submission = (re.sub("[^a-zA-Z0-9]+", '', submission).replace(" ","")) return submission print(cleantext(submission)) #create a string that's the reverse of the text ...
dbfeab698ec2f7577e255f5e91a7b383432711f4
kkelk/fun-compiler
/funcompiler/util.py
1,430
3.734375
4
def integer_to_int(): """Assuming the top of the stack is a reference to an Integer, replace it with an int.""" return """ checkcast java/lang/Integer invokevirtual java/lang/Integer.intValue()I """ def int_to_integer(): return """ invokestatic java/lang/Integer.valueOf(I)Ljava/lang/Integer...
23b52be963857d5b6d2fed178322ef0bc562a095
sujatha1812/pythoncodes
/day11.py
1,066
3.71875
4
# merge using zip file prog_langs = ["python", "java", "c", "javascript"] tiobe_ranks = [1, 2, 3, 4] features = [10, 20, 30, 40] # Display input lists print ("\nTest Input: **********\n Prog Langs : " + str(prog_langs)) print (" TIOBE Ranks : " + str(tiobe_ranks)) print (" Features : " + str(features)) ...
996bd0c2e2e9800f7af5c4445259da0b25dbd7ca
harishh486/LeetcodeSolutions
/company/Facebook/arrays/selectionsort.py
780
3.78125
4
class Solution(object): def indexOfMinimum(array, startIndex): minValue = array[startIndex] minIndex = startIndex for i in range(minIndex + 1,len(array)): if array[i] < minValue: minIndex = i minValue = array[i] return minIndex ...
54e39010942ec470f5406f65957543ab41badebf
he9mei/python_appium
/learning_unittest/leaning/unitest_leaning_01.py
2,471
3.8125
4
''' 一、基本用法 引入unittest模块 1.用unittest编写用例需要遵循规则: (1)创建测试类,以Test开头,必须继承unittest.TestCase类 (2)创建测试方法,必须要以test开头 2.可以使用unittest提供的断言方法,直接以self调用,如self.assertEqual() 3.调用unittest.main()来执行用例,它会按照前面两条规则来查找并执行用例。 二、4个基本概念 unittest有4个基本概念:Test Case、Test Suit、Test Runner、Test Fixture Test Case:最小测试单元,unittest提供了TestCase基类,我们创建的...
a9306f203b95060db5f8125932535c72b4ec6377
psy1064/osam
/python/polymorphism.py
452
3.5
4
class Animal: def cry(self): print("./././") def supertest(self): print("상속받은 클래스입니다.") class Human(Animal): def cry(self): print("엉엉") super().supertest() # super() = 상속받은 클래스에서 부모클래스의 함수를 사용하고 싶을때 class Whale(Animal): def cry(self): print("고래") class Monkey(Animal): def cry(self): print("우끼끼") ...
af2a6c427fb1c951ecef776a1755cc707dff6c08
psy1064/osam
/python/string.py
1,681
3.90625
4
stringa = "abcdefghi" print(stringa[0]) print(stringa[5]) print(stringa[8]) print(stringa[-1]) # 역 순 print(stringa[0:3]) print(stringa[1:3]) print(stringa[0:8]) # 0~8까지 문자 출력 print(stringa[:-1]) stringa = "abc" stringb = "defghi" print(stringa + stringb) # 문자열 합치기 print(stringa * 5) # 문자열 반복 stringa = "오늘도화이팅...
0ce4b86268f42451f21a24484a3466bbc9243e7d
psy1064/osam
/python/repetitive.py
654
3.640625
4
result = 0 result = 1+2+3+4+5+6+7+8+9+10 print(result) result = 0 i = 0 while(i<10): i += 1 print(i, end = ' ') # end = ' ' 출력 시 공백 추가 result += i print(result) # while 이용한 1~10 더하기 x = 0 result = 0 for x in range(0,10): # x >= 0 and x < 10 x += 1 print (x, end = ' ') result += x print(result) # for - ...
7a8256b3bef1e6aea82fa29590cbf35c81ee47b6
asunYLiu/udacity-data-analyst-nanodegree
/P3-Wrangle-OpenStreetMap-Data/skip_csv_header.py
1,490
3.515625
4
# -*- coding: utf-8 -*- """ Created on Sun Nov 13 15:56:04 2016 @author: Ju """ import csv def add_unique_id(filename, newfilename,idname): """adds a unique id as a column to the original csv file and return a new csv file""" with open(filename, "rb") as infile, open(newfilename, "wb") as outfile: ...
ef720ba21cecd19557c875ee95ee2b33e0bf07f3
nrflynn2/Algorithm-Challenges
/Algorithms_General/ArraysStrings/checkPermutations.py
929
3.734375
4
# O(N) import unittest from collections import Counter def permutation(str1, str2): if len(str1) != len(str2): return False cnt = Counter() for char in str1: cnt[char] += 1 for char in str2: if cnt[char] == 0: return False cnt[char] -= 1 return True clas...
bd84b8a639db9b0cdadc022589a0a94b149316fa
nrflynn2/Algorithm-Challenges
/Rosalind/Algorithms/MAJ.py
1,081
3.765625
4
import sys from collections import Counter '''Alternative: Moore's Voting Algorithm def majority_element(a): # Initialize the candidate element and count. candidate, count = a[0], 0 # Run through the list, updating the count and changing candidates as necessary. for element in a: count += [-1, ...
4d30e061c690da6299b6a7e1c31c0b46ae0b3706
nrflynn2/Algorithm-Challenges
/Rosalind/Stronghold/SPLC.py
1,212
3.765625
4
''' RNA Splicing ------------ After identifying the exons and introns of an RNA string, we only need to delete the introns and concatenate the exons to form a new string ready for translation. Given: A DNA string ss (of length at most 1 kbp) and a collection of substrings of ss acting as introns. All strings are given...
e74a0ce8b1b2301019f58e51ad1befacaf983a4c
sidmusale97/SE-Project
/Pricing Algorithm/linearRegression.py
1,113
4.28125
4
''' ------------------------------------------------------------------------------------ This function is used to compute the mean squared error of a given data set and also to find the gradient descent of the theta values and minimize the costfunction. ------------------------------------------------------------...
40e7d35ffbb5c5e3edf33a613fafa1927833654f
RinozaJiffry/HackerRank-Python
/Loops.py
264
3.875
4
## The provided code stub reads and integer,n , from STDIN. For all non-negative integers i < n, print i^2. ## Sample Input 0 # 5 ## Sample Output 0 # 0 # 1 # 4 # 9 # 16 if __name__ == '__main__': n = int(input()) for i in range(n): print(i*i);
426fe8df7d7675b1b6ccadf0e716bb6ea6b3712b
farukara/algorithms
/counting_sort.py
574
3.953125
4
#!python3 # this is counting sort, preserving original order of equal keys from numpy import random a = random.randint(1000, size=4000000) print(a) def counting_sort(array): """sorts array using counting sort. Respects original order if keys are equal""" l = [0]*(max(array)+1) for i in array: ...
01292c1df24b728df211546fdc7fbcda2fad7d0e
farukara/algorithms
/selection_sorting.py
1,482
3.75
4
#!python3 from numpy import random from time import perf_counter def selection_sort(array): "a is a list like iterable. returns sorted version of a" for i in range(len(array)): j = 1 k=i while i+j<len(array): if array[i+j] < array[k]: k = i+j ...
e1b76beeff1615608909bfa26f69f0a7f7cde083
LucasLopes1/Lista_exercicios_Python
/ex_verifica_vitima.py
699
3.59375
4
print ("verificando a relação com a vitima.") cont=0 pergunta = int(input("Telefonou para a vitima? SIM[1] NÃO[2]\n")) if pergunta == 1: cont=cont+1 pergunta = int(input("Esteve no local do crime? SIM[1] NÃO[2]\n")) if pergunta == 1: cont=cont+1 pergunta = int(input("Mora perto da vitima? SIM[1] NÃO[2]\n")) ...
ce517efe87cd5d702c872876871a4ea233a2bb16
ZhuJiahui/ECTH
/TimeConvert.py
1,545
3.703125
4
#coding:utf-8 ''' Created on 2013年7月17日 @author: ZhuJiahui ''' import time def time_convert(time): """ 将系统时间转化为小时 :param time: :return: """ date = int(time) hour = round((time - date) * 24) time = date + hour / 24 return time def CST_to_Unix(time_string): #CST format: Mon Oct...
526e455025508c352f50064a292786819a339807
orhaneng/Machine-Learning
/PolynomialRegression.py
1,284
3.5625
4
import numpy as np import pandas as pd from matplotlib import pyplot as plt dataset = pd.read_csv('Position_Salaries.csv') # missing data x = dataset.iloc[:, 1:2].values y = dataset.iloc[:, 2].values # fitting linear regression from sklearn.linear_model import LinearRegression lin_reg = LinearRegression() lin_reg.f...
fa260ea16c522140973f1eeeac24c7a2ba6c617c
whad0001/ECE4078_Practical_2021-1
/Week03/Support/math_functions.py
6,153
4
4
import numpy as np import math def compute_distance_between_points(p1, p2): """ Computes distance between two points """ dx = p2[0] - p1[0] dy = p2[1] - p1[1] return math.hypot(dx, dy) def is_point_in_segment(start_seg, end_seg, point_q): """ Determines in point_q is strict...
93226ba29c06e18e86531e1c7326ab89082d473c
SAbarber/python-exercises
/ex12.py
611
4.34375
4
#Write a Python class named Circle. Use the radius as a constructor. Create two methods which will compute the AREA and the PERIMETER of a circle. A = π r^2 (pi * r squared) Perimeter = 2πr class Circle: def area(self): return self.pi * self.radius ** 2 def __init__(self, pi, radius): self.pi = pi ...
153844a39053bf165547a8626a89840a82274f36
alu0100636857/Grupo1H
/src/src/InterpolacionTaylor.py
781
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Interpolación: Taylor # Gabriela Balcedo Acosta y Vanesa Abad Armas # Curso: 2012/2013 from math import * from sympy import * A=0 B=2 def factorial(n): if (n<2): return 1 r=1 for i in range(2,n+1): r*=i return r def deriv(): symb_x = S...
eddbe379662a84229fd4576ff217dd51ec6bc112
swordsx/leetcode
/Simplify Path.py
425
3.65625
4
class Solution: # @param {string} path # @return {string} def simplifyPath(self, path): directories = path.split('/') stack = [] for directory in directories: if directory == '.' or directory == '': continue elif directory == '..': if stack: st...
2c5bbcc13cc32f4aa77edd1abee058851d09f771
swordsx/leetcode
/Count Complete Tree Nodes.py
618
3.84375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param {TreeNode} root # @return {integer} def countNodes(self, root): if not root: return 0 nodeL, nodeR = roo...
07e60d8a62709af01b3e615569f6fe0857171112
swordsx/leetcode
/Binary Tree Postorder Traversal.py
888
3.890625
4
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a list of integers def postorderTraversal(self, root): stack = []; list = [] ...
6e78d8d6952bf5393c72c1dc4af0cfae5d843471
gabbychoi43/PythonExercise
/Duck/Hello.py
340
3.640625
4
class Hello : t='상속해줄객체' @classmethod def calc(self,cls): return cls.t @staticmethod def calc2(): return Hello.t def display(self,x): print('display :',x) class HelloChild(Hello) : t='상속받은객체' print(HelloChild.calc(HelloChild)) print(HelloChild.calc2())
00fe8ed341fef04dc3673a6aa0fccfb38ac315bb
Abhid1239/Python_Gotham_game_basic
/Gothamgame.py
8,788
3.734375
4
from sys import exit #to exit the game from random import randint class scene(object): def enter(self): print("this will be work on later cases lets work on the subclasses for a while") exit(1) class engine(object): def __init__(self,scene_map): self.scene_map=scene_map def play(s...
53d3b4d2b19b72b81aba51e90debc81e28709e26
terintelivia/Siruri-de-caractere
/pr7.py
999
3.875
4
S=str(input("Dati elemente in sirul dat:")) x=S.count('A') print("a) Numarul de aparitii ale caracterului 'A' in sir:",x) for i in S: sir2=S.replace('A','*') print("b) Sirul obtinut prin substituirea caracterului 'A' prin caracterul '*' :",sir2) for i in S: sir3=S.replace('B',' ') print("c) Sirul obtinu...
5d3cc3ec8dd088214baf9d4d03d623b4e8bfeccf
darkbodhi/Some-python-homeworks
/square2rev_2.py
241
3.90625
4
x = int(input("Insert the size of the numeric square: ")) y = int(x*x) for i in range(0, x): for j in range(0, x): print((y - x) + 1, end=" ") y += 1 if (y) % x == 0: print(" ") y = y - 2*x
66f670f58a260d2b9d5113072acdb9bc499539fb
darkbodhi/Some-python-homeworks
/max2.py
163
4.03125
4
x = int(input("Insert the first number: ")) y = int(input("Insert the second number: ")) if x > y : print(x) elif x < y : print(y) else : print(x or y)
31a1c03f4e8f53e04d87da53d38412c0bfb6554a
darkbodhi/Some-python-homeworks
/comparison.py
224
3.953125
4
print("Type the first number: ") x = input() print("Type the second number: ") y = input() print("x < y",x < y) print("x > y",x > y) print("x == y",x == y) print("x != y",x != y) print("x >= y",x >= y) print("x <= y",x <= y)
f9dcae3fc27471fb9f773d65def3cb44be96a022
darkbodhi/Some-python-homeworks
/division.py
123
3.765625
4
print('Insert the first number: ') x = int(input()) print('Insert the second number: ') y = int(input()) z = x / y print(z)
1cca34bd53ba9d73f844dccf011526deb399cd18
darkbodhi/Some-python-homeworks
/divN.py
713
4.25
4
minimum = int(input("Please insert the minimal number: ")) maximum = int(input("Please insert the maximal number: ")) divisor = int(input("Please insert the number on which the first one will be divided: ")) x = minimum % divisor if divisor <= 0: raise Exception("An error has occurred. The divisor is not a natural ...
a8188181e4443956f358b45332ef8190aa40bd46
ishikalamba222/tathastu_week_of_code
/day 1/day2/program3.py
129
3.609375
4
a=int(input("enter any number")) count=0 while(a!=0): rem = a % 10 count = count * 10 + rem a = a //10 print(count)
ff3fc1bca18efff1ac15ef4f67add738dd1d266d
mjpraino/adventure_game
/My_Adventure_Gamev5.py
6,231
4.125
4
# Python Text RPG import time import random # Definitions bag = [] scroll = ['FireBlast', 'FrostNova', 'Ignite'] MagicRune = ['Frost Bolt', 'Fire Ball', 'Lightning Bolt'] Dragon = ['Blue Dragon', 'Green Dragon', 'Red Dragon'] Weapon = ['Rusted Sword', 'Long Sword', 'Wand'] Dungeon = [] MagicRune = r...
f5c0133e80193d186c93b67531dde83d31aa675b
HarshGG/college-search-csv
/highest_in_state.py
803
4.0625
4
import csv def highest_in_state(state): """ Returns the name and cost of the most expensive university in state We're using the TUITIONFEE_IN field as cost and INSTNM as the school name. Be careful on data types on this one. """ with open('university-data.csv', newline='')...
981f02874d9b0befadd0b6a53d58ca657221efc6
aigazulu/JoeyPizza
/python-tools/degree_tools.py
735
3.84375
4
import csv def getDegreesAndCount(): degrees = [] with open('degree.csv') as csvfile: spamreader = csv.reader(csvfile) for row in spamreader: print row tmp_list = [] tmp_list = row[0].split(",") if len(tmp_list) > 0: for item in tmp_list: degrees.append(item) else: degrees.append...
b22be12dc1a6fcce010a7e0976edb7aeb92ca9cb
scottwedge/blib
/bLib/test.py
226
3.8125
4
from abc import ABC, abstractmethod class Parent(ABC): def __init__(self): print ('init') @abstractmethod def a(self): pass class Child(Parent): def __init__(self): pass def a(self): pass A = Child() A.a()
aa0c6a66944e2cef568c401bd7f55e55bca1cec6
anilkumar-satta-au7/attainu-anilkumar-satta-au7
/create_a_dictionary_from_a_string.py
430
4.21875
4
#3) Write a Python program to create a dictionary from a string. # Note: Track the count of the letters from the string. # Sample string : 'w3resource' # Expected output: {'3': 1, 's': 1, 'r': 2, 'u': 1, 'w': 1, 'c': 1, 'e': 2, 'o': 1} test_str = "w3resource" all_freq = {} for i in test_str: ...
01b0cf471c7e1a3d5ea42bd4e8ce2b44eaaba293
pyaephyokyaw15/credit-card-validation
/credit-card.py
1,811
4.28125
4
''' Credit-card Validation - This script is used to determine whether a certain credit-card is valid or not. - It is based on Luhn’s algorithm. - It also determines the type of Card(eg.MASTER, VISA, AMEX) ''' def main(): # getting number from user until it is numeric value while True: card = i...
a36d51210c4062391cca3a8218f990388fc20cca
jenihuang/hb_challenges
/EASY/lazy-lemmings/lemmings.py
942
4.21875
4
"""Lazy lemmings. Find the farthest any single lemming needs to travel for food. >>> furthest(3, [0, 1, 2]) 0 >>> furthest(3, [2]) 2 >>> furthest(3, [0]) 2 >>> furthest(6, [2, 4]) 2 >>> furthest(7, [0, 6]) 3 >>> furthest(7, [0, 6]) 3 >>> furthest(3, [0, 1, 2])...
de62ef9fb09f2d10b0813bf727442cb6c282b546
jenihuang/hb_challenges
/EASY/replace-vowels/replacevowels.py
946
4.34375
4
"""Given list of chars, return a new copy, but with vowels replaced by '*'. For example:: >>> replace_vowels(['h', 'i']) ['h', '*'] >>> replace_vowels([]) [] >>> replace_vowels(['o', 'o', 'o']) ['*', '*', '*'] >>> replace_vowels(['z', 'z', 'z']) ['z', 'z', 'z'] Make sure to handle ...
6ce8b6c28e28ea4207d7bfbc95fb9ccc0d558602
jenihuang/hb_challenges
/MEDIUM/balanced-brackets/balancedbrackets.py
1,935
4.15625
4
"""Does a given string have balanced pairs of brackets? Given a string, return True or False depending on whether the string contains balanced (), {}, [], and/or <>. Many of the same test cases from Balance Parens apply to the expanded problem, with the caveat that they must check all types of brackets. These are fi...
29c4f36d8bfa47db7391311153a590deeb43216b
jenihuang/hb_challenges
/MEDIUM/maxpath/maxpath.py
2,844
4.125
4
"""Given a triangle of values, find highest-scoring path. For example:: 2 5 4 3 4 7 1 6 9 6 = [2,4,7,9] = 22 This works: >>> triangle = make_triangle([[2], [5, 4], [3, 4, 7], [1, 6, 9, 6]]) >>> triangle [2, 5, 4, 3, 4, 7, 1, 6, 9, 6] >>> maxpath(triangle) 22 """ class Node(...
56b74a67432b51d620cd2b9d18dd994bd1b2b802
jenihuang/hb_challenges
/MEDIUM/calculator/calculator.py
1,162
4.03125
4
"""Calculator >>> calc("+ 1 2") # 1 + 2 3 >>> calc("* 2 + 1 2") # 2 * (1 + 2) 6 >>> calc("+ 9 * 2 3") # 9 + (2 * 3) 15 Let's make sure we have non-commutative operators working: >>> calc("- 1 2") # 1 - 2 -1 >>> calc("- 9 * 2 3") # 9 - (2 * 3) 3 >>> calc("/ 6 - 4 ...
9015d36d969ed1e22d46113064e94a3c26dc0043
jenihuang/hb_challenges
/EASY/rev-string/revstring.py
519
4.15625
4
"""Reverse a string. For example:: >>> rev_string("") '' >>> rev_string("a") 'a' >>> rev_string("porcupine") 'enipucrop' """ def rev_string(astring): """Return reverse of string. You may NOT use the reversed() function! """ rev_str = '' for i in range(len(astring)-1, ...
96da77967598606b8d3e1e67cc61d5d82a1c6068
jenihuang/hb_challenges
/MEDIUM/pivot-ll/pivot.py
2,906
4.09375
4
"""Pivot linked list around a value. Given a singly linked list and a data value, rearrange linked list so that all items with data less than value are at the start and all items greater than or equal to the value are at the end. For example: >>> ll = LinkedList([7, 6, 2, 3, 9, 1, 1]) >>> ll.pivot(5) >...
6fdb741e9ccd497a7f6a7ae00604072bbf178262
jenihuang/hb_challenges
/EASY/missing-number/missing.py
831
4.15625
4
"""Given a list of numbers 1...max_num, find which one is missing in a list.""" def missing_number(nums, max_num): """Given a list of numbers 1...max_num, find which one is missing. *nums*: list of numbers 1..[max_num]; exactly one digit will be missing. *max_num*: Largest potential number in list >...
6f9076a7848a4ece9619a8df1e09c358312e2875
Bhairavi-shah/CSV-file-manipulation
/specialcharacters.py
1,754
4.03125
4
import pandas as pd import unicodedata import string from os import sys def read_file(filename): """ Function to read a csv File :param filename: File Name :return: Dataframe of the read File """ try: return(pd.read_csv(filename, keep_default_na=False)) except IOError : prin...
40d0867594c66ff7299e4744b5352ea0c13b98b8
gravitino/libripoff
/examples/all_pairs.py
1,357
3.734375
4
'''Some basic example calls for the all_pairs method''' from ripoff import all_pairs, distances #import pickle if __name__ == '__main__': catalogue = [""" public class HelloWorld { // A program to display the message // "Hello World!" on standard output public static void main(String[] args) { ...
7a243b23aa791559524d9ab3c06790bafb63273d
michelleyick/Iteration
/Guess the number game.py
178
3.59375
4
#Michelle Yick #10-11-2014 #Guess the number game. count = 0 number = import random random.randint(0,100) guess = int(input("Enter a number (1-100):")) while guess
6662cbea3cf303a29e492c168b9d420be47bc756
michelleyick/Iteration
/Class exercises (Revision Q5).py
486
4.0625
4
#Michelle Yick #29/10/2014 #Iteration class exercises. Revision Q5. total = 1 numberSeries = 1 amount = int(input("Amount of numbers you want to average")) while numberSeries != -1: if numberSeries > 0 or numberSeries < -1 or numberSeries == 0: numberSeries = int(input("Enter the number you wish...
1c8beb6fd403be86211242e1e4b2b4165ff9b5c2
orangefishliu/biography-corpus
/wiki_full_text.py
1,096
3.546875
4
import wikipediaapi import json # load wikipedia extractor wiki_extract = wikipediaapi.Wikipedia( language='en', extract_format=wikipediaapi.ExtractFormat.WIKI ) # a function to get a list of wikipedia's category members def list_category_members(category_members): cat_list = [] for c in category_mem...
fdbff6e7b4f17cb0bbd9d3dc27b3825f152d9df3
natan-kilo/multifactory-py
/client.py
1,785
3.515625
4
import socket import common import os import pickle def get_config(): if not os.path.exists("config"): raw_ip = input("Server IP: ") if len(raw_ip.split(":")) != 2: print("Please enter a valid IP!") quit() (ip, port) = raw_ip.split(":") passwd = input("Serve...
0d4b9cf0766435e1e9b19a0a247c8845b4187818
careynation/python_class
/Chapter2/exercise6.py
1,065
4.03125
4
# @author Carey Nation # @title Chapter 2, Exercise 6 # @description Calculate county and state sales tax for a sale STATE_SALES_TAX_RATE = 0.05 COUNTY_SALES_TAX_RATE = 0.025 def read_it(prompt): # read a single value, makes sure it is a valid number, and return it valid = False f = 42 # get it scoped ...
245a0625ffc0abf415e0ed4bf0c09cd902d36a1d
careynation/python_class
/Chapter2/exercise12.py
826
3.890625
4
# @author Carey Nation # @title Chapter 2, Exercise 12 # @description Calculate commissions and profit/loss for a stock sale COMMISSION_RATE = 0.03 SHARES = 2000 BUY_PRICE = 40 SELL_PRICE = 42.75 cost = SHARES * BUY_PRICE buy_commission = COMMISSION_RATE * cost total_cost = cost + buy_commission sell_amount = SHARES ...
0b56f51a691701736f9c84872057c10421ac07c0
JaviS1997/ie_python_course
/HW.py
1,891
4
4
import numpy as np def askName(): print("What's your name ?") name = input() print("Nice to meet you {} !".format(name)) return 1 def division(): print("Input two integer numbers for the division. \nNumerator :") num = int(input()) print("Denominator :") denominator = int(input()) ...
33c6283be192776c46839c86bb216fbfd1ed82ec
atiburcio/R-Code
/airport_sim.py
6,174
3.6875
4
import random import pandas as pd import simpy # Repurposed car wash example from simpy documentation to create an airport simulation. The objects/generators are still using carwash syntax but the print statements have been updated. RANDOM_SEED = 42 NUM_WASH_MACHINES = 4 # Number of washing machines in carwas...
c1e34faecdc4121a02daf10cc98b36c25b76e6d2
Fishelstix/softdev_spring16
/HW06/password.py
598
3.6875
4
import string def minStrength(pw): charTypes = [0 if x in string.ascii_lowercase else 1 if x in string.ascii_uppercase else 2 if x in string.digits else 3 for x in pw] return (0 in charTypes) and (1 in charTypes) and (2 in charTypes) def strength(pw): index = 0 index += min(2,len([1 for x in pw if x i...
b77331fbc316ca06ed510559710ab548638a3c2c
PresterJuan/Fun_Scripts
/birthdays.py
506
4.09375
4
from fractions import * people = 20 days = 365 def birthday_odds(people,days): """Used to calculate the odds that two people share a same birthday in a room full of people.""" odds_not_same_day = [] while people != 0: odds_not_same_day.append(Fraction(days,365)) days -= 1 people -...
cd89cdec7fd02724a26f417b721f76a29814dfda
NadavShwartz93/DBTableScanner
/Excel_tables_creators.py
2,025
3.59375
4
import write_excel_file as wef import querys_mysql as qm if __name__ == '__main__': # This section is just for execute the code, and generate the excel tables in Command Line way val = input("Press 1 for change mysql configuration, Else, press 2: ".title()) if val == str(1): host = input("...
7ca9a0f872aa497c457a6b793482b14937c12cd1
alsonlu/python
/RecursionAndConditions/recursion.py
527
3.921875
4
import turtle def recurse(n, s): if n == 0: print(s) else: recurse(n - 1, n + s) # print statement below goes in opposite order as it resolves from the lowest n to the highest (since highest is where it starts) print(n) recurse(3, 0) def draw(t, length, n): if n == 0: ...
6009b813b74f968244ca96a3b61aa44dfaec3aa9
alsonlu/python
/Loops/eval_loop.py
182
3.90625
4
import math def eval_loop(): while True: line = input('> ') if line == 'done': print(line) break print(eval(line)) eval_loop()
cda3e8bdb2bf45f56f5b4f7b59c7cc665f4c6b4e
alsonlu/python
/Functions/CreateOwnFunction.py
2,248
3.671875
4
import math def print_lyrics(): # Single quotes print('I can show you the world') # Double quotes print("Shining, shimmering splendid") print_more_lyrics() print("Aladdin and Jasmine") # Empty line to signify end of function not needed, can just be an untabbed line def print_more_lyrics(): p...
39754cc20f6a95880536c15e508f21aec7c3b10b
chm7374/Social-Media-Scanner
/main.py
1,222
3.609375
4
from urllib.request import urlopen from bs4 import BeautifulSoup import requests import urllib from urllib.request import urlopen from lxml import html import nltk # This code searches the html of a specific instagram page and relays the information. def post_scan(): """url = "https://www.instagram.com/p...
d08bdcca0bffface25c676599334420929149312
shemar100/coding_challenge
/big_o_examples.py
2,075
3.984375
4
# O(1) Constant # With algorithms that has a constant time complexity, the growth of the input doen't have a computational intesnity def func_constant(values): ''' Prints the first items in a list of values. ''' print(values[0]) func_constant([1,2 ,3, 4, 5]) # O(n) Linear # With algorithms that has ...
253862277ae19898ea209eb2520b73630c2d3c06
ugaldedr/Digital-Signal-Processing
/Homework 8/dru8068-hw08/notchFilter.py
1,475
3.59375
4
""" Name: Dario Ugalde MavID: 1001268068 Course: CSE 3313 Digital Signal Processing """ import numpy as np import matplotlib.pyplot as plt def applyNotch(fs, dataFile) : f = 17 w = 2 * np.pi * f / fs data = np.genfromtxt(dataFile, delimiter=",") y = np.array([]) print(len(data)) ...
de346421fd9bf36a0113d702ccf6de03620b8198
Johan-p/learnpythonShizzle
/exercise_36_birthdayplots.py
1,639
4.28125
4
""" In this exercise, use the bokeh Python library to plot a histogram of which months the scientists have birthdays in! """ print(__doc__) from bokeh.plotting import figure, show, output_file from collections import Counter import json def read_jsonfile(): #global birthday_dictionary global x global ...
713ed8035bf707c380e127bab4f0c6b36f6641ce
Johan-p/learnpythonShizzle
/Madlibs.py
1,517
4.46875
4
""" In this project, we'll use Python to write a Mad Libs word game! Mad Libs have short stories with blank spaces that a player can fill in. The result is usually funny (or strange). Mad Libs require: A short story with blank spaces (asking for different types of words). Words from the player to fill in those ...
1144185ef458b827d111ad96630d3385493f2d25
Johan-p/learnpythonShizzle
/firstclasslesson.py
3,092
4.25
4
#lesson 1 class Animal(object): pass #lesson 2 class Animal(object): def __init__(self): pass #lesson 3 class Animal(object): def __init__(self, name): self.name = name #lesson 4 class Animal(object): def __init__(self, name): self.name = name zebra = Animal("Jeffrey") ...
8a8d89f72edd35ccb2928af5b147ad882899c6fe
Johan-p/learnpythonShizzle
/exercise_33_birthdaydictionaries.py
884
4.59375
5
""" or this exercise, we will keep track of when our friends birthdays are, and be able to find that information based on their name. Create a dictionary (in your file) of names and birthdays. When you run your program it should ask the user to enter a name, and return the birthday of that person back to them. ...
d03f25d7cfe3bb9ff334c74d964ea7542e6269f0
Johan-p/learnpythonShizzle
/classes.py
2,394
3.96875
4
class Triangle(object): number_of_sides = 3 def __init__(self, angle1, angle2, angle3): self.angle1 = angle1 self.angle2 = angle2 self.angle3 = angle3 def check_angles(self): sum_angles = self.angle1 + self.angle2 + self.angle3 if sum_angles == 180: return True else: ...
c816a4224eeff0e5610176feb5df8eacfe3efcfb
HarrisonWelch/MyHackerRankSolutions
/python/Nested Lists.py
496
4.25
4
# Nested Lists.py # Given the names and grades for each student in a Physics class of N students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade. marksheet = [] for _ in range(0,int(input())): marksheet.append([raw_input(), float(raw_input())]) second_highest =...
831544c8a534a3885c6fec8b1dcd55b25bb6a93b
anjalp/Project-Image-Steganography
/source/Image Steganography T1.py
7,215
3.609375
4
from PIL import Image from numpy import array import os def encodeImg(): img_loc = '' string = '' saveName = '' os.system('cls') print(" --------------------------------Image Steganography T1-------------------------------\n") print(" ---------------------------------Insert Text To Image-...
acf762ce8329c29c8a8254a1210ed655e24c287d
hhummel/codewars-kata
/python/determinant.py
489
3.671875
4
#Solution to "Matrix determinant" 4 kyu #https://www.codewars.com/kata/52a382ee44408cea2500074c def determinant(matrix): length = len(matrix) if length == 1: return matrix[0][0] if length == 2: return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0] def submatrix(matrix, i): ...
b5444afc98dd453814caabf021d1d70f0f0c93b2
hhummel/codewars-kata
/python/hard_sudoku.py
6,075
3.953125
4
#Solution for "Hard Sudoku Solver" 3 kyu #https://www.codewars.com/kata/55171d87236c880cea0004c6 def solve(puzzle): """return the solved puzzle as a 2d array of 9 x 9""" #Find candidate solutions for each 3x3 subgrid that satisfy the initial puzzle constraints all_solutions = make_all_solutions(puzzle) ...
29857f04b3e0b7abd9f7d2c55e0a3206506e7398
hhummel/codewars-kata
/python/max_subarray_sum.py
950
3.828125
4
#Solution for "Maximum subarray sum" 5 kyu #https://www.codewars.com/kata/54521e9ec8e60bc4de000d6c def maxSequence(arr): #If the arr is empty, return an empty subarray if len(arr) == 0: return 0 #Start from the right hand side and find the largest subarray for each position #Reverse the initial...