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
7c4fe32f8c25b9a37526776842abef9664df53d2
danjchoi/CodingChallengePractice
/pathlib_reader.py
471
3.671875
4
# [-Imports:Python-] import pathlib import sys # [-Public-] def main(): """The main function.""" if len(sys.argv) < 2: raise RuntimeError("No input filename supplied") input_file_name = sys.argv[1] input_path = pathlib.Path(input_file_name) try: print(input_path.read_text()) ex...
7356ed3eec8bd68b38312d6d837569ae414acc3d
wade-sheedy/CP1404_2018_1
/week_02_files.py
317
3.765625
4
"""Week 02 files demo.""" file_in = open("text.txt") # text = file_in.read() # text = file_in.readlines() for line in file_in: name, age = line.strip().split() print("{} is {} years old".format(name, age)) file_in.close() file_out = open("results.txt", "w") print("Thanks.", file=file_out) file_out.close()
29756c35b19f126f7c7532fc4882c753c596b285
danong/ctci-6th-solutions
/pythonsolutions/arrays_and_strings/test/test_is_unique.py
535
3.546875
4
import unittest from ..is_unique import unique_characters, unique_characters_ds class Test(unittest.TestCase): def setUp(self): self.test_cases = [ ('aa', False), ('ab', True) ] def test_unique_characters(self): for a, expected_ans in self.test_cases: ...
12403938312318a2d4c18d0bb92f354d99e13d74
Varshitha2925/Codeforces-Solutions
/String Task.py
153
3.890625
4
def solve(str): return "".join("."+char.lower() for char in str if char.lower() not in "aeiouy") str = input() print(solve(str))
8e80b1006bc765ff53493073f34731554ff52c27
yuliaua1/algorithms
/RandomList_01.py
382
4.3125
4
# This is a simple program to generate a random list of integers as stated below import random def genList(s): randomList = [] for i in range(s): randomList.append(random.randint(1, 50)) return randomList print(genList(30)) #This is creating the list using list comprehensions #randomList = [ ra...
37aaf1fd82c0ded9d0578e8a971eb146463ba95f
testlikeachamp/codecademy
/codecademy/day_at_the_supermarket.py
1,874
4.125
4
# from collections import Counter prices = { "banana": 4, "apple": 2, "orange": 1.5, "pear": 3 } # Write your code below! def compute_bill(food): stock = { "banana": 6, "apple": 0, "orange": 32, "pear": 15 } assert isinstance(food, (list, tuple, set)), "{...
8cbd0ade9a0c4ccb948f10a884325ebe2d6374dd
testlikeachamp/codecademy
/codecademy/conditionals_and_control_flow.py
437
3.875
4
def greater_less_equal_5(answer): """ This function compares argument answer with number 5. :param answer: a number to be compared with 5 :return: int, 1 if answer > 5, -1 if answer < 5, 0 otherwise """ assert not isinstance(answer, (str, bool)) and answer is not None, "{} was not int or float"....
cd2c4be708fc8fd9bcdcf2848f4f57233a17d48e
tkshivaprasad/Python-ClassDemos
/NN_cancer.py
1,821
3.953125
4
import os import numpy as np import pandas as pd import matplotlib.pyplot as plt import sklearn.datasets from sklearn.datasets import load_breast_cancer cancer = load_breast_cancer() cancer.keys() # Print full description by running: # print(cancer['DESCR']) # 569 data points with 30 features cance...
fe1995757119ad56de6aff4561f8f0957d94eecb
bsnitzer/python-bible
/project-7-pig-latin.py
906
4.03125
4
# Python Bible # Brian Snitzer # July 25, 2019 # Turn regular words into pig latin # Get sentence from user original = input("Please provide a sentence: ").strip().lower() # Split sentence into words words = original.split() # Loop through words and convert to pig latin new_words = [] for word in words: if word[...
c530507cb6c87efa15643a55a93fcf204c3932a0
Alf0nso/NN-Games
/NN/neural_net.py
4,714
4.375
4
# Neural Network (MLP) # # @Author: Afonso Rafael & Renata # # Implementation of neural networks in python # to be used for learning board games. The # intention is to learn how something like this # can be written in a programing language import numpy as np # The use of the numpy library was to ease # the burden of ...
e07acdd312a8b3188acb9a89e1145027ec4109ed
MishaLaskin/rl-prep
/ml-coursework/cs231/assignment1/cs231n/classifiers/softmax.py
3,956
3.625
4
from builtins import range import numpy as np from random import shuffle from past.builtins import xrange def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. I...
6a11cd0704d373ae0318e5fa1158159b20680a53
LiangChen0323/DevOps-learning-notes
/Python/FileErrorHanding.py
571
3.828125
4
#!/usr/bin/env python3.8 import argparse parser = argparse.ArgumentParser(description="File Reader") parser.add_argument("file_name", help="the file to read") parser.add_argument("line_number", type=int, help="the line to print from the file") args = parser.parse_args() try: lines = open(arg...
20849ee4f75e876464e380437d45a5b0f8835f4d
shedaniel/python_3
/Lesson4.2.py
235
4.5
4
#Range #It is used for loops #it will run the loop form %start% to %stop% which each time added it by %plus% #range(start, stop) for x in range(1 , 6): print(x) #range(start, stop, plus) for x in range(100, 107, 3): print(x)
cdba6fc2ff40af463aba9786b2a41c44f12122e6
colinjhong/Alphadoku
/HW2 TEST (numbers).py
3,455
3.59375
4
import timeit ##reads csv file, returns a list of lists def get_board(csvfile): csvlist=[] fp=open(csvfile) for i in fp: csvlist.append(i.strip().split(',')) fp.close() return csvlist ##returns characters (not empty) present in given row def in_row(board,row,column): Row=[] for i i...
98af61117b66d6dd1578ee77642467c7e80424f5
lucianohdonato/aulas_python3_basico
/primeiro_igual_ultimo.py
407
3.96875
4
#!/usr/bin/python3 #-*- coding: UTF-8 -*- num = 0 prim_dig = 0 ult_dig = 0 num = int(input("digite número maior que 9 para testar: ")) ult_dig = num % 10 while num > 9: prim_dig = num // 10 num = prim_dig if prim_dig == ult_dig: print("o primeiro(", prim_dig,") e o últ. (", ult_dig, ") são iguais") else: ...
ec4d15e7b6370db7abc50a28096b2fc868504a9c
despo/learn_python_the_hard_way
/exercises/ex15.py
536
4.09375
4
# import mofule argv from system from sys import argv # assign the first argument to script and the second to filename script, filename = argv # open the file txt = open(filename) # print the filename print "Here's your file %r:" % filename # read and print the open file print txt.read() txt.close() print "I'll als...
838fe55c092043e1e18f9cc8b65be5cac2890f93
despo/learn_python_the_hard_way
/exercises/ex19.py
965
4.03125
4
# defining function that outputs information about cheese and boxes of crackers count def cheese_and_crackers(cheese_count, boxes_of_crackers): print "You have %d cheeses!" % cheese_count print "You have %d boxes of crackers!" % boxes_of_crackers print "Man that's enought for a party!" print "Get a blanket. \n"...
d290ec12c0ee323074bc1cea663bf2e4680bdf3f
ipashchenko/mllc
/mllc/utils.py
845
3.546875
4
# -*- coding: utf-8 -*- def precision(cm): """ Return precision. :param cm: Confusion matrix. :return: Value of precision. """ return float(cm[1, 1]) / (cm[1, 1] + cm[0, 1]) def recall(cm): """ Return recall. :param cm: Confusion matrix. :return: ...
3bce247b7072fc6a0cc46ab6982184189f3e7aac
gardenia-homsi/holbertonschool-python
/0x0C-python-input_output/2-read_lines.py
367
3.609375
4
#!/usr/bin/python3 """read based on nb lines""" def read_lines(filename="", nb_lines=0): """ Read the file acording to number of required lines """ a = 0 with open(filename, encoding="utf-8") as reader: for line in reader: print(line, end="") if a == (nb_lines - 1...
b39e6330741e27d3b31cc0e1cfb2ac0234cdd8b6
gardenia-homsi/holbertonschool-python
/0x0F-python-network_0/6-peak.py
657
3.90625
4
#!/usr/bin/python3 """ Find a peak in a list of unsorted integers. """ def find_peak(list_of_integers): """Find a peak in a list of unsorted integers.""" if len(list_of_integers) == 0: return None elif len(list_of_integers) == 1: return list_of_integers[0] h = len(list_of_integers...
e19d3ae4edcb015dca72d04d906332bc8e7ba3bc
gardenia-homsi/holbertonschool-python
/0x1D-primegame/0-prime_game.py
852
3.671875
4
#!/usr/bin/python3 """ Module for isWinner. """ def isWinner(x, nums): """ Prime numbers game. """ if x < 0 or nums[-1] < 1: return None Maria_score = 0 Ben_score = 0 prime = [False] * 100001 primes = [] for i in range(2, 100001): if not prime[i]: primes.append...
1fa3e2153aaade9fe3259f74a5e97fc62d881ec3
gardenia-homsi/holbertonschool-python
/0x0C-python-input_output/1-number_of_lines.py
251
3.75
4
#!/usr/bin/python3 """count line number""" def number_of_lines(filename=""): """return line number of file""" count = 0 with open(filename, "r") as reader: for line in (reader): count += 1 return count
d100871a9b6de884309e938e5462e914e3c77c9b
gardenia-homsi/holbertonschool-python
/0x0B-python-inheritance/2-is_same_class.py
228
3.515625
4
#!/usr/bin/python3 """Module 2-is_same_class.py""" def is_same_class(obj, a_class): """check if obj is a_class""" if type(obj).__name__ == a_class.__name__: return True else: return False
c8fb7efd78479488374ba2a8c881a24d4ffd42a1
arcofdescent/code_snippets
/python/sock_merchant.py
494
3.5625
4
#!/usr/bin/python3 import sys import logging def sockMerchant(n, ar): # Complete this function num_pairs = 0 while len(ar) > 0: s = ar.pop(0) print(s) try: idx = ar.index(s) print(idx) ar.pop(idx) num_pairs = num_pairs + 1 e...
3fcac156bfc660d70a7582c6aec8fceb61388ae7
Tscott7/TicTacTournament
/backend/FullBoard.py
11,083
3.53125
4
''' Cinnamon Fresh Tic-Tac-Tournament FullBoard.py ----------------------------------------------------------------------- The class that stores and handles information for an instance of Ultimate Tic-Tac-Toe. ----------------------------------------------------------------------- Sources: 1. htt...
18c656d4e69e8c6ee881c0c9a4bd9af8908196c9
GlenboLake/DailyProgrammer
/C204E_remembering_your_lines.py
2,868
4.21875
4
''' I didn't always want to be a computer programmer, you know. I used to have dreams, dreams of standing on the world stage, being one of the great actors of my generation! Alas, my acting career was brief, lasting exactly as long as one high-school production of Macbeth. I played old King Duncan, who gets brutally mu...
1676f3e1da1c48b4623acc6a7abacf03fc85ea5b
GlenboLake/DailyProgrammer
/C214I_pile_of_paper.py
4,104
3.65625
4
''' Have you ever layered colored sticky notes in interesting patterns in order to make pictures? You can create surprisingly complex pictures you can make out of square/rectangular pieces of paper. An interesting question about these pictures, though, is: what area of each color is actually showing? We will simulate t...
4b0d6ec6077ef791f4c63c88fa96813f30a12a22
GlenboLake/DailyProgrammer
/C225I_maze_rotation.py
1,355
3.765625
4
def print_rotated_maze(maze): # Assume that all cells intersections do have a +. cell_size = maze[0].find('+', 1) # Get the maze size, then get the "true" size. E.g.: # "+--+--+--+" doesn't get printed count as a row # "| | |" does. Likewise for columns. h = len(maze) h = int(h - (h + ...
a93db487ca0a5a453edf6fe2375a2be25951553d
GlenboLake/DailyProgrammer
/C206E_recurrence_relations_1.py
451
3.75
4
from functools import reduce def recur(init, relation): steps = relation.split() return reduce(lambda x, step: eval(str(x)+str(step)), steps, init) def print_recurrence(init, relation, times): print('Term 0:', init) for i in range(times): init = recur(init, relation) print('Term {}: {}'...
149deeb16c3ba356cb6eb5b6f8fd041564574472
GlenboLake/DailyProgrammer
/C223H_heighway.py
728
3.625
4
def heighway_sequence(degree): if degree == 1: return 'L' else: first = heighway_sequence(degree - 1) second = ''.join(['L' if turn == 'R' else 'R' for turn in first[::-1]]) return first + 'L' + second def heighway(degree): directions = [(1,0), (0,1), (-1,0),(0,-1)] d = ...
551c0178761363fea032e5d5447c07c789f19387
GlenboLake/DailyProgrammer
/C266_graphs.py
1,734
3.796875
4
import networkx # Easy: Get the degrees of nodes and print adjacency matrix def undirected_graph_from_file(filename): with open(filename) as f: node_count = int(f.readline()) graph = networkx.Graph() graph.add_nodes_from(range(1, node_count + 1)) graph.add_edges_from(list(map(int, ...
b38474adb255b279df977012d87a95ba6ee9dcf1
rodrigorezender/udacity_project3_bikeshare
/bikeshare.py
8,483
4.15625
4
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york': 'new_york_city.csv', 'washington': 'washington.csv' } def yes_or_no(phrase): """ Asks user to choose yes or no. Returns: (str) choice - yes or no """ while Tr...
478fe9864b7278fe0d13218866f3c1b114939baf
SmartPracticeschool/SBSPS-Challenge-1090-Predicting-the-energy-output-of-wind-turbine-based-on-weather-condition
/App/Server/ChartData.py
597
3.65625
4
# This Function formating the data to plot in Line Chart ... def get_LineChartData(date_time,actualPower): lineChartData = [] for i,j in zip(date_time,actualPower): lineChartData.append(list((i,j))) return lineChartData # This Function formating the data to plot in Bar Chart ... def get_BarChart...
7ce77a82988036e276a2bc04cbec648055e0958a
renokan/study_python
/Sqlite/utils.py
944
3.640625
4
"""Utilits for sqlite3.""" import sqlite3 def init_db(path_to_db, schema_db): try: connection = sqlite3.connect(path_to_db) connection.executescript(schema_db) except sqlite3.DatabaseError as err: return str(err) else: return True def create_connection(path_to_db): r...
c22699f6448d98710025d1c34d71545b50e2cc32
Pablito2020/graph-playground
/algorithms/BFS.py
956
3.75
4
from structure.Graph import Graph from structure.Tree import Tree from structure.Pairs import Pairs def bfs(graph: Graph, value): array = __bfs_helper(graph, value) tree = Tree(array.pop(0).first.value) for i in array: actual = tree.get_tree(i.second.value) actual.add_descendant(Tree(i.fir...
0c8a859ff6e5180b523210d4d5d5a7a1589e5942
uma2828/interview-prep-notes
/python-programs.py.py
29,232
4.09375
4
#swap code x, y = 10, 20 print (x, y) x, y = y, x print (x, y) #increment x = 10 x += 1 print(x) ## prints 11 #decrement x = 10 x -= 1 print(x) #type conversion >>> float(42) # convert 42 to float 42.0 >>> >>> float("3.4") # convert "3.4" to float 3.4 >>> str() function # ...
96a979013f6999c4c6eaa9c6dc584fb9395d16a8
Aman-Mittal/AmanSTPython
/Day 9/9D.py
401
3.796875
4
class Animal: def __init__(self,name,color): self.name=name self.color=color class Cat(Animal): def mew(self): print("Cat meows") class Dog(Animal): def bark(self): print("woof") if __name__=="__main __": pet1=Dog('tomy','brown') pet2=Cat('Lucy','White')...
dadd810c1df1cbad20652b2040d432e4f0cbd5d6
Aman-Mittal/AmanSTPython
/day 16/16I.py
180
3.65625
4
import numpy as np import matplotlib.pyplot as plt X=np.array([1,2,3,4,5,6,7,8,9,10]) print(X) Y=np.array([5,6,3,5,34,5,6,2,45,55]) print(Y) plt.plot(X,Y) plt.show()
b72d34a4f96e0160faa08bbe19544e5f4fc9fafd
Aman-Mittal/AmanSTPython
/Day 8/8J.py
453
3.984375
4
#program to perform differen set operations like in mathematics #define three sets E={0,2,4,6,8} N={1,2,3,4,5} #set union print("Union of E and N",E|N) #set intersection print("Intersection of E and N",E&N) #set difference print("Difference of E and N is",E-N) print("Difference of N and E is",N-E) #s...
de3b978fc263b1a92c5ad5f3dc988c62dc371a24
Aman-Mittal/AmanSTPython
/Assignments python/hw1.py
396
4
4
#1)make a simple game with random module #Soln: import random maxn = 10 n = random.randint(1, maxn) print('Welcome to guess the number game!') print('Guess the number from 1 to %d' % maxn) guess = None while guess != n: guess = int(input('Your try: ')) if guess > n: print('Too high') if ...
3972fa026aa7a3332973cda18b8ebc6e563eabf8
ronimizy/ITMO
/1_sem/AlgorithmsAndStructures/1/D.py
1,175
3.96875
4
def merge(leftList, rightList): leftLength = len(leftList) rightLength = len(rightList) left = 0 right = 0 array = [] for _ in range(leftLength + rightLength): if left < leftLength and right < rightLength: if leftList[left] <= rightList[right]: ...
926db9a862264dfa6eb5eca8df372526413d656e
deivshan98/Academic_Projects
/DeivanayagamShanmugasundaram _173001650_ Lab _ 3.py
8,677
4.0625
4
#!/usr/bin/env python # coding: utf-8 # # Econometric 322 Lab \#3 # ## <font color = blue> Assignment </font> # # Collect data on the following: # # - Physicians and nurses by state # # Use the reference in Lesson 3. # # <font color = red> Documentation </font> # ## <font color = blue> Abstract </font> # The pu...
26d5df3fd92ed228fb3b46e32b1372a0eb5e9664
UIHackyHour/AutomateTheBoringSweigart
/07-pattern-matching-with-regular-expressions/dateDetection.py
2,902
4.46875
4
#! python3 # Write a regular expression that can detect dates in the DD/MM/YYYY format. ## Assume that the days range from 01 to 31, the months range from 01 to 12, and the years range ## from 1000 to 2999. Note that if the day or month is a single digit, it’ll have a leading zero. # The regular expression doesn’t ...
b70e265f97eb9bd86d39cf4ca8e65c880ca88b72
UIHackyHour/AutomateTheBoringSweigart
/04-lists/characterPictureGrid.py
1,544
4.03125
4
# Write code that uses it to print the image. # ..OO.OO.. # .OOOOOOO. # .OOOOOOO. # ..OOOOO.. # ...OOO... # ....O.... # From the provide grid variable # Hint: You will need to use a loop in a loop in order to print grid[0][0], ## then grid[1][0], then grid[2][0], and so on, up to grid[8][0]. # This will finish the ...
4e223ae7c5e4972616ce2b327b6a294cd06b9a36
codeJRV/CS_Concepts
/AlgorithmsPractice/Python Basics/DFS.py
536
3.875
4
from collections import defaultdict class Graph: def __init__(self): self.graph = defaultdict(list) def addEdge(self, u, v): self.graph[u].append(v) def DFS(self,start): path = [] stack = [start] while stack != []: v = stack.pop() if v not in path: path.append(v) print v for w in reve...
bc5bf3d849b596d4209631d8b18bc99797eef164
PureMath86/uber-bot-challenges
/question3.py
4,045
4.40625
4
""" This time you are an Uber driver and you are trying your best to park your car in a parking lot. Your car has length carDimensions[0] and width carDimensions[1]. You have already picked your lucky spot (rectangle of the same size as the car with upper left corner at (luckySpot[0], luckySpot[1])) and bottom right c...
591f863b5dcfc432a975e5837451fc40ec1ad0b3
JunMuko/assignments
/superheroepowers.py
596
3.71875
4
# load libraries import json # read superhero.json with open('superheroes.json', 'r') as f: superheroes = json.load(f) #print(superheroes) allpowers = [] # get the members members = superheroes['members'] #print(members) # loop through each members for member in members: # for each member, get a list of...
129075ca982e85ee62ddef46af2c365159d8d641
BBernYY/GalgjeGame
/frontend.py
485
3.546875
4
# lives is een int met amount levens, letters_wrong is een list met alle verkeerde letters, en word is iets zoals a__le # probeer een in een prompt zo goed mogelijk deze variabelen te zien def func(lives, letters_wrong, word): # code string = "" for i in list(word): string += i+" " print(string)...
a04ba451e47eff6859d3c0d9744cec020dcabb82
hotpro/python10minutes
/syntax.py
219
3.8125
4
s1 = "Hello" s2 = " World." print s1 + s2 print s1 print s2 print "swap in one line" s1, s2 = s2, s1 print s1 + s2 print s1 print s2 """ Output Hello World. Hello World. swap in one line World.Hello World. Hello """
feac8387e6a3ef022f18afedeb695ad0b530aea6
pengpsw/python
/classTest.py
1,252
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- std1 = { 'name': 'Michael', 'score': 98 } std2 = { 'name': 'Bob', 'score': 81 } def print_score(std): print('%s,%s' % (std['name'],std['score'])) print_score(std1) print_score(std2) class Student(object): def __init__(self,name,score): self.__name=name ...
005aa49183d337f086a232526275ddf303b12697
Rivide/learnproject
/learn/lib/utils.py
232
3.5625
4
def formatPath(string): """Formats a string for integration into a url path""" return string.replace(' ', '_') def pathToString(string): """Formats a path to a user-friendly string""" return string.replace('_', ' ')
a7022d4acdad24db3974f4624ebec2abf1023394
nictrak/MappingICP
/occupancy_grid.py
3,617
3.828125
4
import math import numpy as np from functools import reduce IDENTITY = np.array([[1, 0], [0, 1]]) def raw_to_point(raw): # define meaning of raw data deg = raw[1] distance = raw[2] # deg to rad rad = deg * math.pi / 180 # calculate point x = distance * math.cos(rad) ...
f2e6e18aba8f90f4cb04c3d7ef99530e08a925d3
cxclark/hive_ml
/hive_ml/layers/flatten.py
1,472
3.640625
4
import numpy as np class Flatten: """ Implements flattening of convolution volumes before passing to dense layers. """ def __init__(self): self.cache = {} def forward(self, Z): """ Flattens volumes. Arguments: Z -- input, numpy 4D array of shape (batch_s...
f7dcf6d3295a8eafa2ab6d26d8465581c0ce71a5
zsd58697/test2
/day_05.py
2,197
3.859375
4
# _*_ conding:utf8- ''' 1. class sushu: def __init__(self): self.a=eval(raw_input("enter a number :")) def fuc(self): for i in range (2,self.a): if (self.a%i)==0: print("{} bu shi su shu".format(self.a)) break else: print("{} shi su...
0bb1d24ab9cdb2c0111f89fec94725f53b4d2a4b
devashish89/FirstOccurence_ModifiedBinarySearch
/main.py
627
3.625
4
# first occurrence of element using Modified Binary Tree # Assumption and Pre-condition that list is sorted def get_firstOccurrence(l,x): left = 0 right = len(l) -1 while left <= right: mid = (left + right)//2 if x > l[mid]: left = mid + 1 elif x < l[mid]: rig...
cb4a1c3bc08d5b0c28c3bcb62a900b2c7cc344ef
zhs2326/leetcode
/leetcode_78.py
650
3.984375
4
#We can solve this problem recursively. #Namely, for a list nums with elements nums[0: len(nums)] #we can first find the subsets of nums[0: len(nums)-1], we call it res #then the subsets of nums is res+[temp+[nums[-1]] for temp in res] #and the base case is when the list becomes empty #then the subset of an empty list ...
926cabf74fae6de0a8dc33f6be5ba6ddf028679a
zhs2326/leetcode
/leetcode_470.py
1,013
3.703125
4
#Interestring question! #The solution to such kind of questions is summarized as below: #(1) if we want to realize randX with randY, where Y > X. # In such cases, it's very simple. # while True: # rand_num = randY() # if rand_num <= X: # return rand_num #(2) if we want to realize randX wit...
cc8944d560658e92d313938b47b9840f9b2f9f15
zhs2326/leetcode
/leetcode_222.py
2,273
4.09375
4
''' The easiest way is to iterate over all the nodes in the tree. However, we need to take care that the tree is a complete one. Therefore, except the last level, we can calculate the number of nodes in each level easily. suppose we have a complete tree with depth = d, then the number of nodes except the last level i...
2ae753b005db84a9660deb1ef71b3ff7c321da83
DoulingHuang/Spark
/spark_sql/dataframe_from_json_files.py
974
3.640625
4
from pyspark.sql import SparkSession if __name__ == "__main__": # Create SparkSession spark = SparkSession \ .builder \ .getOrCreate() # Create a DataFrame from a JSON file stocks_df = spark.read.json("hdfs://devenv/user/spark/spark_sql_101/data/stocks.json", schema="adj_close float, c...
8dd900a77f8b63874ff1c7dc2e10a00bf8846847
Igor7086/Less4
/Less4_4_1.py
134
3.8125
4
""" 1) Создайте список 2 в степени N, где N от 0 до 20 """ sp = [2 ** n for n in range(20)] print(sp)
0c2ce0c9978ffea806f874d0540beeadf2477708
Igor7086/Less4
/Less4_5_2.py
141
3.90625
4
# B. both_ends def both_ends(s): if len(s)>2: return s[:2] + s[-2:] else: return "_" print(both_ends('qwerty'))
35ed854c98cf0f36118c9384135127f3fe2a7a2e
DavidDeLille/writeups
/bctf_2015/weak_enc/test_code.py
1,318
3.578125
4
def updateDict(s, lzwDict): if not s in lzwDict: count = len(lzwDict.keys()) lzwDict[s] = count % 256 def print_dict(my_dict): i = my_dict.items() print "lzwDict=", sorted(i, key=(lambda (s,d) : d)) def LZW(s, lzwDict): # LZW written by NEWBIE for c in s: updateDict(c, lzwDict) # p...
cf2e82f76396039145cb29dc6937d43fb36b81c8
DavidDeLille/writeups
/picoctf_2014/steves_list/create_wordlist.py
310
3.546875
4
import itertools upper = "ABCDEFGHJIKLMNOPQRSTUVWXYZ" lower = "abcdefghijklmnopqrstuvwxyz" digits = "0123456789" specials = "_!?@.s" suffix = "b:1;" alphabet = lower with open("mywordlist", 'w') as f: for x in itertools.combinations_with_replacement(alphabet,8): f.write(''.join(x)+suffix+'\n')
ef9488e83336a1a6fb7473b5fd43975681f1703a
tung2389/picoCTF
/picoGym/Transformation/solve.py
304
3.5
4
#! /usr/bin/env python3 import sys line = sys.stdin.readlines()[0] flag = "" for char in line: for code in range(0, 127): if ord(char) - (code << 8) <= 126 and ord(char) - (code << 8) > 0: flag = flag + chr(code) + chr(ord(char) - (code << 8)) break print(flag)
5a7e4c5764de5aebd0d4a5fe0349c04f6cdc57b6
hlynurstef/Snake
/snake.py
2,956
3.59375
4
import pygame from block import Block class Snake(): """A class representing the snake.""" def __init__(self, screen, settings): """Initialize the snake.""" self.screen = screen self.settings = settings self.tail = [] self.initialize_snake() self.scale = setting...
f0789ab224d0138ae3a051bf64885694a6cd6ecc
ISISComputingGroup/EPICS-DeviceEmulator
/lewis_emulators/volumetric_rig/pressure_sensor.py
743
3.546875
4
from .sensor import Sensor from .sensor_status import SensorStatus class PressureSensor(Sensor): """ A sensor that reads the pressure. """ def __init__(self): super(PressureSensor, self).__init__() def set_value(self, v, target): """ Updates the pressure reading with a ne...
8b51fe1339c6d273bb13161110b300552c52fb33
zachradtka/ProjectEuler
/Problem_9/prob9.py
869
4.09375
4
import math import sys def is_triplet(a,b,c): if a**2 + b**2 != c**2: return False if a>=b or a>=c or b>=c: return False return True def generate_triplet(c=5): while True: # divisors = generate_divisors(c**2) # num_divisors = len(divisors) # Ensure there are m...
b8b5cbc9085bc9e99479313d3179e1e48985ecd8
zachradtka/ProjectEuler
/Problem_6/prob6.py
387
3.9375
4
def sum_of_squares(num): sum = 0 for i in range(1, num+1): sum += i**2 return sum def square_of_sums(num): sum = 0 for i in range(1, num+1): sum+=i return sum**2 def main(): num = 100 # difference print('square of sums minus sum of squares: %d' % (square_of_sums(n...
bd15d94a02e5f964d439a9f92d2e2c2ad1cabbba
zachradtka/ProjectEuler
/Problem_14/prob14.py
695
3.734375
4
import sys def generate_collatz(start): if start > 1: if start%2 == 0: result = start/2 yield result else: result = 3*start + 1 yield result for val in generate_collatz(result): yield val def main(): end = long(sys.argv[...
0da3ccdd96592a005d2e12c4829ed4700955b2d0
icoder18/Python-Games
/hangman.py
3,073
3.96875
4
import random def hangman(): words=['dog','cat','monkey','lion','tiger','panda','elephant','giraffe'] validLetters='qwertyuioplkjhgfdsazxcvbnm' word=random.choice(words) turns=10 guess='' while len(word)>0: main="" #missed=0 for letter in word: if letter i...
fa7d795bd0ed996e9a100f808b6ad58662435e77
RunnerMom/VirtEnv
/hackbright_app.py
7,109
3.625
4
import sqlite3 DB = None CONN = None ######### Queries######## def get_student_by_github(github): try: query = """SELECT first_name, last_name, github FROM Students WHERE github = ?""" DB.execute(query, (github,)) row = DB.fetchone() # print "Github should be: %r" % github r...
66d6d8e95d5c3a7949e60a30f2e870f346d8eac4
acay08/nguyenminhque-labs-c4e16
/Labs03/homework/1_turtle.py
309
3.9375
4
from turtle import * shape('turtle') speed(-1) color('purple') def write_words(times, text): j = -50 for i in range(times): write(text, font=("Arial", 20, "normal")) penup() goto(0,j) pendown() ht() j += -50 write_words(3, "Hello World") mainloop()
9d7f94d9fe855bc9305eb308710027fb9973229d
acay08/nguyenminhque-labs-c4e16
/Labs03/fmtha.py
117
3.53125
4
# from eval import calc # # res = calc(3, 3, '+') # print(res) import eval res = eval.calc(3, 3, '+') print(res) #
b66c516343428f75e1c4c7ff936c5532d4ee35f5
dashabinash/PythonDataScience
/numpy.py
7,036
4.1875
4
# -*- coding: utf-8 -*- """ Created on Sat Jul 28 15:53:09 2018 @author: Abinash Dash """ #This tutorial demonstrates about the knowledge on Python #Numpy is a Linear Algebra Library for Python, the reason it is so important for Data Science with Python #is that almost all of the libraries in the PyData EcoSys...
8fb4a26f61dd788c326bc0000f000cb3371fb872
souravBhandari/python-Exceptions
/error.py
521
3.78125
4
'''c=a+b,syntax errors if b is not defined , they are traced in developement phase 1 syntax errors 2 logical errors,finded in test cases,extensive debugging 3 run time errors(exception) ,occurs in execution time,exception is thrown and program is terminated syntax: try: statement(s) except: statement(s) f...
3c23ca55a8d0d4fa8bdfccc890db7fb8c260c06a
geyixin/LeetCodeExercising
/0404 Sum of Left Leaves/Sum of Left Leaves.py
2,035
4.09375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- #####################-------------------####################### ''' 注意看两个LeftList()的定义和使用的差别 第三个是提交成功显示的速度最快的代码。 ''' #####################------------- ----####################### # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # ...
1881a4e8730c51f5570c06d21dbcf5479202d1fe
geyixin/LeetCodeExercising
/0001 Twosum/twosum.py
1,472
3.75
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ########################------------------------################### ''' 第一个是我自己做的,慢如蜗牛,80ms; 第二个是提交成功看到的最快的,36ms。 --不想说话,贴出来对比 感觉脸很疼!!! ''' ########################------------------------################### class Solution: def twoSum(self, nums, target):...
d135752e9786df5e16bc5641ad8a57032fb817a1
Raavada/nenene
/quiz.py
1,791
3.921875
4
import logging import unittest import sys def print2largest(arr): try: logging.info("print2largest!") setFlag = True arr_size = len(arr) # There should be atleast # two elements if (arr_size < 2): #print(" Invalid Input ") logging.info("List i...
cbf278ee52411875a9fbeb263afc4074fb2f88c0
Link-kkkkk/python-wheel
/starter/oop2.py
1,203
4.0625
4
#!/usr/bin/python #coding:utf-8 class Animal(object): def run(self): print 'A animal is running...' # 继承Animal class Dog(Animal): def __init__(self, *name): self.name = name def run(self): print('Dog is running...') class Cat(Animal): def run(self): print('Cat is run...
b1d104ce38178e791b30fdc30062770dfdff9c14
Link-kkkkk/python-wheel
/starter/oop3.py
1,327
3.9375
4
#!/usr/bin/python #coding:utf-8 class Men(object): # 特殊变量,只允许设置name和age这两个属性 # __slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的 __slots__ = ('name', 'age') def set_name(self, name): self.name = name # 绑定一个方法 Men.set_name = set_name s = Men() s.set_name('Lily') s2 = Men() s2.set_name('Saber') class Student(ob...
24e238601bfe282712b8fbea574a98114ecf9b99
omarBnZaky/python-data-structures
/check_palanced_parenthece.py
1,231
4.3125
4
""" Use a stack to check whether or not a string has balanced usage of parnthesis. """ from stack import Stack def is_match(p1,p2): print("math func:" + str((p1,p2))) if p1 == '(' and p2 == ')': print("match") return True elif p1 == '{' and p2 == '}': print("match") return...
174e92e63cc13b3d6d8d69a6654928433d54ba30
stubird/micStudy
/leetcode/nextGreatestLetter.py
1,857
3.5
4
""" Copyright 2018 (c) Jinxin Xie Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in...
bd3ab04d1aaa6bac16dc8b8963e0db235dc47e06
TinFe/sorting_algos
/Merge Sort.py
2,968
3.671875
4
#convert input list into a list of lists of 2 numbers (with one list of one number if input contains an odd number of items) to be sorted later. def initial_divide(lst): #set an index variable to 0 z = 0 #create empty output list out = [] #traverse the input list while z < len(lst) - 1: ...
dacd4f6e242c40d72e9f5a664828d26c576d457d
Katt44/dragon_realm_game
/dragon_realm_game.py
1,195
4.1875
4
import random import time # having the user pick between to caves, that randomly are friendly or dangerous # printing text out slowly for suspense in checking the cave # asking user if they want to play again def display_intro(): print ('''Standing at the mouth of a cave you take one long inhale and you exhale as...
e0f5ab8ec1f69e085823c5450fb6595b45228d48
dj38/MLtraining
/hello.py
1,201
3.78125
4
# import d'un module avec un alias #import math as m # danger : a n'utiliser que sur les petits codes si je redefinis la fonction tanh son fonctionnement est change from math import tanh # essais lies au slides Yield # generateur = (x*x for x in range(3)) # for i in generateur : # print(i) # # lst = [x*x for x in...
9cea2b8c8abb1262791201e1d03b12e2684673ea
gsandoval49/stp
/ch5_lists_append_index_popmethod.py
712
4.25
4
fruit = ["Apple", "Pear", "Orange"] fruit.append("Banana") fruit.append("Tangerine") #the append will always store the new at the end of the list print(fruit) #lists are not limited to storing strings # they can store any data type random = [] random.append(True) random.append(100) random.append(1.0) random.appe...
063cd95fee751c664b3a01c6dab8c0d790ab5743
GaborIreHun/Stage-Name
/stage_name.py
7,068
4.3125
4
# -*- coding: utf-8 -*- """ @author: GaborIreHun Project Title: Gangster Stage Name. """ # I chose to start with a While loop as I needed to run the first part of the code an undefined time. validAnswer = False while not validAnswer: try: # I asked for the first input to determinate...
0c06319cc988a47e821da5dd64f7f2e17c14e5d8
wouldhee/DNA-String-Sequencing-Assignment
/a2.py
40,375
3.828125
4
"""CSCA08 Assignment 2, Fall 2017 I hereby agree that the work contained herein is solely my work and that I have not received any external help from my peers, nor have I used any resources not directly supplied by the course in order to complete this assignment. I have not looked at anyone else's solution, and no ...
e874c4c743db5099f20b9626adca4baff4ce23af
Riley-Robinson/Intro-Python-I
/hello.py
177
4.03125
4
# print('Hello world') name = 'Sean' # print('Hello' + name) # print(f'Hello {name}'') if name != 'sean': print('who you be willis') else: print(f'hello {name}')
6193b28beb17da2ab64a19e51f93e9fca6f2c4d1
tanyatrell/Lesson1
/task_functions2.py
1,132
3.890625
4
'''Задание 2 Создайте в Sublime файл answers.py Создайте функцию get_answer(), которая принимает аргумент question (строку, полученную от пользователя, например "привет") и словарь answers описывающий типичный диалог: {"привет": "И тебе привет!", "как дела": "Лучше всех", "пока": "Увидимся"} Сделайте, чтобы функция во...
d1d5d3c83ce67b854bfe02dbf267144ed08d1cf8
emiliechhean/Checkers_MC
/src/player.py
4,339
3.75
4
import random class Player: """ class """ def __init__(self, symb='x'): if symb != 'x' and symb != 'o': raise Exception("wrong symbol, try 'x' or 'o' ") self.symb = symb self.pawns = [] self.checkers = [] #init pos combi ici def __str__(self): ...
3133d80a387e5feaf613d1a9ba0464be02537196
ofmkms/Kingdom-Tower-Defense-Game
/kingdoms/kingdom.py
1,955
3.625
4
import pygame import os from menu.menu import Menu, Button class Kingdom: """ Abstract class for towers """ def __init__(self): self.x = 0 self.y = 0 self.img = None self.selected = False self.width = 40 self.height = 59 self.range = 36 s...
782d67c70b45c769152bea3d4ebad0fe6925a2fe
Vrndavana/cs-module-project-recursive-sorting
/src/sorting/sorting.py
881
4.09375
4
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge(arrA, arrB): elements = len(arrA) + len(arrB) merged_arr = [0] * elements j, k = 0, 0 for i in range(len(merged_arr)): if k > len(arrB) - 1: merged_arr[i] = arrA[j] j += 1 elif j > len(...
931bfe3cb959c64fac8e5446e5913f3089730010
maziar0andriy/main_academy-1
/lab_1.4/prime1.py
174
3.90625
4
def prime(a): if a == 2: return True if a < 2 or a % 2 == 0: return False return not any(a % x == 0 for x in range(3, int(a**0.5) + 1, 2)) print(prime(int(input())))
69959faa7efe56b4515cd56d3481e26a202f42f9
qwlake/study-algorithm
/Python/programmers/l42583.py
560
3.65625
4
# -*- coding: utf-8 -*- def solution(bridge_length, weight, truck_weights): answer, truck, on = 0, 0, 0 que = [0 for _ in range(bridge_length)] while len(que) != 0: poll = que.pop(0) on -= poll if truck < len(truck_weights) and on+truck_weights[truck] <= weight: que.appe...
a8326b39eff1146c30bf33ebc538480bca29251c
qwlake/study-algorithm
/Python/참고자료/quick_sort.py
1,435
3.78125
4
class Solution: def test(self): a = [1, 4, 2, 5, 2, 3, 5] self.sorted(a) print(a) def sorted(self, arr, key=None): self.quickSort(arr, 0, len(arr) - 1) def quickSort(self, arr, i, j): if i >= j: return middle = j // 2 self.swap(arr, i, m...
4289c77d566f20827509c6268ecb98c6890cc4ec
qwlake/study-algorithm
/Python/baekjoon/n9663/n9663.py
1,264
3.65625
4
# -*- coding: utf-8 -*- import array def loop(row, col, queens): # for (int i = 0; i < number; i++) { for (int j = 0; j < number; j++) { # System.out.print(pan[i][j]); } System.out.println(); } System.out.println(); if queens == N: global count count += 1 return elif row < N: ...
767d5ecb0a104522d807570b96a79474b9cc926e
syedsaadahmed/HackerRank-Problem-Solutions
/Python/playing_with_csv.py
3,272
4.15625
4
#!/usr/bin/python ################################################################# #OBJECTIVE OF THE TASK # Your program will read this data file and perform the following jobs: # (1) Read all the data from file and save it into a Python dictionary. # Each key in the dictionary should be a country name as read fr...
bede31d22fb7958c0a421df6a0daff4b4c38cc51
jacoblbuchanan/Compound-Interest-Calculator
/Compound_Interest_Calculator.py
240
3.734375
4
startValue = float(raw_input("What is the present value? ")) Rate = float(raw_input("Interest Rate? (x.x%) ")) / 100 Years = float(raw_input("How many years? ")) endValue = startValue*(1+Rate)**(Years) print "$" + str(int(endValue))
2ef90fd11ebe4028603c78c05d94ea996f697d46
coryjamesfisher/Udacity-FSWD-Movie-Site-Project
/src/media.py
999
4.03125
4
""" This module contains datastructures surrounding media objects. """ class Movie(object): """Class representing a movie in the application See the constructor for public property information. """ __module__ = "media" __name__ = "Movie" def __init__(self, movie_title, movie_storyline, ...