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(remainders):
resulto += num * 2 ** power
print(resulto) |
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
def hasRightChild(self):
return self.rightChild
def isLeftChild(self):
return self.parent and self.parent.leftChild == self
def isRightChild(self):
return self.parent and self.parent.rightChild == self
def isRoot(self):
return not self.parent
def isLeaf(self):
return not (self.rightChild or self.leftChild)
def __str__(self):
return "%s %s" % (self.key, self.payload)
class BinarySearchTree:
def __init__(self):
self.root = None
self.size = 0
def length(self):
return self.size
def __len__(self):
return self.size
def __iter__(self):
return self.root.__iter__()
def put(self,key,val,file):
if self.root:
self._put(key,val,self.root,file)
else:
self.root = TreeNode(key,val,file)
self.size = self.size + 1
def _put(self,key,val,currentNode,file):
if key == currentNode.key:
currentNode.payload+=val
currentNode.file.add(file)
return
if key < currentNode.key:
if currentNode.hasLeftChild():
self._put(key,val,currentNode.leftChild,file)
else:
currentNode.leftChild = TreeNode(key,val,file,parent=currentNode)
else:
if currentNode.hasRightChild():
self._put(key,val,currentNode.rightChild,file)
else:
currentNode.rightChild = TreeNode(key,val,file,parent=currentNode)
def get(self,key):
if self.root:
res = self._get(key,self.root)
if res:
return res
else:
return None
else:
return None
def _get(self,key,currentNode):
if not currentNode:
return None
elif currentNode.key == key:
return currentNode
elif key < currentNode.key:
return self._get(key,currentNode.leftChild)
else:
return self._get(key,currentNode.rightChild)
|
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 correctly
try:
#GPIO imports
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(16, GPIO.IN)
print("GPIO pins setup successfully")
while True:
main()
except KeyboardInterrupt:
print("Exiting gracefully")
# Turn off your GPIOs here
GPIO.cleanup()
#Catch GPIO import error
except RuntimeError:
print("Error importing RPi.GPIO!")
except e:
GPIO.cleanup()
print("Some other error occurred")
print(e.message)
except:
print("Some other error occurred")
|
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 python Flask form with the backend processing done through python. All files associated with the UI are within the templates directory. To run the application locally, the main file can be exported as app.py (export FLASK_APP="app.py" and then invoked through the command: flask run"""
@app.route('/', methods=['GET', 'POST'])
def index():
form = Operations()
output = 0
if form.validate_on_submit():
one = int(request.form['one'])
two = int(request.form['two'])
output = one+two if request.form['button'] == "+" else one-two if request.form['button'] == "-" else one*two if request.form['button'] == "X" else one/two if request.form['button'] == "/" else 0
if request.form['button'] == "Clear":
return redirect(url_for('index'))
return render_template("operations.html", output=output, form=form)
|
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_missing: list, len(n_features)
list containing the number of missing values for every feature
"""
n_instances,n_features = data.shape
n_missing = [0]*n_features
for j in range(n_features):
for i in range(n_instances):
if data[i,j] == '':
n_missing[j] += 1
return n_missing
def test_compute_missingness():
import numpy as np
data = np.empty((4,9),dtype=list)
data[0,0] = ''
data[0,1] = ''
data[1,4] = ''
for i in range(6):
data[3,i] = ''
n_missing = compute_missingness(data)
print n_missing
if __name__ == "__main__":
test_compute_missingness()
|
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():
print("Hello world!")
r = await asyncio.sleep(2)
print("Hello again!")
loop = asyncio.get_event_loop()
tasks = [hello(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close() |
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 in s:
if ch not in seen:
seen[ch] = idx
idx += 1
ret.append(seen[ch])
return ret
if to_num_list(S) == to_num_list(T):
print('Yes')
else:
print('No')
|
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:
ans += up * 2 + down * 1
down += 1
up -= 1
print(ans)
|
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 in enumerate(s):
ch2i[ch] = i
S = input()
arr = [ch2i[ch] for ch in S]
# https://www.geeksforgeeks.org/number-swaps-sort-adjacent-swapping-allowed/
N = len(S)
cnt = 0
for i in range(N - 1):
for j in range(i + 1, N):
cnt += arr[i] > arr[j]
print(cnt)
|
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:
return True
else:
return False
ans = Awin()
if ans:
print("Takahashi")
else:
print("Aoki")
|
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)*(perc/100)
print(result) |
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
def digitSum(n):
sum=0
while n!=0:
r=n%10
sum+=r
n=n//10
return sum
input1 = int(input('First integer: '))
input2 = int(input('Second integer: '))
for i in range((input1+1),input2):
if isPrime(digitSum(decimalToBinary(i))):
print(i)
|
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":
print("NOT VALID INPUT")
if b==0 and a=="rock":
print("Tie")
if b==1 and a=="paper":
print("Tie")
if b==2 and a=="scissor":
print("Tie")
if b==0:
if a == "paper":
print("A wins")
if a == "scissor":
print("B wins")
if b==1:
if a == "paper":
print("A wins")
if a == "scissor":
print("B wins")
if b==2:
if a == "paper":
print("A wins")
if a == "scissor":
print("B wins")
else:
print("Please enter input") |
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=="Paper":
print("Same....Try again")
elif a=="Paper" and b=="Scissor":
print("B wins")
elif a=="Scissor" and b=="Paper":
print("A Wins")
elif a=="Scissor" and b=="Rock":
print("B wins")
elif a=="Scissor" and b=="Scissor":
print("Same Try Again")
else:
print("Invalid Input") |
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
class MLP:
"""This is a class for a two layered neural network"""
def __init__(self, n_input, n_output, n_hidden):
eps = 0.001 # In order to randomly initialize weight with zero mean
self.LR = 0.005 # learning rate
# Initialize weights and biases for all the layers
self.L1_weights = np.random.uniform(low=0-eps, high=0+eps, size=(n_input,n_hidden))
self.L1_biases = np.random.uniform(low=0-eps, high=0+eps, size=(1, n_hidden))
self.L2_weights = np.random.uniform(low=0-eps, high=0+eps, size=(n_hidden,n_output))
self.L2_biases = np.random.uniform(low=0-eps, high=0+eps, size=(1, n_output))
self.SigmoidCE = SigmoidCrossEntropy()
def train(self, x_batch, y_batch):
# --- Forward Propagation of Layer 1--- #
b1 = extrude(np.copy(self.L1_biases), batch_size=16)#--ask yathu abt this#
b2 = extrude(np.copy(self.L2_biases), batch_size=16)
# z = weight*input + bias
z1 = x_batch.dot(self.L1_weights) + b1 #--b is added individually here--#
# Pass z through the activation function a=f(z). This is the output of hidden-layer
a1 = RELU(z1)#----what if use other activation functions--#
# --- Forward Propagation of Layer 2--- #
# z = weight*input + bias
z2 = a1.dot(self.L2_weights) + b2
# Activation for Layer2 will be sigmoid, which is implemented inside SigmoidCrossEntropy function
#ask --why sigmoid in 2nd layer and relu in 1st layer-#
# Now that we have passed it through Layer 1 and 2, we need to generate an output, and calculate loss
# We will do this in the SigmoidCrossEntropy function, just to keep it clean
loss, prediction = self.SigmoidCE.forward(z2, y_batch) #--ask yathu abt actual outputs of P and Loss--#
avg_loss = sum(loss)
# --- Forward Pass is done! Now do backward pass --- #
# Gradient of output (a-y). "d" means derivative
d_output = prediction - y_batch #--what#
d_L2_weights = self.SigmoidCE.backward(d_output, a1)
d_L2_biases = d_output #TODO: fix this??? ask
# Output layer backpropagation done
# Now, do Hidden-layer backpropagation
# TODO: is this called loss for hidden layer?
# As in loss = output_gradient*hidden_layer_weights
loss_hidden = np.dot(d_output, self.L2_weights.T) # RELU backprop
loss_hidden[a1<=0] = 0
d_L1_weights = np.dot(x_batch.T, loss_hidden)
d_L1_biases = loss_hidden
# Update weights and biases
self.L2_weights = self.L2_weights - self.LR*d_L2_weights
self.L2_biases = self.L2_biases - self.LR*np.reshape(np.mean(d_L2_biases, axis=0), (1, len(d_L2_biases[0])))
self.L1_weights = self.L1_weights - self.LR*d_L1_weights
self.L1_biases = self.L1_biases - self.LR*np.reshape(np.mean(d_L1_biases, axis=0), (1, len(d_L1_biases[0])))
return avg_loss
def evaluate(self, x_batch, y_batch):
'''Do the same forward pass as during training
It would have been cleaner to put the forward pass for the training and evaluation
both into a common forward function
'''
# --- Forward Propagation of Layer 1--- #
# z = weight*input + bias
z1 = x_batch.dot(self.L1_weights) + self.L1_biases
# Pass z through the activation function a=f(z). This is the output of hidden-layer
a1 = RELU(z1)
# --- Forward Propagation of Layer 2--- #
# z = weight*input + bias
z2 = a1.dot(self.L2_weights) + self.L2_biases
# Activation for Layer2 will be sigmoid, which is implemented inside SigmoidCrossEntropy function
# Now that we have passed it through Layer 1 and 2, we need to generate an output, and calculate loss
# We will do this in the SigmoidCrossEntropy function, just to keep it clean
loss, prediction = self.SigmoidCE.forward(z2, y_batch)
avg_loss = sum(loss)
diff = prediction - y_batch # if prediction is same as labels diff will be zero
is_correct = (np.abs(diff)) <= 0.49
accuracy = np.mean(is_correct) * 100.0
return accuracy, avg_loss
if __name__=="__main__":
# Load CIFAR data
#data = pkl.load(open('cifar_2class_py2.p', 'rb')) # This was throwing error
with open('cifar_2class_py2.p', 'rb') as f:
u = pkl._Unpickler(f)
u.encoding = 'latin1'
data = u.load()
# Training samples
train_x = data['train_data']
train_y = data['train_labels']
# Tesing samplies
test_x = data['test_data']
test_y = data['test_labels']
# Get dimensions
num_examples, INPUT_DIMS = train_x.shape
_, OUTPUT_DIMS = train_y.shape
# PARAMETERS
NUM_EPOCHS = 50
NUM_BATCHES = 16
HIDDEN_UNITS = 32
LEARNING_RATE = 0.005
# --- Start training --- #
# Instantiate neural network (multi-layer perceptron)
neural_network = MLP(INPUT_DIMS, OUTPUT_DIMS, HIDDEN_UNITS)
neural_network.LR = LEARNING_RATE
# Tracking
loss_per_epoch = []
train_accuracy_per_epoch = []
test_accuracy_per_epoch = []
for epoch in range(NUM_EPOCHS):
total_loss = 0.0
# Create batches of data
for batch in iterate_minibatches(train_x, train_y, NUM_BATCHES, shuffle=True):
avg_loss =0.0
x_batch,y_batch = batch
x_batch = x_batch/255.0
avg_loss = neural_network.train(x_batch,y_batch)
# Update total loss for epoch
total_loss = total_loss + avg_loss
#print("Epoch ="+str(epoch)+" Epoch batch Loss="+str(total_loss))
loss_per_epoch.append(total_loss)
# Now, calculate train accuracy for the whole dataset
train_accuracy, train_loss = neural_network.evaluate(train_x, train_y)
train_accuracy_per_epoch.append(train_accuracy)
#print("Train accuracy="+str(train_accuracy)+" Train loss="+str(train_loss))
#
# Now, calculate test accuracy for the whole dataset
test_accuracy, test_loss = neural_network.evaluate(test_x, test_y)
test_accuracy_per_epoch.append(test_accuracy)
print("Epoch ="+str(epoch)+" Epoch batch Loss="+str(round(total_loss[0],2)) +
" Train accuracy="+str(round(train_accuracy,2))+" Train loss="+str(round(train_loss[0],2)) +
" Test accuracy="+str(round(test_accuracy,2)) + " Test loss=" + str(round(test_loss[0],2)))
#print("\n")
# plotting after all epochs are done
plt.plot(loss_per_epoch)
plt.title('Average Loss (' + "Ep:" + str(NUM_EPOCHS) + " Batches: "+str(NUM_BATCHES)+" H-units:"+str(HIDDEN_UNITS)+" LR:"+str(LEARNING_RATE))
plt.xlabel('Epoch')
plt.ylabel('Average Loss')
plt.show()
plt.plot(train_accuracy_per_epoch)
plt.title('Training Accuracy (' + "Ep:" + str(NUM_EPOCHS) + " Batches: "+str(NUM_BATCHES)+" H-units:"+str(HIDDEN_UNITS)+" LR:"+str(LEARNING_RATE))
plt.xlabel('Epoch')
plt.ylabel('Training Accuracy')
plt.show()
plt.plot(test_accuracy_per_epoch)
plt.title('Test Accuracy (' + "Ep:" + str(NUM_EPOCHS) + " Batches: " + str(NUM_BATCHES) + " H-units:" + str(
HIDDEN_UNITS) + " LR:" + str(LEARNING_RATE))
plt.xlabel('Epoch')
plt.ylabel('Testing Accuracy')
plt.show()
print("Finished Plotting")
|
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 working with is a sample of 50,000 data points that was prepared by Dataquest including simulating a less-cleaned version of the data.
#
# The data dictionary provided with data is as follows:
#
# - dateCrawled - When this ad was first crawled. All field-values are taken from this date.
# - name - Name of the car.
# - seller - Whether the seller is private or a dealer.
# - offerType - The type of listing
# - price - The price on the ad to sell the car.
# - abtest - Whether the listing is included in an A/B test.
# - vehicleType - The vehicle Type.
# - yearOfRegistration - The year in which year the car was -first registered.
# - gearbox - The transmission type.
# - powerPS - The power of the car in PS.
# - model - The car model name.
# - kilometer - How many kilometers the car has driven.
# - monthOfRegistration - The month in which year the car was first registered.
# - fuelType - What type of fuel the car uses.
# - brand - The brand of the car.
# - notRepairedDamage - If the car has a damage which is not yet repaired.
# - dateCreated - The date on which the eBay listing was created.
# - nrOfPictures - The number of pictures in the ad.
# - postalCode - The postal code for the location of the vehicle.
# - lastSeenOnline - When the crawler saw this ad last online.
#
# The aim of this project is to clean the data and analyze the included used car listings.
# In[1]:
import pandas as pd
import numpy as np
# In[2]:
autos = pd.read_csv('autos.csv',encoding='Latin-1')
# In[3]:
autos.head()
# In[4]:
autos.info()
#
# Our dataset contains 20 columns, most of which are stored as strings. There are a few columns with null values, but no columns have more than ~20% null values. There are some columns that contain dates stored as strings.
#
# We'll start by cleaning the column names to make the data easier to work with.
# ## Clean Columns
# In[5]:
autos.columns
#
# We'll make a few changes here:
#
# - Change the columns from camelcase to snakecase.
# - Change a few wordings to more accurately describe the columns.
# In[6]:
autos.columns = ['date_crawled', 'name', 'seller', 'offer_type', 'price', 'ab_test',
'vehicle_type', 'registration_year', 'gearbox', 'power_ps', 'model',
'odometer', 'registration_month', 'fuel_type', 'brand',
'unrepaired_damage', 'ad_created', 'num_photos', 'postal_code',
'last_seen']
autos.head()
# ## Initial Data Exploration and Cleaning
# In[7]:
autos.describe(include='all')
#
# Our initial observations:
#
# There are a number of text columns where all (or nearly all) of the values are the same:
# - **seller**
# - **offer_type**
#
# The **num_photos** column looks odd, we'll need to investigate this further contain **0** value for all rows
#
# so, will drop this columns
# In[8]:
autos.drop(['seller','offer_type','num_photos'],axis=1,inplace=True)
# and convert **price** and **odometer** columns to numeric values
# In[9]:
autos['price'] = autos['price'].str.replace('$','').str.replace(',','')
autos['odometer'] = autos['odometer'].str.replace('km','').str.replace(',','')
autos['price'] = autos['price'].astype(int)
autos['odometer'] = autos['odometer'].astype(int)
# In[10]:
autos[['price','odometer']].head()
# convert **odometer** to **odometer_km** to illustrate it
# In[11]:
autos.rename({'odometer':'odometer_km'},axis = 1 , inplace=True)
# In[12]:
autos[['price','odometer_km']].head()
# ## Exploring Odometer and Price
# In[13]:
print(autos['price'].unique().shape)
print(autos['price'].describe())
# In[14]:
print(autos['price'].value_counts().sort_index(ascending=False).head(25))
# In[15]:
print(autos['price'].value_counts().sort_index(ascending=True).head(25))
# Given that eBay is an auction site, there could legitimately be items where the opening bid is \$1. We will keep the \$1 items, but remove anything above \$350,000, since it seems that prices increase steadily to that number and then jump up to less realistic numbers.
# In[16]:
autos = autos[autos['price'].between(1,351000)]
autos['price'].describe()
# In[17]:
print(autos['odometer_km'].unique().shape)
print(autos['odometer_km'].shape)
# In[18]:
print(autos['odometer_km'].describe())
# ## Exploring the date columns
#
# There are a number of columns with date information:
#
# - date_crawled
# - registration_month
# - registration_year
# - ad_created
# - last_seen
#
# These are a combination of dates that were crawled, and dates with meta-information from the crawler. The non-registration dates are stored as strings.
#
# We'll explore each of these columns to learn more about the listings.
# In[19]:
autos[['date_crawled','ad_created','last_seen']][:5]
# In[27]:
autos['date_crawled'].str[:10].value_counts(normalize=True,dropna=False).sort_index()
# In[32]:
(autos['date_crawled']
.str[:10]
.value_counts(normalize=True,dropna=False)
.sort_values())
# Looks like the site was crawled daily over roughly a one month period in March and April 2016. The distribution of listings crawled on each day is roughly uniform.
# In[31]:
(autos["last_seen"].str[:10]
.value_counts(normalize=True, dropna=False)
.sort_index())
# The last three days contain a disproportionate amount of 'last seen' values. Given that these are 6-10x the values from the previous days, it's unlikely that there was a massive spike in sales, and more likely that these values are to do with the crawling period ending and don't indicate car sales
# In[33]:
(autos["ad_created"]
.str[:10]
.value_counts(normalize=True, dropna=False)
.sort_index()
)
# There is a large variety of ad created dates. Most fall within 1-2 months of the listing date, but a few are quite old, with the oldest at around 9 months.
# In[35]:
print(autos["registration_year"].head())
autos["registration_year"].describe()
#
# The year that the car was first registered will likely indicate the age of the car. Looking at this column, we note some odd values. The minimum value is 1000, long before cars were invented and the maximum is 9999, many years into the future.
# ## Dealing with Incorrect Registration Year Data
# One thing that stands out from the exploration we did in the last screen is that the registration_year column contains some odd values:
#
# - The minimum value is 1000, before cars were invented
# - The maximum value is 9999, many years into the future
#
# Because a car can't be first registered after the listing was seen, any vehicle with a registration year above 2016 is definitely inaccurate. Determining the earliest valid year is more difficult. Realistically, it could be somewhere in the first few decades of the 1900s.
# In[48]:
((~autos['registration_year'].between(1900,2016))
.sum()/autos.shape[0]*100)
# Given that this is less than 4% of our data, we will remove these rows.
# In[49]:
autos = autos[autos["registration_year"].between(1900,2016)]
autos["registration_year"].value_counts(normalize=True).head(10)
# ## Exploring price by brand
# In[54]:
freq_brands = autos['brand'].value_counts().sort_values(ascending = False).head(20)
freq_brands
# German manufacturers represent four out of the top five brands, almost 50% of the overall listings. Volkswagen is by far the most popular brand, with approximately double the cars for sale of the next two brands combined.
# In[57]:
common_brands = freq_brands[:5].index
common_brands
# In[58]:
brand_mean_price = {}
for brand in common_brands:
brand_only = autos[autos['brand'] == brand]
mean_price = brand_only['price'].mean()
brand_mean_price[brand] = mean_price
brand_mean_price
# ## Exploring Mileage
# In[60]:
bmp_series = pd.Series(brand_mean_price)
pd.DataFrame(bmp_series, columns=["mean_price"])
# In[65]:
brand_mean_mileage = {}
for brand in common_brands:
brand_only = autos[autos["brand"] == brand]
mean_mileage = brand_only["odometer_km"].mean()
brand_mean_mileage[brand] = mean_mileage
mean_mileage = pd.Series(brand_mean_mileage).sort_values(ascending=False)
mean_prices = pd.Series(brand_mean_price).sort_values(ascending=False)
# In[66]:
brand_info = pd.DataFrame(mean_mileage,columns=['mean_mileage'])
brand_info
# In[67]:
brand_info["mean_price"] = mean_prices
brand_info
# The range of car mileages does not vary as much as the prices do by brand, instead all falling within 10% for the top brands. There is a slight trend to the more expensive vehicles having higher mileage, with the less expensive vehicles having lower mileage.
# In[ ]:
|
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 choosenode(vertices, alpha=0, nbofnodes=1):
# choose nbofnodes nodes based on BA preferential attachment with alpha as initial attractiveness
# a node with higher indegree is more likely to be chosen than nodes with lower indegree
pdb.set_trace()
nver = len(vertices)
totdegalpha = gettotdegree(vertices) + nver * alpha
lsidx = range(nver)
prevr = totdegalpha + 1 # large enough value
nodes = []
for i in range(nbofnodes):
pdb.set_trace()
# generate a random number between 1 to totdegalpha
r = random.randint(1, totdegalpha)
print "r: "+ str(r)
if r < prevr:
# search from the beginning of lsidx
j = 0
sumdegree = 0
stop = False
while j < len(lsidx) and not stop:
idx = lsidx[j]
degalpha = vertices[idx] + alpha
sumdegree += degalpha
if sumdegree >= r:
# stop the loop
stop = True
# add the index to the solution list
nodes.append(idx)
# remove the index from lsidx to prevent it to be chosen again
lsidx.pop(j)
# "remove" its degree
totdegalpha -= degalpha
sumdegree -= degalpha
# record the current random number for later comparison
prevr = r
else:
j += 1
return nodes
def __test(argv):
vertices = initvertices(10, 20)
print vertices
totdegree = gettotdegree(vertices)
print totdegree
nodes = choosenode(vertices, 0, 20)
print nodes
if __name__ == '__main__':
sys.exit(__test(sys.argv))
|
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 - enter 2")
spam_type = int(input('Enter your choice: '))
return spam_type
# to get the speed of how fast it should spam
# in simple words, it returns the time after
# which the next spam message has to be sent
def get_spam_speed():
print()
print("=== SPAM SPEED speed (seconds) ===")
print("Super fast = Enter 0")
print("Medium speed = Enter 0.7")
print("Or set your custom speed: ")
print()
spam_speed = float(input("Enter your speed: "))
return spam_speed
def get_timeout_and_timeout():
timeout = float(input("Enter the time you need to open the app and focus the cursor on:"))
print("HURRY UP AND PLACE YOUR CURSOR WITHIN", timeout, "SECONDS!!")
sleep(timeout)
def get_spam_text():
text = input("Enter what you want to spam: ")
return text
def spam_text(spam_speed, num_of_times, text):
print("Spamming...")
i = 0
while i < num_of_times:
pyautogui.typewrite(text)
pyautogui.press("enter")
sleep(float(spam_speed))
i += 1
def quit():
print("BEAN the bot quits...")
sys.exit()
def main():
welcome()
spam_type = get_spam_type()
spam_speed = get_spam_speed()
if spam_type == 1:
def get_num_of_times():
# word or sentence entered by user
num_of_times = float(input("Enter number of times to spam: "))
return num_of_times
text = get_spam_text()
num_of_times = get_num_of_times()
get_timeout_and_timeout()
spam_text(spam_speed, num_of_times, text)
quit()
elif spam_type == 2: # to spam from a text file
def spam_from_file(spam_speed):
file_name = str(
input("Enter the name of the file (eg. spam_text.txt): "))
print("NOTE: Text file has to be in same folder/directory")
print("NOTE: Currently only text files are supported!")
get_timeout_and_timeout()
try:
text_file = open(file_name, "r")
for line in text_file:
pyautogui.typewrite(line)
pyautogui.press("enter")
sleep(spam_speed)
except:
print("File not found or file name incorrect")
quit()
spam_from_file(spam_speed)
else:
quit()
# calling the main function
try:
main()
except:
print("Invalid Input/Something went wrong. Please try again!")
quit()
|
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
x[i], x[min_idx] = x[min_idx], x[i]
|
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(form1)
two += 1
return store[n]
print (dbl_linear(50)) |
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
mins = 0
days = 0
years = 0
while seconds >= 31536000:
years += 1
seconds -= 31536000
while seconds >= 86400:
days += 1
seconds -= 86400
while seconds >= 3600:
hour += 1
seconds -= 3600
while seconds >= 60:
mins += 1
seconds -= 60
if years:
ans += str(years) + " year" + format(years, days, hour, mins, seconds)
if days:
ans += str(days) + " day" + format(days, hour, mins, seconds, 0)
if hour:
ans += str(hour) + " hour" + format(hour, mins, seconds, 0, 0)
if mins:
ans += str(mins) + " minute" + format(mins, seconds, 0, 0, 0)
if seconds:
ans += str(seconds) + " second" + format(seconds, 0, 0, 0, 0)
if ans:
return ans
return "now"
print (format_duration(3662)) |
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(summ)):
summ[x][0] = str(summ[x][0])
summ[x][1] = str(summ[x][1])
for y in range(len(summ)):
for x in range(len(summ)-y-1):
if x < len(summ)-1:
if summ[x][0] == summ[x+1][0]:
if summ[x][1] > summ[x+1][1]:
summ[x][1], summ[x+1][1] = summ[x+1][1], summ[x][1]
for x in range(len(summ)):
if x < len(summ)-1:
result += summ[x][1] + " "
else:
result += summ[x][1]
return result
print (order_weight('1 2 200 4 4 6 6 7 7 18 27 72 81 9 91 425 31064 7920 67407 96488 34608557 71899703'))
|
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 = True
elif string_list[x] == "(" and string_list[x+num] == ")":
ident = True
else:
ident = False
break
if string_list.index("(") > string_list.index(")"):
ident = False
break
if "[" == string_list[x]:
if string_list[x] == "[" and reverse_list[x] == "]":
ident = True
elif string_list[x] == "[" and string_list[x+num] == "]":
ident = True
else:
ident = False
break
if string_list.index("[") > string_list.index("]"):
ident = False
break
if "{" == string_list[x]:
if string_list[x] == "{" and reverse_list[x] == "}":
ident = True
elif string_list[x] == "{" and string_list[x+num] == "}":
ident = True
else:
ident = False
break
if string_list.index("{") > string_list.index("}"):
ident = False
break
if x == len(string_list)-1:
num = 0
return 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 to your password")
elif keyword != re.search("\w", keyword):
print("invalid! add numbers to your password.")
else:
print("good password congratulations!")
else:
print("password not supported too short. ")
password_test()
|
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 datasets
faces = datasets.fetch_olivetti_faces()
faces.data.shape
# Visualize these faces.
from matplotlib import pyplot as plt
fig = plt.figure(figsize=(8, 6))
# plot several images
for i in range(15):
ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[])
ax.imshow(faces.images[i], cmap=plt.cm.bone)
plt.show()
# Localization and scaling to a common size.
# A typical train-test split on the images.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(faces.data,
faces.target, random_state=0)
print(X_train.shape, X_test.shape)
# Use PCA to reduce these 1850 features to a manageable size
# while maintaining most of the information in the dataset.
from sklearn import decomposition
pca = decomposition.PCA(n_components=150, whiten=True)
pca.fit(X_train)
# Visualizing the PCA outcome. The "mean" image/data.
plt.imshow(pca.mean_.reshape(faces.images[0].shape),
cmap=plt.cm.bone)
plt.show()
print(pca.components_.shape)
# Visualizing multiple PCA outcomes.
fig = plt.figure(figsize=(16, 6))
for i in range(30):
ax = fig.add_subplot(3, 10, i + 1, xticks=[], yticks=[])
ax.imshow(pca.components_[i].reshape(faces.images[0].shape),
cmap=plt.cm.bone)
plt.show()
# The components (“eigenfaces”) are ordered by their importance
# from top-left to bottom-right.
# The components (“eigenfaces”) are ordered by their importance
# from top-left to bottom-right. We see that the first few
# components seem to primarily take care of lighting conditions;
# the remaining components pull out certain identifying
# features: the nose, eyes, eyebrows, etc.
# Project our original training and test data onto the PCA basis:
X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)
print(X_train_pca.shape)
print(X_test_pca.shape)
# Perform support-vector-machine classification on this reduced dataset.
from sklearn import svm
clf = svm.SVC(C=5., gamma=0.001)
clf.fit(X_train_pca, y_train)
# Evaluate the classification performance.
# Plot a few of the test-cases with the labels learned from the training set.
import numpy as np
fig = plt.figure(figsize=(8, 6))
for i in range(15):
ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[])
ax.imshow(X_test[i].reshape(faces.images[0].shape),
cmap=plt.cm.bone)
y_pred = clf.predict(X_test_pca[i, np.newaxis])[0]
color = ('black' if y_pred == y_test[i] else 'red')
ax.set_title(y_pred, fontsize='small', color=color)
plt.show()
# Performance Evaluation
# sklearn.metrics: Do the classification report.
# The precision, recall, and other measures of
# the “goodness” of the classification
# The confusion matrix: Indicates how often any
# two items are mixed-up.
# The confusion matrix of a perfect classifier would
# only have nonzero entries on the diagonal, with
# zeros on the off-diagonal.
from sklearn import metrics
y_pred = clf.predict(X_test_pca)
print(metrics.classification_report(y_test, y_pred))
print(metrics.confusion_matrix(y_test, y_pred)) |
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: unique integer in the array
|
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 = name
self.cap = cap
self.patients = []
self.beds = self.bed_count()
def bed_count(self):
beds = []
for i in range(0, self.cap):
beds.append({
"bed_id": i,
"Available": True
})
return beds
def admit(self, patient):
if len(self.patients) <= self.cap:
self.patients.append(patient)
for i in range(0, len(self.beds)):
if self.beds[i]["Available"]:
patient.bed_num = self.beds[i]["bed_id"]
self.beds[i]["Available"] = False
break
print "Patient #{} admitted to bed #{}".format(patient.id, patient.bed_num)
else:
print "Hospital is full"
def discharge(self, patientid):
for patient in self.patients:
if patient.id == patientid:
for bed in self.beds:
if bed["bed_id"] == patient.bed_num:
bed["Available"] = True
break
self.patients.remove(patient)
print "Patient #{} sucessfully discharged. Bed #{} now available".format(patient.id, patient.bed_num)
h1 = Hospital("Upper Chesapeak", 20)
pa1 = Patient("Bill", "Peanut")
pa2 = Patient("Brad", "eggs")
pa3 = Patient("Wendy", "lactose")
h1.bed_count()
h1.admit(pa1)
h1.admit(pa2)
h1.admit(pa3)
h1.discharge(0)
|
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
print(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)
plt.ylabel('The Y Axis', fontsize=14)
plt.grid(True)
plt.show()
|
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 filenames
Opens both files if possible and returns them in a tuple
@return tupe of (input_file, output_file) or
None in place of files that cannot be opened
'''
inputFile = input('Please enter the input file: ')
outputFile = input('Please enter the output file: ')
try:
fin = open(inputFile, 'r')
except FileNotFoundError:
fin = 'None'
try:
fout = open(outputFile, 'w')
except FileNotFoundError:
fout = 'None'
return (fin, fout)
def process_files(files: 'tuple(open_file_for_reading, open_file_for_writing)'):
'''Produces sales report from input file.
Closes both files when done
'''
if(files[0] != 'None' and files[1] != 'None'):
fin = files[0]
fout = files[1]
fout.write('ICE CREAM SALES REPORT \n')
fout.write ('Flavor Store 1 Store 2 Store 3 Total')
fout.write('-' * 30)
for line in fin:
tokens = line.split()
favor = tokens[0]
store1 = tokens[1]
store2 = tokens[2]
store3 = tokens[3]
total = tokens[4]
fout.write('{} {} {} {} {}'.format(favor, store1, store2, store3, total))
fin.close();
fout.close();
else:
print('The files do not exist')
return
if __name__ == '__main__':
files = open_files(); # prompt and open
if (files[0] != None and files[1] != None):
process_files(files)
|
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:
print("password matches") |
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'
return lst
testList = [-1, 3, 5, -5]
testList2 = biggie_size(testList) # pass by reference
print(testList)
print(testList2) # pointing to the same list
testList2[0] = "changed"
print(testList)
def biggie_size_copy(lst):
cpy = lst.copy() # make a copy of the list
for x in range(0,len(cpy),1):
if cpy[x] > 0:
cpy[x] = 'big'
return cpy
testList3 = [-1, 3, 5, -5]
testList4 = biggie_size_copy(testList3) # pass by reference, but copied
print(testList3) # unchanged
print(testList4)
# Count Positives - Given a list of numbers, create a function to replace the last value with the number of positive
# values. (Note that zero is not considered to be a positive number).
# Example: count_positives([-1,1,1,1]) changes the original list to [-1,1,1,3] and returns it
# Example: count_positives([1,6,-4,-2,-7,-2]) changes the list to [1,6,-4,-2,-7,2] and returns it
def count_positives(lst):
pos = 0
for x in range(0, len(lst), 1):
if lst[x] > 0:
pos+=1
lst[len(lst) - 1] = pos
return lst
print(count_positives([-1,1,1,1]))
print(count_positives([1,6,-4,-2,-7,-2]))
# Sum Total - Create a function that takes a list and returns the sum of all the values in the array.
# Example: sum_total([1,2,3,4]) should return 10
# Example: sum_total([6,3,-2]) should return 7
def sum_total(lst):
sum = 0
for x in range(0, len(lst), 1):
sum+=lst[x]
return sum
print(sum_total([1,2,3,4]))
print(sum_total([6,3,-2]))
# Average - Create a function that takes a list and returns the average of all the values.
# Example: average([1,2,3,4]) should return 2.5
def average(lst):
return sum_total(lst)/len(lst)
print(average([1,2,3,4]))
# Length - Create a function that takes a list and returns the length of the list.
# Example: length([37,2,1,-9]) should return 4
# Example: length([]) should return 0
def length(lst):
return len(lst)
print(length([37,2,1,-9]))
print(length([]))
# Minimum - Create a function that takes a list of numbers and returns the minimum value in the list.
# If the list is empty, have the function return False.
# Example: minimum([37,2,1,-9]) should return -9
# Example: minimum([]) should return False
def minimum(lst):
if(len(lst) == 0):
return False
min = lst[0]
for x in range(1, len(lst), 1):
if lst[x] < min:
min = lst[x]
return min
print(minimum([37,2,1,-9]))
print(minimum([]))
# Maximum - Create a function that takes a list and returns the maximum value in the array.
# If the list is empty, have the function return False.
# Example: maximum([37,2,1,-9]) should return 37
# Example: maximum([]) should return False
def maximum(lst):
if(len(lst) == 0):
return False
max = lst[0]
for x in range(1, len(lst), 1):
if lst[x] > max:
max = lst[x]
return max
print(maximum([37,2,1,-9]))
print(maximum([]))
# Ultimate Analysis - Create a function that takes a list and returns a dictionary that has the sumTotal,
# average, minimum, maximum and length of the list.
# Example: ultimate_analysis([37,2,1,-9]) should return {'sumTotal': 31, 'average': 7.75, 'minimum': -9, 'maximum': 37, 'length': 4 }
def ultimate_analysis(lst):
return {
'sumTotal': sum_total(lst),
'average': average(lst),
'minimum': minimum(lst),
'maximum': maximum(lst),
'length': length(lst)
}
print(ultimate_analysis([37,2,1,-9]))
# Reverse List - Create a function that takes a list and return that list with values reversed.
# Do this without creating a second list. (This challenge is known to appear during basic technical interviews.)
# Example: reverse_list([37,2,1,-9]) should return [-9,1,2,37]
def reverse_list(lst):
stop = len(lst) // 2
for x in range(0, stop, 1):
temp = lst[x]
lst[x] = lst[len(lst) - (1 + x)]
lst[len(lst) - (1 + x)] = temp
return lst
print(reverse_list([37,2,3,1,-9]))
print(reverse_list([37,2,1,-9]))
|
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 + y
print reduce(sum, input)
print [(x, y) for x in range(1, 40) for y in range(1, 40) if y == 2*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(float(row[1]))
row_total = len(month)
total = sum(profit)
#Big shoutout to Rama for the help with this!
for i in range(1, len(profit)):
x_list.append(profit[i] - profit[i-1])
x_avg = sum(x_list) / len(x_list)
max_profit = max(x_list)
min_profit = min(x_list)
max_date = str(month[x_list.index(max(x_list)) + 1])
min_date = str(month[x_list.index(min(x_list)) + 1])
def Analysis():
print("")
print("Financial Analysis")
print("-----------------------------------")
print(f"Total Months: {row_total}")
print(f"Total Profit: ${total}")
print(f"Average Change: ${x_avg}")
print(f"Greatest Increase in Profit: {max_date} (${max_profit})")
print(f"Greatest Decrease in Profits: {min_date} (${min_profit})")
Analysis()
#TXT OUTPUT
output_path = os.path.join('Analysis', 'Financial_Analysis.txt')
with open(output_path, 'a') as f:
sys.stdout = f
Analysis()
|
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)
n = np.array([int(x) for x in list(bin(num)[2:])])
ret[ret.size - n.size:] = n
return ret
def index_length(record_count):
return math.ceil(math.log2(record_count))
|
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))
print ifil
for i in ifil:
print i
ifilfalse = itertools.ifilterfalse(lambda x:x>5,range(10))
print ifilfalse
for i in ifilfalse:
print i
li = filter(lambda x:x>5,range(10))
print li
print 'this is the other function of itertools'
take = itertools.takewhile(lambda x:x>5,[6,2,6,7,3])
for i in take:
print 'this is the takewhile function ',i
drop = itertools.dropwhile(lambda x:x>5,[1,2,6,7,3])
for i in drop:
print 'this is the dropwhile function ',i
|
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"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
#contac the words ,if there a comma,there is two lines to a sigle-line
#remember there one line is less than 80 characters
#if not comma,then there will be two lines
#print end1 + end2 + end3 + end4 + end5 + end6,
print end1 + end2 + end3 + end4 + end5 + end6
print end7 + end8 + end9 + end10 + end11 + end12
|
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 values
x = "there are %d typs of people." % 10
binary = "binary"
do_not = "don't"
#this is use two variables to strings and use %s
y= "those who know %s and those who %s." % (binary,do_not)
print x
print y
#use %r to set x ,%s is the string,and the %r is use the repe() function
print "I said: %r." % x
#this is use %s to se value y
print "I also said:%s'." % y
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
#this is use hilarious to set the string of %r
print joke_evaluation % hilarious
w = "this is the left side of ..."
e = "a string with a right side."
#use + to concate the two strings
print w + e
|
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".center(20),"|"
#the string center have more args is the width and the space or other arguments
print "|","kel".center(20,"*"),"|"
print "|","kel".ljust(20,"*"),"|"
print "|","kel".rjust(20,"*"),"|"
"""
用来整理字符串的格式,主要使用的方法为ljust,rjust和center,默认情况下使用空格
第二个参数用来表示用什么字符进行填充
"""
|
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 %s"% (pieces[0],pieces[1],pieces[2])
print "kel" + "is" + "the best"
#use function to use the string
import operator
print reduce(operator.add,pieces,"")
"""
在进行拼接字符串的时候,有很多方法,但是都会产生中间变量
最好的方法是使用join方法,在使用join方法的时候,首先构建列表list,然后使用"".join(list)即可,性能最佳
其次的方法是使用%s进行替换,从而在有的是数字的时候,也不需要用str进行字符串的转换
reduce方法用来对sequence的pieces的进行add操作,初始化的值为空,最后返回一个值,对序列中值
进行从左到右的function的operator。add操作
"""
|
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 months: ",months
print " %r " % months
print """
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want,or 5,or 6.
"""
|
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 are:",
for item in shoplist:
#there have a comma at the end of the line,it's mean is ride of the newline
print item,
print "\nIalso have to buy rice."
#this is append the function,add a shopinglinst a rice,using append
#append is the last the argument
shoplist.append("rice")
print "My shopping list is now",shoplist
print "I will sort my list now"
#list is a changeable,so this is sort,and the list is changed
shoplist.sort()
print "Sorted shoping list is ",shoplist
print "The first item I will buy is ",shoplist[0]
#this is get the list of value,use the index and then get the value
olditem = shoplist[0]
#this is delete some of the list
del shoplist[0]
print "I bouthe the",olditem
print "My shopping list is now",shoplist
|
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 save_user(self):
'''
save_user method saves user objects into user_list
'''
User.user_list.append(self)
def delete_user(self):
'''
delete_user method deletes a saved user from the user_list
'''
User.user_list.remove(self)
@classmethod
def find_by_username(cls,username):
'''
Method that takes in a username and returns a user that matches that username.
Args:
username: Username to search for
Returns :
Username of person that matches the name.
'''
for user in cls.user_list:
if user.username == username:
return user
@classmethod
def user_exist(cls,name):
'''
Method that checks if a user exists from the user list.
Args:
username: Username to search if it exists
Returns :
Boolean: True or false depending if the user exists
'''
for user in cls.user_list:
if user.username == name:
return True
return False
@classmethod
def display_user(cls):
'''
method that returns the user list
'''
return cls.user_list
class Credentials:
'''
Class that generates new instances of the user's credentials
'''
credentials_list = [] # Empty credentials list
# Init method
def __init__(self,account,username,password):
'''
Initialises the user's credentials
'''
self.account = account
self.username = username
self.password = password
def save_credentials(self):
'''
save_credentials method saves credentials objects into credentials_list
'''
Credentials.credentials_list.append(self)
def delete_credentials(self):
'''
delete_credentials method deletes a saved credentials from the credentials_list
'''
Credentials.credentials_list.remove(self)
@classmethod
def find_by_account(cls,account):
'''
Method that takes in an account and returns credentials that matches that account.
Args:
account: account to search for
Returns :
credentials of person that matches the account.
'''
for credentials in cls.credentials_list:
if credentials.account == account:
return credentials
@classmethod
def credentials_exist(cls,account):
'''
Method that checks if a credential exists from the credentials list.
Args:
account: account to search if it exists
Returns :
Boolean: True or false depending if the user exists
'''
for credentials in cls.credentials_list:
if credentials.account == account:
return True
return False
@classmethod
def display_credentials(cls):
'''
method that returns the credentials list
'''
return cls.credentials_list
|
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.2 บาท \n Diesel : ราคา 21.1 บาท")
# กรอกประเภทน้ำมัน
A = str(input("*โปรดเลือกประเภทน้ำน้ำมัน \n 1. Gasoline 95 \n 2. Gasoline 91 \n 3. Gasohol 91 \n 4. Gasohol E20 \n 5. Gasohol 95 \n 6. Diesle \n ระบุตัวเลย(ลำดับ):"))
# กรอกคำสั่ง เปลี่ยนลิตรเป็นเงิน/เปลี่ยนเงินเป็นลิตร
B = str(
input("*คำนวณ \n 1.จำนวนลิตรเป็นเงิน \n 2.จำนวนเงินเป็นลิตร \n ระบุตัวเลข:"))
# ระบุจำนวน เงิน / ลิตร
c = float(input("ระบุจำนวน:"))
# เงื่อนไขการทำงานของโปรแกรม
if '1' in A:
if '1' in B:
print("น้ำมัน Gasoline 95:", c * 29.16, "บาท")
elif '2' in B:
print("น้ำมัน Gasoline 95:", c / 29.16, "ลิตร")
elif '2' in A:
if '1' in B:
print("น้ำมัน Gasoline 91:", c * 25.30, "บาท")
elif '2' in B:
print("น้ำมัน Gasoline 91:", c / 25.30, "ลิตร")
elif '3' in A:
if '1' in B:
print("น้ำมัน Gasohol 91:", c * 21.68, "บาท")
elif '2' in B:
print("น้ำมัน Gasohol 91:", c / 21.68, "ลิตร")
elif '4' in A:
if '1' in B:
print("น้ำมัน Gasohol E20:", c * 20.2, "บาท")
elif '2' in B:
print("น้ำมัน Gasohol E20:", c / 20.2, "ลิตร")
elif '5' in A:
if '1' in B:
print("น้ำมัน Gasohol 95:", c * 21.2, "บาท")
elif '2' in B:
print("น้ำมัน Gasohol 95:", c / 21.2, "ลิตร")
elif '6' in A:
if '1' in B:
print("น้ำมัน Diesel:", c * 21.1, "บาท")
elif '2' in B:
print("น้ำมัน Diesel:", c / 21.1, "ลิตร")
else:
print("***ข้อมูลไม่ถูกต้องกรุณาตรวจสอบข้อมูลที่กรอกใหม่อีกครั้ง")
x = input(
"กรอก Restart เพื่อเริ่มต้นใหม่ \n กรอก Exit เพื่อหยุดทำงาน \n ระบุคำสั่ง:")
if 'Restart' in x:
y = 1
elif 'Exit' in x:
y = 0
elif y == 0:
break
|
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>")
if "buy" in p or "Buy" in p or "BUY" in p:
c = str(input("choose kind of coffee - (1)espresso / (2)latte / (3)cappuccino\n>"))
if 'espresso' in c or '1' in c:
print("you must pay 4 $")
print("")
print("The Coffee machine has:")
print(int(W)-250,"ml of water")
print((M),"ml of milk ")
print(int(B)-16,"g of coffee beans")
print(int(C)-1,"of disposable cups ")
print(int(m)-4,"$ of money")
elif 'latte' in c or '2' in c:
print("you must pay 7 $")
print("")
print("The Coffee machine has:")
print(int(W)-350,"ml of water")
print(int(M)-75,"ml of milk ")
print(int(B)-20,"g of coffee beans")
print(int(C)-1,"of disposable cups ")
print(int(m)-7,"$ of money")
elif 'cappuccino' in c or '3' in c:
print("you must pay 6 $")
print("")
print("The Coffee machine has:")
print(int(W)-200,"ml of water")
print(int(M)-100,"ml of milk ")
print(int(B)-12,"g of coffee beans")
print(int(C)-1,"of disposable cups ")
print(int(m)+6,"$ of money")
else:
print("Error")
elif "fill" in p or "Fill" in p or "FILL" in p:
wf = int(input("write how many ml of water do you want to add:\n>"))
Mf = int(input("write how many ml of milk do you want to add:\n>"))
Bf = int(input("write how many grams of coffee beans do you want to add:\n>"))
mf = int(input("write how many disposable cups do you want to add:\n>"))
print("")
print("The Coffee machine has:")
print(int(W)+(wf),"ml of water")
print(int(M)+(Mf),"ml of milk ")
print(int(B)+(Bf),"g of coffee beans")
print(int(C)+(mf),"of disposable cups ")
print(int(m),"$ of money")
elif "take" in p or "Take" in p or "TAKE" in p:
print("I gave you $",(m))
print("")
print("The Coffee machine has:")
print(int(W)+(wf),"ml of water")
print(int(M)+(Mf),"ml of milk ")
print(int(B)+(Bf),"g of coffee beans")
print(int(C)+(mf),"of disposable cups ")
print(int(m),"$ of money")
else:
print("Error")
x = input("Exit/Restart\n>")
if "Exit" in x:
y = 0
elif "Restart" in x:
y = 1
else:
print("Error")
elif y == 0:
break
|
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_filename'])
#print(diabetes.DESCR)
#diabetes_X=diabetes.data[:,np.newaxis,2]
diabetes_X = diabetes.data
# print(diabetes_X)
diabetes_X_train = diabetes_X[:-30] # last 30 features
diabetes_X_test = diabetes_X[-30:] # first 20
diabetes_Y_train = diabetes.target[:-30] # labels
diabetes_Y_test = diabetes.target[-30:]
model = linear_model.LinearRegression()
model.fit(diabetes_X_train, diabetes_Y_train)
diabetes_Y_predicted = model.predict(diabetes_X_test)
print("mean", mean_squared_error(diabetes_Y_test, diabetes_Y_predicted))
print("weights", model.coef_)
print("intercept", model.intercept_)
plt.scatter(diabetes_X_test,diabetes_Y_test)
plt.plot(diabetes_X_test,diabetes_Y_predicted)
plt.show()
|
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, compare_columns)
print out
|
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
def slightly_holey(cls):
return cls(random.randint(0, 33))
@classmethod
def very_holey(cls):
return cls(random.randint(66, 100))
@classmethod
def cheese10(cls):
return cls(10)
if __name__ == "__main__":
gouda = Cheese()
emmentaler = Cheese.random()
leerdammer = Cheese.slightly_holey()
custom1 = Cheese(10)
print custom1.number_of_holes
custom2 = Cheese.cheese10()
print custom2.number_of_holes
print gouda, emmentaler, leerdammer, custom1, custom2
|
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,88,85],
'Rate':[2,3,2,2],
'GDP':[50,52,50,53]},
index=[2001,2002,2003,2004])
#concat=pd.concat([df1,df2,df3])
#print(concat)
df4=df1.append(df3)
print(df4)
|
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):
raise ValueError('N debe ser multiplo de 3.')
#calculamos h
h = (b - a) / n
#Inicializamos nuestra varible donde se almacenara las sumas
suma = 0.0
#hacemos un ciclo para ir sumando las areas
for i in range(1, n):
#calculamos la x
#x = a - h + (2 * h * i)
x = a + i * h
# si es par se multiplica por 4
if(i % 3 == 0):
suma = suma + 2 * fx(x, f)
#en caso contrario se multiplica por 2
else:
suma = suma + 3 * fx(x, f)
#sumamos los el primer elemento y el ultimo
suma = suma + fx(a, f) + fx(b, f)
#Multiplicamos por h/3
rest = suma * (3*h / 8)
#Retornamos el resultado
return (rest)
#Funcion que nos ayuda a evaluar las funciones
def fx(x, f):
return eval(f)
#valores de ejemplo para la funcion sin(x) con intervalos de
n = 6
a = 0.0
b = 1.0
#f = '(x+1)**-1'
#f = 'x*(e**(3*x))'
n = 9
a = 0
b = 0.8
f = '0.2+25*x-200*(x**2)+675*(x**3)-900*(x**4)+400*(x**5)'
print(simpson38(n, a, b, f)) |
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","05","04","03","02","01","00"]
id_middle = random.choice(id_middle_limit)
Number = "0123456789"
randomNumber = "".join(random.choice(Number) for i in range(2))
student_id = (id_head + id_middle + randomNumber)
return student_id
path = "test.csv"
writefile = open(path,'w',newline = '')
csv_head = ["Teacher_id","Name"]
writer = csv.writer(writefile).writerow(csv_head)
for i in teacher_name:
if i == '授課教師':
continue
writefile = open(path,'a',newline = '')
date = [create_teacher_id(),i]
writer = csv.writer(writefile).writerow(date) |
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, channel=7, power=6, address=0x75626974, group=0, data_rate=radio.RATE_M1MBIT)
# The one you will be using the most is setting the channel, this can be any
# number between 0 and 83.
radio.config(channel=68)
# For more information about what each of these settings mean, visit
# https://microbit-micropython.readthedocs.io/en/latest/radio.html
# If you somehow mess up the settings, you can always reseet it:
radio.reset()
# Radios are actually very easy to use. But remember, each message is broadcasted
# to every other microbit out there using the same channel. It's a good idea to use a unique
# channel for you microbits.
# To send messages, simply use radio.send().
# To receive messages, simply use radio.receive().
# Test this program out with a parner, changing the channel your radio is using.
# Can you figure out what this program does?
radio.config(channel=7)
while True:
sleep(50)
if button_a.was_pressed():
display.show(Image.HAPPY)
radio.send('A')
elif button_b.was_pressed():
display.show(Image.SAD)
radio.send('B')
message = radio.receive()
if message == 'A':
display.show(Image.HAPPY)
if message == 'B':
display.show(Image.SAD)
|
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(error)
except ValueError:
print(error)
def yes_no(question):
valid = False
while not valid:
response = input(question).lower()
if response == "yes" or response == "y":
response = "yes"
return response
elif response == "no" or response == "n":
response = "no"
return response
else:
print("Please enter yes or no")
def instructions():
print(" *** How to Play the Lucky Unicorn game *** ")
print(" *** The rules of the game are *** ")
print("*** To play you must enter the amount of money you wish to play with ***")
print(" *** This amount must be between 1 and 10 dollars *** ")
print(" *** Each game costs $1 *** ")
print(" *** Every game you are given 1 of 4 random tokens *** ")
print(" *** And each will give you a certain amount of money *** ")
print(" *** Unicorn gives $4, Horse and Zebra give $0.50 and Donkey give $0 ***")
print(" *** You can quit at anytime but if you run out of money you lose *** ")
# Main routine
balance = 0
rounds_played = 0
print("Welcome to the Lucky Unicorn Game")
# Ask user if played_before
played_before = yes_no("Have you played the game before? ")
if played_before == "no":
instructions()
# Ask user how much
how_much = number_check("How much would you like to play with?")
balance = how_much
print("You have asked to play with ${}".format(how_much))
# Generate a Token
tokens = ["Unicorn", "Horse", "Zebra", "Donkey"]
selected_token = random.choice(tokens)
print(selected_token)
balance -= 1
# Ask user if they wish to play again
if selected_token == "Unicorn":
balance += 4
print("You got a Unicorn! You now have ${}".format(balance))
elif selected_token == "Horse":
balance += 0.50
print("You got a Horse! you now have ${}".format(balance))
elif selected_token == "Zebra":
balance += 0.50
print("You got a Zebra! You now have ${}".format(balance))
else:
balance += 0
print("Oh no, You got a Donkey! You now have ${}".format(balance))
|
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(year1,month1,day1)
date2 = date(year2,month2,day2)
Day = date2 - date1
print(Day.days, "Days have been passed!") |
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()
self.frames = [[plt.imshow(data[:, :, frame], animated=True)] for frame in range(data.shape[2])]
# Set up formatting for saving an animation
# self.save_animation = True
# Writer = animation.writers['ffmpeg']
# self.writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)
def animate(self):
ani = animation.ArtistAnimation(self.fig, self.frames, interval=50, blit=True, repeat_delay=1000)
plt.axis('off')
plt.show()
# if self.save_animation:
# ani.save('im.mp4', writer=self.writer)
##### EXAMPLE #####
# sample = np.random.randn(100, 100, 60)
# anim = Animation(sample)
# anim.animate() |
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 = best_action_value(table, obs)
if random.random() < epsilon:
return random.randint(0, n_actions - 1)
else:
return action
def select_greedy_action(table, obs, n_actions):
'''
Select the action using a greedy policy (take the best action according to the policy)
'''
value, action = best_action_value(table, obs)
return action
def best_action_value(table, state):
'''
Exploring the table, take the best action that maximize Q(s,a)
'''
best_action = 0
max_value = 0
for action in range(n_actions):
if table[(state, action)] > max_value:
best_action = action
max_value = table[(state, action)]
return max_value, best_action
def Q_learning(table, obs0, obs1, reward, action):
'''
Q-learning. Update Q(obs0,action) according to Q(obs1,*) and the reward just obtained
'''
# Take the best value reachable from the state obs1
best_value, _ = best_action_value(table, obs1)
# Calculate Q-target value
Q_target = reward + GAMMA * best_value
# Calculate the Q-error between the target and the previous value
Q_error = Q_target - table[(obs0, action)]
# Update Q(obs0,action)
table[(obs0, action)] += LEARNING_RATE * Q_error
def test_game(env, table, n_actions):
'''
Test the new table playing TEST_EPISODES games
'''
reward_games = []
for _ in range(TEST_EPISODES):
obs = env.reset()
rewards = 0
while True:
# Act greedly
next_obs, reward, done, _ = env.step(select_greedy_action(table, obs, n_actions))
obs = next_obs
rewards += reward
if done:
reward_games.append(rewards)
break
return np.mean(reward_games)
# Some hyperparameters..
GAMMA = 0.95
# NB: the decay rate allow to regulate the Exploration - Exploitation trade-off
# start with a EPSILON of 1 and decay until reach 0
epsilon = 1.0
EPS_DECAY_RATE = 0.9993
LEARNING_RATE = 0.8
# .. and constants
TEST_EPISODES = 100
MAX_GAMES = 15001
# Create the environment
# env = gym.make('Taxi-v2')
env = gym.make("FrozenLake-v0")
obs = env.reset()
obs_length = env.observation_space.n
n_actions = env.action_space.n
reward_count = 0
games_count = 0
# Create and initialize the table with 0.0
table = collections.defaultdict(float)
test_rewards_list = []
while games_count < MAX_GAMES:
# Select the action following an ε-greedy policy
action = select_eps_greedy_action(table, obs, n_actions)
next_obs, reward, done, _ = env.step(action)
# Update the Q-table
Q_learning(table, obs, next_obs, reward, action)
reward_count += reward
obs = next_obs
if done:
epsilon *= EPS_DECAY_RATE
# Test the new table every 1k games
if games_count % 1000 == 0:
test_reward = test_game(env, table, n_actions)
print('\tEp:', games_count, 'Test reward:', test_reward, np.round(epsilon, 2))
test_rewards_list.append(test_reward)
obs = env.reset()
reward_count = 0
games_count += 1
# Plot the accuracy over the number of steps
plt.figure(figsize=(20, 10))
plt.xlabel('Steps')
plt.ylabel('Accurracy')
plt.plot(test_rewards_list)
plt.show()
|
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):
self.rightNode = Node(data)
class Tree:
def __init__(self):
self.root = None
def makeRoot(self, data):
self.root = Node(data)
self.root.setPrev('Root')
## Make BST
def makeBST(self, arr):
self.makeRoot(arr[0])
for item in arr[1:]:
self.makeBSTNode(item)
def makeBSTNode(self, data):
self.makeBSTNodeRec(self.root, data)
def makeBSTNodeRec(self, curNode, data):
if data < curNode.data:
if curNode.leftNode == None:
curNode.setLeftNode(data)
curNode.leftNode.setPrev(curNode)
else:
self.makeBSTNodeRec(curNode.leftNode, data)
else:
if curNode.rightNode == None:
curNode.setRightNode(data)
curNode.rightNode.setPrev(curNode)
else:
self.makeBSTNodeRec(curNode.rightNode, data)
## Make balanced BST
def makeBBST(self, arr):
sortedArr = list(sorted(arr))
midInd = math.floor(len(arr)/2)
mid = sortedArr[midInd]
left = arr[:mid]
right = arr[mid+1:]
self.makeRoot(mid)
self.makeBBSTNode(self.root, left, right)
def makeBBSTNode(self, curNode, left, right):
if left:
## In case left is not empty
midLeftInd = math.floor(len(left)/2)
midLeft = left[midLeftInd]
curNode.leftNode = Node(midLeft)
self.makeBBSTNode(curNode.leftNode, left[:midLeftInd], left[midLeftInd+1:])
if right:
midRightInd = math.floor(len(right)/2)
midRight = right[midRightInd]
curNode.rightNode = Node(midRight)
self.makeBBSTNode(curNode.rightNode, right[:midRightInd], right[midRightInd+1:])
## Print tree
def printTree(self):
print(f"tree = {self.printNode(self.root)}")
def printNode(self, curNode):
s = f'{curNode.data} '
if curNode.leftNode != None and curNode.rightNode == None:
lS = self.printNode(curNode.leftNode)
rS = 'xR'
s += f'({lS} {rS})'
elif curNode.leftNode == None and curNode.rightNode != None:
lS = 'xL'
rS = self.printNode(curNode.rightNode)
s += f'({lS} {rS})'
elif curNode.leftNode != None and curNode.rightNode != None:
lS = self.printNode(curNode.leftNode)
rS = self.printNode(curNode.rightNode)
s += f'({lS} {rS})'
return s
## Return list of all nodes in tree
def treeToArr(self):
return self.treeToArrRec(self.root)
def treeToArrRec(self, cur):
arr = [cur]
if cur.leftNode != None:
leftSet = self.treeToArrRec(cur.leftNode)
arr.extend(leftSet)
if cur.rightNode != None:
rightSet = self.treeToArrRec(cur.rightNode)
arr.extend(rightSet)
return arr
## Q1
def diffRandNode(tree):
print('-'*10 + 'Q1: maxDifference of rand node' + '-'*10)
import random as rd
if tree.root == None:
print('The tree is empty, please populate the tree first')
return
arr = tree.treeToArr()
randNode = arr[rd.randrange(0, len(arr))]
if randNode == tree.root:
return 0
print(f"inputNodeVal: {randNode.data}, maxDiff: {maxDifference(randNode, tree)}")
def maxDifference(node, tree):
allNodes = tree.treeToArr()
maxDiff = float('-inf')
for curNode in allNodes:
if curNode != node and curNode.data-node.data > maxDiff:
maxDiff = curNode.data-node.data
return maxDiff
## Q2
def printLeafNodes(tree):
print('-'*10 + 'Q2: print leaf nodes' + '-'*10)
if tree.root == None:
print('The tree is empty, please populate the tree first')
return
leafNodes = getLeaves(tree)
for leafNode in leafNodes:
print(nodePath(leafNode))
def getLeaves(tree):
return getNodeLeaves(tree.root)
def getNodeLeaves(node):
leaves = []
if node.leftNode == None and node.rightNode == None:
leaves.append(node)
if node.leftNode != None:
leaves.extend(getNodeLeaves(node.leftNode))
if node.rightNode != None:
leaves.extend(getNodeLeaves(node.rightNode))
return leaves
def nodePath(node):
path = []
cur = node
while(cur.prev != 'Root'):
path.append(cur.data)
cur = cur.prev
return path
## Q3
def revTree(tree):
print('-'*10 + 'Q3: reverse tree' + '-'*10)
if tree.root == None:
print('The tree is empty, please populate the tree first')
return
revTree = Tree()
revTree.makeRoot(tree.root.data)
revNodeRec(tree.root, revTree.root)
return revTree
def revNodeRec(node, revNode):
if node.leftNode != None:
revNode.rightNode = Node(node.leftNode.data)
revNodeRec(node.leftNode, revNode.rightNode)
if node.rightNode != None:
revNode.leftNode = Node(node.rightNode.data)
revNodeRec(node.rightNode, revNode.leftNode)
return revNode
def hw6(arr):
print('-'*75)
print(f'inputArr = {arr}\n')
if not arr:
print('the given array is empty, please re-try with another array')
return
myTree = Tree()
myTree.makeBST(arr)
myTree.printTree()
##Q1
diffRandNode(myTree)
##Q2
printLeafNodes(myTree)
##Q3
revT = revTree(myTree)
revT.printTree()
print('-'*75 + '\n'*2)
arr0 = []
hw6(arr0)
arr = [0, 1, 2, 3 ,4, 5, 6, 7, 8]
hw6(arr)
arr2 = [4, 0, 1, 2, 3, 5, 6, 7, 8]
hw6(arr2)
myTree = Tree()
myTree.makeBBST(range(10))
myTree.printTree()
|
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) for i in range(1, 7)]
# Figure 1: Elbow plot
figure1 = plt.scatter(x=list(range(1, 7)),
y=[var for (cent, var) in df])
plt.xlabel('Number of clusters')
plt.ylabel('Average Euclidean distance between \n observations and centroids')
plt.show()
# Figure 2: Visualize clusters with PC1 and PC2
cent, var = df[clusters - 1] # choose number of clusters
# use vq() to get as assignment for each obs.
assignment, cdist = cluster.vq.vq(PCs[:, 0:2], cent)
plt.style.use('classic')
figure2 = plt.scatter(PCs[:, 0], PCs[:, 1], c=assignment) # Plot PC1 and PC2
plt.xlabel('PC1', fontsize=18)
plt.ylabel('PC2', fontsize=18)
plt.title('Clustering for {}'.format(title), fontsize=18)
return assignment |
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))
print(sorted(pointsInAGame, reverse=True))
leaderBoard = {231:'ckl', 123:'abc', 432:'jkc'}
print(sorted(leaderBoard, reverse=True))
print(leaderBoard.get(432))
students = [('alice', 'b',12), ('eliza', 'a', 16, ('tae', 'c', 15))]
print(sorted(students, key=lambda student: student[0]))
print(sorted(students, key=lambda student: student[1]))
print(sorted(students, key=lambda student: student[2])) |
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 Dummy Data
import numpy as np
# train Data
train_x = np.random.random((1000,20)) #Return random floats in the half-open interval [0.0, 1.0).
train_y = np.random.randint(10,size=(1000,1))
# test Data
test_x = np.random.random((100,20))
test_y = np.random.randint(10,size=(100,1))
#one hot encoding
train_y = keras.utils.to_categorical(train_y)
test_y = keras.utils.to_categorical(test_y)
model = Sequential()
# Dense(64) is a fully-connected layer with 64 hidden units.
# in the first laye, you must specify the excepted input data type
model.add(Dense(64,activation='relu',input_dim=20))
model.add(Dropout(0.2))
model.add(Dense(64,activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(10,activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='sgd',
metrics=['accuracy'])
model.fit(train_x,train_y,epochs=20,batch_size=128)
score = model.evaluate(test_x,test_y,batch_size=128)
|
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 number:"))
break
except ValueError:
print("You didn't enter a number")
except:
print("An unknown error occurred")
print("Thank you for entering the number {}".format(number))
# -----------------------------------------------------------------------------------------
# DO/WHILE LOOPS - always execute code at least once, will run again if conditions met
# -----------------------------------------------------------------------------------------
secret_number = 7
while True:
guess = int(input("Guess a number between 1 and 10 : "))
if guess == secret_number:
print("You guessed it")
break
# ----------------------------------------------------------------------------------------
# A more complex version
# ----------------------------------------------------------------------------------------
secret_number = 7
while True:
try:
guess = int(input("Guess a number between 1 and 10:"))
if guess == secret_number:
print("You guessed it!")
break
elif guess != secret_number:
print("Guess again!")
except ValueError:
print("You didn't guess a number!")
except:
print("An unknown error occurred")
# -----------------------------------------------------------------------------------------
# Using the MATH Module
# -----------------------------------------------------------------------------------------
import math
ceil = math.ceil(4.7) # rounds up 5
floor = math.floor(4.7) # rounds down 4
fabs = math.fabs(-4.7) # absolute value 4.7
factorial = math.factorial(4) # factorial 1*2*3*4 = 24
fmod = math.fmod(5,4) # remainder of division 5/4 = ...remainder = 1
trunc = math.trunc(4.7) # returns an integer 4
pow = math.pow(2,2) # to the power of x^y
sqrt = math.sqrt(4) # square root 2
e = math.e # e 2.71...
pi = math.pi # pi 3.14...
exp = math.exp(4) # exponent e^x 54.59...
log = math.log(20) # natural log e^? = 20
log10 = math.log(1000,10) # defining base as 10 log10(1000) = 3
sin = math.sin(90) # trig functions 1
deg = math.degrees(1.56) # converts rad to deg 90
rad = math.radians(90) # converts deg to rad 1.57...
# -----------------------------------------------------------------------------------------
# Importing individual methods (Decimal) from modules (decimal), and reassigning name (D)
# -----------------------------------------------------------------------------------------
from decimal import Decimal as D
# Decimal avoids the inaccuracy of math operations on floats
sum = D(0)
sum = D(0)
sum += D("0.1")
sum += D("0.1")
sum += D("0.1")
sum -= D("0.3")
print("Sum =", sum)
# -----------------------------------------------------------------------------------------
# Type
# -----------------------------------------------------------------------------------------
# Output:
print(type(3)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type('words')) # <class 'str'>
# -----------------------------------------------------------------------------------------
# Referencing index of a string
# -----------------------------------------------------------------------------------------
mystring = "Words go here"
print(mystring[0]) # W
print(mystring[-1]) # e
print(mystring[3+5]) # h
print(mystring[2:7]) #rds g
# Cycle through characters in pairs
# Subtract 1 from the length because length is 1 more then the highest index
# because strings are 0 indexed
# Use range starting at index 0 through string length and increment by
# 2 each time through
for i in range(0, len(samp_string)-1, 2):
print(samp_string[i] + samp_string[i+1])
# ---------- PROBLEM : SECRET STRING ----------
# Receive a uppercase string and then hide its meaning by turning
# it into a string of unicode
# Then translate it from unicode back into its original meaning
# ---------------------------------------------
# input_string = input("What is your string?")
# unicode_string = ''
#
# for i in range(0, len(input_string)-1, 1)
# unicode_string = unicode_string + str(ord(input_string[i]))
# print(unicode_string)
|
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():
print(k.ljust(leftWidth, '.') + str(v).rjust(rightWidth))
picnicItems = {
'sandwiches': 4,
'apples': 12,
'cups': 4,
'cookies': 8000
}
printPicnic(picnicItems, 12, 5)
printPicnic(picnicItems, 20, 6)
#demo of strip(), rstrip(), lstrip()
spam = ' Hello World '
print(spam)
print(spam.strip())
print(spam.lstrip())
print(spam.rstrip())
|
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 methods for
manipulating it in a game
"""
def __init__(self):
self.suit = None # Card suit, e.g. Spades
self.name = None # Name string, e.g. King
self.id = None # Number identifier, [1-13]
self.faceup = False # Face up or down, boolean value
self.value = None # Point value within a game
def __add__(self, other):
return self.value + other
def __radd__(self, other):
return other + self.value
def __sub__(self, other):
return self.value - other
def __rsub__(self, other):
return other - self.value
def __lt__(self, other):
return self.value < other
def __le__(self, other):
return self.value <= other
def __gt__(self, other):
return self.value > other
def __ge__(self, other):
return self.value >= other
def __eq__(self, other):
return self.value == other
def __ne__(self, other):
return self.value != other
def __int__(self):
return int(self.value)
def __str__(self):
return '{0} of {1}'.format(self.name, self.suit)
def flip(self):
"""Set faceup value to False if True and vice versa."""
if self.faceup:
self.faceup = False
else:
self.faceup = True
def face(self):
"""Return True or False whether or not the card is face up."""
return self.faceup
def set_attributes(self, name, suit, id_no=0):
"""Set the card's name, suit, and identification number."""
self.name = str(name)
self.suit = str(suit)
self.id = int(id_no)
def assign_value(self, points):
"""Set the card's point value."""
self.value = int(points)
class CardDeck(object):
"""Contains 52 or more playing cards and the methods for using them."""
def __init__(self, decks=1):
self.deck = deque()
self.deck_count = int(decks)
self.shuffle_count = self.deck_count * 7
self.suits = (
'Clubs',
'Diamonds',
'Hearts',
'Spades',
)
self.names = (
'Ace',
'Two',
'Three',
'Four',
'Five',
'Six',
'Seven',
'Eight',
'Nine',
'Ten',
'Jack',
'Queen',
'King',
)
self.shuffle()
def __len__(self):
return len(self.deck)
def __iter__(self):
return iter(self.deck)
def __getitem__(self, index):
return self.deck[index]
def shuffle(self):
"""Initialize the deck with 52 or more cards."""
if self.deck:
self.deck = deque()
max_decks = self.deck_count + 1 # +1 for range function
for deck in range(1, max_decks):
for suit in self.suits:
for num, name in enumerate(self.names, start=1):
card = PlayingCard()
card.set_attributes(name, suit, num)
self.deck.append(card)
for deck_shuffle in range(self.shuffle_count):
random.shuffle(self.deck)
def draw(self):
"""Remove the first card from the deck and return it."""
return self.deck.popleft()
class Blackjack:
"""Game logic for the card game Blackjack"""
def __init__(self, bet, decks=2, shuffle=25, debug=False):
self.deck_count = decks # Number of card decks in the game deck
self.shuffle = shuffle # Percent of deck left for shuffle threshold
self.player_bet = bet
self.verbose = debug
self.deck = CardDeck(decks=self.deck_count)
self._assign_values()
self.card_total = len(self.deck)
self.player = BlackjackPlayer()
self.dealer = BlackjackDealer()
def _assign_values(self):
for card in self.deck:
if card.id > 9:
card.assign_value(10)
else:
card.assign_value(card.id)
def _shuffle_time(self):
"""Check if it is time to shuffle the deck by calculating the
percentage of the cards remaining in the deck
"""
remaining = len(self.deck) # Current count of cards in the deck
percentage_left = int((remaining / self.card_total) * 100)
if ( percentage_left > 25 ):
return False # It isn't time to shuffle
else:
return True # Or maybe it is
def deal(self):
"""Deal out a new hand of cards to the dealer and player."""
if self.dealer: # Has cards in hand
self.dealer.reset()
if self.player: # Has cards in hand
self.player.reset()
dealer_first = self.deck.draw()
dealer_second = self.deck.draw()
dealer_second.flip()
self.dealer.take_card(dealer_first)
self.dealer.take_card(dealer_second)
player_first = self.deck.draw()
player_second = self.deck.draw()
player_first.flip()
player_second.flip()
self.player.take_card(player_first)
self.player.take_card(player_second)
if self.verbose:
print('Player bets:', self.player_bet)
for player in (self.player, self.dealer):
print(player, 'dealt:')
for card in player:
if card.face():
print(' '*3, str(card)+':', 'face up')
else:
print(' '*3, str(card)+':', 'face down')
def check_hand(self, player):
"""Check point value of the hand of cards and act appropriately."""
total = player.score()
if total > 21:
status = 'bust'
elif total == 21:
status = 'win'
else:
status = 'okay'
if self.verbose:
print(total, 'points')
return status
def hit(self, player):
"""Retrieve a face up card from the deck, and add it to a hand."""
hit_card = self.deck.draw()
hit_card.flip()
player.take_card(hit_card)
if self.verbose:
print(player, 'receives', hit_card)
def stay(self):
"""End the player's turn and pass control to the dealer."""
pass
|
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 = file.read()
split_data = read.split("\n")
no_header = split_data[1:len(split_data)]
final_list = list()
for i in no_header:
string_fields = i.split(",")
int_fields = []
for i in string_fields:
int_fields.append(int(i))
final_list.append(int_fields)
return final_list
cdc_list = read_csv("US_births_1994-2003_CDC_NCHS.csv")
# Create a function that takes a list of lists argument
def month_births(input_lst):
# Store monthly totals in a dictionary
births_per_month = {}
for i in input_lst:
# Label the columns
month = i[1]
births = i[4]
# Check if item already exists in dictonary list
if month in births_per_month:
# Add the current number of births to the new integer
births_per_month[month] = births_per_month[month] + births
# If the item does not exist, create it with integer of births
else:
births_per_month[month] = births
return births_per_month
cdc_month_births = month_births(cdc_list)
# This function uses day of the week instead of month
def dow_births(input_lst):
births_per_day = {}
for i in input_lst:
dow = i[3]
births = i[4]
if dow in births_per_day:
births_per_day[dow] = births_per_day[dow] + births
else:
births_per_day[dow] = births
return births_per_day
cdc_day_births = dow_births(cdc_list)
# This function is more superior because it is a generalized form
def calc_counts(data, column):
sums_dict = {}
for row in data:
col_value = row[column]
births = row[4]
if col_value in sums_dict:
sums_dict[col_value] = sums_dict[col_value] + births
else:
sums_dict[col_value] = births
return sums_dict
|
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)
elif operacion == "resta":
print ("La operacion es una resta")
resultado = int(operando1) - int(operando2)
elif operacion == "div":
print ("La operacion es una division")
try:
resultado = int(operando1) / int(operando2)
except ZeroDivisionError:
print("No intentes dividir entre cero")
sys.exit()
elif operacion == "mult":
print ("La operacion es una multiplicacion")
resultado = int(operando1) * int(operando2)
else:
print ("La operacion introducida no es correcta")
sys.exit()
print(resultado)
sys.exit()
|
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(priorities)
else: # ?꾨┛??遺덇???
priorities.append(top)
if location == 0:
location = len(priorities) - 1
else:
location -= 1
return answer |
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.