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 |
|---|---|---|---|---|---|---|
93d2d0026b5d737c60049229091c9c01faedf0f0 | yogesh1234567890/insight_python_assignment | /functions/Func7.py | 666 | 4.25 | 4 | """ 7. Write a Python function that accepts a string and calculate the number of
upper case letters and lower case letters.Sample String : 'The quick Brow Fox'
Expected Output :
No. of Upper case characters : 3
No. of Lower case Characters : 12 """
string="The quick Brow Fox"
def check(string):
upper=0
l... |
45c4e66f0dba9851ea5539d2c98e6076ed1ad8fd | sk-ip/coding_challenges | /December_2018/stopwatch.py | 734 | 4.125 | 4 | # program for stopwatch in python
from datetime import date, datetime
def stopwatch():
ch=0
while True:
print('stopwatch')
print('1. start')
print('2. stop')
print('3. show time')
print('4. exit')
ch=input('enter your choice:')
if ch=='1':
sta... |
e8114325fa7221653cb5af4600ae7398930f965b | PrathameshDhumal/Machine-Learning-Applications | /Titanic/script.py | 4,016 | 3.78125 | 4 | ##############################################################
#
#Author:Prathamesh Dhumal
#Date:22/7/21
#About:Logistic regression on Titanic Dataset
#
##############################################################
import math
import numpy as np
import pandas as pd
import seaborn as sns
from seaborn imp... |
532325bc67a55cf8cc6fb165aac226347f18f9a3 | PrathameshDhumal/Machine-Learning-Applications | /Diabetes_Log_reg/script.py | 1,511 | 3.9375 | 4 | ##############################################################
#
#Author:Prathamesh Dhumal
#Date:18/7/21
#About: Diabetes Predictor application using Logistic Regression algorithm
#
##############################################################
#Import the Libraries
import pandas as pd
import numpy as np
im... |
2c7bd8089aaaa7e486ef456b20641028a020cc6a | LuisOlCo/Topic_Modeling | /2_find_topics/tokenizer_potts.py | 7,660 | 3.96875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This code implements a basic, Twitter-aware tokenizer.
A tokenizer is a function that splits a string of text into words. In
Python terms, we map string and unicode objects into lists of unicode
objects.
There is not a single right way to do tokenizing. The be... |
f4710268d31a8b6b9e32652a7c4ac6ed9d23df40 | B001bu1at0r81/Home-Work | /Home_Work8/Home_Work8_Task_1.py | 903 | 4.03125 | 4 | ###################################
#!!!~~~~~~~~~~~~~~~~~~~~~~~~~~~!!!#
#!!!_______Orest Danysh________!!!#
#!!!________Home-work_8________!!!#
#!!!___________Task_1__________!!!#
#!!!_________Rectangle_________!!!#
#!!!~~~~~~~~~~~~~~~~~~~~~~~~~~~!!!#
###################################
class Polygon:
def __init__... |
888537ae81ac1f0a4b2b1452d32bd86b004c610c | B001bu1at0r81/Home-Work | /Home_Work4/Home_Work4_Task_3.py | 664 | 4.125 | 4 | ###################################
#!!!~~~~~~~~~~~~~~~~~~~~~~~~~~~!!!#
#!!!_______Orest Danysh________!!!#
#!!!________Home-work_4________!!!#
#!!!___________Task_3__________!!!#
#!!!_____Fibonacci_number______!!!#
#!!!~~~~~~~~~~~~~~~~~~~~~~~~~~~!!!#
###################################
quantity_of_numbers = int(input(... |
d60e5e1c0445b7b21b7fc7143e9b4b195bacea89 | sgomez125/tictactoe | /tictactoe.py | 4,374 | 4 | 4 | """
Tic Tac Toe Player
"""
import math
import copy
import time
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]]
def player(board):
"""
Returns ... |
ad92fdc3c49fdc47d657f81a6c897a25ec8e1b33 | michchen/241 | /Project 4/HashTable Notes.py | 574 | 3.8125 | 4 | # Hashing
a = {}
a["cat"] = "a feline friend"
# key on the left value on the right
a= []
a.append(("cat" , "a feline friend"))
# using a list is not quite as convenient because you have to search through the whole list O(n) and it's a waste of time
# first thing for hash is to determine how many buckets you want
c... |
65142b996c6d5f6963fa03677861d2dd8c14c6ee | NicoleFS/Heuristieken_Rush_Hour | /Oude versies/RushHour.py | 13,062 | 3.890625 | 4 | # Rush Hour
# Name: Nicol Heijtbrink (10580611), Nicole Silverio (10521933) & Sander de Wijs (10582134)
# Course: Heuristieken
# University of Amsterdam
# Time: November-December, 2016
import numpy as np
import math
class Queue:
"""
This will contain all possible moves from grid state X.
From there, if a ... |
43efc3a27e27f28b7680091e0accf5c1d6b9a519 | Raviteja02/MagicMethod | /venv/prime.py | 2,137 | 3.71875 | 4 | class Account:
def __init__(self,acbal,cname,cacno,cadd):
self.acbal=acbal
self.cname=cname
self.cacno=cacno
self.cadd=cadd
print("your ac is successfully created.")
print("Name",self.cname)
print("Account NO",self.cacno)
print("Address",self.... |
0cace2bfda57d586230bb54a02881019aaa00995 | abesto/debugging-workshop | /1/main.py | 176 | 3.515625 | 4 | #!/usr/bin/env python
# vim: ts=4
def multiply(a, b):
result = 0
for n in range(b):
# wheee a comment
result += a
return result
print multiply(3, 10)
|
ca7bb4bcfd8915a530fd7cdf93cc7c147671473b | levinhdu/while | /elip.py | 500 | 3.796875 | 4 | import turtle
import random
pen = turtle.Turtle()
color = ["red","yellow","brown","blue","skyblue","violet","green"]
pen.pensize(3)
i= 0
# for i in range(36):
# pen.color(random.choice(color))
# pen.rt(10)
# for j in range(2):
# pen.circle(90, 90)
# pen.circle(45, 90)
def elip():
a=0
... |
e89bd190d6cc6a2117a63e6097c33b6009f47aa0 | HsinTsao/LeetCode | /7合并两个链表.py | 1,298 | 3.984375 | 4 | class ListNode:
def __init__(self, x):
self.data = x
self.next = None
def initList(data):
# 创建头结点
head = ListNode(data[0])
r = head
p = head
# 逐个为 data 内的数据创建结点, 建立链表
for i in data[1:]:
node = ListNode(i)
p.next = node
p = p.next
return r
def ... |
2906917ff2db9cc13d4058feff6f8f6961f9c9b6 | vilesovds/python_edu | /hw5/task1.py | 623 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем.
Об окончании ввода данных свидетельствует пустая строка.
"""
def collaborate(file_path):
with open(file_path, 'w') as f:
while True:
i = input("Please enter some s... |
326485129bdd88233d51f3bb9b046823069f2970 | vilesovds/python_edu | /hw4/task5.py | 688 | 3.796875 | 4 | # -*- coding: utf-8 -*-
from functools import reduce
"""
Реализовать формирование списка, используя функцию range() и возможности генератора. В список должны войти четные
числа от 100 до 1000 (включая границы). Необходимо получить результат вычисления произведения всех элементов списка.
Подсказка: использовать функцию ... |
1d0b26512932577922013c42f6f78ebc146bbd27 | vilesovds/python_edu | /hw1/main.py | 3,076 | 4.125 | 4 | # first part
str_var = 'String example'
int_var = -43
float_var = 1.3e+2
bool_var = bool()
# additional types
list_var = [1, 2, 3]
tuple_var = ('1', 2, print)
dict_var = {'name': 'Boris', 'age': 20}
print('str_var:\n\ttype:', type(str_var), '\n\tvalue:', str_var)
print('int_var:\n\ttype:', type(int_var), '\n\tvalue:',... |
6e133b12fa7e480f5775bdc1429ae19439f41f05 | danielle8farias-zz/hello-world-python3 | /exercicio_py/ex0018_matrizes/main_v5.py | 1,217 | 3.53125 | 4 | ########
# autora: danielle8farias@gmail.com
# repositório: https://github.com/danielle8farias
# Descrição: Abrindo uma matriz de um arquivo e mostrando seus elementos na tela.
########
import sys
sys.path.append('/home/danielle8farias/hello-world-python3/meus_modulos')
from mensagem import ler_cabecalho, criar_rodap... |
c972526fff435f1b20881e91023bf479e447e9f4 | iqbalwaldan/Tutorial_Python | /09-latihan-program-perhitungan-sederhana/main.py | 515 | 4.03125 | 4 | # latihan konfersi satuan temperature
# progtam konversi celcius ke satuan lain
print("\nPROGRAM KONVERSI TEMPERATUR\n")
celcius = float(input("Masukkan suhu dalam celcius :"))
print("suhu dalam celcius adalah",celcius,"Celcius")
# reamur
reamur = (4/5) * celcius
print("suhu dalam reamur adalah",reamur,"reamur")
#... |
aab1f68e96e01365cbded147121e4a1503a122d1 | artem-tkachuk/birthdayParadox | /main.py | 524 | 3.59375 | 4 | import matplotlib.pyplot as plt
import numpy as np
def permutations(k, n):
assert k > n, 'k must be larger than n'
prod = 1
for i in range(k - n, k):
prod *= i
return prod
def graph(n):
x = np.arange(1, 101)
y = [1 - permutations(365, i) / 365 ** i for i in range(n)]
plt.scatte... |
6a9dc67741604db78e4445a941657fbb70a07b23 | MRossol/Python_and_DataScience | /Data_Science.py | 11,979 | 4.03125 | 4 | __author__ = 'MRossol'
from matplotlib import pyplot as plt
from collections import Counter
from functools import partial, reduce
import math
import random
#Chapter 4 - Linear Algebra
#Vectors
def vector_add(v, w):
"""adds corresponding elements"""
return [v_i + w_i
for v_i, w_i in zip(v, w)]
def... |
8d497c5783528cec7f0eac4a107a4118b39d557e | beamjl/Python-AndrewNgML | /ex4.py | 8,525 | 4.21875 | 4 | """Machine Learning Online Class - Exercise 4 Neural Network Learning
Instructions
------------
This file contains code that helps you get started on the
linear exercise. You will need to complete the following functions
in this exericse:
sigmoidGradient complete
randInitializeWeights complete
nnCostFunction c... |
7c68ef45396dd6bc191492c9a99f2376120e3adf | beamjl/Python-AndrewNgML | /ex2_reg.py | 4,461 | 4.28125 | 4 | """ Machine Learning Online Class - Exercise 2: Logistic Regression
Instructions
------------
This file contains code that helps you get started on the second part
of the exercise which covers regularization with logistic regression.
You will need to complete the following functions in this exericse:
sigmoid - compl... |
d04d51bb57a8a63fb8e826b79ffd14a4b5decac2 | MagMongoing/Python | /1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py | 1,509 | 3.9375 | 4 | '''Amit is a monitor of class XII-A and he stored the record of all
the students of his class in a file named “class.dat”.
Structure of record is [roll number, name, percentage]. His computer
teacher has assigned the following duty to Amit
Write a function remcount( ) to count the number of students who need
re... |
5af07ad8518c72c91b58f94b341533ccafeb8632 | MagMongoing/Python | /1 File handle/File handle text/special symbol after word.py | 292 | 3.59375 | 4 | F=open("happy.txt","r")
# method 1
val=F.read()
val=val.split()
for i in val:
print(i,"*",end="")
print("\n")
#method 2
F.seek(0)
value=F.readlines()
for line in value:
for word in line.split():
print(word,"*",end="")
F.close()
|
163aaca851db0809af6ea81697d8b4a1219e8613 | Zelphy712/brainfuck | /brainfuck_interpreter.py | 3,497 | 3.609375 | 4 | """
This class (or rather pair of classes) acts as an interpreter for the esolang brainfuck(https://esolangs.org/wiki/Brainfuck).
For the time being, the variable text_to_be_interpreted contains whatever you want to interpret and must be hardcoded there.
Created by Ethan Lynch
"""
class Tape():
def __init__(self... |
24bbae5401a6db3cc4ea69dc332c2904ac57ba3a | yonatanGal/Four-In-a-Row | /ex12/disc.py | 771 | 3.890625 | 4 | RADIUS=3
DEFAULT_X=''
DEFAULT_Y=''
class Disc:
def __init__(self,color):
self.__radius=RADIUS
self.__color=color
self.__x_location=DEFAULT_X
self.__y_location=DEFAULT_Y
def get_radius(self):
'''
:return: the radius of the disc
'''
return self.__ra... |
ebfacc7f7b117f04e701092ce58f87568bc13e0b | JN-Lab/OC-Pr7-GrandPyBot | /botapp/utils/message_parse.py | 3,481 | 3.5625 | 4 | #! /usr/bin/env python3
# coding: utf-8
import unicodedata
import re
from string import punctuation
from botapp.utils.stop_words import common_words, welcome_words
class MessageParser:
"""
This class is one of the main treatment of this programm.
It is used to identify the location the user is looking for ... |
983a4a117af824aef1d1714f7c76a99c73b23fe4 | idletekz/scrap | /time_delta.py | 788 | 3.609375 | 4 | # time_delta — Parse a time duration
# ref: https://stackoverflow.com/a/51916936/2445204
import re
from datetime import datetime, timedelta
regex = re.compile(r'^((?P<days>\d+?)d)? *'
r'((?P<hours>\d+?)h)? *'
r'((?P<minutes>\d+?)m)? *'
r'((?P<seconds>\d+?)s?)?$... |
f6f7fbb893a1d373d264884e2c846379973f1719 | SadiqSarwar/The-Matrix-Game | /check.py | 1,264 | 3.921875 | 4 | #This Class is for Input Validation.
class Check:
#Declare the constructor(Initializes the attribute).
#def __int__(self, ): This is the Syntax for the Constructor.
def __int__(self,userInput):
#Pass by value from main()
self.userInput = userInput
#Make Sure the Quantiy is Checked from m... |
37521b6b3d35ad40980d332015dc636caf245c61 | Neihtq/sorting-algorithms | /quicksort.py | 939 | 4.03125 | 4 | def quickSort_inPlace(array: list):
def _quickSort(array, fst, lst):
if fst >= lst:
return
pivot = array[lst]
i, j = fst, lst
while i <= j:
while array[i] < pivot: i += 1
while array[j] > pivot: j -= 1
if i <= j:
array[i... |
caa6d0df752d2df6f589a01859820b1d31bad08e | cristime/2048Game | /main.py | 2,918 | 3.515625 | 4 | # Author: Cristime Cai
# -*- coding: utf-8 -*-
# 1 TODOs
import os
import platform
import sys
import time
import random
MAPSIZE = 4
FILENAME = r"score.txt"
class Game:
data = []
gameStatus = True
score = 0
def __init__(self):
self.gameStatus = True
self.score = 0
random.seed... |
965c873705cebfc33fdd2c1ee3ab554ea2ac579e | mbramson/Euler | /python/problem020/problem020.py | 472 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 24 20:49:21 2015
@author: Bramson
This is very simple in Python. Certainly a more interesting problem in other
languages
"""
## This function returns the sum of the digits (base 10) of n factorial
def FactorialDigitSum(n):
import math
fac = math.factorial(n)
... |
9f34a088a4d0a61f2af65fa911222eb2d3372dd8 | mbramson/Euler | /python/problem016/problem016.py | 488 | 4.125 | 4 | # -*- coding: utf-8 -*-
## Power Sums
## 2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
## What is the sum of the digits of the number 2**1000?
## This is actually a very simple problem in python, because Python automatically deals with large numbers.
## Returns the Power Sum of n. As in it sum... |
2d6a3c012073bdbd9ab70483278fa07ce6ff44f1 | BinyaminCohen/math_function | /main.py | 486 | 3.984375 | 4 | def pow(x, y):
if y == 0:
return 1
elif y > 0:
res = x
for i in range(1, y):
res *= x
return res
elif y < 0 and x != 0:
res = 1 / x
for i in (y, -1):
res *= 1 / x
return res
def factorial(x):
if x < 0:
return ("Err... |
40efd5559aac696b62743d1b5747ce9ca85b95e6 | cverluise/paper-utils | /paper_utils/plots.py | 1,499 | 3.71875 | 4 | import matplotlib.pyplot as plt
def format_label(s):
"""Return `s` as a capitalized string with spaces instead of "_"
Arguments:
s: label to be formated
**Usage:**
```python
from paper_utils.plots import format_label
label = "nb_patentees"
format_label(label)
# >>> "... |
b988253629007d324a741e957cf12e51a8a95cca | Junhong-Kim/BOJ | /2908.py | 181 | 3.75 | 4 | A, B = input().split()
reversed_a = ''.join(reversed(A))
reversed_b = ''.join(reversed(B))
if int(reversed_a) > int(reversed_b):
print(reversed_a)
else:
print(reversed_b)
|
f6ff114885d9ccc94ab08664e9064dbe7e11f8ac | Junhong-Kim/BOJ | /2920.py | 804 | 3.796875 | 4 | notes = input().split()
start_sequence = None
current_sequence = None
for index, note in enumerate(notes):
try:
if start_sequence is None:
if note < notes[index + 1]:
start_sequence = 'ascending'
current_sequence = 'ascending'
elif note > notes[index ... |
67adf1fdd2447db73e9372d507780047db32550e | MeijiIshinIsLame/binary_tree_python | /binarytree.py | 3,329 | 3.8125 | 4 | class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
if (data <= self.data):
if(self.hasleft()):
self.left.insert(data)
else:
self.left = Node(dat... |
990f89da2fe3f9a85bd2df0235cffcc211786488 | deqncho/Robots | /robots.py | 2,967 | 3.625 | 4 | from gasp import *
import random
class Player:
pass
class Robot:
pass
def place_player():
global player
player = Player()
player.x = random_between(0,63)
player.y = random_between(0,47)
def place_robot():
global robot
robot = Robot()
robot.x = random_between(0,63)
robot.... |
22d6fcdb0aea8d9478f75a17339e248df60a6e36 | githsem/Python_Coding | /Asal/Asal.py | 691 | 3.59375 | 4 | print("""
******************
Asal Sayi Programi
******************
""")
def asal(sayi):
bolen = 0
for i in range(2,sayi):
if sayi%i == 0:
bolen +=1
if bolen == 0:
print("{} sayisi asal bir sayidir".format(sayi))
else :
print("{} sayisi asal bir sayi degildir".format(... |
074617aae66c2d070f3711f679a0c82e76d47221 | wilttang/SoftDesSp15 | /gene_finder/exercise_5-3.py | 599 | 4.0625 | 4 | def check_fermat(a,b,c,n):
""" checks Fermat's Theorem
>>> check_fermat(1,2,3,4)
No, that doesn't work
"""
if (a**n + b**n == c**n):
print 'Holy Smokes, Fermat was wrong!'
else:
print "No, that doesn't work"
def ask_fermat_Constants():
""" Prompts user for 4 numbers to check Fermat's Theorem
... |
a4382447caa1d2c2e4bfd9ddedef88a7063bf943 | valerienierenberg/holbertonschool-low_level_programming | /0x1C-makefiles/5-island_perimeter.py | 1,421 | 4.1875 | 4 | #!/usr/bin/python3
"""This module contains a function island_perimeter that returns
the perimeter of the island described in grid
"""
def island_perimeter(grid):
"""island_perimeter function
Args:
grid ([list of a list of ints]):
0 represents a water zone
1 represents a la... |
4025e579746646f23a62e85e81a2723665d57bfc | ViktorCollin/avalg12 | /Factorizer/Factorizer/test/mul.py | 282 | 3.59375 | 4 | #!/usr/bin/env python
# -*- encoding: utf8 -*-
from sys import stdin
lines = stdin.read().splitlines();
x = 1
for line in lines:
if len(line) == 0:
print x if x > 0 else 'fail'
x = 1
elif line == 'fail':
x = 0
else:
x *= int(line)
|
74a62d228dbd2ce456d09211bea6f15d822ca3f7 | James-E-Sullivan/BU-MET-CS300 | /sullivan_james_lab3.py | 2,052 | 4.25 | 4 | # Eliza300
# Intent: A list of helpful actions that a troubled person could take. Build 1
possible_actions = ['taking up yoga.', 'sleeping eight hours a night.',
'relaxing.', 'not working on weekends.',
'spending two hours a day with friends.']
'''
Precondition: possibl... |
d689784e46691a5ff1eb4b63ccfdb4ef97f343d2 | bperard/PDX-Code-Guild | /python/lab05-magic8.py | 638 | 3.78125 | 4 | import random
outcomes = ['Leave me alone.', 'Doubt it.', 'Beat it kid.', 'Sure, why not?', 'I mean, anything is possible.', 'Undoubtedly.', 'I\'m not going to justify that with an answer.']
answer = ''
print('Hello, I am a "Magic" Eight Ball, and since you\'ve found me, I might as well answer a question or two.\n')
pr... |
91e5fa35bc4ea64c7cc65e096d10ed0d91d8d88b | bperard/PDX-Code-Guild | /python/lab04-grading.py | 320 | 4.125 | 4 | score = int(input('On a scale of 0-100, how well did you?'))
grade = ''
if score > 100:
grade = 'Overachiever'
elif score > 89:
grade = 'A'
elif score > 79:
grade = 'B'
elif score > 69:
grade = 'C'
elif score > 59:
grade = 'D'
elif score >= 0:
grade = 'F'
else:
grade = 'Leave'
print(grade)
|
21ab8c793589afe2c8f984db02ca2b5650be962b | bperard/PDX-Code-Guild | /python/lab08-roshambo.py | 1,309 | 4.25 | 4 | '''
Rock, paper, scissors against the computer
'''
import random
throws = ['rock', 'paper', 'scissors'] #comp choices
comp = random.choice(throws)
player = input('Think you can beat me in a game of Roshambo? I doubt it, but let\'s give it a shot.\n Choose your weapon: paper, rock, scissor.').lower() #player prompt
... |
75566c13a5e09874a1ea4ff64c7f198b7f4218fc | bperard/PDX-Code-Guild | /python/lab31-atm.py | 2,865 | 4.21875 | 4 | '''
lab 31 - automatic teller machine machine
'''
transactions = [] # list of deposit/withdraw transactions
class ATM: # atm class with rate and balance attribute defaults set
def __init__(self, balance = 0, rate = 0.1):
self.bal = balance
self.rat = rate
def __str__(self): # format w... |
e5a8eae58dc45a0259309b867eeac974b3dc7d62 | bperard/PDX-Code-Guild | /python/lab09-change.py | 838 | 4.25 | 4 | '''
Making change
'''
# declaring coin values
quarters = 25
dimes = 10
nickles = 5
pennies = 1
# user input, converted to float
change = float(input('Giving proper change is key to getting ahead in this crazy world.\n'
'How much money do you have? (for accurate results, use #.## format)'))
# conv... |
f554fd90c0763c105b4d3052409d03e57b7fa1df | xtopherbrandt/UD-120 | /outliers/outlier_cleaner.py | 707 | 3.5625 | 4 | #!/usr/bin/python
def outlierCleaner(predictions, ages, net_worths):
"""
Clean away the 10% of points that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where
each tuple is of the f... |
f3ae22bce32ca9a7c45773d3e3495265f96d0386 | m-star18/NLP100 | /chapter01/knock08.py | 330 | 3.875 | 4 | def cipher(text):
# アルファベット小文字 → (97, 123)
text = [chr(219 - ord(t)) if 97 <= ord(t) <= 123 else t for t in text]
return ''.join(text)
text = 'this is a message.'
encryption_text = cipher(text)
decryption_text = cipher(encryption_text)
print('{}\n{}'.format(encryption_text, decryption_text))
|
74316a9c7e7181d5dc31d42220486171462f934c | AJB363/PartIA-Flood-Warning-System-AJB363-MK2078 | /floodsystem/plot.py | 1,292 | 3.765625 | 4 | import matplotlib.pyplot as plt
import matplotlib.dates as d
from numpy import linspace
from .analysis import polyfit
def plot_water_levels(station, dates, levels):
""" Plots the station water level history against time """
# Return early if data is invalid
if len(dates) != len(levels):
print("fl... |
8a1c432d4c4a61435f9c002ac47ab69043c294d5 | YoushaExT/temp | /attendance/attendanceDatabaseClass.py | 8,609 | 3.59375 | 4 | import sqlite3
class DbClass:
def __init__(self, file):
self.conn = sqlite3.connect(file)
self.c = self.conn.cursor()
def print_user_info(self, uid=None, my_filter=True):
# print all columns or few depending on my_filter
if my_filter and uid: # print 1 person with my_filter
... |
2bf02a92bc6081e2bcd5bacbd61176a9ed65a4d7 | Semestre-3-estructura-de-datos/PIA | /codigo.py | 3,236 | 4 | 4 | import datetime
import sys
import sqlite3
from sqlite3 import Error
from funciones import insertardatos
from funciones import validacion
menu=1
separador=("*"*30)
contador=1
try:
while menu==1:
print(separador+"Bienvenido al Menu Principal" +separador)
print("Opciones del menu")
print("1=Re... |
07de036683eeaf643caaa7e140c8959af82703e7 | RobertCochran/connect4 | /user_input.py | 1,148 | 4.25 | 4 | import random
def user_input():
""" This function allows the user to choose where their red piece goes. """
print "We're going to play Connect Four."
print " I'll be black and you'll be red. "
print "You go first and choose where you want to put your piece. There are seven columns in total."
... |
b902058ee0b01d8cf586816902a443711f8a1d81 | QwertyPanda/quiz-bot | /src/quiz_mangement/verificators.py | 2,676 | 3.921875 | 4 | from datetime import datetime
from typing import Union
import dateparser
from ..environment import LANGUAGE
def parse_datetime(date_string: str, *extra_languages, use_default_lang=True) -> Union[datetime, None]:
"""
parse datetime using dateparser
:param date_string: the string to parse a date from
... |
4f2204a713af71c312ead83cb81a1e587e42b7a0 | giulianeacademy/Napp-Academy | /semana5/MyHolidays/myholidays/holidays.py | 2,428 | 3.59375 | 4 | from datetime import date
from datetime import datetime
#from dateutil.parser import parse
class MyCalendar:
def __init__(self, *args):
self.datas = []
self.check_holiday()
for item in args:
if isinstance(item, date):
self.datas.append(item)
elif t... |
066f22d28bfaba48a0a73e216f9c0fe1c655e3af | kangsungsu/python3_coding | /21.04.19/no3687.py | 1,157 | 3.53125 | 4 | num=int(input())
def small(n):
str=''
if n%7==0:
for i in range(n//7):
str+='8'
elif n==2:
return 1
elif n==3:
return 7
elif n==4:
return 4
elif n==5:
return 2
elif n==6:
return 6
elif n==7:
return 8
elif n=... |
e51daa660b8669d5c4b1bd336ea72fd6ff724ad2 | dinpandy/DC_Birthday_Code | /ExcelRead_postTwitter.py | 1,526 | 3.5625 | 4 | # import required packages
import pandas as pd
import datetime
import time
from createapi import tweet_message
def make_ordinal(n):
'''
Convert an integer into its ordinal representation::
make_ordinal(0) => '0th'
make_ordinal(3) => '3rd'
make_ordinal(122) => '122nd'... |
d688364c51369eb4398ddbd5eee7d1f6952ef423 | dlaredo/intelligent_hvac | /commonTools/TF_MLP.py | 2,556 | 3.84375 | 4 | import tensorflow as tf
class MLPClassifier:
def __init__(self, hidden_layer_sizes=(100,), alpha=1e-4, batch_size=256, learning_rate_init=1e-3):
self.coeffs_ = {}
self.intercepts_ = {}
self.hidden_layer_sizes_ = hidden_layer_sizes
self.alpha = alpha
self.batch_size = batch_size
self.learning_rate_init ... |
e38d1e5af710f2363c8c0dcb89559cd4106f84c1 | sravyasr/Pyfords | /fruitful.py | 338 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 11 08:41:40 2019
@author: sri
"""
import math
def triArea(base,height):
area=((1/2)*(base*height))
return area
inp=triArea(10,5)
print("The area of a triangle is:",inp)
def print_twice(word):
print(word)
print(word)
print_twi... |
5b9bc07eaeaa4e282f51ac36e38ae42001e820ca | gxhrid/PyTorch-MNSIT-Model | /src/data/tranforms/in_place_tranformer.py | 1,014 | 3.703125 | 4 | import abc
import torch
class InPlaceTransformer(abc.ABC):
"""
This transformer is used to record the transformations in place in the original data set.
This is class is useful when:
- The transformations are costly to compute
- AND items of the data set are read more than once
Note ... |
f9c024f7b53cee4238ba17e670ef61fbd6c94080 | WEIOKING/python-study | /features/list_comprehensions.py | 871 | 3.890625 | 4 | # 列表生成器
# 0开始依次生成数字到5结束,5除外
print(list(range(5)))
# 2开始依次生成数字到11,11除外
print(list(range(2, 11)))
# 生成1到10的平方
print([x * x for x in list(range(1, 11))])
# 生成1到10中偶数的平方
print([x * x for x in list(range(1, 11)) if x % 2 == 0])
# 生成1到5与5到10中每个数字求和
print([x + y for x in list(range(1, 6)) for y in list(range(6, 11))])
# 生成1到... |
ef6f4d613f388b4ceae8f708e7ce3bed1302b36a | DavidGardu/Python-Morsels | /matrix_add.py | 1,072 | 3.859375 | 4 | '''
I'd like you to write a function that accepts two lists-of-lists
of numbers and returns one list-of-lists with each of the
corresponding numbers in the two given lists-of-lists added
together.
'''
def suma(mat1, mat2):
nuevo = []
if len(mat1) == len(mat2):
for i in range(len(mat1)):
s... |
2d1a0ee8dce7393702cefb392752dfe278ef935f | tractiming/trac-gae | /Scraper/scraper.py | 2,557 | 3.546875 | 4 | import urllib
import urllib2
from bs4 import BeautifulSoup
import csv
#site_open = urllib2.urlopen("https://www.tfrrs.org/athletes/4513882/Loyola_IL/Jamison_Dale.html")
def obtain_html(url):
"""
PASS IN URL FROM OBTAIN_ID AND USE IT TO QUERY ATHLETE SPECIFIC DATA.
"""
request = urllib2.Request(url, headers={'User... |
f6545582d4cc1258c23090244dd7a788265e6f12 | tractiming/trac-gae | /apps/scrapers/base.py | 643 | 3.71875 | 4 | class Scraper(object):
'''
Base class for a Scraper object. These are used to access running result
websites and scrape data (athlete information and race results).
Contains the following methods which should be implemented when subclassing:
- get_athlete_results_from_url
- get athlete_detail... |
c5e23f2892c355640ae6d318627e74202d9a713c | ToddCombs/Phenomenon | /pets.py | 995 | 3.6875 | 4 | # author:ToddCombs
# 删除包含特定值的所有列表元素
def exercise_20():
pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
exercise_20()
# 设定形参
def describe_pet(animal_type, pet_name):
print("\nI have a " + animal_ty... |
ab2e4d80a9e335907ecc4f73c90f451f7dc3c09c | ToddCombs/Phenomenon | /exercise_forget_me.py | 954 | 3.5625 | 4 | # author:ToddCombs
# 小练习程序,提示用户输入他的名字,并json.dump存到文件中
import json
def get_new_name():
"""获取新用户名"""
user_name = input("请输入你的姓名: ")
file_name = 'forget_me.json'
with open(file_name, 'w') as f_obj:
json.dump(user_name, f_obj)
return user_name
def get_save_name():
"""获取存储在json... |
f1ebc7999228aac476857756f86ba1ed13b2fcb8 | ToddCombs/Phenomenon | /person.py | 1,521 | 3.890625 | 4 | # author:ToddCombs
# 返回一个字典,其中包含有关一个人的信息
def build_person(first_name,last_name,age=''):
# 将传入的实参存入字典
person = {'first':first_name, 'last':last_name}
if age:
person['age'] = age
# 返回表示人的整个字典
return person
musician = build_person('todd','combs',age=33)
print(musician)
def get_... |
18981831203bc15a014639acb246edb4b5d88db4 | Kuro-000/pawapuro_success | /pawapuro/create_loop.py | 1,361 | 3.625 | 4 | #!/usr/bin/env python
# _*_ coding: utf-8 _*_
import random
if __name__ == "__main__":
with open('./loop.txt', mode='w') as f:
f.write('1\n') # ゲームスタート
f.write('name\n') # 名前を入力
f.write('1\n') # 背番号
f.write('1\n') # ポジション(1で投手、2から9で野手)
f.write('\n'*4) # 会話
f.wr... |
bdcfd8fafc68c68d76b6bfae3008173bb56331a6 | bhargodevarya/PythonLearning | /Misc.py | 291 | 3.578125 | 4 | # *args means var args of java
def func(*args):
print('as a tuple', args)
print('not as tuple', *args)
func(1,2,3,4)
# **kwargs means all named params passed to a function
def kwargsFunc(**kwargs):
print(kwargs.pop('a', 'not_found'))
print(kwargs)
kwargsFunc(one_param=1) |
eb7cb4ffdec2e4c5790db0c1d1b407ed5b8a2930 | galgodon/astr-119-hw-1 | /operators.py | 1,641 | 4.5 | 4 | #!/usr/bin/env python3 # makes the terminal know this is in python
x = 9 #Set variables
y = 3
#Arithmetic Operators
print(x+y) # Addition
print(x-y) # Subtraction
print(x*y) # Multiplication
print(x/y) # Division
print(x%y) # Modulus (remainder)
print(x**y) # Exponentiation ... |
9bdfa82561a8638beb7caa171e52f717cc3bb89e | galgodon/astr-119-hw-1 | /functions.py | 1,209 | 4.1875 | 4 | #!/usr/bin/env python3
import numpy as np # import numpy and sys
import sys
def expo(x): # define a function named expo that needs one input x
return np.exp(x) # the function will return e^x
def show_expo(n): # define a subroutine (does not return ... |
b03d9a5588af7d957ebc5171346507ea746c8d26 | OscarABazanez/Curso-de-POO-y-Algoritmos-con-Python | /busqueda_binaria.py | 1,386 | 3.78125 | 4 | import random
def busqueda_lineal(lista,objetivo):
match = False
contador =0
for elemento in lista: #O(n)
contador +=1
if elemento == objetivo:
match = True
break
return match, contador
def busqueda_binaria(lista,comienzo,final,objetivo,contador=0):
... |
5d9c8c0cd61a7f5e5a6bea3d6cd8f30b218a9fd3 | PaulLem2019/lesson2_tasks | /les2_task1.py | 667 | 4.09375 | 4 | """
1. Создать список и заполнить его элементами различных типов данных. Реализовать скрипт проверки типа данных
каждого элемента. Использовать функцию type() для проверки типа. Элементы списка можно не запрашивать у пользователя,
а указать явно, в программе.
"""
my_list = ['asd', 2343, ['qwee', 'sfddsgf'], (12, 35, '... |
f8e843a9f366200f1a2922d8d31e1792bbdb331b | A-very-Cunning-ham/CS-115 | /lab9 - mandelbrot/mandelbrot.py | 3,511 | 3.859375 | 4 | # mandelbrot.py
# Lab 9
#
# Name:
# keep this import line...
from cs5png import PNGImage
# start your Lab 9 functions here:
def mult(c, n):
"""Returns c*n but does the calculation using addition"""
result = 0
for _ in range(n):
result += c
return result
assert mult(6, 7) == 42
assert mult(... |
c96101fb826e306de47173df050fb7d461e9f34d | frankcleary/misc | /parallel_examples.py | 1,345 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 11 15:51:06 2013
Compare serial vs. parallel processing for matrix multiplication
@author: Frank Cleary (frank@frankcleary.com)
"""
import pp
import time
import random
def randprod(n):
"Waste time by creating and inefficiently multiplying an n x n matrix"
rando... |
be7c8da4087537dccc0ef9ee15b9c1f67e7fdc51 | RusAv/Mi | /Lab4/lab4.py | 5,113 | 3.65625 | 4 | import pygame
import math
from pygame.draw import *
from random import randint
pygame.init()
FPS = 30
x_size=1200
y_size=900
screen = pygame.display.set_mode((x_size, y_size))
global scrx,scry
RED = (255, 0, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
GREEN = (0, 255, 0)
MAGENTA = (255, 0, 255)
CYAN = (0, 255, 255)
B... |
f49eadbec6894cb5e6afd7bf7ae1de71ef71a611 | prathishaprathisha/python | /Exe67.py | 161 | 3.625 | 4 | import math
m2=int(input("Enter Value"))
if m2<10: print("10")
else:
l2=len(str(m2))
m2+=5
m2=m2/(10**(l2-1))
print(math.floor(n2)*(10**(l2-1)))
|
2873d8b4d887484b1c3d329c5be65ab116095ebf | prathishaprathisha/python | /Exe105.py | 79 | 3.765625 | 4 | p=int(input("enter the no"))
q=int(input("enter the no"))
print(str(p)+str(q))
|
7ad5225dbd02f1b3210e7d75388f3fd5dd2e9d2c | prathishaprathisha/python | /Exe75.py | 224 | 3.90625 | 4 | h = input("Enter String: ")
if len(h) % 2 == 0:
print(h[len(h) // 2 - 1] + h[len(h) // 2])
k=h.replace( h[len(h) // 2 - 1],"*")
print(k.replace(h[len(h) // 2 ],"*"))
else:
print(h.replace(h[len(h) // 2],"*"))
|
5b7f64231329b7546e24de9c7287db36dc80287e | prathishaprathisha/python | /Exe54.py | 65 | 3.859375 | 4 |
s=int(input("Enter Number"))
if s%2==0:print(s)
else:print(s-1)
|
59db8b8ee7d2cb72816276edb8785f7e5522a0bb | prathishaprathisha/python | /python12.py | 205 | 4 | 4 | m=int(input("Enter number:"))
temp=m
rev=0
while(m>0):
dig=m%10
rev=rev*10+dig
m=m//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
|
cb390d03b109eb3deb1dfd0e14ef5243984b10ab | prathishaprathisha/python | /python17.py | 210 | 3.71875 | 4 | z=int(input("Enter any number: "))
s=list(map(int,str(n)))
j=list(map(lambda x:x**3,s))
if(sum(j)==z):
print("The number is an armstrong number. ")
else:
print("The number isn't an arsmtrong number. ")
|
d2c2e9faa5857820cce0548a25d2ef9181623e3b | robotsecr/random-stuff | /twoPointChaseEachOther.py | 182 | 3.859375 | 4 | import matplotlib.pyplot as plt
for x in range(1,6):
print(x)
plt.clf()
plt.plot([0,5-x],[3+x,x],'k:',marker='o')
plt.axis([-2,10,0,10]) # make the axis constant
plt.pause(1)
|
75959aa7e895e79d2df978d6ea571bd9f3ff54ce | borchardtR/algorithms_python | /chapter_4/directed_graphs/directed_cycle.py | 3,884 | 3.875 | 4 | # Title: directed_cycle.py
# Author: Ryan Borchardt
# The implementation uses a recursive implementation of depth first search.
# This class extends the functionality of directed graphs to be able to:
# 1. Determine if a cycle exists in the digraph.
# 2. If a cycle exists, list a cycle (just one) in the digrap... |
4fb18252f73601e6ead67c61a5bc388c40296993 | borchardtR/algorithms_python | /chapter_4/directed_graphs/scc_bruteforce.py | 2,905 | 3.734375 | 4 | # Title: scc_bruteforce.py
# Author: Ryan Borchardt
# Identifies the strongly connected components in a directed graph.
# This expands the functionality of digraphs to be able to determine:
# 1. If two given vertices are strongly connected.
# 2. How many strong componenets are in the digraph
# Time complexi... |
2fb78123342a61930d94cd6d5c5b66e99a5ed346 | borchardtR/algorithms_python | /chapter_4/undirected_graphs/paths_dfs_recursive.py | 2,612 | 3.625 | 4 | # Title: paths_dfs_recursive.py
# Author: Ryan Borchardt
# This implementation builds off of the code in dfs_recursive.py
# This class extends the functionality of undirected graphs to be able to:
# 1. Determine if a path exists from a vertex to another vertex (using the same dfs algorithm as in dfs_recursive.p... |
0f44f0ded97344bab5d732e14bcc7bce860b994f | borchardtR/algorithms_python | /chapter_4/undirected_graphs/biparite.py | 1,882 | 3.953125 | 4 | # Title: biparite.py
# Author: Ryan Borchardt
# This implementation utilizes depth first search.
# This class extends the functionality of undirected graphs to be able to:
# 1. Determine if a graph is biparite.
# Note that:
# 1. If the graph is acyclic, it is automatically/guaranteed biparite / two-colorabl... |
8a644478c9154feb025949b0da95a351c17933e0 | borchardtR/algorithms_python | /chapter_1/queue/queue_linkedlist.py | 3,313 | 4 | 4 | """
Title: queue_linkedlist.py
Author: Ryan Borchardt
Implemented using linked lists.
For this implementation: push() inserts node to end of linked list and pop() removes first node from linked list.
Requires additional instance variable to reference the last node in linked list to avoid having to traverse link... |
4a24e2b01cd34443f82008cebaf48d78447766a9 | borchardtR/algorithms_python | /chapter_4/undirected_graphs/cycle.py | 1,604 | 3.78125 | 4 | # Title: cycle.py
# Author: Ryan Borchardt
# This implementation utilizes depth first search. dfs automatically stores the previous vertex as v.
# This class extends the functionality of undirected graphs to be able to:
# 1. Determine if a graph contains a cycle or if it is acyclic.
# Example:
# python cy... |
13ee2c8de4384fdf176cdf785b4877a82fd44faa | borchardtR/algorithms_python | /chapter_4/edge_weighted_digraphs/apsp_floyd_warshall.py | 1,782 | 3.609375 | 4 |
"""
Title: apsp_floyd_washall.py
Author: Ryan Borchardt
Determines the all-paths shortest paths for an edge-weighted digraph (ie determines the shortest paths from every vertex to every other vertex).
Idea: incrementally considering (and building if shorter) all intermediate paths between nodes u and v
#... |
52a1098fda3fffc03c0a33165764e668f2abc175 | jianfeiZhao/Data-Structure-and-Algorithms | /SwordToOffer/字符串/34第一个只出现一次的字符.py | 697 | 3.65625 | 4 | '''
在一个字符串(0<=长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置,
如果没有则返回 -1(需要区分大小写).
'''
class Solution:
'''
利用python内置函数list.count()和list.index()。
'''
def firstOnceChar(self, s):
s = list(s)
a = set(s)
loc = len(s) # record the location
for i in a:
if s.count(i) == 1... |
ff3a16caabdd6caec4f3984afa7f926590c9deae | jianfeiZhao/Data-Structure-and-Algorithms | /LeetCode/TopK.py | 1,229 | 3.953125 | 4 | '''
Find the i-th order statistic in a set of n elements, which is the i-th smallest element.
'''
def partition(arr, left, right):
pivot = arr[right]
i = left-1
for j in range(left, right):
if arr[j] <= pivot:
i += 1
swap(arr, i, j) # swap those smaller than pivot to left
... |
eaa0f55979f48f0a47bafaac3d0434731ce3b006 | jianfeiZhao/Data-Structure-and-Algorithms | /SwordToOffer/字符串/62.括号序列.py | 1,374 | 4.03125 | 4 | '''
给出一个仅包含字符'(',')','{','}','['和']',的字符串,判断给出的字符串是否是合法的括号序列
括号必须以正确的顺序关闭,"()", "[()]"和"()[]{}"都是合法的括号序列,但"(]"和"([)]"不合法。
'''
class Solution:
# 字符串替换
def isValid(self , s ):
# write code here
if not s: return False
flag = True
while flag:
n = len(s)
s = s.... |
e67252dcee2f5b6be720d70dedfc8ea02eb3440c | jianfeiZhao/Data-Structure-and-Algorithms | /SwordToOffer/46圆圈中最后剩下的数.py | 1,199 | 3.671875 | 4 | '''
首先,让小朋友们围成一个大圈。然后,随机指定一个数m,让编号为0的小朋友开始报数。
每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,
从他的下一个小朋友开始,继续0...m-1报数,直到剩下最后一个小朋友,可以不用表演,并且拿到名贵的礼品。
请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1)
'''
class Solution:
def lastNumber(self, n, m):
if not m or not n:
return -1
ls = [i for i in range(n)... |
a8e9fd1d927b6bf369bf621fdf8214049cbf5be8 | jianfeiZhao/Data-Structure-and-Algorithms | /SwordToOffer/字符串/02替换空格.py | 316 | 3.59375 | 4 | '''
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.
则经过替换之后的字符串为We%20Are%20Happy。
'''
def replaceSpace(str):
ls = str.split(' ')
print(ls)
return '%20'.join(ls)
str = 'We Are Happy'
print(replaceSpace(str)) |
cc6eacdf41c1343339f603d021bf24f018493e5a | jianfeiZhao/Data-Structure-and-Algorithms | /Huffman/minHeap.py | 1,519 | 3.671875 | 4 | class MinHeap:
def __init__(self, ls):
self.heapSize = len(ls)
self.arr = self.buildMinHeap(ls)
def buildMinHeap(self, arr): # O(N)
n = len(arr)
for i in range(n//2, -1, -1):
# do heapify from the first inner node
self.heapify(arr, i)
return ar... |
b942eeaf51746e681c758b19273fa06d8577482c | jianfeiZhao/Data-Structure-and-Algorithms | /SwordToOffer/字符串/71字符串判断回文.py | 1,010 | 3.6875 | 4 | '''
给定一个字符串,请编写一个函数判断该字符串是否回文。如果回文请返回true,否则返回false。
中心扩散
'''
class Solution:
def judge(self , str ):
# write code here
def func(str, left, right):
while left>=0 and right<len(str) and str[left]==str[right]:
left -= 1
right += 1
if right - lef... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.