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
274a77dadd0d9a74f87d8695025ff8b626b87341
babtiss/ITMO_AlgoAndDataStruct
/Algo 1 course/9 lab/1.py
1,351
3.53125
4
''' Топологическая сортировка — упорядочивание вершин бесконтурного ориентированного графа согласно частичному порядку, заданному ребрами орграфа на множестве его вершин. Переводя на человеческий - отсортировать в порядке выхода из dfs. ''' def dfs(v): global color,f,answer q=[v] while q: f...
4ddda8da0be4ee303de96079c0ee4e247343836a
Jdicks4137/function
/functions.py
1,419
4.46875
4
# Josh Dickey 9/21/16 # This program solves quadratic equations def print_instructions(): """This gives the user instructions and information about the program""" print("This program will solve any quadratic equation. You will be asked to input the values for " "a, b, and c to allow the program to s...
2042817935e3f1ca3cf0d8fe652ce1918cef5aa0
aliciatb/public_scripts
/books.py
3,660
3.75
4
import pprint import sys import urllib from datetime import datetime from apiclient.discovery import build def sampleCall(api_key): """ Sample code kindly provided by google, https://developers.google.com/api-client-library/python/samples/simple_api_cmd_line_books.py """ # The apiclient.discovery.build() function re...
bebfa995365aeb95541a6e5e6ad7cd63a7e81646
mos2kn/sphinx-python-doc-example
/example1.py
442
3.6875
4
def func1(arg1, arg2): """This function takes two arguments, sets the first argument to the second, and returns. Pointless... :param arg1: Some value :type arg1: [type] :param arg2: Another value :type arg2: [type] :return: arg1 :rtype: [type] """ arg1 = arg2 return arg1 d...
e899d7aa5ab3884c798e9dbfdb7f51eaf256f326
kangwonlee/ECA
/lab_02_root_finding/use_sequential.py
831
3.671875
4
# -*- coding: utf8 -*- # [학번] [이름] """ 1변수 방정식의 근을 찾는 방법 중 sequential method 를 사용하여 어떤 함수 f(x)의 근을 찾고자 함 """ # 1변수 방정식의 근을 찾는 함수를 모아둔 root_finding 모듈을 불러들임 import root_finding print dir(root_finding) def func(x): """ 근을 구하고자 하는 함수 이 경우는 x * x - 3.0 = 0 을 만족하는 x 를 찾게 되며 이러한 x 는 3 ** 0.5 즉 3 의 제곱근임 :p...
5ad59cbed8413ac8ba1404600a67c7f3e0ea3bf4
kangwonlee/ECA
/lab_01_intro/04_test_numpy.py
362
3.59375
4
# -*- coding: utf8 -*- # 배열, 행렬 관련 기능을 담고 있는 numpy 모듈을 불러 들여 np 라는 이름 아래 연결함 import numpy as np r1 = np.array((1.0, 2.0)) print "r1 =", r1 r2 = np.array((-2.0, 1.0)) print "r2 =", r2 r3 = r1 + r2 print "r3 =", r3 # Numpy Quickstart tutorial, https://docs.scipy.org/doc/numpy-dev/user/quickstart.html
d69013b655375166899ee0747a76bac4171e58af
danrobdanrob/AutomateTheBoringStuff
/scratchpad.py
74
3.671875
4
myList = [('a',1),('b',2,3),('c',3)] for x,y,z in myList: print(x,y,z)
e8fd292b3a4bf54aa52a5b2133d1e152b5c0d9f8
MrWC/nseDL_GPU
/util.py
10,045
3.921875
4
""" Helper functions and data types. """ from itertools import tee, izip import math import pandas as pd from operator import eq import numpy as np from sklearn.cluster import DBSCAN # mean earth radius in kilometers # https://en.wikipedia.org/wiki/Earth_radius earth_radius = 6371.0 def great_circle_dist(a, b, unit=...
2f33f1d3d31a7308ad87b61b6314b0fe3fc3033b
rhitwij/python-gui-basics
/pm.py
612
3.9375
4
from tkinter import * import tkinter def body(): sum = int(e1.get()) + int(e2.get()) ans.set(sum) root = Tk() ans = StringVar(); Label(root, text="enter number").grid(row=0, sticky=W) Label(root, text="enter number").grid(row=1, sticky=W) Label(root, text="result").grid(row=2, sticky=W) result = L...
f2f959003206e9c2e9fe7662f1b0d796b207799b
waldo237/pythonPractice
/generalPractice.py
765
3.75
4
""" itertools.compress() Filters one iterable with another.""" import itertools # def main(): # class1 = ["Bob", "James", "Chad", "Darcy", "Penny", "Hannah" # "Kevin", "James", "Melanie", "Becky", "Steve", "Frank"] # selections = [True, False, True, False, True] # result = itertools.compress...
acaa6f62e6796d843292753b518ebd326b58de48
mrtajik/Python_intro
/7.py
421
3.765625
4
""" Advance data type - Lists,tuple,dict,set """ #dictionary """ dict({}) {} type({}) <class 'dict'> {1:"test"} {1: 'test'} where 1: is the immutable key, test is the value accessing to data through key: num[1] 'one' num.get(1) 'one' to add num["four"]=4 nnum {1: 'one', 2: 'two', 3: 'three', 'four': 4} search 1 i...
3196967c50c7931024506197bf857bc4038151ab
Pavankalyan0105/CP
/CCC prac/isSubSet.py
654
3.515625
4
def isSubset(arr,sum): rows = len(arr) cols = sum+1 DP = [[False for j in range(cols)] for i in range(rows)] # arr = sorted(arr) for i in DP: print(i) DP[0][arr[0]] = True for i in range(rows): DP[i][0] = True for i in range(1 ,rows): for j in range(1 ...
7e0b869d04af959d148f5d10dc1a0eaad8a70e38
Pavankalyan0105/CP
/CCC prac/nearestPower.py
549
3.84375
4
# from math import pow,sqrt # def nearestPower(a , b): # l = int(sqrt(b)) # print(l) # n,p = 0,0 # for i in range(2 ,l): # print("l-->",l) # power = int(pow(a,i)) # if(power>b): # n = int(pow(a,i)) # p = int(pow(a,i-1)) # break # if(...
783419bbb56781eda72c637f6041c2416fae6dbe
Pavankalyan0105/CP
/CCC prac/sett.py
146
3.59375
4
s = "helllo" t = "hlelo" s = set(s) t = set(t) print(s,t) arr= [3,23,2,23344,24] arr.sort(reverse = True) print(arr) [print(x) x for x in arr]
7fbfbc45636bcb9196ed7805fa1aa88c83e211de
schef/pp_curses
/practices.py
836
3.53125
4
#!/usr/bin/python3 import random class Practices: def __init__(self): self.randomPool = [] def setRandomNFromPool(self, n, pool): self.randomPool = [] pool = list(pool) for i in range(n): self.randomPool.append(random.choice(pool)) pool.remove(self.random...
fef659d6ad0e92902ca75709f4e0bef33c911ec2
kyleicban/Optimization-Algorithms
/bisection.py
990
3.703125
4
import math def bisection(f, a, b, err): if(f(a) * f(b) > 0): print("Invalid range") return None a_n = a b_n = b p_n = 0 it = 0 while(b_n - a_n >= err): it += 1 print("Iteration: " + str(it)) p_n = (a_n + b_n) / 2 print("a_" + str(it) + " = " + ...
7a9324c1bca3144f1df4ec5bea8f59a62eb3ce4d
thiangus/FactoryJokes
/src/admclient.py
2,304
3.515625
4
#!/usr/bin/env python # -*- coding: ISO-8859-1 -*- # inetclient.py - Versao 1.0 # um cliente para se conectar ao servidor multithread # Mario O. Menezes baseado no codigo Java do # Prof. Elliott # python inetclient.py endereco_servidor numero_porta import socket # networking module import sys raw_text = "Escolha...
b5bd5dde9e50041eaa9b1e53eb55d455b6625bf4
jasimdipu/django_batch_6th
/seventh_cls_30_07_21/file_handling.py
109
3.71875
4
# create a file file = open("file.txt", 'r') for i in file.readline(): print(i, end="") file.close()
1bd25b31434d662073c05e21a24a454eb2d9863a
jasimdipu/django_batch_6th
/eight_cls_02_08_21/student.py
400
3.625
4
# abstraction, encapsulation, inheritance, polymorphism from abc import ABC, abstractmethod class Student(ABC): # class -> signeture @abstractmethod def get_stu_name(self): pass @abstractmethod def set_stu_name(self, name): pass @abstractmethod def get_stu_dept(self): ...
4c20ac4082a5dc35a4f8b30f5c6e30b95035df4c
herzenuni/sem5-firsttask-04092018-stuklovao-1
/answer.py
1,301
3.515625
4
class RangeException(Exception): def __init__(self,text): RangeException.txt = text numbers = ['ноль','один','два','три','четыре','пять','шесть','семь','восемь','девять'] types = ['bin', 'oct', 'hex'] a = input("Введите один из типов hex, oct, bin:") def func(x, num_type): if num_type in types and num_...
575de7537ae45b6d88a0b208999b95fd34dcb314
birkoff/data-structures-and-algorithms
/minswaps.py
1,856
4.40625
4
''' There are many different versions of quickSort that pick pivot in different ways. - Always pick first element as pivot. - Always pick last element as pivot (implemented below) - Pick a random element as pivot. - Pick median as pivot. ''' def find_pivot(a, strategy='middle'): if strategy and 'middle' == strate...
c3d8ee29d8d2eee8a180478d2ff9f37d5d372ca9
JuanDelAguila/ManMetHacks-2.0
/Main.py
1,415
3.578125
4
from Scraper import Scraper from Data import Data from Sentiment import Sentiment from newspaper import Article def main(): myData = Data() evaluate = Sentiment() companies = myData.getCompanies() myScraper = Scraper(companies) url = str(input("Input a newspaper url: ")) #url = "http...
0ed62fbc1e32ace794d71c3b78114c245d760dbb
wyrlamildred/cadastro_aluno
/remover_matricula.py
256
4
4
def remover_matricula (): aluno=str(input("Digite o nome do aluno:")) aluno=aluno.upper() if aluno in laluno: laluno.remove(aluno) print('Aluno Removido') else: print('Esse Aluno Não Está Matriculado') pass
ba63cad537626282dce592202bc10c41a0253f09
hash167/adventofcode
/2020/day18.py
2,947
3.9375
4
from abc import ABC, abstractmethod import itertools def add(x, y): return x + y def mul(x, y): return x * y class Expression(ABC): @abstractmethod def evaluate(self): pass class Number(Expression): def __init__(self, value=None): self.value = value def __repr__(self): ...
3deacf24be5cac8b80f4fcdd2ae7321c79054797
neel6762/Automate-the-Boring-stuff-with-python-
/CH-08 -- Mad-libs.py
665
4
4
# doing this without the use of Regular Expression file = open('madlibs.txt') content = list(file.read().split()) print('The ADJECTIVE panda walked to the NOUN and then VERB') print('\nEnter in the following words to replace them above and see the new string !') adj = input('Adjective:') noun = input('Noun:') verb = i...
6127b110de3fd488e9252361d7c68870bf051eef
jop611/chips_circuits
/code/helpers/helpers.py
2,462
3.71875
4
""" helpers.py Traces path of a connection and appends coordinates to list used for visualisation. (C) 2020 Teamname, Amsterdam, The Netherlands """ from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np def trace(paths, destination): """ Traces path from destination to ...
3e9384998a82d0d8d1c31ef7711860f746ceb00e
OliverAndreasHood/NLP_Final
/modules/part_B.py
796
3.59375
4
from nltk.probability import FreqDist import time def word_counter2(alw, out=False, cl = 10): """ alw => type==list, list of words to count out => type==bool default = False, to print out BoW, SoW and most_common_words plot. cl => type==int default = 10, number of most_common_words to plot. if...
d7a343a7bc881e409c0505f7e5f542ead6cc331c
azheng333/video_code
/python_7.py
1,185
3.671875
4
# coding=utf-8 class Animal: '''this is a help doc''' name = 'no name' owner = 'no owner' noise = 'no noise' def __init__(self, name, owner, noise): self.name = name self.owner = owner self.noise = noise def __del__(self): print 'destroy' def printName(sel...
2e9c2e31fdb07a4e9523acd6105ad722d4a8c612
deepakcr26/adv_python_training
/family.py
1,061
3.828125
4
class Mgm: """ Base Class """ def walk(self): print("Walk - MGM", id(self)) class Mgf: """ Base Class """ def walk(self): print("Walk - MGF", id(self)) class Pgm: """ Base Class """ def walk(self): print("Walk - PGM", id(self)) class Pgf: """ Base Class """ ...
379132b85c5717ee06d36219d28a4f6d54cd441b
rosafsw/Final_Project
/Player.py
845
4.03125
4
""" Player.py This class defines the operation for human players, including movement of the stone. """ class Player(object): def __init__(self, board, player): self.board = board self.player = player def human_action(self): """ ask player to input the position to put ...
4b213f9aaa1578c4b4b0ecbe45b354220fe71c74
lenomosh/password-manager
/Credentials.py
2,408
3.5625
4
from string import ascii_letters, digits, punctuation from secrets import choice, token_hex class Credentials: def __init__(self): self.accounts = [] def generate_password(self, password_length=None): """ Generates an alphanumeric password whose length is specified in the argument ...
88075201b5804d6589f8e659110e30288318f77f
olivethomas/DSA
/7/7-8.py
385
3.53125
4
#the look-and-say problem """ 8 o/p: 1113213211 //n-th element in look-and-say sequence """ def find(a): s='' i=0 while i<len(a): d=a[i] c=1 while i+1<len(a) and a[i+1]==a[i]: c+=1 i+=1 s+=str(c)+d #print s, i+=1 return s n=input...
01d033c5da459436550b7c58aaafd9ffa5a0f26e
AIHackerTest/Allenzhangxm_Py101-004
/Chap1/project/MVP.py
1,038
3.625
4
d = {} h = {} #file = open("weather_info.txt") with open ("C:/Users/ZHANG/weather_info.txt", 'r' , encoding = 'utf-8') as f: for info in f.readlines(): key = info.split(',')[0] d[key]=info.split(',')[1].strip('\n') #print(d) #city = input("please enter the city name:") #print () while True: ...
9af3afea0c3616aea2f0924eef0a4166767098ec
ch-liux/spiders
/others/豆瓣读书.py
825
3.65625
4
# 豆瓣读书 import re import requests response = requests.get('https://book.douban.com/').text # bookpa = '<li.*?cover.*?href="(.*?)".*?title="(.*?)".*?author">(.*?).*?publisher">(.*?)</span>.*?</li>' # pattern = re.compile('<li.*?cover.*?href="(.*?)".*?title="(.*?)".*?more-meta.*?author">(.*?)</span>.*?year">(.*?)</span...
efc3ca432e4a76e5b9841e78d18ac089b2f92b2b
ch-liux/spiders
/pythoning/src/useModule/demo2.py
2,237
3.609375
4
''' Created on 2018年8月15日 @author: Administrator ''' """ collections""" from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(1, 2) print(p) print(p.x) print(isinstance(p, Point), isinstance(p, tuple)) Circle = namedtuple('Circle', ['x', 'y', 'z']) # 使用list存储数据时,按索引访问元素很快,但是插入和删除元素就很慢...
715bc25677f74d5c21ff844b8933de86812fbcca
sunny809/leetcode-solutions
/leetcode/AddTwoNumbers/solution.py
2,083
3.84375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1, l2): ...
30bfc6035f518991150561f39ca3dd3240936539
nadiasvertex/cql-db-py
/column_store/mq.py
4,686
3.78125
4
from collections import OrderedDict import math class Cache(object): """ :synopsis: Stores key/value references using a particular caching policy. The policy used is basically covered in the MQ algorithm description at http://opera.ucsd.edu/paper/TPDS-final.pdf In short, there are a configurable numbe...
48d02d16ec3faa450b36a62c49be1a6ecd7b6e72
babiswas2020/python-practise
/Graph/graph15.py
820
3.65625
4
class Cell: def __init__(self,x,level): self.x=x self.level=level def is_valid(x,N): if x<0 or x>=N: return False return True def step_to_end(pos,N,l): queue=[] visited=[False]*N dx=[1,-1] queue.append(Cell(pos,0)) visited[pos]=True while queue: m=queue.pop(...
d2e72b21f0f4a27b6f492b4f9884b4a6a0a0d629
babiswas2020/python-practise
/process1.py
420
3.53125
4
import time import multiprocessing def calc_square(numbers): for n in numbers: print('Square'+str(n*n)) def calc_cube(numbers): for n in numbers: print('cube'+str(n*n*n)) if __name__=="__main__": arr=[2,3,8,9] p1=multiprocessing.Process(target=calc_square,args=(arr,)) p2=multiprocess...
96ec9464a125bbaa3ca188ad513cd8cc0dd7f850
babiswas2020/python-practise
/Tree/tree12.py
1,648
4.09375
4
class Node: def __init__(self,value): self.value=value self.left=None self.right=None def level_trav(self): queue=[] queue.append(self) while queue: m=queue.pop(0) print(m.value) if m.left: queue.append(m.left) if m.right: ...
5b95d6f2a5fa3c33905cc0dc5ce12ef83f202eca
dmaia1194/CursoAlura
/Python3/jogos/adivinhacao.py
739
4.03125
4
print("*********************************") print("Bem vindo ao jogo de Adivinhação!") print("*********************************") print("Teste") numero_secreto = 42 total_tentativas = 3 rodada = 1 while(rodada <= total_tentativas): print("Tentativa {} de {}".format(rodada, total_tentativas)) chute_str = input("Digi...
3242754e8d6de3c06acc7d77df793b77d0c3cf0d
Barracudakun/pythonProject_class1
/class1.Find elements/class1_8 way locate elements.py
4,244
3.890625
4
''' 实战经验中,必须要写!!!!! from selenium import webdriver driver = webdriver.Chrome('/Users/seashore/Dropbox/My Mac (MacBook-Air.lan)/Desktop/chromedriver') #括号内为webdriver地址 driver.maximize_window() driver.implicitly_wait(10) ''' from selenium import webdriver driver = webdriver.Chrome('/Users/seashore/Dropbox/My Mac (MacBoo...
0601caab7dfdc773ffff5fc7484b68c3fcc4c2f4
Barracudakun/pythonProject_class1
/class1.Find elements/Class2_xpath.py
3,549
3.609375
4
''' 实战经验中,必须要写!!!!! from selenium import webdriver driver = webdriver.Chrome('/Users/seashore/Dropbox/My Mac (MacBook-Air.lan)/Desktop/chromedriver') #括号内为webdriver地址 driver.maximize_window() driver.implicitly_wait(10) ''' ''' 为什么使用Xpath和css定位? 1 ID,name, class; 依赖于元素定位这三个对应的属性, 如果元素没有以上三个属性,定位方法不能使用 2 ling_text, par...
9358338200a8b4494b18c15ab8870c2221a4acd4
alex-rantos/python-practice
/problems_solving/list_filtering.py
232
3.5625
4
def filter_list(l): integer_list = [] for elem in l: if type(elem) == type(1): integer_list.append(elem) return integer_list if __name__ == '__main__': print(filter_list([1,2,'a','b']))
10ee344ede87f5fd75675ab2f381b3033261a5f5
alex-rantos/python-practice
/problems_solving/wordDictionary.py
3,123
4.09375
4
"""Design a data structure that supports the following two operations: void addWord(word) bool search(word) search(word) can search a literal word or a regular expression string containing only letters a-z or dot(s) (..). A dot (.) means it can represent any one letter.""" class TrieNode: def __init__(self): ...
7d675116f4ae33521e71488c51e839e068d52aa7
alex-rantos/python-practice
/problems_solving/max_power.py
421
3.921875
4
"""Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character. Return the power of the string. """ def maxPower(self, s: str) -> int: c = 1 ans= 0 found=False for i in range(0,len(s)-1): if s[i] == s[i+1]: c+=1 ...
e70eaf556e977b8318ed176db8e95512ba8b8402
alex-rantos/python-practice
/problems_solving/max_square.py
819
3.625
4
# Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. def maximal_square(matrix: [[str]]) -> int: n = len(matrix) m = 0 if n > 0: m = len(matrix[n - 1]) dp = [[0] * (m+1) for _ in range(n+1)] max_sq = 0 for i in range(1, n...
1ebc6432017b7d7754997e832592f589b7d1064e
alex-rantos/python-practice
/problems_solving/coinChange2.py
1,647
3.703125
4
from typing import List """ You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin. """ class Solution: def changeRecursive(self, amount: int, ...
4bc3fc901daf36615ffb6d76dc103c1fc56c9c69
alex-rantos/python-practice
/problems_solving/binaryTreeWidth.py
1,597
4.125
4
import collections """Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null. The width of one level is defined as the length between the end-node...
692a51a670300673336af200c1f4e88abb0b7133
alex-rantos/python-practice
/problems_solving/graph.py
2,537
3.890625
4
class MyGraph: """ An undirected weighted graph structure that saves all the nodes in the dictionary 'self.nodes' and the edges in an array of dictionaries (adjacency list). Each key of the 'self.nodes' dict represents the id of the node and the value is the position of that node to the array 'self.edge...
2991deeeb5aa13cc1a542f989111479f0b5680a8
alex-rantos/python-practice
/problems_solving/sortColors.py
1,248
4.21875
4
from typing import List """ Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. """ class Solu...
f43c482355400d273d09aae66ffa85269b94218e
alex-rantos/python-practice
/problems_solving/zigzag.py
1,771
3.828125
4
""" The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" """ class Solution: def convert(self, s: str, numRows...
7cdf9020906d48753005b57f3d5f9ec8bf582e7d
alex-rantos/python-practice
/problems_solving/can_construct.py
880
3.84375
4
""" Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. Each letter in the magazine string can only be used once in your ransom note. Note:...
55d9825cc8e56b92edab7c9aaa4c9cbaa07d754e
alex-rantos/python-practice
/problems_solving/invertBinary.py
686
3.8125
4
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right import copy def invertTree(self, root: TreeNode) -> TreeNode: ans = copy.deepcopy(root) def util(ansTree: TreeNode, node: TreeNo...
4d8a8b1dc9e26df64db21565ae4f6ba97d9120fd
alex-rantos/python-practice
/problems_solving/hammingDIstance.py
529
4.15625
4
""" The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, calculate the Hamming distance. """ class Solution: def hammingDistance(self, x: int, y: int) -> int: xorResult = x ^ y hd = 0 while xorResult...
6fd1b9e364aa0650e4601f0973d79e8927c8759a
alex-rantos/python-practice
/problems_solving/remove_unnecessary_lists.py
906
4.375
4
""" Extracts all inner multi-level nested lists and returns them in a list. If an element is not a list return the element by itseft """ from itertools import chain # stackoverflow answer def remove_unnecessary_lists(nested_list): for item in nested_list: if not isinstance(item,list): yield ...
ad511f56044b44dba6f64e647acdb1048f69b95b
alex-rantos/python-practice
/problems_solving/jump_game.py
1,020
4.0625
4
from typing import List """ Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. """ def can_jump(nums: List[int]) -> bool: n = len...
8d854b13fde0f1188ec2d27fff91f79d879459b2
fxalban8/Python-INPUT-Exercises
/03_personal-info.py
418
3.859375
4
#Asking for four pieces of information first_name=input("Write your first name: ") second_name= input("Write your second name: ") identity_number= input("Write your ID number: ") college= input("Write the institute where you are studying: ") space = " " #Writing a sentence with the parameters above: print("Hi "+first_...
a41dbc6c6a0968f55cd1107c4819b2c3abdd9207
elenacat-dice/Elena_Python
/NumGuess.py
532
4.0625
4
import random n = random.randint(1, 100) print("Enter an integer from 1 to 100.") guess = int(input()) while n != guess: print() if guess < n: print("Your guess is too low.") print("Enter another integer from 1 to 100: ") guess = int(input()) elif guess > n: print("Your gues...
ff80789746c490bdbdfe914f73a8047a9c4ab5c5
ChrisMuga/python-study
/functions-2.py
319
3.765625
4
# using *args to obtain positional arguments # using **kwargs to obtain key-word arguments in form of a dict def print_details(*args, **kwargs): print(args) print(kwargs) details = { "name": "Chris", "age": 25 } print_details(details, color = "Blue", marks = 90, msg="I've always loved this shirt")
4108ddc84171d6fb7f153d02e8333ad8ac385832
danuker/country-stats
/CountryRecognizer/CountryRecognizer.py
2,598
3.5
4
""" This script translates the names of countries to country codes """ from logging import warning import os import re class CountryRecognizer(): def __init__(self, code_filename=None): if code_filename is None: code_filename = os.path.join(os.path.dirname(__file__), 'country_codes.csv') ...
941110897547e1881c94116fd7f95949d41c8961
SaeSimcheon/Nomad
/asd/cht2_7_timeover.py
345
3.5
4
import sys sys.stdin = open("cht2_7_input.txt","rt") n=int(input()) def remain_counter(element): num_list=list(range(1,element+1)) check_zero=list(map(lambda x : element % x, num_list)) return check_zero.count(0) list_below_n=list(range(1,n+1)) count_list=list(map(remain_counter,list_below_n)) print(cou...
6b8faf11224d09c132f5d9897da3c33435b9a40b
zcai2/topic
/database_storing/Contents/cleaner.py
2,902
3.578125
4
''' cleaner: cleans the format of the table of contents provided ''' import re import string ''' Standardizes the contents format The reason for the complications is to ensure uniformality. Alot of the formats differ and to ensure that a majority of formats work the regular expressions have to be somewhat compli...
3b39b933005168fe29a57223c0b33dc8d57ced75
asadasivan/ssllabs-scan
/UtilityPartner.py
1,188
3.5
4
#!/usr/bin/env python import sys from collections import OrderedDict # Read all URLs or IP address from file into list def readURLListFile(URLList_File): try: fileHandler = open(URLList_File,"r") fileList = fileHandler.readlines() # read file into a list with \n return fileList except...
a765d0369eb15a4b56ea7e0d45c96b619ac69aa5
oaurbanov/yt_audio_scraper
/audioscraper/scraper/phrase_analyser.py
1,271
3.578125
4
def clean_phrase(phrase): chars_to_replace = ["¡", "!", "\"", "#", "$", "%", "&", "(", ")", "*", "+", ",", ".", ";", ":", "?", "¿", "\n", "\r"] for char in chars_to_replace: phrase = phrase.replace(char, " ") phrase = phrase.replace(" ", " ") phrase = phrase.replace(" ", " ") phrase = phra...
6861a54d712e361d37e372068dacf472f694b890
jamalzkhan/PECS
/performance_framework/Logger.py
676
3.71875
4
import logging class Logger: def __init__(self, logging, name ,extention=".log"): self.extension=".log" self.format = '[%(levelname)s] %(asctime)s - %(name)s - %(message)s' self.config = logging.basicConfig(format=self.format, level=logging.INFO) self.logger = logging.getLogger(name) def lo...
b82ad2497032c9a9134ff60dfc17cd6b968c3561
Derrick-Nyongesa/PasswordLocker
/password_test.py
4,689
3.921875
4
import unittest from password import User from password import Credential import pyperclip class TestUser(unittest.TestCase): """ Test class that defines the test cases for the user class behaviours. Args: unittest: TestCase class that helps in creating test cases. """ def setUp(self): ...
deb5b24f89c73eeb6c08e96abba8f9fefabc4eeb
raphaeluwadone/pythonex
/quadratic.py
323
3.6875
4
import math a = int(input("Input the first coefficient: ")) b = int(input("Input the second coefficient: ")) c = int(input("Input the constant: ")) ans1 = ((-b) + (math.sqrt((b**b)-(4*a*c)))) / (2*a) ans2 = ((-b) - (math.sqrt((b**b)-(4*a*c)))) / (2*a) print(f"The answers to the quadratic equation are {ans1} and {ans2...
c9e0e8158f7eba7a986ca5117c4783625b8c34d9
scottnuma/hayward-python
/autonomous.py
3,410
4.09375
4
"""Functions for controlling the HaywardBot Without a driving robot currently, testing this code is difficult. However, you can still write up code to be then tested later. The Application Programming Interface (API) documentation will definitely be very useful here: http://pie-api.readthedocs.org/api.html It'll ...
64922f96c10fd6e795169c92cde0fe95182093c1
diwakar-raj-saket/hackerrank-solutions
/python-language/Problem_Collections.OrderedDict().py
352
3.578125
4
from collections import OrderedDict n = int(input()) item_list = OrderedDict() for i in range(n): a = input() b = a.split() c = b[len(b)-1] d = a.replace(c,'') if d in item_list: item_list[d]+= int(c) else: item_list[d]= int(c) for key,value in item_list.items(): print("{a}{...
bc2d557edd934daf9603e75eb71d9ca2a4fde288
Max-creator11/OOP10
/OOP10.py
5,255
3.578125
4
import datetime class Groups: numbers_of_students = 0 stipend_percent = 1.07 default_stipend = 1040 def __init__(self, first, last, group, stipend): self.first = first self.last = last self.group = group self.stipend = stipend self.person = first +...
644edca7f635775e5cea731c2c7fa4af603f6f10
shilihui1/Python_codes
/kth_largest.py
556
3.5625
4
class Solution: def kth_largest(input_list, k): # initialize the top_k list to first k elements and sort descending top_k = input_list[0:k] top_k.sort(reverse = True) for i in input_list[k:]: if i > top_k[-1]: top_k.pop() # remove the lowest of the top k elem...
20bd0c0f04c09ad0bb8fa522b113e43c5a99c0db
shilihui1/Python_codes
/dict_forloop.py
565
4.40625
4
'''for loop in dictionary, using dictionary method a.items()''' a = {1: 'a', 2: 'b', 3: 'c', 4: 'd'} # items method for dictionary for key, value in a.items(): print(str(key) + "--" + str(value)) # keys method for dictionary for key in a.keys(): print(key) # values method for dictionary for value in a.values(...
ad427a558672615e2d1ebc529ab6bebc57cbe59e
shilihui1/Python_codes
/dict_choosevalues.py
201
4
4
''' choose the even indexed values in a dictionary, i.e., ['b', 'd']''' a = {1:'a', 2:'b', 3:'c', 4:'d'} res = [] for key, value in a.items(): if key % 2 == 0: res.append(value) print(res)
2dab63b885c45794c7934e90502170d330aaacd1
craftpip/youtube-downloader-test
/ytdl.py
5,251
3.515625
4
# line of action: # 1. get the search string from the user # 2. search it in youtube, get the first result's id, (esVRiC6s9f8) # 3. ytdl will get us the video or the audio. mp3 # 4. aac, convert to mp3, change ID3 tags. thumbnail # 5. setup selenium to read whatsapp web # read music and memes group, find message...
c95a8eae91e6d453324ec2320f6f6440757d657d
harryhk/ProgrammingCompetition
/Hackerrank/Algorithmic/search/bst.py
3,859
3.828125
4
class Node(object): def __init__(self, data): self.left = None self.right = None self.p= None self.data = data class BST(object): def __init__(self): self.root =None def insert(self, data): y = None x = self.root n = Node(data) while ...
cdc0f99f595799235a024444cc4a58c8de7e30a2
harryhk/ProgrammingCompetition
/Hackerrank/Algorithmic/tutorial/1_2.py
483
3.78125
4
#!/bin/python # Head ends here def insertionSort(ar): for i in range(1, len(ar)): insertSub(ar, i) print ''.join( [ '%s ' % (j) for j in ar]) def insertSub( ar, index ): # insert sort ar[0:index-1], ar[index] temp = ar[index] i=index while i>0: if ar[i-1] > temp : ar[i] = ar[i-1] else: ...
b7a230e883cb9145df1f8ade4bfc7a9e6c0a9d36
jdh10791/combi_tco
/scripts/helpers/pickletools.py
1,192
3.546875
4
# Tools for working with pickles import pickle def save_pickle(obj, file): with open(file,'wb') as f: pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL) print('Dumped pickle to {}'.format(file)) def load_pickle(file): with open(file,'rb') as f: return pickle.load(f) class pickle_dict(): def __init__(self,file)...
a85372c57624993f6bb3607719ddda097246d907
donovanr/napari
/napari/util/misc.py
3,566
3.9375
4
"""Miscellaneous utility functions. """ import numpy as np import inspect import itertools def ensure_iterable(arg, color=False): """Ensure an argument is an iterable. Useful when an input argument can either be a single value or a list. If a color is passed then it will be treated specially to determine ...
4a8e6f7dfaf9e79fd3e2339539aa2451e1c6d2b7
Shanarelle/feed-the-dino
/menuBar.py
6,139
3.578125
4
''' update method will be called every round of game loop. if the mouse is within the menu area then don't return until it leaves. drop down menu will appear when its representative is clicked on. most clicks will just call a function implemented in the main game module. doesn't actually work for two levels o...
ecc55c9c6ffdd128c19b3cc147e5b097459495b4
HanQ42/Snake-Game
/main.py
760
3.5
4
import turtle import parameters import borders ########## Draw Window ########## game_window = turtle.Screen() game_window.title("Snake") game_window.setup(parameters.SCREEN_WIDTH, parameters.SCREEN_HEIGHT, parameters.STARTX, parameters.STARTY) game_window.bgcolor(parameters.BACKGROUND_COLOR) game_window.tracer(0) ##...
935799d019590e694fc169742041ea9bf7e0e802
VictorChiangTW/hi
/hi.py
51
3.640625
4
name = input('What is your name') print('hi', name)
585ff3844130f15a4765ddd5461570994dfa87e0
chungjsm/python-games
/blackjack.py
3,148
3.671875
4
import random print "" print "Welcome to Mike's BlackJack Game" print "" money = 100 def dealCard(): card = random.randint(1,13) return card def valueCard(card): if card in [11, 12, 13]: return 10 else: return card def strCard(card): if card == 1: return "A" elif ca...
8e1adea55c41b22eb3b1083777085b8ed57ded10
biogui/exercicios-criptografia-rsa
/capitulo_09/exercicio_09/main.py
1,681
3.640625
4
''' Números Inteiros e Criptografia RSA - Capítulo 9. Exercício 9 - Método de Fermat para Números de Mersenne. ''' from sympy import primerange, isprime from tqdm import tqdm MODO = 1 PRIMO_MINIMO = 2 PRIMO_MAXIMO = 257 PRIMOS = list(primerange(PRIMO_MINIMO, PRIMO_MAXIMO + 1)) M = lambda p: 2**p - 1 def po...
16c5f0c1a3aecc129a1bc925d0b2f277ba9a1465
biogui/exercicios-criptografia-rsa
/capitulo_05/exercicio_16/02/main.py
894
3.859375
4
''' Números Inteiros e Criptografia RSA - Capítulo 5. Exercício 16.2 - Inverso modular . ''' def pot_mod(a, k, n): if k == 0: return 1 modulo_da_raiz = pot_mod(a, k // 2, n) modulo = (modulo_da_raiz * modulo_da_raiz) % n return (modulo * a) % n if k % 2 == 1 else modulo def inv_mod(a, p): ...
89f23f791b3b144d8892c95bd4d1d531b847897f
biogui/exercicios-criptografia-rsa
/capitulo_05/exercicio_17/main.py
756
3.9375
4
''' Números Inteiros e Criptografia RSA - Capítulo 5. Exercício 17 - Equação de congruência. ''' def pot_mod(a, k, n): if k == 0: return 1 modulo_da_raiz = pot_mod(a, k // 2, n) modulo = (modulo_da_raiz * modulo_da_raiz) % n return (modulo * a) % n if k % 2 == 1 else modulo def main(): ...
326a5e3fbdaa888842eadb233fa2d242fe5f0fc4
ssunpa/Practice-Python
/CH04/04-02gradeif.py
227
3.90625
4
# 평균 평점 3.8 이상이면 장학금 지급 대상자 grade = float(input('1학기 평균 평점은? ')) if 3.8 <= grade: print('장학금 지급 대상자입니다.') print('당신의 평균 평점 : %.1f' % grade)
382523662e51e81ba3afc39f1c1d772d1ec9c0a8
ssunpa/Practice-Python
/ProjectLab/04-pl03-printonemonth.py
469
3.65625
4
dates = int(input('한 달 최대 일수를 입력 >> ')) day = int(input('첫 날 1일의 시작 요일을 입력(0=일, 1=월, ... 6=토) >>')) day %= 7 print('\n', end=' ') for i in '일월화수목금토': print('%s' % i, end=' ') else: print('\n') cnt = 0 if day != 0: print(' '* day, end=' ') cnt += day for i in range(1, dates + 1): print('%2d' % i...
3796ba3936ec81b0c2d6cde75d721d6b9a32be70
Suraj-Mohite/Problems_on_Numbers
/prime_factor.py
164
3.796875
4
def prime_factor(no): i=2 while no!=1: if no%i==0: print(i,end=" ") no//=i else: i+=1 prime_factor(220)
83319f145a25cd3ba4d550bb92093b1467b148af
syang98/Language-Detection
/Language_Detection.py
5,924
3.609375
4
""" Author: Steven Yang This file process data to be feed into the network """ import unicodedata import string import numpy as np # We are dealing with around 570,000 words for each of the three languages we are studying # Data are lists downloaded from GitHub with open("es_full.txt", encoding="utf-8") as s: span...
438fa0b0ffe347b24eca5e15ea9ec4305a08829c
shouvikbj/Daily-Python-Challenges
/day2.py
329
3.671875
4
def pattern(n): for i in range(1, n + 1): k = i + 1 if (i % 2 != 0) else i for g in range(k, n): if g >= k: print(end=" ") for j in range(0, k): if j == k - 1: print("*") else: print("*", end=" ") n = 10 pa...
ed2ace751351b3ff301003db85a5ed0821146ed1
Maksov/geekbrains-python
/lesson04/home_work/hw04_normal.py
5,029
3.53125
4
import re from random import randint __author__ = 'Povalyaev Ivan' # Задание-1: # Вывести символы в нижнем регистре, которые окружают 1 или # более символа в верхнем регистре. # Т.е. из строки "mtMmEZUOmcq" нужно получить ['mt', 'm', 'mcq'] # Решить задачу двумя способами: с помощью re и без. def find_by_...
14342f688ab097949a0fe29720f973f30c484ca5
Maksov/geekbrains-python
/lesson04/home_work/hw04_easy.py
2,466
3.875
4
# Все задачи текущего блока решите с помощью генераторов списков! from random import randint __author__ = 'Povalyaev Ivan' # Задание-1: # Дан список, заполненный произвольными целыми числами. # Получить новый список, элементы которого будут # квадратами элементов исходного списка # [1, 2, 4, 0] --> [1, 4, 16, ...
e387457c12c9152752807d2eb87283772267454b
Maksov/geekbrains-python
/lesson03/exercises/wordcount.py
4,347
3.59375
4
#!/usr/bin/python3 """Упражнение "Количество слов" Функция main() ниже уже определена и заполнена. Она вызывает функции print_words() и print_top(), которые вам нужно заполнить. 1. Если при вызове файла задан флаг --count, вызывается функция print_words(filename), которая подсчитывает, как часто каждое слово встречае...
9de6c6484fb918a933fe19a4f8d90d0c7e4e91ed
Maksov/geekbrains-python
/lesson01/home_work/hw01_hard.py
804
4.34375
4
__author__ = 'Povalyaev Ivan' # Задание-1: # Ваня набрал несколько операций в интерпретаторе и получал результаты: # Код: a == a**2 # Результат: True # Код: a == a*2 # Результат: True # Код: a > 999999 # Результат: True # Вопрос: Чему была равна переменная a, если точно известно, что её # значение не из...
127c9866f092e40f5ac9aa182810df15708b6c4d
RM7mei/-
/9週/1_bubble.py
765
3.8125
4
#里井瑠海奈 import matplotlib.pyplot as plt data = [6, 15, 4, 2, 8, 5, 11, 9, 7, 13] x = list(range(1, len(data)+1)) def bubble(data): global x fig = plt.figure() for i in range(len(data)): for j in range(len(data) - i - 1): if data[j] > data[j + 1]: data[j], data[j + 1] = d...
e0eb4260ce3164369e45325e4eb54a450bcae0c3
Arvind-Bhakuni/Projects
/number_guessing_game/ngg.py
2,304
4
4
import sys, os import random, time def clear_window(t): time.sleep(t) try: os.system('cls') except: os.system('clear') def game(): print('Hello, Welcome to Guessing the Number Game!\n You get 3 chances to guess the number. Are you ready to play?') choice = input("Press Y to start...
19230ab98960febd17e249a42ff86c0a929049f8
diana-coman/bac-parser
/bacparser/maintable.py
1,310
3.546875
4
__docformat__ = "restructuredtext en" import lxml.etree import lxml.html import sys from .ged import get_inner_html def get_main_table(html, year): """Return the mainTable table, the one containing the results""" html = unicode(html, 'utf-8') doc = lxml.html.fromstring(html) if year <= 2011: ...
7f9983e6357e53e6868673d1d11658fa2d6e439e
mmaning/hello-world
/fib.py
594
4.09375
4
# Print fibonacci series up to n def fib(n): a, b = 0, 1 while a < n: print(a, end=' ') a, b = b, a+b print() fib(1000) # Return the N number of fibonacci series def fib1(n): if n == 0: return 0 if n == 1: return 1 else: return fib1(n-2) + fib1(n-1) #...
0e21281a5c07d6990081eafb16f747b9f4ae1d9b
Thom-ASM/Project-Euler-answers
/Problem.14.py
856
3.734375
4
#problem 14 - Longest Collatz sequence #This solution uses brute force unfortunately # You could potentially check if the number has already been in a previous sequence and then add currentChainLength # to the chain length of the matched number (although this would be faster, it would take up more memory) currentN...