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 |
|---|---|---|---|---|---|---|
391a3799db474e9d1390d80b839960ab109bb215 | sobigha/ADF- | /3.prime numbers/prime.py | 335 | 3.53125 | 4 | import time
start=2
try:
while True:
flag = 0
for i in range(2, start//2+1):
if (start % i) == 0:
flag=1
break
if(flag==0):
print(start)
time.sleep(5)
start=start+1
except:
pri... |
3d85e0e52ac17749814becceede1a85244734ed4 | sobigha/ADF- | /5.Decimal Conversion/decimaltooctal.py | 264 | 3.765625 | 4 | num = int(input())
result = ""
try:
while num!=0:
rem=num%8
num=num//8
result=str(rem)+result
print(result)
except:
print("Exception")
#inbuilt function
print(oct(int(input())))
print(hex(int(input())))
print(bin(int(input()))) |
cb4be1337794cbad2a5b6e171ca5b8e710e9ce59 | jbehrend89/she_codes_python | /lists/starter/q4.py | 359 | 4.03125 | 4 | # Using the following starter code:
# a = [1, 2, 3]
# b = [4, 5, 6]
# c = [7, 8, 9]
# d = []
# e = []
# Produce the following lists:
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
d = []
e = []
d.append(a)
d.append(b)
d.append(c)
print(d)
print()
e.exten... |
10a9857231cf309241035bf6269db0ed4e4e2f26 | jbehrend89/she_codes_python | /oop/employee.py | 779 | 3.84375 | 4 | class Employee:
def __init__(self, name, salary, phone, start_date):
self.name = name
self.salary = salary
self.phone = phone
self.start_date = start_date
# create str method
def __str__(self):
return self.name
def get_employment_details(self):
... |
5819dbb5b6c308ac62f478185a3d52718832a533 | jbehrend89/she_codes_python | /functions/functions_exercises.py | 429 | 4.125 | 4 | # Q1)Write a function that takes a temperature in fahrenheitand returns the temperature in celsius.
def convert_f_to_c(temp_in_f):
temp_in_c = (temp_in_f - 32) * 5 / 9
return round(temp_in_c, 2)
print(convert_f_to_c(350))
# Q2)Write a function that accepts one parameter (an integer) and returns True when tha... |
01737a7e81085eb53a75dfcb3d03c2f9d7165ac9 | abhishekkolli/assignment-3 | /problem7.py | 1,354 | 3.890625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 20 02:16:42 2021
@author: kolliabhishek
"""
"""centered average"""
"""using set data structure it is easier since it vomits duplicates"""
def centered_average(array):
if len(array)<3:
return "enter atleast three numbers for computing ce... |
fad44a0afb08094559d29bd30c9de8b510c4a23e | gopalmenon/CS-6140-Assignment-2-Document-Similarity-And-Hashing | /HashFunctions.py | 1,088 | 3.59375 | 4 | import FileIo
import NGrams
import sys
SALT_FILE_NAME = "Data/MobyDickChapter1.txt"
N_GRAMS_SIZE = 3
class NGramHash(object):
"""Get character n-grams from salt file"""
def __get_salt_file_character_n_grams(self):
char_n_grams = NGrams.get_character_n_grams(FileIo.get_text_file_contents(SALT_FILE_NA... |
fa0fec74a35f329a36e62e09797812c787f4e99a | ajolayemi/jet_academy_uni_project | /University Admission Procedure/task/university.py | 13,470 | 3.953125 | 4 | #!/usr/bin/env python
import os
# Module to be used to find the mean of values
import statistics
# Stores those departments that require more than one
# exam to determine whether to accept applicant or no
DEPTS_CHOICE = {'Physics': ['Physics', 'Mathematics'],
'Engineering': ['Engineering', 'Mathematic... |
3c5198103afe66dea0e8000695f96aeafdd44529 | pvcraven/arcade_book | /source/chapters/26_libraries_and_modules/matplotlib_12.py | 1,020 | 3.71875 | 4 | """
Create a candlestick chart for a stock
"""
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, WeekdayLocator,\
DayLocator, MONDAY
from matplotlib.finance import quotes_historical_yahoo_ohlc, candlestick_ohlc
# Grab the stock data between these dates
date1 = (2014, 10, 13)
date2 = (201... |
ab61c9973606aeec2edb141871ec09a40cc26898 | pvcraven/arcade_book | /source/chapters/26_libraries_and_modules/matplotlib_07.py | 176 | 4.03125 | 4 | """
How to do a bar chart.
"""
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 3, 8, 4]
plt.bar(x, y)
plt.ylabel('Element Value')
plt.xlabel('Element')
plt.show()
|
db6fc881b4b9715f67c4b0d2dbe40d9846c0fefa | pvcraven/arcade_book | /source/chapters/14_advanced_looping/problem_02.py | 149 | 3.59375 | 4 | for row in range(10):
print("*",end=" ")
print()
for row in range(5):
print("*",end=" ")
print()
for row in range(20):
print("*",end=" ") |
d65648624196a72da80d43bff234fe77c4b008e7 | pvcraven/arcade_book | /source/chapters/14_advanced_looping/problem_10.py | 202 | 3.84375 | 4 | for i in range(1, 10):
for j in range(1, 10):
# Extra space?
if i * j < 10:
print(" ", end="")
print(i * j, end=" ")
# Move down to the next row
print() |
8f406736a425d36663cf7a4e5e6c31e8cd626f6f | pvcraven/arcade_book | /source/chapters/26_libraries_and_modules/matplotlib_03.py | 260 | 3.953125 | 4 | """
This example shows graphing two different series
on the same graph.
"""
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y1 = [1, 3, 8, 4]
y2 = [2, 2, 3, 3]
plt.plot(x, y1)
plt.plot(x, y2)
plt.ylabel('Element Value')
plt.xlabel('Element')
plt.show()
|
8ab868451761c0086f78fb5bc75712af318a4500 | pvcraven/arcade_book | /source/chapters/14_advanced_looping/problem_07.py | 140 | 3.6875 | 4 | for row in range(10):
for column in range(10):
print(row, end=" ")
# Print a blank line to move to the next row
print() |
f7b585ed163a98056e65c88b53c4adbd7dede0a3 | bhavyagoel/Algorithms | /introductionToAlgorithmCLRS/chp2/Exercise/Ex_2.3/q7.py | 1,202 | 4 | 4 | import math
def binarySearch(array, p, r, value):
if (r >= p):
q = math.floor((p + r) / 2)
if (array[q] < value) :
return binarySearch(array, q + 1, r, value)
elif (array[q] > value) :
return binarySearch(array, p, q - 1, value)
else:
return q
... |
af26fe228e865e1ee7f5dc6a35ac068f2a1ed475 | bhavyagoel/Algorithms | /introductionToAlgorithmCLRS/chp2/Chapter_Problems/q3HornersRule.py | 472 | 4.09375 | 4 | def HornersRule(degree, coef, x):
val = 0
for i in range(degree, -1, -1):
val = coef[i] + x*val
return val
if __name__ == "__main__":
degree = int(input("Enter the degree of polynomial you wish to have : "))
coef = list(map(lambda x: int(x), input("Enter the coefficients of the polynomi... |
ffb4c3bd67d6d4a778c3d3ecfa4c5160912275e7 | jaimemarston/bdinvdemo | /replacebd.py | 1,280 | 3.5 | 4 | import sqlite3
#nombretabla='gestionapp_articulo'
#nombretabla='gestionapp_material'
newline_indent = '\n '
conn = sqlite3.connect("dbinventario.sqlite3")
#cursor = con.cursor()
#Statement = "UPDATE " + nombretabla + " SET descolor = color "
#Statement = "update gestionapp_dmateriales set codpro = (select gest... |
28e2d4c18df9dd86277bf825b18a3a4b8d70419c | nataitapp/QA_class_1 | /class_7.py | 539 | 3.609375 | 4 | __author__ = 'nata'
prop1 = "Hello Stan"
class Myclass():
# default property
prop1 ="I am a class property!"
# method which sets a new property
def setProperty(self, newval):
self.prop1 = newval
# method which return the property
def getProperty(self):
return self.prop1
... |
e4b0e3129362e82500f38686234ef7ebc5dd7c20 | thrombe/TicTacToeMiniMax | /TicTacToeMinimax(withAlphaBetaPruning).py | 4,363 | 3.984375 | 4 | '''
TODO
-
'''
if __name__ == '__main__':
print('''\
welcome to terminal tic-tac-toe or knots and krossess
or whatever you call this game
made by thrombe
''')
input('press enter to start')
def genBoard():
board = { }
for i in range(9): #generating blank board with coords like a2 starting from top left
x = ['... |
0fb9d1c2d5b74f5c815ab41a951a05f4728ae25a | niceman5/pythonProject | /02.교육/Python-응용SW개발/Project/froamtEx01.py | 516 | 3.703125 | 4 | n1 = 10
n2 = 20
print('n1:',n1,'n2=',n2)
print('n1=%d, n2=%d'%(n1,n2)) # 서식문자가 2개이상이면 소괄호를 사용해야 한다.
print('%d'%n1) #왼쪽 정렬
print('%5d'%n1) #자리수가 정해지면 오른쪽 정렬
print('%-5d'%n1) #왼쪽정렬옵션
print()
print('사과 %d개'%12)
apple = 212
print('사과 %d개'%apple)
pear = 551
print('사과 %d개, 배 %d개'%(apple,pear))
f1 = '사과'
f2 = ... |
216c437aed5b413627a585de732773482aeeb93f | niceman5/pythonProject | /02.교육/Python-응용SW개발/Project/day20190420/book_122.py | 612 | 3.609375 | 4 | ##treeHit = 0
##
##while treeHit < 10:
## treeHit += 1
## print('나무를 %d번 찍었습니다.' % treeHit)
## if treeHit == 10:
## print('나무넘어갑니다.')
##
prompt = """
1. Add
2. Del
3. List
4. Quit
Enter Number : """
number = 0
while number != 4:
number = int(input(prompt))
if number == 1:
p... |
8e05d610dc575187daeddc918c9395d9709a43c4 | niceman5/pythonProject | /02.교육/Python-응용SW개발/Project/day20190420/whileEx01.py | 561 | 4.125 | 4 |
num = 1 # 초기값
while num < 3: #조건식 : #반복할 조건 true일동안만 실
#명령문
print('num = {}'.format(num))
num += 1 # 증감식
print('실행종료')
# 무한loop돌면서 조건으로 체크하는 방식이 있음
num = 1
while True:
print('num = {}'.format(num))
num += 1 # 증감식
if num == 3:
break
print('실행종료')
num = 1
while n... |
a823ff06b579196ef04d1d0c2d00a1296c871361 | niceman5/pythonProject | /class/class01.py | 633 | 3.90625 | 4 | # 클래스는 연산자 중복을 지원한다. 파이썬에서 사용하는 모든 연산자의 동작을 정의할수 있다.
class MyClass:
# 객체가 생성되고 나서 자동으로 실행된다.
def __init__(self):
self.value = 0
# 기본연산자를 재정의한다.
def __add__(self, x):
print('add {} call'.format(x))
return x
# 소멸자. 객체가 삭제될때 실행된다..... del로 객체 삭제시...
def __del__(self):... |
37b33023d7f8e01f05ac8226ddfb05bb88b55fc6 | niceman5/pythonProject | /02.교육/Python-응용SW개발/Project/day20190511/exceptEx01.py | 511 | 3.9375 | 4 | # try:
# # 예외가발생
#
# except:
# # 예외가발생했을때 처리할 명령
#
# else:
# #예외가 발생하지 않았을 때
# finally:
# #예외 발생 여부와 상관없이 무조건 마지막에 실행하고자하는 명령문.
#
n1 = 5
n2 = 0
result1, result2 = 0, 0
try:
result1 = n1 / n2
result2 = n1 % n2
except:
print('exception')
else:
print('n1 / n2 :', result1)
print('n1 %... |
57b4325000fb7a12efa52d0d4c5e486ec43403ac | niceman5/pythonProject | /02.교육/Python-응용SW개발/Project/day20190511/classEx01.py | 636 | 4.0625 | 4 | class Mother:
money = 1000000 #class변수
def buy(self):
# class변수 사용시 해당 class명을 같이 써주어ㅓ야 한다.
Mother.money -= 200000
def balance(self):
print('balance :', Mother.money)
# Mother를 상속한다.
class Son(Mother):
def buy(self, money):
Mother.money -= money
# 변수종류
# -전역변수
# ... |
fe45269dd859013c338bb476b87498b57961e498 | niceman5/pythonProject | /CodingTest/L1.같은글자반복하기.py | 860 | 3.828125 | 4 | '''
문제 설명
길이가 n이고, 수박수박수박수....와 같은 패턴을 유지하는 문자열을 리턴하는 함수, solution을 완성하세요.
예를들어 n이 4이면 수박수박을 리턴하고 3이라면 수박수를 리턴하면 됩니다.
제한 조건
n은 길이 10,000이하인 자연수입니다.
입출력 예
n return
3 수박수
4 수박수박
'''
'''
def water_melon(n):
s = "수박" * n
return s[:n]
def water_melon(n):
return "수박"*(n//2) + "수"*(n%2
def water_melon... |
6897bb7b6ecec66f0bb8aba025438d2e5bf2b0ee | niceman5/pythonProject | /02.교육/Python-응용SW개발/Project/day20190518/reEx01.py | 1,170 | 3.640625 | 4 | #1. re모듈 import
import re
data = 'abc. d2y mart food m day 379'
#2. compile(정규표현식)
# p = re.compile('[abc]')
# p = re.compile('[m]')
# p = re.compile('[a-zA-Z]') # 모든 알파벳을 찾아라.
# p = re.compile('[0-9]') # 모든 숫자
# p = re.compile('[135]') # 13룰 찾아
# p = re.compile('[^135]') # 135를 제외한 모든것
# p = re.compile('[\d]') ... |
5665106ca9f7b7fee6de6d0caa985d55374ef0d1 | niceman5/pythonProject | /02.교육/Python-응용SW개발/Project/day20190504/classEx02.py | 437 | 3.71875 | 4 |
class Person():
def setName(self, name):
nick = 'aa' # 지역변수..해당 함수내에서만 사용한다.
self.name = name
def setAge(self, age):
self.age = age
def info(self):
print('name : {}, age : {}'.format(self.name, self.age))
p = Person()
p.setName('kim') # 인스턴스 변수 여기서 만들어지기 때문에 이거... |
e703fe2866f46326e7ef954fa76a1da20e2a7257 | niceman5/pythonProject | /02.교육/Python-응용SW개발/Project/day20190427/book_131.py | 847 | 3.6875 | 4 | ##a = [(1,2),(3,4),(5,6)]
##
##for first, last in a:
## print('first={} last={}'.format(first, last))
##
##
##for first in a:
## print('first={} last={}'.format(first[0], first[1]))
##marks = [90, 25, 67, 45, 80]
##numbers = 0
##
##for mark in marks:
## numbers += 1
##
## if mark >= 60:
## print('%d... |
0722ad79f69fb4b847028c834cdcc735eafb02de | niceman5/pythonProject | /02.교육/Python-응용SW개발/Quiz/20190509-Long Repeat.py | 1,606 | 3.5 | 4 | # 이 임무는이 시리즈의 첫 번째 임무입니다. 여기서 동일한 문자로 구성된 가장 긴 하위 문자열의 길이를 찾아야합니다. 예를 들어,
# "aaabbcaaaa"행에는 "aaa", "bb", "c"및 "aaaa"와 같은 4 개의 하위 문자열이 있습니다. 마지막 부분 문자열은 대답을 만드는
# 가장 긴 부분 문자열입니다.
def long_repeat(line):
max_char = ''
tmp_char = ''
for v in line:
if len(tmp_char) > 0 and tmp_char[-1] != v:
... |
0a59e101c9c51f108300ecdb5b4a825f95cceb42 | niceman5/pythonProject | /00.LibExample/EffevtivePython/00.func_list.py | 875 | 3.90625 | 4 | """리스트를 반환하는 대신 제너레이터를 고려해야 함
"""
# 리스트를 직접반환 하는 코드임
# 모든 결과를 리스트에 저장했다 리턴. 대량의 처리시 메모리 사용이 클수 있음
def index_words(text):
result = []
if text:
result.append(0)
for index, letter in enumerate(text):
if letter == ' ':
result.append(index + 1)
return result
# 리스트로 반환하는 부분이 없어 ... |
538a53542de562d8bcd8e6102b6f32f3695950d9 | Edjchg/Python_REST_API_tutorial | /api_hello_world.py | 2,220 | 3.640625 | 4 | import flask
# Tutorial: https://programminghistorian.org/en/lessons/creating-apis-with-python-and-flask
from flask import jsonify, request
main_api = flask.Flask(__name__)
main_api.config["DEBUG"] = False
books = [
{'id': 0,
'title': 'A Fire Upon the Deep',
'author': 'Vernor Vinge',
'first_sentenc... |
70bdcbd7e8ceff606940e2ae8725ff4593a8ecef | namlook/trackeet | /trackeet/helpers.py | 1,196 | 3.640625 | 4 |
def process_stub(stub):
"""
process stub and extract tags and comments.
* a tag is one or two words
* a comment is more than two words
* tags and comments are comma separated
>>> process_stub("tag1, a tag2, this is a comment")
{'comments': ['this is a comment'], 'tags': ['tag1', 'a tag2']... |
20f53883ff2f25f6f47906b027caf0746a2a67fb | CodyBuilder-dev/python-practice | /pythonic-code/chap01/nested_function_write.py | 244 | 3.546875 | 4 | def greeting(name) :
greeting_msg = "Hello "
def add_name() :
greeting_msg = "Not Hello "
return "%s%s" % (greeting_msg,name)
msg = add_name()
print(msg)
if __name__ == '__main__' :
greeting("codybuilder") |
9dcd83d636b054f122adb049fb0ecb97b342d3f4 | nishanthegde/bitesofpy | /105/slicing.py | 1,848 | 4.3125 | 4 | from string import ascii_lowercase
text = """
One really nice feature of Python is polymorphism: using the same operation
on different types of objects.
Let's talk about an elegant feature: slicing.
You can use this on a string as well as a list for example
'pybites'[0:2] gives 'py'.
The first value is inclus... |
0bf226349b05ef044d437b4a382190369327c44e | nishanthegde/bitesofpy | /pybites_bite374/anagrams.py | 531 | 4.0625 | 4 | from collections import defaultdict
def group_anagrams(strings: list[str]) -> list[list[str]]:
"""Group anagrams together."""
anagrams = defaultdict(list, {k: [] for k in strings})
for k in anagrams.keys():
anagrams[k] = [v for v in strings if sorted(v) == sorted(k)]
ret = list(ana... |
19cbd6a0651814892fc7722b98aac2f25f70d787 | nishanthegde/bitesofpy | /111/ipinfo.py | 537 | 3.75 | 4 | import requests
IPINFO_URL = 'http://ipinfo.io/{ip}/json'
def get_ip_country(ip_address: str) -> str:
"""Receives ip address string, use IPINFO_URL to get geo data,
parse the json response returning the country code of the IP"""
resp = requests.get(IPINFO_URL.format(ip=ip_address))
retu... |
6d98b5e675c41f1934af80dce0f2663fab8346f9 | nishanthegde/bitesofpy | /225/convert_chars.py | 737 | 3.96875 | 4 | PYBITES = "pybites"
def _in_pybites(c):
return c.lower() in PYBITES
def _swap_case(c):
if c.islower():
return c.upper()
else:
return c.lower()
def convert_pybites_chars(text):
"""Swap case all characters in the word pybites for the given text.
Return the resu... |
f778220e5768bf4b02fc1fd8738744bab84170c0 | nishanthegde/bitesofpy | /259/reverse_complement.py | 2,866 | 3.796875 | 4 | import test_reverse_complement as trc
# See tests for a more comprehensive complementary table
SIMPLE_COMPLEMENTS_STR = """#Reduced table with bases A, G, C, T
Base Complementary Base
A T
T A
G C
C G
"""
# Recommended helper function
def _clean_sequence(sequence: str, str_table: str) -> str... |
0c92db36c65048e84375821b89ff4eaf8caa2e1b | nishanthegde/bitesofpy | /pybites_bite352/hash_sql.py | 1,257 | 3.625 | 4 | import hashlib
from random import shuffle
query = """select Candidate, Election_year, sum(Total_$), count(*)
from combined_party_data
where Election_year = 2016
group by Candidate, Election_year
having count(*) > 80
order by count(*) DESC;
"""
def hash_query(query: str, length: in... |
d29cd26f84328a611576c65461ad651715fbc7d1 | nishanthegde/bitesofpy | /145/high_low_temps.py | 5,220 | 4.0625 | 4 | from collections import namedtuple
import datetime as dt
import pandas as pd
DATA_FILE = "http://projects.bobbelderbos.com/pcc/weather-ann-arbor.csv"
STATION = namedtuple("Station", "ID Date Value")
def load_csv(url=DATA_FILE):
frame = pd.read_csv(url)
return frame
def high_low_record_breakers_f... |
9a1f3827647f370ac42ce3aa1103fd04c29f520e | nishanthegde/bitesofpy | /192/log_it.py | 1,307 | 3.515625 | 4 | import logging
from typing import Callable
def set_debug_level():
logging.getLogger().setLevel("DEBUG")
def set_info_level():
logging.getLogger().setLevel("INFO")
def set_warning_level():
logging.getLogger().setLevel("WARNING")
def set_error_level():
logging.getLogger().setLevel... |
02a24e5506ae1678cc635deb41c276c1299a6307 | nishanthegde/bitesofpy | /71/record.py | 1,002 | 3.828125 | 4 | import numbers
class RecordScore():
"""Class to track a game's maximum score"""
def __init__(self):
self.max_score = None
def __call__(self, score):
if not(isinstance(score, numbers.Number)):
raise ValueError("score must be numeric")
if isinstance(score,... |
b8f881af4f7678dfb48d8bccfc8fa2e1704835bb | nishanthegde/bitesofpy | /208/combos.py | 1,008 | 3.734375 | 4 | from itertools import combinations
def find_number_pairs(numbers, N=10):
ret = []
for tup in list(combinations(numbers, 2)):
if tup[0] + tup[1] == N:
ret.append(tup)
return ret
def _sort_all(ret):
return sorted(
[tuple(sorted(n)) for n in ret]
)
... |
5e30dd1789bdc62b2b37d7de7f30e35ce6ba7ebb | nishanthegde/bitesofpy | /348/citation_indexes.py | 1,559 | 3.78125 | 4 | from typing import Sequence
TYPE_ERROR_MSG = "Unsupported input type: use either a list or a tuple"
VALUE_ERROR_MSG = "Unsupported input value: citations cannot be neither empty nor None"
def h_index(citations: Sequence[int]) -> int:
"""Return the highest number of papers h having at least h citations"""
... |
1ad2e7463aff6086e9506fe45d87a94b0d6b9226 | nishanthegde/bitesofpy | /9/palindrome.py | 1,805 | 4.21875 | 4 | """A palindrome is a word, phrase, number, or other sequence of characters
which reads the same backward as forward"""
import os
import urllib.request as ur
import re
local = '/tmp'
# local = os.getcwd()
DICTIONARY = os.path.join(local, 'dictionary_m_words.txt')
ur.urlretrieve('http://bit.ly/2Cbj6zn', DICTI... |
537849e4c23127c078b6a72b4d07225c89a03665 | nishanthegde/bitesofpy | /274/conversion.py | 508 | 4.03125 | 4 | def dec_to_base(number, base):
"""
Input: number is the number to be converted
base is the new base (eg. 2, 6, or 8)
Output: the converted number in the new base without the prefix (eg. '0b')
"""
add = number % base
if number <= 1:
if number == 0:
return ''
... |
c6d1f0e7c1d7c6f92dd7bd0dd6cd2dffe1b0b8d5 | nishanthegde/bitesofpy | /280/regex_lookahead_lookbehind.py | 1,156 | 3.578125 | 4 | import re
def count_n_repetitions(text, n=1):
ret = 0
regex = r'((.)\2{' + re.escape(str(n)) + ',})'
text = re.sub(r"\n", " ", text)
match = re.findall(regex, text)
# print(match)
ret = len(match)
if match:
for m in match:
ret += count_n_repetitions(m[0][1:], n)
... |
6da23e7e856cdaafcd5de0d3bee56bc014ef5c38 | nishanthegde/bitesofpy | /134/twosums.py | 2,766 | 3.796875 | 4 | from random import sample, seed
NUMBERS = [2202, 9326, 1034, 4180, 1932, 8118, 7365, 7738, 6220, 3440, 1538, 7994, 465,
6387, 7091, 9953, 35, 7298, 4364, 3749, 9686, 1675, 5201, 502, 366, 417,
8871, 151, 6246, 3549, 6916, 476, 8645, 3633, 7175, 8124, 9059, 3819, 5664,
3783, 3585, ... |
489a9fbaa6d206101364ed5db32b3bf291c3d875 | nishanthegde/bitesofpy | /304/max_letter.py | 2,435 | 4.25 | 4 | from typing import Tuple
import re
from collections import Counter
sample_text = '''It is a truth universally acknowledged, that a single man in
possession of a good fortune, must be in want of a wife.'''
with_numbers_text = '''20,000 Leagues Under the Sea is a 1954 American
Tec... |
132fafc17d7de25e506e7eb077e24ee243cb758e | nishanthegde/bitesofpy | /179/comments.py | 4,139 | 3.90625 | 4 | import re
single_comment = '''
def hello_world():
# A simple comment preceding a simple print statement
print("Hello World")
# tmmmimi mimimm
'''
single_comment_after_strip = '''
def hello_world():
print("Hello World")
'''
single_docstring = '''
def say_hello(name):
"""A simple functi... |
5437f23adbeb3954eacc85ebc451ddf2ed3d198f | nishanthegde/bitesofpy | /pybites_bite353/script.py | 443 | 3.734375 | 4 | import typer # use typer.run and typer.Argument
def sum_numbers(a: int, b: int):
"""Sums two numbers"""
return a + b
def main(
a: int = typer.Argument(1, help="The value of the first summand"),
b: int = typer.Argument(2, help="The value of the second summand"),
):
"""
CLI that ... |
5db039c74def3124d330341bc9d789aad33924dc | nishanthegde/bitesofpy | /57/calculator.py | 3,709 | 4.25 | 4 | import argparse
class InvalidArgType(Exception):
"""Raised when the user is not in USERS"""
pass
def calculator(operation, numbers):
"""TODO 1:
Create a calculator that takes an operation and list of numbers.
Perform the operation returning the result rounded to 2 decimals"""
... |
c2e0d08cf977c216e326da83a6e1580b01c3af7b | nishanthegde/bitesofpy | /66/running_mean.py | 666 | 4.125 | 4 | import itertools
def running_mean(sequence: list) -> list:
"""Calculate the running mean of the sequence passed in,
returns a sequence of same length with the averages.
You can assume all items in sequence are numeric."""
it = iter(sequence)
n = len(sequence)
run_mean = []
... |
f8c34ebdecf70153f6c0d4c69e7afed4d0af4ea3 | linuxias/MachineLearning | /LinearRegression.py | 1,174 | 3.515625 | 4 | import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#The numbers of data
num_points = 1000
# DataSet
vectors_set = []
for i in range(num_points):
x1 = np.random.normal(0.0, 0.55)
y1 = 0.1 * x1 + 0.3 + np.random.normal(0.0, 0.03) # h(x) = theta * x + b
vectors_set.append([x1, y1])
... |
74e15572ed325930b9690b77f0bcb49b5ae6e33c | lippertr/machine_learning_examples | /numpy_class/numpy_lesson.py | 1,367 | 3.578125 | 4 | # coding: utf-8
import numpy as np
L = [1,2,3]
A = np.array([1,2,3,])
get_ipython().magic('whos ')
l2 = [4,5,6]
l2
np.append(A, l2)
A.append(l2)
#no append like there is for lists in numpy instead think of it as vectore
'''
we must use for loops with lists [] or comprehensions which is just a for
loop shorthand and the... |
924f5bf1eb38458914d4d33ef4cb3a529322f7cf | flora-c/DataProcessing | /Lab/week6/convertCSV2JSON2.py | 421 | 3.640625 | 4 | # Name: Flora Boudewijnse
# Student number: 10196153
# Function converts csv to json.
import json
import csv
# import csv file
input_file = open("zuid-holland.csv", "r")
columns = ["party", "votes", "seats", "percentage"]
reader = csv.DictReader(input_file, fieldnames = columns)
# write jsonfile
jsonfile = open("zui... |
93de403bd96ef116db02a8fef1c735cb38621233 | Ape/python-projecteuler | /004.py | 254 | 3.796875 | 4 | #!/usr/bin/env python3
import itertools
def products(limit):
return (x*y for x,y in itertools.product(range(limit), repeat=2))
def is_palindrome(n):
s = str(n)
return s == s[::-1]
print(max(x for x in products(1000) if is_palindrome(x)))
|
3f9c89ca7d71559974c1e99dfe74d0f20dea9711 | ucsd-cse-spis-2017/spis17-final-project-Lovpreet | /poker_hands.py | 7,034 | 3.703125 | 4 | import collections
import itertools
import random
SUIT_LIST = ("Hearts", "Spades", "Diamonds", "Clubs")
NUMERAL_LIST = ("2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace")
SCORE_DICT = {"2": 0, "3": 1, "4": 2, "5": 3, "6": 4, "7": 5, "8": 6, "9": 7, "10":8, "Jack": 9, "Queen":10, "King":11, "... |
343625f1230b7387b34aa4c499079cc8e3494b6d | paulbendixen/tronxt | /src/tronThread.py | 1,415 | 3.71875 | 4 | #!/usr/bin/python
#Thread functions for connecting to a TroNXT.
from threading import *
from BTControl import *
class TronThread(Thread):
"""Threading class used to serve several TroNXT bikes"""
trons = 0
tronsLock = Lock()
def __init__(self,address):
"""Initialization of the thread, includes setting up conne... |
f70649cbba312ef901ac9aa035cc529e46127200 | Caleb-o/VU405 | /sort.py | 694 | 4.1875 | 4 | """
Author: Caleb Otto-Hayes
Date: 11/2/2021
"""
def swap(x: int, y: int) -> tuple:
return (y, x)
def bubbleSort(unsorted: list) -> None:
length: int = len(unsorted)
full_pass: bool = False
# Cannot parse if only 1 number exists
if length < 2:
return
while not full_p... |
333c3e12c49250b96d015c7d73976cfdaca2caf6 | Caleb-o/VU405 | /onlydigits.py | 143 | 4 | 4 | import re
def onlydigits(text: str) -> str:
return re.sub(r'[A-Za-z]+|\s', '', text)
print('Digits: ', onlydigits(input('Enter text: '))) |
a6dcb027f20d2f6afa3475e618f8dc47b975e362 | rohitraut3366/DSA-Problems | /Practice Question Set-1/permutation.py | 496 | 3.9375 | 4 | string = "ABC"
def get_permutations(array):
perms = []
permutation_helper(0, array, perms)
return perms
def permutation_helper(i, array, perms):
if i == len(array) - 1:
perms.append((array[:]))
else:
for j in range(i, len(array)):
swap(array, i, j)
permuta... |
8df64411bcdca97de8274ff16a6adf5ec061dc95 | messrobd/cs262-implementing-re | /re_parser.py | 790 | 3.515625 | 4 | from re_lexer import tokens
'''
required grammar:
expression => regexp expression
expression => regexp
regexp => CH
expression => expression *
expression => expression | expression
expression => ( expression ) '''
start = 'expression'
def p_exp(p):
'expression : regexp expression'
p[0] = [p[1... |
506dd7cd779f9cc841e47e054a92ebc83cc0853a | fraroco/Rosalind-answers | /bu/Fib.py | 273 | 3.53125 | 4 | def fib (n,k):
fib = []
for i in range(int(0), n):
if i < 2:
fib.append(1)
else:
fib.append(fib[i-2]*k + fib[i-1])
return fib[-1]
with open('fib', 'r') as f:
n, k = f.readline().split()
print fib(int(n), int(k)) |
d558860b1fff565888139c63b3b858e7c7cfa710 | mucollabo/pandasForML | /source/part1/1.7_remove_row.py | 694 | 3.65625 | 4 | # -*- coding: utf-8 -*-
import pandas as pd
# DataFrame() 함수로 데이터프레임 변환. 변수 df에 저장
exam_data = {'수학' : [ 90, 80, 70], '영어' : [ 98, 89, 95],
'음악' : [ 85, 95, 100], '체육' : [ 100, 90, 90]}
df = pd.DataFrame(exam_data, index=['서준', '우현', '인아'])
print(df)
print('\n')
# 데이터프레임 df를 복제하여 변수 df2에 저... |
7d9372e8dd2ea19a44cb5ce03bff692519929489 | AzadeAlizade/Hangman-Game | /HangMan.py | 2,976 | 3.578125 | 4 | print("=====================")
print("###### Hangman ######")
print("=====================")
from random import choice
import os
import re
d=open("tmdb_5000_movies.csv",'r')
def hasNumbers(inputString):
return any(char.isdigit() for char in inputString)
data=d.read()
rows = data.split('\n')
rows = rows[1:len(row... |
c8c0a30036df09570ea2eb10ddb24a46790c1dd9 | hsloss/interview-problems | /python/shortener.py | 930 | 4.09375 | 4 | ######## Shortener
# Given two strings s, t, determine if string s can be changed into string t using the following rule:
# Remove any number of lowercase letters from s (or none at all), then capitalize all remaining letters of s.
# Example of the rule:
# s = AAbcD
# Possible outputs using the rule:
# Remove none, ... |
fd30f0ace6ef3a69daad93f2c02777d049415715 | staspozniakou/lessons_2 | /t2/five.py | 237 | 3.921875 | 4 | cathetus1=int(input('Введите первое число'))
cathetus2=int(input('Введите первое число'))
hypotenuse=((cathetus1)**2+(cathetus2)**2)**0.5
print(hypotenuse)
square=cathetus1*(cathetus2)/2
print(square)
|
27e84cfe16fb906fde5927794c36cd9df1fd5d41 | napoleonwxu/ProjectEuler | /033.py | 395 | 3.609375 | 4 | def digitCancellingFractions():
common = []
simple = []
for a in xrange(1, 5):
for b in xrange(a+1, 10):
for c in xrange(1, 10):
if float(10*a+b)/(10*b+c) == float(a)/c:
common.append(str(10*a+b)+'/'+str(10*b+c))
simple.append(str(a... |
ada4a36a49c2ab1db88615d40aec652fd1370f5d | napoleonwxu/ProjectEuler | /028.py | 261 | 3.515625 | 4 | def numberSpiralDiagonals(n):
if n < 3:
return
sum = 1
num = 1
d = 2
for i in xrange(3, n+1, 2):
for j in xrange(4):
num += d
sum += num
d += 2
return sum
print numberSpiralDiagonals(1001) |
86a5f25182e5055d6274ba786603dbd2594eb7df | napoleonwxu/ProjectEuler | /062.py | 713 | 3.8125 | 4 | def cubicPermutations(num):
d = {}
n = 1
while True:
c = n**3
l = sorted(str(c))
key = ''.join(l)
if not d.get(key):
d[key] = [1, c]
else:
d[key][0] += 1
if d[key][0] == num:
print key, n
return d[key... |
6f1d95ac23b81cf99374d285508a64b5388fbb0f | ZUros/FizzBuzz | /FizzBuzz.py | 486 | 3.8125 | 4 | i = int(raw_input("Vnesi stevilo do katerega naj steje med 1 in 100: "))
#prvi del programa
while 1>i>100:
if i<1:
print ("Vpisi vecje stevilo.")
if i > 100:
print ("Vpisi manjse stevilo")
#drugi del programa
else:
for x in xrange(1,i+1):
if x%3!=0 and x%5!=0:
print x
... |
09d44cb516ef33dd5b50a5d682b2750c7d1ff46d | Skoy87/gspread-pandas | /gspread_pandas/util.py | 3,720 | 3.53125 | 4 | import pandas as pd
def parse_sheet_index(df, index):
"""Parse sheet index into df index"""
if index and len(df.columns) > index:
df = df.set_index(df.columns[index - 1])
# if it was multi-index, the name is tuple;
# choose last value in tuple since that is more common
if type(d... |
04e1255a14638ac049af672fbd58f7ffd88b37b0 | AdrianVides56/holbertonschool-low_level_programming | /0x1C-makefiles/5-island_perimeter.py | 681 | 3.890625 | 4 | #!/usr/bin/python3
""" Module to calc the perimeter """
def island_perimeter(grid):
""" return the perimeter of the island """
i, j, per = 0, 0, 0
while i < len(grid):
while j < len(grid[0]):
if grid[i][j] == 1:
per += 4
if i > 0 and grid[i - 1][j] == 1:... |
1572a767db054bb13877a5d56f5efb212d0b844d | ahumoe/dragonfly-commands | /_text_utils.py | 1,978 | 4.15625 | 4 | #!/usr/bin/env python
# (c) Copyright 2015 by James Stout
# (c) Copyright 2016 by Andreas Hagen Ulltveit-Moe
# Licensed under the LGPL, see <http://www.gnu.org/licenses/>
"""Library for extracting words and phrases from text."""
import re
def split_dictation(dictation, strip=True):
"""Preprocess dictation to do ... |
8848410a07af7035aeeaebedc7c7811cda14788d | 3b1b/videos | /_2017/eoc/chapter10.py | 114,081 | 3.53125 | 4 | from manim_imports_ext import *
def derivative(func, x, n = 1, dx = 0.01):
samples = [func(x + (k - n/2)*dx) for k in range(n+1)]
while len(samples) > 1:
samples = [
(s_plus_dx - s)/dx
for s, s_plus_dx in zip(samples, samples[1:])
]
return samples[0]
def taylor_appr... |
f2efe0b9a3e8c91c5328e2e2e11077a058ca2219 | razzlestorm/code-challenges | /maximumSubarray_Easy/problem.py | 669 | 3.84375 | 4 | '''
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
Example 1:
Input: nums = [-2,1,... |
301743a5a8b79f26aaa153be6548c3e8ddde9d48 | razzlestorm/code-challenges | /missingNumber_Easy/set_solution.py | 163 | 3.59375 | 4 |
def missingNumber(self, nums: List[int]) -> int:
num_set = set(nums)
for ii in range(0, len(nums)+1):
if ii not in num_set:
return ii
|
d4533f5f846ff4ead280d69ebd69ccc69e35a63a | razzlestorm/code-challenges | /requestMatching_Med/naive_solution.py | 1,518 | 3.53125 | 4 | # if pro_distance <= max_pref_distance,
# then matching score = distance between pro and customer
# otherwise, the non-matching score = distance between pro and customer - max travel distance
#
def requestMatching(pros, distances, travelPreferences):
matching = {}
non_matching = {}
# compare distances/trave... |
ad6f53d4c9ffd4b4e48db070cdaafa9e119fa6ac | SirADV24/Pathfinder | /Interface/Menu.py | 3,619 | 3.6875 | 4 | import pygame as pg
import pygame_menu as pgm
class Menu:
TUTORIAL_TEXT = ["- Use Left-Click to fill cells on the board, first cell will be the starting",
"point while the second one will be the end point, the rest will be walls",
"- Use Right-Click to erase any fi... |
57ac7ca84fc6403322edf97442b73e18d6a74082 | MrSiGua/pylearning | /tuple.py | 414 | 3.5625 | 4 | classmates = ('Michael', 'Bob', 'Tracy')
# >>> t = (1)
# >>> t
# 1
# 定义的不是tuple,是1这个数!这是因为括号()既可以表示tuple,又可以表示数学公式中的小括号,这就产生了歧义,因此,Python规定,这种情况下,按小括号进行计算,计算结果自然是1。
# 所以,只有1个元素的tuple定义时必须加一个逗号,,来消除歧义:
# t = (1,) |
99b71494d6207dff7de86784bdc93fbdd0dc9dd2 | MrSiGua/pylearning | /获取对象信息.py | 4,946 | 3.53125 | 4 | # 使用type()
# 首先,我们来判断对象类型,使用type()函数:
# 基本类型都可以用type()判断:
import 继承和多态 as anamail
type(123)
type('str')
type(None)
type(abs)
print(type(anamail.cat))
# 判断基本数据类型可以直接写int,str等,但如果要判断一个对象是否是函数怎么办?可以使用types模块中定义的常量:
import types
def fn():
pass
print(type(fn) == types.FunctionType)
type(abs) == types.BuiltinFunct... |
6884a7438cfc5a917b7e6655b53e8042230c4c9b | BarYar/MonopolyGame | /Game/Player.py | 2,856 | 3.796875 | 4 | from Game.Houses import Houses
from Game.Character import Character
"""Player class-
parameters:
1.name - The player name (string)
2.money - The player money (float) - can't be negative
3.The character of the player.
4.x (float) - default value=None... |
dcdb8588fbf778a46017e45b4330dacc7823b255 | BarYar/MonopolyGame | /Game/Characters.py | 2,226 | 3.625 | 4 | import os
import random
from Game.Character import Character
from Game.Displayable import Displayable
""" Character_List class-
parameters:
attributes:
1.names- List of all the available character names (List(string))
2.pictures- List of all of the pictures locatio... |
3588fda405f0e10c3434881653a0f3d11897e9af | darwin-nam/python-algorithm | /codeup/6036.py | 85 | 3.796875 | 4 |
word, num = input().split()
num = int(num)
for i in range(num) : print(word, end='') |
b4c9ffb1b4b9dcc879f99bc730ce3e57b18c4ede | darwin-nam/python-algorithm | /codeup/6037.py | 98 | 3.84375 | 4 | num = input()
string = str(input())
num = int(num)
for i in range(num) : print(string, end = '')
|
c3062c4b5da4a684bb5ce8a19b074e6585618620 | josepicon/practice.code.py | /Exercise Files/Ch2/functions_start.py | 747 | 4.34375 | 4 | #
# Example file for working with functions
#
# define a basic function
def func1():
print("i am a function")
# function that takes arguments
def func2(arg1, arg2):
print(arg1, "", arg2)
# function that returns a value
def cube(x):
return x*x*x
# function with default value for an argument
def power(n... |
937b69e57e2c6b066542ce1539be81fde35b4ca9 | hanshnnn/FFC-coding-exercise | /Algorithms/Implement Quick Sort/solution.py | 720 | 3.671875 | 4 | def partition(array, start, end):
if start == end:
return -1
else:
i = start - 1
pivot = array[end]
for j in range(start, end):
if array[j] <= pivot:
i += 1
array[i], array[j] = array[j], array[i]
array[i+1], array[end] = array[... |
6285ec7346a574559be14151eb205073e38188f9 | hanshnnn/FFC-coding-exercise | /Algorithms/No Repeats Please/solution.py | 774 | 3.65625 | 4 | def swab(string, i, length):
string = list(string)
global combinations
if i == length:
combinations.append(string)
else:
for j in range(i, length):
string[i], string[j] = string[j], string[i]
swab(string, i + 1, length)
string[i], string[j] = string[j]... |
080fa1a292fe225984f8889d5e5bd13ed05b0f07 | MayThuHtun/python-exercises | /ex3.py | 444 | 4.28125 | 4 | print("I will now count my chickens")
print("Hens", 25+30/6)
print("Roosters", 100-25*3 % 4)
print("Now I will count the egg:")
print(3+2+1-5+4 % 2-1/4+6)
print("Is it true that 3+2<5-7?")
print(3+2 < 5-7)
print("What is 3+2?", 3+2)
print("What is 5-7?", 5-7)
print("Oh, that is why it is false")
print("How about some m... |
2c6ea896080be3be0d19c01a5e9cf1d5bd6b3c92 | CeciliaMartins/-LingProg | /3-calculoSalario.py | 380 | 4 | 4 | ##3 Faça um Programa que pergunte quanto você ganha por hora e o
##número de horas trabalhadas no mês. Calcule e mostre o total do
##seu salário no referido mês.
recebePorHora = float(input("Quanto você ganha por hora? "))
horasTrabalhadas = int(input("Quantas horas trabalhadas no mês? "))
salario = (recebePorHo... |
90b34ee9623041c01d16ccf10998be5f7a35053e | CeciliaMartins/-LingProg | /4-transformacaoDeTemperatura.py | 381 | 4.09375 | 4 | ##4 Faça um Programa que peça a temperatura em graus Farenheit,
##transforme e mostre a temperatura em graus Celsius. C = (5 * (F-32)/9)
temperaturaF = int(input("Digite a temperatura em graus Farenheit: "))
temperaturaC = (5 * (temperaturaF-32)/9)
mensagem = "A temperatura %f em graus Farenheit para graus Celsius ... |
71191aff305c9dae5028b28c2f43b0d963112b9b | dev-aleks/info_2021 | /lab4/house.py | 1,380 | 4.125 | 4 | def main():
x, y = 300, 400
width, height = 200, 300
draw_house(x, y, width, height)
def draw_house(x, y, width, height):
'''
Функция рисует домик
:param x: координата x у низа фундамента
:param y: координата y у низа фундамента
:param width: полная ширина домика (фундамент или вылеты ... |
bbdd9e156fb2bb738aaa0410ad1b76ea4eb57f2c | gebijiaxiaowang/Credit-score-card-model | /Credit-score-card-model/Fuction_Total.py | 4,587 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
此脚本用于定义函数,供1,2,3调用
"""
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
def f(x):
"""时间转化"""
if 'years' in str(x):
x = str(x).strip('years')
x = str(x).replace('+', '')
elif ... |
da41671d59cfc64c1f5159618cc12d9ea299f1fb | TheShepord/hello-world | /6.00.1x/Primes.py | 619 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 16 11:17:12 2017
@author: lucas
"""
def genPrimes():
prime1 = 2
primes = []
count = 0
test = True
while True:
yield prime1
if test:
primes.append(prime1)
test = False
print(prime1)
... |
52423cb5ddc4b52a3746d2b77365c949e624407f | alifianadexe/tic-tac-toe | /tic-tac-toe.py | 5,812 | 4.03125 | 4 | # Tic Tac Toe
import random
print('Welcome to the tic tac toe')
def drawBoard(board):
# This function prints out the board that it was pased.
# "broad" is a list of 10 strings representing the board (ignore index 0)
print('-----------')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
... |
5ab1964a2a2d7c7213f33530761ca4633b570b74 | AMG86/new1986 | /stroki.py | 587 | 3.96875 | 4 | def my_function ():
while True:
stroka1 = input('Введите первую строку: ')
stroka2 = input('Введите вторую строку: ')
if type(stroka1) != str or type(stroka2) != str:
return 0
elif len(stroka1) == len(stroka2):
print(1)
elif len(stroka1... |
c5dc3ad52ad4acf76b6aeec351b767667d7bf390 | clash402/quizzer | /quiz_brain.py | 945 | 3.609375 | 4 | class QuizBrain:
def __init__(self, question_list):
self.score = 0
self.question_number = 0
self.question_list = question_list
def still_has_questions(self):
return self.question_number < len(self.question_list)
def proceed_to_next_question(self):
i = self.question_... |
f8b7ad4efa9b2f75c375fa5e9278aa6a36d63ed2 | jaymit31/Applied-Machine-Learning-in-Python | /week2_Assihnment.py | 24,405 | 4.1875 | 4 | Assignment 2
In this assignment you'll explore the relationship between model complexity and generalization performance, by adjusting key parameters of various supervised learning models. Part 1 of this assignment will look at regression and Part 2 will look at classification.
Part 1 - Regression
First, run the fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.