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 |
|---|---|---|---|---|---|---|
69cb103b973403f0663ffa34db2391de748d6dc2 | baybailz/PythonChallenge | /PyBank/main.py | 2,272 | 3.625 | 4 | import os
import csv
bankData = os.path.join('budget_data.csv')
output_path = os.path.join('output.txt')
months = []
numbers = [] # (profit and losses)
difference = []
with open(bankData, 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
header = next(csvreader)
for row in csvre... |
070deb834559da8bb1f375f6b7d7e78fd8b1df3a | sam16222/CSC510_43 | /src/data.py | 1,421 | 3.625 | 4 | from col import Cols
from main import the
from misc import isfloat, coerce, csv, push
from row import Row
class Data(object):
"""Class Data to add a 'Row' to 'data'"""
def __init__(self, src):
"""Contructor to initialize cols, rows and add the 'Row' to 'data'"""
self.cols = None
self.r... |
3dd09e91200b964ae1114bf6d655fcb9776816fd | EnricoFiasche/assignment1 | /scripts/target_server.py | 1,276 | 4.125 | 4 | #!/usr/bin/env python
import rospy
import random
from assignment1.srv import Target, TargetResponse
def random_target(request):
"""
Function that generates two random coordinates (x,y) given the range
(min,max)
Args:
request: The request of Target.srv
- minimum value of the random coordinate
- maximum va... |
d4f434b043bacf8707ef29d76e41c5d434f8c5dc | JulCesWhat/Show_Me_the_Data_Structures | /problem_1.py | 2,136 | 3.640625 | 4 | class Cache_Item(object):
def __init__(self, data, pos):
self.data = data
self.pos = pos
class LRU_Cache(object):
def __init__(self, capacity):
# Initialize class variables
self.dic = dict()
self.lis = list()
self.capacity = capacity
def get(self, key):
... |
72582b54f3a556ad8b90e18ed6542d0e68211487 | bluestar31/dinhthanhlong-fundamental-c4e13 | /Session 1/Homework/Exercise_2_area.py | 73 | 3.78125 | 4 | r = float(input("Radius? "))
Area = 3.14 * r ** 2
print("Area = ", Area)
|
c77d6ecc50fd891ff7f04ed88581f7cd86dc0c51 | bluestar31/dinhthanhlong-fundamental-c4e13 | /Session 4/Homework/study_20_8_1.py | 970 | 3.875 | 4 | # Solution 1
string = 'ThiS is String with Upper and lower case Letters'
string = string.lower()
alphabet = 'abcdefghijklmnopqrstuvwxyz'
letter_count = {}
for char in string:
if char in alphabet: # ignore any punctuation, numbers, etc
if char in letter_count:
letter_count[char] = letter_count... |
ade7df7b32136c83ad70f806880fd0ee9e8508d3 | bluestar31/dinhthanhlong-fundamental-c4e13 | /Session 2/maze.py | 116 | 3.828125 | 4 | from turtle import *
shape("turtle")
speed(0)
for i in range(5, 500, 5):
forward(i)
left(90)
mainloop()
|
9d7239fbd777694df3d28c2b21dcfc7f9aac3fe1 | bluestar31/dinhthanhlong-fundamental-c4e13 | /Session 2/Homework/Exercise04_print_b.py | 185 | 4 | 4 | n = int(input("Enter a number: "))
for i in range(n):
print("x *", end = " ")
# Same 4d
# This is another solution
# print("x", end = " ")
# print("*", end = " ")
|
c734596501b09b58444cd85f2d653c81ae553db2 | Tarunkumar2498/skillrack_codes | /alternatingcharacters.py | 707 | 3.78125 | 4 | """code written in python 3 by TARUN KUMAR on 17/06/2018
This code prints the alternating x characters in a string
example:
inputs:
ENVIRONMENTAL(string)
3(distance)
output:
ENVNMEL
The code should print the first 'x' characters then it should skip the foll... |
a3af77c55562a3c70c9b1ee570086bc941b9bbee | Sidhved/Data-Structures-And-Algorithms | /Python/DS/Trees.py | 1,731 | 4.375 | 4 | #Program to traverse given tree in pre-order, in-order and post-order fashion
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Tree:
def __init__(self, root):
self.root = TreeNode(root)
def inorderTraversal(self, node, path):... |
ba726a8761c291cdea04c669e114cdaaf1485f98 | jonghwanhyeon/snippets | /merge_dict/merge_dict.py | 1,106 | 3.671875 | 4 | from copy import deepcopy
def merge_dict(left, right):
if not isinstance(right, dict):
return right
merged = dict(left)
for key, value in right.items():
if isinstance(merged.get(key), dict):
merged[key] = merge_dict(merged[key], value)
else:
merged[key] = d... |
0fa3ef2f3de21ce37eac36b03fbc75841f82c598 | SoniaComp/LIKELION_Session | /python_exercise/hw.py | 876 | 3.671875 | 4 | '''
# 연습문제
# 리스트
a = ['Life', 'is', 'too', 'short']
result = ' '.join(a)
print(result)
# 별찍기
i=0
s=''
while i < 5:
s+='*'
print(s)
i+=1
#아니면, print('*' * i) 이런식으로 찍어내도 된다.
# 모음찾기
s = [i for i in "mutzangesazachurum" if i in "aeiou"]
print(len(s))
'''
#1-1
# i = 1
# sum = 0
# while i<1001:
# if i%3 == 0:
# ... |
ef787d25b4cbe9bf424086a5545ec38fd45c9997 | Wrenzepi/RandomWalk | /random_walk.py | 7,120 | 3.578125 | 4 | #!/usr/bin/env python3
'''
Author: David Kohler
random_walk.py
'''
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import seaborn as sns
def user_customization_1D():
'''
Prompts user for customization options for 1D
'''
sns.set_palette('husl')
n_string ... |
f188b2c65ba43c3a61443e128fb5131c03c90f15 | artemrazer/HW2 | /2b.py | 158 | 3.5625 | 4 | N = 350
under = float(1e0)
over = float(1e0)
for i in range (N):
under = under / 10.
over = over * 10.
print (i, 'UNDER = ', under,'OVER = ', over)
|
f1d05054ad7dce2238358316a0e24d8c0ffa207a | bmrabiulalam/Learn-Python | /w3schools/1-Syntax/ex8-Functions.py | 3,205 | 4.6875 | 5 | #======================================================
#Python Functions
#======================================================
#A function is a block of code which only runs when it is called.
#You can pass data, known as parameters, into a function.
#A function can return data as a result.
#Creating a Function
def... |
fb857923f6d8eec026000ac21505136eba8691e8 | GeomEunTokki/ToDoList | /test.py | 656 | 3.984375 | 4 | # The goal of "test.py" is to enact a basic first pass test to the app's database
#
# sqlite is the database engine chosen to use
import sqlite3
# initiate connection with SQL database
connection = sqlite3.connect("project.db")
# here, the cursor acts as a pointer to the database
cursor = connection.cursor()
# SQL c... |
05d8cd5f1958c6dac9ca1e27c3e27a1d127b2818 | xavierfonsecaphd/AI-Tutorials | /1 - Machine Learning/3 - Unsupervised _Clustering/3 - DBSCAN/How to DBScan Python.py | 16,643 | 3.890625 | 4 | """
DBSCAN Algorithm
Let's:
Use DBSCAN to do Density based clustering
Use Matplotlib to plot clusters
Most of the traditional clustering techniques, such as k-means, hierarchical
and fuzzy clustering, can be used to group data without supervision. However,
when applied to tas... |
ef75cd06efa45f44cd98a245c4f68d064c9b22ff | xavierfonsecaphd/AI-Tutorials | /1 - Machine Learning/1 - Supervised _ Regression/Polynomial Regression/1 - HOW TO - Polynomial linear Regression Scikit-learn.py | 5,507 | 3.75 | 4 | """
Created on Thu Apr 22 11:06:12 2021
@author: Xavier Fonseca
"""
import matplotlib.pyplot as plt
import pandas as pd
import pylab as pl
import numpy as np
%matplotlib inline
df = pd.read_csv("/Users/Xavier/GoogleHDD/Trabalho/1 - Cursos/Machine Learning with Python - Coursera/1 - Supervised _ Polynomial Regression... |
e13bb827654807109474af834df6a5e4a7f0d7c3 | jiaweichen99/CSE337 | /a1/1a.py | 532 | 3.921875 | 4 | def pal_test_iterative (string):
# stopping case, either we went through entire str or one letter left
while (len(string) > 1):
# last letter == first letter?
if (string[0] != string[-1]):
return False
string = string[1:-1]
return True
# test cases taken from lecture slides
s1 = "racecar" # Tru... |
8785a1ce3aacc3854ceb84e44ff12715623f4d4c | BenjaminAm/python_guard_dog | /vulnerability/vulnerability.py | 2,058 | 3.53125 | 4 | from enum import Enum
from dataclasses import dataclass
import colorama
colorama.init()
class VulnerabilityLevel(Enum):
"""
Enum of the severity levels corresponding to vulnerability type
"""
low = 0
moderate = 1
high = 2
@dataclass
class VulnerabilityType:
"""
Dataclass representin... |
b271076565916c6a318167a0066c6518e9638016 | elavallee/learnMorse | /smorse.py | 1,904 | 3.75 | 4 | from itertools import chain
morseDict = {'a':'.-',
'b':'-...',
'c':'-.-.',
'd':'-..',
'e':'.',
'f':'..-.',
'g':'--.',
'h':'....',
'i':'..',
'j':'.---',
'k':'-.-',
... |
036cadc559a3472d001e2d9a70d55d4b2364f116 | PJOGomes/Euler | /multipleof3and5.py | 127 | 3.921875 | 4 | sum = 0
for i in range (1, 1000):
if(i%3==0 or i%5 ==0):
sum+=i
print ("{}==>{}".format(i, sum))
print(sum) |
c44ed928d0a16eb6d7fdf4ba9fc382167ad9f94c | captainAyan/pycryptor | /controller.py | 2,888 | 3.625 | 4 |
from tkinter import filedialog
from tkinter import messagebox
import utility as util
from cryptography import Cryptography as crypt
class Controller:
def __init__(self, files, listbox):
self.files = files
self.listbox = listbox
self.error = ""
# adds file to list
def add(self):... |
da25d0c6be3b94b731926d72b9bc89a780b68138 | MPNeale/Current-Emerging-Trends | /TreasureMaze.py | 6,155 | 3.59375 | 4 | # This class represents the environment, which includes a maze object defined as a matrix.
import numpy as np
visited_mark = 0.8 # The visited cells are marked by an 80% gray shade.
pirate_mark = 0.5 # The current cell where the pirate is located is marked by a 50% gray shade.
# The agent can move in one of four... |
56247952dc8d2fbefcfac9b34bc472bdf61b2c68 | snehal0307/print-positive-no | /Positiveno.py | 196 | 3.828125 | 4 | list1=[12,-7,5,64,-14]
print(list1)
for n in list1:
if n>=0:
print(n,end=" ")
print("\n")
list2=[12,14,-95,3]
print(list2)
for num in list2:
if num>=0:
print(num,end=" ")
|
24fbbfe858e4239484d8550dc277c7b2be3d42a8 | zkroliko/DeepSearch | /model/Field.py | 1,260 | 3.546875 | 4 | import copy
from enum import Enum
from model.twoCoordinate import TwoCoordinate
# Used for distinguishing empty and inaccessible fields
class FieldType(Enum):
empty = 0
inaccessible = 1
class Field(TwoCoordinate):
# The type is empty on default
# If the field is just a hypothetical field or a smal... |
c6899d11bbf0892f42b3b877bbe5f9a2a66bf757 | ben-coxon/cs01 | /sudoku_solver.py | 2,916 | 4.28125 | 4 | #!/usr/bin/python
# THREE GOLD STARS
# Sudoku [http://en.wikipedia.org/wiki/Sudoku]
# is a logic puzzle where a game
# is defined by a partially filled
# 9 x 9 square of digits where each square
# contains one of the digits 1,2,3,4,5,6,7,8,9.
# For this question we will generalize
# and simplify the game.
# Define a... |
5a13734f8133ea7dc9d84779e6256eeed73ae8d9 | LucasBR96/ALGO-STUDY | /CHP6-HEAPS/young_square.py | 5,920 | 3.796875 | 4 | '''
-------------------------INCOMPLETE------------------------------------
Problem 6.1
A YOUNG TABLE IS A MATRIX OF SIZE MxN OF SOME ORDERABLE TYPE WHERE EACH
ROW IS SORTED IN ASCENDING ORDER, AND THE COLUMNS AS WELL. SO THE ITTEM
AT M[ 0 , 0 ] IS THE SMALLEST OF THE MATRIX.
WRITE THE FUNCTIONS FOR:
1 - POPING T... |
e37fd89a8e3cc647b0c688639fb1128ec2d23c88 | weilin2018/climate-som | /Percentile.py | 507 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 23 12:58:46 2015
@author: claireyun
"""
import sys
def percentile(data, percentage):
data.sort()
return data[int(percentage/100.0 *len(data))]
def AnnualMax(data):
max = sys.maxint
for i in range(len(data)):
if i > max or max == sy... |
f9992713e756bf5f3e14b912b586d07dff4d8a5e | shivshankar31/project1 | /compintcal.py | 689 | 3.9375 | 4 | # principle = principle amount
def compIntCal(*amount):
principle = 0
for each_amount in amount:
principle = principle + each_amount
print('Principle Amount is:', principle)
# rate of interest input
interest = float(input('Rate of intrest is:'))
# time period input
year = int(input(... |
b750c319e49bbb941bf8bb746813cfff4ae107b2 | r-tran/data-structures-and-algorithms | /python-dsa/queue/test_linkedqueue.py | 1,344 | 3.6875 | 4 | """
Tests the implementation of the linked list queue
"""
from linkedqueue import LinkedQueue, EmptyError
from nose.tools import assert_equal, assert_true, raises
class TestLinkedQueue(object):
"""Test class for the queue implementation"""
def test_linkedqueue_ctor(self):
queue = LinkedQueue()
... |
67714b6492c0c1af04422ce97270215e3c023138 | danigfavero/py14 | /jogos/adivinhacao3.py | 1,010 | 4 | 4 | # Exercício 3.16 -
# inicializando variáveis
numero = 42
pontos = 1000
# escolha do nível do jogo
nivel = input('Escolha o nível 1, 2 ou 3:')
if nivel == '1':
tentativas = 20
elif nivel == '2':
tentativas = 10
elif nivel == '3':
tentativas = 5
for rodada in range(1, tentativas + 1):
# joga... |
e855f2b3ebe6d0c125b814737307e4930ce5ca3c | danigfavero/py14 | /extra/cpf.py | 2,317 | 3.609375 | 4 | ''' Validador de cpf, conforme as normas do ministério da fazenda
'''
def eh_inteiro(caracter):
''' Recebe um caracter e verifica se é possível transformá-lo em inteiro.
Devolve True caso seja possível e False caso contrário.
'''
try:
int(caracter)
return True
except ValueError:
... |
52ea18052efb67802d0f9a3fce4d1c9daf48cecd | danigfavero/py14 | /oo/conta_privada.py | 1,527 | 3.734375 | 4 | """Exercícios 9.5 - Modificadores de acesso
"""
from cliente import Cliente
from historico import Historico
class Conta:
def __init__(self, numero, cliente, saldo, limite=1000.0):
# todos os atributos privados
self.__numero = numero
self.__titular = cliente
self.__saldo = saldo
... |
ef30cd9d45bbed5191789a5f2a991de7e05376cc | danigfavero/py14 | /oo/conta_abstrata.py | 2,557 | 3.65625 | 4 | """Exercícios 11.9 - Classes abstratas
"""
import abc
from cliente import Cliente
from historico import Historico
class Conta(abc.ABC):
def __init__(self, numero, cliente, saldo=0, limite=1000.0):
self._numero = numero
self._titular = cliente
self._saldo = saldo
self._limite = lim... |
c0282f29561d98cabf0e85f8b333fb2d83746fbe | perlsmith/data_structures | /week2/make_heap/build_heap.py | 1,480 | 3.53125 | 4 | # python3
import pdb
class HeapBuilder: # min heap..
def __init__(self):
self._swaps = []
self._data = []
def ReadData(self):
n = int(input())
self._data = [int(s) for s in input().split()]
assert n == len(self._data)
def WriteResponse(self):
print(len(self._swaps))
for swap in self.... |
da11ba251aec0bb33ef5fb9500d7ea909315f5c6 | hunseok329/codesignal | /43 - isBeautifulString.py | 423 | 3.875 | 4 | def isBeautifulString(inputString):
if 'a' not in inputString:
return False
if (ord(sorted(inputString)[-1]) - ord('a')) > len(inputString):
return False
sortList = sorted(set(inputString))
count = inputString.count('a')
for word in sortList:
if count >= inputString.count(wor... |
fd147503c99b810bc1f4d2702e2462bb186c649e | hunseok329/codesignal | /52 - longestWord.py | 212 | 4 | 4 | import re
def longestWord(text):
p = re.compile('[a-zA-Z]+')
text = p.findall(text)
result = ''
for word in text:
if len(result) < len(word):
result = word
return result
|
9480bd10f565eeae298205f896e53c67d2c0823f | thomastien/hackerrank | /euler/euler012.py | 1,977 | 3.734375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
import collections
samples = input()
debug=0
cap=45000 # arbitrary yes, this was picked via trial & error will handle the max test case N=1000
def triangulate(n):
return ((n**2)+n) / 2
def numfactors(n):
ceiling = int(mat... |
39f9d6c19232b57796d6e6f4a6c2bde37aa65fcd | thomastien/hackerrank | /bijective.py | 883 | 4.0625 | 4 | #!/usr/bin/python
# Enter your code here. Read input from STDIN. Print output to STDOUT
# Bijective function, basically counts uniqueness and 1-to-1 mapping
# Example, 6 [1 2 3 4 5 6] = YES
# 6 [1 2 3 4 5 5] = NO
# 5 [1 2 3 4 5 6] = NO
# 20 [20 19 18 17 16 15 14 13 12 11 1 2 3 4 5 6 7 8 9 10] = YES... |
c45365938855d03aac4c0f9a5c6f558c16e6dc3a | thomastien/hackerrank | /euler/euler026.py | 4,252 | 3.515625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import decimal
from decimal import *
# If this is set too low, you get truncated results
# e.g. earlier this was set at 4k, and we got a bunch of wrong answers capped at 3906
getcontext().prec = 10000
samples = input()
inputs = []
cap = 0
debug =0... |
4b75f503372da774cc8af42bbbb9e77699bb3c7a | thomastien/hackerrank | /euler/euler020.py | 387 | 3.53125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
samples = input()
for i in xrange(samples):
# can do this in one line, but not great for readability
# print sum ( map(int, list(str(math.factorial(input())))))
val = input()
answer = math.factorial(val)
answer = lis... |
76865e64ef34bc15756489e36bf9b8c11b21a509 | thesharpshooter/algo | /CreditCrad.py | 2,395 | 3.546875 | 4 | class CreditCard:
def __init__(self,customer,bank,account,limit):
self._customer = customer
self._balance = 0
self._bank = bank
self._limit = limit
self._account = account
def get_customer(self):
return self._customer
def get_balance(self):
return self._balance
d... |
98cdab0e3e584e4a8b025bcd0569cb5fae64e0d3 | jlengrand/Tippy | /examples/histogram_display.py | 1,404 | 3.71875 | 4 | '''
Created on Dec 15, 2011
@author: Julien Lengrand-Lambert
@email: julien@lengrand.fr
---
Here is a simple example of an histogram calculation on a grayscale image in
Python.
The histogram calculation is performed using the OpenCV library. In order to
simplify the process, an Histogram class has been created, whic... |
8258fdfc0b708866a67a2ed6eb285b45b8bb5423 | AlexAnarcho/UFCManager | /manager.py | 13,604 | 3.5 | 4 | # The manager class that manages one fighter in a league
import inquirer
import random
class Manager:
def __init__(self, available_fighters, league, fighter=None, money=None):
self.league = league
self.available_fighters = available_fighters
self.active_flag = False
self.training_... |
3d1f89606abd55ed2ad912460961932db60d7fd4 | lukasz-starosta/constrained-optimization | /hooke_jeeves.py | 4,002 | 3.59375 | 4 | import math
import numpy as np
from matplotlib.patches import ConnectionPatch
def norm(v):
return math.sqrt(v[0] ** 2 + v[1] ** 2)
dim = 2
def hooke_jeeves(fun, u, h, eps_step, eps_abs, max_iterations):
"""
Implementation of the Hooke-Jeeves algorithm
:param fun: function to be minimized
:par... |
ae2defe090651ef729d37e2188424e3fd9871a2f | huy2512hcm/air-traffic-control-AI | /python-air-traffic-control/utility.py | 1,866 | 3.84375 | 4 | # File: utility.py
import math;
class Utility:
# Function: locDist(loc1, loc2)
# Returns the Euclidean distance between two points in 2D space.
# Uses Pythagoras theorem to compute. If you do not *need* the
# result square rooted, it is preferred that you use locDistSq
# and square the comparat... |
dfc5dda5c51af6a83b80be4157fd39348d8af96c | zhangfuli/leetcode | /手把手刷动态规划/动态规划玩游戏/10. 正则表达式匹配.py | 1,197 | 3.796875 | 4 | # 给你一个字符串s和一个字符规律p,请你来实现一个支持 '.'和 '*'的正则表达式匹配。
#
# '.' 匹配任意单个字符
# '*' 匹配零个或多个前面的那一个元素
# 所谓匹配,是要涵盖 整个 字符串 s的,而不是部分字符串。
#
# 示例 1:
# 输入:s = "aa" p = "a"
# 输出:false
# 解释:"a" 无法匹配 "aa" 整个字符串。
#
# 示例 2:
# 输入:s = "aa" p = "a*"
# 输出:true
# 解释:因为 '*' 代表可以匹配零个或多个前面的那一个元素, 在这里前面的元素就是 'a'。因此,字符串 "aa" 可被视为 'a' 重复了一次。
#
# 示例3:
# 输入:... |
7c1bb647d708caf33a1762ea9a045d3942d218cc | zhangfuli/leetcode | /必知必会算法技巧/分治算法/归并排序.py | 1,046 | 3.875 | 4 | # 归并排序采用分而治之的原理:
# 一、将一个序列从中间位置分成两个序列;
# 二、在将这两个子序列按照第一步继续二分下去;
# 三、直到所有子序列的长度都为1,也就是不可以再二分截止。这时候再两两合并成一个有序序列即可。
# O(nlogn) 稳定排序 辅助空间O(n)
def merge(left, right):
res = []
h = j = 0
while j < len(left) and h < len(right):
if left[j] < right[h]:
res.append(left[j])
j += 1
... |
2f7a1499c45a788dcd25f4b08297ab400079bb61 | zhangfuli/leetcode | /必知必会算法技巧/DFS/剑指 Offer 12. 矩阵中的路径.py | 1,557 | 3.671875 | 4 | # 给定一个m x n 二维字符网格board 和一个字符串单词word。
# 如果word 存在于网格中,返回 true ;否则,返回 false 。
# 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。
# 同一个单元格内的字母不允许被重复使用。
#
# 例如,在下面的 3×4 的矩阵中包含单词 "ABCCED"(单词中的字母已标出)。
# 示例 1:
# 输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
# 输出:true
class Solution... |
60f4a0b6c2bc38c1b51e8bce733a2bd89da7d245 | zhangfuli/leetcode | /高频面试/5. 最长回文子串.py | 624 | 3.765625 | 4 | class Solution:
def palindrome(self, s, left, right):
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
return s[left + 1:right]
def longestPalindrome(self, s):
res = ''
for i in range(len(s)):
# 从中心往两边扩散
... |
4b24b1a4070552da337b52fc35296fb56c753bf5 | zhangfuli/leetcode | /手把手刷动态规划/动态规划玩游戏/887. 鸡蛋掉落.py | 1,750 | 3.75 | 4 | # 给你 k 枚相同的鸡蛋,并可以使用一栋从第 1 层到第 n 层共有 n 层楼的建筑。
# 已知存在楼层 f ,满足0 <= f <= n ,任何从 高于 f 的楼层落下的鸡蛋都会碎,从 f 楼层或比它低的楼层落下的鸡蛋都不会破。
# 每次操作,你可以取一枚没有碎的鸡蛋并把它从任一楼层 x 扔下(满足1 <= x <= n)。如果鸡蛋碎了,你就不能再次使用它。如果某枚鸡蛋扔下后没有摔碎,则可以在之后的操作中 重复使用 这枚鸡蛋。
# 请你计算并返回要确定f确切的值的最小操作次数是多少?
#
# 示例 1:
#
# 输入:k = 1, n = 2
# 输出:2
# 解释:
# 鸡蛋从 1 楼掉落。如果它碎了,肯定能得出 f = 0 ... |
5421ce966d6b60ec40f9e43ece33809fe9576c84 | Ricky842/Shorts | /Movies.py | 1,404 | 4.40625 | 4 | #Empty list and dictionaries to store data for the movies and their ratings
movies = []
movie_dict = {'movie': '', 'rating': 0}
#Check validity of movie rating
def check_entry(rating):
while rating.isnumeric() is True:
movie_rating = int(rating)
if(movie_rating > 10 or movie_rating < 1):
... |
6d28ab51cee4109a2183e1037bf350c95d4eb574 | karthikKSayyaparaju/PythonLearning | /python_learning/learning_1.py | 865 | 3.90625 | 4 |
####Print Commands
#name = input("Please enter your name: ")
#### Input command to learn
#age= int(input("Hi {0}, Please enter your age : ".format(name)))
####IF condition to learn
#if age < 18 | age > 31:
# print("Sorry, you are not eliglible for Holidays")
#else :
#### Print vlaue of
# print("Congratulati... |
daae1ed7dd652fecdb63f33ad5f59376a271a1b8 | ivanmudarth/TakeAction-backend | /utils/getURL.py | 1,635 | 3.578125 | 4 | import urllib.request
from typing import List
from bs4 import BeautifulSoup
def getURL(url: str) -> List[str]:
bank = {"covid-19": 0, "virus": 0, "rally": 0, "pandemic": 0, "contaminate": 0,
"distancing": 0, "coronavirus": 0, "deaths": 0, "coronavirus": 0, "cases": 0}
with urllib.request.urlopen... |
cf45339f66bed549f33e9329e0eba318e735a185 | NIROJ-SATYAL/POOP.PY | /poop.py | 1,121 | 3.9375 | 4 |
class dog:
def __init__(self,name,age):
self.a=name
self.b=age
def bark(self):
print("bark bark!")
def doginfo1(self):
print(ozzy.a+ " is " + str(ozzy.b) + " years old")
def doginfo2(self):
print(skippy.a+ " is " + str(skippy.b) + " years old")
def doginfo... |
644df581da9485a978c25dc10bf5b0e99f453485 | ninguemns/Animacao | /Main.py | 1,367 | 3.796875 | 4 | import turtle
import random as rand
import math
# usar #000080 para azul com sobra e #0000ff para azul normal
# Apesar de existir uma função para desenhar o circulo, precisamos percorre-lo
raio = 50
tela = turtle.Screen() # Instancia a tela (Não necessario caso n mudar atributos)
tela.bgcolor('black') # Define a... |
5ed55cdbe3082ebcd87c8cc5ab40defff9542932 | anandavelum/RestApiCourse | /RestfulFlaskSection5/createdb.py | 605 | 4.125 | 4 | import sqlite3
connection = sqlite3.connect("data.db")
cursor = connection.cursor()
cursor.execute("create table if not exists users (id INTEGER PRIMARY KEY,name text,password text)")
users = [(1, "Anand", "Anand"), (2, "Ramya", "Ramya")]
cursor.executemany("insert into users values (?,?,?)", users)
rows = list(c... |
383e1929453715e7bea7a413045d60c1bab10ffc | migduroli/covid-uk-variant | /toolbox/date_params.py | 969 | 3.703125 | 4 | import numpy as np
OFFSET = 15
def is_leap_year(year):
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
return True
else:
return False
else:
return True
else:
return False
class Months:
class Leng... |
bc7a6c6227eccbe962fe5288e68616f4938a76aa | Luckram/Piskvorky | /piskvorky.py | 1,213 | 3.71875 | 4 | from random import randrange
pole = '--------------------'
import util
import ai
def vyhodnot(pole):
if ("xxx" in pole):
return "x"
elif ("ooo" in pole):
return "o"
elif ("-" not in pole):
return "!"
else:
return "-"
def tah_hrace(pole):
symbol = 'x'
while T... |
049612f837ef2751390eec11918076dccedb0e96 | demo-dia/PythonLearn | /learning/base/file/zip.py | 1,277 | 3.890625 | 4 | import os
import zipfile
def compress(zip_file, input_dir):
f_zip = zipfile.ZipFile(zip_file, 'w')
for root, dirs, files in os.walk(input_dir):
for f in files:
# 获取文件相对路径,在压缩包内建立相同的目录结构
abs_path = os.path.join(os.path.join(root, f))
rel_path = os.path.relpath(abs_pat... |
5be5a9951f419d96ace02ef4f53590af408d94f1 | demo-dia/PythonLearn | /learning/math/question/ou_ji_li_de.py | 355 | 3.828125 | 4 | '''
欧几里得算法,辗转相除求最大公约数:
假定m >= n: m对n取余,除数作为大数,余数作为小数,继续循环取余
即使m<n ,循环中也将其交换了
'''
def gcd(m, n):
while not n == 0:
temp = m % n
m = n
n = temp
return m
def main():
print(gcd(6, 9))
main() |
553ace49545ae076ab7a1260633ebbf7e296148c | demo-dia/PythonLearn | /algorithm/recursion/factorial.py | 516 | 4.09375 | 4 | # 递归和尾递归的对比, 无论是何种方式都会被Python的递归深度限制
def simple(n):
""" 最简单的递归方式来计算阶乘"""
if n == 1:
return 1
else:
return n * simple(n - 1)
def factorial(n, result=1):
""" 尾递归, 直接调用函数并返回"""
if n == 1:
return result
else:
return factorial(n - 1, n * result)
num = 1000
print(... |
8f10cb82386cb0c1188f13fd2e45f94b81680931 | demo-dia/PythonLearn | /pygame/eliminate/util/tool.py | 487 | 3.75 | 4 | import unittest
# 隐式返回None
def add(a, b) -> int:
if a > 0:
return a + b
# just temporary code
class Tool(unittest.TestCase):
def test_generate_data(self):
for i in range(100):
print('1,', end='')
def test_a(self):
result = [1]
a = [1, 4, 5]
result.ext... |
79e7c63026fbc9908051d0bf520115e6caa008d3 | demo-dia/PythonLearn | /pygame/alien_refactor/alien_settings.py | 1,498 | 3.5625 | 4 | """
设置类
"""
class Settings:
def __init__(self):
self.screen_width = 800
self.screen_height = 500
self.bg_color = (230, 230, 230)
# 飞船速度的设置,因为rect的centerx等属性只能放整数,所以还要进行修改
# self.ship_speed_factor = 1.5
self.ship_limit = 3
# 子弹设置
# self.bullet_spe... |
a53271943b399ea777d374004219a33bf501b4df | demo-dia/PythonLearn | /algorithm/sort/heap.py | 3,167 | 4.1875 | 4 | """
堆(优先队列) 建立在完全二叉树上 使用列表存储,第一个元素是标识元素,真正从1开始是堆
小顶堆: i <= 2*i 且 i<2*i+1 即父节点大于等于左右子节点
大顶堆: 相反
这里我使用小顶堆
"""
def insert(heap, value):
""" 将元素插入堆中 上滤"""
heap.append(0) # 增加长度
index_parent = int((len(heap) - 1) / 2) # 长度的一半就是父节点
index_space = len(heap) - 1
# print(index_parent, inde... |
4ea8e9931edb9ffe2aaa4025dd1055495f625b1b | GavasBadger/second | /forRange.py | 205 | 4 | 4 | print('for range funbction')
def fun(n):
for i in range(0,n, 2): #start, end, increment by
print(str(i))
# for taking desending order alternate the values
n = input()
fun(n)
|
6d6eeb0c74be9e885e406d4ead2adaf176471f87 | tburcham/codepoetry | /python_lesson_1/lists.py | 188 | 3.890625 | 4 | names = ["Marx", "Trotsky", "Lenin", "Engels"]
names.append("Eisenstein")
print("total names:", len(names))
for name in names:
print(name)
print(name[0])
print("That's it")
|
72994802e57e471f8cc14515072749eb35d79037 | LadyKerr/cs-guided-project-array-string-manipulation | /src/class.py | 657 | 4.21875 | 4 | # Immutable variables: ints; O(1) [to find new location for them is cheap]; string
# num = 1
# print(id(num))
# num = 100
# print(id(num))
# num2 = num
# print(num2 is num)
# num2 = 2
# print(num)
# print(num2 is num)
# Mutable Variables: arrays, dictionaries, class instances
arr = [1,2,3] #arrays are mutable
print... |
e8d98f1d15ae95a7a3dab51aa47893e5c7c62a28 | a-b-v-k/PythonBootCamp | /finalproject.py | 1,849 | 3.546875 | 4 | # CERTIFICATE GENERATOR
# Import all the necessities
import xlrd
from PIL import Image, ImageDraw, ImageFont
from datetime import datetime, date, timedelta
# Open the excel sheet to collect data
book = xlrd.open_workbook("certificate_details.xls")
sheet = book.sheet_by_name("Sheet1")
for r in range(0, sheet.nrows):... |
55e4152febbde1e2f5bdea34dbbc94c725da64c0 | a-b-v-k/PythonBootCamp | /day05.py | 425 | 4.03125 | 4 | n = int(input("Enter the value of n:"))
l = []
print("Enter", n, "values:")
for i in range(n):
l.append(int(input()))
print(l)
#add an element in to the list
l.append(100)
print(l)
#remove an element
l.pop()
print(l)
#store the maximum and minimum values in a and b
a = max(l)
b = min(l)
#create a tuple
t = (1... |
0599efa7db96b8c5fd20e642243db242e58fcc21 | a-b-v-k/PythonBootCamp | /day07.py | 540 | 3.953125 | 4 | def func1():
a, b = input('Enter two numbers:').split()
a = int(a)
b = int(b)
print('Addition of two numbers:', a+b)
print('Subtraction of two numbers:', a-b)
print('Mutliplication of two numbers:', a*b)
print('Division of two numbers:', a/b)
def covid():
name = input("Enter patient's n... |
15fb2808dc5645594a2e830688e9dc259f932ea0 | ProHackerVovandy/hw | /hw6.py | 1,807 | 3.71875 | 4 | import random
Otvet = ['Мой магический шар говорит: ','Духи шепчут мне ответ на твой вопрос. Но я не могу его расслышать, положи еще 1000руб в шляпу на лечение слуха. Спасибо. О, о, кажется что-то расслышала. Они сказали: ','Карты глаголят: ']
def read_book(filename):
text = ''
with open(filename, encoding='u... |
91fcf444d3e0ddfe6b923351afbedb60f038cfe9 | chriswolfdesign/MIT600EDX | /week2/pset2/Problem2/ps2b.py | 554 | 4.03125 | 4 | """
Used for running, do not include when submitting to grader
"""
balance = int(input("Balance: "))
annualInterestRate = float(input("Annual Interest Rate: "))
"""
End Runner Code
"""
MONTHS = 12
balanceTmp = balance
monthlyInterestRate = annualInterestRate / MONTHS
paymentGuess = 0
while balanceTmp > 0:
balance... |
e1427ce445a939b4b35107d0e5651bf8339c4448 | chriswolfdesign/MIT600EDX | /week3/Lecture5/Exercises/17_apply_to_each/apply_to_each3.py | 417 | 3.703125 | 4 | """
Used for running, do not include when submitting to grader
"""
testList = [1, -4, 8, -9]
def applyToEach(L, f):
for i in range(len(L)):
L[i] = f(L[i])
"""
End Runner Code
"""
def square(x):
"""
x: int or float
return: x**2
"""
return x**2
applyToEach(testList, square)
"""
Used f... |
0b3c953f2007c79ba23cb9110321ef2489b01374 | chriswolfdesign/MIT600EDX | /week2/Lecture4/Exercises/14_gcd_recur/gcd_recur.py | 388 | 4.03125 | 4 | def gcdRecur(a, b):
"""
Input:
a, b: positive integers
return: a positive integer, the greatest common divisor between a & b
"""
if b == 0:
return a
else:
return gcdRecur(b, a % b)
"""
Used for running, do not include when submitting to the grader
"""
a = int(input("a: "))
... |
49dc25556e905897390f62a28a6e3d14e578721d | chriswolfdesign/MIT600EDX | /week2/Lecture4/Exercises/8_eval_quadratic/eval_quadratic.py | 523 | 3.65625 | 4 | """
Used for running, do not include when submitting to the grader
"""
a = 5
b = 4
c = 3
x = 2
"""
End Runner Code
"""
def evalQuadratic(a, b, c, x):
"""
a, b, c: numberical values for the coefficients of a quadratic equation
x: numerical value at which to evaluate the quadratic
return: the solution fo... |
a71d233bc36979df8613ec4875fc77efab006cae | sanket17/python_basic | /decorator.py | 867 | 3.90625 | 4 | # Example for function as object
def hello():
print('Hello World')
hello()
print(hello)
greet = hello
print('After deleting hello() function')
del hello
print('Calling greet() after deleting hello')
greet()
#hello()
def original_func():
print('This is original function')
def decorator_func(some_func):
... |
abccec27acb35086f4e486831aa2d06d334b3e03 | debankur-ghosh/football-salary-ccl | /model.py | 1,072 | 3.5625 | 4 | # Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pickle
dataset = pd.read_csv('wage.csv')
dataset['age'].fillna(0, inplace=True)
dataset['match'].fillna(dataset['match'].mean(), inplace=True)
X = dataset.iloc[:, :3]
#Converting words to integer values
"""def c... |
199dc2b0ea80bace92cb0dce023c6f102210a26e | Firedorange717/LEGO_Search | /lego.py | 7,025 | 4.09375 | 4 | ###
### Author: Firedorange717
### Description: A program that takes 4 user inputs, a LEGO set file name, a type of input {sets or pieces}
### type of search {subset, superset, none} and the id numbers. it them depending on the
### inputs performs the desired search with the correct ... |
ba6068d95c6b6016e696ff31401b5ca493197e63 | gioiab/simple-web-crawler | /tests/sync/mocks.py | 4,925 | 3.796875 | 4 | import urllib.error
class MockHTTPRequest:
"""
Defines the mock for a generic urllib.request.Request.
"""
def __init__(self, url, method):
self.url = url
self.method = method
class MockHTTPResponse:
"""
Defines the mock for a generic urlopen response.
"""
def __init__(... |
9e88023e59e8705080f21181f50212168c21aef8 | anujnirval/automate_boring_stuff_exercise | /ch_7_regex_strip_function.py | 854 | 4.03125 | 4 | import re
input_string = input("Enter the string to remove whiespaces:\n")
rightSpace = re.compile(r'\s+$')
leftSpace = re.compile(r'^\s+')
def space_Check(statement):
if rightSpace.search(statement):
leftStrip = rightSpace.sub('',statement)
if leftSpace.search(leftStrip):
return lef... |
fa714cb3d3ec8c6b273eb61188c08d52684de068 | anujnirval/automate_boring_stuff_exercise | /ch_5_dictionary_fantasy_game_inventory.py | 317 | 3.90625 | 4 | inventory={'rope':1,'torch':6,'gold coin':42,'dagger':1,'arrow':12}
def displayInventory(inventory):
print("Inventory:")
item_total = 0
for k,v in inventory.items():
print(str(v)+ ' ' + k)
item_total +=v
print("Total number of items: " + str(item_total))
displayInventory(inventory)
|
8c902651f21a4c5d25b384a3f73922c06eba74aa | gabefreedman/music-rec | /dates.py | 2,624 | 4.4375 | 4 | #!/usr/bin/env python
"""This module defines functions for manipulating and formatting date
and datetime objects.
"""
from datetime import timedelta
def get_month(today):
"""Format datetime to string variable of month name.
Takes in `today` and extracts the full month
name. The name is returned in all... |
3b2d9f12bcfee600b30eeb27e34788ae5c8ed4f9 | jc345932/sp53 | /workshopP1/shippingCalculator.py | 368 | 4.1875 | 4 | item =int(input("How many items:"))
while item < 0:
print("Invalid number of items!")
item = int(input("How many items:"))
cost =int(input("How much for item:"))
while cost < 0:
print("Invalid prices")
cost = int(input("How much for item:"))
total = cost * item
if total > 100:
total = total * 0.9
el... |
88b3cc3b96b5381d19ecef7da67d4729a178fe9e | jc345932/sp53 | /workshopP3/functions-1.py | 743 | 3.96875 | 4 | """
lower = 10
upper = 100
print("Enter a number ({}-{})".format(lower,upper))
for i in range(10, 120, 11):
print("{} {}".format(i, chr(i)))
"""
def get_number(lower, upper):
invaildValue = False
user_input = 0
while not invaildValue:
try:
user_input = int(input("Enter a numb... |
1f45bdd57c3e4381ff05c668fadcb38bcaf589f8 | jc345932/sp53 | /workshopP4/numList.py | 322 | 4.15625 | 4 | list = []
for i in range(5):
num = int(input("Enter the number: "))
list.append(num)
print("The first number is: ",list[0])
print("the last number is: ", list[-1])
print("the smallest number is: ", min(list))
print("the largest number is: ",max(list))
print("the average of the numbers is: ",sum(list)/len(list)... |
eb5d5e910e30c8167d1f703344ce42cc7790bfa8 | KimRaicho/main.py | /core_classes/person.py | 1,844 | 3.625 | 4 | import os
class Person:
people = []
def __init__(self, first_name: str, last_name: str, gender: str, age: int = 0, id_number: int = 0):
assert age >= 0, f"Age {age} should be greater or equal to 0"
self.first_name = first_name.title()
self.last_name = last_name.title()
self.a... |
7051e87f971fda073df77cd8d085d16556964c01 | sagarvegad/Math_of_Intelligence | /Gradient_descent.py | 1,418 | 3.75 | 4 | import numpy as np
import pandas
def cost_function(data,theta_0,theta_1,no_instances):
totalError = 0
for i in range(no_instances):
x = data["Distance"][i]
y = data["Calories"][i]
totalError += (y - ( theta_1* x + theta_0)) ** 2
return totalError / float(no_instances)
def best_fit_line(data,theta_0,theta_1,n... |
1c00b0602ac3a75e4ac5d68e472f81f37b9f0ad3 | Dwijesh522/ml_assignments | /2017CS50407/question2/stochastic_gradient_descent.py | 2,867 | 3.546875 | 4 | import numpy as np
import math
# J(theta) = 1/(2m) * (Y - X.theta)^ * (Y - X.theta)
# returns cost at a given theta
def cost(X, theta, Y):
temp = Y - np.dot(X, theta)
return np.dot(temp.T, temp) * (1/Y.shape[0]) * (1/2)
# d(J(theat))/d(theta) = 1/m * ( (X^).X.theta - X^.Y)
# returns gradient of cost functin a... |
ae371d21e0e505a31704228de21cc7240ee968b6 | ankur17/algorithms | /algorithms/selection.py | 1,546 | 3.734375 | 4 | import random
from algorithms.sorting2 import mergesort
from utils import remove_smallest, split_into_chunks, get_median, get_kth, split_list_by_pivot
CHUNK_SIZE = 5
def kth_by_extreme(unsorted_list, k):
for ith in xrange(k):
kth, unsorted_list = remove_smallest(unsorted_list)
return kth
def kth_by... |
606b9267499764ebd8cee9aa63b9dc424cb4e225 | tartaros09/rubik | /r.py | 7,012 | 3.546875 | 4 | #!/usr/bin/python3
import numpy as np
import itertools, sys
# Works with odd cubes
# Store each cubie as a 3x3x3 array, with colours of stickers on each face in the six elements (1,0,0), (-1,0,0), (0,1,0), etc.
# Overall cube a concatenation of cubies
# Colour 0 is transparent/no sticker
N = 3 #size of the Rubik's ... |
a642f1a51b0be728938a84eae0da5a54d8ff420a | Kevin-dot1/PythonTiranaAl1 | /convert_decimal_to_binary.py | 312 | 3.734375 | 4 | def Converter(nr):
x = nr
binary = []
while nr > 0:
r = int(float(nr % 2))
binary.append(r)
nr = (nr - r) / 2
binary.append(0)
string = ""
for j in binary[::-1]:
string = string + str(j)
print('The binary nr for %d is %s' % (x, string))
Converter(5)
|
2058096c8f23293fc22f0d2c9227eef9511955c1 | antiformio/LigaRecord-Bot | /dbcon.py | 3,140 | 3.96875 | 4 | import sqlite3, json
class WriteToDb:
""""
Exemplo de formato de ficheiro a importar por este código:
Messishow,Chuecos FC
FC Poukitxo,FC Kombichos
Black Mamba FC,FCBalasar
SL Bernardes,Athletic Dafundo
Virose,FC Chupitos
ClassOnGrass,TascoFC
Alphateam,F... |
fe4d6239f27a8c9aa4cdca1c1642f5d5c1c41548 | Evalle/python3 | /100days-of-code/piglatin.py | 573 | 4.09375 | 4 | #!/usr/bin/env python3
'''
Pig Latin is a game of alterations played on the English language
game. To create the Pig Latin form of an English word the initial
consonant sound is transposed to the end of the word and an 'ay' is
affixed (Ex.: "banana" would yield 'ananabay')
'''
print("Please, enter your word")
use... |
5edb5d2c0bb6854ec1687be950cf2d60ce6f267a | Evalle/python3 | /Anagram_detection/poc3.py | 461 | 4.03125 | 4 | #!/usr/bin/env python3
# Anagram detection example, POC #3
# O(n**2) or O(n logn) because of sorting operations
def anagram_solution(s1, s2):
alist1 = list(s1)
alist2 = list(s2)
alist1.sort()
alist2.sort()
pos = 0
matches = True
while pos < len(s1) and matches:
if alist1[pos] =... |
8c92c7e6eab51dd87795444b849608f2ceedd2bb | Evalle/python3 | /Recursion/Visualizing_recursion/fractal_tree.py | 477 | 3.96875 | 4 | #!/usr/bin/env python3
# Fractal tree
import turtle
def tree(branch_len, t):
if branch_len > 5:
t.forward(branch_len)
t.right(30)
tree(branch_len-15, t)
t.left(60)
tree(branch_len-15, t)
t.right(30)
t.backward(branch_len)
def main():
t = turtle.Turtle... |
8c15327fc0ea2553906b48e5597a47e2bb3ac4af | Evalle/python3 | /minimum/min3.py | 605 | 3.90625 | 4 | #!/usr/bin/env python3
import time
from random import randrange
def find_minimum(alist):
''' calsulates the minimum in the list
O(n**2) (NON-OPTIMAL!) way '''
overallmin = alist[0]
for i in alist:
issmallest = True
for j in alist:
if i > j:
issmallest = Fal... |
90a850631774ab695d5a5f6e1bf8ccd0ab99d079 | gastbob40/fmsi | /fractions.py | 784 | 3.71875 | 4 | def rational_to_contfrac(x, y):
'''
change x/y en une list de quotients [a0, ..., an]
'''
a = x // y
pquotients = [a]
while a * y != x:
x, y = y, x - a * y
a = x // y
pquotients.append(a)
return pquotients
def convergents_from_contfrac(frac):
'''
calcule la ... |
10c3f1ec27b1c7327e4c144767d524d3aa7b037c | danamir1/RevolvingDoors | /company_name_translator.py | 1,933 | 3.640625 | 4 | '''
Translating companies names using Wikipedia
'''
import wikipedia
# import urllib2
import urllib.request as urllib2
from bs4 import BeautifulSoup
import wikipedia
import wikipediaapi
# def langBS(link):
# # get languages
# soup = BeautifulSoup(urllib2.urlopen(link))
# links = [(el.get('lang'), el.get(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.