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 |
|---|---|---|---|---|---|---|
987c27dedc35d463fac038dc6d164dbd2c68d0f2 | karanrs96/forsk_btcp | /Day8/Karan_Raj_Singh_25.py | 306 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 21 10:46:53 2018
@author: Karan
"""
lst = []
while True:
ip = raw_input("Enter name, age & score: ")
#if ip == "":
if not ip:
break
name, age, score = ip.split(',')
lst.append((name, int(age), int(score)))
lst.sort()
print lst |
f69d74bd7644d94fd4ab8766a94b3a208001b86b | tatsuya-nagashima/atcoder | /abc226/a.py | 135 | 3.703125 | 4 | from decimal import Decimal,ROUND_HALF_UP
X = input()
a = Decimal(str(X))
b = a.quantize(Decimal('0'), rounding=ROUND_HALF_UP)
print(b) |
deb02a12a9ebad1562ad173bd826e04b9e862c31 | kasrasadeghi/cs373 | /notes/06-30.py | 1,305 | 3.609375 | 4 | # -----------
# Fri, 30 Jun
# -----------
# singleton design pattern
# Java
class A {
public final static A only = A()
private A () {}
void f () {...}}
class T {
public void static main (...) {
A x = new A(); # not ok
A x = A.only;
x.f();
A.only.f();
# old A
x = A()... |
8713a1ff28ad0cf2d3d625ce538f1d688da19baf | cwein3/stanford-ai4all-vision | /notebooks/project/model_helpers.py | 2,482 | 3.84375 | 4 | import numpy as np
from scipy.special import expit as s_curve
from utils.logistic_regression_utils import *
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
def predict_probability(data, weights):
"""
Use the data and weights to calculate a probability for each data point.
... |
5f5ee5236160dfecc45a64c571a244f1cf7f05bd | AngelGuale/pysimiam | /controllers/followwall.py | 6,024 | 3.734375 | 4 | #
# (c) PySimiam Team 2013
#
# Contact person: Tim Fuchs <typograph@elec.ru>
#
# This class was implemented as a weekly programming excercise
# of the 'Control of Mobile Robots' course by Magnus Egerstedt.
#
from pid_controller import PIDController
import math
import numpy
class FollowWall(PIDController):
... |
e72c7aa29978bc817a8f975e9371211b5a22ac65 | nehabinish/Multidimensional-PES | /source_code/python-codes/plot.py | 7,406 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 24 01:53:19 2021
@author: nehabinish
"""
import numpy as np
import matplotlib.pyplot as plt
import pylab
from mpl_toolkits.mplot3d import Axes3D
def read_file(filename):
'''
-----------------------------------------------------------... |
7e2a2712a6a3c3ba0db9d3ece49025d49cb80f44 | vhemsley/python-challenge | /PyBank/Pybank.py | 2,505 | 3.65625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[5]:
# Pybank
# Dependencies
import csv
import os
#Loading Files and Output Data
loading_file = os.path.join("budget_data.csv")
file_to_output = os.path.join("budget_thorough_analysis")
#Financial Data Parameters
Number_Of_Months = 0
Number_Of_Months_of_Change = []
Net_C... |
2c4eeccf9ea864add1feef2e25854a50e9a52b37 | Scybaloot/BioInformaticsAlgorithsmFA13 | /sub.py | 345 | 3.96875 | 4 | match = "PPPP"
def substitute_mer(match):
match_list = []
for letter in match:
match_list.append(letter)
for y in range(len(match)):
for letter2 in ["A", "C", "G", "T"]:
print "letter equals", letter2
match_list[y] = letter2
match_list[y-1] = match[y-1]
match = "".join(match_list)
print mat... |
e25de8a46aa43d4e0745554eab09803e59dcabe2 | dukedududu/tiaojian-xunhuan | /PythonApplication1.py | 1,341 | 3.828125 | 4 | '''
a=10
b=20
if a>b:
print('a为最大数')
else:
print('b为最大数')
'''
'''
i=1
sum=0
while(i<=100):
sum=sum+i
i=i+1
else:
print('等差数列一到一百的和') #python有别于c的不同 while...else语句
print(sum)
'''
'''
#无限循环
a=1
while(a):
print('hello world')#ctrl+c结束无限循环
print('good bye!')#输出结果并没有执行这个语句
'''
'''
#for语句
a=[1,2,3,4,... |
49488e429bf4124adf40471af60e2a8bb9488f07 | makesler/python_exercises | /deleteCharacter.py | 92 | 3.703125 | 4 | # deletes a given character
s = input()
s = s.replace("@", "")
# Print a string:
print(s)
|
70cb570dc6233e1074d98cca7aba3b2578f70bcc | makesler/python_exercises | /passwordCracker.py | 545 | 4 | 4 | import string
import itertools
def guess_password(real):
chars = string.ascii_lowercase + string.digits #all letters and numbers
attempts = 0
for password_length in range (1, 6): #length of password
for guess in itertools.product(chars, repeat = password_length):
attempts += 1 #adds a... |
48aa708f9cf67c2bdc4711d4c032966429a127d8 | Nagiliys/CourseWork | /coursework/1_system.py | 2,634 | 4.03125 | 4 | from math import factorial
"""
Нахождение вероятностных характеристик
для системы массового обслуживания с
ограничением на длину очереди
"""
def main():
n = int(input('введите число каналов обслуживания: '))
l = int(input('введите интенсивность входяшего потока: '))
h = int(input('введите пр... |
e4c14ff53b3c46e258c15edf591d66ad919a9603 | eriktaubeneck/bayesian_ab_test | /cli.py | 1,783 | 3.53125 | 4 | """ Calculates Bayesian Probabilty that A - B > x
Usage:
ab_test.py <a_population> <a_success> <b_population> <b_success>
[--sample_size=<n>] [--absolute_effect_size=<x> | --relative_effect_size=<x>]
[--alpha=<a>] [--beta=<b>]
Options:
--sample_size=<n> Select a sample size [default: 1... |
fa0876b602e5656560ef13260c5b02baef63411b | NihadM11/pdsnd_github | /bikeshare_2.py | 10,415 | 4.3125 | 4 | import time
import pandas as pd
import numpy as np
import calendar
#This project was made based on a template by Udacity
#those guys are the best!
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
A... |
7b7a2fc5373254085d5e02f7d8d1d9c69c926940 | AndreiZeshko/SkillFactory_modul | /C2/С1.10.2/C1102.py | 366 | 3.6875 | 4 | class Rectangle:
def __init__(self, lenght, width):
self.lenght = lenght
self.width = width
def get_area(self):
return self.lenght * self.width
def __str__(self):
return f"{self.lenght}, {self.width}"
rect_1 = Rectangle(2, 5)
rect_2 = Rectangle(4, 6)
print(f... |
3860d7f63842483775d9adbd099f8572435d8e68 | YuqingDuan/Python_09 | /numpy.py | 537 | 3.609375 | 4 | import numpy
# numpy创建一维数组的语法
# numpy.array([a,b,c,...,n])
arr1 = numpy.array([69,77,22,33,34,63,11])
# numpy创建二维数组的语法
# numpy.array([[a,b],[c,d,e],[f,g],...,[n]])
arr2 = numpy.array([[100,54,35],[33,55,44],[99,77,88]])
# 排序sort
arr1.sort()
arr2.sort()
# 取最值
max1 = arr1.max()
max2 = arr2.max()
min1 = arr1.min()
min2... |
ab7837df62ead50711730424158c18896495b401 | maqianghua/PythonStudy | /workdir/test/lazy_sum.py | 337 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# 函数的返回结果不是返回值,而是函数
def lazy_sum(*args):
def sum():
ax=0
for n in args:
ax=ax+n
return ax
return sum
if __name__ == '__main__':
f=lazy_sum(1,3,5,7,9)
print f #<function sum at 0x05AA7930>
print f() #25 |
2d342d721e779469e540ee680c9f824df7cd691b | maqianghua/PythonStudy | /workdir/py_django/booktest/20180320/ex15.py | 228 | 3.65625 | 4 | from sys import argv
script, filename=argv
txt=open(filename)
print "Here's you file %r:" % filename
print txt.read()
print "Type the filename agin:"
file_again=raw_input("> ")
txt_again=open(file_again)
print txt_again.read()
|
d787fabc0e16e235b73969412a36c70819a89655 | maqianghua/PythonStudy | /workdir/py_django/booktest/20171124/classtest.py | 259 | 3.578125 | 4 |
class CocaCola:
formula =['caffeine', 'sugar', 'water', 'soda']
coke_for_me = CocaCola()
coke_for_you = CocaCola()
print (CocaCola.formula)
print (coke_for_me.formula)
print (coke_for_you.formula)
for element in coke_for_me.formula:
print (element)
|
5fd9d4c18fe919a3458366f55ca1bee1c1833e54 | maqianghua/PythonStudy | /workdir/py_django/booktest/20171121/test6.py | 470 | 3.5625 | 4 | #coding=utf-8
# for every_letter in 'Hello world':
# print (every_letter)
# for num in range(1,11): #不包含11,因此实际范围是1~10
# print (str(num) + ' + 1 = ', num+ 1)
songslist = ['Holy Diver', 'Thunderstruck', 'Rebel Rebel']
for song in songslist:
if song == 'Holy Diver':
print (song, ' - Dio')
elif ... |
237ebdc36f14b009a63ca7de3099c5cfe955d7f2 | maqianghua/PythonStudy | /workdir/test/Fib_class.py | 662 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
class Fib(object):
def __init__(self):
self.a,self.b=0,1 # 初始化两个计数器,a,b
def __iter__(self):
return self #实例本身就是迭代对象,故返回自己
# def __next__(self):
# self.a, self.b=self.b,self.a+self.b #计算下一个值
# if self.a>100000:
# raise... |
7f5de79bf22a129c02a35fdd8c9a11b23ddd65a3 | Trieu210/Duc-session5-C4T8 | /b1.py | 221 | 4 | 4 | x = int(input('Pls type a month u like'))
if x < 2:
print('winter')
if 2 < x < 5:
print('spring')
if 5 < x < 8:
print('summer')
if 8 < x < 11:
print('autumn')
elif 11< x < 13:
print("winter")
|
d18a687c7dd94593d82cb8f2aecf5df5f7c2b645 | nunayerBeezwax/queen_attack_python | /queenAttack.py | 772 | 3.828125 | 4 | def horizontalCheck(x, i):
if i == x:
return True
def verticalCheck(y, j):
if j == y:
return True
def diagonalCheck(x, y, i, j):
x = x, y
i = i, j
if abs(x[0] - i[0]) == abs(x[1] - i[1]):
return True
else:
return False
def queenAttack(x, y, i, j):
if horiz... |
a1a16056938a7ee3a911ed87d05582bf7df3cce4 | bds01/SparkScala | /CodeFiles/Python/PythonClass01.py | 444 | 3.8125 | 4 | class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first+'.'+last+'@company.com'
def Fullname(self):
return '{} {}'.format(self.first, self.last)
emp_1 = Employee('Earl','Thomas',300000)
emp_2 ... |
be62904cd1398267f8bf60a4daa4df68546c5bea | thaibee/Geekbrains_algorithms | /2/2.6.py | 393 | 3.90625 | 4 | import random
n = random.randint(0, 100)
c = 1
while c <= 10:
m = int(input('Give me a number please:'))
if m == n:
print(f'Your guessed it! You used {c} attempts')
break
c += 1
if c == 11:
print(f'You guessed wrong, my number is:{n}')
break
if m > n:
print('... |
063bcbf4e480393aa7c9c3cfcfbae0c92316481c | thaibee/Geekbrains_algorithms | /2/2.8.py | 164 | 3.984375 | 4 | n = int(input('Enter quantity:'))
s = input('Enter the desired symbol:')
m = sum((input(f'Enter line #{i+1}:').count(s)) for i in range(n))
print(f'quantity: {m}')
|
e91950b5a359896caac2403cf76cba2433dc4bbe | soundless/tinyurl | /lib/short_url.py | 1,399 | 3.765625 | 4 | #!/usr/bin/env python
# -*- utf-8 -*-
#
# Converts any interger to a base[BASE] number.
# Base as 62 to represent using all of alphanumeric characters.
# [no space characters] = {0..9}, {B..Z}, {b..z}.
# encode(): take an integer and turns it into the base 51 string.
# decode(): take the base 62 key as a string, turns ... |
b62b77d34cb4d6957320f03ca0ca901e8a91c58f | AhsanAli13503/Obsense-Word-Detector | /detectingWords.py | 724 | 3.921875 | 4 | import re #for Removing number from text
import nltk
from nltk.corpus import stopwords #for removing most common used words from text
class Data:
orignalText=""
preprocesstext=""
def __init__(self,orignalText):
self.orignalText =orignalText
self.preprocesstext=""
def removing_... |
4d4e50d41dde3441d2118e27eba0b13eb6300598 | RamenMode/9-29_Sales | /standardAlgorithm.py | 3,353 | 3.875 | 4 | def nostradamus(dataframe, baselinedataframe, horizon, numepochs, batchsize, regindex):
""" OVERVIEW OF THE INPUT VARIABLES OF THE FUNCTION nostradamus:
dataframe: A dataframe which contains dates as the index and sales data
baselinedataframe: A dataframe which contains (AND MUST CONTAIN) the same dates a... |
104ec9812e62aaa01d94fefe932f90830445e74b | odumitr/StringMatching | /code/ZAlgorithm.py | 3,292 | 3.984375 | 4 | from array import array
import sys
pattern = input('Enter the pattern ')
text = input('Enter the text ')
if(len(pattern) > len(text)):
sys.exit('Text has to be at least the same length as pattern')
input = pattern+'$'+text
def printResult(zArray, pattern):
checker = False
indexMat... |
3aa6b487a0c1653d304d1c3dd9ad9ffbdb45a93e | mzhao15/Algorithms | /binarysearch.py | 335 | 4.0625 | 4 |
def binary_search(array,x):
"""find x in a sorted array """
num = len(array)
left = 0
right = num-1
while left<=right:
mid = (left+right)//2
#print('left:{},mid:{},right:{}'.format(left,mid,right))
if array[mid] == x:
return mid
elif array[mid] < x:
left = mid+1
else:
right = mi... |
f540bddea8a7434305d88c193d62e4e0a44d7d65 | vmangahis/SecondYear-SourceCodes | /First-Semester/Computer Programming 3/Dictionary_Frequency.py | 139 | 3.671875 | 4 | name = "aldrinbaldonado"
dictionary = dict()
for a in name:
dictionary[a] = 0
for b in name:
dictionary[b]+=1
print(dictionary)
|
29f62f5474687977e2c59adf4e9b5b9dcc5105a1 | khanmaster/python_api_json | /json_parsing_with_api.py | 1,695 | 3.53125 | 4 | import requests
import json
post_codes_req = requests.get("https://api.postcodes.io/postcodes/se120nb")
# print(post_codes_req.status_code)
# print(post_codes_req.content)
# print(type(post_codes_req.content))
# print(post_codes_req.headers)
# print(type(post_codes_req.headers))
#print(post_codes_req.json())
json_dat... |
9fd4dd421b659260bdd30f0934880c2c1996898f | tomilashy/using-lists-in-python | /list comprehension.py | 552 | 4.15625 | 4 |
name = [1,2,3,4,5,6,7,8,9];
odd=[x for x in name if x%2!=0 ];
even=[x for x in name if x%2==0 ];
print (odd,even);
edit=[x if x%2==0 else x*2 for x in name ];
print (edit);
mixed="This is jesutomi";
vowels=', '.join(v for v in mixed if v in "aeiou");
print (vowels);
nested_list=[[1,2,3],[4,5,6],[7,8,9]];
print(... |
3afd514e85fad4906c27aa040884bcaf6bcad050 | dvalbuena/433Proj2 | /433Proj2/Cipher.py | 2,716 | 3.546875 | 4 | import sys
from DES_433 import DES_433
from RSA_433 import RSA_433
#Checks if input is valid
class InvalidArgument(Exception):
def __init__(self, value):
self.value = value #Set value
def __str__(self):
return repr(self.value)
def cipher():
#Check if command is of length 6
if len... |
2b63af6ed6bd14f63fc948c7db5a93120969fc1e | Fransisnk/STK-INF-CC | /linearRegression.py | 5,679 | 3.578125 | 4 | import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from sklearn import linear_model
import dataframes
from sklearn.neural_network import MLPClassifier
from datetime import timedelta
from sklearn.externals import joblib
import warnings
warnings.filterwarnings("ignore")
mpl.rcParams['figure.figsi... |
7d0c2c6be3c8af0feff5e7f570906a8b68ba3238 | Borreguin/F.R.E.D.A-Zero | /my_lib/RTDB/RTDA_BaseClass.py | 11,481 | 3.921875 | 4 | # Created by Roberto Sanchez at 3/17/2019
"""
This Abstract class contains abstract methods to deal with Data Acquisition.
The abstract methods are declared, but contains no implementation. Abstract classes may not be instantiated,
and its abstract methods must be implemented by its subclasses.
ABCs in... |
6261dff54e64b86d730f3a1ac66eb8436156b0ee | nse1994/DS-Algorithm | /recursive_sum.py | 144 | 3.796875 | 4 | def recursive_sum(arr):
if arr==[]:
return 0
return arr[0]+recursive_sum(arr[1:])
print(recursive_sum([2,4,6])) |
975c62c2bff39b77cc8865a95ebd818220217b9b | MinThaMie/graph_isomorphism | /color_refinement_helper.py | 11,685 | 3.84375 | 4 | """
Module with helper methods for the Color Refinement Algorithm
"""
from typing import Iterable
from coloring import *
from graph import Graph
from tools import create_graph_helper
Module = [Vertex]
ModularDecomposition = [Module]
DEBUG = False
def debug(*args):
"""
Prints debug statements when DEBUG is ... |
1c5e105c1424bce1dafb795e4d8f77fbb2163a3a | mrcrittall2016/MS-Powerpoint-to-Excel-Table-Extractor | /power_to_excelv7.py | 17,521 | 3.765625 | 4 | # This code is designed to extract text from a TABLE shape type in a powerpoint slide and import it to Microsoft Excel.
# It's first task is to identify how many different TYPES of table there are - meaning how many different heading lists there are
# Try to simplify code so only goes through presentation once... also... |
fea0177db2916665aa5d46d3e61892ff3d140af2 | jrl-labs/getglue | /rt_module.py | 1,556 | 4.09375 | 4 | """
Very very simple module to demonstrate working with an API.
We'll use the rotten tomatoes API since it is very simple.
http://developer.rottentomatoes.com
"""
import requests
import yaml
def query_moviename(moviename, key, page_limit=50):
"""
Queries API by moviename and returns results as a list.
... |
f4ccb014cfacf6a25bc38579ea272dfd38348150 | sametweb/Graphs | /projects/ancestor/ancestor.py | 559 | 3.703125 | 4 | def earliest_ancestor(ancestors, starting_node):
tree = {}
for p, c in ancestors:
if c not in tree:
tree[c] = [p]
else:
tree[c] += [p]
if tree[starting_node] == []:
return -1
current_parents = tree[starting_node]
for p in tree[starting_node]:
... |
401b5235a02c6b7b734bd79f7350f721fe41eb70 | runningwendybird/HBexcer3 | /arithmetic.py | 447 | 3.8125 | 4 | def add(numList):
if len(numList) == 1:
return numList[0]
else:
return (numList[0] + add(numList[1:]))
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
return float(num1) / num2
def square(num1):
return num1**2... |
a612316807a42d5cc2a42136ec103e2c6feeed87 | reeddunkle/Codjo | /Problem1_Richie_Rich/Solutions/Max_Output/richie_rich_max1.py | 507 | 3.703125 | 4 |
def make_palindrome(s, max_moves):
arr = list(s)
moves = 0
for i in range(len(s)//2):
a = arr[i]
z = arr[-1-i]
if a != z:
moves += 1
if z > a:
arr[i] = z
else:
arr[-1-i] = a
if moves > max_moves:
... |
de3eb59451cf4406f84be837a3d9c3d907ea85a6 | ccbury/MapReduceBigDataProject | /StateNames/NameCleanerMapper.py | 348 | 3.84375 | 4 | #Import pandas. will be used to take in the csv file so that it can be worked on
import pandas as pd
#set df equal to the csv file i will be working on
df = pd.read_csv('StateNames.csv')
#For loop to find the Name and Count values on each line and print them out
for ind in df.index:
print('%s\t%s' % (df['Name... |
bb6702afd8d7f178f549781ce9716f1d4692697c | macadada/eink-server | /src/eink/generate/rotation.py | 366 | 3.765625 | 4 | from enum import Enum
class Rotation(Enum):
"""A rotation to use when drawing to the Inkplate device."""
# Landscape rotation
LANDSCAPE = 4
# Portrait left (bottom of device on left)
PORTRAIT_LEFT = 3
# Portrait right (bottom of device on right)
PORTRAIT_RIGHT = 1
# Upside down lan... |
37933bfea31f56ac46322b5615160358236b8930 | thongngoduc/bt_python | /b4.6.py | 93 | 3.609375 | 4 | hoten=input('Ho va ten:').split
print(hoten)
for i in hoten():
print(i.split(','))
|
8119a571523a8cf2bb146033c274677ad94e2311 | malhotraguy/Finding-the-specific-letter | /Code.py | 435 | 4.1875 | 4 | cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai", "Mexico City", "São Paulo", "Hyderabad"]
search_letter = input("Enter the letter you want to search: ")
total = 0
for city_name in cities:
total += city_name.lower().count(search_letter)
print("In",city_name,"there are:",city_name.lower().count(sear... |
5ace4600c412faa4a582e52f453aac1f0279f66d | izzitan/CP1404_practical | /prac_06/languages.py | 529 | 3.5625 | 4 | """
Name: Hafidz Izzi Baihaqi
GitHub: https://github.com/izzitan/CP1404_practical
"""
from prac_06.programming_language import ProgrammingLanguage
ruby = ProgrammingLanguage("Ruby", "Dynamic", True, 1995)
python = ProgrammingLanguage("Python", "Dynamic", True, 1991)
visual_basic = ProgrammingLanguage("Visual Basic"... |
7af95b9fff3e280352fdc799ab60951c289fc5e8 | izzitan/CP1404_practical | /prac_02/randoms.py | 536 | 3.6875 | 4 | import random
print(random.randint(5, 20)) # line 1
print(random.randrange(3, 10, 2)) # line 2
print(random.uniform(2.5, 5.5)) # line 3
"""
Q1 What was the smallest number you could have seen, what was the largest?:
Smallest = 5, largest = 20
Q2 What was the smallest number you could have seen, what was the la... |
4cc802d818f40279cae58017e80074eb14effc4c | izzitan/CP1404_practical | /prac_03/password_check.py | 630 | 4.125 | 4 | """
Name: Hafidz Izzi Baihaqi
GitHub: https://github.com/izzitan/CP1404_practical
"""
MIN_LENGTH = 4
def main():
password = get_password()
while not is_valid_password(password):
print("Invalid password")
password = get_password()
print("Password {} is valid".format(print_asterisk(passwor... |
2c5201d6d6bb1bdb0933b75592630c9cb79286d0 | manishask112/Elements-of-AI | /Machine Learning/orient.py | 24,575 | 3.703125 | 4 | import sys
import csv
import math
import numpy as np
from matplotlib import pyplot as plt
import pickle
import pandas as pd
class NeuralNetwork(object):
def __init__(self, epochs, learning_rate):
self.learning_rate = learning_rate
self.epochs = epochs
# references to Relu and Softmax activati... |
9e596d7cfea1cd15ab81b4628cb6d2ce3426be42 | lemonade512/EulersProject | /Problem020.py | 262 | 3.953125 | 4 | #!/usr/bin/env python
# TODO look into how big integers are actually manipulated in languages
# like Java and C++
total = 1
for i in range(1, 101):
total *= i
sum_ = 0
while total > 0:
num = total % 10
sum_ += num
total /= 10
print sum_
|
b24b76bdcd13ea17c2fda9c6d30fc2e6053ba608 | lemonade512/EulersProject | /Problem032.py | 593 | 3.8125 | 4 | #!/usr/bin/env python
from Problem030 import digits
def digits_pandigital_1to9(d_list):
return sorted(d_list) == [1,2,3,4,5,6,7,8,9]
if __name__ == "__main__":
# TODO find more mathematical way to figure out where to stop
# TODO needs lots of optimizing :)
pandigital_products = set()
for i in x... |
a285d21e89e6860b383a195ab3278614e038d67c | lemonade512/EulersProject | /Problem005.py | 399 | 4.03125 | 4 | #!/usr/bin/env python
from math import sqrt
def is_divisible(n):
for i in xrange(1, 21):
if float(n) % i != 0:
return False
return True
if __name__ == "__main__":
print "Not yet implemented"
#print divisors(20)
#n = 20
#while True:
# n += 20
# print n
# ... |
8abcd87ad2b1d49a3e22175e0546f136b3c6c822 | hcxDawn/python_passion | /data_analysis/charpter_numpy.py | 580 | 3.609375 | 4 | import numpy as np
import random
import matplotlib.pyplot as plt
if __name__ == "__main__":
# total_steps = 1000
# position = 0
# walk = []
# for i in range(total_steps):
# step = random.randint(-1, 1)
# position += step
# walk.append(position)
# plt.plot(range(total_steps),... |
e068f6bb041f2dbd1ba9fbd57cdd165c269397c5 | robertpatrick6/PathfindingMaze | /BasicPathFindingGame/pathfinding.py | 2,494 | 3.921875 | 4 | from collections import deque
def find_path(start_node, end_node, game_map):
''' Attempts to find a path from start_coords to end_coords on
the given game_map, using a basic implementation of the
A* algorithm. Returns a deque object for the path.
set entries are 5-tuples with the... |
69e98a809e7ab76d42f803b19fa0f8256cf7ef11 | chemplife/Python | /python_core/exceptions_basics.py | 9,997 | 3.65625 | 4 | '''
EAFP = It is EASY to ASK for FORGIVENESS than ask for PERMISSION
Exceptions are objects (instances) of the 'class' of exception, they belong to.. Like ValueError, NotImplemented, etc..
When Exceptions are raised:
-> It triggers a special execution 'propogation' workflow
-> We can intercept that workflow by doin... |
35cc2b1e7a38e0d056487a09c811e2371c690ae9 | chemplife/Python | /python_core/chainmaps.py | 4,473 | 4.1875 | 4 | '''
Chainmap works the same way as chain() from itertools.
-> Chain map is to iteratre over multiple Dictionaries without copying them in 1 single Dict.
-> It is a realtime view like chain. Meaning, we can change the underlying dictionaries while iterating over them with Chainmap, and
Cahinmap will iterate over the ch... |
bbc8e82af86f8b5b4df344c5a017fb0cbfe53442 | chemplife/Python | /python_core/iterable_test.py | 9,268 | 3.6875 | 4 | t = (1,2,3,4)
l = [1,2,3,4]
s = {1,2,3,4}
d = {'a':1, 'b':2, 'c':3, 'd':4}
st = 'abce'
# set and dictionary -> s[0], d[0] WON'T WORK. They are UNORDERED.
# UNPACKING
# 1. Tuple
a,b,c,e = t
print(f'Tuple: a={a}, b={b}, c={c}, e={e}')
# 2. List
a,b,c,e = l
print(f'List: a={a}, b={b}, c={c}, e={e}')
# 3. String
a,b,c,... |
0cdf6e634afa0163d568e406260829a90b5542b0 | chemplife/Python | /practice_problems/biggest_string.py | 949 | 3.875 | 4 | '''
Problem 1: Find the biggest substring in the string that has only 2 unique characters
Input: assdeeeddfffhf
Output: deeedd
Problem 2: Find the longest word that has the input characters.
Input: {'act', 'acquaintance', 'trace'}
chars: cat
Output: acquaintance
'''
#### Problem 1:
inp_str = 'assdeeeddfffhf'
# Brute... |
457964a41f30fee081ff58912b839cbc1e27b6dc | chemplife/Python | /python_core/Modules_Tests/create_module_from_scratch/main.py | 2,011 | 3.5625 | 4 | # To build the path to module1_source and help sys locate it.
import os.path
# To create Module using types.ModuleType
import types
# To load module to sys
import sys
# For search and load module manually
# What will be the name of the module going to be. This doesn't have to match the actual file name, but typicall... |
a9e847b2dcaa769c2a764d6c107e5f1913e9322e | chemplife/Python | /python_core/json_serialization.py | 6,827 | 3.59375 | 4 | '''
JSON: JavaScript Object Notation.
Default: Serialization/Deserialization will not execute code so, it is consider safe compared to pickling/unpickling
Datatype supported: "string" -> Double Quotes Delimiter And Unicode characters only.
Numbers -> 100, 3.14, 3.14e-05, 3.14E+5 -> all are considered floats. No... |
584d9a90b5a59a30f6dc531130e6e7ed1636d94c | chemplife/Python | /python_core/serialization_and_deserialization.py | 1,203 | 3.953125 | 4 | '''
Serializing/Deserializing Objects
Useful when dealing with persisting data or for Transmiting Data.
-> Data that we want to 'save' somewhere so that is can 'loaded' at later time.
-> Even after the program is terminated.
-> Transmit the data outside of the app.
It can be applied to any object:
-> Persistent Re... |
73dddc9d4d1adc61bdd4fdb33e04ee63b4e3756c | chemplife/Python | /python_core/grouping_iterable.py | 984 | 4 | 4 | '''
Grouping iterators based on the first element of the iterable.
Eg: [1,10,100] -|
[1,1000,2000] | Group 1
[1,4000,6000] -|
[2,20,200] -|
[2,500,5000] -| Group 2
[3,30,300] -|
[3,3000,7000] | Group 3
[3,3500,9000] -|
itertools.groupby(iterable, [keyfunc])
-> Returns LAZY ITERATOR
-> default ke... |
6dc649fe5d64f037fe4ac0fa8acd49863efbb2ac | chemplife/Python | /python_core/function_args_kargs.py | 1,492 | 4.25 | 4 | # *args scoops the positional arguments into a Tuple.
# **kwargs scoops the Keyword arguments into a Dictionary.
def my_func0(a,b,*args):
print('my_func0')
print(f'a:{a}, b:{b}, args:{args}')
my_func0(10,20,30,40)
print('-------------------------------')
# '*args' takes all the left overs.
# To have anything after... |
4191728016f0a8f1130b2a84687e68fbdb2b8345 | chemplife/Python | /python_core/lazy_iteration.py | 2,524 | 3.9375 | 4 | '''
LAZY EVALUTION: Don't evaluate something until it is requested.
'''
# How to get area of a circle as property when only radius is passed.
import math
# Currently, area is calculated each time radius change
class Circle:
def __init__(self, r):
self.radius = r
@property
def radius(self):
return self._radiu... |
2574d6ee37ff0e0842762a56f4efbb602eefc8f1 | chemplife/Python | /python_core/default_dict.py | 4,394 | 4.59375 | 5 | '''
- Standard Dictionary (dict), if we don't find 'key' we get KeyError
- If we use 'd.get(key, defaultValue)'' -> We get either the 'Key' value or the DefaultValue if 'Key' is missing
- But if we have a lot of these 'd.get()' methods that uses a 'Default Value', to maintain consistancy,
we Need to remember the Defau... |
5cacc5b8c370f07cb27ec26f944ddf038ecfddd9 | Andrew-Figueiredo/Algoritmos-Ordenacao | /Bubble Sort/bubble_sort.py | 442 | 4.0625 | 4 | def bubble_sort(vetor):
for i in range(len(vetor)-1,0,-1):
for j in range(i):
if vetor[j+1] < vetor[j] :
aux = vetor[j]
vetor[j] = vetor[j+1]
vetor[j+1] = aux
if __name__ == "__main__":
vetor = [9, 5, 2, 3, 1 ,0, 7, 13, 10]
... |
8318bf6fac4d4c73273ccb7dcf616d528f374bd7 | fras2560/graph-helper | /algorithms/induced_subgraph.py | 6,355 | 3.8125 | 4 | """
-------------------------------------------------------
contains
holds a function contains
-------------------------------------------------------
Author: Dallas Fraser
ID: 110242560
Email: fras2560@mylaurier.ca
Version: 2014-09-17
-------------------------------------------------------
"""
import itertool... |
7cfd845725de8261416ae7861d8ba15163f45e92 | sramsubbu/weatherforecast_imd | /imd_forecast/imd_interface.py | 1,608 | 3.515625 | 4 | import requests
import bs4
from bs4 import BeautifulSoup
CITY_LIST_URL="https://internal.imd.gov.in/pages/city_weather_main_mausam.php"
CITY_FORECASE_URL = "https://city.imd.gov.in/citywx/city_weather.php"
def get_cities():
resp = requests.get(CITY_LIST_URL)
soup = BeautifulSoup(resp.text, "html.parser")
... |
3201f2dbd2a238efc7166b6b4c3da194e859feec | OliverWarwick/housing_scrapper | /src/database_tester.py | 1,734 | 3.640625 | 4 | import sqlite3
from sqlite3 import Error
import os
def create_connection(db_file):
conn = None
try:
conn = sqlite3.connect(db_file)
print(sqlite3.version)
return conn
except Error as e:
print(e)
# Create database if not there.
def create_table(create_table_sql, connection):
try:
connection.execute(cre... |
69f2023e39b5ebfc7c87ba8b0beb524d19512311 | dotnet-tech/python-basics | /Operators/Operator_Overloading.py | 1,368 | 4.3125 | 4 | #Operator Overloading
print(1 + 2)
print("Python"+"is")
print(3 * 4)
print("Python"*4)
#output
'''
3
Pythonis
12
PythonPythonPythonPython
'''
class AddNumbers:
def __init__(self,a):
self.a =a
def __add__(self,b): #magic method (+ overloading)
return self.a + b.a ... |
b1a68a490eb58df25181727405e298bd9722774e | Darnele91/100Days_Of_Python | /classes2.py | 718 | 3.953125 | 4 | students = []
class Student:
schoolName = "Springfield High School"
def __init__(self, name, studentId):
self.name = name
self.studentId = studentId
students.append(self)
def __str__(self):
return "Student and ID: " + self.name + ", " + self.studentId
def getNameCapi... |
76cdac2092cd93a0a8f55280f956a2759dd11661 | akashagarwal123/coder | /n.py | 155 | 3.71875 | 4 | n = input()
c=0
for i in n:
if(i=="1" or i=="2" or i=="3" or i=="4" or i=="5" or i=="6" or i=="7" or i=="8" or i=="9" or i=="0"):
c+=1
print(c) |
91fb0af3be8841d25a9edafb23721d67f5871c21 | tianlin1028/isdhw | /01/main.py | 167 | 3.75 | 4 | #homework01
for i in range(1,10):
for j in range(i,10):
w=str.format("{0:1}*{1:1}={2:>2}",i,j,i*j)
print(w,end=" ")
print()
|
34f3214dbc2f0e0c38b5a46972a9832782ee7b1f | Mat4wrk/Object-Oriented-Programming-in-Python-Datacamp | /1.OOP Fundamentals/Create your first class.py | 785 | 4.46875 | 4 | # Create an empty class Employee
class Employee:
pass
# Create an object emp of class Employee
emp = Employee()
# Include a set_name method
class Employee:
def set_name(self, new_name):
self.name = new_name
# Create an object emp of class Employee
emp = Employee()
# Use set_name() on emp to set ... |
c71fdafcca6cdfebd85e7b8f22ff758179d20a90 | Mat4wrk/Object-Oriented-Programming-in-Python-Datacamp | /3.Integrating with Standard Python/Overloading equality.py | 577 | 3.84375 | 4 | class BankAccount:
# MODIFY to initialize a number attribute
def __init__(self, number, balance=0):
self.balance = balance
self.number = number
def withdraw(self, amount):
self.balance -= amount
# Define __eq__ that returns True if the number attributes are equal
... |
fdaedb3d40cdd6ee9c08e3eda9f0d23c1de2c55e | anikm89/pythonExercises | /samples/anagramCheck.py | 1,226 | 3.84375 | 4 |
s1 = "clint eastwood"
s2 = "old west action"
def anagram(s1,s2):
result =''
s1 = s1.replace(" ","")
s2 = s2.replace(" ","")
dictS1 = {}
if len(s1) !=len(s2):
return False
for i in range (len(s1)):
if s1[i] not in dictS1:
dictS1[s1[i]] = 1
else:
... |
ef39675cdf9d70bb7f10450426b1ae2fe8472e3b | anikm89/pythonExercises | /samples/removeDups.py | 460 | 3.515625 | 4 |
import timeit
s = 'tree traversal'
def dups(s):
newS = []
d ={}
for i in range(len(s)):
if s[i] not in newS:
newS.append(s[i])
return "".join(newS)
def unique(s):
result =[]
seen ={}
for item in s:
if item not in seen:
seen[item] = 1
... |
23743a42d4d7db87b0c530502690921c739b70cf | myleet/BI | /scripts/testrecur.py | 8,984 | 4.0625 | 4 | #!/usr/bin/env python
from __future__ import print_function
from builtins import range
import os
# Chapter 4. Recursion
# Reinforcement
"""
R-4.1
Describe a recursive algorithm for finding the maximum element in a sequence, S, of n
elements. What is your running time and space usage?
"""
def find_max(dlist, index,... |
767d4f816688ca88fefdeb7ac499aa9ca4b8fbc7 | myleet/BI | /scripts/testsClass.py | 5,985 | 4.40625 | 4 | #!/usr/bin/env python
from __future__ import print_function
from builtins import range
import os
# Chapter 2. Class
# Reinforcement
"""
R-2.1
Give three examples of life-critical software applications.
R-2.2
Give an example of a software application in which adaptability can mean
the difference between a prolonged ... |
f88c36164f8867b295507fc6466dacbc1b927770 | KiranSpace/pythonScriptsTutorial | /for.py | 84 | 3.671875 | 4 | #!/usr/bin/python
lst=(0,"One",2,"three")
for element in lst:
print element
|
6fd2d798546cf5fac317444333b71d5f7a276503 | KiranSpace/pythonScriptsTutorial | /Naveen/login.py | 262 | 3.609375 | 4 | #! /usr/bin/python
import getpass
username=input("Username :")
password=getpass.getpass("password :")
if(username == "Naveen") and (password == "Naveen"):
print("login successfull")
else:
print("login un-successfull")
|
e0504710ea499bd394004095ba27d8b0a24b5c46 | ajay0006/madPythonLabs | /Lab5/verticalDisplay.py | 815 | 4.15625 | 4 | # this code displays a vertical line across the gfx hat screen
from gfxhat import lcd
lcd.clear()
lcd.show()
# this is a function that takes the user input for the X coordinate and validates it, making sure it isnt above 127
# it also returns the users input
def verticalDisplayInput():
x = int(input("please ent... |
1ebe1aa2e314333c3889705de766fea34f5aa025 | ajay0006/madPythonLabs | /Lab5/staircase.py | 1,895 | 3.84375 | 4 | # This program draws staircases on the GFXHat
from gfxhat import lcd
# clearing the buffer and showing the cleared buffer
lcd.clear()
lcd.show()
# setting values for the variable height and width, this remains constant throughout the program
w = 21
h = 9
# We will be creating eleven functions to depict the lowe... |
4a10a7ac84a121e134505038b4c4dbf00b7df0e4 | ericzacharia/MarkovSpeakerRecognition | /map.py | 2,162 | 4.625 | 5 | from abc import ABC, ABCMeta, abstractmethod
class Map(ABC):
"""
Map is an Abstract Base class that represents an symbol table
"""
@abstractmethod
def __getitem__(self,key):
"""
Similar to the __getitem__ method for a Python dictionary, this will
return the ... |
0cb1d45b9084f5bd152a7e7d0de50010c1e74e02 | itoledoc/coneHighFreq | /analysisUtilsLight.py | 8,335 | 3.578125 | 4 | from pylab import *
bandDefinitions = {
1: [31.3e9, 45e9],
2: [67e9, 90e9],
3: [84e9, 116e9],
4: [125e9, 163e9],
5: [163e9, 211e9],
6: [211e9, 275e9],
7: [275e9, 373e9],
8: [385e9, 500e9],
9: [602e9, 720e9],
10: [787e9, 950e9]
}
def getBand(freq):
"""
Converts a freque... |
13c7560f05b7948da4e28fbd3e2f103f9080a0a5 | PSauerborn/MLP-for-MNIST-Hand-Written-Digit-Classification | /neural_network.py | 4,482 | 3.625 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
# Training Models Using TensorFlows High Level API
# ------------------------------------------------------------------------------
# The following code will explore two of tensorflows high level API's. One is calle... |
076d030df176d76b7fbeec24a1bc976389ab1bc7 | GraceDurham/scrapy | /tutorial/tutorial/spiders/quotes_spider.py | 1,186 | 3.578125 | 4 | ####This spider just pulls back html for each url and throws it in the console
import scrapy
class QuotesSpider(scrapy.Spider): #Inhert from scrapy.Spider
name = "quotes"
#Create a method called start_requests that yeilds the urls to get the html from
def start_requests(self):
urls = [
... |
6d528e9d9c3b74cc3b4c81555e74edd4c8ddc069 | cha9ro/translation-speech2speech | /src/translate.py | 596 | 3.875 | 4 | '''
Translation between English to Japanese
'''
from googletrans import Translator
translator = Translator()
string = input('input(enter \'q\' to exit): ')
while string != 'q':
result = translator.detect(string)
if result.lang == 'en':
result = translator.translate(string, dest='ja')
output =... |
001166331b73f174c6b3c300e5164a5e83a859cd | elliotta/quick_scripts | /matting_gui.py | 15,225 | 3.828125 | 4 | #!/usr/bin/env python
from decimal import Decimal
import Tkinter as tk
class DecimalVar(tk.Variable):
"""Value holder for float variables."""
_default = 0.0
def __init__(self, master=None, value=None, name=None):
"""Construct a float variable.
MASTER can be given as master widget.
... |
86b148a5bf75378264cce1ba56af7742008a1195 | guckeale000/Project_Euler | /problem_1.py | 360 | 4.09375 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
if __name__ == '__main__':
upto = 1000
valid_increments = (3, 5)
s = sum(sum(x for x in range(0, upto, y)) for y in ... |
43d0a944eb575744d2010b5c7fba39af7e9d96c9 | Tiagosf00/sudoku-solver | /sudoku.py | 1,775 | 4.21875 | 4 | # Sudoku solver using backtrack recursion
# Example with an unique solution.
sudoku = [[5,3,0, 0,7,0, 0,0,0],
[6,0,0, 1,9,5, 0,0,0],
[0,9,8, 0,0,0, 0,6,0],
[8,0,0, 0,6,0, 0,0,3],
[4,0,0, 8,0,3, 0,0,1],
[7,0,0, 0,2,0, 0,0,6],
[0,6,0, 0,0,0, 2,8,0],
... |
b47ca7a1a297862ae07303ca25b9d661ba36bbbb | HenryEscobar/public-notes | /python/notes/basic/the_basics.py | 1,963 | 3.796875 | 4 | # from the_basics import *
# dir(foobar) and type(foobar) are your friends
#
# Examples of ways to print options for a class/variable
# dir(set)
# print(*dir(set), sep="\n")
# print(' '.join(str(x) for x in dir(set)))
# print(' '.join(map(str,dir(list))))
# print(('\n'.join(dir(list))))
#
# # Utilities
# help('modu... |
604b34d1e248e3617adb50278f5a19ff51989e7f | HenryEscobar/public-notes | /python/exercises/fibonacci.py | 768 | 3.921875 | 4 |
# Fn = Fn -1 + Fn -2
fibonacci_cache = {}
fibonacci_cache[0] = 0
fibonacci_cache[1] = 1
def fibonacci(n):
if n not in fibonacci_cache:
fibonacci_cache[n] = fibonacci(n-1) + fibonacci(n-2)
return(fibonacci_cache[n])
if __name__ == '__main__':
user_input = input("Please enter an int): ")
... |
22ea0ebe93fc4d4da19d255913a2a76937b21d08 | OneArmyj/assignment1 | /CS3243_P1_17_5.py | 11,120 | 3.734375 | 4 | '''
Experiment file
'''
import random
import CS3243_P1_17_1 #uninformed
import CS3243_P1_17_2 #misplaced tiles
import CS3243_P1_17_3 #manhattan
import CS3243_P1_17_4 #linear conflict
import timeit
'''
#undo multiline comment to utilize run() function. It returns a list of 5 randomly selected initial state with specifi... |
dd12069cdf3fd0e233400bf817811551d5b3b46b | wendiewang/hackbright-me | /ex05_arithmetic.py | 721 | 3.890625 | 4 | def add(first_number, second_number):
answer = first_number + second_number
return answer
def subtract(first_number, second_number):
answer = first_number - second_number
return answer
def multiply(first_number, second_number):
answer = first_number * second_number
return answer
def divide(first_number, se... |
fbc9ece740fd81b9cf01c93c6fe79345770d4eb7 | Fenkail/Data_Structure | /Heap_sort.py | 902 | 3.875 | 4 | import time
def heapify(A,n,i):
largest = i
left = 2*i + 1
right = 2*i + 2
# 判断左右子节点,是否大于根节点
if left < n and A[i] < A[left]:
largest = left
if right < n and A[largest] < A[right]:
largest = right
# 需要完成的交换步骤
if largest != i:
A[i], A[largest] = A[largest], A[i]
... |
9692ffc527756dab634800d96b5b9e168cae5528 | LizAharonian/SecureProgrammingEx2 | /breakcloud.py | 1,086 | 4.03125 | 4 |
# Consts
PLAINTEXT_FILE_NAME = "plain.txt"
ZERO_AS_BYTE = b'\x00'
EMPTY_STRING = ""
def breakcloud(cloud):
"""
receives 'cloud', an object of type Cloud.
creates a file with the name 'plain.txt' that stores the current text that is encrypted in the cloud.
you can use only the Read/Write interfaces of Cloud (do n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.