blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
8a61b80b3b96c4559149609d9630323a05f3a134 | tanviredu/DATACAMPOOP | /first.py | 292 | 4.34375 | 4 | # Create function that returns the average of an integer list
def average_numbers(num_list):
avg = sum(num_list)/float(len(num_list)) # divide by length of list
return avg
# Take the average of a list: my_avg
my_avg = average_numbers([1,2,3,4,5,6])
# Print out my_avg
print(my_avg) |
e8bd55a1e99a13855e4757dbde04e29b3f0cfd69 | mradamt/python-katas | /learn-python-programming/while-loops.py | 380 | 3.65625 | 4 | # binary.2.py
n = 39
remainders = []
while n > 0:
# remainder = n % 2
# remainders.append(remainder)
# n //= 2
n, remainder = divmod(n, 2)
remainders.append(remainder)
# remainders.insert(0, remainder) # book does this, not sure why??
print(remainders)
resulto = 0
for power, num in enumerate(... |
0ba8aa42bb7af47413ad79097820892660575658 | chainrocker55/Python-IR-Flask | /BinarySearchTree.py | 2,387 | 3.59375 | 4 | class TreeNode:
def __init__(self,key,val,file,left=None,right=None,parent=None):
self.key = key
self.payload = val
self.leftChild = left
self.rightChild = right
self.parent = parent
self.file = {file}
def hasLeftChild(self):
return self.leftChild
de... |
ec2a6f427af58e41c0b8eabcc8c27e3fa57cd17d | matthew-william-lock/Prac1_BasicGPIOandCounter_EEE3096S | /firstScript.py | 926 | 3.734375 | 4 | #!/usr/bin/python3
"""
First Python Script
Names: Matthew Lock
Student Number: LCKMAT002
Prac: NA
Date: 20 July 2019
"""
def main():
#print("Hello World!")
if GPIO.input(16):
print('Input was HIGH')
else:
print('Input was LOW')
if __name__ == "__main__":
# Make sure the GPIO is stopped... |
4837166fd3510edb5f201445d603b321dc3c22a4 | Lutfi-Mechatronics/Python | /linkingMultipleScripts/function.py | 147 | 3.6875 | 4 | def add(a,b):
c= a+b
return c;
print("This is another module")
#a = int(input("a = "))
#b = int(input("b = "))
#c = add(a,b)
#print(c)
|
668fd6ba4d9f0f1da31c81da37646b2c14d2484d | jewellwk/flask-basic-calc | /app.py | 1,144 | 3.796875 | 4 | from flask import Flask, request, render_template, redirect, url_for
from config import Config
from operations import Operations
app = Flask(__name__)
app.config['SECRET_KEY']='tempconfig'
"""The application is a basic calculator that has a single server route called index. The input from the user is handled through a... |
caaf2c8cf85b91b74b917523796029eda659131f | samithaj/COPDGene | /utils/compute_missingness.py | 976 | 4.21875 | 4 | def compute_missingness(data):
"""This function compute the number of missing values for every feature
in the given dataset
Parameters
----------
data: array, shape(n_instances,n_features)
array containing the dataset, which might contain missing values
Returns
-------
n_missin... |
5fba100eca7a94ce5e68ec7fba2c028befc5733e | fleetingold/PythonStudy | /PythonSample/asynciostudy/async_hello2.py | 744 | 3.546875 | 4 | #用asyncio提供的@asyncio.coroutine可以把一个generator标记为coroutine类型,然后在coroutine内部用yield from调用另一个coroutine实现异步操作。
#为了简化并更好地标识异步IO,从Python 3.5开始引入了新的语法async和await,可以让coroutine的代码更简洁易读。
#请注意,async和await是针对coroutine的新语法,要使用新的语法,只需要做两步简单的替换:
#把@asyncio.coroutine替换为async;
#把yield from替换为await。
import asyncio
async def hello():
... |
8676dee51ce9e5407202043280047d09451a1dd1 | minus9d/programming_contest_archive | /event/utpc2014/a/a.py | 311 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
S = input()
words = S.split()
ret = []
stack = []
for w in words:
if w == "not":
stack.append(w)
else:
if len(stack) % 2:
ret.append("not")
ret.append(w)
stack = []
ret += stack
print(" ".join(ret))
|
c5acc42ccc23c63efa120fdea4436271fa4ad553 | minus9d/programming_contest_archive | /abc/110/c/c.py | 522 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import array
from bisect import *
from collections import *
import fractions
import heapq
from itertools import *
import math
import random
import re
import string
import sys
S = input()
T = input()
def to_num_list(s):
seen = {}
ret = []
idx = 0
for ch ... |
30ef0618cc35dc760b5f346cc632ecbef6335ce5 | minus9d/programming_contest_archive | /abc/028/c/c.py | 241 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import itertools
nums = list(map(int,input().split()))
possible = set()
for comb in itertools.combinations(nums,3):
possible.add(sum(comb))
l = list(possible)
l.sort()
print(l[-3])
|
c82802c86b01f24c0d165543b5f8b602319f5c70 | minus9d/programming_contest_archive | /arc/051/b/b.py | 134 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
K = int(input())
a,b = 1,1
k = 1
while k < K:
a,b = b, a+b
k += 1
print(a,b)
|
b31144ab8fcbfffa577b6a4fef4ae666df374f18 | minus9d/programming_contest_archive | /event/tenka1_2015/qualB/a/a.py | 128 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
a = [100,100,200]
for i in range(17):
a.append( sum(a[-3:]) )
print(a[-1])
|
6db29c6dcbe242875195ed813a3f3b94dd42825c | minus9d/programming_contest_archive | /agc/015/b/b.py | 389 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import array
from bisect import *
from collections import *
import fractions
import heapq
from itertools import *
import math
import re
import string
S = input()
up = len(S) - 1
down = 0
ans = 0
for ch in S:
if ch == 'U':
ans += up * 1 + down * 2
else:
... |
c45fd0c9098369dc593ea99be100f3605fc79ea8 | minus9d/programming_contest_archive | /arc/050/a/a.py | 137 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
a,b = input().split()
if a.lower() == b.lower():
print("Yes")
else:
print("No")
|
9e0620c57ebd8a013fd8e503aa11792b6411e94b | minus9d/programming_contest_archive | /abc/264/d/d.py | 612 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import array
from bisect import *
from collections import *
import fractions
import heapq
from itertools import *
import math
import random
import re
import string
import sys
sys.setrecursionlimit(10 ** 9)
s = "atcoder"
ch2i = dict()
for i, ch... |
e947f2c0644dfa19946e57563a5f5a538896ecbc | minus9d/programming_contest_archive | /arc/046/b/b.py | 482 | 3.65625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def Awin():
N = int(input())
A, B = map(int,input().split())
if A == B:
if N % (A + 1) == 0:
return False
else:
return True
else:
if A > B:
return True
else:
if N <= A:
... |
173eb8898187ad1be75b1b6d8c3a3082fd1b8483 | shayansaha85/pypoint_QA | /set 1/8_set1.py | 177 | 3.625 | 4 | s = input('Enter the string : ')
c = input('Enter the character : ')
qty=0
for i in range(len(s)):
if s[i]==c:
qty+=1
if qty==0:
print("Character absent.")
else:
print(qty) |
20fa8440f891bb2e029f91ffaa4c756c1390b5e8 | shayansaha85/pypoint_QA | /set 5/4.py | 202 | 3.859375 | 4 | user_in = int(input('Enter an integer = '))
reversed_num = 0
while user_in!=0:
remainder = user_in%10
reversed_num = reversed_num*10 + remainder
user_in = user_in//10
print(reversed_num) |
b64227987d45a45b49e29fa72eade1e270b7e04f | shayansaha85/pypoint_QA | /set 1/7_set1.py | 341 | 3.59375 | 4 | def isPrime(n):
c=0
if n==1 or n==0:
return False
else:
for i in range(2,n+1):
if n%i==0:
c=c+1
if c==1:
return True
else:
return False
n = input('Enter the price : ')
sumOfPrime=0
for i in range(len(n)):
if isPrime(int(n[i])):
sumOfPrime+=int(n[i])
perc = sumOfPrime
result=int(n)-int(n)*(pe... |
db426dec0f8cfd0d8fc138ce1385a616bf997777 | shayansaha85/pypoint_QA | /set 2/4.py | 568 | 3.859375 | 4 | def decimalToBinary(decimal):
binary=0
i=1
while decimal!=0:
remainder=decimal%2
binary=binary+remainder*i
i=i*10
decimal=decimal//2
return binary
def isPrime(n):
if n==1 or n==0:
return False
else:
c=0
for i in range(2,n+1):
if n%i==0:
c+=1
if c==1:
return True
else:
return False
... |
1825166f93661260fc8c8c7111325d109e2bf949 | nirajchaughule/Python_prac | /percentage.py | 176 | 3.765625 | 4 | a=int(input("Enter marks for phy:"))
b=int(input("Enter marks for math:"))
c=int(input("Enter marks for chem:"))
e=a+b+c
d=((e)/100)
print(f"percentage is: {d} thank you") |
4eeae28692a734dbb6157c28980f15a0393a1126 | nirajchaughule/Python_prac | /12345.py | 76 | 3.625 | 4 | i=1
j=1
while(i!=6):
while(j!=6):
print(f'{i} {j}')
i=i+1
j=j+1 |
174ef8a1e79763772af182c5ff63f39a87cafafc | nirajchaughule/Python_prac | /first.py | 71 | 3.640625 | 4 | d=int(input("How many miles ran?"))
a=d*(1.60934)
print(f"{a} kms")
|
30796510837442fecdbe295212ea85076e8652c0 | nirajchaughule/Python_prac | /goffour.py | 290 | 3.875 | 4 | print("Hello please enter 4 numbers:")
a=input()
b=input()
c=input()
d=input()
if a>b and a>c and a>d:
print(f"{a} greatest")
elif b>a and b>c and b>d:
print(f"{b} greatest")
elif c>a and c>b and c>d:
print(f"{c} greatest")
elif d>a and d>b and d>c:
print(f"{d} greatest") |
9800840f7281936dddcec440dc419c3abbf7e262 | nirajchaughule/Python_prac | /rps ai.py | 795 | 3.859375 | 4 | import random
a= input("User A:Enter input").lower()
print("NO CHEATING\n"*10)
b=random.randint(0,2)
#rock
if b==0:
print("User B chose rock")
#paper
if b==1:
print("User B chose paper")
#scissor
if b==2:
print("User B chose scissor")
if a:
if a!="rock" and a!="paper" and a!="scissor":
... |
9aed22ae137e7764b813a0e18c5b9d3a2d7b19a7 | nirajchaughule/Python_prac | /rps.py | 609 | 3.921875 | 4 | print("Enter user 1's choice")
a=input()
print("Enter user 2's choice")
b=input()
if a=="Rock" and b=="Rock":
print("Same....Try again")
elif a=="Rock" and b=="Paper":
print("B Wins")
elif a=="Rock" and b=="Scissor":
print("A Wins")
elif a=="Paper" and b=="Rock":
print("A Wins")
elif a=="Paper" and b=="... |
74a1f29554e95d3b518d5f3dd189371dc59ee74a | bodhita8/ML-image- | /NeuralNetwork/NeuralNetwork.py | 7,701 | 4.09375 | 4 | """This code implements a Neural Network from scratch in Python
Yathartha Tuladhar
03/15/2019
"""
from __future__ import division
from __future__ import print_function
import numpy as np
from utils import RELU, SigmoidCrossEntropy, iterate_minibatches, extrude
import pickle as pkl
import matplotlib.pyplot as plt
cl... |
da779d1b219ada1df2d9631bb16592c3a7e6fc26 | omarmohamed10/Analyzing-Used-Car-Listings-on-eBay | /Analyzing Used Car Listings on eBay.py | 8,926 | 3.5625 | 4 | #!/usr/bin/env python
# coding: utf-8
#
# # Analyzing Used Car Listings on eBay Kleinanzeigen
#
# We will be working on a dataset of used cars from eBay Kleinanzeigen, a classifieds section of the German eBay website.
#
# The dataset was originally scraped and uploaded to Kaggle. The version of the dataset we are w... |
fd515f691b43ee8569759f10fcf632759101e551 | libxing/ns3-simulating-scale-free-network-and-other-related-models. | /graph-tool/test3.py | 2,022 | 3.5 | 4 | import pdb
import sys
import random
def initvertices(nver, degrange):
vertices = []
for i in range(nver):
vertices.append(random.randrange(degrange))
return vertices
def gettotdegree(vertices):
totdegree = 0
for deg in vertices:
totdegree += deg
return totdegree
def choosenod... |
08bfd6700db8bbd26996e991d6af47e32c46ec2d | notexactlynikhil/Bean-The-Bot | /bean-bot.py | 2,809 | 3.75 | 4 | import pyautogui
from time import sleep
import sys
# the basic welcome message
def welcome():
print("\t==>> THE BEAN BOT <<==")
print()
# to check if the user wants to spam from a txt file or a word/sentence
def get_spam_type():
print("Spam a word/sentence - enter 1")
print("Spam from a text file -... |
d0290ae89b63087d7e26d688b091bd08972c3357 | viverbungag/Codewars | /selection sort.py | 369 | 3.546875 | 4 | x = [12 ,24, 54 ,67, 2, 5]
for i in range(len(x)):
# Find the minimum element in remaining
# unsorted array
min_idx = i
for j in range(i+1, len(x)):
if x[min_idx] > x[j]:
min_idx = j
# Swap the found minimum element with
# the first element ... |
76c23944851c4f88c43e1a282e103e4348abeae9 | viverbungag/Codewars | /Find The Parity Outlier.py | 216 | 3.921875 | 4 | def find_outlier(integers):
return [x for x in integers if x % 2 == 0][0] if sum([1 for x in integers if x % 2 == 0]) == 1 else [x for x in integers if x % 2 == 1][0]
print (find_outlier([2, 4, 6, 8, 10, 3])) |
9c4e8e6ba49e2fccf1999ca306486abce35a919a | viverbungag/Codewars | /Twice linear.py | 403 | 3.640625 | 4 | def dbl_linear(n):
store = [1]
two = 0
three = 0
while len(store) <= n:
form1 = 2 * store[two] + 1
form2 = 3 * store[three] + 1
if (form1) > (form2):
store.append(form2)
three += 1
else:
if form1 != form2:
store.append(f... |
8817d9af61eadc0c41e6e94c4bf0bdd663ed7947 | viverbungag/Codewars | /Permutations.py | 264 | 3.78125 | 4 | from itertools import permutations as permute
def permutations(string):
perm = set(permute(string))
ans = []
for x in perm:
wrd = ""
for y in x:
wrd += y
ans.append(wrd)
return ans
print (permutations('aabb')) |
599d78a0769b929a571859a17db23b73ed5e3809 | viverbungag/Codewars | /Human readable duration format.py | 1,160 | 4 | 4 |
def format(current, next1, next2, next3, next4):
addFormat = ""
if current > 1:
addFormat += "s"
if next2 or next3 or next4:
addFormat += ", "
elif next1:
addFormat += " and "
return addFormat
def format_duration(seconds):
#your code here
ans = ""
hour = 0... |
4d084fd8486ab049ba2b709408adc2e2eb7f0b2c | viverbungag/Codewars | /Weight for Weight.py | 1,015 | 3.5 | 4 | def order_weight(string):
list = string.split()
summ = []
dict = {}
result = ""
for x in range(len(list)):
tot = 0
for y in range (len(list[x])):
tot += int(list[x][y])
summ.append([tot, list[x]])
summ.sort(key = lambda elem: elem[0])
for x in range(len(su... |
236dcf7526ba3d9c5bfc1f866592b88215d91c25 | viverbungag/Codewars | /Valid braces.py | 1,514 | 3.59375 | 4 | def validBraces(string):
ident = False
string_list = list(map(str, string))
reverse_list = string_list.copy()
reverse_list.reverse()
num = 1
for x in range(len(string_list)):
if "(" == string_list[x]:
if string_list[x] == "(" and reverse_list[x] == ")":
ident ... |
34626d7f4d5fdbb31239306b73277e86bc8aea53 | viverbungag/Codewars | /Sum of the first nth term of Series.py | 244 | 3.671875 | 4 | def series_sum(n):
# Happy Coding ^_^
ans = [1]
tri = 0
for x in range (1, n):
tri += 3
ans.append(1/(1+tri))
ret = round(sum(ans), 2) if n != 0 else 0
return "{:.2f}".format(ret)
print (series_sum(1)) |
982c097c8c499ca525fefe940aac29858abdc27d | musa0491/special-musa | /password.py | 596 | 4.09375 | 4 | import re
def password_test():
keyword = input("enter a keyword: ")
if int(len(keyword)) >= 8:
if keyword != re.search("\w", keyword):
print("invalid add lower case letter to your password: ")
elif keyword != re.search("\w", keyword):
print("invalid add uppercase letter... |
83eb924d792a8041042aac4dca4c79e4120ef05d | shayan-taheri/LeetCode_Projects | /PCA_SVM_Face.py | 3,473 | 3.8125 | 4 | # PCA (Unsupervised Method) + SVM (Supervised Method) Execution Code.
# Link: https://scipy-lectures.org/packages/scikit-learn/auto_examples/plot_eigenfaces.html
# Data: Face Images.
# Author: Shayan (Sean) Taheri - Jan/10/2021
# Simple facial recognition example: Labeled Faces in the Wild.
from sklearn import d... |
a4f8fd53911b00b854fb6a6c20f3826b1325b57d | T-800cs101/Codewars-solutions | /Find the unique number/main.py | 349 | 3.75 | 4 | import collections
def find_uniq(arr):
# your code here
arr_1 = []
result = 0
arr_1 =([item for item, count in collections.Counter(arr).items() if count > 1])
n = set(arr)
for i in arr_1:
if i in n:
n.remove(i)
n = list(n)
n = n[0]
return n # n:... |
6a4f4d6e293a21a53fcac3b73e16480e17c80287 | py1-10-2017/MikeGerrity- | /week1/hospital.py | 1,775 | 3.53125 | 4 | class Patient(object):
PA_COUNT = 0
def __init__(self, name, allergies):
self.name = name
self.alergies = allergies
self.bed_num = None
self.id = Patient.PA_COUNT
Patient.PA_COUNT += 1
class Hospital(object):
def __init__(self, name, cap):
self.name = na... |
d7d24d1e8ea4f520a8f8923627d504b70aba73ec | LetsAdventOfCode/AdventOfCode2019 | /adam/dag 1 py/day1-pt2.py | 334 | 3.75 | 4 | total = 0
with open("input.txt") as file:
for line in file:
next_fuel = int(line)
fuel_total = 0
while True:
next_fuel = next_fuel // 3 - 2
if next_fuel > 0:
fuel_total += next_fuel
else:
break
total += fuel_total... |
6dacc34c6af0880a7a59a67703c0c1e6aec66fda | rdfriedm/math-notes | /electronics/labs/plot_points.py | 386 | 3.828125 | 4 | from matplotlib import pyplot as plt
import math
import pandas as pd
df = pd.read_csv("data.csv")
x = df['x_label']
y = df['y_label']
# plt.xscale("log")
# plt.yscale("log")
plt.plot(x, y) # marker='o' will make dots on the graph, linewidth=0 will not draw a line between the dots
plt.xlabel('The X Axis', fontsize=14... |
629325c65652c095f398ecebd82bce90b02a6dc4 | sreypin/python-3 | /H02/src/salesreport.py | 1,894 | 3.578125 | 4 | '''
CS 132 Homework #2
salesreport.py
@author: Vivan Chung
'''
#TODO You must add your student ID (eg sgilbert) HERE
def student_id():
'''Return your student ID (eg. mine is sgilbert)'''
return 'vchung1'
pass
def open_files()->'(input_file, output_file)':
'''Prompt for input and output file... |
ae2d045b691837d7a45c7b981a89fb2ad5766aed | bluecrayon52/CodingDojo | /python_stack/flask/flask_mysql/login_and_registration/test_regex.py | 347 | 3.765625 | 4 | import re
NAME_REGEX = re.compile(r'^[A-Za-z]{2,50}$')
PASS_REGEX = re.compile(r'^(?=.*[A-Z])(?=.*\d)(.{8,15})$')
name="Albert2"
pswrd = "Password2"
if not NAME_REGEX.match(name):
print("name does not match")
else:
print("name matches")
if not PASS_REGEX.match(pswrd):
print("password does not match")
else:
... |
13e5bc03606ac107892cc1c438ea839256a53003 | bluecrayon52/CodingDojo | /python_stack/python/fundamentals/for_loop_basic_2.py | 4,334 | 4.28125 | 4 | # Biggie Size - Given a list, write a function that changes all positive numbers in the list to "big".
# Example: biggie_size([-1, 3, 5, -5]) returns that same list, but whose values are now [-1, "big", "big", -5]
def biggie_size(lst):
for x in range(0,len(lst),1):
if lst[x] > 0:
lst[x] = 'big'
... |
45b87d8aff8260c6b8b2e0b0fdefbe2cefbebe17 | mate0021/algothink1 | /scratchpad.py | 419 | 3.578125 | 4 | a, b = 0, 1
while b < 20:
# print b
a, b = b, a + b
stack = [2, 3, 4]
stack.append(5)
print stack.pop()
print stack
input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def f1(x): return x*x
def f2(n): return 2 ** n
print "kwadrat: " + str(map(f1, input))
print "2 ^ n: " + str(map(f2, input))
def sum(x, y): return x +... |
ce5b4ac9c403d513e1fc7c945857353ed638bc0f | wgaechter/WG_HW3_Python_Challenge | /PyBank/PyBank.py | 1,267 | 3.703125 | 4 | import os
import csv
import sys
csvpath = os.path.join('Resources', 'budget_data.csv')
with open(csvpath, 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
next(csvreader)
month = []
profit = []
x_list = []
for row in csvreader:
month.append(row[0])
profit.append... |
210bd451a88a4c3f891f93f2e9ca3398935320ee | YigitDemirag/blindstore | /common/utils.py | 504 | 3.59375 | 4 | import math
import numpy as np
def binary(num, size=32):
"""Binary representation of an integer as a list of 0, 1
>>> binary(10, 8)
[0, 0, 0, 0, 1, 0, 1, 0]
:param num:
:param size: size (pads with zeros)
:return: the binary representation of num
"""
ret = np.zeros(size, dtype=np.int... |
4e2cdb91d7f7cd2c66446f3357adb3a7f737410e | kellyseeme/pythonexample | /525/poolthread.py | 124 | 3.609375 | 4 | #!/usr/bin/env python
import multiprocessing
def f(n):
return n*n
p = multiprocessing.Pool(5)
print p.map(f,[1,2,3])
|
31116f0e83ba9681303f5540d51b28e8d7d0c1c3 | kellyseeme/pythonexample | /220/str.py | 228 | 4.3125 | 4 | #!/usr/bin/env python
import string
a = raw_input("enter a string:").strip()
b = raw_input("enter another string:").strip()
a = a.upper()
if a.find(b) == -1:
print "this is not in the string"
else:
print "sucecess"
|
f87d0be2b63ff9c8807e8f2f10cd2ae3d75af0f8 | kellyseeme/pythonexample | /44/iter.py | 787 | 3.84375 | 4 | #!/usr/bin/env python
import itertools
print 'this is the difference of the imap and map'
itre = itertools.imap(pow,[1,2,3],[1,2,3])
print itre
for i in itre:
print i
li = map(pow,[1,2,3],[1,2,3])
print li
print 'this is the difference of ifilter and filter'
ifil = itertools.ifilter(lambda x:x >5 ,range(10))
prin... |
c445a40dbea157dbcdf2f28dfed5fe4b63840653 | kellyseeme/pythonexample | /221/morePrinting.py | 740 | 3.9375 | 4 | #!/usr/bin/env python
#only print a text
print "Mary had a little lamb."
#print a text and format a string using snow,and the snow is not a variable,its just a string
print "its fleece was white as %s." % "snow"
#use the * to print more words
print "." * 10 #print ten of .
#define more values
end1 = "C"
end2 = "h"
end... |
d66a2b7006d3bbcede5387ed1a56df930862bccb | kellyseeme/pythonexample | /221/stringsText.py | 945 | 4.21875 | 4 | #!/usr/bin/env python
"""this is to test the strings and the text
%r is used to debugging
%s,%d is used to display
+ is used to contact two strings
when used strings,there can used single-quotes,double-quotes
if there have a TypeError,there must be some format parameter is not suit
"""
#this is use %d to set the valu... |
5a2b8b97398fce8041886ad4920b5f7acd092ef7 | kellyseeme/pythonexample | /323/stringL.py | 693 | 4.15625 | 4 | #!/usr/bin/env python
#-*coding:utf-8 -*-
#this is use the string method to format the strins
#1.use the ljust is add more space after the string
#2.use the rjust is add more space below the string
#3.use the center is add more space below of after the string
print "|","kel".ljust(20),"|","kel".rjust(20),"|","kel".cen... |
bbb41f0db54a2a443f15cc6855cfa9a2d8a0e3ab | kellyseeme/pythonexample | /323/opString.py | 1,007 | 4.125 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
this file is to concatenate the strings
"""
#this is use join to add the list of string
pieces = ["kel","is","the best"]
print "".join(pieces)
#use for to add string
other = ""
for i in pieces:
other = other + i
print other
#use %s to change the string
print "%s %s... |
21fa0c12f2ffb9e2df26cd191109ba229c6e61d9 | kellyseeme/pythonexample | /221/prpr.py | 512 | 3.96875 | 4 | #!/usr/bin/env python
#this used the three quotes formating the string
#if use the %r it will be dispaly raw string
#if use the %s then it will be diaplay the string formatting
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print "Here are the days: ",days
print "Here are the mo... |
0db7502613ff0c05461e17509d9b8b6abb1be3d2 | kellyseeme/pythonexample | /33/using_list.py | 1,053 | 4.34375 | 4 | #!/usr/bin/env python
"""
this is for test the list function
"""
#this is define the shoplist of a list
shoplist = ["apple","mango","carrot","banana"]
#get the shoplist length,using len(shoplist)
print "Ihave",len(shoplist),"items to pruchase."
#this is iteration of the list,the list is iterable
print "These items ar... |
d60fcacb7ef32add14ef1ffbc1d009baa9eafe42 | prashant2015/My-Python-works | /Word_Count_Function.py | 269 | 3.734375 | 4 | #Word Count #
def word_count(val):
val=val.lower()
dist={}
list1=val.split()
#list1=val.split()
for x in list1:
if x in dist:
dist[x] +=1
else:
dist[x]=1
return dist
|
7dd39bf363186c6d6a700f565215fc14bc8529ca | GeGe-K/pass-locker | /user.py | 3,436 | 3.984375 | 4 | class User:
'''
Class that generates new instances of users.
'''
user_list = [] # empty account user list
# Init method
def __init__(self,username,password):
'''
Initialises the user
'''
self.username = username
self.password = password
def s... |
5e230e3223ccd19c86ee98d6345a80b32c13c489 | karnthiLOL/myFirstPythonHW | /OilPrice1.py | 3,412 | 3.734375 | 4 | # เงื่อนไขทำงาน เมื่อพิมพ์ Restart/หยุดทำงาน เมื่อพิมพ์ Exit
y = 1
while True:
if y == 1:
# แสดงราคา และ ประเภทของน้ำมัน
print("#ประเภทและราคาน้ำมัน \n Gasoline 95 : ราคา 29.16 บาท \n Gasoline 91 : ราคา 25.30 บาท \n Gasohol 91 : ราคา 21.68 บาท \n Gasohol E20 : ราคา 20.2 บาท \n Gasohol 95 : ราคา 21.... |
95f906d93e23c909970ff479b5e8b4ce2ad770fb | karnthiLOL/myFirstPythonHW | /Other/Cafe Calculate Origins.py | 2,669 | 3.765625 | 4 | W = 400
M = 540
B = 120
C = 9
m = 550
y = 1
while True:
if y == 1:
print("The Coffee machine has:")
print((W),"ml of water")
print((M),"ml of milk ")
print((B),"g of coffee beans")
print((C),"of disposable cups ")
print((m),"$ of money")
p = input("choose one option - buy / fill/ take\n... |
30b70dabade98b6ed5f0e8fc7c88ce76828b4796 | anil2211/A_Machine_learning-Price-Prediction-Real_estate | /main.py | 1,047 | 3.5625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import sklearn
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error
diabetes = datasets.load_diabetes()
#print(diabetes.keys())
# dict_keys(['data', 'target', 'frame', 'DESCR', 'feature_names', 'data_filename', 'target_file... |
2a781e4e638370ad3bcaee7623fd85f059f39d30 | clcsar/python-examples | /sort.py | 341 | 3.75 | 4 | L = [4, 6, 3, 1]
def compare(a, b):
return cmp(int(a), int(b)) # compare as integers
L.sort(compare)
print L
L = [[4, 2], [6, 1], [3, 1], [1, 3], [1, 1]]
def compare_columns(a, b):
# sort on ascending index 0, descending index 1
return cmp(a[0], b[0]) or cmp(b[1], a[1])
out = sorted(L, compar... |
dce1bc0115e5e2c9b808ddefab5443eeb29fb921 | clcsar/python-examples | /multiple_constructors.py | 852 | 3.625 | 4 | import random
class Cheese(object):
def __init__(self, num_holes=0):
"defaults to a solid cheese"
self.number_of_holes = num_holes
def __repr__(self):
return str(self.number_of_holes)
@classmethod
def random(cls):
return cls(random.randint(0, 100))
@classmethod
... |
6684dbf7b5a65a5429b02987bd04fb74010a07f3 | clcsar/python-examples | /findall.py | 288 | 3.703125 | 4 | def findall(L, value):
# generator version
i = 0
try:
while 1:
i = L.index(value, i+1)
yield i
except ValueError:
pass
L = [1,2,2,3,3,2]
value = 2
for index in findall(L, value):
print "match at", index
|
cdc32be86a4e2a51b026068515c4238197b4a767 | clcsar/python-examples | /abstractmethod.py | 305 | 3.625 | 4 | from abc import ABCMeta, abstractmethod
class Abstract(object):
__metaclass__ = ABCMeta
@abstractmethod
def foo(self):
pass
#Abstract() #cant instantiate
class B(Abstract):
pass
#B() #cant instantiate
class C(Abstract):
def foo(self):
return 7
print (C()).foo()
|
ccc7acb61650ddc22d6817583c41e7f551aa51b6 | CorinaaaC08/lps_compsci | /class_samples/3-2_logicaloperators/calculatedonuts.py | 287 | 4 | 4 | print('How many people will you have at your party?')
x = int(raw_input())
print('How many donuts will you have at your party?')
y = int(raw_input())
l = y / x
print('Our party has ' + str(x) + ' people ' + str(y) + ' donuts.')
print('Each person will get ' + str(l) + ' donuts.')
|
6687a44474306236be6bd2d140b998267b89c024 | CorinaaaC08/lps_compsci | /class_samples/2-2_nano/2-3_variables/2-4_operators/types.py | 284 | 3.734375 | 4 | myName = 'Mr. Flax'
myAge = 100
isOld = False
print('Here is the type for my Name:')
print(type(myName))
print('Here is the type for myAge:')
print(type(myAge))
print('Here is the type for isOld:')
print(type(isOld))
print('My age is ' + str(myAge))
print('My age is ' + myAge)
|
a2861764344d6b0302e21b4d670addd638b13e38 | CorinaaaC08/lps_compsci | /class_samples/3-2_logicaloperators/college_acceptance.py | 271 | 4.125 | 4 | print('How many miles do you live from Richmond?')
miles = int(raw_input())
print('What is your GPA?')
GPA = float(raw_input())
if GPA > 3.0 and miles > 30:
print('Congrats, welcome to Columbia!')
if GPA <= 3.0 or miles <= 30:
print('Sorry, good luck at Harvard.')
|
71a5430293b81a24e1c1066a08abc3ea25c8e5e5 | YashSaxena75/Python_Data_Science | /5.py | 518 | 3.5625 | 4 | import pandas as pd
df1=pd.DataFrame({'HPI':[80,85,88,85],
'Rate':[2,3,2,2],
'GDP':[50,55,65,55]},
index=[2001,2002,2003,2004])
df2=pd.DataFrame({'HPI':[80,85,88,85],
'Rate':[2,3,2,2],
'GDP':[50,55,65,55]},
index=[2005,2006,2007,2008])
df3=pd.DataFrame({'HPI':[80,85,... |
d43564688a3b210a46b346b96b8ce5f2f6a022a2 | ivansanchezvera/UPSE_Metodos_Numericos | /Integracion/simpson38.py | 1,350 | 3.5 | 4 | #Tomado de: http://rodrigogr.com/blog/metodo-de-integracion-simpson-13/
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Importamos math
from math import *
#Definimos la funcion
#@ n: numero de x
#@ a y b los intervalos de la integral
#@ f: La funcion a integrar
def simpson38(n, a, b, f):
#validamos
if(n%3!=0)... |
b0ff4e5d67d48cb8dc3f9ccc200d9031a17b0402 | jease0502/LLW_SQL_Project | /Python/teacher_id_create/teacher_id.py | 890 | 3.515625 | 4 | import csv
import random
with open('DB_Table_course.csv', newline='',encoding="utf-8") as csvfile:
rows = csv.reader(csvfile)
teacher_name = []
for row in rows:
teacher_name.append(row[8])
teacher_name = set(teacher_name)
def create_teacher_id():
id_head = "T"
id_middle_limit = ["08","07","06","0... |
cfd8488da3913f4ef8147736edb1113fde9779f4 | 15831944/Linux | /study1.py | 300 | 3.75 | 4 | a = [1,5,7,3,2]
b=[]
def Sort():
for i in range(0,len(a)):
b.append(GetMin(a))
a.remove(GetMin(a))
return b
def GetMin(array):
min = array[0]
for i in range(0,len(array)):
if min > a[i]:
min = a[i]
return min
Sort()
print(b) |
7c6a891a68dd84b144a5b47d2e3e30f6dbb3e5a3 | hackonnect/microbit-course | /5_Radio.py | 1,547 | 3.921875 | 4 | from microbit import *
import radio
# First of all, the radio must be turned on in order for the microbit
# to send and receive any messages.
radio.on()
# You can also turn the radio off
radio.off()
# There are ways you can configure the radio. Here are the default settings.
radio.config(length=32, queue=3, chann... |
88748254c446d3511e4c43c0744edac0b332d7ef | ShadySomeone/Lucky_unicorn | /main.py | 2,578 | 3.96875 | 4 | import random
# Functions
def number_check(question):
error = "Please enter a whole number between 1 and 10"
valid = False
while not valid:
try:
response = int(input(question))
if 0 < response <= 10:
return response
else:
print(e... |
1d9dba5c3c23f35a906c2527a8fa557e74460d02 | hasandawood112/python-practice | /Task-5.py | 432 | 4.15625 | 4 | from datetime import date
year1 = int(input("Enter year of date 1 : "))
month1 = int(input("Enter month of date 1 : "))
day1 = int(input("Enter day of date 1 : "))
year2 = int(input("Enter year of date 2 : "))
month2 = int(input("Enter month of date 2 : "))
day2 = int(input("Enter day of date 2 : "))
date1= date(ye... |
89771adbde3636fa5a7407abffbe1b231d177606 | bklooste/epann | /epann/core/environment/animation.py | 998 | 3.703125 | 4 | # """
# =================
# General Purpose Animation
# =================
#
# Creates an animation figure out of a 3D array, animating over axis=2.
# """
import matplotlib.pyplot as plt
import matplotlib.animation as animation
class Animation:
def __init__(self, data):
self.fig = plt.figure()
sel... |
3799495976ee1e5edbf352793a9aff405d8c361b | the-carpnter/codewars_level_6_kata | /integer_with_the_largest_collatz_sequence.py | 154 | 3.703125 | 4 | def collatz(n):
return 1 + collatz(3*n+1 if n%2 else n//2) if n!=1 else 1
def longest_collatz(input_array):
return max(input_array, key=collatz)
|
ad3d8734e9f8213c3eca3d795df1dfee19a8677e | the-carpnter/codewars_level_6_kata | /ideal-electron-distribution.py | 252 | 3.546875 | 4 | def atomic_number(electrons):
k = []
n = 1
while True:
cap = 2*n*n
e = cap if cap <= electrons else electrons
k += [e]
electrons = electrons - e
n += 1
if electrons == 0:
return k
|
37cc51dccfd921a1d5d2b3889ff4bab81acb2240 | the-carpnter/codewars_level_6_kata | /split_odd_and_even.py | 280 | 3.515625 | 4 | def split_odd_and_even(n):
n = list(str(n))
cache = n[0]
k = []
for i, d in enumerate(n[1:], 1):
if int(n[i])%2 == int(n[i-1])%2:
cache += d
else:
k += [cache]
cache = d
k += [cache]
return [*map(int,k)]
|
59593f33b7badbe93e188e3ec9f61ed1c3721f3a | the-carpnter/codewars_level_6_kata | /detect_pangram.py | 117 | 3.6875 | 4 | import string
def is_pangram(s):
return set(i.lower() for i in s if i.isalpha()) == set(string.ascii_lowercase)
|
0393455a2977b0f8d6b7e39b587b4aaf3d0d408e | the-carpnter/codewars_level_6_kata | /backwards_reads_prime.py | 259 | 3.546875 | 4 | from gmpy2 import is_prime
def backwards_prime(start, stop):
k = []
for i in range(start, stop+1):
if is_prime(i):
n = int(str(i)[::-1])
if is_prime(n) and str(i)!=str(i)[::-1]:
k += [i]
return k
|
60562052afeb3e6759848f9b2fe212694ae46eea | the-carpnter/codewars_level_6_kata | /valid_parantheses.py | 250 | 3.734375 | 4 | def valid_parentheses(s, stack = 0, i=0):
if i == len(s):
return stack == 0
if s[i] == '(':
stack += 1
if s[i] == ')':
stack -= 1
if stack < 0:
return False
return valid_parentheses(s, stack, i+1)
|
6b8010cd517c29872f7a0c3d6d100ea9ca3520fb | jamess010/60_Days_RL_Challenge | /Week2/frozenlake_Qlearning.py | 3,465 | 3.578125 | 4 | import gym
import random
from collections import namedtuple
import collections
import numpy as np
import matplotlib.pyplot as plt
def select_eps_greedy_action(table, obs, n_actions):
'''
Select the action using a ε-greedy policy (add a randomness ε for the choice of the action)
'''
value, action = bes... |
8502f638864672b1ed7d46be90760576b85ef656 | arkumar404/Python | /continue.py | 136 | 4.09375 | 4 | for num in range(10):
if num % 2 == 0:
print('Found an even number: ',num)
continue
print('An odd number', num)
|
720feb2ca92f66fa043c6223633e162cde2cac14 | jcanedo279/bootcamp-2020.1 | /week-6/Python/jorgeCanedo.py | 6,040 | 3.53125 | 4 | import math
class Node:
def __init__(self, data):
self.data = data
self.prev = None
self.leftNode, self.rightNode = None, None
def setPrev(self, prevNode):
self.prev = prevNode
def setLeftNode(self, data):
self.leftNode = Node(data)
def setRightNode(self, data):
... |
e0fd6fff8f98a6503c09f25db7f3f2566a33a7d3 | BrachyS/Poverty_food_environment_diabetes | /functions/kmeans_model.py | 1,094 | 3.78125 | 4 | def kmeans_model(PCs, clusters, title):
'''Conduct K-means clustering, make elbow plot,
clustering plot with PC1, PC2,
and return clustering assignment'''
from scipy import cluster
# Use PC1 and PC2 for kmeans clustering, looping through 1 to 6 clusters
df = [cluster.vq.kmeans(PCs[:, 0:2], i) fo... |
bae16ce3264b3eb19226704b11e33c6c2932dfc2 | sedstan/LinkedIn-Learning-Python-Course | /Learning_the_Python_3_Standard_Library/Exercise Files/Ch01/01_07/01_07_Start.py | 715 | 3.65625 | 4 | # Least to Greatest
pointsInAGame = [0, -10, 15, -2, 1, 12]
sortedGame = sorted(pointsInAGame)
print(sortedGame)
# Alphabetically
children = ['Sue', 'Jerry', 'Linda']
print(sorted(children))
print(sorted(['Sue', 'jerry', 'linda']))
# Key Parameters
print(sorted("My favourite child is Linda".split(), key=str.upper))
pri... |
119aa4f88bf7fc356930485636c27f78fce4f481 | codeDroid1/MultiClass-Softmax-Classification | /multilayer_perceptron_(mlp)_for_multi_class_softmax_classification.py | 1,270 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""Multilayer Perceptron (MLP) for multi-class softmax classification.ipynb
# Multilayer Perceptron (MLP) for multi-class softmax classification
"""
import keras
from keras.models import Sequential
from keras.layers import Dense,Dropout,Activation
from keras.optimizers import Adam
#Generate Du... |
8ea72cbb19ffbf6dcb9902b3414f79f7922c9a2a | hamishll/learning-python | /Derek Banas tutorials/Tutorial3_ExceptionHandling.py | 4,887 | 4.25 | 4 | # -----------------------------------------------------------------------------------------
# Forcing a user to enter a number (and not a string or alphabet)
# -----------------------------------------------------------------------------------------
while True:
try:
number = int(input("Please enter a numb... |
e9ceff2b323af0a95553adeae9e9eb01579abe3f | brynelee/automationwithpython | /chapter6/stringProcessingDemo1.py | 678 | 3.71875 | 4 |
#demo of slice of string, in and not in
spam = 'Hello world!'
fizz = spam[0:5]
print(fizz)
print('world' in spam)
print()
# demo of usage center(), ljust(), rjust()
def printPicnic(itemsDict, leftWidth, rightWidth):
print('PICNIC ITEMS'.center(leftWidth + rightWidth, '-'))
for k, v in itemsDict.items():
... |
14bd41b30d479da1e433037b60039feddab30aaa | ferrari8608/tkblackjack | /cards.py | 6,769 | 4.09375 | 4 | """This module holds classes for creating an object oriented deck
of cards and the necessary methods for manipulating them
"""
__all__ = ['PlayingCard', 'CardDeck']
import random
from collections import deque
from players import *
class PlayingCard(object):
"""Contains the attributes of a single playing card and ... |
e39b27aedc66784673d2086364db20860dc06357 | SJTsai/CS408-Python | /Game/Piece.py | 319 | 3.671875 | 4 | class Piece(object):
""" Use 'b' or 'w' for color for the purposes of this project """
def __init__(self, color):
self.color = color
""" Returns 'b' or 'w' for the Piece color """
def getColor():
return self.color
def __repr__(self):
return "Piece color: %s" % self.color
|
06366e956623f3305dbb737d6f91ddcea542daf4 | dataneer/dataquestioprojects | /dqiousbirths.py | 2,146 | 4.125 | 4 | # Guided Project in dataquest.io
# Explore U.S. Births
# Read in the file and split by line
f = open("US_births_1994-2003_CDC_NCHS.csv", "r")
read = f.read()
split_data = read.split("\n")
# Refine reading the file by creating a function instead
def read_csv(file_input):
file = open(file_input, "r")
read = fil... |
86b4639fc49d504b1b026b23bd7d2f2f0b3392ff | natalonso/X-Serv-13.6-Calculadora | /calculadora.py | 888 | 3.703125 | 4 | #!/usr/bin/python3
import sys
if len(sys.argv) != 4:
print("El numero de argumentos introducidos no es correcto")
sys.exit()
operacion = sys.argv[1]
operando1 = sys.argv[2]
operando2 = sys.argv[3]
if operacion == "suma":
print ("La operacion es una suma")
resultado = int(operando1) + int(operando2)
... |
d50f8785fcd85cb567193f397fe9b56f6f5ebf57 | wh2per/Programmers-Algorithm | /Programmers/Lv2/Lv2_프린터.py | 562 | 3.53125 | 4 | def solution(priorities, location):
answer = 0
temp = max(priorities)
while True:
top = priorities.pop(0)
if top == temp: # ?꾨┛??媛??
answer += 1
if location == 0: # 李얠븯??
break
else:
location -= 1
temp = max... |
b28f49afc51a075024df06c06ef2549576051e84 | wh2per/Programmers-Algorithm | /Programmers/Lv2/Lv2_최댓값과최솟값.py | 201 | 3.640625 | 4 | def solution(s):
answer = ""
split_s = s.split()
temp = []
for i in split_s:
temp.append(int(i))
temp.sort()
answer = str(temp[0])+" "+str(temp[-1])
return answer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.