blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
55b85abe021098cc1b7825729eb3c8d9d92f8b4b
FishoGithub/Five_Question_Quiz
/main.py
3,167
3.8125
4
#colors green = "\033[0;32m" red = "\033[0;31m" yellow = "\033[0;33m" blue = "\033[0;34m" magenta = "\033[0;35m" cyan = "\033[0;36m" white = "\033[0;37m" bright_cyan = "\033[0;96m" bright_blue = "\033[0;94m" name = "Mihir" score = 0 answer = "" def zero(): print(white + "nothing") def one(): print(white + "hotdo...
919234365969a9eeb5ff5a6cd645b2f3734107cc
py1-10-2017/nathan-m-python1
/OOP/animal.py
1,107
3.84375
4
class Animal(object): def __init__(self, name, health): self.name = name self.health = health def walk(self): self.health -= 1 return self def run(self): self.health -= 5 return self def displayHealth(self): print "Name: ", self.name print "Health: ", self.health class Dog(Animal): def __i...
aadd5e959ed1c1792a683c933696c248495c14b2
nasridexp/advent_of_code19
/python/11.py
8,347
3.515625
4
import numpy as np import matplotlib.pyplot as plt from time import sleep class IntComputer: def __init__(self, inst_list_or): #Create an array of 0 10 times longer that the actual list with the # actual list in the beggining self.inst_list = inst_list_or[:] + [0] * (9*len(inst_list_or)) ...
b1bbcc4c6329e0747dbeeccfc84d0deb24d23f17
anilkanchamreddy/Python_basics
/function_as_variable.py
733
3.9375
4
#Functions can be treated as values in some programming languages. If a value can be used for assignment, parameters, return types, etc., #such a value is called as a #first class citizen. For example def check_bag(number): print("Number of bags checked ",number) x=check_bag x(4) #Higher Order functions are th...
109dfd1f1db0d08abe2ff9deeda343a1249ac003
rlberry/CSE-1311-003
/datasets.py
1,984
3.90625
4
import math def inputFunction(): dataset=input("Please enter a set of numbers:") return dataset def maxFunction(dataSet): return max(dataSet) def minFunction(dataSet): return min(dataSet) def meanFunction(dataSet): total=sum(dataSet) count=len(dataSet) mean=total*1.0/f...
c1d7b4d1b9734715d56ea46b076afe9eea0bd3f0
mvabf/uri-2021
/1165.py
263
3.5625
4
qtd = int(input()) for x in range(qtd): n = int(input()) divisores = 0 for i in range(1, n + 1, 1): if (n % i == 0): divisores+=1 if (divisores > 2): print(f'{n} nao eh primo') else: print(f'{n} eh primo')
a68881f3e78650e8736fa20d9b6d8c2b1b1c4a25
tonish/Plank-fit
/search_T_E_iterate_folder.py
2,531
3.546875
4
''' this code reads: 1) an ENVI format radiance image 2) an ASCII spectrum file with the same spectral resolution it then runs a search for the best fitting planck function for each pixel in the radiance image. the output is: 1) a spectral cube containing the best fitted planck function of every pixel (ENVI image form...
4306c99f16e39f056c2e8d14baabea4066f91486
ayjabri/ComputerVision
/PIL_vs_OpenCV/whichIsFaster.py
1,847
3.703125
4
''' This small test is to find out which library is faster in prcessing photos in python: PIL SIMD or OpenCV Summary: On resize: PIL is 2.3 times faster in resizing a photo grayscaling: OpenCV is faster when it comes ot grayscaling a photo Conclusion: if you want to grayscale then resize a photo for DeepLearning then ...
5d3cf25f5e643a403d602018e0971d0716c0edb1
sophiawang310/Othello
/PycharmProjects/Othello/old/strategy.py
11,322
3.796875
4
import random import math import numpy #### Othello Shell #### P. White 2016-2018 EMPTY, BLACK, WHITE, OUTER = '.', '@', 'o', '?' # To refer to neighbor squares we can add a direction to a square. N,S,E,W = -10, 10, 1, -1 NE, SE, NW, SW = N+E, S+E, N+W, S+W DIRECTIONS = (N,NE,E,SE,S,SW,W,NW) PLAYERS = {BLACK: "Blac...
49f2e7025896748955fd025325aff214352fd6d8
israandikabakhri/python-data-structure
/heap.py
2,364
3.734375
4
class Heap: def __init__(self): self.h = [] self.currsize = 0 def _left_child(self, i): if 2*i+1 < self.currsize: return 2*i+1 return None def _right_child(self, i): if 2*i+2 < self.currsize: return 2*i+1 return None def _max_he...
42d586c19063c414150f1b430d1478e7fb079e32
JulianTrummer/le-ar-n
/code/01_python_basics/examples/02_lists_tuples_dictionaries/ex5_dictionaries.py
891
4.34375
4
"""Dictionary datatype""" # Unordered datatype with key:value pairs, there are no duplicates allowed my_dict = { "name" : "Kathrin", "age" : 71, "profession" : "Still not decided" } print(len(my_dict)) print(type(my_dict)) print("These are keys: ", my_dict.keys()) print("These are the values: ", my_dict...
e9d575f0bc4c1d15d8e10e523d29b67a106c8c05
arzanpathan/Python
/Assignment 3.py
804
4.15625
4
#WAP to print all odd No's between 13 to 123 print('\nOdd Numbers between 13 to 123\n') for i in range(13,125,2): print(i) #WAP to print all Natural No's from 100 to 1 using For Loop print('\nPrint All Natural Numbers from 100 to 1\n') for j in range(100,0,-1): #for j in range(100): print(j) ...
8749468453f733362f4d5ffbe857f9912472cdf8
algoitssm/algorithm_taeyeon
/Swea/1926_d2_간단한369게임.py
457
3.609375
4
n = int(input()) str_list = [] for i in range(1, n + 1): str_list.append(str(i)) # print(str_list) for str_l in str_list: cnt = 0 if '3' in str_l: cnt += str_l.count('3') if '6' in str_l: cnt += str_l.count('6') if '9' in str_l: cnt += str_l.count('9') if cnt == 0: ...
b9ff85b6f1d6b4106bc616f918e835c2c9cb10af
andrea321123/Advent-of-code-2020
/problem04.py
2,684
3.515625
4
# Problem 4 # 4/12/2020 # input file = open("input/input04.txt", "r") input = file.readlines() passports = [] single_passport = [] for i in input: if i == "\n": # end of passport passports.append(single_passport.copy()) single_passport = [] else: line = i.split() for j in...
382588ed9ad606054c49e3fbd1d1dc530b4396d5
R1G0x/python-practice
/App programming/Working with files/HTMLHandling.py
1,884
4.28125
4
#HTML is a markup language for describing web documents or web pages. #HTML documents are described by HTML tags. Each HTML tag describes different document content. #For understanding parsing of HTML pages, let consider the sample url "http://xkcd.com". This url #display comics about math and other languages. #The...
336ba3c46f0f52dda102eb46136c209baab7db26
Kruchinin-v/black_jack
/modules/functions/alignmebt_string.py
735
3.921875
4
""" Module for function alignment_string """ def alignment_string(string, length): """ Функция для выравнивания строковой переменной до нужной длины с помощью пробелов :param string: входная переменная, которую нужно выровнять :type string: string :param length: необходимая длин...
edd6d5d1e731257c4e8c253d7746d2e659912708
sudhansom/python_sda
/python_fundamentals/00-python-HomePractice/w3resource/conditions-statements-loops/problem4.py
588
4.15625
4
""" Write a Python program to construct the following pattern, using a nested for loop. * * * * * * * * * * * * * * * * * * * * * * * * * """ user_input = int(input("Enter the height of the pyramid : ").strip()) n = int(user_input / 2) for i in range(n): for j in range(i): print('*', end="") print("")...
645b1db1ad3d72fd4934386fad3e929c2a48a673
kmclaugh/Python_Toolset
/dictionaries.py
198
3.515625
4
games={'x':'home','y':'away'} print(games) for g in games: print(g,games[g]) del games['x'] print(games) if not games.get('z'): games['z']='something' if 'z' in games: print(games['z'])
890a649c6dbce9f97517452823966add79bde165
dKab/University-Stuff
/вычмат/numerical integration/trapezoid.py
547
3.71875
4
from math import sin, exp, sqrt import unittest def function(x): return sin(exp(-x)) + sqrt(x) def trapezoidIntegral(f, a, b, n): result = 0 h = (b - a) / n for i in range(n): result += f(a + (h * (i + 1))) + f (a + (h * i)) result *= h / 2 return result class TestNewton(unittest.TestCase): ...
9cdd4239c0677064eff49bfa709b862ee757adab
wangshubo90/python_code
/learn_python/slice.py
506
3.671875
4
import numpy as np a = np.array(range(100)).reshape(10,10) print("a[slice(3)] = \n{}".format(a[slice(3)])) print("a[slice(1,10,2)] = \n{}".format(a[slice(1,10,2)])) print("a[slice(0,None,2)] = \n{}".format(a[slice(0,None,2)])) print("a[(slice(0,None,2),slice(0,None,2))] = \n{}".format(a[(slice(0,None,2),slice(0,None...
0c1fc6644d5ca627c0a381fa3bc8e578b0d1fdb0
semg101/Python-machinelearningfundamentals
/2_2_3_1_score_and_cross_validated_scores.py
1,436
3.640625
4
from sklearn import datasets, svm import numpy as np #The technique used: is called a ***KFold cross-validation*** #First technique #Load the digits dataset digits = datasets.load_digits() X_digits = digits.data y_digits = digits.target #Construction of the estimator svc = svm.SVC(C=1, kernel='linear') #As we hav...
fd5a98eb4e5c3c97fe3df7e852e7fd41ec8d713e
mateusziwaniak/Python-UDEMY-course---tutorial
/OOP Problems.py
1,133
4.03125
4
""" class Cylinder: def __init__(self, height = 1, radius = 1): self.pi = 3.14 self.height = height self.radius = radius def volume(self,): result = self.pi * self.radius * self.radius * self.height return result def surface_area(self): ...
902db88fd25ffc430f6e70ef9c54b44c70c95ebd
eriksylvan/AdventOfCode2019
/25prep.py
708
3.6875
4
import itertools items = ('spool of cat6', 'hypercube', 'weather machine', 'coin', 'candy cane', 'tambourine', 'fuel cell', 'mutex') def combs(x): return [c for i in range(len(x)+1) for c in itertools.combinations(x,i)] allCombi...
cab48156c4601021d6b551417036285e77f96122
markomonsalud/project-euler-100
/Problem2.py
486
3.90625
4
import sys def fib_even_sum(number): total = 0 fib_number = 0 prev_fib_number = 1 second_prev_fib_number = 0 while fib_number <= int(number): if fib_number % 2 == 0: total += fib_number fib_number = prev_fib_number + second_prev_fib_number second_prev_fib_numbe...
e37e7c026ee8ae0f9b761f528639724322badf76
Rosthouse/AdventOfCode2019
/challenge3_part1.py
1,814
3.96875
4
# Advent of Code 2019: Day 3, Part 1 # https://adventofcode.com/2019/day/3 def man_dist(p1: (int, int), p2: (int, int)) -> int: return abs(abs(p1[0]) - abs(p2[0])) + abs(abs(p1[1]) - abs(p2[1])) def lay_cable(wire: [str]) -> [(int, int)]: pos = (0, 0) switcher = { "R": lambda pos: (pos[0]+1, pos[...
e03731800796acb0883e84ca87da068ffc5882b7
jkbockstael/adventofcode-2015
/day18_part1.py
1,431
3.625
4
# Advent of Code 2015 - Day 18 - Like a GIF For Your Yard # http://adventofcode.com/2015/day/18 import sys def parse_input(lines): return [[(lambda x: 1 if x == "#" else 0)(x) for x in line.rstrip()] for line in lines] def count_neighbours(grid, line, column, state): size = len(grid) total = 0 for x ...
d56222d1c341f43626206291c7aa34228510a42f
RobertooMota/Curso_Python
/PythonMundo1/Exercicios/ex054 - contador de pessoas de maior.py
448
3.734375
4
#informa a quantidade de pessoas que ja sao de maiores e de menores pessoa = [] deMaior = 0 deMenor = 0 anoAtual = 2021 for i in range(0, 7): pessoa.append(int(input('Digite o ano do seu nascimento: '))) for i in range(0, 7): idade = int(anoAtual - pessoa[i]) if idade >= 18: deMaior += 1 else:...
220bf37620610589889d71723503a1ebd403b56c
lijuanjiayou/typical-code
/Python/day24-面向对象与实例属性/类属性增删该查.py
709
3.765625
4
class Chinese: country='China' def __init__(self,name): self.name=name def play_ball(self,ball): print('%s 正在打 %s' %(self.name)) #查看 print(Chinese.country) #修改 Chinese.country='Japan' print(Chinese.country) p1=Chinese('alex') print(p1.__dict__) print(p1.country) #增加 Chinese.dang='共产党' #...
c0c3c34f1d9874e12ad9cdc091a5631b6429dc17
daiyanze/cs50
/pset6/credit/credit.py
846
3.828125
4
from cs50 import get_string # get credit card number input input = [int(digit) for digit in get_string('Number: ')] digits = len(input) # Odd digit sum odd_sum = sum( (digit * 2 > 9) and (digit * 2 % 10 + int(digit * 2 / 10)) or digit * 2 for idx, digit in enumerate(input[::-1]) if idx % 2 != 0) # Ev...
d82de8d5c988b55d3113dd858a1e8aa368cd12ab
dandumitriu33/codewars-Python
/set4/disemvoweltrolls.py
214
3.859375
4
def disemvowel(string): vowels = 'aeiou' for i in string: if i.lower() in vowels: string = string.replace(i, '') return string print(disemvowel("This website is for losers LOL!"))
64b5e7b5e931a76ec888b347c73ad9444528ac39
FinTrek/ctci-python
/Bit Manipulation/5.7.py
596
3.5
4
# Pairwise Swap def pairwise_swap(num: int) -> int: return ((num & 0xaaaaaaaa) >> 1) ^ ((num & 0x55555555) << 1) def brute_pairwise_swap(num: int): bin_list = list(bin(num))[2:] for b in range(len(bin_list) - 1, 0, -2): bin_list[b], bin_list[b - 1] = bin_list[b - 1], bin_list[b] return int(...
f2853275012d2823001fc700809b321e77b05e3b
alexhong33/ScrapyProjects
/basic/多线程基础.py
748
3.71875
4
# -*- coding: utf-8 -*- # @Time : 2017/7/17 9:51 # @Author : Hong # @Contact : alexhongf@163.com # @File : 多线程基础.py # @Description : STOP wishing START doing. import threading class A(threading.Thread): def __init__(self): # 初始化该线程 threading.Thread.__init__(self) def ru...
1481cc94622cfb3412a1ea895236e200dfa97cf9
ZhouZiXuan-imb/pythonCourse
/python_Day10-列表/02-遍历列表.py
540
3.6875
4
names = ['zhufengjiao', 'zhouzixuan', 'zhouzhou'] # while循环 # i = 0 # while (i < len(names)): # print("我是%d个名字%s" % (i + 1, names[i])) # i += 1 # for循环 # for 临时变量名 in 需要遍历的变量名(例如列表的变量名): # 可以使用临时变量... # ... # 如果列表中的数据已经遍历完成了 for循环会自动停止 # enumerate方法每次执行的时候会自动给i赋值为0,1,2,3,4..... for i, key in enumera...
5594ce0f5dfc5e8a0a5265a038798bce157b70a7
vsofi3/UO_Classwork
/315/HW/315assignment2.py
1,969
3.96875
4
import sys file = sys.stdin def getDag(n): vertices = file.readline() #stores number of vertices in the graph edges = file.readline() #stores number of edges, also moves to the next line of the file short = [0] * int(vertices) #an array for the shortest possible p...
b9120b261e2e6a01053c4b96ea84dc6cee983597
kennedyjosh/Ice-Hockey
/game/main.py
5,410
3.8125
4
''' Josh Kennedy ---------------------------------- Honors Intro to Video Game Design Final Project "Hockey 2017" ---------------------------------- V ALPHA 3.2 ''' # import modules and stuff from supporting files import pygame, math, time, sys, os from rink import * from gameEngine import * from constants import * fr...
a6f4dade4bd5d80f42692b7e1dab82f3abdc2465
jsverch/practice
/leet_1268.py
532
3.640625
4
from typing import List class Solution: def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]: k = str() sug = list() for i in range(0, len(searchWord)): k = k + searchWord[i] s = [p for p in products if p[0:len(k)] == k] ...
cd2e9379bac533672f5cecae7ce846ba26691dc4
ver0nika4ka/PythonCrashCourse
/10.1_Learning_Python.py
666
4.125
4
# Print contents by reading in the entire file with open('learning_python.txt') as file_object: contents = file_object.read() print(contents.strip()) print("\n") # Print contents by looping over the file object filename = 'learning_python.txt' with open(filename) as file_object: for line in file_object: ...
460790760176c9a1896b821ca1e2946a552b06b7
Lee-Geon-Yeong/SW_Expert_Academy
/D1/6246_repeatation8.py
114
3.59375
4
i = 0 j = 5 while(i < 5): j=5-i while(j>0): print("*",end='') j-=1 print("") i+=1
aa0ccc38b31b1bcdd170d13ad8e2081a6624e0d1
WhiteheadAaron/python-game
/game.py
7,861
4.09375
4
import random import time def intro(): print() print("It is the zombie apocolypse.") print("You must survive at all costs.") print("Choices you make will directly affect you and those around you.") print("In the new reality, you either thrive or you die.") print() ready = "" while read...
dc9057f7777b499ce6f9c584e6b88bf8ac42df3d
virenkhandal/funpy
/MATLAB/bisection.py
1,266
4.0625
4
import math from math import e sign = lambda x: math.copysign(1, x) def function(x): return (600 * (x ** 4)) - (550 * (x ** 3)) + (200 * (x ** 2)) - (20 * x) - 1 def method(a, b, error): print("Question: Use the bisection method to find the root on the interval [" + str(a) + ", " + str(b) + "] within " + str...
4f4cfdc746915046b3a086b67618b1d3efdfe4ea
esch3r/Python--Projects-
/selfclass.py
407
3.9375
4
# self is a temporary placeholder for the object class className: def createName(self,name): self.name = name def displayName(self): return self.name def saying(self): print ( "hello" % self.name) first =className() second =className() first.createNa...
86f8df082e714a05f09512cc87050132a2c6f59d
Tenbatsu24/Project-Euler
/divisors.py
276
3.5
4
import math def f(n): divisors = set({1, n}) for i in range(2, math.ceil(math.sqrt(n)) + 1): if (n % i) == 0: divisors.add(i) divisors.add(n // i) return divisors if __name__ == '__main__': print(f(4001)) print(f(2689))
0589d11a523e8e118e953d8078136e0648932295
bazhenov4job/Algorithms_and_structures
/Lesson_09/homework/Task_02.py
1,515
3.828125
4
""" 2. Закодируйте любую строку по алгоритму Хаффмана. """ from collections import Counter, OrderedDict from binarytree import Node from copy import deepcopy def tree_search(tree, symbol, path=''): print(symbol, path, tree.value) if tree.value == symbol: print('нашёл', path) return path ...
1f95cf8b9875b9586a2e2c731e035225df5f190d
Sergey0987/firstproject
/Алгоритмы/Грокаем алгоритмы/1. Бинарный поиск - draft.py
1,279
3.703125
4
list1=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] index_min=0 #самый левый индекс в интервале index_max=len(list1)-1 #самый правый индекс в интерале search_number=int(input('Введи число от '+str(list1[0])+' до '+str(list1[len(list1)-1])+': ')) while search_number != list1[index_max] and search_number != list1[index_min]: ...
42fe4ca4251a043e77cd41fe571d5019594343a8
shijiachen1993/learn-Python
/class/student.py
500
3.671875
4
class Student(object): def __init__(self, name, score): self.__name = name self.__score = score def get_name(self): return self.__name def set_name(self, name): self.__name = name def get_score(self): return self.__score def set_score(self,score): self.__score = score bart = Stud...
a95a29f5ad3378376fa82d9fc2a4c80b7a07fb3a
thenaterhood/thenaterweb
/tools/postData.py
5,294
3.828125
4
""" Author: Nate Levesque <public@thenaterhood.com> Language: Python3 Filename: postData.py Description: common classes and functions for manipulating posts in json and plaintext formats """ from datetime import datetime import os import codecs import json class postData(): """ Defines variables and fu...
f05edab45c6bd5d6dabfa23d2028e28349f42e98
Ignacio01/MachineLearning
/detectFlowers.py
1,745
4.28125
4
# # Tutorial from Google about Machine Learning. # import numpy as np from sklearn.datasets import load_iris from sklearn import tree # Importing the library iris from sklearn iris = load_iris() # # VISUALIZATION OF THE DATA # # The dataset contains the values of the columns in # wikipedia and the metadata tells...
dc7a0fb7a3426f2a9dea2be9428a9aeca31aa110
RishabhArya/Coursera-Data-Structures-and-Algorithms-by-University-of-California-San-Diego-
/1.Algorithmic Toolbox/week4_divide_and_conquer/2_majority_element/majority_element.py
1,136
3.734375
4
# Uses python3 # Boyer Moore Majority Vote Algoithum import sys def check_majority_element(ar , majority_element): i = 0 count = 0 while i < len(ar): if ar[i] == majority_element: count = count + 1 i = i + 1 if count > len(ar)/2: return 1 if count <= len(ar)/2: ...
24d684e5fd0b089d3fec7013d7cb8df2a9463ca8
djtsorrell/Intro-Python-OOP
/Orbits/animate.py
3,511
3.578125
4
import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation from matplotlib.lines import Line2D from orbit import Orbit class Animate(Orbit): """Initialises patches to visualise orbital motion.""" def __init__(self, filename, timestep): """TODO: to be defined. """ super()...
e52eb480815579c2585b06e48d8aebe1fb9aba5c
acgis-dai00035/gis4107-day09
/world_pop_explorer.py
3,613
3.921875
4
# -*- coding: UTF-8 -*- #------------------------------------------------------------------------------- # Name: world_pop_explorer.py # # Purpose: Provide some functions to analyze the data in # world_pop_by_country.py # # Author: David Viljoen # # Created: 24/11/2017 #------...
2a618c41583039a423b2bfcbb94cbec5ac3c458a
Ryalian/cse491-numberz
/sieve_gen/test3.py
270
3.921875
4
import sieve print "Test if 233 is a prime" print "" for x, y in zip(range(233), sieve.sieve_g()): list = y for i in list: if i == 233: print "233 is prime" Flag = 1 break if Flag != 1 : print "Damn! 233 is not prime!" #Test if one specific number is prime
00d1881ba24a1cea7e3735705be485a7fab40775
AkitaFriday/dataStructure
/sort/simpleSort.py
7,220
3.71875
4
""" 几个简单的排序算法 author: weiyc 2019-05-08 """ import random import time import matplotlib.pyplot as plt # 数据元素类,假设将要排序的序列中的每个元素是以下定义的类的实例对象 class Item(object): def __init__(self, key, datum): self.key = key self.datum = datum # 插入排序 # 就是调整第i个元素在下标[0, i]范围的顺序,i从下标1扩充到len(list) - 1时,就最终生成了整个lis...
591aa30e092133c0e848f509d93bacb4bdac6973
zhouf1234/untitled3
/面向对象-魔术方法-模拟range.py
667
3.65625
4
class Myrange: def __init__(self,start,stop): self.__start=start self.__stop=stop def __iter__(self): return self def __next__(self): #不写此两条if语句的话,则会无限显示下去,根本不会管结束字符是谁 #self.__start即为n的返回值,self.__stop,即为结束字符 if self.__start == self.__stop: #raise...
aaf9ddfc91f566db5c16f0fe0774b7d2808e78ed
vmakksimov/PythonFundamentals
/ListAdvanced/3. Next Version.py
426
3.59375
4
first, second, third = current_version = input().split('.') first = int(first) second = int(second) third = int(third) if third >= 9: third = 0 if second >= 9: second = 0 if first < 9: first += 1 else: second += 1 else: third += 1 new_version = '' new_version += str(f...
0eb85570456cbf2a768b38d1a8b64db6aaa40b9c
jorendorff/tinysearch
/tiny.py
4,432
3.6875
4
"""A simple search engine in python.""" import re, pathlib, collections, array, struct, csv, math # === Phase 1: Split text into words def words(text): return re.findall(r"\w+", text.lower()) # === Phase 2: Create an index Document = collections.namedtuple("Document", "filename size") Hit = collections.named...
4f7dfd5c3bf8a125c52549be89ddc9de0257c9f5
CristianYuri/Kindermath
/Kindermath/cod/mouse.py
981
3.859375
4
#Classe responsavel pela definicao, movimentacao, visibilidade e eventos do mouse class Mouse(object): def __init__(self, amb, screen, local_arquivo, arquivo): self.amb = amb self.screen = screen self.local_arquivo = local_arquivo self.arquivo = arquivo self.carregar_mouse() self.definir_visib_cursor(F...
301c930db2b258af3b3a89cc5ab74fc7da25cdaf
Shuaiyicao/leetcode-python
/23.py
1,142
3.859375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param a list of ListNode # @return a ListNode def merge(self, a, b): if a == None: return b if b == None: return a...
1200309fd81e8151ce3c946547c95440932e9a26
NixonZ/PythonZ
/Practice_ques/Odd Or Even.py
512
4.375
4
#Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. # Hint: how does an even / odd number react differently when divided by 2? x=int(input("Enter a number:")) if x%2: print("Odd") elif not(x%4): print("Multiple of 4") else : print("Even")...
b99912ada9c7d273014b7f7c02efa2ef5b1d4bc1
Aasthaengg/IBMdataset
/Python_codes/p02265/s505685111.py
333
3.625
4
from collections import deque n = int(input()) dl = deque() for _ in range(n): op = input().split() if op[0] == 'insert' : dl.appendleft(op[1]) elif op[0] == 'delete' : if op[1] in dl: dl.remove(op[1]) elif op[0] == 'deleteFirst': dl.popleft() elif op[0] == 'deleteLast' : dl.pop(...
5682e6e439102ba025ee5705332918594d4ecc5b
donnyhai/dla
/documents/OLD/Stochastic Geometry SS20/Arbeitsanweisungen/Sheet7Problem1d.py
3,770
3.921875
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 27 07:27:01 2019 """ ################################################################# # run %matplotlib in the console to get an interactive plot # ################################################################# from mpl_toolkits.mplot3d import Axes3D from scip...
1f339291f6b26ae1050226785db95248efc852b2
jiriVFX/data_structures_and_algorithms
/hash_tables/google_sum_of_two_but_return_indices.py
1,081
3.9375
4
# Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. # # You may assume that each input would have exactly one solution, and you may not use the same element twice. # # You can return the answer in any order. # Brute force nested loops solution d...
46f0b7b6641c279b6b426dc21fb668ad097d68cc
yeori/py-training
/hackerrank/q008.py
726
4
4
""" https://www.hackerrank.com/challenges/py-collections-namedtuple/problem # handling string ``` print({0:.3f}.format(12.34567)) # 12.345 ``` # Named Tuple * https://docs.python.org/3.6/library/collections.html#collections.namedtuple """ from collections import namedtuple if __name__ == '__main__': skip_empty_v...
903b57846cf4e2fe91cf8d992a070013d6dd021a
danielsimonebeira/aulaCesuscPython
/aula4/exerc_10.py
723
3.890625
4
#10. Faça um Programa que pergunte em que turno você estuda. Peça para digitar M-matutino ou # V- Vespertino ou N- Noturno. Imprima a mensagem "Bom Dia!", "Boa Tarde!" ou "Boa Noite!" # ou "Valor Inválido!", conforme o caso. nome_aluno = input("Digite seu nome: ") turno = input(" {}, digite o turno que você estud...
4beab0c80b7a0844c9acb2475948917eb2b690c0
carolinvdg/MyExercises
/ex45GAMEREADY.py
10,892
4.03125
4
from sys import exit from random import randint class Engine(object): def __init__(self, scene_map): self.scene_map = scene_map def play(self): current_scene = self.scene_map.opening_scene() last_scene = self.scene_map.next_scene('finished') while current_scene ...
04afffef6917c501df6d892d8731f85ef5ac3cbc
sunanth123/pypixelator
/src/mirror.py
883
3.96875
4
## This function will mirror an image that is provided to it by using ## nested loops to iterate through the original image pixels and placing them ## in the new image in an inverted manner from PIL import Image def mirror(im): ## get the dimensions and pixels from the original image and initialize ## a new im...
11c352d20b0c40275d6f82c90a130ca49b62abaf
zzynggg/python
/Hash Table ADTs/list_adt.py
16,083
4
4
""" List ADT and an array implementation. Defines a generic abstract list with the usual methods, and implements a list using arrays and linked nodes. It also includes a linked list iterator. Also defines UnitTests for the class. """ __author__ = "Maria Garcia de la Banda, modified by Brendon Taylor" __docformat__ = ...
fcab3ff3814d1241e380e8a4ba6ad13a9d78e4ec
huyhoang17/Project_Euler
/36.py
1,034
3.859375
4
#!/usr/bin/python3 ''' - The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. - Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. - (Please note that the palindromic number, in either base, may not include leading zeros.) ''' from base impor...
9233a7dfb7e38471039995f661eae0e8155a75cd
JayFoxFoxy/ProjectEuler
/P10v4.py
667
4.03125
4
#Sieve of eratosthenes algorythm def removeNonPrimes(numbers, total): auxList = [2,3,5,7] index = 0 #print(auxList[index]) n = 0 aux = 2 for i in auxList: print(i) while(n<=int(total)): n = int(i) * aux #print(n) if n in numbers: numbers.remove(n) aux+=1 aux = 2 n = 0 #print(numbers) ...
961f13608e9aecd3129220888ab2292b9da8449a
Nora-Wang/Leetcode_python3
/Hash and Heap/lintcode_0955. Implement Queue by Circular Array.py
2,468
4.03125
4
Implement queue by circulant array. You need to support the following methods: CircularQueue(n): initialize a circular array with size n to store elements boolean isFull(): return true if the array is full boolean isEmpty(): return true if there is no element in the array void enqueue(element): add an element to the q...
f28e6b12506c121cf5c11a7882cd6b63520f4141
Liu-Zhijuan-0313/pythonAdvance
/lianxi/day0212/day03.py
401
3.6875
4
class AI(object): # 如果随意添加岂不是封装不安全了? # 可以通过__slots__限制添加的内容 __slots__ = ("name", "hp", "mp") def __init__(self, _hp): self.hp = _hp a1 = AI(50) print(a1.hp) # 动态的添加类属性 #实例也拥有了该属性 AI.name = "python1811" print(a1.name) print(AI.name) # 动态的添加实例属性 a1.mp = 30 print(a1.mp)
2ea976f760557bb6cb0089484621d84cb4dc9640
SREEHARI1994/ThinkPython_mysolutions
/tuples_chapter/most_frequent.py
7,134
3.625
4
# -*- coding: utf-8 -*- import string def most_frequent(text): #removing punctuations for letter in text: if letter in list(string.punctuation): text=text.replace(letter,"") #removing all whitespaces and converting to lower case text= "".join(text.split()).lower() d={} for letter in text: d[letter]=d.get(...
3d4d42cc3807141c4bd6179c86ad750e519fc386
Likh-Alex/PostgreSQL-Python
/lottery.py
1,164
3.84375
4
import random def menu(): #Ask player for numbers #Calculate lottery numbers #Print out the winnings player_numbers = get_players_number() lottery_numbers = create_lottery_numbers() lottery_numbers matched_numbers = lottery_numbers.intersection(player_numbers) if len(matched_n...
44082caf0455c8f307469fa6d862db2dfc82489b
AveryHuo/PeefyLeetCode
/src/Python/101-200/151.ReverseWordsInString.py
253
3.703125
4
class Solution: def reverseWords(self, set): return ' '.join(set.split()[::-1]) if __name__ == "__main__": solution = Solution() print(solution.reverseWords("the sky is blue")) print(solution.reverseWords(" hello world! "))
09b7b8494b5a0640127f46df20650a132c5fc853
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/hamming/e24c21afe3ff46c1863c2f45eb9ae131.py
334
3.984375
4
def distance(strand, mut_strand): '''This function calculates the hamming distance between two DNA strands''' strand_len = len(strand) if strand_len != len(mut_strand): raise ValueError('Both DNA strands need to be the same length') return sum([strand[c] != mut_strand[c] for c in range(0, stran...
bc4bbe31282a164f7490f19f8809323a04e551c7
mangel2500/Programacion
/Práctica 7 Python/Exer-2.py
603
4.1875
4
'''MIGUEL ANGEL MENA ALCALDE - PRACTICA 7 EJERCICIO 2 Escribe un programa que lea el nombre y los dos apellidos de una persona (en tres cadenas de caracteres diferentes), los pase como parmetros a una funcin, y sta debe unirlos y devolver una nica cadena. La cadena final la imprimir el pr...
6c1694a3cd7f4c4966888d8c5025d4f6c64645b5
hsiehkl/Data-Structure-and-Programming
/programming_hw4/programming_hw4.py
3,302
3.59375
4
########################################### # 107-1 Data Structure and Programming # Programming Assignment #4 # Instructor: Pei-Yuan Wu ############################################ import sys # ********************************** # * TODO * # ********************************** ''' You ...
5ce4e69a76c571d7212e399103a1d001a0b3a479
dymbow10/python-faculdade
/folha 3/exercicio 1.py
518
3.796875
4
#achar aposição de um caractere numa string def ler(): frase=input("Insira sua frase bro: ") l=input('Insira a letra a ser procurada: ') return frase,l def procura(frase,l): achei=False for i in range(len(frase)): if l == frase[i]: print("Caractere encontrado na posição {:1d}".f...
6299f8e9e8b8b470656de8256ae3e250cfb4c654
Jangwoojin863/python
/고급예제5.py
3,542
3.515625
4
# 고급 예제 5 # 콘솔창에서 실행하는 예제입니다. # python 고급예제5.py <엔터> import os MAZE_SIZE = 12 WALL = '#' MOUSE = 'Q' END = '$' UP = 0 RIGHT = 1 DOWN = 2 LEFT = 3 Exit = False ms = [0, 0, 0] # 마우스 좌표와 방향 저장 x, y, d old_ms = [0, 0, 0] # 마우스 이전 좌표와 방향 저장 # 미로 정의 데이터 maze = [ ['#','#','#','#','#','#','#',...
10553ddf1d1978e4fa74a3cd1317703014e7efd7
tahmid-tanzim/problem-solving
/flipping-an-image.py
452
3.890625
4
#!/usr/bin/python3 # https://leetcode.com/problems/flipping-an-image/ def flip_and_invert_image(A): output = [] for a in A: i, x = len(a) - 1, [] while i >= 0: x.append(1 - a[i]) i -= 1 output.append(x) return output if __name__ == '__main__': print(fl...
b502e0556519fbf3855399bd4b75a1dedfc4a585
Allen-Wu-Jialin/FinanceGame
/miscutils.py
277
3.59375
4
class MiscUtils: @staticmethod def Loop(num, min, max): difference = max - min num -= min num %= difference num += min return num if __name__ == "__main__": for x in range(1000): print(MiscUtils.Loop(x, -100, 400))
14924fe19fec667c5bdad85bd86001d1c67b0f7d
yang-yangfeng/board2FEN
/tests/Boardtest.py
2,459
3.9375
4
from Board import Board from random import randint #class to keep track of squares w pieces on them class randsquares: def __init__(self, board): self.board = board def randfreesq(self): row = randint(1,8) col = randint(1,8) #will be infinite loop if every square has a piece on...
de6e27be05d0c4088fa27c8ac9117822a07450c5
macbeth93/lesson6
/hw6.4.py
2,418
4.03125
4
# Реализуйте базовый класс Car. У данного класса должны быть следующие атрибуты: speed, color, # name, is_police (булево). # А также методы: go, stop, turn(direction), которые должны сообщать, что машина поехала, остановилась, # повернула (куда). # Опишите несколько дочерних классов: TownCar, SportCar, WorkCa...
f9b4e45a7fb78326361ac29a0740a50a02039df7
critoma/armasmiot
/labs/workspacepy/tutorial-python/p005_tuples.py
623
4.375
4
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) tinytuple = (123, 'john') print (tuple) # Prints complete tuple print (tuple[0]) # Prints first element of the tuple print (tuple[1:3]) # Prints elements starting from 2nd till 3rd print (tuple[2:]) # Prints elements starting from 3rd ele...
071d17d0dba17670cf704dfd7fd88c8fbb869e26
Romits/BigDataScience
/anagrams/Anagram.py
761
3.59375
4
#!/usr/bin/python -tt import sys input = ['cat','dog','rats','moon','god','star','tsar'] def main(): outputDict ={} outputDict = findAnagrams(input) printResult(outputDict) def findAnagrams(inputList): resultDict = {} for i in range(len(inputList)): key = str(sorted(inputList[i])) if key in resul...
c4d38bcade4328d70a5b07884393c3478ec79277
fanyan1120/Python_ex
/ex_06_07_08.py
810
3.8125
4
#coding=utf-8 x = "%d green bottles hanging on the wall." %10 apple = "apples" orange = "oranges" y = "there are 5 %s and 10 %s on the table." %(apple, orange) print x print y print "I sang the sang: %r " % x print "I said: '%s' " % y ff = False tt = True joke = "Isn't that joke funny? %r" print joke % ff print joke...
531bfff20920a5a619d57a43757af18777dca9d6
Basilisvirus/Band-gap-energy-of-photocatalyst
/col_per.py
1,376
3.625
4
''' input: txt file with two columns, first col: wavelength. second col:light intensity, seperated with tab. output: % of each measured intensity (2nd col), based on the maximum value of intensity of the 2nd col ''' '''Calculate the maximum value of the column 2 (light intensity) in a file, return column and maximim v...
82bc78d9eee316c32b2ea75eda4db02ee7c88bbc
twf2360/Phys281-SolarSystem
/V2/CalculatorV2.py
8,039
3.578125
4
#Class that works out the acceleration of all of the bodies import math import numpy as np from ParticleV2 import ParticleV2 import copy import matplotlib.pyplot as plt import matplotlib.axes as axs import dataclassV2 from mpl_toolkits import mplot3d import sympy #Defining the current 'state of the solar system' s...
917cc156aedbbfc90fb25425ad726c76fd864261
ashwiniingole/python.first
/welcome.py
246
3.921875
4
name = input("ENTER YOUR NAME: ") print("WELCOME TO THE WORLD OF PYTHON ", name) condition = input("How are you today? ") if condition == "GOOD": print("Great I am GOOD too") elif condition == "BAD": print("Sorry to hear about that :(")
996587e967cb1247bb3f5ca84339c43de8872656
ojenksdev/python_crash_course
/chapt_10/read_a_file.py
441
4.15625
4
def read_contents(filename): """Read the contents of a file""" try: with open(filename, 'r') as f_obj: content = f_obj.read() except FileNotFoundError: print("Sorry, but the file " + filename + " appears to be missing.") else: print(content) filenames = [...
e6272e2c3636327943a976e185c5b6511c2a6ca1
tmescic/python-test
/task3.py
1,848
3.796875
4
#!/usr/bin/python2.7 # encoding: utf-8 ''' Created on Dec 17, 2014 Write a decorator that stores the result of a function call and returns the cached version in subsequent calls (with the same parameters) for 5 minutes, or ten times ­­ whichever comes first. @author: tmescic ''' import datetime def cache_func(func)...
879abeb19e535c7b0c9e76dcd6bb897538057049
ecurtin2/Project-Euler
/src/003.py
975
3.890625
4
""" The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ import argparse import itertools def factorize(n): if n < 0: yield -1 n *= -1 elif n > 2: i = 2 while n % i != 0 and i <= n: i += 1 ...
7f583704f189af2e46a6efcbb3435bc098eb938f
Risvy/30DaysOfLeetCode
/Day_19/19.py
334
3.75
4
/* https://leetcode.com/problems/climbing-stairs/ Tags: Dynamic Programming, Easy */ class Solution: def climbStairs(self, n: int) -> int: if n<=2: return n else: a,b=1,1 for i in range (n): b,a=a+b, b return a return 0 ...
eb27f96dd5484cf9d17121424940944885533dfe
mpfilbin/Softener
/shell/commands/factory/__init__.py
1,114
3.53125
4
from shell.commands import posix, cygwin import re as regex from shell.exceptions import UnSupportedShellException shells = {"Linux": posix, "CYGWIN_NT-6.1": cygwin, "CYGWIN_NT": cygwin} def from_unix_name(uname): """ Attempt to determine the appropriate shell from the unix name provided :param uname: ...
6867766d6fe4ee81b44346d5468b4a448fed3ffe
srikanthpragada/demo_27_sep_2019
/ex/unique_chars.py
169
4.1875
4
# Unique chars of a given string st = input("Enter a string : ") chars = [] for c in st: if c not in chars: chars.append(c) for c in chars: print(c)
b766acfa47f743cb6268deab3183c2d4a1f1de07
sarthakjain07/TIC_TAC_TOE
/project.py
4,375
4.28125
4
# Global variables # this is a platform where the game will be played platform=["-", "-", "-", "-", "-", "-", "-", "-", "-"] # If game is still going on goingOn=True # winner or tied or loser winner=None loser=None # who's turn is it? currentPlayer="X" # This function displays the platform of G...
cbdc16a8fbef5659ad2da4524a528244d164858f
memoia/sparkcalc
/infix.py
6,313
3.546875
4
import unittest import operator from collections import deque, namedtuple from types import IntType OperatorProperty = namedtuple('OperatorProperty', ('weight', 'method')) class BaseOperators(object): """Subclass this to add new operators""" operators = { # symbol to precendence (higher value is higher pr...
eed6b64947e109d551af6bf9fc8697bfac941ec3
hardenmvp13/Python_code
/python知识体系/8,错误与异常/调试.py
1,089
4.03125
4
''' debug相关功能 F8:step over 单步(第一个按钮) 遇到断点后,程序停止运行,按F8单步运行。 F7:step into 进入(第二个按钮) 配合F8使用。单步调试F8时,如果某行调用其他模块的函数,在此行F7,可以进入函数内部,如果是F8则不会进入函数内容,直接单步到下一行。 Alt+shift+F7:step into mycode(第三个按钮) 个人理解F8和F7的综合。1、没遇到函数,和F8一样;2、遇到函数会自动进入函数内部,和F8时按F7类似的 shift+F8:step out 跳出(第五个按钮) 调试过程中,F7进入函数内后,shift+F8跳出函数,会回到进入前调用函数的代码。不是函数地...
fc13a1bfd84191494352fc88a63ec37a338d5b89
lemaoliu/LeetCode_Python_Accepted
/142_Linked_List_Cycle_II.py
680
3.703125
4
# 2015-02-02 Runtime: 177 ms # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @return a list node def detectCycle(self, head): if not head: return None fast, sl...
30391f82dfd5e9259f1d866f5efe9226664df10d
vampy/university
/fundamentals-of-programming/labs/proposed_1.py
218
3.828125
4
# http://python-future.org/compatible_idioms.html from __future__ import print_function from builtins import input s = 0 for i in range(1, int(input("Give a number: ")) + 1): s += i print("The sum is " + str(s))
03a10156148da3e2136a35f185b46a711065ee91
mikey084/Algorithms_Practice
/practice1.py
1,591
4.15625
4
''' https://www.interviewcake.com/question/python/reverse-linked-list Write a function that can reverse a linked list and does it in-place. Strategy: ''' class LinkedListNode: def __init__(self, value): self.value = value self.next = None def __str__(self): return "value:{}".format...