blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
9e9a035528e322e167ada1adb567c8052fc35b4e
tony-andreev94/Python-Fundamentals
/01. Functions/04. Odd and Even Sum.py
676
4.1875
4
# You will receive a single number. You have to write a function that returns the sum of all even and all odd digits # from that number as a single string like in the examples below. # # Input Output # 1000435 Odd sum = 9, Even sum = 4 # 3495892137259234 Odd sum = 54, Even sum = 22 d...
e6036913f6445e433aa539a106c0193c871922d5
philips-ni/ecfs
/leetcode/083_remove_duplicates_linklist/python/remove_duplicates_linklist.py
1,039
3.515625
4
class ListNode(object): def __init__(self, x): self.val = x self.next = None def initList(list): if len(list) == 0: return None head = ListNode(list[0]) prevNode = head for i in list[1:]: currentNode = ListNode(i) prevNode.next = currentNode prevNode ...
e0b76f270ed551ad06e1eec383aaada7600213a5
davidalejandro1223/Introduccion-ciencia-datos
/Numpy/Taller 1 - Intro python/taller1-Ciencias.py
503
3.71875
4
import random num = (random.randrange(0,99)) print (num) intents = 0 while intents<10: inp = int(input('Ingrese tu numero\n')) if inp == num: print('Has adivinado el numero') print('Tu puntaje fue: ' + str((10-intents))) break elif inp < num: print('El numero a adivinar es ...
064cf4d753e9def732842f472231e1d3a4567431
dineshkumar12004/Interview-Experience
/Accenture/PermutationCount.py
188
3.890625
4
# permutation count of a string def permute(string): if len(string) == 1: return 1 else: return len(string) * permute(string[1:]) ans = permute('abc') print(ans)
c62ce11a1b4b6bf036b2f6279b6798f45947e0c6
YuLili-git/leetcode_offer
/剑指 Offer 07. 重建二叉树.py
1,088
3.796875
4
#输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。 #假设输入的前序遍历和中序遍历的结果中都不含重复的数字。 #示例 1: #Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] #Output: [3,9,20,null,null,15,7] #示例 2: #Input: preorder = [-1], inorder = [-1] #Output: [-1] # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # s...
68db601ad5ab20fa79e87dfadc8fe20d912e1387
iaevan/Pybook1-solutions
/page 114.py
234
3.796875
4
import turtle x = 0 y = 1 z = 0 n = 12 for i in range(n): z = x + y x = y y = z print(x) for i in range(4): turtle.forward(x*10) turtle.left(90) turtle.circle(x * 10 , 90)
7ade29789a1dae0b128cc1120d1dfdf225ee6ae7
Leo428/CS61A
/cats/typing.py
10,016
3.78125
4
"""Typing test implementation""" from utils import * from ucb import main, interact, trace from datetime import datetime ########### # Phase 1 # ########### def choose(paragraphs, select, k): """Return the Kth paragraph from PARAGRAPHS for which SELECT called on the paragraph returns true. If there are few...
6d410a16cb59af71c659766eaa78ff555e4fa09b
kozhakhmetov/PythonTasks
/Hackerrank/Easy/py-hello-world/test_main.py
514
3.546875
4
import main class TestClass: def test_1(self): # main.input = lambda: 'some_input' output = main.main() assert output == 'Hello world' def test_2(self): # main.input = lambda: 'some_other_input' output = main.main() assert output == 'Hello world' def test_...
b17957c35abbaacab1ca68e910e83e870c37491b
Deepak-Rai-1027/Probability_Python_Codes
/Conditional_Probability.py
1,816
4.0625
4
# Probability of an event A given another event B has already occured. # In this case the new universe is event B (the new sample space omega) # Main objective is to calculate the portion of A in event B. # Example # Calculate the probability a student gets an A (80% +) in math, given they miss 10 or more classes. ...
0b5741b74c6fe0e14d24ab22fe232512b1d7b84f
A7xSV/Algorithms-and-DS
/Codes/Py Docs/fibo.py
577
3.765625
4
# Fibonacci numbers module def fib(n): """Print fibonacci series upto n.""" a, b = 0, 1 while a < n: print a, a, b = b, a + b print def fibr(n): """Return fibonacci series upto n.""" a, b = 0, 1 result = [] while a < n: result.append(a) a, b = b, a + b ...
6ad62ed3f692d4fc78dec59b2a7aa5867d775571
daftstar/learn_python
/01_MIT_Learning/00_final_exam/final_problem4.py
997
4.0625
4
# Implement a function that meets the specifications below. def max_val(t): """ t, tuple or list Each element of t is either an int, a tuple, or a list No tuple or list is empty Returns the maximum int in t or (recursively) in an element of t e.g. find the largest integer in the entire t """ #...
2cb6b0d2a77e4128654b2af5b9834d2a04ad2031
CompassMentis/CheckIO
/triangle_angles.py
941
4.1875
4
""" Solution for http://www.checkio.org/mission/triangle-angles/ in Python 2.7 """ import math def calculate_angle(a, b, c): cos = (b*b + c*c - a*a) / (2.0 * b * c) result = math.acos(cos)/math.pi * 180 result = int(round(result)) if result >= 180: result -= 180 return result def checki...
7c12c89b9006986af6513ecbdb33a4ba8c623c29
edevaldolopes/learning
/08 - object1.py
836
3.703125
4
class Car: def __init__(self, brand, color, year, tank, wheel): self.brand = brand self.wheel = wheel self.color = color self.year = year self.tank = tank def fuel(self, liter): self.tank += liter class Motorcycle(Car): def __init__(self, brand, color, year...
36794b3e99fe00868c14111f2bf297702be699a4
Loksta8/FlipCoin
/flipcoinClass.py
2,234
4.375
4
""" @Author: Logan Herrera @Date: 3/19/2020 @Python Version 3.5.3 The functionality of this class is to generate a montecarlo run of a flipped coin on a case by case basis. It returns the results to the user. """ #Add needed libraries import random from fractions import * #Class definition that takes user input class...
389f570ef9a71a645a91ae84b4d75a5c98a31284
Chalex0/PythonOOP
/lesson_5_1_1.py
296
4
4
""" 5.1 Исключения в Python """ print('Hello1') print('Hello2') try: int('hello') except ValueError: print('wrong type') print('Hello3') try: print('hello'[9]) except IndexError: print('wrong index') print('Hello3') print('Hello4') print('Hello5') print('Hello6')
2e3962263444738d5386df5f2e0d03d03cb6629f
pramodith/DL1
/1_cs231n/cs231n/layers.py
12,633
3.703125
4
import numpy as np def affine_forward(x, w, b): """ Computes the forward pass for an affine (fully-connected) layer. The input x has shape (N, d_1, ..., d_k) where x[i] is the ith input. We multiply this against a weight matrix of shape (D, M) where D = \prod_i d_i Inputs: x - Input data, of shape (N, ...
1d94f5978380afe65e4c2d3c39fdc8ad96e0bad7
krish001/MyPhython
/MatPlotlib.py
781
3.921875
4
# The program evaluates your performance of typing speed # The program will plot a graph. import matplotlib.pyplot as plt import time as t times = [] mistakes = 0 print("this program will validate your typing speed") input("press to continue") while len(times) <5: start = t.time() word = input("Type the word...
fcb6320b1b0a2d1e1f3fc2ee9eaeab8fed89005c
badFarmer/PythonJumpstart_GuessTheNumber
/program.py
834
4.0625
4
#import random import random print('--------------------------------------------') print(' HELLO WORLD') print('--------------------------------------------') print() the_number = random.randint(0, 100) name = input ('What is your name?') #print (the_number, type(the_number)) #print (guess, type(guess)) ...
c343c1660481f25e2c6ef61a3d77692933458ee5
djiang-ucc/image-viewer
/image.py
1,853
3.703125
4
from tkinter import* from PIL import ImageTk,Image root= Tk() root.title('view an image') #create a image viewer #images my_img1 = ImageTk.PhotoImage(Image.open("6ix.jpg")) my_img2 = ImageTk.PhotoImage(Image.open("eastyork.gif")) my_img3 = ImageTk.PhotoImage(Image.open("west.jpg")) #my_img4 = ImageTk.PhotoImage(Imag...
d95ac7222d52a30b2fa4caab90c56f5fb9f30c27
Kontowicz/Daily-Interview-Pro
/solutions/day_125.py
313
3.859375
4
def find_anagrams(s, t): to_return = [] t = sorted(t) for i in range(0, len(s) - len(t) + 1): if sorted(s[i:i+len(t)]) == t: to_return.append(i) return to_return assert find_anagrams('acdbacdacb', 'abc') == [3, 7] print(find_anagrams('acdbacdacb', 'abc')) print('Test pass.')
bfcc97e6188981b238b0cfff751cf8f73c27979a
randell/Project-Euler
/0022-name_scores.py
2,067
3.75
4
# -*- coding: utf-8 -*- """ Project Euler Problem N Title: Name scores Description: Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this...
8d5861aa9738ea91c567eaeede25284ea13f2bb1
Sushmitha26/Pong_Game
/Pong game/pong.py
4,928
4.5625
5
#turtle module is used to do some basic graphics,for games,Using Turtle, we can easily draw in a drawing board. import turtle import winsound wn=turtle.Screen() wn.title("Pong by Sushmitha") wn.bgcolor("black") wn.setup(width=800, height=600) #tracer stops window from updating so we have to manually update it,...
bb6e433e4d0ac5adf12febda1a16a226988f169c
jpark527/Fall2018
/Python/HarvaidX/week2_4.py
1,506
3.59375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Oct 6 19:46:36 2018 @author: j """ ''' Simulating Randomness & Clock ''' import random import numpy as np import matplotlib.pyplot as plt for i in range(10): print(random.choice(['head', 'tail'])) ''' case 1: ''' n = 10000 data = [] #print('\nRo...
f2e5246b8bc030d1d744e0a2fc29177cdb84152c
jadenpadua/Data-Structures-and-Algorithms
/trees/RecoverBST.py
1,036
3.75
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def recoverTree(self, root): """ :type root: TreeNode :rtype: None Do not return anything, ...
20db6364532d0a67b888a86cc249ff51acf40d53
jaredjamieson/personal
/python/SolarSystem/Star.py
1,045
3.921875
4
####Star.py#### #Lab 12 Jamieson & Cardaropoli #Imports class Star: #Constructor def __init__(self, name, type1, mass): self.__name = name self.__type1 = type1 self.__mass = mass #Returns "'name' Star" def __str__(self): return self.__name + 'Star' ...
2f4a30bac02a360e92ea7babee91cb2e11c5fbb4
MollyJ04/python
/classProject.py
15,576
3.84375
4
# Molly Jain # classProject.py import random # variable that decides if the game is still running gameOver = False class Computer: def __init__(self, name): self.name = name self.health = 100 def attack(self, opponent): # one of the options when dueling print(f...
40d8c113ea24b812e0710ae75b4821399ede9954
Asano-H/Hana
/list2.py
437
3.625
4
datalist=[1,2,3] complist=[[10,20,30],1000,["red","blue"]] print(datalist) datalist[2]="three" #datalistの3つ目の要素をthreeに置き換える print(datalist) print(complist[2][0]) #complistの3つ目のリストの1つ目の要素を出力 """ 2次元配列、3次元配列のような複数の階層をもたせることが可能。 数値や文字列を同じリストにまとめることができる。 """
ec4e5ab4b65c2cb1830aa68dd98ad6a8dc2085c8
Nidhi-Chourasiya/Credit_Card
/Credit_Card.py
1,390
3.875
4
import datetime import random while True: card_no = str(input('enter a credit card : ')) if len(card_no)==16: print('valid no. ') else: print('invalid length') user_name = input('enter user name FN MN LN ').split() date=datetime.datetime.now() yyyy=int(input('please enter the y...
6d31230b44dd7593e195e726ab21b834a341c188
BryceGetzHub/Ch.03_Input_Output
/Practice.py
1,002
3.859375
4
# for i in range(10,0,-1): # print(i) # print("blast off") # # total=0 # for i in range (5): # new_number = int(input("enter a number")) # if new_number ==0: # total += 1 # print("you entered a total of", total, "zeros") # # # a=0 # for i in range(10): # a += 1 # print(a) # # # a = 0 # for i in ...
813ce907c0b6019d37cc6204e8568a5ac5572fb9
pisaia01/EPANETinp
/createDBTables.py
4,662
3.578125
4
#!/usr/bin/python import psycopg2 from config import config def delete_table_values(tables): """ create tables in the PostgreSQL database""" conn = None try: # read connection parameters params = config() # connect to the PostgreSQL server print('Connecting to the PostgreSQL...
100118bf105bd5ea946dca16d728dab10b43cd6d
andrew-oxenburgh/python-bowling
/src/test/test_bowling.py
391
3.640625
4
balls = [] def score(): out = "" for ball in balls: out += ball return out def bowl(cnt): balls.append(cnt) return cnt def _test_frame_1_ball_1(): expected = '0' bowl('0') actual = score() assert actual == expected def test_frame_1_ball_2(): expected = '00' bowl(...
dd6c434319031ddc0a68c0684db6e8127e0bc438
CodeupClassroom/curie-natural-language-processing
/acquire_walkthrough.py
4,874
3.671875
4
import pandas as pd import numpy as np from requests import get import os from bs4 import BeautifulSoup def get_all_urls(): ''' This function scrapes all of the Codeup blog urls from the main Codeup blog page and returns a list of urls. ''' # The main Codeup blog page with all the urls url = 'h...
89b454bac0f9b5c3aa0d34b33bea71560962d04d
priyankakl/Pro-Python-Accelerator
/assignment_7.4.py
981
4.03125
4
dict1 = {} list1 = [] list2 =[] dict2 = {} sentence = input("Enter the sentence:") # To split the sentence into words and form a list list_of_words = sentence.split(" ") for word in list_of_words: # if word has more than one occurance in the sentence, increase its count by 1 each time if(word in...
ee9c8db9091ef1d5c47a8839deae5e040ea830ef
osama1998H/standerdLearnd-string
/q68.py
333
3.59375
4
from typing import Counter string = input('enter some text : ') a = Counter(string) d = [] nd = [] for key, value in a.items(): # print(key, value) if value > 1: d.append(key) else: nd.append(key) text1 = '' text2 = '' for i in d: text1 += i for i in nd: text2 += i print(text1) ...
e662e9ed381085a602b663970eb6019f09f08039
michelepeixoto/TextEditor
/TextEditor/TextEditor.py
3,559
4.28125
4
# Notepad style application that can open, edit, and save text documents. # Optional: Add syntax highlighting and other features. import os def open_file(): while True: try: path = input("Where is your file located?\n") os.chdir(path) name = input("What is the file cal...
05366b7f6a9a45e7c48ea892a45455fe8b46747c
Tansiya/tansiya-training-prgm
/sample_question/puzzle.py
545
3.6875
4
"""Write a program to solve a classic ancient Chinese puzzle: We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have?""" #create a function def solve(numheads,numlegs): ns='No solutions!' #access the for loop for i in range(numheads+1): ...
3a1c605a0c097d525b73d344eb2d514c764e6c12
csxeba/wiw
/kata/megoldasok/fvdef.py
1,294
3.5625
4
def rendez(*szamok): """ Írj egy függvényt, amely sorba rendezi a neki átadott számokat és visszatér a rendezett számokkal! """ return sorted(szamok) # :) def legnagyobb(*szamok, hanyadik): """ Írj egy függvényt, amely visszaadja a neki átadott számok közül a "hányadik" legnagyobbat. ...
2450a802c65e8319b97f86ab861d542295f37c1b
adam-berlak/REL-Studios-Music-Robot
/theory/i_pitched_object.py
1,615
3.5625
4
import abc class IPitchedObject(abc.ABC): @abc.abstractmethod def __eq__(self): pass @abc.abstractmethod def __str__(self): pass @abc.abstractmethod def __repr__(self): pass @abc.abstractmethod def __add__(self, p_object): ''' Must handle Cases: isinstance(p...
58e389f33f2c1550599fe86979b34cb9b2b94e66
dmitri-mamrukov/coursera-data-structures-and-algorithms
/course2-data-structures/assignments/assignment_002_make_heap/build_heap.py
5,356
3.703125
4
#!/usr/bin/python3 class MinBinHeap: def __init__(self): self._size = 0 self._heap_list = [] def __str__(self): return str(self._heap_list) def __repr__(self): return ('[size=' + str(self.size) + ', list=' + str(self._heap_list) + ']') @property def s...
84dc064420786e8143e69afb639a2fb597e78f59
TUlicai/shark
/screen.py
536
3.609375
4
# -*- encoding: utf-8 -*- import pygame from pygame.locals import * pygame.init() class Screen: @staticmethod def init(): """ A static method to use the SAME rect all the time. Like this, it is way easier to change it when the user resize the screen """ Screen...
e2ef301b4e3939c57d3ab402ddc57512ed2aed34
lschnellmann/LPTHW
/ex4.py
1,852
4.09375
4
# number of cars total cars = 100 # number of people who can fit in each car space_in_a_car = 4 #available drivers drivers = 30 # available passengers passengers = 90 # cars idle.. since there are 100 cars, and only 30 drivers, 70 idle cars cars_not_driven = cars - drivers # it follows that with 30 drivers only 30 c...
3b9082bdfdc5673a40a7dd33b107cc17bda9ead6
AP-MI-2021/lab-2-SiminaPop
/main.py
2,788
3.6875
4
#pb3 def is_prime(n): """ :param n: numar natural :return: True daca numarul n este prim si False daca numarul n nu este prim """ if n < 2: return False if n == 2: return True if n % 2 == 0: return False for d in range(3, n // 2, 2): if n % d == 0: ...
fe30b9fa0940e6f9e1e624885b53c9869b862d79
YuLili-git/leetcode_offer
/剑指 Offer 63. 股票的最大利润.py
763
3.578125
4
#假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少? #示例 1: #输入: [7,1,5,3,6,4] 3输出: 5 #解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 # 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。 #示例 2: #输入: [7,6,4,3,1] #输出: 0 #解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。 class Solution: def maxProfit(self, prices: List[int]) -> int: ...
516cab1e6a5ea3e7fa178c33e049d0536fb51767
lugia493/Leet-Code
/Binary Trees/n_ary_max_depth.py
768
3.65625
4
def max_depth(root): # If we have a None root, return 0 if not root: return 0 # if the children of a root is None, return 1 for that rot if not root.childen: return 1 # We need the two condtions if we run into a tree that has some # valid nodes and some None nodes. # i.e....
725c5de6688287c88421464ef331858e4496d585
susunini/leetcode
/169_Majority_Element.py
1,793
3.859375
4
class Solution(object): """ Hash Table. Time O(n) Space O(n)""" def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) dic = collections.Counter(nums) for key, val in dic.items(): if val > n/2: ...
8bc1524c67af607e6a23e798996516f8dca88079
kmgaurav2611/GFG_Solutions
/extra/sol.py
504
3.796875
4
def printArray(arr, size): for i in range(size): print(arr[i], end = " ") print() return def getSuccessor(arr, k, n): p = k - 1 while (arr[p] == n and 0 <= p < k): p -= 1 if (p < 0): return 0 arr[p] = arr[p] + 1 i = p + 1 while(i < k): arr[i] = 1 i += 1 return 1 def printSequences(n,...
3c408ac15657a3c40796d15fe84477cfe170181f
MelvilQ/stacksrs-web
/importMemriseCourse.py
2,172
3.5
4
import csv import sys import requests from bs4 import BeautifulSoup courseId = sys.argv[1] invertColumns = sys.argv[2] == 'i' if len(sys.argv) > 2 else False # load course overview page courseUrl = 'https://www.memrise.com/course/' + courseId response = requests.get(courseUrl) if response.status_code != 200: print('...
4c8384392349801c4dd704e2af762707d2340fa6
pauleclifton/GP_Python210B_Winter_2019
/students/daniel_carrasco/session03/list_lab.py
948
3.953125
4
#!/usr/bin/env python3 #task1 list1 = ['Apples','Pears','Oranges','Peaches'] print(list1) response = input(" name another fruit ") list1.append(response) print(list1) response2 = input(" name a number ") print(f'the {response2}rd item in the list is {list1[int(response2)-1]}') list1 = ['Cherry']+list1 print(list1) list...
8475a0c56b3f72a9f367e191c90b97b6c04158a8
mani-9642/mani-9642
/armstrong loop.py
336
3.9375
4
ch="y" while ch=="y": n = int(input("Enter the Number : ")) s = 0 t = n while t>0: r=t%10 s+=r**3 t//=10 if n==s: print(n,"is Armstrong Number") else: print(n,"is not a Armstrong Number") ch=input("Do you want to check again (Y/N) : ") pr...
3b5e1cd67f36e17db8c7bb2a29982fc1a85ba176
XMK233/Information-Security-Experiment
/14061075_修闽珂_实验二/Greatest_Common_Divisor.py
2,480
3.703125
4
'''hui dai fa''' import time a = int( input ( "the a is: " ) ) b = int( input ( "the b is: " ) ) s = [ 0 ] t = [ 0 ] i = 0 '''do some change if a is larger than b''' convertA = convertB = 1 if a < 0 and b >= 0: a = abs( a ) convertA = -1 elif b < 0 and a >= 0: b = abs( b ) convertB = -1 elif a < 0 an...
cde78c98307415e2311bca0f6d13c09802d416bc
bbjy/MachineLearningHomework
/ml2018-hw3/code/Multiboosting.py
6,817
3.546875
4
# -*- coding: utf-8 -*- """ This is an implementation of <MultiBoosting: A Technique for Combining Boosting and Wagging>, GEOFFREY I. WEBB, 2000. """ # @author: WangBei # 2018-12-09 import math from math import e, log,exp import numpy as np from numpy import * from sklearn.tree import DecisionTreeClassifier from sklear...
32d213205f737069a2f84bda3a333bcfb2b2aa81
AronIS98/Basic
/Forritun/Aron_verkefni/Prof_2019.py
1,567
4.09375
4
def get_input(): """gets the input from the user""" user_input = input("Enter an ISBN: ") return user_input def input_to_list(the_input): word_as_list = [item for item in the_input] return word_as_list def is_valid(input_as_list,LENGTH_OF_ISBN,PLACEHOLDER_POSITION): if len(input_as_lis...
b4a242ef9c3c2ada77992889bcbb1280620f0639
materdd/python_tutorial
/tutorial_5.py
5,774
3.75
4
###### Pythonの基礎 ##### # GOAL: Numpy、Scipy、Pandas、Matplotlibのライブラリを # 読み込みそれらの基本的な役割を知る """ 便利ライブラリ(関数群) Numpy: 多次元配列処理 Pandas: 表計算やデータベースのようなデータ操作 Matplotlib: データ可視化(プロット) """ #----- numpy -----# # %% numpy module import """ 多次元配列を処理することができます。 実際に扱うデータは多次元であることが多く、 その処理をするためにNumpyを使うと便利です。 また、NumpyはCで実装されており、処理が高速で...
24df668bdbf0ca9f1e9672cfe11e480a9f5af389
blackplusy/python1119
/例子-1120-05.列表的访问.py
120
3.734375
4
#coding=utf-8 l=['58','ganji','zhilian','51job'] print(l) for a in l: print(a) if '58' in l: print('58 is here!')
3c7fdcc0cccb84c1c8241c5fcf59a497c19e0f51
NicholasTing/Competitive_Programming
/CodeForces_651/c.py
908
3.90625
4
from functools import lru_cache t = int(input()) player_one = 'Ashishgup' player_two = 'FastestFinger' def isPrime(n) : if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0...
4792bf1b27d0bdb3b8b61a9e42d389c572e504a2
rishikeshpuri/Algorithms-and-Data-Structure
/tree/level order data in reverse order.py
725
4.125
4
class Node: def __init__(self, value): self.value = value self.left = None self.right = None def reverseLevelOrder(root): queue = [] stack = [] queue.append(root) while len(queue)>0: root = queue.pop(0) stack.append(root) if root.right: q...
124d9c7036622d334bcbdf06b6bac76659afaf89
MichaelWoo-git/Apriori_Algorithm_from_Scratch
/Apriori_Algo.py
10,634
3.5625
4
# Imports import numpy as np import pandas as pd import os import time from itertools import permutations, combinations from IPython.display import display # this will display the max column width so we can see the associations involved.... pd.set_option('display.max_colwidth', None) pd.set_option('display.max_colum...
917944d62a9978e15b21a2137fbca48cdab3d161
Lilyfodata/ghio
/python/ex13.py
792
3.84375
4
#!/usr/bin/python # -*- coding : utf-8 -*- from sys import argv script, first, second, third, anthoer = argv print "The script is called:", script print "The first variable is:", first print "Your second variable is:", second print "Your third variable is:", third # --------------------------------------------------...
67047ed537ffef7b337aff6ab7045e9530d84b66
thecomputerguy/full-speed-python
/lambdas/pairwithzerosum/PairWithZeroSum.py
435
3.921875
4
def pairWithZeroSum(elements): for i in range(len(elements)): for j in range(i+1,len(elements)): sum_of_two_elements = elements[i] + elements[j] if sum_of_two_elements == 0: return True j = j+1 return False result = pairWithZeroSum([1,2,5,-5,6,-4,3,-8...
3aedc6cbc21851424c8d21e924dc56432486d891
ajkumark/pyqt
/pyqt.py
1,984
3.546875
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ ZetCode PyQt4 tutorial This example shows text which is entered in a QtGui.QLineEdit in a QtGui.QLabel widget. author: Jan Bodnar website: zetcode.com last edited: August 2011 """ import sys from PyQt4 import QtGui, QtCore class Example(QtGui.QWidget): def...
9e1816ed505f61ed13c8893535afacaebf48596a
TayExp/pythonDemo
/05DataStructure/42希尔排序.py
547
3.625
4
def shell_sort(alist,n): """希尔排序""" # n = len(alist) gap = n // 2 while gap > 0: for j in range(gap,n): # j = gap,gap+1,...n-1 i = j while i>gap-1: if alist[i]<alist[i-gap]: alist[i],alist[i-gap] = alist[i-gap],alist[i] ...
e058a50346e75cc017180d7205e5d935e1558b2d
katel85/pands-Problem-Sheet
/Week 5 Task/Weekday.py
654
4.46875
4
# Write a program that outputs whether or not today is a weekday # Author Catherine Leddy #ref : https://www.w3schools.com/python/python_datetime.asp # ref : https://www.xspdf.com/resolution/58438157.html import datetime day= datetime.datetime.today().weekday() if day<5 : print("Yes, unfortunately today is a ...
8ad6ff1ea21ea75e1eebf6b6c73246993f3b4cbe
DevShasa/code-challenges
/codewars/compare_triplets.py
1,190
4.03125
4
''' Alice and Bob each created one problem for HackerRank. A reviewer rates the two challenges, awarding points on a scale from 1 to 100 for three categories: problem clarity, originality, and difficulty. The rating for Alice's challenge is the triplet a = (a[0], a[1], a[2]), and the rating for Bob's challenge is the ...
fcc4f48b33d211b41e4589a40962031f97910af1
ridhim-art/practice_list2.py
/lambda_expresion_ex.py
357
3.59375
4
cir = lambda r: 2 * r * 3.14 cuboid = lambda l,b,h :l*b*h print("circumference for radius 10 is",cir(10)) print("circumference for radius 10 is",cir(5)) print("circumference for radius 10 is",cir(6)) print("circumference for radius 10 is",cir(2)) print("circumference for radius 10 is",cuboid(3,4,3)) print("circumfere...
c490fe9a58221b76284866d04efee81bdde9c74e
krishnanunni-pr/Pyrhon-Django
/Django/Functional programming/Lmabda fuction3.py
266
3.9375
4
# filter function # print even numbers only # filter function - filter(function,iterable) **has condition lst=[1,2,3,4,5,6,7,8,9] #[2,4,6,8] even=list(filter(lambda num:num%2==0,lst))# even number odd=list(filter(lambda num:num%2!=0,lst)) print(even) print(odd)
e3234656a5ccfae4d20543573d2b46d1afde1262
devng/code-puzzles
/src/devng/codejam2018/whole_new_word.py
1,276
4.28125
4
#!/usr/bin/env python3 from itertools import product def find_word(words, n, l): words_set = set(words) chars = [] # put all characters in sets per columns for i in range(l): chars.append({w[i] for w in words}) # print(chars) """ # generates all word prefixes prefs = [] f...
883e82b1cc2987d2009380cb3e53175d08b7d6b4
shafirpl/InterView_Prep
/Basics/Colt_Data_structure/Sorting_Algorithms/Bubble_Sort/Bubble_Sort.py
1,363
4.25
4
def bubble_sort(arr): length = len(arr) if(length == 0): return arr # it goes like this, after first loop, first highest number at the # end of the loop, and so on, so if we have 5 numbers, after first loop # 14 will be at the end of the array, afrer 2nd loop second highest number # 10 will be ...
1fdc22811c1e383c476c7d4a06b1dc9257ab9a4d
csdms/standard_names
/standard_names/tests/test_standardname.py
3,411
3.609375
4
#!/usr/bin/env python """Unit tests for standard_names.StandardName""" import pytest from standard_names import BadNameError, StandardName def test_create(): """Test class creation.""" name = StandardName("air__temperature") assert name.name == "air__temperature" def test_bad_name(): """Try to cre...
2615f01b7685be6a526f3d7e08f31f11d65d22d4
ATinyBanana233/sudokuPY3
/single_ll.py
953
4.125
4
#define the basic data structure node class node(object): def __init__(self, key, value): self.data=value self.key=key self.next=None #define the linked list structure class ll(object): def __init__(self): self.head=None def insert(self,key,node_value): new_node=node(key,node_value) new_node.next=self....
460af1e6f01a502860246fd9612e5965617e4c2f
souvikb07/DS-Algo-and-CP
/data_structures/arrays/easy_6.py
620
3.625
4
def checkPossibility(self, nums): """ :type nums: List[int] :rtype: bool """ length = len(nums) if length == 1: return True count = 0 for i in range(length - 1): if i == 0: if nums[i] > nums[i+1]: nums[i] = nums[i+1] count += 1 ...
066b9d1bfba1194200e3a503dd79922c92757301
Mukul-Singhal/Bibliophile-Companion
/bibliophile/connecti.py
1,613
3.71875
4
import sqlite3 from PIL import ImageGrab con = sqlite3.connect('example.db') c = con.cursor() c.execute( '''CREATE TABLE IF NOT EXISTS History( timestamp TEXT PRIMARY KEY, TYPE NUMBER NOT NULL ,ID INTEGER NOT NULL)''' '''CREATE TABLE IF NOT EXISTS Text(id INTEGER PRIMARY KEY AUTOINCREMENT , Text TEXT) '...
9d50b98b1fd8afa4006994d51b4b0e7b0ac3b1b1
mslshao/InterviewStreet
/insertsort.py
837
3.90625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT T = int(raw_input()) for i in range(0,T): # Run through # of test cases iterator = 0 N = int(raw_input()) # Read in N elements per line;... Crap, how to do?! arr = [] arr = raw_input().split() for j in range (0,N): arr[j] =...
e1fd25434ed9c8087836a970306a8a7de57f09b9
WuraolaS/Lesson3_HW
/lesson3.py
1,635
4.5
4
#This is Exercise 3.3.1 #inches->cm cm = 2.54 def inches_to_cm(inches): return cm * inches inc=2 print(inches_to_cm(inc)) #feet to inches #create a function that turns the an input which will be in feet to inches #ft = 12in inch = 12 def ft_to_inches(ft): return ft * inch feet = 5 print(f"{feet} feet is e...
47ebe7899a3b8f78cffb7cee4c7628b2c1281d5d
liuyi-CSU/learn-python
/xiaosi/day001/test004.py
408
3.734375
4
""" 题目描述 写出一个程序,接受一个十六进制的数值字符串,输出该数值的十进制字符串。(多组同时输入 ) 输入描述: 输入一个十六进制的数值字符串。 输出描述: 输出该数值的十进制字符串。 """ #!/usr/bin/env python3 # -*- coding: utf-8 -*- print("请输入一个十六进制的数值字符串:") inp = input() print(int(inp, 16))
84fb7f63fdcd064e697644b08ffa210453d259e3
coolsnake/JupyterNotebook
/new_algs/Number+theoretic+algorithms/Karatsuba+algorithm/compute_all_permutations_non_unique_chars.py
1,475
4.125
4
#!/usr/bin/python # Date: 2018-08-04 # # Description: # Write a method to compute all permutations of a string whose characters are # not necessarily unique. The list of permutations should not have duplicates. # # Approach: # Not much clear, refer 8.6 from CTCI. # # Complexity: # O(n * n!) import collections def co...
2799d173bfc5f9bb8fbc7a5e5edf4d05820c764a
shahud1/thaiwseg
/Backstage/Real_GUI.py
3,146
3.671875
4
from Main import * from tkinter import * class Application(Frame): """A GUI with app button""" def __init__(self,master): """ init the frame""" Frame.__init__(self,master) self.grid() self.create_widgets() def create_widgets(self): """Create button,text,and Entry wid...
4be1ebf388ae123a8b7d4e13908ba954e636e161
dshuhler/codility_lessons
/codility/4_counting_elements/frog_river_one.py
1,147
3.75
4
import unittest def solution(X, A): leaf_coverage = [False] * X frog_position = -1 # iterate over leaf coverage array for time, fallen_leaf_position in enumerate(A): leaf_coverage[fallen_leaf_position - 1] = True # move our frog across the river as far as we can # this will n...
fdc6af7d4537a23993174875c0c98b2346325ce3
rakshaharish/Basic-ML-Algorithms
/Find-S algorithm.py
945
3.625
4
import csv with open('lab1.csv','r') as f: read=csv.reader(f) data=[] print("given training example:") for row in read: print(row) if(row[-1]=="yes" or row[-1]=="Yes" or row[-1]=="YES"): data.append(row) print('---------------------------------') print("pos...
c9111ad908b4f0601b1233d9d53e61df9fc3305f
Lkik/test1
/test.py
152
3.6875
4
a = input() e = len(a) for i in range(e//2): if a[i] != a[-1-i]: print("не полиндром") quit() print("полиндром")
f83444e3f39b2047af2febdc31928c407c631ca0
H4rsh4/Edureka_Python-Course
/Day 2/Case Study 1/q2.py
478
4
4
''' Obj: Write a code which accepts a sequence of words as input and prints the words in a sequence after sorting them alphabetically. Assuming the input is structured as : "A C B F" ''' query = str(input('>')) #->The following statement SPLITs the given string with the given seperator(' ') and returns a list of s...
3bc341bf8ae8663c25a3fc39823532fcd4e29d33
gsakkas/seq2parse
/src/tests/parsing_test_24.py
332
3.5
4
def friendsOfFriends(d): for key1 in d: for key2 in d: if key1 == key2: continue else: d[key1].update(d[key1]- d[key2]) return d print(friendsOfFriends({"fred": set(["wilma", "betty", "barney", "bam-bam"]), "wilma": set(["fred", "betty", "...
c07df7ad59b9583ddb2d7280fe575fe6f9abf50b
SehwanJeon2/ssafy1219
/dict.py
4,565
3.765625
4
""" 파이썬 dictionary 활용 기초! """ # 1. 평균을 구하세요. iu_score = { "수학": 80, "국어": 90, "음악": 100 } # 답변 코드는 아래에 작성해주세요. print("=====Q1=====") score = 0 count = 0 for i in iu_score: score = score + iu_score[i] count = count+1 score=score/count print(score) #Teacher Answer #iu_score라고 하는 dic 변수에서 value 값만...
00d738445a95413d6429f074aa207264d862439b
robbiemccorkell/martianrobots
/position.py
1,062
3.578125
4
class Position: compass = ['N', 'E', 'S', 'W'] def __init__(self, xPos, yPos, bearing): self.xPos = int(xPos) self.yPos = int(yPos) self.bearingIndex = self.compass.index(bearing) def moveForward(self): if self.compass[self.bearingIndex] == 'N': self.translate([0,1]) elif self.compass[self.bearingInde...
07b22e3bd73ea659f07799c051faf0b03a7f5b0f
murali-kotakonda/PythonProgs
/PythonBasics1/basics/functions/Ex19.py
203
3.671875
4
""" How to access global variables inside the function """ city = "Hyd" def change(): global city # functn can acces global bvariable city city ="bangaore" print(city) change() print(city)
cd5078ba0097500c92c3dbf43c1a520774297e1e
rednikon/Python
/Raspberry-Pi/Blinking-LED/GPIO.py
303
3.578125
4
import RPi.GPIO as GPIO import time # Write a Raspberry Pi program that makes an LED on your breadboard blink on and off. while True: GPIO.setmode(GPIO.BOARD) GPIO.setup(11,GPIO.OUT) GPIO.output(11,True) time.sleep(2) GPIO.output(11,False) time.sleep(2) GPIO.cleanup()
649c2ba963372ab2810d8d9aed099abbf9c9ac45
pdubslax/hackerRankSolutions
/CTCI/ctci-bubble-sort.py
590
4.03125
4
def bubbleSort(numbers, values): totalSwaps = 0 for i in range(numbers): newSwaps = 0 for j in range(numbers-1): if values[j] > values[j+1]: values[j],values[j+1] = values[j+1],values[j] totalSwaps += 1 newSwaps += 1 if newSwaps...
89be93b937a6caa806f287c9c505e2ae26b4a50a
juanjoneri/Bazaar
/Interview/Quora/forming-teams-2.py
2,624
3.59375
4
# Find how many ways to arrange the students into teams, so that each team's skills summ up to a target value k from sys import stdin from collections import Counter from math import factorial def nck(n, k): # n choose k: arangements of k elements from a set of n return factorial(n) // (factorial(k) * factori...
997207fc08bbb3ab4c01550657111d4edf549c52
rahulkuriyedath/Sudoku
/sudoku_test.py
1,192
3.5625
4
import numpy as np grid = [[6,0,0,0,0,0,0,0,0], [0,0,1,0,0,0,4,6,0], [5,0,0,0,0,3,2,0,0], [0,0,0,0,8,0,0,0,0], [0,9,6,4,0,0,0,0,0], [2,0,4,0,1,0,5,0,3], [0,0,8,0,0,0,0,3,0], [0,0,3,2,4,0,0,1,0], [0,0,0,0,0,8,6,0,2]] def possible(x, y, n): for i in r...
ec4cb58bc367bbbe6634dc7fdecf0d08c4061ca4
Courage-GL/FileCode
/Python/month02/day03/exercise_2.py
683
4
4
""" 练习1: 基于单词本完成 编写一个函数,传入一个单词,返回单词对应的解释 提示: 每行一个单词 单词与解释之前有空格 单词按顺序排列 split() """ def find_word(word): file = open("dict.txt") # 读打开 # 查找单词 for line in file: # 提取单词和解释 tmp = line.split(' ',1) # 如果遍历到的单词已经比目标单词大,则结束查找 if tmp[0] > word: fi...
b6b48fe8680039b442ede1abc86b24dab47300a5
DominicSchiller/osmi-module-datascience
/assessment_03/cards/Shuffle.py
1,308
3.671875
4
import random from .Card import Card from .CardColor import CardColor from .CardValue import CardValue __author__ = 'Dominic Schiller' __email__ = 'dominic.schiller@th-brandenburg.de' __version__ = '1.0' __license__ = 'MIT' class Shuffle: """ Shuffle machine dedicated to generate and shuffle full card decks...
0642ec788c8725f2fcded420ebae54204b8c65c3
thiagofb84jp/python-exercises
/pythonBook/generalExercises/math/exercise10.py
600
4.09375
4
""" 10. Write a Python program to calculate the discriminant value. """ def discriminant(): xValue = float(input("The 'x' value: ")) yValue = float(input("The 'y' value: ")) zValue = float(input("The 'z' value: ")) discriminant = (yValue ** 2) - (4 * xValue * zValue) if discriminant > 0: ...
cb1984660be3e0c5b995706900f805cca4a7f306
bmoretz/Daily-Coding-Problem
/py/dcp/problems/stack_queue/n_stack.py
3,677
4.21875
4
""" Three in one. Use a single array to implement three stacks. """ '''Approach #1. This approach uses a single array with empty elements to offset each individual stacks elements inside the single backing array. pros: simple, easily extendable relatively efficient. cons: potentially lots of empty space unused. '''...
a35f3dee7a67f05055fe3b10a8dcebff79da83dc
timpark0807/self-taught-swe
/Algorithms/Leetcode/261 - Valid Graph Tree.py
1,513
3.6875
4
import unittest import collections class Solution(object): def validTree(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: bool """ adj_list = self.get_adj_list(edges) queue = [0] seen = set([0]) while queue: ...
593fd71af2c42f19d502ea8c54525aacb4fea966
mattlevan/Search_Control_Algorithms
/BreadthFirst.py
5,081
3.921875
4
''' BreadthFirst search is a program that finds optimal solutions to games (using the Game class) by iterating through all possible moves and comparing to both the game goal state and all previous states visited. ''' from EightPuzzle import EightPuzzle from MissionaryCannibal import MissionaryCannibal from SlidingT...
fec5f806a424dbb269144164cd465679d7279466
AnujRuhela7/Python-Tutorial
/Q4.py
418
3.984375
4
a = int(input(" Enter 1st Value (a) = ")) b = int(input(" Enter 2nd Value (b) = ")) Sum = a + b Difference = a - b Product = a * b Division = a / b F_Division = a//b Exponent = a ** b Remainder = a % b print("Sum = ",Sum) print("Diiference = ",Difference) print("Exponent = ",Exponent) print("Remainder = ",Remainder) pr...
667dc7ef2332360fefe9f216c5900fa32a54d018
zyyxydwl/Python-Learning
/file/nineth.py
330
3.5
4
#!/usr/bin/env python # -*- coding:utf-8 -*- #@Time :2017/10/25 22:49 #@Author :zhouyuyao #@File :nineth.py for i in range(10): if i>3: break print('a=' +str(i)) print('#' *20) i=0 for i in range(1,5): print(i) if i==3: print('hello world') continue print('i =...
564cae1515988951178d637a65ff6ef105801e0d
yehongyu/acode
/2019/binary_tree/binary_tree_preorder_traveersal_66.py
1,572
3.9375
4
#coding=utf-8 """ Definition of TreeNode: """ class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None class Solution: """ @param root: A Tree @return: Preorder in ArrayList which contains node values. """ def helper(self, root, res): i...
5ff84fc111adb506f3aa0dda6d5e368580031a4b
ldpeng/study-code
/Python/lambda.py
331
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Python对匿名函数的支持有限,只有一些简单的情况下可以使用匿名函数。 # 匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果。 print(list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])))
8595a02904cd0e3b6fa685ea239a6830ae0769ce
Raipagnin/Python.exercises
/ex05.py
404
4
4
# ex 5 - faca um programa que leia um numero inteiro, e mostre na tela o numero, o antecessor e o sucessor x = int(input('Digite um valor:')) a = x - 1 s = x + 1 print('Baseado no valor {}, seu antecessor eh {} e seu sucessor eh {}'.format(x, a, s)) # vc tb pode fazer tudo com apenas uma variavel e dentro do .format co...
be9cbef15cfeadac528d84cd07b8e4d7a8ed0fa5
nipuntalukdar/NipunTalukdarExamples
/python/misc/print_permute_recurse.py
551
3.625
4
from copy import copy def print_permute(input, lst, printed): if len(input) == 1: lst.append(input[0]) word = ''.join(lst) if word not in printed: printed.add(word) print(word) lst.pop() else: i = 0 while i < len(input): newinp...