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
c3411f5bb900a9d5e7fe35b9116580620656a922
Jyutt/HKIME
/hkime/distribution.py
2,061
3.984375
4
import random class Distribution(): """ This class is used to store and represent the probability distribution of n-grams. By default, we work with trigrams, that is n = 3. """ def __init__(self, n=3): self.counter = {} self.single_counter = {} self.ngram_count = 0 ...
702c3dd020a000d985bf3aa829b72d910f44f261
zzwshow/python
/learn_python/正则表达式.py
3,245
3.734375
4
#coding=utf-8 import re #findall()可以将匹配到的结果以列表的形式返回,如果匹配不到则返回一个空列表 def re_method(): s1='Hello this is joey' s2='The first price is $9.90 and the second price is $100' print(re.findall(r'\w',s1)) #[a-z-A-Z-0-9] print(re.findall(r'\d+\.?\d*',s2)) #finditer() 可以将匹配到的结果生成一个迭代器 def re_method1(): s2='T...
f31f31bd05fe96f22b02932e02e696859ecc35ae
zzwshow/python
/learn_python/排序.py
1,527
3.796875
4
#coding=utf-8 #sorted #排序也是在程序中经常用到的算法。无论使用冒泡排序还是快速排序,排序的核心是比较两个元素的大小。如果是数字,我们可以直接比较,但如果是字符串或者两个dict呢? # 直接比较数学上的大小是没有意义的,因此,比较的过程必须通过函数抽象出来。 #数字排序默认从小到大 a=sorted([22,1,-4,0,5,-2,8,3]) print(a) #sorted()函数也是一个高阶函数,它还可以接收一个key函数来实现自定义的排序,例如按绝对值大小排序: #key指定的函数将作用于list的每一个元素上,并根据key函数返回的结果进行排序(key=abs)默认将元素排序了 aa = sor...
10ed0083b0f2bd5ae3d75480a54b913bc817216b
zzwshow/python
/learn_python/file_操作.py
2,224
3.625
4
#coding=utf-8 #utf-8 :一个汉字3个字节 # #gbk:一个汉字2个字节 # #1字节等于8比特(bit) # # # #字符串转换字节类型:bytes(只要转换的字符串,按照什么编码) # s="张志伟" # n = bytes(s,encoding="utf-8") # print(n) # # #字节转换为字符串(转换上面的n) # new_str=str(n,encoding="utf-8") # print(new_str) # # #open 打开文件 # # 需要三个步骤 # # 1、打开文件 # # 2、操作文件 # # 3、关闭文件 # # #每次都要关闭文件比较麻烦,可以使用...
5fb0a33d30e2a27d245dded481abda78b1f6cfef
ksm0207/Python_study
/chapter6_python_function/part6_quiz.py
1,136
4
4
# Quiz) 표준 체중을 구하는 프로그램을 작성하십시오. # 표준 체중 : 각 개인의 키에 적당한 체중 # 성별에 따른 공식은 다음과 같습니다. # 남자 : 키(m) * 키(m) *22 # 여자 : 키(m) * 키(m) *21 # 조건 1 표준 체중은 별도의 함수 내에서 계산 # * 함수명 : std_weight # * 전달값 : 키(height), 성별(gender) # 조건 2 표준 체중은 소수점 둘째자리까지 표시 # 출력예제 # 키 175cm 남자의 표준 체중은 67.38kg 입니다 def std_...
9cd16976feb172c40ecb0b55a234dd3051654b09
dominicpeel/teambomba
/substitution/substitution.py
3,873
4
4
""" TEAMBOMBA 2017 - Proprietary Program Simple monoalphabetic substitution cracker """ """ Key is dictionary which maps each letter in the alphabet to another letter in the alphabet Creates a random initial key Then, uses a hill climbing algorithm to work out the final key. ---> Changes 2 letters in the k...
6da0f7eadbefdb603075a4920153e15cc224e449
CoderPat/CAM-MPHIL-ACS
/MLADM-17-18/proj2/data/plotdataset.py
699
3.515625
4
import networkx as nx import matplotlib.pyplot as plt import numpy as np from utils import load_data def connected_subgraph(graph, n_nodes): node = np.random.choice(graph.nodes()) visited = [] while len(visited) < n_nodes: neighbors = list(graph[node].keys()) node = np.random.choice(neigh...
4585382bfab6ba11415c68b4a2796c1d2ab8d24a
boboran/LC-python
/PathSumIII.py
1,628
3.921875
4
""" You are given a binary tree in which each node contains an integer value. Find the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes). The tree has no more than 1,000 nodes and the val...
e0ea3ae2e901556cb6b510ffa3f48596251a741a
chandralekhamaity/python-script
/learning datastrustures.py2.py
3,493
3.9375
4
# -*- coding: utf-8 -*- """ Created on Mon Aug 23 17:26:36 2021 @author: CHANDRALEKHA """ print("hare krishna") #Numbers #a=3 , b=5 #a and b are number objects #string str1 = 'Hare Krishna' str2 = 'Radhe Radhe' str1 str2 print(str1[0:5]) (str1[0:5]) print(str1[8]) print(str1[2]) print (str1*2...
d63cde2358b5c28ffc4be10947c50625b01336a3
khmelinin/AlgorithmsTeorLabs
/Lab1/Lab1.py
1,260
3.53125
4
import os import random as r n=10 list=[] worst=[] best=[] bestT=[] for i in range(n): best.append(i+1) print("Best before") print(best) bestT=best print() countB=0 for i in range(n-1): for j in range(n-1): countB+=1 if best[j]>best[j+1]: best[j],best[j+1]=best[j+1],best[j] ...
84f09908a7af42eec163df317cc7a3cd6403c9a0
pjt3591oo/exchange-crawler
/utils/t.py
548
3.78125
4
import datetime ''' 해당 패키지는 datetime 형으로 반환 ''' def getToday() : now = datetime.datetime.now() now = now.strftime('%Y-%m-%d %H:%M:00') return datetime.datetime.strptime(now, '%Y-%m-%d %H:%M:00') def converted(s) : s = s.replace('T', ' ').replace('+00:00', '') return datetime.datetime.strptime(s, '%Y-%m-%d ...
f6699e6f81a69b99d027dedf402950955da4d9f4
pjt3591oo/exchange-crawler
/test.py
642
3.515625
4
''' https://datascienceschool.net/view-notebook/c645d51f308b4047aa78e8b343a2e181/ ''' from statsmodels.tsa.statespace.kalman_filter import KalmanFilter import numpy as np import matplotlib.pyplot as plt model1 = KalmanFilter(k_endog=1, k_states=1, transition=[[1]], selection=[[1]], state_cov=[...
b0771d0fcd567ac306bf4094a1956247c1ef1444
kFurlan/Nuvem_Prova1
/par_impar.py
361
3.765625
4
n = int(input()) numeros_par = [] numeros_impar = [] for i in range(n): numero = int(input()) if numero % 2 == 0: numeros_par.append(numero) else: numeros_impar.append(numero) numeros_par.sort() numeros_impar.sort(reverse=True) for par in numeros_par: print(par) for impa...
54982d8d26405884c75052ce0243e2d7f7594c37
izza-khalid/ICS3U-Unit5-02-Python
/multi_funct_area.py
823
4.03125
4
#!/usr/bin/env python3 # Created by: Izza Khalid # Created on: November 2019 # This program calculates area of a triangle def area(height, base): # calculates area of a triangle # process triangle_area = (height * base)/2 # output print("") print("The area of the triangle is {0} cm^2".forma...
72abbb6b17523969eb1d366a828d65f5e40a5d4d
duttashi/scrapers
/scripts/python/scrp_init_fundamentals_of_requests_and_beautifulsoup.py
8,178
3.71875
4
#!/usr/bin/env python # coding: utf-8 # #### Introduction # # The [requests](https://2.python-requests.org/en/master/) library is the de facto standard for making HTTP requests in Python. It abstracts the complexities of making requests behind a beautiful, simple API so that you can focus on interacting with services...
9f9c62ca07dcd7399c9fcfb607023f988b66bee4
duttashi/scrapers
/scripts/python/scrp_init_indeed_website_scraper.py
5,444
3.828125
4
# Objective: Create a beautifulsoup based scraper. # Website to scrape: www.indeed.com.my # What to scrape: extract the job posting details like position name, salary and location. # required libraries import requests from bs4 import BeautifulSoup as soup import pandas as pd # create list of cities in Malaysia from ht...
a3ad742f0c922e4d1d9bc3f10a9523d05bf2d609
duttashi/scrapers
/scripts/python/scrp_init_requests_L01.py
628
3.640625
4
# load required libraries import requests from bs4 import BeautifulSoup as bs # define the webpage address to access URL = 'https://en.wikipedia.org/wiki/Main_Page' response = requests.get(URL) if(response.status_code == 200): print("Success, able to connect to page") # show the page content #print(respon...
5918bf11b7e38fb0577e490489a3a10cabbc79f5
SkullSec/Python-Study
/desafio006.py
205
3.6875
4
idade = 20 #frase = 'Parabens pelos ' + idade + " anos"' frase = 'Parabens pelos ' + str(idade) + ' anos' print(frase) ''' Existe a necessidade de converter a variasvel int em string. '''
0aa32dda923372e560b61e03e717386918c9b90a
SkullSec/Python-Study
/desafio032.py
193
3.703125
4
pessoas = ['joao', 'maria', 'mateus', 'marta'] for pessoa in pessoas: print('\n' + pessoa.title() + ' e bem tranquila' ) print('E sempre bom ter ' + pessoa.title() + ' por perto!')
a3ca2b1a7591e12ee46e8831ab91784a2bb16ce1
ZohanHo/ClonePPZ
/all python/lesson 27.py
1,113
4.09375
4
"""""" """ Функции списков Функции all и any, часто используемым в условных инструкциях, можно присваивать список в качестве аргумента; значение True возвращается, когда любой их аргумент (или соответственно все аргументы) возвращает True, в противном случае False. Функция enumerate может быть использована для одноврем...
3203bac3e8d5c1d4a2803e7334bb2f09f1f3e51a
ZohanHo/ClonePPZ
/all python/lesson 38.py
3,651
3.515625
4
"""""" """ Множества set - это неупорядоченные наборы простых объектов, они немогут быть проиндексированы, также они немогут иметь дубликаты Множества восновном используют для проверки на вхождение и устранения дубликатов Они необходимы тогда, когда присутствие объекта в наборе важнее порядка или того, сколько раз данн...
db25359cb2fb8c20efd6093a0392a5c1dd455abc
ZohanHo/ClonePPZ
/all python/lesson 23.py
1,308
4.28125
4
"""""" """Функция zip - В Pyhon функция zip позволяет пройтись одновременно по нескольким итерируемым объектам (спискам и др.):""" a = [10, 20, 30, 40] b = ['a', 'b', 'c', 'd', 'e'] for i, j in zip(a, b): print(i, j) # 10 a # 20 b # 30 c # 40 d """ Здесь выражение zip(a, b) создает объект-итератор, из которого...
9f595cfb85fdc9fa2dd1134556af62e4621eb4f7
ZohanHo/ClonePPZ
/OOP/__str__.py
596
3.59375
4
class Fructs: #def __init__(self, weight): #Cоздать через конструктор #self.w = weight def set(self, weight): #Создать через обычый метод, который нужно вызввать self.w = weight def __str__(self): return "Вес яблок {} кг.".format(self.w) #Вернуть нужно обязательно str (строку) ...
15daf24ebe659e6faf52747c80b2d7a95fdc8c9a
ZohanHo/ClonePPZ
/all python/lesson 16.py
958
3.75
4
"""""" """Открытие файлов""" myfile = open("file.txt", "r") # Открыли фаил в режиме чтения с помощюц фунции open, указуем два параметра, имя файда и режим (чтение, запись) cont = myfile.read((100)) # Читаем фаил, присваиваем переменной, аргументом передал сколько байт прочитать cont1 = myfile.readlines() # Читаем фаи...
14da7c09a3646871f41cb3f88eba4d97557b01c6
ZohanHo/ClonePPZ
/OOP/Статические переменные.py
1,120
4.0625
4
class Car: #print(Car.__bases__) #Класс наследован от object s = 50 # Статическая переменная def __init__(self): #Обьяляю переменные сразу, их не нужно передавать при создании класа self.x = 10 self.y = 20 self.z = 30 bmv = Car() print(bmv.x) # равно 10 print(bmv.s) # равно 50 mazd...
5e68232272e26ca25fe4f58fb1dc92e58829c0b5
ZohanHo/ClonePPZ
/all python/lesson 7.py
1,689
3.921875
4
"""""" """Цыкл while""" i = 5 while i > 0: print(i) i -= 1 if i == 2: break print("Finish") print ("-------------") number = 23 running = True while running: guess = int(input('Введите целое число : ')) if guess == number: print('Поздравляю, вы угадали.') running = False #...
a071904bc233e29d20c406bbe5d3305c248a3d5b
ZohanHo/ClonePPZ
/all python/lesson 65.py
2,416
4.4375
4
"""""" """Полиморфизм, когда обьект в разных ситуациях ведет себя по разному""" class VectorClass: def __init__(self, x, y): self.x = x self.y = y #def multiplay(self, v2): # В Функцию прийдет обьект класса как аргумент, но мы будем использовать магичесуий метод def __mul__(self, other): #...
c244410a4811613c4a5c0cd7fcce37f90c02e24d
Murphy-Joe/Data_and_Algo
/assn8_merge_sort.py
799
3.625
4
import random import copy def merge_sort(ls): # base case -- a list of 0 or 1 is already "sorted" if len(ls) <= 1: return ls else: median_index = len(ls) // 2 left = ls[:median_index] right = ls[median_index:] left_srt = merge_sort(left) right_srt = merge_so...
597b027d3d976b57752cdde02523a13a4522c273
Murphy-Joe/Data_and_Algo
/assn9/graph.py
1,358
3.75
4
import random from pprint import pprint num_verts = 10 g = {} used = [] vertices = {i for i in range(1,num_verts+1)} # subroutine: vertex may only be used as a neighbor by 3 other vertices AND it can't use itself as a neighbor def eligible_neighbor(used_list, current_vertex): num = random.randint(1,num_verts) ...
a85ecdbfc7049a9dd17ee68a4a6312e4911ce2b0
VanessaKnox/Useful-Repository
/Day007-Python1/mySecondPython.py
361
3.609375
4
animal = input("Please enter an animal: ") number = int(input("Please enter a number: ")) answer = input(f"Do you have {number} {animal}s in your pocket? ") if(answer == 'Y'): inPocket = True elif answer == 'Yes': inPocket = True else: inPocket = False # doesn't work result = "fred" + 1 result = animal + ...
298ddcc1f81486235cd6223984d2d6af634b6ce3
VanessaKnox/Useful-Repository
/Day009-Python3/06-Functions.py
534
3.96875
4
def MySubName(name): print("Hello " + name) def Multiply(num1, num2): return num1 * num2 def House(address, sqFootage = 1200, price = 0): print(address, str(sqFootage), "$" + str(price)) House("123 Habitat") House("123 Free St", 2400) House("123 Street", 1000, 250000) MySubName("dino") x = Multiply(5,...
da3975575b61d090a3dcf71d1313b09649b0fa27
JoshuaBevers/DigitalCrafts-Week-1
/madlibs.py
1,030
3.84375
4
with open('madlib_read_file.txt') as f: flat_list=[word for line in f for word in line.split()] emptyString = "" addTo = "" for word in flat_list: addTo = " " if word == "(adjective)": newWord = input("Please enter an adjective") addTo += newWord if word =...
0e4b609f98f22d560ec24f8242709d4e4105da00
lsimakova/python
/basics/loop_of_things.py
142
3.65625
4
for i in [1, 2, 3, 4]: print(i) for j in range(0, 5): print(j) sum = 0 for x in range(0, 1000 * 1000): sum = sum + x print(sum)
4066143d32e4983f97e24986056773d1db141011
khan-talha/projects
/art1.py
2,302
3.515625
4
from selenium import webdriver import pandas as pd import time #Writing our First Selenium Python Test web = 'https://sports.tipico.de/en/all/football/spain/la-liga' #you can choose any other league (update 1) path = '/Users/Talha Khan/Desktop/Python/chromedriver_win32/chromedriver' driver = webdriver.Chrome(path) dri...
13bc1d732bf230410632ae7ac075db3caa9d74aa
llichee/python_study
/break&continue.py
1,314
3.53125
4
#!/usr/bin/env python #_*_coding:utf-8 _*_ class Hero(object): """ 定义一个英雄类,可以移动和攻击 """ #创建对象时,会默认执行构造函数 __init__() #如果没有重写构造函数,python或默认创建一个什么都不做的构造函数 #一个类里面必须有一个构造函数 #魔法方法:两个下划线开头、两个下划线结尾; #在类里面不需要手动调用,而是某些情况下自动执行的方法; def __init__(self): """python里的构造函数就是 __init__()""" #构造函数: __init__()构造函数是一个特殊的函数,在类实例化...
9e8e41ecab86d6f4fd040f56e0d0fa7e0760a3eb
biagimarco/hmm-fitter
/Example2.py
808
3.53125
4
# Example of fitted HMM and sampling # 1- we create an HMM fitting it from data # 2- we extract some samples from the fitted model import numpy as np from hmmlearn import hmm np.random.seed(42) states = ["Rainy", "Sunny"] n_states = len(states) observations = ["walk", "shop", "clean"] n_observations = len(observatio...
8b31f3413ef0a1a25f34c7bd2503268d5cd6d97a
kabeer1choudary/billing-software-repo
/add_to_db.py
4,959
3.640625
4
from tkinter import * import sqlite3 import tkinter.messagebox as msgbx connection = sqlite3.connect("F:\Python_Files\Billing Software\Database\store_db.db") c = connection.cursor() res = c.execute("SELECT Max(id) from inventory") for r in res: id = r[0] class Database: def __init__(self, master, *args, **kwa...
7c8e5b58f24f323ee93bdc28f3651fdf177ad56c
Ellie2020-ellie/Hogwarts_works
/Ellie/shujuleixing/xxx.py
951
3.53125
4
class Singleton(type): def __init__(self, *args, **kwargs): print("in __init__") self.__instance = None super(Singleton, self).__init__(*args, **kwargs) def __call__(self, *args, **kwargs): print("in __call__") if self.__instance is None: self.__instance = su...
d5832504958a890cc03f35b762851777588c95fe
Ellie2020-ellie/Hogwarts_works
/Ellie/suanfa/kuaisu_paixu_suanfa.py
585
3.859375
4
def quick_sort(arr, first, last): if first >= last: return mid_value = arr[first] low = first high = last while low < high: while low < high and arr[high] >= mid_value: high -= 1 # 游标左移 arr[low] = arr[high] while low < high and arr[low] < mid_value: ...
c716680a3c450185f4545e974d7271ee300155bd
Dev-Srikumar/Python-CodeWars
/NumberofPassengersinBus.py
257
3.53125
4
def number(bus_stops): passengers = 0 for i in bus_stops: #print(i[0],i[1]) for j in range(0,len(i)): if j==0: passengers += i[j] else: passengers -= i[j] return passengers
4429045bc4dad82164bbc66df21b376fc08ec7f3
alejandrodgb/project_euler
/P4.py
687
3.890625
4
#!/usr/bin/python def simetric(n): n=str(n) if n[0:len(n)/2]==n[len(n)/2:len(n)][::-1]: return True return False def palindromes_list(max,min): palindromes=[] for i in range(max*max,min*min,-1): if simetric(i)==True: palindromes.append(i) return palindromes def pal...
f6584d2b0701b1b7f95829f1b416f05bceac6d36
TinkerYxs/PythonMachineLearning
/PythonTest/src/RidgeRegress.py
1,577
3.53125
4
# This Python file uses the following encoding: utf-8 # 岭回归 import mglearn from sklearn.cross_validation import train_test_split from sklearn.linear_model import Ridge X,y = mglearn.datasets.load_extended_boston() X_train,X_test,y_train,y_test = train_test_split(X,y,random_state=0) ridge = Ridge().fit(X_trai...
33806919b6f0bb916b87665409e7d4b97edb84f3
anku255/Interviewbit
/Programming/Linked List/remove_duplicate_sorted_list.py
1,196
3.921875
4
class Node: def __init__(self, data, next=None): self.next = next self.val = data def __repr__(self): print('node.val', self.val) class LinkedList: def __init__(self): self.start = None def add(self, data): newNode = Node(data) if self.start == None: self.start = self.end = ne...
911af638af29b8436ae441f05c5fa4d34bac17d0
anku255/Interviewbit
/Programming/Arrays/mergeOverlappingIntervals.py
986
3.53125
4
class Interval(): def __init__(self, start, end): self.start = start self.end = end class Solution(): def merge(self, A): A = sorted(A, key=lambda x: x.start) result = [A[0]] for i in range(1, len(A)): prev = result[-1] current = A[i] if current.start <= prev.end: r...
e29e7a53da52d1b78582d34fee0359c8604dae40
SUHONGJIAN/leisure-time
/Python learning/Pycharm_project/Third.py
329
3.6875
4
#开发人员 :Hongjian SU #开发时间 :4/19/2019 #开发工具 :PyCharm import datetime a = "Ericsson" b = "Hongjian SU" c = input("Note: ") c = "Note: " + c d = datetime.datetime.now() fp = open(r'Test_internal.txt', 'a+') print(a, b, "\n", c, "\n", d, file=fp) print(chr(38)) fp.close() ''' 就是 添加点 备注 '''
c8a4e387883c143f0d2cf6fde6d74f0ef1e17f78
denisinberg/python_task
/if_else_task(name).py
718
4.125
4
a=int(input('Введите возраст Андрея: ')) b=int(input('Введите возраст Борис: ')) c=int(input('Введите возраст Виктор: ')) if a>b and a>c: print('Андрей старше всех') elif b>a and b>c: print('Борис старше всех') elif b<c>a: print('Виктор старше всех') elif a==b>c: print('Андрей и Борис старше В...
efb5e174403ae900b61f0ae17093f61f2a7cf837
pguiffr62/Engineering_4_Notebook
/Python/QuadraticSolver.py
749
4.03125
4
print("Quadratic Solver") #prints initial message print("Enter the coefficients for ax^2 + bx + c = 0") import math import cmath def quadratic(): #quadratic function a=int(input("enter a: ")) #inputs for quadratic values b=int(input("enter b: ")) c=int(input("enter c: ")) d=((math.pow(b,2))-(4*a*c)) #calculates ...
534a8e7881c0c99c4fcbed684c742e3c1e2a5e7d
ShailjaPythonClass/shailja_python
/week_05/features.py
927
3.53125
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 26 14:54:34 2017 @author: jzuber """ import string import unicodedata def _to_ascii(name): name = unicode(name.lower()) return unicodedata.normalize('NFD', name).encode('ascii', 'ignore') def _vowel_count(name): temp = _to_ascii(name) return sum(map(temp...
468a104d2e256f2f2505e453ba923c3df2e05db5
QBA96/synapsi
/tasks/task_2.py
524
3.984375
4
letters = {1:"", 2: "abc", 3: "def", 4: "ghi", 5: "jkl", 6: "mno", 7: "prst", 8: "tuv", 9: "wxyz", 0: "+" } def combine(letters:dict, input:str): """create combination from letters letters[dict] -> dict with letters from phone input[str] -> string with key number from phone return[list] ...
4fa89b91350bafe6055d8f9b8105669c1a23ea04
GameGamer43/class_proj10
/proj10-working.py
4,242
3.640625
4
#!/usr/bin/env python import sys from event import Event from eventList import EventList #global debug var to help us seperate debug output debug = True ev = EventList() e = Event() def readFile(filename): contents = '' fileList = [] try: with open(filename) as openFile: contents = o...
bf6d3f81f6804c01af3f699c55f36a8a61a334de
sustainable-processes/centripeta
/centripeta/utils/csv_utils.py
1,155
4.0625
4
""" JSON Wrappers .. moduleauthor:: Graham Keenan <https://github.com/ShinRa26> """ import csv def read_csv(filename, delimiter=","): """Reads a CSV file, returning the column names and data Arguments: filename {str} -- Name of the csv file to read Keyword Arguments: delimiter {str} -- ...
e96ebcfd692fc08332fbee681f0ef0f3ec8f8a27
mackenziekira/interview_cake
/completed/max_stack.py
1,539
4.03125
4
class Stack(object): # initialize an empty list def __init__(self): self.items = [] # push a new item to the last index def push(self, item): self.items.append(item) # remove the last item def pop(self): # if the stack is empty, return None # (it would also be ...
1e01d50908db7e5cfcfc035e442e7df9bf2f743d
rafalsikora/PITE_FitBox
/NoiseGenerator.py
448
3.625
4
# Class representing random number generator # following gaussian distribution of given width (sigma). # Can be easily extended to draw numbers from any other distribution. import random class NoiseGenerator: def __init__(self, sigma): self.sigma = 1 self.setSigma(sigma) def __call__(self):...
8da0eff550d0a7ebd436609e472eec25b7a1daa5
JuicyJerry/Python---OOP-Primary_Concepts-
/PythonOOP(SOLID)/03.리스코프_치환_원칙(Liskov_Substitution_Principle)/02.행동_규약을_어기는_자식_클래스.py
1,772
4.125
4
"""자식 클래스가 부모 클래스의 의도와 다르게 메소드를 오버라이딩 하는 경우""" class Rectangle: """직사각형 클래스""" def __init__(self, width, height): """세로와 가로""" self.width = width self.height = height def area(self): """넓이 계산 메소드""" return self.width * self.height @property def width(self)...
0965c458c077c9cbc19925b1c822c6ab00adae14
ospahiu/Code_golfs
/alpha_tri_golf.py
984
3.671875
4
# Code golf attempt for printing out alpha triangle. # Link -> http://codegolf.stackexchange.com/questions/87496/alphabet-triangle # 1st Golf s="ABCDEFGHIJKLMNOPQRSTUVWXYZ"*2 for i in range(51): print(s[:-i-1]+s[-i-3::-1],s[:i]+s[i::-1])[26>i] # 2nd Golf for i in range(51): print s[:i]+s[i::-1]if 26>i els...
204d60c36ece255c08d593bccaa68329e9615614
mmanfrin/cenapad_py
/aula1/task2.py
151
3.734375
4
#Exercício 2: retorne o último sobrenome da string nome nome = "Fulano da Silva" sobrenome = nome.split(sep=' ') print(f'\nO sobrenome é: {sobrenome[-1]}')
577fb1187eea8d0fde81772dbd361aae98952086
carteras/ucssc_public
/Semester 1/Information Technology/exam_t1_2021/long_answer.py
256
3.828125
4
words = ['bob', 'fred'] def is_isogram(word): # out = False set_of_word = set(word) for letter in set_of_word: if word.count(letter) > 1: return False return True def is_palindrome(word): return word == word[::-1]
5a41c268b922c61c708c3da4b34efc7d42018d8c
carteras/ucssc_public
/Semester 1/Digital Technologies - Digital Solutions/T2/path_walking/path_walking_demo.py
449
3.640625
4
from pathlib import Path directories = [Path().cwd()] def walk(directory_name): for path_object in directory_name.glob("*/*"): if path_object.is_file(): print(f'Hey, {path_object} is a file!') elif path_object.is_dir(): directories.append(path_object) # if path_...
3fbdbe0a62cc3809a4c4a170be2d635e728a5d4b
litesaber15/verbal_irony
/aligned_antonym_detect/count_negations.py
1,218
3.734375
4
""" Prints number of sentences with negations markers Sentences that match this filter are saved to .log file Usage: python count_negations.py data_file negations.txt """ import sys import datetime from utils import file_iterator, parse_corpus_line, load_negations if __name__ == '__main__': data_file = sys...
4755e58075c76b5ce66517f7ede9aa42ef7bf84d
litesaber15/verbal_irony
/aligned_antonym_detect/check_aligned_antonyms_dev.py
4,163
3.5
4
""" Prints number of sentences with aligned antonyms Sentences that match this filter are saved to .log file Usage: python check_aligned_antonyms_dev.py \ dev.txt alignments.txt antonyms.txt \ antonym_prefixes.txt """ import sys import datetime from utils import file_iterator, parse_alignm...
5de721579c27704e39cf12b1183a1eebea4d22d4
lion137/Python-Algorithms
/shuffling.py
441
4.1875
4
# algorithm for shuffling given subscriptable data structure (Knuth) import random def swap(alist, i, j): """swaps input lists i, j elements""" alist[i], alist[j] = alist[j], alist[i] def shuffle(data): """randomly shuffles element in the input data""" n = len(data) for token in range(n - 1): ...
3553584f16c36c3dc9b1372781ab34522962fab7
eoin18/AdventOfCode2017
/day7/part1/discs.py
814
3.703125
4
#!/usr/bin/env python class Node(object): def __init__(self, value): self.value = value self.parent = None self.children = [] def __eq__(self, other): return self.value == other.value def main(): nodes = {} with open('data.txt') as f: lines = f.readlines() for line in lines: split = line.split(' ...
537a404f38e979aef07e36b24e2d8d07fd15e9b2
mrcosta93/euler_project
/problem4.py
498
3.546875
4
def reverte(x): return x[::-1] n1 = 999 n1max = 0 n2 = 999 n2max = 0 maior = 0 resultado = str(n1*n2) reverso = reverte(resultado) while n1 > 99: while n2 > 99: resultado = str(n1*n2) reverso = reverte(resultado) resultado = int(resultado) reverso = int(reverso) if resultado =...
36a037db2f2800fb8041224fb342e376afc5b3cf
kamondemwangi/learning-python
/DNAToolkit.py
3,437
3.671875
4
import collections from sequences import * #function for validating if DNA or not def validateSeq(dna_seq): tmpseq = dna_seq.upper() for nuc in tmpseq: if nuc not in Nucleotides: return False return tmpseq #function for counting DNA seq length def countNucFrequency(seq): tmpFreqDict...
f882f9dcf344950cc893bf1e2fb49ffb103d168e
chenjyr/AlgorithmProblems
/HackerRank/Search/FindTheMedian.py
1,652
4.3125
4
""" In the Quicksort challenges, you sorted an entire array. Sometimes, you just need specific information about a list of numbers, and doing a full sort would be unnecessary. Can you figure out a way to use your partition code to find the median in an array? Challenge Given a list of number...
0adf7ed3f2301c043ef269a366a90c3970673b1f
chenjyr/AlgorithmProblems
/HackerRank/Sorting/Quicksort1.py
2,143
4.21875
4
""" The previous challenges covered Insertion Sort, which is a simple and intuitive sorting algorithm. Insertion Sort has a running time of O(N2) which isn’t fast enough for most purposes. Instead, sorting in the real-world is done with faster algorithms like Quicksort, which will be covered in these...
248f5308062ddc2b896413a99dc9d5c3f3c29ac6
chenjyr/AlgorithmProblems
/HackerRank/Sorting/InsertionSort2.py
1,852
4.625
5
""" In Insertion Sort Part 1, you sorted one element into an array. Using the same approach repeatedly, can you sort an entire unsorted array? Guideline: You already can place an element into a sorted array. How can you use that code to build up a sorted array, one element at a time? Note that in the first step, wh...
c2098e9dd0710577a8bcac533b34b3bbee7b3a19
NishuOberoi1996/IF_ELSE
/num_alph_chatr.py
206
4.15625
4
num=input("enter anything:-") if num>="a" and num<="z" or num>="A" and num<="Z": print("it is a alphabet") elif num>="0" and num<="9": print("it is number") else: print("Special Character")
f545439778efdfeae5b034c34eac60cef4714dab
NishuOberoi1996/IF_ELSE
/vote.py
108
3.796875
4
age=int(input("enter the age:-")) if age>=18: print("eligible for vote") else: print("not elible")
5c11ff078795e8f2f5ad752708cf4a36cf2a57b6
NishuOberoi1996/IF_ELSE
/leap_year.py
233
3.953125
4
# year=int(input("enter year:-")) # if year%100==0 and year%400==0 or year%4==0: # print("leap year") # else: # print("ni hai") year=int(input("enter year:-")) if year%4==0: print("leap year") else: print("ni hai")
c8a88f03565785ea7b7f0f381b622d4b4db0e6eb
NishuOberoi1996/IF_ELSE
/reverse.py
230
3.78125
4
num=int(input("enter the number:-")) first=(num//1)%10 second=(num//10)%10 third=(num//100)%10 fourth=(num//1000)%10 reverse=(first*1000)+(second*100)+(third*10)+(fourth*1) if num>1000: print(reverse) else: print("error")
061fd52c10a3ae735e6c99c0e8a690e649dccc3a
shaderkill/Registro-libros
/Clases/libros.py
1,954
3.8125
4
# -- Creación de la clase objeto Libro. lugares = {'ASIA': .7, 'AMERICA': .10, 'EUROPA': .14} class libro(object): def __init__(self, isbn, titulo, categoria, fecha_publicacion, lugar_publicacion, estado, idioma, autor, editorial, cantidad_pag, precio): global lugares ...
89431dc0c092bbec0580f344f73ea5f4e2dcdf75
kevba/aoc2019
/day10/part1/main.py
2,603
3.796875
4
import timeit import math from fractions import Fraction PUZZLE_INPUT_PATH = "../input.txt" ASTEROIDS = [] MAX_WIDTH = 0 MAX_LENTH = 0 class Asteroid(): def __init__(self, x, y): self.x = x self.y = y self.atans_1 = [] self.atans_2 = [] self.atans_3 = [] self.atan...
8c8da9e1a61a6d6d78a2535e2b1bbda1a31b8b17
hhoangnguyen/mit_6.00.1x_python
/test.py
508
4.3125
4
def insertion_sort(items): # sort in increasing order for index_unsorted in range(1, len(items)): next = items[index_unsorted] # item that has to be inserted # in the right place # move all larger items to the right i = index_unsorted while i > 0 and items[i - 1] > next...
538429e4bab6a2971d98376798d9dc9f202852e7
hhoangnguyen/mit_6.00.1x_python
/week_5/animal.py
1,749
4.0625
4
class Animal(object): def __init__(self, age): self.age = age self.name = None def get_age(self): return self.age def get_name(self): return self.name def set_age(self, new_age): self.age = new_age def set_name(self, new_name=""): self.name = new_n...
08b1c52901da46b2e7beb41246effc65ed9b4d3f
hhoangnguyen/mit_6.00.1x_python
/week_1/1_1.py
713
4.15625
4
""" Assume s is a string of lower case characters. Write a program that counts up the number of vowels contained in the string s. Valid vowels are: 'a', 'e', 'i', 'o', and 'u'. For example, if s = 'azcbobobegghakl', your program should print: 5 """ string = 'azcbobobegghakl' def is_valid_vowel(char): if char == ...
61624c80484b0a1e9cceb5c08dd81882db18936e
hhoangnguyen/mit_6.00.1x_python
/week_5/Fraction.py
784
3.96875
4
class Fraction(object): def __init__(self, numer, denom): self.numer = numer self.denom = denom def __str__(self): return str(self.numer) + ' / ' + str(self.denom) def getNumer(self): return self.numer def getDenom(self): return self.denom def __add__(self...
9e7ea03784f9b7ea297930be90a6288de5096a11
hhoangnguyen/mit_6.00.1x_python
/week_3/tuples.py
283
4.03125
4
te = () t = (2, 'one', 3) print(t) print(t[0]) print(t + (5, 6)) print(t[1:2]) # return extra ',' means this is a tuple with a single element print(('one')) # return a string print(('one', 3)) x = 3 y = 2 (x, y) = (y, x) print(x, y) x = (1, 2, (3, 'John', 4), 'Hi') print(x[0:-2])
a096c5ef684c0d0800383fb7eb5529a0f0b7f1bb
hhoangnguyen/mit_6.00.1x_python
/week_3/3_3.py
680
3.984375
4
import string def getAvailableLetters(lettersGuessed): ''' lettersGuessed: list, what letters have been guessed so far returns: string, comprised of letters that represents what letters have not yet been guessed. ''' # list to store alphabet letter_list = list(string.ascii_lowercase) ...
511d8bd606c08ea5fba854a8bf8bc2bd1559a3cf
dolphinsboy/algorithem
/python/chapter1/1_2.py
266
4.0625
4
def is_even(k): while k > 1: k = k - 2 if k == 0: return False elif k == 1: return True def is_even_bit(k): return True if k & 1 else False print is_even(10) print is_even(11) print is_even_bit(10) print is_even_bit(11)
8a47b30a4c9f6baa48417bcccd980f19fd9fc205
dolphinsboy/algorithem
/python/chapter1/1_1.py
142
3.84375
4
def is_multiple(n, m): if n % m == 0: return True else: return False print is_multiple(10,2) print is_multiple(10,3)
f2ad1d81919c851a1791e04834c451912b83698e
advikchava/python
/learning/Factor finder.py
322
4
4
n=str(input("Enter your name:")) p=str(input("Enter Password:")) if (p=="Avengers"): num=int(input("Enter a number:")) print("Factors of the given number {0} are".format(num)) for value in range (1,num+1): if (num%value == 0): print("{0}" .format(value)) else: print("Wrong Password",...
655a5b9cf59b58bde19148bbae7ad6650fe23374
advikchava/python
/learning/ms.py
484
4.21875
4
print("1.Seconds to minutes") print("2.Minutes to seconds") ch=int(input("Choose one option:")) if ch==1: num=int(input("Enter time in seconds:")) minutes=int(num/60) seconds=int(num%60) print("After the Seconds are converted to Minutes, the result is:",minutes,"Minutes", seconds,"Seconds") elif ch==2...
d28893e4ff6d044435f1e5574d6caca8d59d00ad
mingueyun/rangedrill_python
/range.py
235
4.03125
4
mins = [1] mins_len = len(mins) for i in range(0,4,1): print(i) mins = [1,2,3] mins_len = len(mins) for i in range(3,-1,-1): print(i) mins = [1,2,3] mins_len = len(mins) for i in range(8,1,-2): print(i)
17d669ffc8c0dc8520542c5cd43c9efcbc3b75db
IcarusKel74/IcarusKel74
/Untitled-1.pyer.py
583
4.03125
4
name_var = input("Name Please?") if (name_var.find("w") == len(name_var) -1): print("Found") def add_nums(first, Second): return first + Second result = add_nums(1, 2) print(result) if (name_var == "Matt"): print("Hi Matt") else: print("Who tf is " + name_var) if (name_var.find("M") != -...
8f04afc5c6ca9a92a4b272e9482d4f0eaaf88102
AdamBalint/Dominion
/dominion/agent.py
8,709
3.921875
4
import random import click class Agent(object): def __init__(self): '''Base agent class. Agents are used to make decisions for each player in the game. Custom agents can be created by inheriting this class and modifying the decision functions.''' pass def _get_game_state(self...
b218621d1123bf6a9cb035fa8fce7527ac412d77
npnkhoi/Logo-detector
/models/detect_bottle.py
2,117
3.53125
4
import cv2 as cv def detect_bottle(im, thresh_low=90, thresh_high=200, contour_cutoff=300, thresh_label_size=100, contours_to_check=10): """ Detects whether a bottle is present. Parameters: - url: image lin...
f2ee5b62250e6c353f62bd53972aec031a1474d4
jamesjiang52/10000-Lines-of-Code
/python/2015day11part1.py
1,494
3.859375
4
# -*- coding: utf-8 -*- """ Created on Wed Jan 3 15:07:30 2018 @author: James Jiang """ input = 'hepxcrrq' letters = [letter for letter in 'abcdefghijklmnopqrstuvwxyz'] illegals = ['i', 'o', 'l'] def increment(string): if string[-1] != 'z': chars = [char for char in string] chars[-1] = letters[...
806a7edf13a09d37caf1aab686dd942f3b16b9e9
jamesjiang52/10000-Lines-of-Code
/python/2017day15part1.py
453
3.515625
4
# -*- coding: utf-8 -*- """ Created on Thu Dec 14 23:58:31 2017 @author: James Jiang """ start_a = 783 start_b = 325 def next_a(n): num = (16807 * n) % 2147483647 return(num) def next_b(n): num = (48271 * n) % 2147483647 return(num) a = next_a(start_a) b = next_b(start_b) count = 0 x = 0 w...
96b548c090a467d9f7cbef7a3c58054e554be03e
jamesjiang52/10000-Lines-of-Code
/python/2015day12part1.py
594
3.609375
4
# -*- coding: utf-8 -*- """ Created on Wed Jan 3 15:35:45 2018 @author: James Jiang """ with open('Data.txt') as f: for line in f: string = line def is_int(n): try: int(n) return True except ValueError: return False def sum_string(input_string): sum = 0 for i in...
6a57e7ccc768959ed59c86778a46c2a771e1788d
jamesjiang52/10000-Lines-of-Code
/python/2017day22part1.py
2,075
3.640625
4
# -*- coding: utf-8 -*- """ Created on Thu Dec 21 22:25:08 2017 @author: James Jiang """ all_lines = [line.rstrip('\n') for line in open('Data.txt')] grid = [[i for i in line] for line in all_lines] x_position = int((len(grid) + 1)/2) - 1 y_position = int((len(grid) + 1)/2) - 1 direction = 'up' def turn_left(input...
a9f1a553826aff9d33dd8358b07bcbce25bdd044
jamesjiang52/10000-Lines-of-Code
/python/2016day21part2.py
2,191
3.671875
4
# -*- coding: utf-8 -*- """ Created on Sat Dec 30 00:23:31 2017 @author: James Jiang """ all_lines = [line.rstrip('\n') for line in open('Data.txt')] all_instructions = [line.split(' ') for line in all_lines] all_instructions.reverse() password = [i for i in 'fbgdceah'] def rotate_right(input, amount): amount =...
6304d092f954722e9e1c7d3b5b8ec8f7c98ceb67
Abhiprudent677/Rail_run
/rail.py
984
3.984375
4
import math lat = [2,14,4,5,6,7,8,9,10] lng = [2,14,4,5,6,7,8,9,10] def distance(x1,y1,x2,y2): return(math.sqrt(((y1-y2)**2) + ((x1-x2)**2))) def run(): for i in range(2): lat1 = lat[i] lng1 = lng[i] distance1 = distance(lat1, lng1,2,2) distance2 = distance(lat1, lng...
f5e06e5f3bbea772294cef61d853415f6cf0dc29
CyanGirl/Automation-scripts
/time_zone_conversion/time_zone.py
1,619
4.1875
4
class InvalidHours(Exception): """Invalid""" pass class InvalidMins(Exception): """Invalid""" pass # Taking user input starting_zone = input("Enter starting zone: ") time = input("Enter time: ") end_zone = input("Enter desired time zone: ") lst = time.split(":") hours1 = int(lst[0]) mins1 = int(lst...
af2a774cbbb1e1881dc82e195da571344c44cfd7
spizzirri/AlgebraLinealAplicadaConPython
/pca.py
4,263
3.546875
4
import numpy as np import matplotlib.pyplot as plt from modelos.colores import bcolors from funciones.utilidades import graficarVectores """ Analisis de componentes principales (PCA) ----------------------------------------- Es una tecnica muy util para reducir la cantidad de dimensiones con las que estamos trabajan...
c7d48aea7f1f11d37e7f83d6313ed63c17bc6702
opentokix/aoc2019
/01/01-1.py
279
3.53125
4
#!/usr/bin/env python3 def div_fuel(d): return d//3-2 def main(): r = [] with open("input") as f: for line in f: s = line.rstrip() d = div_fuel(int(s)) r.append(d) print(sum(r)) if __name__ == '__main__': main()
ed76d27fc83c536168402336595e4a69c4e38ae7
bigastefan/Python
/Library/pitoncina.py
2,307
3.890625
4
##def ispisivanje (): ## ## f = open ('knjige.txt') ## L=[] ## #unos = input ("Unesite naziv knjige: ") ## ## ## ## a=1 ## while a==1: ## citanje = f.readline() ## d = citanje.split('|') ## l = [] ## #### print (l) ## ## for x in d: ## l.appen...
d28b0f60a07e50e05b80032f80bc85f943ba1590
TerryOShea/algorithms
/project-euler/[16]power_digit_sum.py
95
3.53125
4
def power_digit_sum(n): return sum([int(x) for x in str(2**n)]) print(power_digit_sum(1000))
eda311f276029041b916b6f225ff4f20178fabc4
TerryOShea/algorithms
/longest_common_substring.py
720
3.84375
4
def make_matrix(str1, str2): matrix = [[0 for x in range(len(str1) + 1)] for y in range(len(str2) + 1)] for i in range(len(str1)): for j in range(len(str2)): if str1[i] == str2[j]: matrix[i + 1][j + 1] = matrix[i][j] + 1 else: matrix[i + 1][j + 1]...
a22bc5bb48786abd5f72cc06bfe63046b59483e9
TerryOShea/algorithms
/interview_cake/reverse_words.py
262
3.625
4
def reverse_words(msg): msg = msg.split() lg = len(msg) for i in range(lg//2): msg[i], msg[lg - i - 1] = msg[lg - i - 1], msg[i] return " ".join(msg) print reverse_words("find you will pain only go you recordings security the into if")