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 |
|---|---|---|---|---|---|---|
361c8f83f8202090beaeff70d00427046d8cdc6c | rosteeslove/bsuir-4th-term-python-stuff | /computer_architecture/alu_emulator/floatpoint/testing.py | 3,127 | 3.765625 | 4 | """
This script exists to perform tests on operations w/ my float type.
The point is:
1. to generate random float arguments for an operation
that's being tested.
2. to produce identical arguments of my float type.
3. to produce the float operation result res.
4. to produce my float operation re... |
e2a21d081e7d1dc8ac6f9d05c48ae1c753a8a0e8 | rosteeslove/bsuir-4th-term-python-stuff | /numerical_analysis_methods/nonlineqs/rootapprox/binary_search_method.py | 682 | 4.0625 | 4 | """
This module contains the calculate_root method to find function f's
root on (a, b) interval using binary search algorithm.
"""
MAX_ITERATION_COUNT = 1_000
def calculate_root(f, a, b, eps):
"""
Return root (assuming there's one) of f function
on the (a, b) interval using binary search algorithm
a... |
0487755cae67b8f59554449aae3a6612b0dc3b7e | rosteeslove/bsuir-4th-term-python-stuff | /numerical_analysis_methods/gaussianelimination/gauss_elim_partial_pivoting.py | 2,048 | 4.125 | 4 | """
Схема частичного выбора.
"""
import numpy as np
def solve(A: np.array, b: np.array, interactive) -> np.array:
"""
Solves A*x = b that is returns x-vector.
"""
if interactive:
print('Схема частичного выбора:\n')
input()
# securing args:
A = A.copy()
b = b.copy()
... |
bbfafb380806a566ebd32330006a836cd4901a91 | rosteeslove/bsuir-4th-term-python-stuff | /numerical_analysis_methods/nonlineqs/rootisol/naive_method.py | 935 | 3.8125 | 4 | """
This module contains the isolate_roots method for root isolation
for any function. The method iterates the main interval with the
same step to find intervals in which the function crosses the x-axis.
Ремарка: табличный метод короче.
"""
DEFAULT_STEP = 0.001 # precision
def isolate_roots(f, left, right, eps=... |
defb2a799a90d55b90f5e0784ff71e5951791046 | rosteeslove/bsuir-4th-term-python-stuff | /google_foobar/third_task/find-the-access-codes/solution.py | 993 | 3.8125 | 4 | """
This module contains solution function.
"""
def brute(some_list):
"""
O(n^3) time complexity.
"""
list_len = len(some_list)
num_of_lucky_triples = 0
for i in range(list_len):
for j in range(i+1, list_len):
if some_list[j] % some_list[i] != 0:
continue
... |
28dc6b4aec8e3498d2d560b9fe7eef8bed4b6570 | sukki89/TrendinaliaItalia | /AnylyzeData.py | 327 | 3.734375 | 4 | import sqlite3
conn = sqlite3.connect('ItalyTweets.db')
c = conn.cursor()
symbol = 'italy'
rows = c.execute("select count(hashtags) from tweets where hashtags like ?",('%'+symbol+'%',))
rows = c.execute("select count(hashtags) from tweets where hashtags like ?",('%'+symbol+'%',))
for row in rows:
print(row)
conn.... |
864e2e074783d92025624016c32abae12c274341 | selimyoussry/problem_solving | /pramp/36f13e79-93ae-4031-85bb-44d3c264c245/solution.py | 408 | 3.578125 | 4 | # solution.py
def hotel(arrive, depart, K):
arr_dep = sorted(
[(x, False) for x in depart] + [(x, True) for x in arrive)],
key=lambda u:u[0]
)
current_day = arr_dep[0][0]
i = 0
while i<len(arr_dep):
day, arrival = arr_dep[i]
if day != current_day and K<0:
return False
if arrival:
... |
4ab630c714a00838a7261002e65a41bd61af6e0d | selimyoussry/problem_solving | /euler_projects/p10/erathosthene.py | 778 | 3.671875 | 4 | __author__ = 'somedude'
class Eratho:
def __init__(self, maxi, crible=True):
self.maxi = maxi
self.primes = dict()
self.cribled = False
for i in range(2, self.maxi + 1):
self.primes[i] = True
if crible:
self.crible()
def crible(self):
... |
f73979853c742a2e5449d6f98a3645d72fcc00a3 | selimyoussry/problem_solving | /misc/df2ec7c8-53af-4a6f-9ca1-3cab4951d64e/solution.py | 195 | 3.53125 | 4 | # solution.py
# Linear time solution, cannot do better
def is_twice(arr):
s = set()
for elt in arr:
if elt not in s:
s.add(elt)
else:
return elt
|
bd37c3ac65672973eb58e88bb88aca286c9bef9d | selimyoussry/problem_solving | /euler_projects/p18/tree.py | 1,555 | 3.5625 | 4 | class Triangle:
def __init__(self):
self.data = self.read_data()
def read_data(self):
f = open('data.txt', 'r')
previous_layer = []
current_layer = []
for l in reversed([l for l in f]):
nodes_values = map(lambda s: int(s), l.split(' '))
n_nodes ... |
917421975e595a6cb263fe19ea59e4b49abec19f | agiera/text_minesweeper | /minesweeper/minesweeper.py | 2,339 | 3.75 | 4 | from functools import reduce
from minesweeper.text_game import TextGame
from minesweeper.board import Board
instructions = \
"""
moves are all of the form 'X i j' where i and j are rows and columns respectfully.
'X' must be one of the following commands:
'C' is for checking or clicking on a square
'F' is for flagg... |
8335a5e46f50fb25a5ffea2412b328b001a31f1d | geekywolf/fintec-mock | /zuri/main.py | 3,098 | 3.578125 | 4 | import random
import datetime
from db import bankUsers
time = datetime.datetime.now()
def landingpage():
print("Hello. Enter 1 to login or 2 to register")
option = int(input("1. Login \n 2. Register \n Input: "))
if option == 1:
login()
elif option == 2:
register()
... |
dd00206c5a8bec3da9ebaa27684446533b4e3fc9 | therewillbecode/Pong | /Class_Bar.py | 1,036 | 3.671875 | 4 | __author__ = 'Tom'
import pygame
__doc__ = """
"""
# class for paddle bar used to hit ball
class Bar:
cnt = 0 # cnt would be shared by all instances of the class
x_pos = 0 # x coordinate of centre of bar
# y_pos = pygame.mouse.get_pos()[1] # y coordinate of centre of bar
def __init__(self, leng... |
cc82493981ba16fe429c529accd475b6f1c11f4a | liuwei881/data_wrangling | /code/re_example.py | 273 | 3.8125 | 4 | #coding=utf-8
import re
word = '\w+' # 1
sentence = 'Here is my sentence.'
print re.findall(word, sentence) # 2
search_result = re.search(word, sentence) # 3
print search_result.group(0) # 4
match_result = re.match(word, sentence) # 5
print match_result.group(0) |
a57513fa53ec4ea0973d46432e020500291d4790 | MaxiSaito/code | /ahorcado.py | 5,018 | 3.859375 | 4 | #JUEGO DEL AHORCADO
#by Maximiliano Saito
#El usuario ingresa la dificultad(que hace variar la longitud de la palabra), se genera un numero random que se utiliza para traer la palabra de la lista
#Por defecto son 7 intentos para adivinar la palabra
import random
import os
facil = ['arena','arbol','vacio','l... |
4dc309b2493943adbec08cc80f171124dc6702f8 | minji9611/LikeLion_session | /assignment/hangman.py | 4,004 | 3.828125 | 4 | import random
HANGMAN_SUGGESTED_WORD_START_INDEX = 1
INPUT_ATTEMPT_WORD_MESSAGE = "도전할 문자를 적어주세요:"
INPUT_ATTEMPT_WRONG_WORD_MESSAGE = "올바른 형식으로 입력해주세요.(영어, 한글자)"
PRINTER_FINISH_GAME_MESSAGE = "MISSION COMPLETE: 행맨을 살렸습니다."
PRINTER_WRONG_LETTER_MESSAGE = "단어에 없는 문자입니다!"
PRINTER_FAIL_GAME_MESSAGE = "GAME OVER: 행맨이 죽었습니다... |
928021954a1298f8e06f423b903ea0e7240f1e5f | AndreW-CRA/beaglecar | /src/servo_controller.py | 2,561 | 3.828125 | 4 | #!/usr/bin/env python
import Adafruit_BBIO.PWM as PWM
# Author: Andrew Dai
# MIT License
# This class controls a servo by converting angles between 0 and 180
# into the proper frequency for servo PWM. It can also have maximum
# and minimum angles that clamp input angles.
class Servo:
"""Servo Controller defaults... |
df4f96a75c4a7a574324bb969cbf82e2b56b971a | mindedRK/MANUU | /7_prime_number_upto_n.py | 234 | 3.765625 | 4 | r=int(input("enter upper limt="))
m=int(input("enter lower limt="))
for n in range(m,r+1):
if n>1:
for i in range(2,n):
if(n%i)==0:
break
else:
print(n)
|
1c8a40002721cfa0a06f9935331874b8528347f3 | pulkitagrawal34/DeepDive-Python | /python deepDive part1/python_deepDive_part1.2.py | 15,654 | 4.375 | 4 | #Python -version: 3.7.3
"""
This Module covers:
1. Functions and Parameters
2. Positional unpacking and iterables
3. Fist class Functions
"""
def myfunc(a, b , c):
return "a = {0}, b = {1}, c = {2}".format(a,b,c)
myfunc(1,2,3) # returns a = 1, b = 2, c = 3
def my_func(a, b= 2 , c= 3): #Once you start assigning ... |
327f0fd65992b2909fb2470de691f26fd43b9c58 | sirajmuneer123/MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python | /problem_set_6/findBestShift.py | 537 | 3.796875 | 4 | # Problem 2: Decryption (findBestShift)
def findBestShift(wordList, text):
"""
Finds a shift key that can decrypt the encoded text.
text: string
returns: 0 <= int < 26
"""
### TODO
rWords=0
bShift=0
for i in range(26):
new_text=applyCoder(text,buildCoder(i))
iWords... |
e818b69cf91cc700cbe351b826e71d3fe0860eb9 | sirajmuneer123/MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python | /Quiz/count7.py | 222 | 3.625 | 4 | def count7(N):
'''
N: a non-negative integer
'''
# Your code here
if N==0:
return 0
else:
if N%10==7:
return 1+count7(N/10)
else:
return count7(N/10)
|
0cc442ea2ed19f5130e5cdff5886b6dce22441c4 | tayadehritik/NightShift | /fact.py | 217 | 4.1875 | 4 | args = int(input())
def factorial(num):
fact = num
for i in range(num-1,1,-1):
fact = fact * i
return fact
for i in range(args):
num = int(input())
fact = factorial(num)
print(fact)
|
e129f5a8054045c69543f6508cfd03e836387b74 | gercaballero/Estructuras-de-Datos-y-algoritmos | /UNIDAD 3/Practica 2- Pila y Cola/Ejercicio 6/classColaEncadenada.py | 1,285 | 3.703125 | 4 | class Nodo:
__item = None
__sig = None
def __init__(self, xitem=0):
self.__item = xitem
self.__sig = None
def setSiguiente(self,sig):
self.__sig = sig
def getSiguiente(self):
return self.__sig
def getDato(self):
return self.__dato
cla... |
17f4ea10b47ccddc3da5f1983f36c147e707a201 | gercaballero/Estructuras-de-Datos-y-algoritmos | /UNIDAD 3/Practica 2- Pila y Cola/Ejercicio 1/classPilaEncadenada.py | 1,407 | 3.84375 | 4 |
class Nodo:
__item=None
__siguiente=None
def __init__(self) -> None:
self.__item=None
self.__siguiente=None
def obtenerItem(self):
return(self.__item)
def cargarItem(self,xitem):
self.__item=xitem
def cargarSig(self,sig):
if is... |
ccad021a29205b90336a7e6f0066b3e3dd904a1d | gercaballero/Estructuras-de-Datos-y-algoritmos | /UNIDAD 3/Practica 2- Pila y Cola/Ejercicio 7/main.py | 2,116 | 3.765625 | 4 | import os
from classColaEncadenada import ColaEncadenada
from classCliente import Cliente
from classCajero import Cajero
from random import randint
if __name__ == '__main__':
os.system('cls')
Simulacion = 60
tiempoCaj = int(input(">>>Ingrese el tiempo de atencion cajero: "))
tiempoCli = int... |
9ce3937c23322a84647cef1d4823e8a0ad866a0d | gercaballero/Estructuras-de-Datos-y-algoritmos | /UNIDAD 3/Practica 2- Pila y Cola/Ejercicio 3/factorial.py | 291 | 3.859375 | 4 | from classPilas import PilaEncadenada
def factorial(num):
pila=PilaEncadenada()
fac=1
while num > 0:
pila.insertar(num)
num -= 1
while not pila.vacia():
x = pila.suprimir()
fac = fac * x
print('EL FACTORIAL ES: {}'.format(fac)) |
cd067c9c7ee918b908e31959d1e77d36dae5b36d | destrauxx/famped.github.io | /turtles.py | 469 | 4.125 | 4 | def is_palindrome(s):
tmp = s[:]
tmp.reverse()
print(s, 'input list')
print(tmp, 'reversed list')
if tmp == s:
return True
else:
return
def word(n):
result = []
for _ in range(n):
element = input('Enter element: ')
result.append(element... |
10d0d3e98ce827cbcd4b97171dd2e3858dc00a79 | miaocunfa/Python_demo | /python-crash-course/chapter-05/5-10.py | 310 | 3.59375 | 4 | current_users = ['admin', 'zhanan', 'zhanv', 'zhazha', 'zhagod']
new_users = ['admin', 'songjiang', 'zhazha', 'lujunyi', 'wuyong']
for new in new_users:
if new in current_users:
print(new + " is already in use, Please enter a different user name")
else:
print(new + " is not in use")
|
e1883b45d4eddbbd9d50562a1f357035cfb7cd90 | miaocunfa/Python_demo | /python-crash-course/chapter-07/7-9.py | 452 | 3.84375 | 4 | sandwich_orders = ['meat', 'pastrami', 'pastrami', 'tomato', 'pastrami', 'tuna']
finished_sandwiches = []
while sandwich_orders:
finish = sandwich_orders.pop()
if finish == 'pastrami':
print("Sorry, pastrami sandwich sold out!")
else:
finished_sandwiches.append(finish)
print("I... |
8444c22ea2d6dd8537ef6ac57c02095b8e4886a3 | miaocunfa/Python_demo | /python-crash-course/chapter-08/8-8.py | 632 | 3.828125 | 4 | def make_album(singer,album,num=''):
albums = {'singer': singer, 'album': album}
if num:
albums['num'] = num
return albums
active = True
while active:
print("\nPlease tell me you favorite album and singer?")
print("(enter 'q' at any time to quit)")
album = raw_input("album: ")
if ... |
86bb3f7ba91148112c26b29408a9ffbad9b7d91e | miaocunfa/Python_demo | /python-crash-course/chapter-06/6-7.py | 515 | 3.875 | 4 | friends_0 = {'first_name':'zha', 'last_name':'zha', 'age':'30', 'city':'dalian'}
friends_1 = {'first_name':'nan', 'last_name':'zha', 'age':'22', 'city':'nanning'}
friends_2 = {'first_name':'god', 'last_name':'zha', 'age':'25', 'city':'jinan'}
people = [friends_0, friends_1, friends_2]
for friend in people:
fullna... |
c2e7fbb3985b5da06bb931aef2c41d8386c2f92a | miaocunfa/Python_demo | /python-crash-course/chapter-04/4-13.py | 456 | 3.90625 | 4 | menu = ('TuDouSi', 'XiaoJiDunMoGu', 'YuXiangRouSi', 'JiaoZi', 'LaoCuHuaSheng')
print("this restaurant menu list are:")
for i in menu:
print(i)
#menu.remove(4)
#menu[1]="PiDanShouRouZhou"
#menu[2]="LiangPi"
menu = ('TuDouSi', 'PiDanShouRouZhou', 'LiangPi', 'JiaoZi', 'LaoCuHuaSheng')
print("\nNew products in summ... |
cec21d3c8727460e5904d9e40c18b4632cb699c2 | miaocunfa/Python_demo | /python-crash-course/chapter-03/append_array.py | 356 | 3.734375 | 4 | motorcycles = ['honda', 'yamaha', 'suzuki']
print("motorcycles is: ")
print(motorcycles)
motorcycles.append('ducati')
print("motorcycles append is: ")
print(motorcycles)
#---------------
print("")
motorcycles2 = []
motorcycles2.append('honda')
motorcycles2.append('yamaha')
motorcycles2.append('suzuki')
print("moto... |
bc984bf5d7d2b0dc5a3f590cb506d067d535e454 | miaocunfa/Python_demo | /python-crash-course/chapter-09/9-7.py | 1,186 | 3.859375 | 4 | # encoding=utf-8
class User():
"""定义用户"""
def __init__(self, first_name, last_name, age, address):
self.first_name = first_name
self.last_name = last_name
self.age = age
self.address = address
self.login_attempts = 0
self.full_name = self.last_name.title() + self.... |
641e2738588a9233ef3441bae485d8fda3da1bbf | miaocunfa/Python_demo | /python-crash-course/chapter-05/5-6.py | 239 | 3.953125 | 4 | age = 2
if age < 2:
print("is a baby")
elif age < 4:
print("is study walk")
elif age < 13:
print("is a children")
elif age < 20:
print("is young")
elif age < 65:
print("is man")
elif age >= 65:
print("is oldman")
|
4744ab0f63febb7552465785911df720523a387d | lofues/Sword_finger_offer | /表示数值的字符串.py | 510 | 4 | 4 | # -*- coding:utf-8 -*-
import re
class Solution:
# s字符串
def isNumeric(self, s):
# write code here
regex_int = re.compile('^[+-]?\d+$')
regex_float = re.compile('^[+-]?\d*\.\d+$')
regex_e = re.compile('^[+-]?\d*\.?\d*[Ee][+-]?\d+$')
if re.match(regex_int,s):
... |
89e28694416b0f776323c0d1ae9d4a3c65413354 | lofues/Sword_finger_offer | /树的子结构.py | 846 | 3.953125 | 4 | # -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
# write code here
if pRoot1 is None or pRoot2 is None:
return False
... |
4f0ba8241c51bb198d7ec2defee5d97b27685c13 | lofues/Sword_finger_offer | /数据流中的中位数.py | 508 | 3.734375 | 4 | # -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.num = []
def Insert(self, num):
# write code here
self.num.append(num)
self.num.sort()
def GetMedian(self, data):
# write code here
count = len(self.num)
if self.num == []:
... |
f6277a202c58f7588892095003a98fc111e3f952 | lofues/Sword_finger_offer | /按之字形顺序打印二叉树.py | 859 | 3.65625 | 4 | # -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def Print(self, pRoot):
# write code here
if pRoot is None:
return []
q = [(pRoot,1)]
ret = []
... |
b9437b9fc304951cd8d50659b9c3bdac5c952a08 | sagecorbett/Artificial_Intelligence | /CS50_TicTacToe_Minimax_Algorithm/tictactoe.py | 4,970 | 3.90625 | 4 | """
Tic Tac Toe Player
"""
import math
import copy
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
# return [[EMPTY, O, X],
# [X, O, EMP... |
add5caef2956f941bbc30788e4967ec3173fc56c | markoncan/Pycharm-Tuts | /more range.py | 211 | 3.828125 | 4 | def main():
print("number\tsquare")
print("------ ------")
for number in range(1,11):
square=number**2
##"\t"# escape characters
print(number,'\t','\t',square)
main() |
75e6da7317b84370036a12dc12f5818467a050a1 | annabroomhall/python-challenge | /PyPoll/main.py | 3,478 | 3.6875 | 4 | import os
import csv
import collections
from collections import Counter
csvpath = os.path.join('..','PyPoll', 'Resources','election_data.csv')
#Open file
with open(csvpath, mode='r') as csv_file:
csv_reader = csv.reader(csv_file,delimiter=',')
header = next(csv_reader)
#create empty Candidate List... |
e1fa6ea330bf404a9d6bbdac1aad2385766e0d4b | moadmmh/Competitive-Programming | /Warm ups/Python 3/705A.py | 104 | 3.8125 | 4 | n=int(input())
s="I hate"
for i in range (n-1):
s+=" that I "+["love","hate"][i&1]
print(s+' it')
|
df1e6ba7cf9944f65a040fb467ceb156f9882731 | d0x75/docs | /Programming/Python/code_scrolls/scroll-01-parsing_sql_file.py | 1,215 | 3.59375 | 4 | import sys
# PARSING SQL File
def parse_sql(filename):
data = open(filename, 'r').readlines()
stmts = []
DELIMITER = ';'
stmt = ''
# INICIANDO O LOOP, E VERIFICANDO SE HÁ ALGUM ESPAÇO EM BRANCO NA LINHA , SE HOUVER INTERROMPE A ITERAÇÃO ATUAL.
for lineno, line in enumerate(data):
if not... |
1d1f2800833cb58900a038a1fffe3200137d5fb4 | lee-seongmin/python_code | /vscode/homework1.py | 1,799 | 3.53125 | 4 | #%%
gugudan_button='y'
while(gugudan_button=='y') or (gugudan_button=='Y'):
final_num=int(input("구구단을 계산하고 싶은 범위의 숫자를 정해주세요!! "))
if final_num > 0 :
for i in range(1,final_num+1):
for j in range(1,10):
print(i*j, end=" ")
if(j==9):
... |
7b1e3c0b99350427a7fe6d5222345624aea21a46 | lee-seongmin/python_code | /vscode/example1.py | 355 | 3.546875 | 4 | x=int(input("첫번째 정수"))
y=int(input("두번째 정수"))
list_num=[]
if(x > y):
for i in range(1,y+1):
if(x % i == 0 and y % i == 0):
list_num.append(i)
else:
for i in range(1,x+1):
if(x % i == 0 and y % i == 0):
list_num.append(i)
print("최대공약수={0}".format(list_num.pop())... |
d45b6c683faa734fe4d199b2808da4a8d276d297 | ncfxy/TOJ_Plus_Plus | /linux和python脚本/deal_with_seq_file.py | 2,430 | 3.859375 | 4 | # -*- coding: utf-8 -*-
# This program will deal with the programName#index.cseq.csv and
# generate a programName#index.cseq_update.csv
# It combine the same sequence and add them together.
import csv
class MyMap:
# This class is a map struct for this program
def __init__(self,arg1,arg2,arg3,arg4,arg5,arg6,ar... |
1983cb2acc2fe1e47d1da6135550e53cd771fcc9 | guoyuMao/python_study | /DataStructure.py | 6,243 | 3.5625 | 4 | # vec = [2,4,6]
# test = [3*x for x in vec]
# print(test)
#
# test = [[x,x**2] for x in vec]
# print(test)
#
#
# freshfruit=[' banana',' loganberry ',' passion fruit ']
# test = [weapon.strip() for weapon in freshfruit]
# print(test)
#
# test = [3*x for x in vec if x > 3]
# print(test)
#
# test = [3*x for x in vec if ... |
42160b7b926a67cfea2f482584f39c38e11c4c17 | ssenviel/Python_Projects-Udemy_zero_to_hero | /Generators_play.py | 909 | 4.46875 | 4 | """
problem 1:
create a Generator that generates the squares of numbers up to some number 'N'
problem 2:
create a generator that yields "n" random number between a low and high number
NOTE: use random.randrange or random.randint
problem 3:
use the iter() function to con... |
7003dc4e7e1f2faac6f76f0835657b8cde7b3ce4 | SiddharthHareendran/-Cantor-Lebesgue-CDF | /Cantor.py | 625 | 3.578125 | 4 | import numpy as np
import matplotlib.pyplot as plt
def cantor(x,left_bound=0,right_bound=1,level=1,v_offset=0):
division = (right_bound-left_bound)/3
if level>50: return 1/2**level + v_offset
if x < left_bound + division:
return cantor(x,left_bound,left_bound+division,level+1,v_offset)
elif x < ... |
158e5c8693437468353bafc0ff25473c203496b1 | odooku/odooku | /odooku/helpers/split.py | 178 | 3.71875 | 4 | def split(value, seperator):
splitted = [
part.strip()
for part in value.split(seperator)
if value.strip()
] if value else []
return splitted
|
8545fa637d75a788d7fe6c1c6b2ae2b06e323780 | L-E-Freeman/Typist-Game | /text.py | 3,290 | 3.75 | 4 | from random import choice
import pygame
import pygame.freetype
from settings import Settings
class Text:
"""A class to manage the quote appearing on screen"""
def __init__(self, t_game):
"""Initilize colour attributes and set text location"""
# Assign screen to attribute of Text.... |
9dcf4b33ccf022947239061c307334a7977eb9ec | Kevintjy/Python-Beginner | /pyta/Week11_summer/test.py | 234 | 3.90625 | 4 | def find_odd(obj):
if isinstance(obj, int):
return [obj] if obj % 2 == 1 else []
else:
s = []
for i in obj:
s += find_odd(i)
return s
print(find_odd([1,[2],3,[[[4,5,6],7],8],9])) |
017e216aefd3004a3353d7e62a50f729e96686d2 | Kevintjy/Python-Beginner | /csc148 fall/assignments/a1/simulation.py | 7,929 | 3.53125 | 4 | """CSC148 Assignment 1 - Simulation
=== CSC148 Fall 2018 ===
Department of Computer Science,
University of Toronto
=== Module description ===
This contains the main Simulation class that is actually responsible for
creating and running the simulation. You'll also find the function `sample_run`
here at the bottom of t... |
e3d19bcd4e94d17678e82cf986d8eff35c91b0e8 | Kevintjy/Python-Beginner | /pyta/Week3_summer/lab2/clothes.py | 2,337 | 3.5625 | 4 | class SadWalletError(Exception):
'''
vbn
nothing
'''
pass
class NotInClosetError(Exception):
'''
nothing
'''
pass
class Person:
'''
nothing
'''
def __init__(self, clothes, money):
'''
nothing
'''
self.clothes = clothes
self.cl... |
9b08c6919fcff9a1775edb2f8bcd7658d96d6690 | Kevintjy/Python-Beginner | /pyta/Week5_summer/Lab4/lab4.py | 5,788 | 4.3125 | 4 | from typing import Union, Any
class LinkedListNode:
"""
A Node to be used in a LinkedList.
next_ - The successor to this LinkedListNode
value - The data represented by this LinkedListNode.
"""
next_: Union["LinkedListNode", None]
value: object
def __init__(self, value: object,
... |
e092bc436c397baead756a930c1d5244605d74ce | Kevintjy/Python-Beginner | /pyta/Week7_summer/lab5.py | 2,029 | 4.0625 | 4 | """
This is lab 5
"""
def count_odd(x):
"""
count odd
"""
if isinstance(x, int):
return 1 if x % 2 == 1 else 0
return sum(count_odd(i) for i in x)
def count_longer_than(x, length):
"""
count_longer_than
"""
if isinstance(x, str):
return 1 if len(x) > length else 0... |
d7b1ee269eadcf9a913e49558f9572a360d4e068 | alaaHdiab/Python_iti | /ass/ass1.py | 200 | 3.90625 | 4 |
num=input("enter number:");
for q in range(int(num)):
for k in range(int(num)-(q+1)):
print(' ',end='');
for v in range(q+1):
print('* ',end='');
print("\n");
|
f82c6a07af144786d5063796e0fa8b8575acbefa | cisco-iamit/spacex-api-home-project | /spasex.py | 1,517 | 3.984375 | 4 | """
Functionality related to SpaceX API
"""
import requests
def get_launches() -> list:
"""
Return the list of all past launches.
:return:
"""
url = 'https://api.spacexdata.com/v2/launches/'
response = requests.get(url)
# status code 200 means everything is ok
# see https://httpstatu... |
bd160ff2bbf7bc2b6c004d39a51180a45c0e9a84 | MarceloSaied/py | /python/helloworld/python1.py | 485 | 4.15625 | 4 | # print ("hello world")
# counter = 100 # An integer assignment
# miles = 1000.0 # A floating point
# name = "John" # A string
import datetime
currentDate = datetime.date.today()
currentDate=currentDate.strftime('%a %d %b %y')
print(currentDate)
# print (counter)
# print (miles)
# print (n... |
bcabaff67f4bf9503b44a5573c761d5763ad3d8c | yifeiacc/userinfluence | /EdgeWeightedGraph.py | 488 | 3.5 | 4 | class EdgeWeightedGraph(object):
"""docstring for ClassName"""
def __init__(self, v):
self.V = v
self.E = 0
self.adj = []
for _v in range(0, v):
self.adj.append(set())
def num_V(self):
return self.V
def num_E(self):
return self.E
def addEdge(self, e):
v1 = e.either()
v2 = e.other(v1)
self.ad... |
50c5a465cafd2c4ad95b7e97c43d1dbb47ba6ba7 | yifeiacc/userinfluence | /ShortestDisTree.py | 840 | 3.625 | 4 | from PQ import IndexMinPQ
class ShortestPath(object):
"""docstring for shortestPath"""
def __init__(self, G, s):
self.edgeTo = []
self.distTo = []
self.pq = IndexMinPQ(G.V())
for v in range(0, G.V()):
self.distTo.append(float("inf"))
self.edgeTo.append(None)
self.distTo[s] = 0.0
self.pq.insert(s, 0.... |
fbf72b0e835028e60443c48f6997904adee54aec | FRustSolutions/AdventOfCode20 | /Day05/Day05_01.py | 2,309 | 3.640625 | 4 | # --- Day 5: Binary Boarding ---
# https://adventofcode.com/2020/day/5
# The first 7 characters will either be F or B; these specify exactly one of the 128 rows on the plane
# (numbered 0 through 127). Each letter tells you which half of a region the given seat is in.
# FBFBBF:
# Start by considering the whole range... |
ceb5422cffceb54c53d56fa93db64f04e2f4f255 | saularraffi-fo6197/Leetcode-Solutions | /Easy/Add Digits.py | 506 | 3.640625 | 4 | class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
sum = 0
while int(num / 10) != 0:
while num != 0:
sum = sum + int(num % 10)
num = int(num / 10)
num = sum
sum = 0... |
a0eb038af0e2de668709eac985a99d0de89e999e | bluemutheu/python-intro | /test.py | 272 | 3.921875 | 4 | unique = set ([2,3,5,5,6,6,6])
print (unique)
n = int (input())
if (n%2 > 0) or ((n%2 == 0) and (n>=6 and n <=20)):
print ("weird")
elif ((n%2 == 0) and (n >=2)and (n<= 5)) or ((n%2 == 0) and (n>20)):
print ("Not weird")
else : print ('This is the end') |
4a0e75998296679dcf244b920e50d4e94be3dc8f | emushtaq/ml-scratch | /orange_apple_supervised_decisionTreeClassifier.py | 905 | 3.828125 | 4 | from sklearn import tree
# Hardcoding feature vector of the fruits. Using feature weight and texture (0 ~ bumpy, 1 ~ smooth)
features = [[140, 1], [150, 1], [160, 0], [170, 0], [180, 0]]
# Hardcoding the training labels (0 ~ apples, 1 ~ oranges)
labels = [0, 0, 1, 1, 1]
# Initializing a classifier
clf = tree.Decisio... |
17a2cde8c56eb6fd8a805ac8cd8a8e4c49495894 | jwilber/artcamp | /artcamp/utils.py | 2,093 | 3.578125 | 4 | import json
import requests
import pandas as pd
from bs4 import BeautifulSoup
def load_json(file_path):
with open(file_path) as json_data:
d = json.load(json_data)
return d
def fetch_url(url, tags, verify, strip_unicode):
"""
Scrapes and fetches front-page text content for a given url... |
19ca0463a2f17224003f9c798781e26bb7ff5650 | tmackall/test | /llist01.py | 426 | 3.609375 | 4 |
class node(object):
def __init__(self, data_in):
self.data = data_in
self.next = None
self.prev = None
class llist(object):
def __init__(self):
self.head = None
self.tail = None
self.node = None
def insert(self, node_in):
self.tail.next = node_in
... |
5692e35df3b71c626215663eadcfdce029f19bf2 | tmackall/test | /slice01.py | 631 | 3.875 | 4 | #!/usr/bin/python
#
# test string - create it ('01234567890')
test_str = ''
for i in xrange(10):
test_str += str(i)
print 'test string: %s' % test_str
#
# slice - original string
print 'original string: %s' % (test_str[:3] + test_str[3:])
# reverse
print 'reverse: %s' % test_str[::-1]
# reverse - every other
... |
6ee0d3c8a2166eb5cd87e062774a35e82284cc2f | tmackall/test | /btree03.py | 2,833 | 3.796875 | 4 | #!/usr/bin/python
import random
class btree(object):
def __init__(self, val):
'''
__init__() - initialize val and set left and right to None
'''
self.val = val
self.left = None
self.right = None
def add(self, val):
# if the new value is less than the c... |
39a87f32c213a0a69ff53f30f961700e42cc9232 | shereengh/python | /classes_task.py | 2,491 | 4.09375 | 4 | import datetime
class Employee(object):
def __init__(self, name, age, salary, employment_date):
self.name = name
self.age = age
self.salary = salary
self.employment_date = employment_date
datetime_object = datetime.datetime.now()
def get_working_years(self):
datetime_object = datetime.datetime.now()
r... |
39dded554cd24c8411a767b0707e9694822ebf0e | Yunjusik/Blockchain | /DRL_BC/blockchain_networking/channel_space.py | 825 | 3.5 | 4 | import numpy as np
import gym
class ChannelSpace(gym.Space):
"""
{0,1,2}
0: channel is idle
1: channel is busy
2: unknown
Example usage:
self.observation_space = spaces.ChannelSpace
"""
def __init__(self):
self.n = 3
gym.Space.__init__(self, (), np.int64)
def sa... |
72efcc3be5fc63d62fe142821d283e517ab0a640 | WhiteRadish-Hwang/Algorithm_study | /2231.py | 520 | 3.5 | 4 | n = int(input())
def min_creation():
cre_param = '1' #생성자
element_sum = 0 #분해합
while not cre_param == '1000000' and int(cre_param) < n:
element_list = list(cre_param)
element_list = list(map(int, element_list))
element_sum = sum(element_list) + int(cre_param)
if element_sum ... |
d10bab7c6bba7c959e1d3ff25e67f965010a2919 | realdragonhead/dragonPy | /dataframe/csvToDataFrame.py | 1,394 | 3.734375 | 4 | import pandas as pd
import csv
# Convert list to dataframe
def makeListtoDataFrame(converted_csv_list, header):
try:
df = pd.DataFrame(converted_csv_list)
if header == True:
columns_header = df.iloc[0]
df = df[1:]
df.rename(columns = columns_header, inplace=True)
except Exception as e:
# Handling erro... |
362a7cdcf58616408a8dfd1f43058a5d27a4f9e5 | d1makov/py_sqlphones | /contacts.py | 1,752 | 3.6875 | 4 | """
Module with phonebook options
create
read
update
delete
_save into pickle file
"""
import pickle
class PhoneBook:
"""
Phonebook class
"""
def __init__(self):
self._file = 'phone_book.pickle'
self._book = {}
def create(self, name, phone):
"""
Create a new contac... |
6a3cae879dc55b33f56ffe2706fe46422624ace5 | qdzhangyuhui/201834889ZhangYuhui | /Homework1vsm_and_knn/knnn.py | 1,128 | 3.5 | 4 | import numpy as np
from sklearn import neighbors
key=1
def load_data(path):
train=np.loadtxt(path,delimiter=",", skiprows=0)
vec_train=train[0:,0:-1]
label=train[0:,-1]
labels=[int(i) for i in label]
#print(type(labels) )
return vec_train,labels
def main():
print('knn hello~')
vec_train,... |
7be5a637ee61bfc7d8a2a292e8cd28a31acb5022 | pulse2percept/pulse2percept | /pulse2percept/utils/optimize.py | 2,551 | 3.65625 | 4 | """`bisect`"""
import numpy as np
import logging
def bisect(y_target, func, args=None, kwargs=None, x_lo=0, x_hi=1,
x_tol=1e-6, y_tol=1e-3, max_iter=100):
"""Binary search (bisection method) to find `x` value that gives `y_target`
For a function ``y = func(x, *args, **kwargs)``, returns ``x_opt`` ... |
459cea848ff3f089f43be520761739aac01ca7ab | pulse2percept/pulse2percept | /examples/implants/plot_custom_electrode_array.py | 6,434 | 3.75 | 4 | """
============================================================================
Creating your own electrode array
============================================================================
This example shows how to create a new
:py:class:`~pulse2percept.implants.ElectrodeArray` object.
As the base class for all el... |
d33423f2209961d331de5ec648293751fd0b46f0 | alienshoban/machine-learning | /2-loan-prediction/missing-values.py | 3,553 | 3.5 | 4 | #https://trainings.analyticsvidhya.com/courses/course-v1:AnalyticsVidhya+LP101+2018_T1/courseware/
# Missing Values
# Load libraries
import pandas as pd
import numpy as np # For mathematical calculations
import seaborn as sns # For data visualization
import matplotlib.pyplot as pl... |
e375959b07edb75c6f926d92cd016ac957a15e55 | ZombieWrecker29/CheeseOS-21.1.21 | /CheeseOS_Release_21.1.21/files.py | 2,046 | 3.828125 | 4 | print("Welcome to the CheeseOS File Explorer!")
print("What would you like to do?")
print("1. Create a file")
print("2. Open a file")
print("3. Exit CheeseOS File Explorer")
action1 = input()
if action1 == "1":
print("What is the name of the file you would like to create?")
filename = input()
print("What da... |
e50363bebea3ff601ce15045b659e23772686409 | DevrajVisesh/PYTHON_EXERCISES-01 | /ADD.py | 123 | 3.53125 | 4 | #Program on performing Addition Operation
m1 = 60
m2 = 70
m3 = 80
totmarks= m1 + m2 + m3
print("total marks are:",totmarks) |
d65636f2b048813c6662dc78e20a5d063fbde0b7 | tangtangchn/python-playlist | /json/json_parse.py | 379 | 3.5625 | 4 | # JSON
# Javascript对象表示法
# 在Python中,JSON以字符串形式存在
# p = '{"name": "Alice", "languages": ["Python", "Java"]}'
import json
# 使用json.loads()方法解析JSON字符串
# 该方法返回一个字典
person = '{"name": "Bob", "languages": ["English", "French"]}'
person_dict = json.loads(person)
print(person_dict)
print(person_dict['languages'])
|
500515c10d56717d3cfd4ff19fb523b482a30f5a | ezerc/Qiskit_Projects | /Shor_Factorization/factorization_shor_algorithm.py | 19,965 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 28 11:58:15 2021
@author: Ezequiel
"""
import sys
from qiskit import *
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
import numpy as np
pi = np.pi
from fractions import Fraction
from math import... |
4138e768b2e136f3ff6f1a37b4e05d108c6dad3e | changooman/HeyThatsMyFish | /version-one-queencity/3/Other/tester2.py | 6,397 | 3.84375 | 4 | import unittest
from state import *
from fish import *
# This test class serves to test the creating a state for a certain number of players.
class Testing_CreatingState(unittest.TestCase):
# Tests if two players used in a GameState creates a GameState with two players.
def test_creatingstate(self):
... |
9e48853d14e4a5a569fc7989ced76a97fa396b34 | changooman/HeyThatsMyFish | /version-one-queencity/Fish/Admin/Other/referee_tests.py | 26,522 | 3.53125 | 4 | import unittest
from state import *
from board import *
from strategy import *
from game_tree import *
from referee import *
from player import *
# This test class serves to test the referee function that will return a list of player instances
class TestReferee(unittest.TestCase):
# tests a board with 3 players a... |
5565e55b523ee8f55dfb62c8a5c2d3fd774ac5f6 | changooman/HeyThatsMyFish | /version-one-queencity/3/Other/tester.py | 5,174 | 3.53125 | 4 | import unittest
from fish import *
# This test class serves to test the neighbors function which returns the neighbors of a tile
# It checks to see if the function will return the correct amount of neighbors for a hexagon tile
class Testing_Neighbors(unittest.TestCase):
def test_neighbor(self):
hex_board ... |
6f0a33a88fffab1141140d39be677c2dbbefb26c | furixturi/ud036 | /lesson-5/movies/media.py | 793 | 3.53125 | 4 | # -*- coding: utf-8 -*-
'''
title
storyline
poster_image_url
trailer_youtube_url
*self will be automatically added at instantiation
'''
import webbrowser
class Movie():
""" This class provides a way to store movie related information"""
VALID_RATINGS = ["G", "PG", "PG-13", "R"]
# constructor, being c... |
05dd092e56a1ddd8d4f4f75dc1bbbd0c86359876 | bepstein111/Code-Class | /24-Statistics/DataVisualization/DataVisualization.pyde | 1,637 | 3.6875 | 4 | values = [10, 9, 73, 25, 33, 76, 52, 9, 35, 86]
def mean(sequence):
sum = 0.0
for element in sequence:
sum = sum + element
return sum/len(sequence)
def median(seq):
seq.sort()
half = len(seq)/2
if (len(seq)%2 == 0):
return list([seq[half-1],seq[half]])
else:
return ... |
7878bdd36cd87c619c45301b617f63e6ed8c92f4 | bepstein111/Code-Class | /22-Audio/Code/Ball1_Collision/Ball.py | 995 | 3.609375 | 4 | class Ball():
def __init__(self,ballX,ballY,ballVX,ballVY,ballDiam, ballR,ballG,ballB):
self.ballX = ballX
self.ballY = ballY
self.ballVX = ballVX
self.ballVY = ballVY
self.ballDiam = ballDiam
self.ballCol = color(ballR,ballG,ballB)
def moveBall(self):
f... |
08e42ea8480966910d76ce5331d5a3281da02ffb | sN0wpeak/leetcode | /algorithm/[85]maximal-rectangle.py | 1,440 | 3.640625 | 4 | # 给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
#
# 示例:
#
# 输入:
# [
# ["1","0","1","0","0"],
# ["1","0","1","1","1"],
# ["1","1","1","1","1"],
# ["1","0","0","1","0"]
# ]
# 输出: 6
# Related Topics 栈 数组 哈希表 动态规划
# leetcode submit region begin(Prohibit modification and deletion)
from typing import List
... |
7430e17d1c424362399cf09a0c3ecae825d04567 | this-will-do/Project-Euler | /prob19/prob19.py | 147 | 3.6875 | 4 | import datetime
count = 0
for y in xrange(1901,2001):
for m in xrange(1,13):
if datetime.date(y,m,1).weekday() == 6:
count += 1
print count
|
f28774937fa79b7531329155bb7ffe7f37064122 | selvendiranj-zz/pyth-coin | /python/test_pow.py | 1,896 | 3.5625 | 4 | import hashlib
import json
def hash(block):
"""
Creates a SHA-256 hash of a Block
:param block: Block
"""
# We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes
block_string = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(block_string).he... |
1ddad2e300524a20affd9645a211b2e7d52f3589 | btkhimsar/OpenCV | /List/Ex1.py | 262 | 3.546875 | 4 | #Same type of data
print([1, 2, 3])
print(['cat', 'bat', 'rat', 'elephant'])
print("\n")
#Diffrent type of data
print(['hello', 3.1415, True, None, 42])
print("\n")
#List saved in a variable
spam = ['cat', 'bat', 'rat', 'elephant']
print(spam)
|
c648e44b121c114f7fc4d4d28b83700720388604 | jw3329/algorithm-implementation | /sort/selectionsort.py | 600 | 4.1875 | 4 | def swap(arr, i, j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
# find minimum element, and swap with its element from the start
def selectionsort(arr):
for i in range(len(arr)):
min_index = i
for j in range(i + 1, len(arr)):
if arr[min_index] > arr[j]:
min... |
417d008c80e55195baa1adabcc8f753fd65b96bf | Jochizan/courses-python | /programs-python/generators_3.py | 450 | 3.875 | 4 | def devuelve_ciudades(*ciudades):
for elemento in ciudades:
# for subElemento in elemento:
yield from elemento
ciudad_devueltas = devuelve_ciudades("Madrid", "Barcelona", "Bilbao", "Valencia")
print("Madrid", "Barcelona", "Bilbao", "Valencia")
print(ciudad_devueltas)
for letter in ciuda... |
a671d16233c640548177db2fd5ea4b07935385c1 | Jochizan/courses-python | /palindromes.py | 232 | 3.828125 | 4 | s = input('Ingrese una palabra a evaluar: ')
s = s.replace(' ', '')
s = s.lower()
tmp = s[::-1]
if tmp == s:
print("Es palindromo")
else:
print("NO es palindromo")
# codigo simple para verficar un palindromo con python :)
|
5a814ad4abbd8822de6a69cb64decc060210b84c | Jochizan/courses-python | /programs-python/manager_files.py | 1,005 | 3.625 | 4 | from io import open
archivo_texto=open("archivo.txt", "r+") # lectura y escritura
# archivo_texto.write("\n Siempre es una buena ocasión para estudiar Python")
# archivo_texto.close()
# lineas_texto = archivo_texto.readlines()
# archivo_texto.close()
# print(lineas_texto)
# texto = archivo_texto.readlines()
# a... |
0c0c5b19a66865813c60c497a4e60cbe917bc66e | Jochizan/courses-python | /programs-python/permanent_information.py | 1,769 | 3.765625 | 4 | import pickle
class Persona:
def __init__(self, nombre, genero, edad):
self.nombre = nombre
self.genero = genero
self.edad = edad
print("Se ha creado un persona nueva con el nombre de ", self.nombre)
def __str__(self):
return "{} {} {}".format(self.nombre, self.genero,... |
041054b1928e457dae94e55f55c285c56d8e511e | D-linguist/test_tasks_performance_lab | /task2/task2.py | 460 | 3.53125 | 4 | from math import sqrt
from collections import defaultdict
with open('файл1') as f:
x, y = [int(x) for x in next(f).split()]
r = int(next(f))
with open('файл2') as f:
d = defaultdict(float)
for line in f:
key, value = line.split()
d[float(key)] = (float(value))
for key in d:
h = s... |
f629efc2d7166857c966d0d99f3eef7e9fa52b3b | pymft/mft-05 | /S10/oop_review/main.py | 840 | 4 | 4 | # class Person:
# def __init__(self, name):
# self.__name = name
#
# def get_name(self):
# return self.__name
#
# def set_name(self, value):
# self.__name = value
#
# name = property(get_name, set_name)
#
# class Person:
# def __init__(self, name):
# self.__name = na... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.